/** * The durable subagent-conversation presenter. * * This is the adapter layer between Harness authority and the terminal: it * reads durable direct children from `ctx.subagents.listDescendants`, reads * one child's bounded session window from `ctx.sessionQuery`, and routes human * follow-up/steer through the one human prompt operation Harness publishes. * It owns no lifecycle, no scheduling, and no child conversation state — every * paint re-reads the current reading, and neither a refresh nor a keystroke * invents a row the authority did not publish. * * It is deliberately separate from `HarnessWork`. Work owns active lifecycle * epochs keyed by `runId`, and a settled continuable child has no epoch while * still being a durable conversation. Folding this into Work would also make * `activeWorkCount` see a settled child, which gates retiring the session. * * Interruption is deliberately NOT part of this presenter. `/work` owns the * active lifecycle epoch and its existing human interrupt; a durable child's * catalog `activity` is session-store residency, not proof that a turn is * executing, so offering interrupt here could claim a cancellation Harness * only accepted as a no-op. The durable view inspects and continues instead. * @module dshline/subagents/presenter */ import type { SessionId } from '@deepseek-ai/dsh-session' import type { SubagentRuntime } from '@deepseek-ai/dsh-subagent' import type { LocalCommand } from '../local-commands.ts' import type { TuiSlots } from '../slots.ts' import { openSurface, SurfaceNotice } from '../surface.ts' import { deliverHumanPrompt, type HumanPromptDelivery } from './control.ts' import { catalogReading, subagentRowFollowUp, subagentRowLabel, type SubagentCatalogReading, type SubagentChildRow, } from './model.ts' import { CONVERSATION_NOTICE_MS, createSubagentCatalogOverlay, createSubagentConversationOverlay, createSubagentMessageOverlay, } from './overlay.ts' import type { ChildSessionReads, HumanSubagentSeam } from './seam.ts' import { initialTranscript, readTranscriptNewer, readTranscriptOlder, readTranscriptTail, transcriptReading, type TranscriptState, } from './transcript.ts' /** * The edge distance `listDescendants` reports for a child of the requested * parent; every deeper row belongs to some other parent's branch. */ const DIRECT_CHILD_DEPTH = 1 /** * The subagent operations this presenter calls. * * {@link HumanSubagentSeam} plus descendant discovery, and the addition is the * adopted generation forcing it rather than a preference. `listChildren` now * answers with the parent-owned `subagentCatalog` projection alone — id, * creation time, mode, label — while residency, child presence, and the * `corrupt`/`unsupported`/`unavailable` branch diagnostics are produced only by * the recursive walk. A catalog built from the flat read would have to invent * all three, and a branch Harness says it cannot read is exactly the row a * person most needs to see. * * This widens OBSERVATION only. `interrupt` is still absent for the reason * {@link HumanSubagentSeam} gives: residency is not proof that a turn is * executing, and an open lifecycle epoch is `/work`'s premise, not this * presenter's. */ export type SubagentCatalogSeam = HumanSubagentSeam & Pick /** Narrow dependencies the subagent-conversation presenter needs. */ export interface SubagentsPresenterDeps { /** Live-region registry that owns the overlay stack. */ readonly slots: Pick /** The attached session, which is the durable direct parent Harness authorizes. */ readonly parentSessionId: SessionId /** Redraw after a read or action changes presentation state. */ readonly invalidate: () => void /** Human-authoritative subagent operations, or undefined without `ctx.subagents`. */ readonly subagents?: SubagentCatalogSeam /** Bounded child-session reads, or undefined without `ctx.sessionQuery`. */ readonly query?: ChildSessionReads /** Subscribe to parent-scoped subagent lifecycle edges. */ readonly onLifecycle?: (listener: () => void) => () => void /** * Subscribe to Harness session events, for a selected child's staleness hint. * @param listener - receives the event's durable session id. */ readonly onSessionEvent?: (listener: (sessionId: string) => void) => () => void } /** The subagent-conversation capability as one local command and entry point. */ export interface SubagentsPresenter { /** `/subagents` — browse durable direct children and inspect one. */ readonly command: LocalCommand /** Open the catalog as the root `/subagents` surface, where Escape closes it. */ open(): void /** Open the catalog nested over Work, where Escape returns to Work. */ openFromWork(): void /** * Open one known durable child's conversation directly, with NO catalog * surface underneath. `child` is keyed by the durable child session id. */ openChild(child: SubagentChildRow): void /** Abort in-flight reads and release lifecycle subscriptions. */ dispose(): void } /** One open conversation inspector's presenter-owned state. */ interface OpenConversation { /** The durable child being inspected; refreshed when discovery re-lists it. */ child: SubagentChildRow /** The currently loaded bounded transcript state. */ transcript: TranscriptState /** Cancels this inspector's in-flight reads when it closes or navigates. */ readonly abort: AbortController /** * Identity of the newest read started for this inspector. A read that settles * after a newer one started is discarded, so two quick refreshes (or a refresh * racing a paging read) cannot publish an older window over a newer one. */ readGeneration: number /** * Count of selected-child session events seen. A read captures this before it * starts and publishes `stale` from whether it still matches when the read * settles, which is what keeps an event arriving MID-read from being lost when * the read overwrites the flag with its own `stale:false`. */ eventGeneration: number /** The inspector's own outcome notice. */ readonly notice: SurfaceNotice } /** * Build the durable subagent-conversation presenter. * @param deps - narrow Harness seams, the parent address, and surface controls. * @returns the presenter's local command and Work entry point. */ export function createSubagentsPresenter(deps: SubagentsPresenterDeps): SubagentsPresenter { let catalog: SubagentCatalogReading = deps.subagents === undefined ? { kind: 'unavailable' } : { kind: 'loading' } let catalogGeneration = 0 let catalogAbort: AbortController | undefined let catalogOpen = false let closeCatalog: (() => void) | undefined let conversation: OpenConversation | undefined let conversationAbort: AbortController | undefined const disposers: (() => void)[] = [] /** * Re-run durable discovery under a generation guard. * * `listDescendants` walks the whole reachable tree and this catalog is the * parent's DIRECT children, so the rows are cut at depth one. The traversal * reads deeper only because the seam publishes no direct-children-only form * of a row carrying residency, child presence, and branch diagnostics. A * branch that stopped BELOW the cut is still reported honestly: the direct * child that owns it is listed, and its own `has children` fact is what says * there was something down there to lose. */ const refreshCatalog = (): void => { const seam = deps.subagents if (seam === undefined) { catalog = { kind: 'unavailable' } deps.invalidate() return } const generation = (catalogGeneration += 1) catalogAbort?.abort() const abort = new AbortController() catalogAbort = abort // The previous listing's rows are dropped rather than kept: an aging list // beside a "loading" label would present stale facts as current ones. catalog = { kind: 'loading' } deps.invalidate() void seam.listDescendants(deps.parentSessionId, abort.signal).then(rows => { if (generation !== catalogGeneration) return // Diagnostics are kept, not filtered: a row Harness could not interpret // is a listed record with no conversation behind it, and the catalog // already draws it as such rather than letting the branch vanish. catalog = catalogReading(rows.filter(row => row.depth === DIRECT_CHILD_DEPTH)) // An open inspector keeps showing the freshest residency Harness published // rather than the snapshot taken when it opened. Durable identity, mode, // and label do not change, but residency can. const open = conversation if (open !== undefined && catalog.kind === 'ready') { const fresh = catalog.rows.find( (row): row is SubagentChildRow => row.kind === 'child' && row.id === open.child.id, ) if (fresh !== undefined) open.child = fresh } deps.invalidate() }).catch((error: unknown) => { if (generation !== catalogGeneration) return // Discovery failing is not "no children": the reading says so, and it // never falls back to scanning or to another registry. catalog = { kind: 'failed', message: reason(error) } deps.invalidate() }) } /** Re-read the newest page of one open inspector. */ const reload = (state: OpenConversation): void => { const query = deps.query if (query === undefined) return const generation = (state.readGeneration += 1) const seen = state.eventGeneration void readTranscriptTail(query, state.child.id as SessionId, state.abort.signal).then(next => { if (conversation !== state || state.readGeneration !== generation) return state.transcript = { ...next, stale: state.eventGeneration !== seen } deps.invalidate() }) } /** Replace the loaded window with one older page, keeping it on a failed read. */ const loadOlder = (state: OpenConversation): void => { const query = deps.query if (query === undefined || state.transcript.kind !== 'ready' || !state.transcript.hasOlder) return const generation = (state.readGeneration += 1) const seen = state.eventGeneration void readTranscriptOlder(query, state.child.id as SessionId, state.transcript, state.abort.signal) .then(next => { if (conversation !== state || state.readGeneration !== generation) return state.transcript = { ...next, stale: next.stale || state.eventGeneration !== seen } deps.invalidate() }) .catch((error: unknown) => { if (conversation !== state || state.readGeneration !== generation) return state.notice.show(`Older events failed: ${reason(error)}`, true) deps.invalidate() }) } /** Replace the loaded window with one newer captured page, keeping it on failure. */ const loadNewer = (state: OpenConversation): void => { const query = deps.query if (query === undefined || state.transcript.kind !== 'ready' || !state.transcript.hasNewer) return const generation = (state.readGeneration += 1) const seen = state.eventGeneration void readTranscriptNewer(query, state.child.id as SessionId, state.transcript, state.abort.signal) .then(next => { if (conversation !== state || state.readGeneration !== generation) return state.transcript = { ...next, stale: next.stale || state.eventGeneration !== seen } deps.invalidate() }) .catch((error: unknown) => { if (conversation !== state || state.readGeneration !== generation) return state.notice.show(`Newer events failed: ${reason(error)}`, true) deps.invalidate() }) } /** Push the small message composer over one inspector. */ const openComposer = (state: OpenConversation, delivery: HumanPromptDelivery): void => { openSurface(deps.slots, close => createSubagentMessageOverlay({ childLabel: subagentRowLabel(state.child), delivery, submit: (text, signal) => deliverHumanPrompt(deps.subagents, { parentSessionId: deps.parentSessionId, childId: state.child.id as SessionId, text, delivery, }, signal), onAccepted: () => { // Harness accepted the message; the durable log is the only place the // message may appear, so the receipt is a notice and never a row. state.notice.show('Follow-up accepted') deps.invalidate() }, close, invalidate: deps.invalidate, })) } /** * Push the read-only conversation inspector for one fully-formed row. * * Both entry points converge here: the catalog resolves a durable id to a row * and Work supplies the row it already selected, so there is exactly one * inspector implementation and no second read or address to keep in step. */ const openConversationRow = (row: SubagentChildRow): void => { conversationAbort?.abort() const state: OpenConversation = { child: row, transcript: initialTranscript(deps.query !== undefined), abort: new AbortController(), readGeneration: 0, eventGeneration: 0, notice: new SurfaceNotice(CONVERSATION_NOTICE_MS, { invalidate: deps.invalidate }), } conversation = state conversationAbort = state.abort if (deps.query !== undefined) reload(state) openSurface(deps.slots, close => createSubagentConversationOverlay({ child: () => state.child, reading: () => transcriptReading(state.transcript), followUp: subagentRowFollowUp(row, deps.subagents !== undefined), steer: subagentRowFollowUp(row, deps.subagents !== undefined), loadOlder: () => { loadOlder(state) }, loadNewer: () => { loadNewer(state) }, refresh: () => { reload(state) }, message: delivery => { openComposer(state, delivery) }, notice: state.notice, close: () => { if (conversation === state) conversation = undefined // Cancel this inspector's in-flight reads now, rather than waiting for // the next open or teardown, so a late page never reaches a dead surface. state.abort.abort() state.notice.dispose() close() }, invalidate: deps.invalidate, })) } /** * Resolve one catalog row to its inspector, staying a silent no-op when the * id is not a currently-listed child (a diagnostic, or a row already gone). */ const openConversationFromCatalog = (childId: string): void => { const row = catalog.kind === 'ready' ? catalog.rows.find(candidate => candidate.kind === 'child' && candidate.id === childId) : undefined if (row === undefined || row.kind !== 'child') return openConversationRow(row) } /** * Open the durable-child catalog, replacing any catalog already open. * * `origin` is recorded explicitly rather than inferred from the overlay stack: * it decides only the truthful Escape wording, and a catalog opened over Work * must say `esc back` even if an unrelated surface sat beneath it. */ const openCatalog = (origin: 'root' | 'work'): void => { closeCatalog?.() catalogOpen = true refreshCatalog() closeCatalog = openSurface(deps.slots, close => createSubagentCatalogOverlay({ reading: () => catalog, origin, inspect: childId => { openConversationFromCatalog(childId) }, refresh: refreshCatalog, close: () => { catalogOpen = false closeCatalog = undefined close() }, invalidate: deps.invalidate, })) } /** Open the catalog as the root `/subagents` surface. */ const open = (): void => { openCatalog('root') } /** Open the catalog nested over Work. */ const openFromWork = (): void => { openCatalog('work') } /** * Open a durable child directly, then re-list discovery once. * * Work supplies the row it selected from its own lifecycle view, so the * inspector can draw before any catalog exists. The follow-up discovery read * only reconciles residency; a failure there is reported in the catalog * reading and must never close the inspector or open a catalog, because the * catalog fallback is Work's decision at its own entry point. */ const openChild = (child: SubagentChildRow): void => { openConversationRow(child) refreshCatalog() } if (deps.onLifecycle !== undefined) { disposers.push(deps.onLifecycle(() => { // A direct inspector has no catalog below it, but discovery is still the // authority for its residency, so a lifecycle edge must refresh there too. if (catalogOpen || conversation !== undefined) refreshCatalog() })) } if (deps.onSessionEvent !== undefined) { disposers.push(deps.onSessionEvent(childId => { const state = conversation if (state === undefined || state.child.id !== childId) return // A child event is only a staleness hint: it never mutates the transcript // and never triggers a read, because Harness publishes no per-child // transcript subscription and polling one would be a local state machine. // The count advances for EVERY selected-child event, including one that // arrives while the first read is still in flight; that read captured the // count before it started and publishes `stale` from whether it still matches. state.eventGeneration += 1 if (state.transcript.kind === 'ready') { state.transcript = { ...state.transcript, stale: true } } deps.invalidate() })) } return { command: { name: 'subagents', description: 'Browse durable subagent conversations and continue one', execute: () => { open() }, }, open, openFromWork, openChild, dispose(): void { catalogGeneration += 1 catalogAbort?.abort() conversationAbort?.abort() conversation?.notice.dispose() conversation = undefined for (const dispose of disposers.splice(0)) dispose() }, } } /** * A short, safe account of a read or discovery failure. * @param error - the thrown value. * @returns a message fit for a bounded row. */ function reason(error: unknown): string { return error instanceof Error ? error.message : String(error) }