diff --git a/apps/website/content/docs/react/chat/components/chat-interrupt-panel.mdx b/apps/website/content/docs/react/chat/components/chat-interrupt-panel.mdx index 5f5cb5733..1e6461df3 100644 --- a/apps/website/content/docs/react/chat/components/chat-interrupt-panel.mdx +++ b/apps/website/content/docs/react/chat/components/chat-interrupt-panel.mdx @@ -57,6 +57,41 @@ The shared backend runs c-interrupts by default. Runtime settings can select a d Moving between Code and Run preserves the mounted example and unsent draft. Reloading starts an empty page-local conversation. +## Answer session interrupts from Chat + +A session that can pause lists what it waits on in `snapshot.interrupts`. `Chat` shows nothing for an interrupt by itself, because which value answers an interrupt is the backend's contract. Pass `renderInterrupt` to draw each one, and call `respond.resolve(value)` or `respond.cancel()` from your card: + +```tsx +import { ApprovalCard, Chat } from '@threadplane/react/chat'; + + ( + respond.resolve({ approved: true }), + }, + { + id: 'decline', + label: 'Decline', + onSelect: () => respond.resolve({ approved: false }), + }, + ]} + > + {interrupt.message ?? interrupt.reason} + + )} +/>; +``` + +The cards take the place of the `approval` slot, so the composer reads "Answer the approval to continue" while they are pending and focus returns to it afterwards. `Chat` holds each answer until every pending interrupt has one, then sends them together with one `session.resume`, because a paused run continues once. `respond.answered` is true for an interrupt whose answer waits on the others, and `respond.sending` is true while the answers are on their way. + +If `session.resume` rejects, the answers are dropped so the person can answer again, and the failure goes to `onInterruptError`. `renderInterrupt` is ignored while `approval` is set and on a session that has no `resume`. + ## Build from source From a Threadplane checkout with dependencies installed: diff --git a/apps/website/content/docs/react/chat/components/chat-subagent-card.mdx b/apps/website/content/docs/react/chat/components/chat-subagent-card.mdx index b09b4c6a0..3cd16d872 100644 --- a/apps/website/content/docs/react/chat/components/chat-subagent-card.mdx +++ b/apps/website/content/docs/react/chat/components/chat-subagent-card.mdx @@ -57,7 +57,11 @@ The existing shared backend runs c-subagents. Runtime settings can select a deve `SubagentCard` shows one child agent: its name, a status, a message count, and the child's messages and tool activity behind a closed disclosure. It only presents the data you pass it. Your application still owns the run, the session and any saved history. -Pass `subagents` to `MessageList` or `Chat` to place cards for you. A child whose `toolCallId` matches a tool call in a row renders as a card in place of that call's activity. A child with no matching call is not placed; render `SubagentCard` yourself where it belongs. +`Chat` shows a card for each child agent its session reports in `snapshot.subagents`, with no code from you. A child that names the tool call that started it takes that call's place. A child that names no call, such as a LangGraph child graph, follows the tool calls of the first assistant message of the latest turn, so its card keeps its place as the turn goes on. `toolLabel` and `toolOutcome` apply to the children's own tool calls. + +Pass `subagents` to `Chat` to show your own list instead; an empty list shows no cards. Pass `subagents` to `MessageList` to place cards for you there. A child whose `toolCallId` matches a tool call in a row renders as a card in place of that call's activity. A child with no matching call is not placed unless you set `placeUnanchoredSubagents`; otherwise render `SubagentCard` yourself where it belongs. + +`sessionSubagents(snapshot.subagents)` returns the same card data `Chat` builds, for an application that renders `MessageList` itself. It keeps each card's reference while its child is unchanged. ```tsx import { MessageList, subagentsFromEvidence } from '@threadplane/react/chat'; diff --git a/cockpit/ag-ui/subagents/react/src/children.ts b/cockpit/ag-ui/subagents/react/src/children.ts index 9a4e77113..e660cd401 100644 --- a/cockpit/ag-ui/subagents/react/src/children.ts +++ b/cockpit/ag-ui/subagents/react/src/children.ts @@ -50,14 +50,16 @@ export function observeChildren( const cards = new Map(previous.map((card) => [card.id, card])); let unsupported = false; try { + // Cards follow the current run; children of earlier runs are history. + const children = snapshot.subagents.filter((child) => !child.earlier); if ( cards.size !== previous.length || previous.length > 100 || - snapshot.subagents.length > 30 + children.length > 30 ) throw new Error(); const attributed = new Set( - snapshot.subagents.map((child) => child.started.subagentRunId) + children.map((child) => child.started.subagentRunId) ); if ( snapshot.transcript.some( @@ -68,7 +70,7 @@ export function observeChildren( ) throw new Error(); const seen = new Set(); - for (const child of snapshot.subagents) { + for (const child of children) { const started = child.started; const id = started.subagentRunId, callId = started.parentToolCallId; diff --git a/cockpit/ag-ui/subagents/react/src/policy.ts b/cockpit/ag-ui/subagents/react/src/policy.ts index 6abf36c79..95467c257 100644 --- a/cockpit/ag-ui/subagents/react/src/policy.ts +++ b/cockpit/ag-ui/subagents/react/src/policy.ts @@ -85,7 +85,7 @@ export function confirmParent( if (!valid()) return; const run = snapshot.run, transcript = snapshot.transcript, - children = snapshot.subagents; + children = snapshot.subagents.filter((child) => !child.earlier); if ( !valid() || snapshot.status !== 'idle' || diff --git a/libs/ag-ui/src/runtime/README.md b/libs/ag-ui/src/runtime/README.md index 96926b977..84ee317bd 100644 --- a/libs/ag-ui/src/runtime/README.md +++ b/libs/ag-ui/src/runtime/README.md @@ -149,16 +149,23 @@ const session = createSession({ threadId, url }); is sent. Each entry is the protocol's interrupt, so it has the core `id`, `reason`, `message` and `toolCallId` and any other field the backend sent. It is absent when nothing is waiting, and for a pause this session cannot answer. -- `subagents` lists the current run's children as core child agents: `id`, - `name`, `description`, `toolCallId`, `parentId`, `status`, and the child's own - `messages` and `toolCalls`, which the root lists do not repeat. The protocol - evidence stays on each child as `started` and `terminal`. A child with - finished evidence is `complete`, one with error evidence is `error` and - carries its message, and one with neither is `running` while the root run is - going and `unknown` after it. A child keeps its reference until its evidence, - status or records change. Children of earlier runs are bare evidence in - `earlierSubagents`. Records are matched by run id, so a later child that - reuses an id also lists the earlier child's records. +- `subagents` lists every child the session knows as a core child agent: + children of earlier root runs first, marked `earlier`, then the current run's, + each in start order. A child has `id`, `name`, `description`, `toolCallId`, + `parentId`, `status`, and its own `messages` and `toolCalls`, which the root + lists do not repeat. The protocol evidence stays on each child as `started` + and `terminal`. `earlierSubagents` still holds the earlier children's bare + evidence. + - Error evidence is `error` and carries its message. Finished evidence is + `complete`, unless the child finished `suspended`: it paused and can + continue, so it is `running` in its own run and while a later run is going, + and `unknown` once a later run ends without continuing it. A child with no + ending is `running` while the root run is going and `unknown` after it. + - A child lists the records attributed to its run id within its own run. A + child that starts again after pausing continues: it is one child, and keeps + the records from before the pause. Any other child that reuses a run id + replaces the earlier one and starts with none of its records. + - A child keeps its reference until its evidence, status or records change. - Every publication notifies subscribers, including one that changes only protocol evidence such as a decision or a child. - `submit` takes text, or `{ message, state? }` with a state patch. diff --git a/libs/ag-ui/src/runtime/agent-session.ts b/libs/ag-ui/src/runtime/agent-session.ts index 090f8fbbc..85280f524 100644 --- a/libs/ag-ui/src/runtime/agent-session.ts +++ b/libs/ag-ui/src/runtime/agent-session.ts @@ -33,9 +33,10 @@ export type SessionSnapshot = Omit< */ readonly interrupts?: readonly SessionInterrupt[]; /** - * The current root run's children, each with its own messages and tool - * calls and the protocol evidence it was read from. Children of earlier - * runs are in `earlierSubagents`. + * Every child agent the session knows, each with its own messages and + * tool calls and the protocol evidence it was read from: children of + * earlier root runs first, marked `earlier`, then the current run's. + * `earlierSubagents` still holds the earlier children's bare evidence. */ readonly subagents: readonly SessionSubagent[]; /** diff --git a/libs/ag-ui/src/runtime/child-projection.spec.ts b/libs/ag-ui/src/runtime/child-projection.spec.ts index 7b8d3e9d0..497e25c74 100644 --- a/libs/ag-ui/src/runtime/child-projection.spec.ts +++ b/libs/ag-ui/src/runtime/child-projection.spec.ts @@ -141,6 +141,102 @@ describe('core interrupts and child agents on the AG-UI snapshot', () => { } }); + it('keeps a paused child running and continues it with its records after resume', async () => { + const fixture = bindingFixture(); + try { + const run = fixture.session.submit('Book it'); + const exchange = await fixture.started(); + const paused = fixture.changed( + (snapshot) => snapshot.subagents[0]?.terminal !== undefined + ); + exchange.emit({ + type: 'SUBAGENT_STARTED', + subagentRunId: 'child', + name: 'booker', + }); + exchange.emit({ + type: 'TEXT_MESSAGE_START', + messageId: 'before', + role: 'assistant', + subagentRunId: 'child', + }); + exchange.emit({ + type: 'TEXT_MESSAGE_CONTENT', + messageId: 'before', + delta: 'Need approval', + }); + exchange.emit({ type: 'TEXT_MESSAGE_END', messageId: 'before' }); + exchange.emit({ + type: 'SUBAGENT_FINISHED', + subagentRunId: 'child', + outcome: { type: 'suspended', interruptIds: ['approval'] }, + }); + await paused; + exchange.emit({ + type: 'RUN_FINISHED', + threadId: exchange.body.threadId, + runId: exchange.body.runId, + outcome: { + type: 'interrupt', + interrupts: [{ id: 'approval', reason: 'approve' }], + }, + }); + await expect(run).resolves.toBe('paused'); + // Paused is not finished: the child can continue. + expect(fixture.session.getSnapshot().subagents[0].status).toBe('running'); + + const resumed = fixture.session.resume([ + { interruptId: 'approval', status: 'resolved' }, + ]); + const next = await fixture.started(1); + // Between the answer and the child's restart it is history, still going. + expect(fixture.session.getSnapshot().subagents).toMatchObject([ + { id: 'child', status: 'running', earlier: true }, + ]); + const continued = fixture.changed( + (snapshot) => + snapshot.subagents.length === 1 && + snapshot.subagents[0].messages.length === 2 + ); + next.emit({ + type: 'SUBAGENT_STARTED', + subagentRunId: 'child', + name: 'booker', + }); + next.emit({ + type: 'TEXT_MESSAGE_START', + messageId: 'after', + role: 'assistant', + subagentRunId: 'child', + }); + next.emit({ + type: 'TEXT_MESSAGE_CONTENT', + messageId: 'after', + delta: 'Booked', + }); + next.emit({ type: 'TEXT_MESSAGE_END', messageId: 'after' }); + // One child, not two, and it keeps what it said before the pause. + const child = (await continued).subagents[0]; + expect(child).not.toHaveProperty('earlier'); + expect(child.messages.map((message) => message.content)).toEqual([ + 'Need approval', + 'Booked', + ]); + next.emit({ type: 'SUBAGENT_FINISHED', subagentRunId: 'child' }); + next.emit({ + type: 'RUN_FINISHED', + threadId: next.body.threadId, + runId: next.body.runId, + }); + await expect(resumed).resolves.toBe('success'); + expect(fixture.session.getSnapshot().subagents[0].status).toBe( + 'complete' + ); + } finally { + await fixture.cleanup(); + } + }); + it('lists pending interrupts until an answer is sent, and answers them by id', async () => { const fixture = bindingFixture(); try { diff --git a/libs/ag-ui/src/runtime/child-projection.ts b/libs/ag-ui/src/runtime/child-projection.ts index e29b602e1..25a92f008 100644 --- a/libs/ag-ui/src/runtime/child-projection.ts +++ b/libs/ag-ui/src/runtime/child-projection.ts @@ -1,19 +1,27 @@ import type { AgentSubagent, Message, ToolCall } from '@threadplane/core'; import { projectMessages, projectToolCalls } from './message-projection.js'; import type { Observation } from './session-observation.js'; -import type { SubagentObservation } from './subagents.js'; +import { + currentFrom, + earlierSpan, + suspended, + type ChildSpan, + type SubagentObservation, +} from './subagents.js'; import type { Transcript } from './transcript.js'; type TranscriptRecord = Transcript[number]; /** - * One child of the current root run: the core child, with the protocol - * evidence it was read from. `messages` and `toolCalls` are the child's own - * and are not repeated in the root snapshot's. They are every transcript record - * attributed to the child's run id, so a later child that reuses an id also - * lists the earlier child's records. + * One child agent: the core child, with the protocol evidence it was read + * from. `messages` and `toolCalls` are the child's own and are not repeated in + * the root snapshot's. */ -export type SessionSubagent = AgentSubagent & SubagentObservation; +export type SessionSubagent = AgentSubagent & + SubagentObservation & { + /** Set on a child that settled in an earlier root run or came with the thread. */ + readonly earlier?: true; + }; /** A child's records read as a root transcript, so the root selectors apply. */ const unattributed = new WeakMap(); @@ -29,12 +37,23 @@ function asRoot(record: TranscriptRecord): TranscriptRecord { return known; } +/** + * - Error evidence is `error`, and finished evidence is `complete`, unless the + * child finished `suspended`: it paused and can continue, so it is `running` + * in its own run and while a later run is going, and `unknown` once a later + * run ends without continuing it. + * - A child with no ending is `running` while the root run is going and + * `unknown` after it. + */ function status( evidence: SubagentObservation, - running: boolean + running: boolean, + earlier: boolean ): AgentSubagent['status'] { - if (evidence.terminal) - return evidence.terminal.type === 'SUBAGENT_ERROR' ? 'error' : 'complete'; + const terminal = evidence.terminal; + if (terminal?.type === 'SUBAGENT_ERROR') return 'error'; + if (terminal && !suspended(evidence)) return 'complete'; + if (terminal) return running || !earlier ? 'running' : 'unknown'; return running ? 'running' : 'unknown'; } @@ -43,35 +62,57 @@ const noMessages: readonly Message[] = Object.freeze([]); const noCalls: readonly ToolCall[] = Object.freeze([]); /** - * The current run's children as core children. Each keeps its reference, and - * the list keeps its own, until that child's evidence, status or transcript - * changes. `previous` is the list this function returned last. + * Every child the session knows as a core child: those of earlier root runs + * first, then the current run's, each list in start order. A current child + * replaces an earlier one with the same run ID. + * + * A child lists the records attributed to its run ID within its own run. A + * child that starts again after pausing continues, and keeps the records from + * before the pause; any other child that reuses an ID starts with none. + * + * Each child keeps its reference, and the list keeps its own, until that + * child's evidence, status or records change. `previous` is the list this + * function returned last. */ export function projectSubagents( native: Observation, previous: readonly SessionSubagent[] = none ): readonly SessionSubagent[] { - if (!native.subagents.length) return previous.length ? none : previous; - const records = new Map(); - for (const record of native.transcript) { - const child = (record as { subagentRunId?: unknown }).subagentRunId; - if (typeof child !== 'string') continue; - const own = records.get(child); - if (own) own.push(asRoot(record)); - else records.set(child, [asRoot(record)]); - } - const prior = new Map(previous.map((child) => [child.id, child])); + const current = native.subagents; + const replaced = new Set(current.map((c) => c.started.subagentRunId)); + const earlier = (native.earlierSubagents ?? []).filter( + (child) => !replaced.has(child.started.subagentRunId) + ); + if (!current.length && !earlier.length) + return previous.length ? none : previous; const running = native.status === 'running'; - let changed = previous.length !== native.subagents.length; - const children = native.subagents.map((evidence, index) => { + const transcript = native.transcript; + const prior = new Map(previous.map((child) => [child.id, child])); + let changed = previous.length !== earlier.length + current.length; + const project = ( + evidence: SubagentObservation, + span: ChildSpan, + isEarlier: boolean, + index: number + ): SessionSubagent => { const { started, terminal } = evidence; const id = started.subagentRunId; + const records: TranscriptRecord[] = []; + const end = Math.min(span.to ?? transcript.length, transcript.length); + for (let position = span.from; position < end; position++) { + const record = transcript[position]; + if ((record as { subagentRunId?: unknown }).subagentRunId === id) + records.push(asRoot(record)); + } const before = prior.get(id); - const state = status(evidence, running); - // A child with terminal evidence streams nothing further. + const state = status(evidence, running, isEarlier); + // Only a child of the run that is going can still be streaming. const view = { - status: state === 'running' ? ('running' as const) : ('idle' as const), - transcript: Object.freeze(records.get(id) ?? []) as Transcript, + status: + state === 'running' && running && !terminal + ? ('running' as const) + : ('idle' as const), + transcript: Object.freeze(records) as Transcript, reasoningDurations: native.reasoningDurations, }; const messages = projectMessages(view, before?.messages ?? noMessages); @@ -81,6 +122,7 @@ export function projectSubagents( before.started === started && before.terminal === terminal && before.status === state && + before.earlier === (isEarlier || undefined) && before.messages === messages && before.toolCalls === toolCalls ) { @@ -107,7 +149,27 @@ export function projectSubagents( typeof terminal.message === 'string' && { error: terminal.message }), started, ...(terminal && { terminal }), + ...(isEarlier && { earlier: true as const }), }) as SessionSubagent; - }); + }; + const children = [ + ...earlier.map((child, index) => + project(child, earlierSpan(child), true, index) + ), + ...current.map((child, index) => + project( + child, + { + from: currentFrom( + child.started.subagentRunId, + current, + native.earlierSubagents + ), + }, + false, + earlier.length + index + ) + ), + ]; return changed ? Object.freeze(children) : previous; } diff --git a/libs/ag-ui/src/runtime/create-session.ts b/libs/ag-ui/src/runtime/create-session.ts index 5d40a174c..502238007 100644 --- a/libs/ag-ui/src/runtime/create-session.ts +++ b/libs/ag-ui/src/runtime/create-session.ts @@ -37,7 +37,7 @@ import { initialObservation, type Observation, } from './session-observation.js'; -import { earlierSubagents, type Subagents } from './subagents.js'; +import { nextInvocation, type Subagents } from './subagents.js'; import { createRun, httpFailure, type RunHandle } from './create-run.js'; import { createPublication } from './session-publication.js'; import { @@ -82,16 +82,20 @@ export interface SessionOptions readonly subagents?: Subagents; readonly interruptMode?: InterruptMode; } -/** A new root invocation observes no children yet; settled ones become history. */ -function nextInvocationSubagents(previous: Observation) { - const earlier = earlierSubagents( - previous.earlierSubagents, - previous.subagents +/** + * A new root invocation observes no children yet; settled ones become history. + * `transcript` is the history the new invocation begins with, when it is not + * the previous one. + */ +function nextInvocationSubagents( + previous: Observation, + transcript: Transcript = previous.transcript +) { + return nextInvocation( + previous, + previous.transcript.length, + transcript.length ); - return { - subagents: Object.freeze([]) as Subagents, - ...(earlier && { earlierSubagents: earlier }), - }; } export interface Session { /** The state declaration this session was created with, when it has one. */ @@ -673,7 +677,7 @@ export function createSession( status: 'running', transcript: last.transcript, state: last.state, - ...nextInvocationSubagents(previous), + ...nextInvocationSubagents(previous, last.transcript), run: Object.freeze({ id }), }), undefined, @@ -703,7 +707,9 @@ export function createSession( root(index) ); if (at < 0) - throw new Error('Regenerate needs the id of an assistant message.'); + throw new Error( + 'Regenerate needs the id of an assistant message.' + ); for (let index = at - 1; index >= 0 && prompt < 0; index--) if (transcript[index].role === 'user' && root(index)) prompt = index; @@ -728,7 +734,7 @@ export function createSession( ...previous, status: 'running', transcript, - ...nextInvocationSubagents(previous), + ...nextInvocationSubagents(previous, transcript), run: Object.freeze({ id }), }), signal, @@ -1492,8 +1498,7 @@ function createToolsOwner( resolve('aborted'); return; } - if (interruptMode !== 'native') - throw new TypeError(NOT_SETTLED); + if (interruptMode !== 'native') throw new TypeError(NOT_SETTLED); const previous = publication.getObservation(); captured = captureResponses(responses); claimDecision( diff --git a/libs/ag-ui/src/runtime/decision.type-test.ts b/libs/ag-ui/src/runtime/decision.type-test.ts index bfb4fdcfc..9845aa13e 100644 --- a/libs/ag-ui/src/runtime/decision.type-test.ts +++ b/libs/ag-ui/src/runtime/decision.type-test.ts @@ -99,3 +99,10 @@ void observer.resume?.([ ]); // @ts-expect-error the core contract has no pause token void observer.resume?.(pause, [resolved]); + +// Child agents of earlier root runs are marked, so a view can tell them apart. +const earlierChild: true | undefined = + session.getSnapshot().subagents[0]?.earlier; +// @ts-expect-error The mark is derived, not assigned. +session.getSnapshot().subagents[0].earlier = true; +void earlierChild; diff --git a/libs/ag-ui/src/runtime/session-http.spec.ts b/libs/ag-ui/src/runtime/session-http.spec.ts index ef29ccec0..f358c4746 100644 --- a/libs/ag-ui/src/runtime/session-http.spec.ts +++ b/libs/ag-ui/src/runtime/session-http.spec.ts @@ -319,8 +319,18 @@ describe('composed private session over held HTTP', () => { [...exchange.body.messages, ...next.body.messages].map((m) => m.id) ).size ).toBe(next.body.messages.length); - // The resumed invocation observes no children yet; the finished one is history. - expect(owner.getSnapshot().subagents).toEqual([]); + // The resumed invocation observes no children yet; the finished one is + // history, and still listed as a child agent with its own records. + const carried = owner.getSnapshot().subagents; + expect(carried).toHaveLength(1); + expect(carried[0]).toMatchObject({ + id: 'child', + status: 'complete', + earlier: true, + }); + expect(carried[0].messages).toEqual(settled.subagents[0].messages); + expect(carried[0].started).toBe(settled.subagents[0].started); + expect(settled.subagents[0]).not.toHaveProperty('earlier'); expect(settled).not.toHaveProperty('earlierSubagents'); expect(settled.subagents[0].terminal?.type).toBe('SUBAGENT_FINISHED'); // History keeps the child's protocol evidence, by reference, without @@ -361,17 +371,35 @@ describe('composed private session over held HTTP', () => { }, terminal: { type: 'SUBAGENT_FINISHED', subagentRunId: 'child' }, }; - // This turn asserts the child's identity and evidence, not its own - // messages and tool calls. + // The new child replaces the earlier one with its ID, and starts with + // none of that child's records. expect(latest).toHaveLength(1); - expect(latest).toMatchObject([ - { id: 'child', name: 'again', status: 'complete', ...reused }, + expect(latest).toStrictEqual([ + { + id: 'child', + name: 'again', + status: 'complete', + messages: [], + toolCalls: [], + ...reused, + }, ]); + expect(carried[0].messages).not.toEqual([]); expect(latest[0].started).toStrictEqual(reused.started); expect(latest[0].terminal).toStrictEqual(reused.terminal); const fourth = owner.submit('once more'); const last = await server.next(3); - expect(owner.getSnapshot().subagents).toEqual([]); + expect(owner.getSnapshot().subagents).toStrictEqual([ + { + id: 'child', + name: 'again', + status: 'complete', + messages: [], + toolCalls: [], + ...reused, + earlier: true, + }, + ]); expect(owner.getSnapshot().earlierSubagents).toStrictEqual([reused]); expect(owner.getSnapshot().earlierSubagents?.[0].started).toBe( latest[0].started diff --git a/libs/ag-ui/src/runtime/session-observation.ts b/libs/ag-ui/src/runtime/session-observation.ts index 5e6b216cc..11601a9e4 100644 --- a/libs/ag-ui/src/runtime/session-observation.ts +++ b/libs/ag-ui/src/runtime/session-observation.ts @@ -12,7 +12,11 @@ import type { PlainValue, } from '@threadplane/core'; import { ownTranscript, type Transcript } from './transcript.js'; -import { applySubagent, ownSubagents, type Subagents } from './subagents.js'; +import { + applySubagent, + restoredSubagents, + type Subagents, +} from './subagents.js'; import { NO_STATE, ownState, applyState } from './state.js'; import { reconcileTranscript } from './reconcile-transcript.js'; import { applyTextMessage } from './text-messages.js'; @@ -113,7 +117,7 @@ export function initialObservation( ): Observation { const transcript = ownTranscript(messages); assertTranscriptIdentity(transcript); - const earlier = ownSubagents(subagents); + const earlier = restoredSubagents(subagents, transcript.length); return Object.freeze({ status: 'idle', transcript, diff --git a/libs/ag-ui/src/runtime/subagents.ts b/libs/ag-ui/src/runtime/subagents.ts index 9993c3f00..9581466e3 100644 --- a/libs/ag-ui/src/runtime/subagents.ts +++ b/libs/ag-ui/src/runtime/subagents.ts @@ -32,6 +32,97 @@ export interface SubagentObservation { } export type Subagents = readonly SubagentObservation[]; +/** Where in the transcript a child's own records lie: from `from`, up to but + * not including `to`. A child of the current invocation has no `to`. */ +export interface ChildSpan { + readonly from: number; + readonly to?: number; +} +/** Bookkeeping beside the evidence, so the published evidence keeps its shape. */ +const invocationStarts = new WeakMap(); +const spans = new WeakMap(); + +/** True for a child whose last evidence says it paused and can continue. */ +export function suspended(child: SubagentObservation): boolean { + const terminal = child.terminal; + return ( + terminal?.type === 'SUBAGENT_FINISHED' && + (terminal.outcome as { type?: unknown } | undefined)?.type === 'suspended' + ); +} + +/** The transcript length when the invocation that owns `current` began. */ +export function invocationStart(current: Subagents): number { + return invocationStarts.get(current) ?? 0; +} + +/** + * The records an earlier child owns. Evidence restored with a thread owns the + * restored records attributed to it. + */ +export function earlierSpan(child: SubagentObservation): ChildSpan { + return spans.get(child) ?? { from: 0 }; +} + +/** + * Where a child of the current invocation begins. A child continues an earlier + * one with the same ID when that one paused, so it keeps those records; any + * other reuse of an ID starts a separate child. + */ +export function currentFrom( + id: string, + current: Subagents, + earlier: Subagents | undefined +): number { + const before = earlier?.find((child) => child.started.subagentRunId === id); + return before && suspended(before) + ? earlierSpan(before).from + : invocationStart(current); +} + +/** Restored evidence owns the restored transcript's records, and no later ones. */ +export function restoredSubagents( + restored: unknown, + transcriptLength: number +): Subagents | undefined { + const owned = ownSubagents(restored); + for (const child of owned ?? []) + spans.set(child, { from: 0, to: transcriptLength }); + return owned; +} + +/** + * Child evidence for the next root invocation. `ending` is the transcript + * length the ending invocation reached, and `start` the length the next one + * begins with; they differ when the next invocation rebuilds its history. + */ +export function nextInvocation( + previous: { + readonly subagents: Subagents; + readonly earlierSubagents?: Subagents; + }, + ending: number, + start: number +): { readonly subagents: Subagents; readonly earlierSubagents?: Subagents } { + for (const child of previous.subagents) + if (child.terminal) + spans.set(child, { + from: currentFrom( + child.started.subagentRunId, + previous.subagents, + previous.earlierSubagents + ), + to: ending, + }); + const earlier = earlierSubagents( + previous.earlierSubagents, + previous.subagents + ); + const subagents: Subagents = Object.freeze([]); + invocationStarts.set(subagents, start); + return { subagents, ...(earlier && { earlierSubagents: earlier }) }; +} + /** History for the next root invocation: earlier children, then this * invocation's children that have terminal evidence. A child with no terminal * evidence is dropped, because nothing later can establish what became of it. @@ -160,5 +251,7 @@ export function applySubagent( started: previous[index].started, terminal: captured, }); - return Object.freeze(next); + const applied: Subagents = Object.freeze(next); + invocationStarts.set(applied, invocationStart(previous)); + return applied; } diff --git a/libs/angular/src/observe-agent.ag-ui.spec.ts b/libs/angular/src/observe-agent.ag-ui.spec.ts index e85b62563..b6c498160 100644 --- a/libs/angular/src/observe-agent.ag-ui.spec.ts +++ b/libs/angular/src/observe-agent.ag-ui.spec.ts @@ -130,7 +130,8 @@ describe('observeAgent native AG-UI owner', () => { { id: 'child', name: 'worker', - status: 'complete', + // The child finished suspended: it paused and can continue. + status: 'running', messages: [], toolCalls: [], started: { diff --git a/libs/langgraph/src/runtime/README.md b/libs/langgraph/src/runtime/README.md index 2ff51505c..4f8c834c6 100644 --- a/libs/langgraph/src/runtime/README.md +++ b/libs/langgraph/src/runtime/README.md @@ -317,15 +317,15 @@ panel or telemetry: `getSnapshot()` returns a frozen `LangGraphLifecycle` and `useSyncExternalStore`. Each value is epoch milliseconds on this clock, null until its milestone happens. -| Value | Stamped | -| --------------------- | -------------------------------------------------------------- | -| `streamStartedAt` | The first event to arrive on any run's stream. | -| `streamErrorAt` | The most recent published failure, as `{ at, kind }`. | -| `interruptReceivedAt` | The first time the session held a pending interrupt. | -| `interruptResolvedAt` | The most recent `resume` the session accepted. | -| `threadPersistedAt` | The first history read that returned saved checkpoints. | -| `toolCallStartedAt` | The first time the session held a tool call. | -| `toolCallCompletedAt` | The first time a tool call was complete or failed. | +| Value | Stamped | +| --------------------- | ------------------------------------------------------- | +| `streamStartedAt` | The first event to arrive on any run's stream. | +| `streamErrorAt` | The most recent published failure, as `{ at, kind }`. | +| `interruptReceivedAt` | The first time the session held a pending interrupt. | +| `interruptResolvedAt` | The most recent `resume` the session accepted. | +| `threadPersistedAt` | The first history read that returned saved checkpoints. | +| `toolCallStartedAt` | The first time the session held a tool call. | +| `toolCallCompletedAt` | The first time a tool call was complete or failed. | A session serves one thread, so nothing is reset: where the Angular adapter clears its `AgentLifecycle` on `switchThread()`, a session for another thread @@ -365,6 +365,32 @@ paused. The preflight detects already-observed consumption, but it is not an ato server claim. Applications must coordinate responders to the same task. Distinct checkpoint branches do not provide independent opposing decisions on one task. +## Child agents + +`snapshot.subgraphs` holds one entry for each child graph the run reported, with +its `namespace`, its own `messages` and `toolCalls`, its `state`, `interrupts` +and `error`. `snapshot.subagents` publishes the same children as the core +contract's child agents, one for each and in the same order, so a component +written for core sessions can show them: + +- `id` is the namespace path as JSON, which stays unique whatever a segment + contains. `parentId` is the `id` of the enclosing child graph, and is absent + for a child of the root graph. `namespace` is kept alongside. +- `name` is the node that started the child: the part of the last namespace + segment before its `:`. +- `messages` and `toolCalls` are the child graph's own, the same references as + in `subgraphs`. The root `messages` and `toolCalls` do not repeat them. +- `status` is `error` for a child that failed, with the display text in + `error`, and `running` while the root run is going. After the run, a child + whose last message succeeded is `complete`, one a pause stopped is still + `running` because a resume continues it, and any other child is `unknown`. +- LangGraph does not relate a child graph to a tool call, so `toolCallId` and + `description` are never set. + +A child agent keeps its reference while its child graph and status are +unchanged. Child agents give no command authority: answering a pause is the +root session's `resume`. + ## Thread directory `createLangGraphThreadDirectory` in `thread-directory.ts` implements the diff --git a/libs/langgraph/src/runtime/langgraph-snapshot.ts b/libs/langgraph/src/runtime/langgraph-snapshot.ts index 1393ead24..04442086d 100644 --- a/libs/langgraph/src/runtime/langgraph-snapshot.ts +++ b/libs/langgraph/src/runtime/langgraph-snapshot.ts @@ -5,8 +5,10 @@ import type { DeepReadonly, PlainValue, Message, + ToolCall, ToolContract, } from '@threadplane/core'; +import type { LangGraphSubagent } from './subagent-projection.js'; import type { Interrupt, ThreadState } from '@langchain/langgraph-sdk'; /** Compact metadata from an explicitly loaded page, without repeated state data. */ @@ -39,12 +41,17 @@ export type LangGraphSnapshotState = unknown extends TState export interface LangGraphSubgraph { readonly namespace: readonly string[]; readonly messages: readonly Message[]; + /** The child graph's own tool calls, referenced by `Message.toolCallIds` in `messages`. */ + readonly toolCalls: readonly ToolCall[]; /** A child graph's state. It is never checked against the session's declaration. */ readonly state: LangGraphState | undefined; readonly interrupts: readonly LangGraphWireInterrupt[]; readonly error?: AgentError; } +/** What a publication supplies: the session derives `subagents` from `subgraphs`. */ +export type LangGraphPublication = Omit; + /** Backend-private extension; the core snapshot remains backend-independent. */ export type LangGraphSnapshot< TTools extends { [K in keyof TTools]: ToolContract } = Record< @@ -52,7 +59,7 @@ export type LangGraphSnapshot< ToolContract >, TState = unknown -> = Omit, 'interrupts'> & { +> = Omit, 'interrupts' | 'subagents'> & { /** Last explicit history page; undefined until loaded. Not a live branch tree. */ readonly history: readonly LangGraphHistoryEntry[] | undefined; /** @@ -68,4 +75,9 @@ export type LangGraphSnapshot< readonly reconnect?: { readonly runId: string }; readonly interrupts: readonly LangGraphInterrupt[]; readonly subgraphs: readonly LangGraphSubgraph[]; + /** + * The child graphs in `subgraphs` as the core contract's child agents, one + * for each and in the same order. + */ + readonly subagents: readonly LangGraphSubagent[]; }; diff --git a/libs/langgraph/src/runtime/ownership.ts b/libs/langgraph/src/runtime/ownership.ts index 6a6dabf7d..f44f750a5 100644 --- a/libs/langgraph/src/runtime/ownership.ts +++ b/libs/langgraph/src/runtime/ownership.ts @@ -10,11 +10,13 @@ import { } from '@threadplane/core'; import type { LangGraphInterrupt, + LangGraphPublication, LangGraphWireInterrupt, LangGraphSnapshot, LangGraphSubgraph, LangGraphState, } from './langgraph-snapshot.js'; +import { projectSubagents } from './subagent-projection.js'; // Only objects projected here are trusted. Object.isFrozen on external input is // insufficient: its children may still be mutable. The weak set retains no data. @@ -324,7 +326,7 @@ export function ownSnapshot( /** One backend aggregate, composing the core fields and owned application data. */ export function ownLangGraphSnapshot( - input: LangGraphSnapshot, + input: LangGraphPublication, previous?: LangGraphSnapshot ): LangGraphSnapshot { const core = ownSnapshot(input, previous); @@ -333,6 +335,12 @@ export function ownLangGraphSnapshot( previous?.history as PlainValue ) as LangGraphSnapshot['history']; const subgraphs = ownSubgraphs(input.subgraphs, previous?.subgraphs); + // Derived here, so the children always agree with the published child graphs. + const subagents = projectSubagents( + subgraphs, + core.status, + previous?.subagents + ); const state = ownValueWithSharing(input.state, previous?.state) as | LangGraphState | undefined; @@ -355,6 +363,7 @@ export function ownLangGraphSnapshot( stateIssues === previous?.stateIssues && interrupts === previous?.interrupts && subgraphs === previous?.subgraphs && + subagents === previous?.subagents && reconnect === previous?.reconnect ) return previous; @@ -371,6 +380,7 @@ export function ownLangGraphSnapshot( ...(stateIssues ? { stateIssues } : {}), interrupts, subgraphs, + subagents, ...(reconnect ? { reconnect } : {}), }); } @@ -390,6 +400,13 @@ export function ownSubgraph( ownMessage, sameMessage ); + // A restored child graph may predate `toolCalls`. + const toolCalls = ownArray( + input.toolCalls ?? [], + previous?.toolCalls, + ownToolCall, + sameToolCall + ); const state = ownValueWithSharing(input.state, previous?.state) as | LangGraphState | undefined; @@ -404,6 +421,7 @@ export function ownSubgraph( previous && namespace === previous.namespace && messages === previous.messages && + toolCalls === previous.toolCalls && state === previous.state && interrupts === previous.interrupts && error === previous.error @@ -412,6 +430,7 @@ export function ownSubgraph( return freeze({ namespace, messages, + toolCalls, state, interrupts, ...(error ? { error } : {}), @@ -430,6 +449,7 @@ export function ownSubgraphs( a === b || (a.namespace === b.namespace && a.messages === b.messages && + a.toolCalls === b.toolCalls && a.state === b.state && a.interrupts === b.interrupts && sameError(a.error, b.error)) diff --git a/libs/langgraph/src/runtime/publication.spec.ts b/libs/langgraph/src/runtime/publication.spec.ts index 7595663ac..eadd9d6e1 100644 --- a/libs/langgraph/src/runtime/publication.spec.ts +++ b/libs/langgraph/src/runtime/publication.spec.ts @@ -2,9 +2,9 @@ import { streamingDelivery } from '@threadplane/core'; import { describe, expect, it } from 'vitest'; import { createPublication } from './publication'; import { deferred } from './testing/deferred'; -import type { LangGraphSnapshot } from './langgraph-snapshot'; +import type { LangGraphPublication } from './langgraph-snapshot'; -function snapshot(content = 'one'): LangGraphSnapshot { +function snapshot(content = 'one'): LangGraphPublication { return { status: 'idle', history: undefined, @@ -36,7 +36,7 @@ describe('private snapshot publication', () => { it('publishes reasoning-only changes, owns queued getter strings and suppresses equal values', () => { const publication = createPublication(snapshot()); let reasoning = 'Captured'; - const input = (): LangGraphSnapshot => ({ + const input = (): LangGraphPublication => ({ ...snapshot(), messages: [ { @@ -47,7 +47,7 @@ describe('private snapshot publication', () => { }, ], }); - const seen: LangGraphSnapshot[] = []; + const seen: LangGraphPublication[] = []; publication.subscribe(() => { seen.push(publication.getSnapshot()); if (seen.length === 1) { @@ -78,11 +78,11 @@ describe('private snapshot publication', () => { const citations = [ { id: 'c', index: 1, title: 'Original', extra: { tags: ['original'] } }, ]; - const input = (): LangGraphSnapshot => ({ + const input = (): LangGraphPublication => ({ ...snapshot('two'), messages: [{ ...snapshot('two').messages[0], citations }], }); - const seen: LangGraphSnapshot[] = []; + const seen: LangGraphPublication[] = []; publication.subscribe(() => { seen.push(publication.getSnapshot()); if (seen.length === 1) { @@ -138,7 +138,7 @@ describe('private snapshot publication', () => { if (populated) array[0] = 1; return array; }; - const input = (length: number): LangGraphSnapshot => ({ + const input = (length: number): LangGraphPublication => ({ ...snapshot(), toolCalls: [ { @@ -230,7 +230,7 @@ describe('private snapshot publication', () => { ...snapshot('Invalid'), state: { count: 9 }, interrupts: [{ value: new Date() }], - } as unknown as LangGraphSnapshot) + } as unknown as LangGraphPublication) ).toThrow(TypeError); expect(publication.getSnapshot()).toBe(before); }); @@ -241,7 +241,7 @@ describe('private snapshot publication', () => { publication.publish({ ...snapshot('candidate'), state: { bad: new Date(0) }, - } as unknown as LangGraphSnapshot) + } as unknown as LangGraphPublication) ).toThrow(TypeError); expect(publication.getSnapshot()).toBe(before); }); @@ -249,12 +249,12 @@ describe('private snapshot publication', () => { it('owns application values and suppresses equal queued aggregate publications', () => { const data = { stable: { x: 1 }, count: 1 }; const publication = createPublication({ ...snapshot(), state: data }); - const first = publication.getSnapshot() as LangGraphSnapshot; + const first = publication.getSnapshot() as LangGraphPublication; expect(first.state).toEqual(data); expect(first.state).not.toBe(data); data.stable.x = 9; expect(first.state?.['stable']).toEqual({ x: 1 }); - const seen: LangGraphSnapshot[] = []; + const seen: LangGraphPublication[] = []; for (let index = 0; index < 2; index++) publication.subscribe(() => { if (publication.getSnapshot().status === 'running') { @@ -268,7 +268,7 @@ describe('private snapshot publication', () => { } }); publication.subscribe(() => - seen.push(publication.getSnapshot() as LangGraphSnapshot) + seen.push(publication.getSnapshot() as LangGraphPublication) ); publication.publish({ ...first, status: 'running' }); expect(seen).toHaveLength(2); @@ -288,7 +288,7 @@ describe('private snapshot publication', () => { toolCalls: [{ ...input.toolCalls[0], args: new Date() }], }; expect(() => - createPublication(invalid as unknown as LangGraphSnapshot) + createPublication(invalid as unknown as LangGraphPublication) ).toThrow(TypeError); const publication = createPublication({ ...input, @@ -300,7 +300,7 @@ describe('private snapshot publication', () => { toolCalls: [ { id: 't', name: 'search', status: 'running', args: new Date() }, ], - } as unknown as LangGraphSnapshot) + } as unknown as LangGraphPublication) ).toThrow(TypeError); }); it('caches repeated reads per session and observes only actual changes', () => { diff --git a/libs/langgraph/src/runtime/publication.ts b/libs/langgraph/src/runtime/publication.ts index a1ad40a82..d40e34936 100644 --- a/libs/langgraph/src/runtime/publication.ts +++ b/libs/langgraph/src/runtime/publication.ts @@ -1,12 +1,12 @@ import type { AgentSessionCustomEvent } from '@threadplane/core'; -import type { LangGraphSnapshot } from './langgraph-snapshot.js'; +import type { LangGraphPublication } from './langgraph-snapshot.js'; import { ownLangGraphSnapshot } from './ownership.js'; /** Backend-private publication. Listener failures are reported once to the * optional callback and otherwise ignored; reporter failures are contained too. * Neither kind of failure changes execution state or rejects a command. */ export function createPublication( - initial: LangGraphSnapshot, + initial: LangGraphPublication, reportListenerError: (error: unknown) => void = () => undefined ) { let current = ownLangGraphSnapshot(initial); @@ -36,7 +36,7 @@ export function createPublication( } } - function publish(input: LangGraphSnapshot): void { + function publish(input: LangGraphPublication): void { // Capture external ingress now, including when a listener queues a publish. const captured = ownLangGraphSnapshot(input, current); schedule(() => { diff --git a/libs/langgraph/src/runtime/session-lifecycle.spec.ts b/libs/langgraph/src/runtime/session-lifecycle.spec.ts index 28ba2fb3f..08045e632 100644 --- a/libs/langgraph/src/runtime/session-lifecycle.spec.ts +++ b/libs/langgraph/src/runtime/session-lifecycle.spec.ts @@ -77,6 +77,7 @@ describe('neutral session ownership', () => { state: undefined, interrupts: [], subgraphs: [], + subagents: [], }); expect(first).not.toHaveBeenCalled(); expect(a.stream).not.toHaveBeenCalled(); diff --git a/libs/langgraph/src/runtime/subagent-projection.ts b/libs/langgraph/src/runtime/subagent-projection.ts new file mode 100644 index 000000000..2eddefe70 --- /dev/null +++ b/libs/langgraph/src/runtime/subagent-projection.ts @@ -0,0 +1,86 @@ +import type { AgentStatus, AgentSubagent } from '@threadplane/core'; +import type { LangGraphSubgraph } from './langgraph-snapshot.js'; + +/** + * A child graph as a core child agent. `id` is the child's namespace path as + * JSON, which stays unique whatever a segment contains, and `name` is the node + * that started it. LangGraph does not + * relate a child graph to a tool call, so `toolCallId` and `description` are + * never set. + */ +export type LangGraphSubagent = AgentSubagent & { + /** The child graph's full namespace path, as in `subgraphs`. */ + readonly namespace: readonly string[]; +}; + +/** A namespace segment is `node:task`; a node name may itself hold no colon. */ +function nodeOf(segment: string): string { + const at = segment.indexOf(':'); + return at < 0 ? segment : segment.slice(0, at); +} + +/** + * - A child that failed is `error`. + * - While the root run is going, a child is `running`. + * - After it, the child's last message decides: a successful one is + * `complete`, and one a pause stopped is still `running`, because a resume + * continues it. Anything else, and a child with no messages, is `unknown`. + */ +function statusOf( + child: LangGraphSubgraph, + running: boolean +): AgentSubagent['status'] { + if (child.error) return 'error'; + if (running) return 'running'; + const last = child.messages.at(-1)?.delivery; + if (last?.phase !== 'complete') return 'unknown'; + if (last.outcome === 'success') return 'complete'; + return last.outcome === 'paused' ? 'running' : 'unknown'; +} + +const projected = new WeakMap< + LangGraphSubgraph, + Partial> +>(); +const none: readonly LangGraphSubagent[] = Object.freeze([]); + +/** + * The session's child graphs as core child agents, in the order they were + * first observed. A child keeps its reference while its child graph and status + * are unchanged, and the list keeps its own while every child does. + */ +export function projectSubagents( + subgraphs: readonly LangGraphSubgraph[], + status: AgentStatus, + previous: readonly LangGraphSubagent[] = none +): readonly LangGraphSubagent[] { + if (!subgraphs.length) return previous.length ? none : previous; + const running = status === 'running'; + let changed = previous.length !== subgraphs.length; + const children = subgraphs.map((child, index) => { + const state = statusOf(child, running); + let known = projected.get(child); + if (!known) projected.set(child, (known = {})); + let subagent = known[state]; + if (!subagent) { + const { namespace } = child; + const message = child.error?.message; + subagent = Object.freeze({ + id: JSON.stringify(namespace), + name: nodeOf(namespace[namespace.length - 1] ?? ''), + ...(namespace.length > 1 && { + parentId: JSON.stringify(namespace.slice(0, -1)), + }), + status: state, + messages: child.messages, + toolCalls: child.toolCalls, + ...(state === 'error' && message && { error: message }), + namespace, + }); + known[state] = subagent; + } + if (previous[index] !== subagent) changed = true; + return subagent; + }); + return changed ? Object.freeze(children) : previous; +} diff --git a/libs/langgraph/src/runtime/subgraph-projection.ts b/libs/langgraph/src/runtime/subgraph-projection.ts index 215b02ce8..2ac8a0fbd 100644 --- a/libs/langgraph/src/runtime/subgraph-projection.ts +++ b/libs/langgraph/src/runtime/subgraph-projection.ts @@ -95,7 +95,7 @@ function replace( previous: SubgraphObservation, namespace: readonly string[], child: ChildProjection, - entry: LangGraphSubgraph + entry: Omit ): SubgraphObservation { const key = JSON.stringify(namespace); const active = new Map(previous.active); @@ -104,7 +104,11 @@ function replace( (value) => JSON.stringify(value.namespace) === key ); const entries = [...previous.subgraphs]; - const projected = ownSubgraph(entry, previous.subgraphs[index]); + // The child's reducer state is the one source of its tool calls. + const projected = ownSubgraph( + { ...entry, toolCalls: child.state.toolCalls }, + previous.subgraphs[index] + ); if (index < 0) entries.push(projected); else entries[index] = projected; return { active, subgraphs: ownSubgraphs(entries, previous.subgraphs) }; diff --git a/libs/langgraph/src/runtime/subgraphs.spec.ts b/libs/langgraph/src/runtime/subgraphs.spec.ts index e8fab8c93..992fbddc7 100644 --- a/libs/langgraph/src/runtime/subgraphs.spec.ts +++ b/libs/langgraph/src/runtime/subgraphs.spec.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import type { ThreadState } from '@langchain/langgraph-sdk'; +import type { AgentSession } from '@threadplane/core'; import { createSession } from './create-session'; import type { AgentTransport, StreamEvent } from './transport.types'; import { controlledTransport } from './testing/controlled-transport'; @@ -76,6 +77,82 @@ afterEach(async () => { await Promise.all(cleanups.splice(0).map((cleanup) => cleanup())); }); +describe('child graphs as core child agents', () => { + it('publishes one child agent for each child graph, with its own transcript', async () => { + const f = fixture(); + expect(f.session.getSnapshot().subagents).toEqual([]); + const run = f.session.submit('Go'); + await f.started(); + await f.emit(child('Found it', ['research:1'])); + await f.emit(child('Nested', ['research:1', 'tools:2'])); + const running = f.session.getSnapshot(); + expect(running.subagents).toHaveLength(2); + const [research, nested] = running.subagents; + expect(research).toMatchObject({ + id: '["research:1"]', + name: 'research', + status: 'running', + namespace: ['research:1'], + toolCalls: [], + }); + expect('parentId' in research).toBe(false); + expect(nested).toMatchObject({ + id: '["research:1","tools:2"]', + name: 'tools', + parentId: research.id, + status: 'running', + }); + // The child agent and the child graph share one transcript. + expect(research.messages).toBe(running.subgraphs[0].messages); + expect(research.messages[0].content).toBe('Found it'); + // The root transcript does not repeat a child's messages. + expect(running.messages.map((message) => message.content)).toEqual(['Go']); + + // A change to one child leaves the other child agent's reference alone. + await f.emit(child(' again', ['research:1', 'tools:2'])); + const next = f.session.getSnapshot(); + expect(next.subagents[0]).toBe(research); + expect(next.subagents[1]).not.toBe(nested); + // A root-only event keeps the whole list. + await f.emit({ ...child('Root'), namespace: undefined }); + expect(f.session.getSnapshot().subagents).toBe(next.subagents); + + await f.emit(full('Root answer')); + f.streams[0].finish(); + expect(await run).toBe('success'); + const settled = f.session.getSnapshot(); + expect(settled.subagents.map((entry) => entry.status)).toEqual([ + 'complete', + 'complete', + ]); + // A core observer reads the same children. + const observer: AgentSession = f.session; + expect(observer.getSnapshot().subagents?.[0]?.id).toBe('["research:1"]'); + }); + + it('reports a failed child as error and an aborted one as unknown', async () => { + const f = fixture(); + const run = f.session.submit('Go'); + await f.started(); + await f.emit(child('Working', ['ok:1'])); + await f.emit(child('Working', ['bad:2'])); + await f.emit({ + type: 'error', + namespace: ['bad:2'], + data: { error: 'Boom', message: 'The search failed' }, + }); + const failed = f.session.getSnapshot().subagents[1]; + expect(failed.status).toBe('error'); + expect(typeof failed.error).toBe('string'); + expect(f.session.getSnapshot().subagents[0].status).toBe('running'); + await f.session.stop(); + expect(await run).toBe('aborted'); + expect( + f.session.getSnapshot().subagents.map((entry) => entry.status) + ).toEqual(['unknown', 'error']); + }); +}); + describe('private subgraph observations', () => { it('preserves custom root error wrapper fields when capturing event routing', async () => { const session = createSession({ @@ -196,6 +273,18 @@ describe('private subgraph observations', () => { recovery: 'none', }); expect(JSON.stringify(snapshot)).not.toContain('SECRET'); + // The child's call is the child's own: listed with it, not at the root. + expect(snapshot.subgraphs[0].toolCalls.map((call) => call.id)).toEqual([ + 'child-tool', + ]); + expect(snapshot.subagents[0].toolCalls).toBe( + snapshot.subgraphs[0].toolCalls + ); + expect(snapshot.subagents[0].messages[0].toolCallIds).toEqual([ + 'child-tool', + ]); + expect(snapshot.subagents[0]).toMatchObject({ status: 'error' }); + expect(snapshot.subagents[0].error).not.toContain('SECRET'); expect(snapshot.subgraphs[0].messages[0].delivery).toMatchObject({ outcome: 'error', }); diff --git a/libs/langgraph/src/runtime/subgraphs.type-test.ts b/libs/langgraph/src/runtime/subgraphs.type-test.ts index fd962061f..57b6f10e3 100644 --- a/libs/langgraph/src/runtime/subgraphs.type-test.ts +++ b/libs/langgraph/src/runtime/subgraphs.type-test.ts @@ -1,6 +1,13 @@ -import type { AgentSession, Message, PlainValue } from '@threadplane/core'; +import type { + AgentSession, + AgentSubagent, + Message, + PlainValue, + ToolCall, +} from '@threadplane/core'; import { createSession } from './create-session'; import type { LangGraphSubgraph } from './langgraph-snapshot'; +import type { LangGraphSubagent } from './subagent-projection'; const session = createSession({ assistantId: 'a', threadId: 't', @@ -20,6 +27,18 @@ const snapshot = session.getSnapshot(); const children: readonly LangGraphSubgraph[] = snapshot.subgraphs; const messages: readonly Message[] = children[0].messages; const payload: PlainValue = children[0].state?.['any']; +// Child graphs are also published as the core contract's child agents. +const agents: readonly LangGraphSubagent[] = snapshot.subagents; +const coreAgents: readonly AgentSubagent[] | undefined = + observer.getSnapshot().subagents; +const agentCalls: readonly ToolCall[] = agents[0].toolCalls; +const childCalls: readonly ToolCall[] = children[0].toolCalls; +const path: readonly string[] = agents[0].namespace; +// @ts-expect-error The child agents are derived, not assigned. +snapshot.subagents = []; +// @ts-expect-error A child agent exposes no commands. +agents[0].resume([]); +void [coreAgents, agentCalls, childCalls, path]; // @ts-expect-error Observation collection is readonly. snapshot.subgraphs = []; // @ts-expect-error Observation arrays are readonly. diff --git a/libs/react/src/chat/chat-fake-session.spec.tsx b/libs/react/src/chat/chat-fake-session.spec.tsx index 05e22763d..806164545 100644 --- a/libs/react/src/chat/chat-fake-session.spec.tsx +++ b/libs/react/src/chat/chat-fake-session.spec.tsx @@ -10,8 +10,9 @@ import { createFakeAgentSession, type FakeAssistantStream, } from '@threadplane/core/testing'; +import type { AgentSession, CompleteOutcome } from '@threadplane/core'; import { useAgent } from '../use-agent'; -import { Chat } from './index'; +import { Chat, type RenderInterrupt } from './index'; afterEach(cleanup); @@ -73,3 +74,231 @@ it('drives useAgent through the fake session controls', () => { expect(result.current.status).toBe('error'); expect(result.current.error?.message).toBe('Down'); }); + +it('shows the child agents the session reports, with no subagents prop', () => { + const fake = createFakeAgentSession(); + const view = render(); + act(() => { + fake.set({ + messages: [ + { role: 'user', content: 'Research it' }, + { role: 'assistant', content: 'Delegating', toolCallIds: ['task-1'] }, + { role: 'assistant', content: 'Here is the summary' }, + ], + toolCalls: [ + { id: 'task-1', name: 'task', args: {}, status: 'complete', result: 1 }, + ], + subagents: [ + { + // Related to the root call that started it: the card takes its place. + id: 'anchored', + name: 'researcher', + toolCallId: 'task-1', + messages: [ + { + role: 'assistant', + content: 'Found two sources', + toolCallIds: ['search-1'], + }, + ], + toolCalls: [ + { + id: 'search-1', + name: 'search', + args: { q: 'sources' }, + status: 'complete', + result: 'ok', + }, + ], + }, + // Related to no call, as a LangGraph child graph is. + { id: 'loose', name: 'writer', status: 'error', error: 'It failed' }, + ], + }); + }); + const cards = [ + ...view.container.querySelectorAll('[data-subagent-id]'), + ]; + expect(cards.map((card) => card.dataset['subagentId'])).toEqual([ + 'anchored', + 'loose', + ]); + expect(cards[0].textContent).toContain('researcher'); + expect(cards[0].textContent).toContain('Found two sources'); + expect(cards[1].textContent).toContain('writer'); + expect(cards[1].textContent).toContain('It failed'); + // Both belong to the turn's first assistant message, not the last one. + const first = view.getByText('Delegating').closest('.tp-chat-message'); + expect(first?.contains(cards[0])).toBe(true); + expect(first?.contains(cards[1])).toBe(true); + // The delegating call is the card, not also a tool row. + expect(view.queryByText('task')).toBeNull(); +}); + +it('lets the subagents prop replace the session child agents', () => { + const fake = createFakeAgentSession({ + subagents: [{ id: 'reported', name: 'reported-child' }], + messages: [ + { role: 'user', content: 'Go' }, + { role: 'assistant', content: 'Done', toolCallIds: ['task-1'] }, + ], + toolCalls: [ + { id: 'task-1', name: 'task', args: {}, status: 'complete', result: 1 }, + ], + }); + const none = render(); + expect(none.container.querySelector('[data-subagent-id]')).toBeNull(); + none.unmount(); + const own = render( + + ); + expect( + [...own.container.querySelectorAll('[data-subagent-id]')].map( + (card) => card.dataset['subagentId'] + ) + ).toEqual(['mine']); +}); + +const card: RenderInterrupt = (interrupt, respond) => ( +
+

{interrupt.message}

+ + +
+); + +it('shows nothing for a pending interrupt unless renderInterrupt is set', () => { + const fake = createFakeAgentSession({ + interrupts: [{ id: 'i1', message: 'Refund $20?' }], + }); + const view = render(); + expect(view.queryByText('Refund $20?')).toBeNull(); + expect( + view.getByRole('textbox', { name: 'Message' }).getAttribute('placeholder') + ).not.toBe('Answer the approval to continue'); +}); + +it('answers one interrupt through session.resume from renderInterrupt', async () => { + const fake = createFakeAgentSession({ + interrupts: [{ id: 'i1', message: 'Refund $20?' }], + }); + const view = render(); + expect(view.getByText('Refund $20?')).toBeTruthy(); + // The composer waits on the answer, as it does for the approval slot. + expect( + view.getByRole('textbox', { name: 'Message' }).getAttribute('placeholder') + ).toBe('Answer the approval to continue'); + await act(async () => { + fireEvent.click(view.getByRole('button', { name: 'Approve i1' })); + }); + expect(fake.resumes.map((call) => call.responses)).toEqual([ + [{ interruptId: 'i1', status: 'resolved', value: { approved: true } }], + ]); + // The fake removes an answered interrupt; the card goes with it. + expect(view.queryByText('Refund $20?')).toBeNull(); +}); + +it('holds answers until every pending interrupt has one, then sends them together', async () => { + const fake = createFakeAgentSession({ + interrupts: [ + { id: 'i1', message: 'First?' }, + { id: 'i2', message: 'Second?' }, + ], + }); + const view = render(); + await act(async () => { + fireEvent.click(view.getByRole('button', { name: 'Cancel i2' })); + }); + expect(fake.resumes).toHaveLength(0); + expect( + view.container + .querySelector('[data-interrupt="i2"]') + ?.getAttribute('data-answered') + ).toBe('true'); + await act(async () => { + fireEvent.click(view.getByRole('button', { name: 'Approve i1' })); + }); + // One resume, in the order the session lists the interrupts. + expect(fake.resumes.map((call) => call.responses)).toEqual([ + [ + { interruptId: 'i1', status: 'resolved', value: { approved: true } }, + { interruptId: 'i2', status: 'cancelled' }, + ], + ]); +}); + +it('lets the interrupts be answered again after resume rejects', async () => { + let fail = true; + const fake = createFakeAgentSession({ + interrupts: [{ id: 'i1', message: 'Refund $20?' }], + }); + // A session that refuses the first answer and leaves the interrupt pending. + const session: AgentSession = { + ...fake.session, + resume: (responses, options) => + fail + ? Promise.reject(new TypeError('Not accepted')) + : (fake.session.resume?.( + responses, + options + ) as Promise), + }; + const errors: unknown[] = []; + const view = render( + errors.push(error)} + /> + ); + await act(async () => { + fireEvent.click(view.getByRole('button', { name: 'Approve i1' })); + }); + expect(errors).toHaveLength(1); + expect(errors[0]).toBeInstanceOf(TypeError); + expect(fake.resumes).toHaveLength(0); + // Still pending, and its control is usable again. + const again = view.getByRole('button', { name: 'Approve i1' }); + expect((again as HTMLButtonElement).disabled).toBe(false); + fail = false; + await act(async () => { + fireEvent.click(again); + }); + expect(errors).toHaveLength(1); + expect(fake.resumes).toHaveLength(1); + expect(view.queryByText('Refund $20?')).toBeNull(); +}); + +it('leaves the approval slot to the app when approval is set', () => { + const fake = createFakeAgentSession({ + interrupts: [{ id: 'i1', message: 'Refund $20?' }], + }); + const view = render( + App approval

} + /> + ); + expect(view.getByText('App approval')).toBeTruthy(); + expect(view.queryByText('Refund $20?')).toBeNull(); +}); diff --git a/libs/react/src/chat/chat.tsx b/libs/react/src/chat/chat.tsx index fd992db17..0ccb2968c 100644 --- a/libs/react/src/chat/chat.tsx +++ b/libs/react/src/chat/chat.tsx @@ -33,6 +33,11 @@ import { type MessageListProps, } from './message-list.js'; import { ScrollBubble } from './scroll-bubble.js'; +import { + useSessionInterrupts, + type RenderInterrupt, +} from './session-interrupts.js'; +import { sessionSubagents } from './session-subagents.js'; import { Select, type SelectOption } from './select.js'; import { ThreadList, type ThreadListItem } from './thread-list.js'; @@ -71,7 +76,11 @@ export interface ChatProps * the composer when none is. The app passes `clientTools.tools` to the session; Chat never runs a tool. Off unless set. */ readonly clientTools?: ChatClientTools; - /** Child agents shown as subagent cards in place of the tool calls that started them. Keep stable. */ + /** + * Child agents shown as subagent cards in place of the tool calls that started them. Keep stable. + * Left unset, Chat shows the child agents the session reports in `snapshot.subagents`. Pass a list, + * which may be empty, to show that instead. + */ readonly subagents?: MessageListProps['subagents']; /** Application-owned handler for a retry declared by `toolOutcome`; Chat never re-runs a call. Keep stable. */ readonly onToolRetry?: MessageListProps['onToolRetry']; @@ -104,6 +113,20 @@ export interface ChatProps * composer. The app decides when it is pending and what answering does. */ readonly approval?: ReactNode; + /** + * Draws each interrupt the session reports in `snapshot.interrupts`, in the place `approval` + * takes. Chat shows nothing for an interrupt by itself: return the card, and call + * `respond.resolve(value)` or `respond.cancel()` from it. Chat holds each answer until every + * pending interrupt has one, then sends them together with `session.resume`. Which value answers + * an interrupt is the backend's contract, so it stays with the app. Ignored while `approval` is + * set, and on a session with no `resume`. Off unless set. + */ + readonly renderInterrupt?: RenderInterrupt; + /** + * Called when `session.resume` rejects an answer sent from `renderInterrupt`; the interrupts can + * then be answered again. Left unset, the failure is reported as an unhandled error. + */ + readonly onInterruptError?: (error: unknown) => void; /** Answered approvals as one-line records in the transcript; see `MessageListProps.approvalRecords`. */ readonly approvalRecords?: MessageListProps['approvalRecords']; /** Built-in Copy and rating under finished assistant messages; see `MessageListProps.messageActions`. Keep stable. */ @@ -247,7 +270,9 @@ export function Chat({ inputTrailing, inputFooter, modelPicker, - approval, + approval: ownApproval, + renderInterrupt, + onInterruptError, approvalRecords, messageActions, math, @@ -281,7 +306,8 @@ export function Chat({ // handles it itself. Built-in actions stay off until `messageActions` is set. const actions = useMemo(() => { if (!messageActions || !session.regenerate) return messageActions; - if (messageActions !== true && messageActions.onRegenerate) return messageActions; + if (messageActions !== true && messageActions.onRegenerate) + return messageActions; return { ...(messageActions === true ? {} : messageActions), onRegenerate: (messageId: string) => { @@ -316,6 +342,14 @@ export function Chat({ // composer. An app that disables the composer while the answered run goes on // gets focus there as soon as it is enabled again. const composer = useRef(null); + // The session's own pending interrupts, unless the app supplies the approval. + const asks = useSessionInterrupts( + session, + snapshot.interrupts, + ownApproval === undefined ? renderInterrupt : undefined, + onInterruptError + ); + const approval = ownApproval === undefined ? asks : ownApproval; const pending = approval !== undefined && approval !== null && approval !== false; const disabled = input.disabled ?? false; @@ -415,6 +449,15 @@ export function Chat({ suggestionFocus.current = false; composer.current?.focus(); }, [greeted]); + // The session's own child agents, unless the app supplies the cards. + const children = subagents === undefined ? snapshot.subagents : undefined; + const reported = useMemo( + () => + children?.length + ? sessionSubagents(children, { toolLabel, toolOutcome }) + : undefined, + [children, toolLabel, toolOutcome] + ); // The run's messages keep their identity while only later snapshots change. const messages = snapshot.messages; const runMessages = useMemo(() => { @@ -458,7 +501,9 @@ export function Chat({ renderToolCall={renderToolCall} renderToolCallPrompt={renderPrompt} renderToolResult={renderToolResult} - subagents={subagents} + subagents={subagents ?? reported} + // A session child may name no tool call, as a LangGraph child graph does not. + placeUnanchoredSubagents={subagents === undefined} onToolRetry={onToolRetry} plan={snapshot.plan} onStop={snapshot.status === 'running' ? stop : undefined} @@ -485,7 +530,11 @@ export function Chat({ } > {runActivity === null ? null : ( -
+
{runActivity}
)} diff --git a/libs/react/src/chat/index.ts b/libs/react/src/chat/index.ts index 7869e31f6..afc292122 100644 --- a/libs/react/src/chat/index.ts +++ b/libs/react/src/chat/index.ts @@ -58,6 +58,14 @@ export { type SubagentEvidenceRecord, type SubagentProjection, } from './subagent-evidence.js'; +export type { + InterruptResponder, + RenderInterrupt, +} from './session-interrupts.js'; +export { + sessionSubagents, + type SessionSubagentOptions, +} from './session-subagents.js'; export { Suggestions, type SuggestionItem, diff --git a/libs/react/src/chat/message-list.tsx b/libs/react/src/chat/message-list.tsx index be566778f..182abbaaf 100644 --- a/libs/react/src/chat/message-list.tsx +++ b/libs/react/src/chat/message-list.tsx @@ -160,6 +160,11 @@ export interface MessageListProps { * stable between updates; custom renderMessage retains full ownership. */ readonly subagents?: readonly SubagentInfo[]; + /** + * Also places a child that names no tool call: its card follows the tool calls of the first + * assistant message of the latest turn. Off unless set, so such children stay with the application. + */ + readonly placeUnanchoredSubagents?: boolean; /** * Answered approvals, each rendered as a one-line `ApprovalRecord` after the row its `afterId` * names, or after the last row when that row is absent. Records stay where the app put them while @@ -320,15 +325,33 @@ function toolRowsShownElsewhere( } const NO_CITATIONS: readonly never[] = []; const NO_SUBAGENTS: readonly SubagentInfo[] = Object.freeze([]); -/** Each row's children by spawning call. Rows without one share a constant so their memo stays stable. */ +/** + * Each row's children by spawning call. With `unanchored`, a child that names + * no call belongs to the first assistant message of the latest turn, so its + * card keeps its place as the turn goes on. Rows without one share a constant + * so their memo stays stable. + */ function subagentsByRow( rows: readonly MessageRow[], - subagents: readonly SubagentInfo[] + subagents: readonly SubagentInfo[], + unanchored: boolean ): readonly (readonly SubagentInfo[])[] { - return rows.map((row) => { - const own = subagents.filter((subagent) => - row.toolCalls.some((call) => call.id === subagent.toolCallId) + const loose = unanchored + ? subagents.filter((subagent) => subagent.toolCallId === undefined) + : []; + let home = -1; + if (loose.length) + for (let index = rows.length - 1; index >= 0; index--) { + if (rows[index].role === 'user') break; + if (rows[index].role === 'assistant') home = index; + } + return rows.map((row, index) => { + const own = subagents.filter( + (subagent) => + subagent.toolCallId !== undefined && + row.toolCalls.some((call) => call.id === subagent.toolCallId) ); + if (index === home) own.push(...loose); return own.length ? own : NO_SUBAGENTS; }); } @@ -558,6 +581,9 @@ function RowView({ if (last && 'activities' in last) last.activities.push(activity); else runs.push({ activities: [activity] }); }); + // A child that names no call follows the message's own calls. + for (const child of subagents) + if (child.toolCallId === undefined) runs.push({ child }); // The plan and Stop belong to the row's last built-in group, the one the turn is still running. const planGroup = [...runs].reverse().find((run) => 'activities' in run); const actionLabel = @@ -722,6 +748,7 @@ export function MessageList({ onStop, running = false, subagents, + placeUnanchoredSubagents = false, approvalRecords, typingIndicator = true, messageActions, @@ -754,8 +781,11 @@ export function MessageList({ [onToolRetry, rows] ); const rowSubagents = useMemo( - () => (subagents?.length ? subagentsByRow(rows, subagents) : undefined), - [rows, subagents] + () => + subagents?.length + ? subagentsByRow(rows, subagents, placeUnanchoredSubagents) + : undefined, + [rows, subagents, placeUnanchoredSubagents] ); const retrying = useMemo( () => (toolOutcome ? retryingByRow(rows) : undefined), diff --git a/libs/react/src/chat/session-interrupts.tsx b/libs/react/src/chat/session-interrupts.tsx new file mode 100644 index 000000000..cd3a37de5 --- /dev/null +++ b/libs/react/src/chat/session-interrupts.tsx @@ -0,0 +1,114 @@ +import { Fragment, useCallback, useRef, useState, type ReactNode } from 'react'; +import type { + AgentInterrupt, + AgentInterruptResponse, + AgentSession, + PlainValue, +} from '@threadplane/core'; + +/** Answers one pending interrupt from the view `renderInterrupt` returns. */ +export interface InterruptResponder { + /** Resolves this interrupt, with the value the backend expects for it. */ + resolve(value?: PlainValue): void; + /** Cancels this interrupt, where the backend supports cancelling. */ + cancel(): void; + /** True once this interrupt has an answer that waits on the other pending ones. */ + readonly answered: boolean; + /** True while the answers are being sent; disable the controls. */ + readonly sending: boolean; +} + +/** Draws one pending interrupt. Return `null` to show nothing for it. */ +export type RenderInterrupt = ( + interrupt: AgentInterrupt, + respond: InterruptResponder +) => ReactNode; + +interface Collected { + /** The pause these answers belong to: the snapshot's `interrupts` list. */ + readonly pause: readonly AgentInterrupt[]; + readonly answers: ReadonlyMap; + readonly sending: boolean; +} + +function report(error: unknown, onError?: (error: unknown) => void): void { + if (onError) onError(error); + // An unhandled failure must not be silent. + else + (globalThis as { reportError?: (error: unknown) => void }).reportError?.( + error + ); +} + +/** + * The views for a session's pending interrupts, or undefined when there is + * nothing to show. Each answer is held until every pending interrupt has one; + * they are then sent together with one `session.resume`, because a paused run + * continues once. A new pause starts with no answers. If `resume` rejects, the + * answers are dropped so the person can answer again, and the failure goes to + * `onError`. + */ +export function useSessionInterrupts( + session: AgentSession, + interrupts: readonly AgentInterrupt[] | undefined, + render: RenderInterrupt | undefined, + onError?: (error: unknown) => void +): ReactNode | undefined { + const [collected, setCollected] = useState(); + const current = + collected && collected.pause === interrupts ? collected : undefined; + // The latest values for callbacks a view may keep past this render. + const live = useRef({ session, interrupts, current, onError }); + live.current = { session, interrupts, current, onError }; + + const answer = useCallback((response: AgentInterruptResponse) => { + const { session, interrupts, current, onError } = live.current; + if (!interrupts?.length || current?.sending) return; + if (!interrupts.some((entry) => entry.id === response.interruptId)) return; + const answers = new Map(current?.answers); + answers.set(response.interruptId, response); + const complete = interrupts.every((entry) => answers.has(entry.id)); + const next = { pause: interrupts, answers, sending: complete }; + live.current = { ...live.current, current: next }; + setCollected(next); + if (!complete) return; + const responses = interrupts.map( + (entry) => answers.get(entry.id) as AgentInterruptResponse + ); + const failed = (error: unknown) => { + // Answerable again, unless a newer pause has already replaced this one. + setCollected((latest) => (latest === next ? undefined : latest)); + report(error, onError); + }; + try { + const run = session.resume?.(responses); + if (!run) throw new TypeError('This session cannot resume.'); + run.then( + () => setCollected((latest) => (latest === next ? undefined : latest)), + failed + ); + } catch (error) { + failed(error); + } + }, []); + + if (!render || !interrupts?.length || !session.resume) return undefined; + const sending = current?.sending ?? false; + const views = interrupts.map((interrupt) => { + const view = render(interrupt, { + resolve: (value) => + answer({ + interruptId: interrupt.id, + status: 'resolved', + ...(value !== undefined && { value }), + }), + cancel: () => answer({ interruptId: interrupt.id, status: 'cancelled' }), + answered: current?.answers.has(interrupt.id) ?? false, + sending, + }); + return view == null || view === false ? null : ( + {view} + ); + }); + return views.some((view) => view !== null) ? <>{views} : undefined; +} diff --git a/libs/react/src/chat/session-subagents.spec.ts b/libs/react/src/chat/session-subagents.spec.ts new file mode 100644 index 000000000..a0d136c3f --- /dev/null +++ b/libs/react/src/chat/session-subagents.spec.ts @@ -0,0 +1,125 @@ +import { completeDelivery, type AgentSubagent } from '@threadplane/core'; +import { describe, expect, it, vi } from 'vitest'; +import { sessionSubagents } from './session-subagents'; + +const child = (over: Partial = {}): AgentSubagent => ({ + id: 'c', + name: 'researcher', + description: 'Find sources', + toolCallId: 'task-1', + status: 'complete', + messages: [ + { + id: 'u', + role: 'user', + content: 'Find sources', + delivery: completeDelivery('g', 'success'), + }, + { + id: 'a', + role: 'assistant', + content: 'Found two', + reasoning: 'Looking', + toolCallIds: ['search-1', 'missing'], + delivery: completeDelivery('g', 'success'), + }, + { + id: 'empty', + role: 'assistant', + content: '', + delivery: completeDelivery('g', 'success'), + }, + ], + toolCalls: [ + { + id: 'search-1', + name: 'search', + args: { q: 'sources' }, + status: 'complete', + result: { hits: 2 }, + }, + ], + ...over, +}); + +describe('sessionSubagents', () => { + it('builds card data from a core child agent', () => { + const [card] = sessionSubagents([child()], { + toolLabel: (name) => (name === 'search' ? 'Searching' : undefined), + }); + expect(card).toMatchObject({ + id: 'c', + name: 'researcher', + description: 'Find sources', + toolCallId: 'task-1', + status: 'complete', + }); + // Only the child's own answers are shown; an empty one adds nothing. + expect(card.messages).toHaveLength(1); + expect(card.messages[0]).toMatchObject({ + id: 'a', + text: 'Found two', + reasoning: 'Looking', + }); + // A call the child does not list is skipped, not invented. + expect(card.messages[0].activities).toEqual([ + expect.objectContaining({ + id: 'search-1', + name: 'search', + label: 'Searching', + phase: 'complete', + resultText: JSON.stringify({ hits: 2 }, null, 2), + }), + ]); + }); + + it('carries a failure as the card summary and omits absent fields', () => { + const [card] = sessionSubagents([ + { + id: 'x', + status: 'error', + error: 'It failed', + messages: [], + toolCalls: [], + }, + ]); + expect(card).toEqual({ + id: 'x', + status: 'error', + messages: [], + errorSummary: 'It failed', + }); + }); + + it('keeps references while a child and the callbacks are unchanged', () => { + const first = child(); + const second = child({ id: 'd' }); + const toolLabel = vi.fn(() => undefined); + const children = [first, second]; + const cards = sessionSubagents(children, { toolLabel }); + expect(sessionSubagents(children, { toolLabel })).toBe(cards); + // A new list with one changed child keeps the other child's card. + const next = sessionSubagents( + [first, child({ id: 'd', status: 'error' })], + { + toolLabel, + } + ); + expect(next).not.toBe(cards); + expect(next[0]).toBe(cards[0]); + expect(next[1]).not.toBe(cards[1]); + // A different callback rebuilds, so a stale label is never shown. + expect( + sessionSubagents(children, { toolLabel: () => 'Other' })[0] + ).not.toBe(cards[0]); + }); + + it('contains a throwing outcome callback', () => { + const [card] = sessionSubagents([child()], { + toolOutcome: () => { + throw new Error('app bug'); + }, + }); + expect(card.messages[0].activities?.[0].phase).toBe('complete'); + }); +}); diff --git a/libs/react/src/chat/session-subagents.ts b/libs/react/src/chat/session-subagents.ts new file mode 100644 index 000000000..164a0dd46 --- /dev/null +++ b/libs/react/src/chat/session-subagents.ts @@ -0,0 +1,114 @@ +import type { AgentSubagent, ToolCall } from '@threadplane/core'; +import type { SubagentInfo, SubagentMessageInfo } from './subagent-card.js'; +import { toolActivityPhase, type ToolActivityInfo } from './tool-activity.js'; +import { + resolveToolOutcome, + type ToolActivityOutcome, +} from './tool-outcome.js'; + +/** App-authored presentation for the children's own tool calls. */ +export interface SessionSubagentOptions { + readonly toolLabel?: (name: string, args?: unknown) => string | undefined; + readonly toolOutcome?: ( + activity: ToolActivityInfo + ) => ToolActivityOutcome | undefined; +} + +/** Argument and result text, as `MessageList` shows it for root calls. */ +const literal = (value: unknown): string => + typeof value === 'string' ? value : JSON.stringify(value, null, 2) ?? ''; + +function card( + child: AgentSubagent, + { toolLabel, toolOutcome }: SessionSubagentOptions +): SubagentInfo { + const calls = new Map( + child.toolCalls.map((call) => [call.id, call]) + ); + const running = child.status === 'running'; + const messages: SubagentMessageInfo[] = []; + for (const message of child.messages) { + if (message.role !== 'assistant') continue; + const activities: ToolActivityInfo[] = []; + for (const id of message.toolCallIds ?? []) { + const call = calls.get(id); + if (!call) continue; + const activity: ToolActivityInfo = { + id: call.id, + name: call.name, + label: toolLabel?.(call.name, call.args), + phase: toolActivityPhase(call.status, message.delivery, running), + argumentsText: literal(call.args), + resultText: + call.status === 'complete' ? literal(call.result) : undefined, + errorText: call.status === 'error' ? call.error : undefined, + }; + let outcome: ToolActivityOutcome | undefined; + try { + outcome = toolOutcome?.(activity); + } catch { + // A throwing app hook must not break the card; the call keeps its phase. + } + activities.push( + outcome ? resolveToolOutcome(activity, outcome) : activity + ); + } + const text = message.content || undefined; + const reasoning = message.reasoning || undefined; + if (!text && !reasoning && !activities.length) continue; + messages.push({ + id: message.id, + ...(text && { text }), + ...(reasoning && { reasoning }), + ...(activities.length && { activities }), + }); + } + return { + id: child.id, + ...(child.toolCallId !== undefined && { toolCallId: child.toolCallId }), + ...(child.name !== undefined && { name: child.name }), + ...(child.description !== undefined && { + description: child.description, + }), + status: child.status, + messages, + ...(child.error !== undefined && { errorSummary: child.error }), + }; +} + +interface Known { + readonly options: SessionSubagentOptions; + readonly info: SubagentInfo; +} +const cards = new WeakMap(); +const lists = new WeakMap< + readonly AgentSubagent[], + { + readonly options: SessionSubagentOptions; + readonly list: readonly SubagentInfo[]; + } +>(); +const same = (a: SessionSubagentOptions, b: SessionSubagentOptions) => + a.toolLabel === b.toolLabel && a.toolOutcome === b.toolOutcome; + +/** + * Card data for the child agents a session reports in `snapshot.subagents`. + * A child whose reference is unchanged keeps its card's reference, and an + * unchanged list keeps its own, while the two callbacks stay the same. + */ +export function sessionSubagents( + children: readonly AgentSubagent[], + options: SessionSubagentOptions = {} +): readonly SubagentInfo[] { + const known = lists.get(children); + if (known && same(known.options, options)) return known.list; + const list = children.map((child) => { + const before = cards.get(child); + if (before && same(before.options, options)) return before.info; + const info = card(child, options); + cards.set(child, { options, info }); + return info; + }); + lists.set(children, { options, list }); + return list; +} diff --git a/libs/react/src/use-agent.ag-ui.spec.tsx b/libs/react/src/use-agent.ag-ui.spec.tsx index 660f10e0c..69591dc4e 100644 --- a/libs/react/src/use-agent.ag-ui.spec.tsx +++ b/libs/react/src/use-agent.ag-ui.spec.tsx @@ -120,7 +120,8 @@ describe('useAgent native AG-UI owner', () => { { id: 'child', name: 'worker', - status: 'complete', + // The child finished suspended: it paused and can continue. + status: 'running', messages: [], toolCalls: [], started: { diff --git a/scripts/react-parity/dispositions.json b/scripts/react-parity/dispositions.json index ed2e0e46a..ce3b65da3 100644 --- a/scripts/react-parity/dispositions.json +++ b/scripts/react-parity/dispositions.json @@ -12767,6 +12767,17 @@ "reason": "Private staged LangGraph runtime subset; fixture-only and not a neutral public LangGraph root or tarball.", "note": "Resume projection preserves unchanged baseline delivery, attributes current same-ID activity, and limits finalized tool eligibility to the resumed turn across stream batches and follow-ups. Live pause delivery still uses the shared root interrupt batch. Broader T09 migration remains open." }, + { + "id": "source:libs/langgraph/src/runtime/subagent-projection.ts", + "taskIds": [ + "T09", + "T10" + ], + "treatment": "internal", + "status": "in-progress", + "reason": "Private projection of the session's child graphs into the core contract's child agents: an id, the starting node's name, a status and the child's own messages and tool calls.", + "note": "Covered by runtime specs. LangGraph does not relate a child graph to a tool call, so toolCallId and description are never set." + }, { "id": "source:libs/langgraph/src/runtime/subgraph-projection.ts", "taskIds": [ @@ -19097,6 +19108,66 @@ "target": "libs/react/src/chat/subagent-card.tsx", "reason": "Readonly child-agent presentation matching the Angular subagent card: name, status, message count, and the child's messages and tool activity behind one closed disclosure. MessageList places a card in the tool call that started the child. Status and messages are borrowed; execution, sessions and restored child history remain application-owned. This does not certify whole-framework parity." }, + { + "id": "export:libs/react/src/chat/index.ts#InterruptResponder", + "taskIds": [ + "T28" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/session-interrupts.tsx", + "reason": "React-only opt-in view of the interrupts a core session reports. Chat draws nothing by itself: the application returns each card from renderInterrupt, and Chat holds the answers until every pending interrupt has one, then sends them with one session.resume. No built-in card and no answer values." + }, + { + "id": "export:libs/react/src/chat/index.ts#RenderInterrupt", + "taskIds": [ + "T28" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/session-interrupts.tsx", + "reason": "React-only opt-in view of the interrupts a core session reports. Chat draws nothing by itself: the application returns each card from renderInterrupt, and Chat holds the answers until every pending interrupt has one, then sends them with one session.resume. No built-in card and no answer values." + }, + { + "id": "source:libs/react/src/chat/session-interrupts.tsx", + "taskIds": [ + "T28" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/session-interrupts.tsx", + "reason": "React-only opt-in view of the interrupts a core session reports. Chat draws nothing by itself: the application returns each card from renderInterrupt, and Chat holds the answers until every pending interrupt has one, then sends them with one session.resume. No built-in card and no answer values." + }, + { + "id": "export:libs/react/src/chat/index.ts#sessionSubagents", + "taskIds": [ + "T28" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/session-subagents.ts", + "reason": "React-only projection from the child agents a core session reports into subagent card data. Chat applies it by default when no subagents prop is given; a child keeps its card's reference while it is unchanged. No session ownership." + }, + { + "id": "export:libs/react/src/chat/index.ts#SessionSubagentOptions", + "taskIds": [ + "T28" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/session-subagents.ts", + "reason": "React-only projection from the child agents a core session reports into subagent card data. Chat applies it by default when no subagents prop is given; a child keeps its card's reference while it is unchanged. No session ownership." + }, + { + "id": "source:libs/react/src/chat/session-subagents.ts", + "taskIds": [ + "T28" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/session-subagents.ts", + "reason": "React-only projection from the child agents a core session reports into subagent card data. Chat applies it by default when no subagents prop is given; a child keeps its card's reference while it is unchanged. No session ownership." + }, { "id": "export:libs/react/src/chat/index.ts#subagentsFromEvidence", "taskIds": [ @@ -19227,7 +19298,7 @@ "treatment": "internal", "status": "in-progress", "reason": "Private core AgentSession view of the native owner: a snapshot derived from the native one with the message and tool-call selectors, change-only notification, a display error for a failed run, and text submit, stop and dispose forwarded to the owner.", - "note": "Covered by runtime specs and a React Chat integration spec over the real owner. Exported from the test-only candidate package entry and checked from installed tarballs; not exported from the published package root. A rejected credential (401 or 403) is an auth error and another HTTP status is carried on a server error. State patches, native resume, client-tool evidence, a status check and a failure without a response are not represented." + "note": "Covered by runtime specs and a React Chat integration spec over the real owner. Exported from the test-only candidate package entry and checked from installed tarballs; not exported from the published package root. A rejected credential (401 or 403) is an auth error and another HTTP status is carried on a server error. Client-tool evidence, a status check and a failure without a response are not represented in the core fields." }, { "id": "source:libs/ag-ui/src/runtime/child-projection.ts", @@ -19239,7 +19310,7 @@ "treatment": "internal", "status": "in-progress", "reason": "Private projection of the current run's child evidence into the core contract's child agents: each child's id, name, task, status and its own messages and tool calls, with the protocol evidence kept alongside.", - "note": "Covered by runtime specs over the real owner. Children of earlier runs stay bare evidence in earlierSubagents, and a child that reuses a run id also lists the earlier child's records." + "note": "Covered by runtime specs over the real owner. Children of earlier runs are listed first and marked earlier. A child that restarts after pausing continues with its records; any other reuse of a run id starts a separate child." }, { "id": "source:libs/ag-ui/src/runtime/message-projection.ts", diff --git a/scripts/react-parity/runtime-consumer.mjs b/scripts/react-parity/runtime-consumer.mjs index a8b4f238a..893b09b69 100644 --- a/scripts/react-parity/runtime-consumer.mjs +++ b/scripts/react-parity/runtime-consumer.mjs @@ -308,8 +308,11 @@ export function assertTextTranscript(messages: readonly Message[]) { child.messages[0].content = 'changed'; // @ts-expect-error Child streams have no execution commands. child.submit('Run'); - // @ts-expect-error Child streams have no executable tool list. - void child.toolCalls; + // A child's tool calls are observations of the child graph; nothing here runs them. + // @ts-expect-error Child tool calls are immutable. + child.toolCalls.push(child.toolCalls[0]); + // @ts-expect-error Child streams have no tool execution command. + child.addToolResult('id', 'result'); if (child.state) { // @ts-expect-error Child values are readonly plain data. child.state['stage'] = 'changed'; diff --git a/scripts/react-parity/verify-langgraph-candidate.mjs b/scripts/react-parity/verify-langgraph-candidate.mjs index 3b2586a6e..941653a7b 100644 --- a/scripts/react-parity/verify-langgraph-candidate.mjs +++ b/scripts/react-parity/verify-langgraph-candidate.mjs @@ -391,7 +391,7 @@ export async function verifyLangGraphCandidate({ const emission = emitCandidate(root, candidate); assert.equal( emission.sources.length, - 35, + 36, 'Complete reviewed backend graph' ); const packed = packCandidate(candidate, temporary); diff --git a/scripts/react-parity/verify-packages.mjs b/scripts/react-parity/verify-packages.mjs index e4ceb5e37..2580b59e8 100644 --- a/scripts/react-parity/verify-packages.mjs +++ b/scripts/react-parity/verify-packages.mjs @@ -518,6 +518,7 @@ const SUPPORTED_EXPORTS = { 'ToolObservation', 'SubagentCard', 'subagentsFromEvidence', + 'sessionSubagents', 'Welcome', 'WelcomeSuggestion', 'Suggestions', diff --git a/scripts/react-parity/verify-packages.spec.mjs b/scripts/react-parity/verify-packages.spec.mjs index 29d28c5a1..f1f5efb55 100644 --- a/scripts/react-parity/verify-packages.spec.mjs +++ b/scripts/react-parity/verify-packages.spec.mjs @@ -1062,6 +1062,7 @@ test('React chat requires its real supported export', () => { supported.citationsWithToolSources = component; supported.SubagentCard = component; supported.subagentsFromEvidence = component; + supported.sessionSubagents = component; supported.StatusPanel = component; supported.ChatError = component; supported.TypingIndicator = component;