Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🔖 fix: Split Activity Phases at Substantial Text (#14785)
Danny Avila05ed7ad8c0c4
diff --git a/client/src/utils/__tests__/activityLabels.spec.ts b/client/src/utils/__tests__/activityLabels.spec.tsindex 50fb24b20d..b7f21102ad 100644--- a/client/src/utils/__tests__/activityLabels.spec.ts+++ b/client/src/utils/__tests__/activityLabels.spec.ts@@ -234,6 +234,142 @@ describe('groupActivityPhases', () => {expect(lastVisibleContentIdx([tool, tool, final, phase as never])).toBe(2);});+ it('keeps an emptied earlier phase header when a later marker recovers nothing', () => {+ const laterTool = {+ type: ContentTypes.TOOL_CALL,+ tool_call: { id: 'later', name: 'web_search', args: '{}', output: 'ok' },+ } as unknown as TMessageContentParts;+ /** Compaction left this completed phase with no children, so its summary+ * header is the entire segment. A later marker recovers nothing from it. */+ const emptied = labelPart({ activity_label: 'Completed the compacted phase', pending: false });+ Object.assign(emptied, {+ activity_label_type: 'phase',+ activity_start_index: 0,+ activity_end_index: 0,+ activity_count: 2,+ });+ const later = labelPart({ activity_label: 'Completed the later phase', pending: false });+ Object.assign(later, {+ activity_label_type: 'phase',+ activity_start_index: 0,+ activity_end_index: 2,+ activity_count: 2,+ });+ const content = [emptied as never, laterTool, later as never];++ const segments = groupActivityPhases(content);++ expect(segments?.filter((segment) => segment.type === 'phase')).toHaveLength(2);+ });++ it('groups multiple logical spans when an earlier phase marker arrives late', () => {+ const first = labelPart({ activity_label: 'Completed the first phase', pending: false });+ Object.assign(first, {+ activity_label_type: 'phase',+ activity_start_index: 0,+ activity_end_index: 2,+ activity_count: 2,+ });+ const second = labelPart({ activity_label: 'Completed the second phase', pending: false });+ Object.assign(second, {+ activity_label_type: 'phase',+ activity_start_index: 3,+ activity_end_index: 6,+ activity_count: 2,+ });+ const boundary = {+ type: ContentTypes.TEXT,+ text: 'Substantial result',+ } as TMessageContentParts;+ const final = { type: ContentTypes.TEXT, text: 'Final result' } as TMessageContentParts;+ const content = [tool, tool, boundary, tool, first as never, tool, final, second as never];++ const segments = groupActivityPhases(content);++ expect(segments).toEqual([+ expect.objectContaining({+ type: 'phase',+ startIndex: 0,+ labelIndex: 4,+ contentIndices: [0, 1],+ }),+ expect.objectContaining({+ type: 'content',+ startIndex: 2,+ contentIndices: [2],+ }),+ expect.objectContaining({+ type: 'phase',+ startIndex: 3,+ labelIndex: 7,+ contentIndices: [3, 5],+ }),+ expect.objectContaining({+ type: 'content',+ startIndex: 6,+ contentIndices: [6],+ }),+ ]);+ });++ it('moves a late child label from an earlier phase into its declared later span', () => {+ const firstTool = {+ type: ContentTypes.TOOL_CALL,+ tool_call: { id: 'first', name: 'web_search', args: '{}', output: 'ok' },+ } as unknown as TMessageContentParts;+ const laterTool = {+ type: ContentTypes.TOOL_CALL,+ tool_call: { id: 'later', name: 'web_search', args: '{}', output: 'ok' },+ } as unknown as TMessageContentParts;+ const lateChild = labelPart({+ activity_label: 'Recorded the later result',+ pending: false,+ tool_call_ids: ['later'],+ });+ const first = labelPart({ activity_label: 'Completed the first phase', pending: false });+ Object.assign(first, {+ activity_label_type: 'phase',+ activity_start_index: 0,+ activity_end_index: 1,+ activity_count: 2,+ });+ const second = labelPart({ activity_label: 'Completed the second phase', pending: false });+ Object.assign(second, {+ activity_label_type: 'phase',+ activity_start_index: 2,+ activity_end_index: 4,+ activity_count: 2,+ });+ const boundary = { type: ContentTypes.TEXT, text: 'Boundary' } as TMessageContentParts;+ const content = [+ firstTool,+ boundary,+ laterTool,+ lateChild as never,+ first as never,+ second as never,+ ];++ const segments = groupActivityPhases(content);++ expect(segments).toEqual([+ expect.objectContaining({+ type: 'phase',+ labelIndex: 4,+ contentIndices: [0],+ }),+ expect.objectContaining({+ type: 'content',+ contentIndices: [1],+ }),+ expect.objectContaining({+ type: 'phase',+ labelIndex: 5,+ contentIndices: [2, 3],+ }),+ ]);+ });+it('keeps a late child label in the phase while leaving final text outside', () => {const child = labelPart({activity_label: 'Recorded the delayed child result',diff --git a/client/src/utils/activityLabels.ts b/client/src/utils/activityLabels.tsindex fb99bab66b..19193fd749 100644--- a/client/src/utils/activityLabels.ts+++ b/client/src/utils/activityLabels.ts@@ -177,19 +177,88 @@ export function groupActivityPhases(segment.contentIndices.push(partIndex);segment.hasContent ||= isVisibleContentPart(child);};+ /** Recovery can empty a span it already claimed. An index-less segment+ * renders nothing but still mounts a nested `ContentParts`, so drop it the+ * same way a fully recovered segment is spliced out below. */+ const pushContent = (segment: ReturnType<typeof collect>, startIndex: number) => {+ if (segment.contentIndices.length === 0) {+ return;+ }+ segments.push({+ type: 'content',+ content: segment.content,+ contentIndices: segment.contentIndices,+ startIndex,+ });+ };/** Phase markers and defined content indexes are both sorted. Walk them in* lockstep so every ordinary part is classified once, even when a custom* max permits many parent phases in one long response. */for (const { part, index } of completed) {if (!part) continue;- const start = Math.max(- cursor,- Math.min(index, Math.max(0, part.activity_start_index ?? index)),- );+ const start = Math.min(index, Math.max(0, part.activity_start_index ?? index));const end = Math.max(start, Math.min(index, Math.max(0, part.activity_end_index ?? index)));const adjacent = collect();const phase = collect();const trailing = collect();+ /** A boundary may resolve after a higher-index parallel activity has+ * already rendered. Recover that activity from an earlier adjacent+ * segment so a later phase marker can still claim its declared span. */+ if (start < cursor) {+ const recoveredIndices: number[] = [];+ const deferredTrailingIndices: number[] = [];+ for (let segmentIndex = segments.length - 1; segmentIndex >= 0; segmentIndex -= 1) {+ const segment = segments[segmentIndex];+ if (segment.type !== 'content' && segment.type !== 'phase') {+ continue;+ }+ const retainedContent: Array<TMessageContentParts | undefined> = [];+ const retainedIndices: number[] = [];+ for (+ let childPosition = 0;+ childPosition < segment.contentIndices.length;+ childPosition += 1+ ) {+ const childIndex = segment.contentIndices[childPosition];+ const child = segment.content[childPosition];+ const canRecover = segment.type === 'content' || getBatchActivityLabelPart(child) != null;+ if (canRecover && childIndex >= start && childIndex < end) {+ recoveredIndices.push(childIndex);+ } else if (canRecover && childIndex >= end) {+ deferredTrailingIndices.push(childIndex);+ } else {+ retainedContent.push(child);+ retainedIndices.push(childIndex);+ }+ }+ if (retainedIndices.length === 0) {+ /** A completed phase can legitimately carry no children after+ * compaction — its summary header is the whole segment. Only drop+ * what recovery actually emptied, not what arrived empty. */+ if (segment.contentIndices.length > 0) {+ segments.splice(segmentIndex, 1);+ }+ } else {+ segment.content = retainedContent;+ segment.contentIndices = retainedIndices;+ segment.startIndex = retainedIndices[0];+ if (segment.type === 'phase') {+ /** Recovery can take the only filled label and leave blank+ * reservations behind. A stale flag renders an expandable card+ * with nothing in it instead of the compact header. */+ segment.hasContent = retainedContent.some(isVisibleContentPart);+ }+ }+ }+ recoveredIndices.sort((a, b) => a - b);+ for (const recoveredIndex of recoveredIndices) {+ append(phase, recoveredIndex);+ }+ deferredTrailingIndices.sort((a, b) => a - b);+ for (const trailingIndex of deferredTrailingIndices) {+ append(trailing, trailingIndex);+ }+ }while (definedPosition < definedIndices.length && definedIndices[definedPosition] < index) {const childIndex = definedIndices[definedPosition];definedPosition += 1;@@ -208,12 +277,7 @@ export function groupActivityPhases(definedPosition += 1;}if (start > cursor) {- segments.push({- type: 'content',- content: adjacent.content,- contentIndices: adjacent.contentIndices,- startIndex: cursor,- });+ pushContent(adjacent, cursor);}const labelText = getActivityLabelText(part);if (labelText) {@@ -230,20 +294,10 @@ export function groupActivityPhases(/** A failed/empty parent stays visually feature-off, but its bounds are* still authoritative: delayed child labels must move back beside the* tools they describe instead of rendering after the final answer. */- segments.push({- type: 'content',- content: phase.content,- contentIndices: phase.contentIndices,- startIndex: start,- });+ pushContent(phase, start);}if (end < index) {- segments.push({- type: 'content',- content: trailing.content,- contentIndices: trailing.contentIndices,- startIndex: end,- });+ pushContent(trailing, end);}cursor = index + 1;}@@ -256,12 +310,7 @@ export function groupActivityPhases(append(adjacent, childIndex);}}- segments.push({- type: 'content',- content: adjacent.content,- contentIndices: adjacent.contentIndices,- startIndex: cursor,- });+ pushContent(adjacent, cursor);}return segments;}diff --git a/packages/api/src/agents/activityPhases/runtime.spec.ts b/packages/api/src/agents/activityPhases/runtime.spec.tsindex 5f217a6bb2..e809f922b7 100644--- a/packages/api/src/agents/activityPhases/runtime.spec.ts+++ b/packages/api/src/agents/activityPhases/runtime.spec.ts@@ -1,8 +1,8 @@import { GraphEvents } from '@librechat/agents';import { ContentTypes, StepTypes } from 'librechat-data-provider';import type { PostToolBatchHookInput } from '@librechat/agents';+import type { ActivityPhaseSnapshot, GenerateActivityPhasePayload } from './runtime';import type { LooseContentPart } from '~/agents/activityLabels/wiring';-import type { GenerateActivityPhasePayload } from './runtime';import {ACTIVITY_PHASE_INSTRUCTION,createActivityPhaseWiring,@@ -24,6 +24,21 @@ const batch = (id: string): PostToolBatchHookInput =>],}) as PostToolBatchHookInput;+const SUBSTANTIAL_TEXT_CHARS = 200;+const substantialText = (prefix: string): string =>+ `${prefix} ${'x'.repeat(SUBSTANTIAL_TEXT_CHARS + 1)}`;++const RETAINED_EVIDENCE_ACTIVITIES = 13;+const OVERFLOW_ACTIVITY_ANCHORS = 64;++const totalTrackedCount = (activities: ActivityPhaseSnapshot['activities']): number =>+ activities.reduce((total, activity) => total + (activity.mergedCount ?? 1), 0);++const numericField = (part: LooseContentPart | null | undefined, field: string): number => {+ const value = part?.[field];+ return typeof value === 'number' ? value : Number.NaN;+};+async function flushDetached(): Promise<void> {for (let i = 0; i < 4; i += 1) {await new Promise((resolve) => setImmediate(resolve));@@ -31,13 +46,14 @@ async function flushDetached(): Promise<void> {}describe('createActivityPhaseWiring', () => {- it('claims one parent phase before forwarding the final text step', async () => {+ it('claims one parent phase when text becomes substantial', async () => {const parts: LooseContentPart[] = [];const forwarded: unknown[] = [];const emitLabelEvent = jest.fn(async () => undefined);const generatePhase = jest.fn(async () => ({ label: 'Resolved the release compatibility' }));const wiring = createActivityPhaseWiring({getContentParts: () => parts,+ getStepIndex: (stepId) => (stepId === 'final-step' ? 1 : undefined),bumpIndexOffset: jest.fn(),emitLabelEvent,trackPendingFill: jest.fn(),@@ -61,6 +77,15 @@ describe('createActivityPhaseWiring', () => {forwarded.push(data);},},+ [GraphEvents.ON_MESSAGE_DELTA]: {+ handle: (_event, data) => {+ const delta = data as { delta?: { content?: { text?: string } } };+ parts[2] = {+ type: ContentTypes.TEXT,+ text: `${parts[2]?.text ?? ''}${delta.delta?.content?.text ?? ''}`,+ };+ },+ },});handlers?.[GraphEvents.ON_RUN_STEP]?.handle(GraphEvents.ON_RUN_STEP,@@ -79,9 +104,21 @@ describe('createActivityPhaseWiring', () => {undefined,undefined,);+ expect(parts).toHaveLength(2);+ handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.handle(+ GraphEvents.ON_MESSAGE_DELTA,+ {+ id: 'final-step',+ delta: {+ content: { type: ContentTypes.TEXT, text: 'A'.repeat(SUBSTANTIAL_TEXT_CHARS + 1) },+ },+ },+ undefined,+ undefined,+ );expect(forwarded).toHaveLength(1);- expect(parts[2]).toMatchObject({+ expect(parts[3]).toMatchObject({type: ContentTypes.ACTIVITY_LABEL,activity_label_type: 'phase',activity_start_index: 0,@@ -99,225 +136,226 @@ describe('createActivityPhaseWiring', () => {prompt: ACTIVITY_PHASE_INSTRUCTION,}),);- expect(parts[2]).toMatchObject({+ expect(parts[3]).toMatchObject({activity_label: 'Resolved the release compatibility',pending: false,});expect(emitLabelEvent).toHaveBeenCalledTimes(2);});- it('keeps interleaved parallel text context keyed to its run step', async () => {- const parts: LooseContentPart[] = [- { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },- { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },- ];- const generatePhase = jest.fn(async () => ({ label: 'Compared both parallel findings' }));+ it('creates multiple phases around substantial root text in one run', async () => {+ const parts: LooseContentPart[] = [];+ const stepIndexes = new Map<string, number>();+ const generatedPayloads: GenerateActivityPhasePayload[] = [];+ const generatePhase = jest.fn(async (payload: GenerateActivityPhasePayload) => {+ generatedPayloads.push(payload);+ return { label: 'Completed the activity phase' };+ });const wiring = createActivityPhaseWiring({getContentParts: () => parts,+ getStepIndex: (stepId) => stepIndexes.get(stepId),bumpIndexOffset: jest.fn(),emitLabelEvent: jest.fn(async () => undefined),trackPendingFill: jest.fn(),generatePhase,});- await wiring.hook(batch('tool-1'), new AbortController().signal);- await wiring.hook(batch('tool-2'), new AbortController().signal);const handlers = wiring.handlers({[GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },- [GraphEvents.ON_MESSAGE_DELTA]: { handle: jest.fn() },+ [GraphEvents.ON_MESSAGE_DELTA]: {+ handle: (_event, data) => {+ const delta = data as { id?: string; delta?: { content?: { text?: string } } };+ const index = delta.id ? stepIndexes.get(delta.id) : undefined;+ if (index != null) {+ parts[index] = {+ type: ContentTypes.TEXT,+ text: `${parts[index]?.text ?? ''}${delta.delta?.content?.text ?? ''}`,+ };+ }+ },+ },});- const emitTextStep = (id: string, agentId: string) =>+ const emitText = (id: string, text: string, phase?: 'final_answer') => {+ const index = parts.length;+ stepIndexes.set(id, index);handlers?.[GraphEvents.ON_RUN_STEP]?.handle(GraphEvents.ON_RUN_STEP,{id,- agentId,- groupId: agentId,stepDetails: {type: StepTypes.MESSAGE_CREATION,- message_creation: { message_id: 'm', content_type: 'text' },+ message_creation: { message_id: id, content_type: 'text', ...(phase && { phase }) },},},undefined,undefined,);- const emitTextDelta = (id: string, text: string) =>handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.handle(GraphEvents.ON_MESSAGE_DELTA,{ id, delta: { content: { type: ContentTypes.TEXT, text } } },undefined,undefined,);-- emitTextStep('lane-a', 'agent-a');- emitTextStep('lane-b', 'agent-b');- emitTextDelta('lane-a', 'First lane ');- emitTextDelta('lane-b', 'Second lane');- emitTextDelta('lane-a', 'completed');- handlers?.[GraphEvents.ON_RUN_STEP]?.handle(- GraphEvents.ON_RUN_STEP,- {- id: 'root-final',- stepDetails: {- type: StepTypes.MESSAGE_CREATION,- message_creation: { message_id: 'm', content_type: 'text', phase: 'final_answer' },- },- },- undefined,- undefined,- );-- await flushDetached();- expect(generatePhase).toHaveBeenCalledWith(- expect.objectContaining({ assistantContext: ['First lane completed', 'Second lane'] }),- );- });-- it('reanchors a tool that lands after the phase hook observes its child label', async () => {- const parts: LooseContentPart[] = [];- const wiring = createActivityPhaseWiring({- getContentParts: () => parts,- bumpIndexOffset: jest.fn(),- emitLabelEvent: jest.fn(async () => undefined),- trackPendingFill: jest.fn(),- generatePhase: jest.fn(async () => ({ label: 'Verified both delayed tool results' })),- });-- /** The child-label hook can synchronously reserve its slot before the- * tool event reaches the shared content array. A tool-only provider turn- * can also leave an empty final-answer part between the tool and label;- * that invisible boundary must not strand the tool outside the phase. */- parts[1] = { type: ContentTypes.TEXT, text: '', phase: 'final_answer' };- parts[2] = {- type: ContentTypes.ACTIVITY_LABEL,- activity_label: 'Recorded the first delayed result',- tool_call_ids: ['tool-1'],- pending: false,};- await wiring.hook(batch('tool-1'), new AbortController().signal);- parts[3] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } };- parts[4] = {- type: ContentTypes.ACTIVITY_LABEL,- activity_label: 'Recorded the second delayed result',- tool_call_ids: ['tool-2'],- pending: false,- };+ parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } });+ await wiring.hook(batch('tool-1'), new AbortController().signal);+ emitText('short-1', 'I pulled the repository history and will analyze it now.');+ parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } });await wiring.hook(batch('tool-2'), new AbortController().signal);+ emitText('long-1', `Here is the first substantial result. ${'A'.repeat(241)}`);- wiring- .handlers({ [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() } })- ?.[GraphEvents.ON_RUN_STEP]?.handle(- GraphEvents.ON_RUN_STEP,- {- id: 'final-step',- stepDetails: {- type: StepTypes.MESSAGE_CREATION,- message_creation: { message_id: 'm', content_type: 'text', phase: 'final_answer' },- },- },- undefined,- undefined,- );+ parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-3' } });+ await wiring.hook(batch('tool-3'), new AbortController().signal);+ emitText('short-2', 'I found another angle worth checking.');+ parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-4' } });+ await wiring.hook(batch('tool-4'), new AbortController().signal);+ emitText('long-2', `Here is the second substantial result. ${'B'.repeat(241)}`, 'final_answer');- expect(parts[5]).toMatchObject({+ await flushDetached();++ expect(generatePhase).toHaveBeenCalledTimes(2);+ expect(generatedPayloads[0]).toMatchObject({+ assistantContext: ['I pulled the repository history and will analyze it now.'],+ totalActivityCount: 2,+ });+ expect(generatedPayloads[1]).toMatchObject({+ assistantContext: ['I found another angle worth checking.'],+ closingTextPhase: 'final_answer',+ totalActivityCount: 2,+ });+ expect(parts[4]).toMatchObject({activity_label_type: 'phase',activity_start_index: 0,- activity_count: 2,+ activity_end_index: 3,+ });+ expect(parts[9]).toMatchObject({+ activity_label_type: 'phase',+ activity_start_index: 5,+ activity_end_index: 8,});- parts[0] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } };- expect(parts.slice(0, 5)).toEqual(- expect.arrayContaining([- expect.objectContaining({ tool_call: { id: 'tool-1' } }),- expect.objectContaining({ tool_call: { id: 'tool-2' } }),- ]),- );});- it('does not claim a visible final answer for a later parent phase', async () => {+ it('retains a later-indexed activity when an interleaved text step crosses a boundary', async () => {const parts: LooseContentPart[] = [- { type: ContentTypes.TEXT, text: 'Earlier final answer', phase: 'final_answer' },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },];+ const generatedPayloads: GenerateActivityPhasePayload[] = [];const wiring = createActivityPhaseWiring({getContentParts: () => parts,+ getStepIndex: (stepId) => (stepId === 'interleaved-text' ? 2 : undefined),bumpIndexOffset: jest.fn(),emitLabelEvent: jest.fn(async () => undefined),trackPendingFill: jest.fn(),- generatePhase: jest.fn(async () => ({ label: 'Verified the later tool results' })),+ generatePhase: jest.fn(async (payload: GenerateActivityPhasePayload) => {+ generatedPayloads.push(payload);+ return { label: 'Completed one activity phase' };+ }),});-- parts[2] = {- type: ContentTypes.ACTIVITY_LABEL,- activity_label: 'Recorded the first later result',- tool_call_ids: ['tool-1'],- pending: false,- };await wiring.hook(batch('tool-1'), new AbortController().signal);- parts[3] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } };await wiring.hook(batch('tool-2'), new AbortController().signal);-- wiring- .handlers({ [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() } })- ?.[GraphEvents.ON_RUN_STEP]?.handle(- GraphEvents.ON_RUN_STEP,- {- id: 'final-step',- stepDetails: {- type: StepTypes.MESSAGE_CREATION,- message_creation: { message_id: 'm', content_type: 'text', phase: 'final_answer' },- },+ const handlers = wiring.handlers({+ [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },+ [GraphEvents.ON_MESSAGE_DELTA]: {+ handle: (_event, data) => {+ const delta = data as { delta?: { content?: { text?: string } } };+ parts[2] = {+ type: ContentTypes.TEXT,+ text: `${parts[2]?.text ?? ''}${delta.delta?.content?.text ?? ''}`,+ };},- undefined,- undefined,- );-- expect(parts[4]).toMatchObject({- activity_label_type: 'phase',- activity_start_index: 1,- activity_count: 2,+ },});- parts[1] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } };- expect(parts.slice(1, 4)).toEqual(- expect.arrayContaining([- expect.objectContaining({ tool_call: { id: 'tool-1' } }),- expect.objectContaining({ tool_call: { id: 'tool-2' } }),- ]),+ handlers?.[GraphEvents.ON_RUN_STEP]?.handle(+ GraphEvents.ON_RUN_STEP,+ {+ id: 'interleaved-text',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'text' },+ },+ },+ undefined,+ undefined,+ );+ handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.handle(+ GraphEvents.ON_MESSAGE_DELTA,+ { id: 'interleaved-text', delta: { content: { type: ContentTypes.TEXT, text: 'prefix' } } },+ undefined,+ undefined,+ );+ parts[3] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-3' } };+ await wiring.hook(batch('tool-3'), new AbortController().signal);+ handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.handle(+ GraphEvents.ON_MESSAGE_DELTA,+ {+ id: 'interleaved-text',+ delta: { content: { type: ContentTypes.TEXT, text: 'x'.repeat(SUBSTANTIAL_TEXT_CHARS) } },+ },+ undefined,+ undefined,);+ parts[5] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-4' } };+ await wiring.hook(batch('tool-4'), new AbortController().signal);++ wiring.complete();+ await flushDetached();++ expect(generatedPayloads).toHaveLength(2);+ expect(generatedPayloads.map(({ totalActivityCount }) => totalActivityCount)).toEqual([2, 2]);+ expect(parts[4]).toMatchObject({ activity_end_index: 2, activity_count: 2 });+ expect(parts[6]).toMatchObject({ activity_start_index: 3, activity_count: 2 });});- it('does not use repeated reasoning to reanchor a missing tool across a phase', async () => {- const repeatedReasoning = 'Compared the same deployment paths.';+ it('preserves a live later reasoning lane across an interleaved text boundary', async () => {const parts: LooseContentPart[] = [- { type: ContentTypes.THINK, think: repeatedReasoning },- {- type: ContentTypes.ACTIVITY_LABEL,- activity_label: '',- activity_label_type: 'phase',- activity_start_index: 0,- activity_count: 2,- pending: false,- },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },];+ const stepIndexes = new Map([+ ['boundary-text', 2],+ ['later-reasoning', 3],+ ]);+ const generatePhase = jest.fn(async () => ({ label: 'Completed the earlier phase' }));const wiring = createActivityPhaseWiring({getContentParts: () => parts,- getStepIndex: (stepId) => {- if (stepId === 'missing-tool-reasoning') return 2;- if (stepId === 'current-reasoning') return 4;- return undefined;- },+ getStepIndex: (stepId) => stepIndexes.get(stepId),bumpIndexOffset: jest.fn(),emitLabelEvent: jest.fn(async () => undefined),trackPendingFill: jest.fn(),- generatePhase: jest.fn(async () => ({ label: 'Verified the current deployment path' })),+ generatePhase,});+ await wiring.hook(batch('tool-1'), new AbortController().signal);+ await wiring.hook(batch('tool-2'), new AbortController().signal);const handlers = wiring.handlers({[GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },[GraphEvents.ON_REASONING_DELTA]: { handle: jest.fn() },+ [GraphEvents.ON_MESSAGE_DELTA]: {+ handle: (_event, data) => {+ const delta = data as { delta?: { content?: { text?: string } } };+ parts[2] = {+ type: ContentTypes.TEXT,+ text: `${parts[2]?.text ?? ''}${delta.delta?.content?.text ?? ''}`,+ };+ },+ },});-handlers?.[GraphEvents.ON_RUN_STEP]?.handle(GraphEvents.ON_RUN_STEP,{- id: 'missing-tool-reasoning',+ id: 'boundary-text',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'text' },+ },+ },+ undefined,+ undefined,+ );+ handlers?.[GraphEvents.ON_RUN_STEP]?.handle(+ GraphEvents.ON_RUN_STEP,+ {+ id: 'later-reasoning',stepDetails: {type: StepTypes.MESSAGE_CREATION,message_creation: { message_id: 'm', content_type: 'think' },@@ -326,22 +364,398 @@ describe('createActivityPhaseWiring', () => {undefined,undefined,);- parts[2] = { type: ContentTypes.THINK, think: repeatedReasoning };+ parts[3] = { type: ContentTypes.THINK, think: 'Investigating the later tool.' };handlers?.[GraphEvents.ON_REASONING_DELTA]?.handle(GraphEvents.ON_REASONING_DELTA,{- id: 'missing-tool-reasoning',- delta: { content: { type: ContentTypes.THINK, think: repeatedReasoning } },+ id: 'later-reasoning',+ delta: { content: { type: ContentTypes.THINK, think: 'Investigating the later tool.' } },},undefined,undefined,);- parts[3] = {- type: ContentTypes.ACTIVITY_LABEL,- activity_label: 'Recorded a result before its tool arrived',- tool_call_ids: ['missing-tool'],- pending: false,- };+ handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.handle(+ GraphEvents.ON_MESSAGE_DELTA,+ {+ id: 'boundary-text',+ delta: { content: { type: ContentTypes.TEXT, text: substantialText('Boundary result.') } },+ },+ undefined,+ undefined,+ );+ parts[5] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-3' } };+ await wiring.hook(batch('tool-3'), new AbortController().signal);++ wiring.complete();+ await flushDetached();++ expect(generatePhase).toHaveBeenCalledTimes(1);+ expect(wiring.snapshot().activityCount).toBe(0);+ });++ it('splits resumed activities around every persisted substantial text boundary', async () => {+ const parts: LooseContentPart[] = [+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },+ { type: ContentTypes.TEXT, text: substantialText('First persisted result.') },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-3' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-4' } },+ { type: ContentTypes.TEXT, text: substantialText('Second persisted result.') },+ ];+ const generatePhase = jest.fn(async () => ({ label: 'Completed one persisted phase' }));+ const wiring = createActivityPhaseWiring({+ initialSnapshot: {+ version: 1,+ generated: 0,+ activityCount: 4,+ failedActivityCount: 0,+ partialActivityCount: 0,+ agentIds: [],+ activities: [+ { startIndex: 0, status: 'success', toolCallIds: ['tool-1'] },+ { startIndex: 1, status: 'success', toolCallIds: ['tool-2'] },+ { startIndex: 3, status: 'success', toolCallIds: ['tool-3'] },+ { startIndex: 4, status: 'success', toolCallIds: ['tool-4'] },+ ],+ assistantContext: [],+ pendingReasoning: [],+ },+ getContentParts: () => parts,+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase,+ });++ wiring.complete();+ await flushDetached();++ expect(generatePhase).toHaveBeenCalledTimes(2);+ expect(parts[6]).toMatchObject({ activity_start_index: 0, activity_end_index: 2 });+ expect(parts[7]).toMatchObject({ activity_start_index: 3, activity_end_index: 5 });+ });++ it('partitions persisted context by activity position across HITL boundaries', async () => {+ const parts: LooseContentPart[] = [+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },+ {+ type: ContentTypes.TEXT,+ text: substantialText('Persisted commentary boundary.'),+ phase: 'commentary',+ },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-3' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-4' } },+ ];+ const payloads: GenerateActivityPhasePayload[] = [];+ const wiring = createActivityPhaseWiring({+ initialSnapshot: {+ version: 1,+ generated: 0,+ activityCount: 4,+ failedActivityCount: 0,+ partialActivityCount: 0,+ agentIds: [],+ activities: [+ { startIndex: 0, status: 'success', toolCallIds: ['tool-1'] },+ { startIndex: 1, status: 'success', toolCallIds: ['tool-2'] },+ { startIndex: 3, status: 'success', toolCallIds: ['tool-3'] },+ { startIndex: 4, status: 'success', toolCallIds: ['tool-4'] },+ ],+ assistantContext: [+ { text: 'Context for the earlier work.', activityPosition: 2 },+ { text: 'Context for the later work.', activityPosition: 4 },+ ],+ pendingReasoning: [],+ },+ getContentParts: () => parts,+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase: jest.fn(async (payload: GenerateActivityPhasePayload) => {+ payloads.push(payload);+ return { label: 'Completed one phase' };+ }),+ });++ wiring.complete();+ await flushDetached();++ expect(payloads).toHaveLength(2);+ expect(payloads[0]).toMatchObject({+ assistantContext: ['Context for the earlier work.'],+ closingTextPhase: 'commentary',+ });+ expect(payloads[1]).toMatchObject({ assistantContext: ['Context for the later work.'] });+ });++ it('keeps a substantial boundary hard when too little preceding work earns a phase', async () => {+ const parts: LooseContentPart[] = [+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ { type: ContentTypes.TEXT, text: substantialText('Standalone result.') },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-3' } },+ ];+ const wiring = createActivityPhaseWiring({+ getContentParts: () => parts,+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase: jest.fn(async () => ({ label: 'Completed the later phase' })),+ });+ await wiring.hook(batch('tool-1'), new AbortController().signal);+ await wiring.hook(batch('tool-2'), new AbortController().signal);+ await wiring.hook(batch('tool-3'), new AbortController().signal);++ wiring.complete();+ await flushDetached();++ expect(parts[4]).toMatchObject({+ activity_start_index: 2,+ activity_end_index: 4,+ activity_count: 2,+ });+ });++ it('keeps interleaved parallel text context keyed to its run step', async () => {+ const parts: LooseContentPart[] = [+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },+ ];+ const generatePhase = jest.fn(async () => ({ label: 'Compared both parallel findings' }));+ const wiring = createActivityPhaseWiring({+ getContentParts: () => parts,+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase,+ });+ await wiring.hook(batch('tool-1'), new AbortController().signal);+ await wiring.hook(batch('tool-2'), new AbortController().signal);+ const handlers = wiring.handlers({+ [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },+ [GraphEvents.ON_MESSAGE_DELTA]: { handle: jest.fn() },+ });+ const emitTextStep = (id: string, agentId: string) =>+ handlers?.[GraphEvents.ON_RUN_STEP]?.handle(+ GraphEvents.ON_RUN_STEP,+ {+ id,+ agentId,+ groupId: agentId,+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'text' },+ },+ },+ undefined,+ undefined,+ );+ const emitTextDelta = (id: string, text: string) =>+ handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.handle(+ GraphEvents.ON_MESSAGE_DELTA,+ { id, delta: { content: { type: ContentTypes.TEXT, text } } },+ undefined,+ undefined,+ );++ emitTextStep('lane-a', 'agent-a');+ emitTextStep('lane-b', 'agent-b');+ emitTextDelta('lane-a', 'First lane ');+ emitTextDelta('lane-b', 'Second lane');+ emitTextDelta('lane-a', 'completed');+ handlers?.[GraphEvents.ON_RUN_STEP]?.handle(+ GraphEvents.ON_RUN_STEP,+ {+ id: 'root-final',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'text', phase: 'final_answer' },+ },+ },+ undefined,+ undefined,+ );++ wiring.complete();+ await flushDetached();+ expect(generatePhase).toHaveBeenCalledWith(+ expect.objectContaining({ assistantContext: ['First lane completed', 'Second lane'] }),+ );+ });++ it('reanchors a tool that lands after the phase hook observes its child label', async () => {+ const parts: LooseContentPart[] = [];+ const wiring = createActivityPhaseWiring({+ getContentParts: () => parts,+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase: jest.fn(async () => ({ label: 'Verified both delayed tool results' })),+ });++ /** The child-label hook can synchronously reserve its slot before the+ * tool event reaches the shared content array. A tool-only provider turn+ * can also leave an empty final-answer part between the tool and label;+ * that invisible boundary must not strand the tool outside the phase. */+ parts[1] = { type: ContentTypes.TEXT, text: '', phase: 'final_answer' };+ parts[2] = {+ type: ContentTypes.ACTIVITY_LABEL,+ activity_label: 'Recorded the first delayed result',+ tool_call_ids: ['tool-1'],+ pending: false,+ };+ await wiring.hook(batch('tool-1'), new AbortController().signal);++ parts[3] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } };+ parts[4] = {+ type: ContentTypes.ACTIVITY_LABEL,+ activity_label: 'Recorded the second delayed result',+ tool_call_ids: ['tool-2'],+ pending: false,+ };+ await wiring.hook(batch('tool-2'), new AbortController().signal);++ wiring+ .handlers({ [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() } })+ ?.[GraphEvents.ON_RUN_STEP]?.handle(+ GraphEvents.ON_RUN_STEP,+ {+ id: 'final-step',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'text', phase: 'final_answer' },+ },+ },+ undefined,+ undefined,+ );++ wiring.complete();+ expect(parts[5]).toMatchObject({+ activity_label_type: 'phase',+ activity_start_index: 0,+ activity_count: 2,+ });+ parts[0] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } };+ expect(parts.slice(0, 5)).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ tool_call: { id: 'tool-1' } }),+ expect.objectContaining({ tool_call: { id: 'tool-2' } }),+ ]),+ );+ });++ it('does not claim a visible final answer for a later parent phase', async () => {+ const parts: LooseContentPart[] = [+ { type: ContentTypes.TEXT, text: 'Earlier final answer', phase: 'final_answer' },+ ];+ const wiring = createActivityPhaseWiring({+ getContentParts: () => parts,+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase: jest.fn(async () => ({ label: 'Verified the later tool results' })),+ });++ parts[2] = {+ type: ContentTypes.ACTIVITY_LABEL,+ activity_label: 'Recorded the first later result',+ tool_call_ids: ['tool-1'],+ pending: false,+ };+ await wiring.hook(batch('tool-1'), new AbortController().signal);+ parts[3] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } };+ await wiring.hook(batch('tool-2'), new AbortController().signal);++ wiring+ .handlers({ [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() } })+ ?.[GraphEvents.ON_RUN_STEP]?.handle(+ GraphEvents.ON_RUN_STEP,+ {+ id: 'final-step',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'text', phase: 'final_answer' },+ },+ },+ undefined,+ undefined,+ );++ wiring.complete();+ expect(parts[4]).toMatchObject({+ activity_label_type: 'phase',+ activity_start_index: 1,+ activity_count: 2,+ });+ parts[1] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } };+ expect(parts.slice(1, 4)).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ tool_call: { id: 'tool-1' } }),+ expect.objectContaining({ tool_call: { id: 'tool-2' } }),+ ]),+ );+ });++ it('does not use repeated reasoning to reanchor a missing tool across a phase', async () => {+ const repeatedReasoning = 'Compared the same deployment paths.';+ const parts: LooseContentPart[] = [+ { type: ContentTypes.THINK, think: repeatedReasoning },+ {+ type: ContentTypes.ACTIVITY_LABEL,+ activity_label: '',+ activity_label_type: 'phase',+ activity_start_index: 0,+ activity_count: 2,+ pending: false,+ },+ ];+ const wiring = createActivityPhaseWiring({+ getContentParts: () => parts,+ getStepIndex: (stepId) => {+ if (stepId === 'missing-tool-reasoning') return 2;+ if (stepId === 'current-reasoning') return 4;+ return undefined;+ },+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase: jest.fn(async () => ({ label: 'Verified the current deployment path' })),+ });+ const handlers = wiring.handlers({+ [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },+ [GraphEvents.ON_REASONING_DELTA]: { handle: jest.fn() },+ });++ handlers?.[GraphEvents.ON_RUN_STEP]?.handle(+ GraphEvents.ON_RUN_STEP,+ {+ id: 'missing-tool-reasoning',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'think' },+ },+ },+ undefined,+ undefined,+ );+ parts[2] = { type: ContentTypes.THINK, think: repeatedReasoning };+ handlers?.[GraphEvents.ON_REASONING_DELTA]?.handle(+ GraphEvents.ON_REASONING_DELTA,+ {+ id: 'missing-tool-reasoning',+ delta: { content: { type: ContentTypes.THINK, think: repeatedReasoning } },+ },+ undefined,+ undefined,+ );+ parts[3] = {+ type: ContentTypes.ACTIVITY_LABEL,+ activity_label: 'Recorded a result before its tool arrived',+ tool_call_ids: ['missing-tool'],+ pending: false,+ };await wiring.hook(batch('missing-tool'), new AbortController().signal);handlers?.[GraphEvents.ON_RUN_STEP]?.handle(@@ -380,6 +794,7 @@ describe('createActivityPhaseWiring', () => {undefined,);+ wiring.complete();expect(parts[5]).toMatchObject({activity_label_type: 'phase',activity_start_index: 2,@@ -538,6 +953,7 @@ describe('createActivityPhaseWiring', () => {undefined,);+ wiring.complete();await flushDetached();expect(generatePhase).toHaveBeenCalledTimes(1);expect(generatedActivities).toHaveLength(2);@@ -704,6 +1120,7 @@ describe('createActivityPhaseWiring', () => {undefined,);+ wiring.complete();await flushDetached();expect(generatePhase).toHaveBeenCalledWith(expect.objectContaining({ activities: expect.arrayContaining([expect.any(Object)]) }),@@ -761,6 +1178,7 @@ describe('createActivityPhaseWiring', () => {undefined,);+ resumed.complete();await flushDetached();expect(generatePhase).toHaveBeenCalledWith(expect.objectContaining({ activities: expect.arrayContaining([expect.any(Object)]) }),@@ -773,7 +1191,7 @@ describe('createActivityPhaseWiring', () => {const parts: LooseContentPart[] = [{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },- { type: ContentTypes.TEXT, text: 'The resumed answer is complete.' },+ { type: ContentTypes.TEXT, text: substantialText('The resumed answer is complete.') },];const wiring = createActivityPhaseWiring({initialSnapshot: {@@ -806,14 +1224,14 @@ describe('createActivityPhaseWiring', () => {wiring.complete();await flushDetached();- expect(parts[3]).toMatchObject({ activity_end_index: 2, activity_count: 3 });+ expect(parts[3]).toMatchObject({ activity_end_index: 2, activity_count: 2 });});- it('resolves index-less pending reasoning before preserving the final-text boundary', async () => {+ it('keeps index-less reasoning after a preceding substantial-text boundary', async () => {const parts: LooseContentPart[] = [{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },- { type: ContentTypes.TEXT, text: 'This answer preceded more reasoning.' },+ { type: ContentTypes.TEXT, text: substantialText('This answer preceded more reasoning.') },];const wiring = createActivityPhaseWiring({getContentParts: () => parts,@@ -856,14 +1274,17 @@ describe('createActivityPhaseWiring', () => {wiring.complete();await flushDetached();- expect(parts[4]).toMatchObject({ activity_end_index: 4, activity_count: 3 });+ expect(parts[4]).toMatchObject({ activity_end_index: 2, activity_count: 2 });});- it('keeps a partially materialized retained batch after the candidate final text', async () => {+ it('does not force a partially materialized batch across a substantial boundary', async () => {const parts: LooseContentPart[] = [{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'batch-a' } },{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },- { type: ContentTypes.TEXT, text: 'This answer preceded the delayed batch tool.' },+ {+ type: ContentTypes.TEXT,+ text: substantialText('This answer preceded the delayed batch tool.'),+ },];const wiring = createActivityPhaseWiring({initialSnapshot: {@@ -894,10 +1315,10 @@ describe('createActivityPhaseWiring', () => {wiring.complete();await flushDetached();- expect(parts[3]).toMatchObject({ activity_end_index: 3, activity_count: 2 });+ expect(parts[3]).toBeUndefined();});- it('bounds persisted evidence while preserving the full activity count', async () => {+ it('bounds persisted evidence and the tracked activity window', async () => {const parts: LooseContentPart[] = [];const wiring = createActivityPhaseWiring({getContentParts: () => parts,@@ -906,17 +1327,283 @@ describe('createActivityPhaseWiring', () => {trackPendingFill: jest.fn(),generatePhase: jest.fn(async () => ({})),});- for (let index = 0; index < 20; index += 1) {+ for (let index = 0; index < 100; index += 1) {const id = `tool-${index}`;parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id } });await wiring.hook(batch(id), new AbortController().signal);}const snapshot = wiring.snapshot();- expect(snapshot.activityCount).toBe(20);- expect(snapshot.activities).toHaveLength(13);- expect(snapshot.overflowActivityStartIndex).toBe(19);- expect(snapshot.overflowToolCallIds).toHaveLength(7);+ expect(snapshot.version).toBe(3);+ /** Bounding drops evidence and folds anchors, never the count: a run that+ * outgrows the anchor budget still reports every activity it performed. */+ expect(snapshot.activityCount).toBe(100);+ expect(snapshot.activities.length).toBeLessThanOrEqual(+ RETAINED_EVIDENCE_ACTIVITIES + OVERFLOW_ACTIVITY_ANCHORS,+ );+ const withEvidence = snapshot.activities.filter((activity) => activity.entries != null);+ expect(withEvidence).toHaveLength(RETAINED_EVIDENCE_ACTIVITIES);+ expect(totalTrackedCount(snapshot.activities)).toBe(100);+ expect(snapshot.activities.every((activity) => activity.startIndex >= 0)).toBe(true);+ /** Folding past the cap must not reorder positions or carry a count+ * forward past a position it started before, or a later boundary would+ * claim work that happened before it. */+ const positions = snapshot.activities.map((activity) => activity.startIndex);+ expect(positions).toEqual([...positions].sort((left, right) => left - right));+ expect(+ snapshot.activities.filter((activity) => (activity.mergedCount ?? 1) > 1).length,+ ).toBeGreaterThan(0);+ });++ /** The partition is the one place a phase decides what it owns, so its+ * contract is checkable directly: wherever the boundary falls, every+ * activity lands on exactly one side and the counts still sum to the run. */+ it('conserves and orders every activity across any substantial-text boundary', async () => {+ const TOTAL_ACTIVITIES = 8;+ for (let boundary = 2; boundary <= TOTAL_ACTIVITIES - 2; boundary += 1) {+ const parts: LooseContentPart[] = [];+ const wiring = createActivityPhaseWiring({+ getContentParts: () => parts,+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase: jest.fn(async () => ({ label: 'Phase' })),+ });+ for (let index = 0; index < TOTAL_ACTIVITIES; index += 1) {+ if (index === boundary) {+ parts.push({ type: ContentTypes.TEXT, text: substantialText('Interim result') });+ }+ const id = `tool-${boundary}-${index}`;+ parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id } });+ await wiring.hook(batch(id), new AbortController().signal);+ }++ wiring.complete();+ await flushDetached();++ const markers = parts.filter(+ (part) =>+ part?.type === ContentTypes.ACTIVITY_LABEL && part.activity_label_type === 'phase',+ );+ expect(markers.length).toBeGreaterThan(1);+ const counted = markers.reduce(+ (total, marker) => total + numericField(marker, 'activity_count'),+ 0,+ );+ expect({ boundary, counted }).toEqual({ boundary, counted: TOTAL_ACTIVITIES });+ const ranges = markers+ .map((marker) => ({+ start: numericField(marker, 'activity_start_index'),+ end: numericField(marker, 'activity_end_index'),+ }))+ .sort((left, right) => left.start - right.start);+ for (const range of ranges) {+ expect(Number.isFinite(range.start) && Number.isFinite(range.end)).toBe(true);+ expect(range.end).toBeGreaterThan(range.start);+ }+ for (let position = 1; position < ranges.length; position += 1) {+ expect(ranges[position].start).toBeGreaterThanOrEqual(ranges[position - 1].end);+ }+ }+ });++ it('keeps a live unmaterialized batch after a substantial boundary', async () => {+ const parts: LooseContentPart[] = [+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'early-1' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'early-2' } },+ ];+ const generatePhase = jest.fn(async () => ({ label: 'Completed the early work' }));+ const wiring = createActivityPhaseWiring({+ getContentParts: () => parts,+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase,+ });+ await wiring.hook(batch('early-1'), new AbortController().signal);+ await wiring.hook(batch('early-2'), new AbortController().signal);+ parts.push({ type: ContentTypes.TEXT, text: substantialText('The interim answer.') });+ /** The child-label slot is reserved before the tool call lands, so this+ * batch is tracked with nothing materialized while its real position is+ * already past the boundary. */+ parts.push({+ type: ContentTypes.ACTIVITY_LABEL,+ [ContentTypes.ACTIVITY_LABEL]: 'Recorded the delayed result',+ tool_call_ids: ['delayed'],+ pending: false,+ });+ await wiring.hook(batch('delayed'), new AbortController().signal);++ wiring.complete();+ await flushDetached();++ const marker = parts.find(+ (part) => part?.type === ContentTypes.ACTIVITY_LABEL && part.activity_label_type === 'phase',+ );+ expect(marker).toMatchObject({ activity_end_index: 2, activity_count: 2 });+ });++ it('reanchors a delayed batch after dropping its already-covered call', async () => {+ const parts: LooseContentPart[] = [+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'covered' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'early-2' } },+ {+ type: ContentTypes.ACTIVITY_LABEL,+ [ContentTypes.ACTIVITY_LABEL]: 'Completed the first phase',+ activity_label_type: 'phase',+ activity_start_index: 0,+ activity_end_index: 2,+ activity_count: 2,+ pending: false,+ },+ ];+ const generatePhase = jest.fn(async () => ({ label: 'Completed the later phase' }));+ const wiring = createActivityPhaseWiring({+ getContentParts: () => parts,+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase,+ });+ parts.push({ type: ContentTypes.TEXT, text: substantialText('The interim answer.') });+ /** The delayed batch keeps one call already inside the emitted phase and+ * one that has not materialized. The surviving activity is the uncovered+ * call, so the covered call's index must not stand in for its position. */+ await wiring.hook(+ {+ hook_event_name: 'PostToolBatch',+ runId: 'run-1',+ entries: [+ {+ toolName: 'web_search',+ toolInput: { query: 'covered' },+ toolUseId: 'covered',+ status: 'success',+ toolOutput: 'covered-result',+ },+ {+ toolName: 'web_search',+ toolInput: { query: 'uncovered' },+ toolUseId: 'uncovered',+ status: 'success',+ toolOutput: 'uncovered-result',+ },+ ],+ } as PostToolBatchHookInput,+ new AbortController().signal,+ );+ parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id: 'later-2' } });+ await wiring.hook(batch('later-2'), new AbortController().signal);++ wiring.complete();+ await flushDetached();++ /** The uncovered call never materialized, so the delayed activity must be+ * held past the boundary rather than inheriting the covered call's index+ * and being counted in the phase that already closed. */+ const markers = parts.filter(+ (part) => part?.type === ContentTypes.ACTIVITY_LABEL && part.activity_label_type === 'phase',+ );+ expect(markers).toHaveLength(2);+ expect(markers[1]).toMatchObject({ activity_start_index: 3, activity_count: 2 });+ });++ it('clears a resolved missing-tool anchor before partitioning', async () => {+ const parts: LooseContentPart[] = [];+ const generatePhase = jest.fn(async () => ({ label: 'Completed the resumed work' }));+ const wiring = createActivityPhaseWiring({+ initialSnapshot: {+ version: 3,+ generated: 0,+ activityCount: 1,+ failedActivityCount: 0,+ partialActivityCount: 0,+ agentIds: [],+ activities: [{ startIndex: 9, status: 'success' as const, toolCallIds: ['delayed'] }],+ assistantContext: [],+ pendingReasoning: [],+ },+ getContentParts: () => parts,+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase,+ });+ /** The saved tool was absent at construction, so the activity kept a high+ * fallback anchor. It then materializes at index 0, well before the+ * boundary, and must close with the earlier phase. */+ parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id: 'delayed' } });+ parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id: 'second' } });+ await wiring.hook(batch('second'), new AbortController().signal);+ parts.push({ type: ContentTypes.TEXT, text: substantialText('The resumed answer.') });++ wiring.complete();+ await flushDetached();++ expect(parts[3]).toMatchObject({+ activity_start_index: 0,+ activity_end_index: 2,+ activity_count: 2,+ });+ });++ it('carries an unresolved position through a folded anchor', async () => {+ const parts: LooseContentPart[] = [];+ const wiring = createActivityPhaseWiring({+ getContentParts: () => parts,+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase: jest.fn(async () => ({})),+ });+ for (let index = 0; index < 90; index += 1) {+ const id = `tool-${index}`;+ parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id } });+ await wiring.hook(batch(id), new AbortController().signal);+ }+ /** This batch's call never reaches the content array, so it is tracked+ * with only a fallback position and must keep it through folding. */+ await wiring.hook(batch('never-materialized'), new AbortController().signal);+ for (let index = 0; index < 20; index += 1) {+ const id = `late-${index}`;+ parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id } });+ await wiring.hook(batch(id), new AbortController().signal);+ }++ const tracked = wiring.snapshot().activities;+ const holding = tracked.filter((activity) => activity.unresolvedToolStartIndex != null);+ expect(holding.length).toBeGreaterThan(0);+ expect(totalTrackedCount(tracked)).toBe(111);+ });++ it('keeps every contributing agent when folding anchors past the cap', async () => {+ const parts: LooseContentPart[] = [];+ const wiring = createActivityPhaseWiring({+ getContentParts: () => parts,+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase: jest.fn(async () => ({})),+ });+ for (let index = 0; index < 100; index += 1) {+ const id = `tool-${index}`;+ parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id } });+ await wiring.hook(+ { ...batch(id), executingAgentId: `agent-${index}` },+ new AbortController().signal,+ );+ }++ const tracked = wiring.snapshot().activities;+ const attributed = new Set(+ tracked.flatMap((activity) => [+ ...(activity.agentId != null ? [activity.agentId] : []),+ ...(activity.mergedAgentIds ?? []),+ ]),+ );+ /** Folding bounds memory, not attribution: an agent whose activity is+ * still counted must still be creditable for it. */+ expect(attributed.size).toBe(totalTrackedCount(tracked));});it('retains every overflow tool ID tied at the latest boundary', async () => {@@ -926,18 +1613,112 @@ describe('createActivityPhaseWiring', () => {bumpIndexOffset: jest.fn(),emitLabelEvent: jest.fn(async () => undefined),trackPendingFill: jest.fn(),- generatePhase: jest.fn(async () => ({})),+ generatePhase: jest.fn(async () => ({})),+ });+ for (let index = 0; index < 13; index += 1) {+ await wiring.hook(batch(`retained-${index}`), new AbortController().signal);+ }+ await wiring.hook(batch('overflow-a'), new AbortController().signal);+ await wiring.hook(batch('overflow-b'), new AbortController().signal);++ const anchors = wiring.snapshot().activities.filter((activity) => activity.bounded === true);+ expect(anchors.flatMap((activity) => activity.toolCallIds ?? [])).toEqual([+ 'overflow-a',+ 'overflow-b',+ ]);+ });++ it('anchors a phase represented entirely by retained overflow bookkeeping', async () => {+ const parts: LooseContentPart[] = [+ { type: ContentTypes.THINK, think: 'Earlier retained work' },+ { type: ContentTypes.TEXT, text: substantialText('Persisted intermediate result.') },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'overflow-a' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'overflow-b' } },+ ];+ const wiring = createActivityPhaseWiring({+ initialSnapshot: {+ version: 1,+ generated: 0,+ activityCount: 15,+ failedActivityCount: 0,+ partialActivityCount: 0,+ agentIds: [],+ activities: Array.from({ length: 13 }, () => ({+ startIndex: 0,+ status: 'success' as const,+ })),+ overflowActivityStartIndex: 30,+ overflowToolCallIds: ['overflow-a', 'overflow-b'],+ overflowBoundaryToolCallIds: ['overflow-a', 'overflow-b'],+ assistantContext: [],+ pendingReasoning: [],+ },+ getContentParts: () => parts,+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase: jest.fn(async () => ({ label: 'Completed the overflow phase' })),+ });++ wiring.complete();+ await flushDetached();++ expect(parts[5]).toMatchObject({+ activity_start_index: 2,+ activity_end_index: 5,+ activity_count: 2,+ });+ expect(Number.isFinite(parts[5]?.activity_start_index)).toBe(true);+ expect(Number.isFinite(parts[5]?.activity_end_index)).toBe(true);+ });++ it('partitions overflow activities on both sides of a substantial boundary', async () => {+ const parts: LooseContentPart[] = Array.from({ length: 13 }, (_, index) => ({+ type: ContentTypes.TOOL_CALL,+ tool_call: { id: `retained-${index}` },+ }));+ parts.push(+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'overflow-before' } },+ { type: ContentTypes.TEXT, text: substantialText('Persisted boundary.') },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'overflow-after' } },+ );+ const generatePhase = jest.fn(async () => ({ label: 'Completed the earlier overflow phase' }));+ const wiring = createActivityPhaseWiring({+ initialSnapshot: {+ version: 1,+ generated: 0,+ activityCount: 15,+ failedActivityCount: 0,+ partialActivityCount: 0,+ agentIds: [],+ activities: Array.from({ length: 13 }, (_, index) => ({+ startIndex: index,+ status: 'success' as const,+ toolCallIds: [`retained-${index}`],+ })),+ overflowActivityStartIndex: 15,+ overflowToolCallIds: ['overflow-before', 'overflow-after'],+ overflowBoundaryToolCallIds: ['overflow-after'],+ overflowActivities: [+ { startIndex: 13, status: 'success', toolCallIds: ['overflow-before'] },+ { startIndex: 15, status: 'success', toolCallIds: ['overflow-after'] },+ ],+ assistantContext: [],+ pendingReasoning: [],+ },+ getContentParts: () => parts,+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase,});- for (let index = 0; index < 13; index += 1) {- await wiring.hook(batch(`retained-${index}`), new AbortController().signal);- }- await wiring.hook(batch('overflow-a'), new AbortController().signal);- await wiring.hook(batch('overflow-b'), new AbortController().signal);- expect(wiring.snapshot()).toMatchObject({- overflowActivityStartIndex: 0,- overflowToolCallIds: ['overflow-a', 'overflow-b'],- });+ wiring.complete();+ await flushDetached();++ expect(generatePhase).toHaveBeenCalledTimes(1);+ expect(parts[16]).toMatchObject({ activity_end_index: 14, activity_count: 14 });+ expect(parts[17]).toBeUndefined();});it('rebases a resumed overflow anchor after content compaction', async () => {@@ -947,7 +1728,7 @@ describe('createActivityPhaseWiring', () => {}));parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id: 'overflow-tool' } },- { type: ContentTypes.TEXT, text: 'The compacted answer is complete.' },+ { type: ContentTypes.TEXT, text: substantialText('The compacted answer is complete.') },);const generatePhase = jest.fn(async () => ({ label: 'Completed the resumed workflow' }));const wiring = createActivityPhaseWiring({@@ -998,7 +1779,7 @@ describe('createActivityPhaseWiring', () => {it('drops a stale reasoning-only overflow anchor after HITL compaction', async () => {const parts: LooseContentPart[] = [- { type: ContentTypes.TEXT, text: 'The compacted answer is complete.' },+ { type: ContentTypes.TEXT, text: substantialText('The compacted answer is complete.') },];const generatePhase = jest.fn(async () => ({ label: 'Completed the resumed workflow' }));const wiring = createActivityPhaseWiring({@@ -1044,14 +1825,14 @@ describe('createActivityPhaseWiring', () => {wiring.complete();await flushDetached();- expect(parts[1]).toMatchObject({ activity_end_index: 0, activity_count: 14 });+ expect(parts[1]).toMatchObject({ activity_end_index: 0, activity_count: 13 });});- it('rejects a text boundary when a duplicate reasoning anchor follows it', async () => {+ it('splits duplicate reasoning anchors by their retained materialized positions', async () => {const duplicate = 'The same reasoning prefix identifies both retained activities.';const parts: LooseContentPart[] = [{ type: ContentTypes.THINK, think: duplicate },- { type: ContentTypes.TEXT, text: 'This looked like the final answer.' },+ { type: ContentTypes.TEXT, text: substantialText('This looked like the final answer.') },{ type: ContentTypes.THINK, think: `${duplicate} Later activity details.` },];const wiring = createActivityPhaseWiring({@@ -1094,14 +1875,17 @@ describe('createActivityPhaseWiring', () => {wiring.complete();await flushDetached();- expect(parts[3]).toMatchObject({ activity_end_index: 3, activity_count: 2 });+ expect(parts[3]).toBeUndefined();});- it('rejects a text boundary when a duplicate overflow reasoning anchor follows it', async () => {+ it('keeps duplicate overflow reasoning after a substantial boundary', async () => {const duplicate = 'The overflow reasoning prefix is shared by both positions.';const parts: LooseContentPart[] = [{ type: ContentTypes.THINK, think: duplicate },- { type: ContentTypes.TEXT, text: 'This looked like the final overflow answer.' },+ {+ type: ContentTypes.TEXT,+ text: substantialText('This looked like the final overflow answer.'),+ },{ type: ContentTypes.THINK, think: `${duplicate} Later overflow details.` },];const wiring = createActivityPhaseWiring({@@ -1146,7 +1930,7 @@ describe('createActivityPhaseWiring', () => {wiring.complete();await flushDetached();- expect(parts[3]).toMatchObject({ activity_end_index: 3, activity_count: 14 });+ expect(parts[3]).toMatchObject({ activity_end_index: 1, activity_count: 13 });});it('checks every overflow reasoning anchor when delayed parts materialize out of order', async () => {@@ -1154,7 +1938,10 @@ describe('createActivityPhaseWiring', () => {const later = 'The later overflow activity materialized before the apparent answer.';const parts: LooseContentPart[] = [{ type: ContentTypes.THINK, think: later },- { type: ContentTypes.TEXT, text: 'This looked like the final overflow answer.' },+ {+ type: ContentTypes.TEXT,+ text: substantialText('This looked like the final overflow answer.'),+ },{ type: ContentTypes.THINK, think: earlier },];const wiring = createActivityPhaseWiring({@@ -1199,13 +1986,16 @@ describe('createActivityPhaseWiring', () => {wiring.complete();await flushDetached();- expect(parts[3]).toMatchObject({ activity_end_index: 3, activity_count: 15 });+ expect(parts[3]).toMatchObject({ activity_end_index: 1, activity_count: 13 });});it('retains an earlier overflow ID when delayed tools materialize in reverse order', async () => {const parts: LooseContentPart[] = [{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'overflow-b' } },- { type: ContentTypes.TEXT, text: 'This answer arrived between delayed tools.' },+ {+ type: ContentTypes.TEXT,+ text: substantialText('This answer arrived between delayed tools.'),+ },{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'overflow-a' } },];const generatePhase = jest.fn(async () => ({ label: 'Completed the delayed workflow' }));@@ -1251,13 +2041,19 @@ describe('createActivityPhaseWiring', () => {wiring.complete();await flushDetached();- expect(parts[3]).toMatchObject({ activity_end_index: 3, activity_count: 15 });+ /** One saved overflow tool materialized on each side of the boundary, so+ * the earlier phase owns the earlier one instead of the later phase+ * claiming the whole remainder. */+ expect(parts[3]).toMatchObject({ activity_end_index: 1, activity_count: 14 });});it('keeps the overflow fallback while a boundary tool remains unresolved', async () => {const parts: LooseContentPart[] = [{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'overflow-a' } },- { type: ContentTypes.TEXT, text: 'This answer preceded a delayed overflow tool.' },+ {+ type: ContentTypes.TEXT,+ text: substantialText('This answer preceded a delayed overflow tool.'),+ },];const wiring = createActivityPhaseWiring({initialSnapshot: {@@ -1302,7 +2098,7 @@ describe('createActivityPhaseWiring', () => {wiring.complete();await flushDetached();- expect(parts[2]).toMatchObject({ activity_end_index: 2, activity_count: 15 });+ expect(parts[2]).toMatchObject({ activity_end_index: 1, activity_count: 13 });});it('extends a sparse phase start using only defined boundary slots', async () => {@@ -1337,7 +2133,7 @@ describe('createActivityPhaseWiring', () => {expect(parts[1_000_001]).toMatchObject({ activity_start_index: 0, activity_count: 2 });});- it('keeps post-cap activities grouped after the last root text', async () => {+ it('keeps post-cap activities outside the phase before substantial text', async () => {const parts: LooseContentPart[] = [];const generatePhase = jest.fn(async () => ({ label: 'Completed the extended investigation' }));const wiring = createActivityPhaseWiring({@@ -1367,7 +2163,10 @@ describe('createActivityPhaseWiring', () => {undefined,undefined,);- parts[13] = { type: ContentTypes.TEXT, text: 'This may be the final answer.' };+ parts[13] = {+ type: ContentTypes.TEXT,+ text: substantialText('This may be the final answer.'),+ };parts[14] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-overflow' } };await wiring.hook(batch('tool-overflow'), new AbortController().signal);@@ -1377,8 +2176,8 @@ describe('createActivityPhaseWiring', () => {expect(generatePhase).toHaveBeenCalledTimes(1);expect(parts[15]).toMatchObject({activity_start_index: 0,- activity_end_index: 15,- activity_count: 14,+ activity_end_index: 13,+ activity_count: 13,});});@@ -1386,7 +2185,7 @@ describe('createActivityPhaseWiring', () => {const parts: LooseContentPart[] = [{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },- { type: ContentTypes.TEXT, text: 'The persisted answer is complete.' },+ { type: ContentTypes.TEXT, text: substantialText('The persisted answer is complete.') },];const generatePhase = jest.fn(async () => ({ label: 'Completed the persisted workflow' }));const wiring = createActivityPhaseWiring({@@ -1410,7 +2209,7 @@ describe('createActivityPhaseWiring', () => {});it('excludes the persisted final text from the phase summary context', async () => {- const finalText = 'The persisted answer is complete.';+ const finalText = substantialText('The persisted answer is complete.');const parts: LooseContentPart[] = [{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },@@ -1477,284 +2276,687 @@ describe('createActivityPhaseWiring', () => {message_creation: { message_id: 'm', content_type: 'text' },},},- undefined,- undefined,- );- parts[2] = { type: ContentTypes.TEXT, text: 'The indexed answer is complete.' };+ undefined,+ undefined,+ );+ parts[2] = {+ type: ContentTypes.TEXT,+ text: substantialText('The indexed answer is complete.'),+ };++ wiring.complete();+ await flushDetached();++ expect(parts[3]).toMatchObject({+ activity_start_index: 0,+ activity_end_index: 2,+ activity_count: 2,+ });+ });++ it('leaves the last materialized text outside even when it retains a lane id', async () => {+ const parts: LooseContentPart[] = [+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },+ {+ type: ContentTypes.TEXT,+ text: substantialText('The lane answer is complete.'),+ phase: 'final_answer',+ groupId: 'lane-a',+ },+ ];+ const wiring = createActivityPhaseWiring({+ getContentParts: () => parts,+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase: jest.fn(async () => ({ label: 'Completed the lane workflow' })),+ });+ await wiring.hook(batch('tool-1'), new AbortController().signal);+ await wiring.hook(batch('tool-2'), new AbortController().signal);++ wiring.complete();+ await flushDetached();++ expect(parts[3]).toMatchObject({ activity_end_index: 2, activity_count: 2 });+ });++ it('skips a trailing empty text reservation when choosing the final boundary', async () => {+ const parts: LooseContentPart[] = [+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },+ {+ type: ContentTypes.TEXT,+ text: substantialText('The materialized answer is complete.'),+ },+ { type: ContentTypes.TEXT, text: '', phase: 'final_answer' },+ ];+ const wiring = createActivityPhaseWiring({+ getContentParts: () => parts,+ getStepIndex: (stepId) => (stepId === 'empty-final' ? 3 : undefined),+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase: jest.fn(async () => ({ label: 'Completed the workflow' })),+ });+ await wiring.hook(batch('tool-1'), new AbortController().signal);+ await wiring.hook(batch('tool-2'), new AbortController().signal);+ wiring+ .handlers({ [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() } })+ ?.[GraphEvents.ON_RUN_STEP]?.handle(+ GraphEvents.ON_RUN_STEP,+ {+ id: 'empty-final',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'text' },+ },+ },+ undefined,+ undefined,+ );++ wiring.complete();+ await flushDetached();++ expect(parts[4]).toMatchObject({ activity_end_index: 2, activity_count: 2 });+ });++ it('ignores an empty reasoning reservation after the materialized final text', async () => {+ const parts: LooseContentPart[] = [+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },+ { type: ContentTypes.TEXT, text: substantialText('The answer is complete.') },+ { type: ContentTypes.THINK, think: '' },+ ];+ const wiring = createActivityPhaseWiring({+ getContentParts: () => parts,+ getStepIndex: (stepId) => (stepId === 'empty-reasoning' ? 3 : undefined),+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase: jest.fn(async () => ({ label: 'Completed the workflow' })),+ });+ await wiring.hook(batch('tool-1'), new AbortController().signal);+ await wiring.hook(batch('tool-2'), new AbortController().signal);+ wiring+ .handlers({+ [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },+ })+ ?.[GraphEvents.ON_RUN_STEP]?.handle(+ GraphEvents.ON_RUN_STEP,+ {+ id: 'empty-reasoning',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'think' },+ },+ },+ undefined,+ undefined,+ );++ wiring.complete();+ await flushDetached();++ expect(parts[4]).toMatchObject({ activity_end_index: 2, activity_count: 2 });+ });++ it('keeps a parallel lane final inside the run-wide phase', async () => {+ const parts: LooseContentPart[] = [+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ ];+ const generatePhase = jest.fn(async () => ({ label: 'Combined both agent outcomes' }));+ const wiring = createActivityPhaseWiring({+ getContentParts: () => parts,+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase,+ });+ await wiring.hook(batch('tool-1'), new AbortController().signal);+ parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } });+ await wiring.hook(batch('tool-2'), new AbortController().signal);+ const handler = wiring.handlers({+ [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },+ })?.[GraphEvents.ON_RUN_STEP];+ const finalStep = {+ id: 'lane-final',+ groupId: 'lane-a',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'text', phase: 'final_answer' },+ },+ };+ handler?.handle(GraphEvents.ON_RUN_STEP, finalStep, undefined, undefined);+ await flushDetached();+ expect(generatePhase).not.toHaveBeenCalled();++ handler?.handle(+ GraphEvents.ON_RUN_STEP,+ { ...finalStep, id: 'root-final', groupId: undefined },+ undefined,+ undefined,+ );+ wiring.complete();+ await flushDetached();+ expect(generatePhase).toHaveBeenCalledTimes(1);+ });++ it('keeps unphased parallel text inside the run-wide fallback phase', async () => {+ const parts: LooseContentPart[] = [+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ ];+ const generatePhase = jest.fn(async () => ({ label: 'Combined both agent outcomes' }));+ const wiring = createActivityPhaseWiring({+ getContentParts: () => parts,+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase,+ });+ await wiring.hook(batch('tool-1'), new AbortController().signal);+ parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } });+ await wiring.hook(batch('tool-2'), new AbortController().signal);+ const handler = wiring.handlers({+ [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },+ })?.[GraphEvents.ON_RUN_STEP];+ const textStep = {+ id: 'lane-text',+ groupId: 'lane-a',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'text' },+ },+ };+ handler?.handle(GraphEvents.ON_RUN_STEP, textStep, undefined, undefined);+ await flushDetached();+ expect(generatePhase).not.toHaveBeenCalled();++ handler?.handle(+ GraphEvents.ON_RUN_STEP,+ { ...textStep, id: 'root-text', groupId: undefined },+ undefined,+ undefined,+ );+ await flushDetached();+ expect(generatePhase).not.toHaveBeenCalled();++ parts[2] = { type: ContentTypes.TEXT, text: 'Finished the run' };+ wiring.complete();+ await flushDetached();+ expect(generatePhase).toHaveBeenCalledTimes(1);+ /** The lane text stays inside, but the root's short answer is still the+ * run's visible reply and must not collapse into the parent card. */+ expect(parts[3]).toMatchObject({+ activity_start_index: 0,+ activity_end_index: 2,+ activity_count: 2,+ });+ });++ it('keeps short final semantic commentary inside a completion-finalized phase', async () => {+ const parts: LooseContentPart[] = [+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ ];+ const generatePhase = jest.fn(async () => ({ label: 'Completed the commentary phase' }));+ const wiring = createActivityPhaseWiring({+ getContentParts: () => parts,+ getStepIndex: (stepId) => (stepId === 'root-commentary' ? 2 : undefined),+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase,+ });+ await wiring.hook(batch('tool-1'), new AbortController().signal);+ parts[1] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } };+ await wiring.hook(batch('tool-2'), new AbortController().signal);+ const handler = wiring.handlers({+ [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },+ })?.[GraphEvents.ON_RUN_STEP];+ handler?.handle(+ GraphEvents.ON_RUN_STEP,+ {+ id: 'root-commentary',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'text', phase: 'commentary' },+ },+ },+ undefined,+ undefined,+ );+ parts[2] = { type: ContentTypes.TEXT, text: 'Intermediate commentary', phase: 'commentary' };wiring.complete();await flushDetached();expect(parts[3]).toMatchObject({activity_start_index: 0,- activity_end_index: 2,+ activity_end_index: 3,activity_count: 2,});});- it('leaves the last materialized text outside even when it retains a lane id', async () => {+ it('keeps short semantic commentary inside after earlier unphased text', async () => {const parts: LooseContentPart[] = [{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },- { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },- {- type: ContentTypes.TEXT,- text: 'The lane answer is complete.',- phase: 'final_answer',- groupId: 'lane-a',- },];+ const stepIndexes = new Map([+ ['root-text', 1],+ ['commentary', 3],+ ]);+ const generatePhase = jest.fn(async () => ({ label: 'Completed the commentary phase' }));const wiring = createActivityPhaseWiring({getContentParts: () => parts,+ getStepIndex: (stepId) => stepIndexes.get(stepId),bumpIndexOffset: jest.fn(),emitLabelEvent: jest.fn(async () => undefined),trackPendingFill: jest.fn(),- generatePhase: jest.fn(async () => ({ label: 'Completed the lane workflow' })),+ generatePhase,});await wiring.hook(batch('tool-1'), new AbortController().signal);+ const handler = wiring.handlers({+ [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },+ })?.[GraphEvents.ON_RUN_STEP];+ handler?.handle(+ GraphEvents.ON_RUN_STEP,+ {+ id: 'root-text',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'text' },+ },+ },+ undefined,+ undefined,+ );+ parts[1] = { type: ContentTypes.TEXT, text: 'I will keep investigating.' };+ parts[2] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } };await wiring.hook(batch('tool-2'), new AbortController().signal);+ handler?.handle(+ GraphEvents.ON_RUN_STEP,+ {+ id: 'commentary',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'text', phase: 'commentary' },+ },+ },+ undefined,+ undefined,+ );+ parts[3] = {+ type: ContentTypes.TEXT,+ text: 'The second search confirmed it.',+ phase: 'commentary',+ };wiring.complete();await flushDetached();- expect(parts[3]).toMatchObject({ activity_end_index: 2, activity_count: 2 });+ expect(parts[4]).toMatchObject({+ activity_start_index: 0,+ activity_end_index: 4,+ activity_count: 2,+ });});- it('skips a trailing empty text reservation when choosing the final boundary', async () => {+ it('keeps persisted short commentary inside the phase after HITL resume', async () => {const parts: LooseContentPart[] = [{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ { type: ContentTypes.TEXT, text: 'I will keep investigating.' },{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },- { type: ContentTypes.TEXT, text: 'The materialized answer is complete.' },- { type: ContentTypes.TEXT, text: '', phase: 'final_answer' },+ { type: ContentTypes.TEXT, text: 'The second search confirmed it.', phase: 'commentary' },];+ const generatePhase = jest.fn(async () => ({ label: 'Completed the resumed commentary' }));const wiring = createActivityPhaseWiring({+ initialSnapshot: {+ version: 1,+ generated: 0,+ activityCount: 2,+ failedActivityCount: 0,+ partialActivityCount: 0,+ agentIds: [],+ activities: [+ { startIndex: 0, status: 'success', toolCallIds: ['tool-1'] },+ { startIndex: 2, status: 'success', toolCallIds: ['tool-2'] },+ ],+ assistantContext: [],+ pendingReasoning: [],+ },getContentParts: () => parts,- getStepIndex: (stepId) => (stepId === 'empty-final' ? 3 : undefined),bumpIndexOffset: jest.fn(),emitLabelEvent: jest.fn(async () => undefined),trackPendingFill: jest.fn(),- generatePhase: jest.fn(async () => ({ label: 'Completed the workflow' })),+ generatePhase,});- await wiring.hook(batch('tool-1'), new AbortController().signal);- await wiring.hook(batch('tool-2'), new AbortController().signal);- wiring- .handlers({ [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() } })- ?.[GraphEvents.ON_RUN_STEP]?.handle(- GraphEvents.ON_RUN_STEP,- {- id: 'empty-final',- stepDetails: {- type: StepTypes.MESSAGE_CREATION,- message_creation: { message_id: 'm', content_type: 'text' },- },- },- undefined,- undefined,- );wiring.complete();await flushDetached();- expect(parts[4]).toMatchObject({ activity_end_index: 2, activity_count: 2 });+ expect(parts[4]).toMatchObject({+ activity_start_index: 0,+ activity_end_index: 4,+ activity_count: 2,+ });});- it('ignores an empty reasoning reservation after the materialized final text', async () => {- const parts: LooseContentPart[] = [- { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },- { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },- { type: ContentTypes.TEXT, text: 'The answer is complete.' },- { type: ContentTypes.THINK, think: '' },- ];+ /** The mock provider in e2e emits no phase metadata, so an unphased short+ * reply is the common real case, not an edge case. Length decides whether+ * intermediate text earns a boundary; the run's answer is always outside. */+ it('keeps a short unphased final answer outside the collapsed phase', async () => {+ const parts: LooseContentPart[] = [];+ const generatePhase = jest.fn(async () => ({ label: 'Completed the run' }));const wiring = createActivityPhaseWiring({getContentParts: () => parts,- getStepIndex: (stepId) => (stepId === 'empty-reasoning' ? 3 : undefined),bumpIndexOffset: jest.fn(),emitLabelEvent: jest.fn(async () => undefined),trackPendingFill: jest.fn(),- generatePhase: jest.fn(async () => ({ label: 'Completed the workflow' })),+ generatePhase,});+ parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } });await wiring.hook(batch('tool-1'), new AbortController().signal);+ parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } });await wiring.hook(batch('tool-2'), new AbortController().signal);- wiring- .handlers({- [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },- })- ?.[GraphEvents.ON_RUN_STEP]?.handle(- GraphEvents.ON_RUN_STEP,- {- id: 'empty-reasoning',- stepDetails: {- type: StepTypes.MESSAGE_CREATION,- message_creation: { message_id: 'm', content_type: 'think' },- },- },- undefined,- undefined,- );+ parts.push({ type: ContentTypes.TEXT, text: 'Done' });wiring.complete();await flushDetached();- expect(parts[4]).toMatchObject({ activity_end_index: 2, activity_count: 2 });+ expect(parts[3]).toMatchObject({+ activity_label_type: 'phase',+ activity_start_index: 0,+ activity_end_index: 2,+ activity_count: 2,+ });});- it('keeps a parallel lane final inside the run-wide phase', async () => {- const parts: LooseContentPart[] = [- { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },- ];- const generatePhase = jest.fn(async () => ({ label: 'Combined both agent outcomes' }));+ it('summarizes all activities and short text once at root-run completion', async () => {+ const parts: LooseContentPart[] = [];+ const stepIndexes = new Map([+ ['intermediate-text', 2],+ ['final-text', 5],+ ]);+ const generatePhase = jest.fn(async () => ({ label: 'Completed the full investigation' }));const wiring = createActivityPhaseWiring({getContentParts: () => parts,+ getStepIndex: (stepId) => stepIndexes.get(stepId),bumpIndexOffset: jest.fn(),emitLabelEvent: jest.fn(async () => undefined),trackPendingFill: jest.fn(),generatePhase,});- await wiring.hook(batch('tool-1'), new AbortController().signal);- parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } });- await wiring.hook(batch('tool-2'), new AbortController().signal);const handler = wiring.handlers({[GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },})?.[GraphEvents.ON_RUN_STEP];- const finalStep = {- id: 'lane-final',- groupId: 'lane-a',- stepDetails: {- type: StepTypes.MESSAGE_CREATION,- message_creation: { message_id: 'm', content_type: 'text', phase: 'final_answer' },++ parts[0] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } };+ await wiring.hook(batch('tool-1'), new AbortController().signal);+ parts[1] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } };+ await wiring.hook(batch('tool-2'), new AbortController().signal);+ handler?.handle(+ GraphEvents.ON_RUN_STEP,+ {+ id: 'intermediate-text',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'text' },+ },},- };- handler?.handle(GraphEvents.ON_RUN_STEP, finalStep, undefined, undefined);- await flushDetached();- expect(generatePhase).not.toHaveBeenCalled();+ undefined,+ undefined,+ );+ parts[2] = { type: ContentTypes.TEXT, text: 'I will try another approach.' };+ parts[3] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-3' } };+ await wiring.hook(batch('tool-3'), new AbortController().signal);+ parts[4] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-4' } };+ await wiring.hook(batch('tool-4'), new AbortController().signal);handler?.handle(GraphEvents.ON_RUN_STEP,- { ...finalStep, id: 'root-final', groupId: undefined },+ {+ id: 'final-text',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'text' },+ },+ },undefined,undefined,);+ parts[5] = { type: ContentTypes.TEXT, text: 'The investigation is complete.' };+ parts[6] = {+ type: ContentTypes.ACTIVITY_LABEL,+ [ContentTypes.ACTIVITY_LABEL]: 'Recorded the delayed child result',+ tool_call_ids: ['tool-4'],+ pending: false,+ };++ expect(generatePhase).not.toHaveBeenCalled();+ wiring.complete();await flushDetached();+expect(generatePhase).toHaveBeenCalledTimes(1);+ expect(generatePhase).toHaveBeenCalledWith(expect.objectContaining({ totalActivityCount: 4 }));+ expect(parts[7]).toMatchObject({+ activity_label_type: 'phase',+ activity_start_index: 0,+ activity_end_index: 5,+ activity_count: 4,+ });});- it('keeps unphased parallel text inside the run-wide fallback phase', async () => {- const parts: LooseContentPart[] = [- { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },- ];- const generatePhase = jest.fn(async () => ({ label: 'Combined both agent outcomes' }));+ it('keeps later activities grouped when the last root text preceded them', async () => {+ const parts: LooseContentPart[] = [{ type: ContentTypes.TEXT, text: 'I will investigate.' }];+ const generatePhase = jest.fn(async () => ({ label: 'Completed the direct-return workflow' }));const wiring = createActivityPhaseWiring({getContentParts: () => parts,+ getStepIndex: (stepId) => (stepId === 'root-text' ? 0 : undefined),bumpIndexOffset: jest.fn(),emitLabelEvent: jest.fn(async () => undefined),trackPendingFill: jest.fn(),generatePhase,});- await wiring.hook(batch('tool-1'), new AbortController().signal);- parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } });- await wiring.hook(batch('tool-2'), new AbortController().signal);const handler = wiring.handlers({[GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },})?.[GraphEvents.ON_RUN_STEP];- const textStep = {- id: 'lane-text',- groupId: 'lane-a',- stepDetails: {- type: StepTypes.MESSAGE_CREATION,- message_creation: { message_id: 'm', content_type: 'text' },- },- };- handler?.handle(GraphEvents.ON_RUN_STEP, textStep, undefined, undefined);- await flushDetached();- expect(generatePhase).not.toHaveBeenCalled();-handler?.handle(GraphEvents.ON_RUN_STEP,- { ...textStep, id: 'root-text', groupId: undefined },+ {+ id: 'root-text',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'text' },+ },+ },undefined,undefined,);- await flushDetached();- expect(generatePhase).not.toHaveBeenCalled();+ parts[1] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } };+ await wiring.hook(batch('tool-1'), new AbortController().signal);+ parts[2] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } };+ await wiring.hook(batch('tool-2'), new AbortController().signal);- parts[2] = { type: ContentTypes.TEXT, text: 'Finished the run' };wiring.complete();await flushDetached();+expect(generatePhase).toHaveBeenCalledTimes(1);expect(parts[3]).toMatchObject({activity_start_index: 0,- activity_end_index: 2,+ activity_end_index: 3,activity_count: 2,});});- it('leaves final semantic commentary outside a completion-finalized phase', async () => {+ it('keeps a parallel tool batch grouped when it straddles the last root text', async () => {const parts: LooseContentPart[] = [{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'parallel-1' } },];- const generatePhase = jest.fn(async () => ({ label: 'Completed the commentary phase' }));+ const generatePhase = jest.fn(async () => ({ label: 'Completed the parallel workflow' }));const wiring = createActivityPhaseWiring({getContentParts: () => parts,- getStepIndex: (stepId) => (stepId === 'root-commentary' ? 2 : undefined),+ getStepIndex: (stepId) => (stepId === 'root-text' ? 2 : undefined),bumpIndexOffset: jest.fn(),emitLabelEvent: jest.fn(async () => undefined),trackPendingFill: jest.fn(),generatePhase,});await wiring.hook(batch('tool-1'), new AbortController().signal);- parts[1] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } };- await wiring.hook(batch('tool-2'), new AbortController().signal);+ const parallelBatch = batch('parallel-1');+ parallelBatch.entries.push({+ ...parallelBatch.entries[0],+ toolUseId: 'parallel-2',+ toolInput: { query: 'parallel-2' },+ toolOutput: 'parallel-2-result',+ });+ await wiring.hook(parallelBatch, new AbortController().signal);const handler = wiring.handlers({[GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },})?.[GraphEvents.ON_RUN_STEP];handler?.handle(GraphEvents.ON_RUN_STEP,{- id: 'root-commentary',+ id: 'root-text',stepDetails: {type: StepTypes.MESSAGE_CREATION,- message_creation: { message_id: 'm', content_type: 'text', phase: 'commentary' },+ message_creation: { message_id: 'm', content_type: 'text' },},},undefined,undefined,);- parts[2] = { type: ContentTypes.TEXT, text: 'Intermediate commentary', phase: 'commentary' };+ parts[2] = { type: ContentTypes.TEXT, text: 'The parallel work may be complete.' };+ parts[3] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'parallel-2' } };wiring.complete();await flushDetached();- expect(parts[3]).toMatchObject({+ expect(generatePhase).toHaveBeenCalledTimes(1);+ expect(parts[4]).toMatchObject({activity_start_index: 0,- activity_end_index: 2,+ activity_end_index: 4,activity_count: 2,});});- it('leaves the last semantic commentary outside after earlier unphased text', async () => {+ it('preserves mixed batch failures as a partial phase outcome', async () => {+ const mixed = batch('tool-1');+ mixed.entries.push({+ toolName: 'web_search',+ toolInput: { query: 'failed' },+ toolUseId: 'tool-1b',+ status: 'error',+ error: 'unavailable',+ });const parts: LooseContentPart[] = [{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1b' } },];- const stepIndexes = new Map([- ['root-text', 1],- ['commentary', 3],- ]);- const generatePhase = jest.fn(async () => ({ label: 'Completed the commentary phase' }));+ const generatePhase = jest.fn(async () => ({ label: 'Recovered part of the search scope' }));const wiring = createActivityPhaseWiring({getContentParts: () => parts,- getStepIndex: (stepId) => stepIndexes.get(stepId),bumpIndexOffset: jest.fn(),emitLabelEvent: jest.fn(async () => undefined),trackPendingFill: jest.fn(),generatePhase,});+ await wiring.hook(mixed, new AbortController().signal);+ parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } });+ await wiring.hook(batch('tool-2'), new AbortController().signal);+ wiring+ .handlers({+ [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },+ })+ ?.[GraphEvents.ON_RUN_STEP]?.handle(+ GraphEvents.ON_RUN_STEP,+ {+ id: 'final-step',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'text', phase: 'final_answer' },+ },+ },+ undefined,+ undefined,+ );++ wiring.complete();+ await flushDetached();+ expect(generatePhase).toHaveBeenCalledWith(expect.objectContaining({ status: 'partial' }));+ expect(parts[parts.length - 1]).toMatchObject({ status: 'partial' });+ });++ it('collects usage after a committed blank phase result', async () => {+ const parts: LooseContentPart[] = [+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ ];+ const collectUsage = jest.fn(async () => undefined);+ const wiring = createActivityPhaseWiring({+ getContentParts: () => parts,+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase: jest.fn(async () => ({ collectUsage })),+ });await wiring.hook(batch('tool-1'), new AbortController().signal);- const handler = wiring.handlers({+ parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } });+ await wiring.hook(batch('tool-2'), new AbortController().signal);+ wiring+ .handlers({+ [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },+ })+ ?.[GraphEvents.ON_RUN_STEP]?.handle(+ GraphEvents.ON_RUN_STEP,+ {+ id: 'final-step',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'text', phase: 'final_answer' },+ },+ },+ undefined,+ undefined,+ );++ wiring.complete();+ await flushDetached();+ expect(collectUsage).toHaveBeenCalledWith(undefined);+ expect(parts[parts.length - 1]).toMatchObject({ activity_label: '', pending: false });+ });++ it('ignores late tool hooks already covered by an emitted phase', async () => {+ const parts: LooseContentPart[] = [+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'late-tool-1' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'late-tool-2' } },+ ];+ const generatePhase = jest.fn(async () => ({ label: 'Completed the covered work' }));+ const wiring = createActivityPhaseWiring({+ getContentParts: () => parts,+ getStepIndex: (stepId) => (stepId === 'boundary' ? 4 : undefined),+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase,+ });+ await wiring.hook(batch('tool-1'), new AbortController().signal);+ await wiring.hook(batch('tool-2'), new AbortController().signal);+ const handlers = wiring.handlers({[GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },- })?.[GraphEvents.ON_RUN_STEP];- handler?.handle(+ [GraphEvents.ON_MESSAGE_DELTA]: {+ handle: (_event, data) => {+ const delta = data as { delta?: { content?: { text?: string } } };+ parts[4] = { type: ContentTypes.TEXT, text: delta.delta?.content?.text ?? '' };+ },+ },+ });+ handlers?.[GraphEvents.ON_RUN_STEP]?.handle(GraphEvents.ON_RUN_STEP,{- id: 'root-text',+ id: 'boundary',stepDetails: {type: StepTypes.MESSAGE_CREATION,message_creation: { message_id: 'm', content_type: 'text' },@@ -1763,170 +2965,174 @@ describe('createActivityPhaseWiring', () => {undefined,undefined,);- parts[1] = { type: ContentTypes.TEXT, text: 'I will keep investigating.' };- parts[2] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } };- await wiring.hook(batch('tool-2'), new AbortController().signal);- handler?.handle(- GraphEvents.ON_RUN_STEP,+ handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.handle(+ GraphEvents.ON_MESSAGE_DELTA,{- id: 'commentary',- stepDetails: {- type: StepTypes.MESSAGE_CREATION,- message_creation: { message_id: 'm', content_type: 'text', phase: 'commentary' },- },+ id: 'boundary',+ delta: { content: { type: ContentTypes.TEXT, text: substantialText('Boundary result.') } },},undefined,undefined,);- parts[3] = {- type: ContentTypes.TEXT,- text: 'The second search confirmed it.',- phase: 'commentary',- };+ await wiring.hook(batch('late-tool-1'), new AbortController().signal);+ await wiring.hook(batch('late-tool-2'), new AbortController().signal);wiring.complete();await flushDetached();- expect(parts[4]).toMatchObject({- activity_start_index: 0,- activity_end_index: 3,- activity_count: 2,- });+ expect(generatePhase).toHaveBeenCalledTimes(1);+ expect(parts.filter((part) => part.activity_label_type === 'phase')).toHaveLength(1);+ expect(wiring.snapshot().activityCount).toBe(0);});- it('leaves persisted final commentary outside the phase after HITL resume', async () => {+ it('retains uncovered calls from a delayed straddling tool batch', async () => {const parts: LooseContentPart[] = [{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },- { type: ContentTypes.TEXT, text: 'I will keep investigating.' },{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },- { type: ContentTypes.TEXT, text: 'The second search confirmed it.', phase: 'commentary' },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'covered-call' } },+ { type: ContentTypes.TEXT, text: substantialText('Boundary result.') },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'uncovered-call' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-3' } },];- const generatePhase = jest.fn(async () => ({ label: 'Completed the resumed commentary' }));+ const payloads: GenerateActivityPhasePayload[] = [];const wiring = createActivityPhaseWiring({- initialSnapshot: {- version: 1,- generated: 0,- activityCount: 2,- failedActivityCount: 0,- partialActivityCount: 0,- agentIds: [],- activities: [- { startIndex: 0, status: 'success', toolCallIds: ['tool-1'] },- { startIndex: 2, status: 'success', toolCallIds: ['tool-2'] },- ],- assistantContext: [],- pendingReasoning: [],- },getContentParts: () => parts,bumpIndexOffset: jest.fn(),emitLabelEvent: jest.fn(async () => undefined),trackPendingFill: jest.fn(),- generatePhase,+ generatePhase: jest.fn(async (payload: GenerateActivityPhasePayload) => {+ payloads.push(payload);+ return { label: 'Completed one phase' };+ }),});+ await wiring.hook(batch('tool-1'), new AbortController().signal);+ await wiring.hook(batch('tool-2'), new AbortController().signal);+ wiring.complete();+ const delayedBatch = batch('covered-call');+ delayedBatch.entries.push({+ ...delayedBatch.entries[0],+ toolUseId: 'uncovered-call',+ toolInput: { query: 'uncovered-call' },+ });+ await wiring.hook(delayedBatch, new AbortController().signal);+ await wiring.hook(batch('tool-3'), new AbortController().signal);wiring.complete();await flushDetached();- expect(parts[4]).toMatchObject({- activity_start_index: 0,- activity_end_index: 3,- activity_count: 2,+ expect(payloads.map(({ totalActivityCount }) => totalActivityCount)).toEqual([2, 2]);+ expect(payloads[1].activities[0]).toMatchObject({+ entries: [expect.objectContaining({ toolInput: { query: 'uncovered-call' } })],});});- it('summarizes all unphased activities once at root-run completion', async () => {- const parts: LooseContentPart[] = [];- const stepIndexes = new Map([- ['intermediate-text', 2],- ['final-text', 5],- ]);- const generatePhase = jest.fn(async () => ({ label: 'Completed the full investigation' }));+ it('keeps a short semantic final answer outside the collapsed phase', async () => {+ const parts: LooseContentPart[] = [+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },+ ];const wiring = createActivityPhaseWiring({getContentParts: () => parts,- getStepIndex: (stepId) => stepIndexes.get(stepId),+ getStepIndex: (stepId) => (stepId === 'final-step' ? 2 : undefined),bumpIndexOffset: jest.fn(),emitLabelEvent: jest.fn(async () => undefined),trackPendingFill: jest.fn(),- generatePhase,+ generatePhase: jest.fn(async () => ({ label: 'Completed the requested work' })),});- const handler = wiring.handlers({- [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },- })?.[GraphEvents.ON_RUN_STEP];-- parts[0] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } };await wiring.hook(batch('tool-1'), new AbortController().signal);- parts[1] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } };await wiring.hook(batch('tool-2'), new AbortController().signal);- handler?.handle(+ const handlers = wiring.handlers({+ [GraphEvents.ON_RUN_STEP]: {+ handle: () => {+ parts[2] = { type: ContentTypes.TEXT, text: '', phase: 'final_answer' };+ },+ },+ [GraphEvents.ON_MESSAGE_DELTA]: {+ handle: (_event, data) => {+ const delta = data as { delta?: { content?: { text?: string } } };+ parts[2] = {+ type: ContentTypes.TEXT,+ text: `${parts[2]?.text ?? ''}${delta.delta?.content?.text ?? ''}`,+ phase: 'final_answer',+ };+ },+ },+ });+ handlers?.[GraphEvents.ON_RUN_STEP]?.handle(GraphEvents.ON_RUN_STEP,{- id: 'intermediate-text',+ id: 'final-step',stepDetails: {type: StepTypes.MESSAGE_CREATION,- message_creation: { message_id: 'm', content_type: 'text' },+ message_creation: { message_id: 'm', content_type: 'text', phase: 'final_answer' },},},undefined,undefined,);- parts[2] = { type: ContentTypes.TEXT, text: 'I will try another approach.' };-- parts[3] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-3' } };- await wiring.hook(batch('tool-3'), new AbortController().signal);- parts[4] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-4' } };- await wiring.hook(batch('tool-4'), new AbortController().signal);- handler?.handle(- GraphEvents.ON_RUN_STEP,+ handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.handle(+ GraphEvents.ON_MESSAGE_DELTA,{- id: 'final-text',- stepDetails: {- type: StepTypes.MESSAGE_CREATION,- message_creation: { message_id: 'm', content_type: 'text' },- },+ id: 'final-step',+ delta: { content: { type: ContentTypes.TEXT, text: 'Done.' } },},undefined,undefined,- );- parts[5] = { type: ContentTypes.TEXT, text: 'The investigation is complete.' };- parts[6] = {- type: ContentTypes.ACTIVITY_LABEL,- [ContentTypes.ACTIVITY_LABEL]: 'Recorded the delayed child result',- tool_call_ids: ['tool-4'],- pending: false,- };-- expect(generatePhase).not.toHaveBeenCalled();- wiring.complete();+ );await flushDetached();- expect(generatePhase).toHaveBeenCalledTimes(1);- expect(generatePhase).toHaveBeenCalledWith(expect.objectContaining({ totalActivityCount: 4 }));- expect(parts[7]).toMatchObject({+ expect(parts[2]).toMatchObject({ type: ContentTypes.TEXT, text: 'Done.' });+ expect(parts[3]).toMatchObject({activity_label_type: 'phase',activity_start_index: 0,- activity_end_index: 5,- activity_count: 4,+ activity_end_index: 2,+ activity_count: 2,});});- it('keeps later activities grouped when the last root text preceded them', async () => {- const parts: LooseContentPart[] = [{ type: ContentTypes.TEXT, text: 'I will investigate.' }];- const generatePhase = jest.fn(async () => ({ label: 'Completed the direct-return workflow' }));+ it('closes context rendered before the boundary despite a later activity position', async () => {+ const parts: LooseContentPart[] = [+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },+ ];+ const payloads: GenerateActivityPhasePayload[] = [];const wiring = createActivityPhaseWiring({getContentParts: () => parts,- getStepIndex: (stepId) => (stepId === 'root-text' ? 0 : undefined),+ getStepIndex: (stepId) => (stepId === 'early-text' ? 2 : undefined),bumpIndexOffset: jest.fn(),emitLabelEvent: jest.fn(async () => undefined),trackPendingFill: jest.fn(),- generatePhase,+ generatePhase: jest.fn(async (payload: GenerateActivityPhasePayload) => {+ payloads.push(payload);+ return { label: 'Completed one phase' };+ }),});- const handler = wiring.handlers({+ await wiring.hook(batch('tool-1'), new AbortController().signal);+ await wiring.hook(batch('tool-2'), new AbortController().signal);+ parts[4] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-3' } };+ /** This activity renders after the boundary, so it is retained and the+ * closing count stays at two while the registration counter reaches+ * three — the text registered next is nonetheless rendered earlier. */+ await wiring.hook(batch('tool-3'), new AbortController().signal);+ const handlers = wiring.handlers({[GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },- })?.[GraphEvents.ON_RUN_STEP];- handler?.handle(+ [GraphEvents.ON_MESSAGE_DELTA]: {+ handle: (_event, data) => {+ const delta = data as { id?: string; delta?: { content?: { text?: string } } };+ if (delta.id === 'early-text') {+ parts[2] = {+ type: ContentTypes.TEXT,+ text: `${parts[2]?.text ?? ''}${delta.delta?.content?.text ?? ''}`,+ };+ }+ },+ },+ });+ handlers?.[GraphEvents.ON_RUN_STEP]?.handle(GraphEvents.ON_RUN_STEP,{- id: 'root-text',+ id: 'early-text',+ groupId: 'parallel',stepDetails: {type: StepTypes.MESSAGE_CREATION,message_creation: { message_id: 'm', content_type: 'text' },@@ -1935,52 +3141,109 @@ describe('createActivityPhaseWiring', () => {undefined,undefined,);- parts[1] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } };- await wiring.hook(batch('tool-1'), new AbortController().signal);- parts[2] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } };- await wiring.hook(batch('tool-2'), new AbortController().signal);+ handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.handle(+ GraphEvents.ON_MESSAGE_DELTA,+ {+ id: 'early-text',+ delta: { content: { type: ContentTypes.TEXT, text: 'Context for the earlier work.' } },+ },+ undefined,+ undefined,+ );+ parts[3] = { type: ContentTypes.TEXT, text: substantialText('Boundary result.') };wiring.complete();await flushDetached();- expect(generatePhase).toHaveBeenCalledTimes(1);- expect(parts[3]).toMatchObject({- activity_start_index: 0,- activity_end_index: 3,- activity_count: 2,+ expect(payloads[0]?.assistantContext).toEqual(['Context for the earlier work.']);+ });++ it('keeps ambiguously matched restored context on its saved side', async () => {+ const parts: LooseContentPart[] = [+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },+ { type: ContentTypes.TEXT, text: 'Shared excerpt.' },+ { type: ContentTypes.TEXT, text: substantialText('Boundary result.') },+ { type: ContentTypes.TEXT, text: 'Later text repeating Shared excerpt.' },+ ];+ const payloads: GenerateActivityPhasePayload[] = [];+ const wiring = createActivityPhaseWiring({+ initialSnapshot: {+ version: 3,+ generated: 0,+ activityCount: 2,+ failedActivityCount: 0,+ partialActivityCount: 0,+ agentIds: [],+ activities: [+ { startIndex: 0, status: 'success' as const, toolCallIds: ['tool-1'] },+ { startIndex: 1, status: 'success' as const, toolCallIds: ['tool-2'] },+ ],+ /** Restored entries carry no step id, so the excerpt is located by+ * text alone and its repetition after the boundary is not proof. */+ assistantContext: [{ text: 'Shared excerpt.', activityPosition: 0 }],+ pendingReasoning: [],+ },+ getContentParts: () => parts,+ bumpIndexOffset: jest.fn(),+ emitLabelEvent: jest.fn(async () => undefined),+ trackPendingFill: jest.fn(),+ generatePhase: jest.fn(async (payload: GenerateActivityPhasePayload) => {+ payloads.push(payload);+ return { label: 'Completed the resumed phase' };+ }),});++ wiring.complete();+ await flushDetached();++ expect(payloads[0]?.assistantContext).toEqual(['Shared excerpt.']);});- it('keeps a parallel tool batch grouped when it straddles the last root text', async () => {+ it('retains earlier-position context rendered after a substantial boundary', async () => {const parts: LooseContentPart[] = [{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },- { type: ContentTypes.TOOL_CALL, tool_call: { id: 'parallel-1' } },];- const generatePhase = jest.fn(async () => ({ label: 'Completed the parallel workflow' }));+ const stepIndexes = new Map([+ ['boundary', 2],+ ['parallel-text', 3],+ ]);+ const payloads: GenerateActivityPhasePayload[] = [];const wiring = createActivityPhaseWiring({getContentParts: () => parts,- getStepIndex: (stepId) => (stepId === 'root-text' ? 2 : undefined),+ getStepIndex: (stepId) => stepIndexes.get(stepId),bumpIndexOffset: jest.fn(),emitLabelEvent: jest.fn(async () => undefined),trackPendingFill: jest.fn(),- generatePhase,+ generatePhase: jest.fn(async (payload: GenerateActivityPhasePayload) => {+ payloads.push(payload);+ return { label: 'Completed one phase' };+ }),});await wiring.hook(batch('tool-1'), new AbortController().signal);- const parallelBatch = batch('parallel-1');- parallelBatch.entries.push({- ...parallelBatch.entries[0],- toolUseId: 'parallel-2',- toolInput: { query: 'parallel-2' },- toolOutput: 'parallel-2-result',- });- await wiring.hook(parallelBatch, new AbortController().signal);- const handler = wiring.handlers({+ const handlers = wiring.handlers({[GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },- })?.[GraphEvents.ON_RUN_STEP];- handler?.handle(+ [GraphEvents.ON_MESSAGE_DELTA]: {+ handle: (_event, data) => {+ const delta = data as { id?: string; delta?: { content?: { text?: string } } };+ const index = stepIndexes.get(delta.id ?? '');+ if (index != null) {+ parts[index] = {+ type: ContentTypes.TEXT,+ text: `${parts[index]?.text ?? ''}${delta.delta?.content?.text ?? ''}`,+ };+ }+ },+ },+ });+ /** The parallel lane registers while only one activity has been tracked,+ * so its activity position is below the closing count even though it+ * renders after the boundary. */+ handlers?.[GraphEvents.ON_RUN_STEP]?.handle(GraphEvents.ON_RUN_STEP,{- id: 'root-text',+ id: 'parallel-text',+ groupId: 'parallel',stepDetails: {type: StepTypes.MESSAGE_CREATION,message_creation: { message_id: 'm', content_type: 'text' },@@ -1989,101 +3252,203 @@ describe('createActivityPhaseWiring', () => {undefined,undefined,);- parts[2] = { type: ContentTypes.TEXT, text: 'The parallel work may be complete.' };- parts[3] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'parallel-2' } };+ parts[1] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } };+ await wiring.hook(batch('tool-2'), new AbortController().signal);+ handlers?.[GraphEvents.ON_RUN_STEP]?.handle(+ GraphEvents.ON_RUN_STEP,+ {+ id: 'boundary',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'text' },+ },+ },+ undefined,+ undefined,+ );+ handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.handle(+ GraphEvents.ON_MESSAGE_DELTA,+ {+ id: 'parallel-text',+ delta: { content: { type: ContentTypes.TEXT, text: 'Context for the later work.' } },+ },+ undefined,+ undefined,+ );+ handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.handle(+ GraphEvents.ON_MESSAGE_DELTA,+ {+ id: 'boundary',+ delta: { content: { type: ContentTypes.TEXT, text: substantialText('Boundary result.') } },+ },+ undefined,+ undefined,+ );+ parts[5] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-3' } };+ parts[6] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-4' } };+ await wiring.hook(batch('tool-3'), new AbortController().signal);+ await wiring.hook(batch('tool-4'), new AbortController().signal);wiring.complete();await flushDetached();- expect(generatePhase).toHaveBeenCalledTimes(1);- expect(parts[4]).toMatchObject({- activity_start_index: 0,- activity_end_index: 4,- activity_count: 2,- });+ expect(payloads).toHaveLength(2);+ expect(payloads[0].assistantContext).toBeUndefined();+ expect(payloads[1].assistantContext).toEqual(['Context for the later work.']);});- it('preserves mixed batch failures as a partial phase outcome', async () => {- const mixed = batch('tool-1');- mixed.entries.push({- toolName: 'web_search',- toolInput: { query: 'failed' },- toolUseId: 'tool-1b',- status: 'error',- error: 'unavailable',- });+ it('retains equal-position context rendered after a substantial boundary', async () => {const parts: LooseContentPart[] = [{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },- { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1b' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },];- const generatePhase = jest.fn(async () => ({ label: 'Recovered part of the search scope' }));+ const stepIndexes = new Map([+ ['boundary', 2],+ ['parallel-text', 3],+ ]);+ const payloads: GenerateActivityPhasePayload[] = [];const wiring = createActivityPhaseWiring({getContentParts: () => parts,+ getStepIndex: (stepId) => stepIndexes.get(stepId),bumpIndexOffset: jest.fn(),emitLabelEvent: jest.fn(async () => undefined),trackPendingFill: jest.fn(),- generatePhase,+ generatePhase: jest.fn(async (payload: GenerateActivityPhasePayload) => {+ payloads.push(payload);+ return { label: 'Completed one phase' };+ }),});- await wiring.hook(mixed, new AbortController().signal);- parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } });+ await wiring.hook(batch('tool-1'), new AbortController().signal);await wiring.hook(batch('tool-2'), new AbortController().signal);- wiring- .handlers({- [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },- })- ?.[GraphEvents.ON_RUN_STEP]?.handle(+ const handlers = wiring.handlers({+ [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },+ [GraphEvents.ON_MESSAGE_DELTA]: {+ handle: (_event, data) => {+ const delta = data as { id?: string; delta?: { content?: { text?: string } } };+ const index = stepIndexes.get(delta.id ?? '');+ if (index != null) {+ parts[index] = {+ type: ContentTypes.TEXT,+ text: `${parts[index]?.text ?? ''}${delta.delta?.content?.text ?? ''}`,+ };+ }+ },+ },+ });+ for (const id of ['boundary', 'parallel-text']) {+ handlers?.[GraphEvents.ON_RUN_STEP]?.handle(GraphEvents.ON_RUN_STEP,{- id: 'final-step',+ id,+ groupId: id === 'parallel-text' ? 'parallel' : undefined,stepDetails: {type: StepTypes.MESSAGE_CREATION,- message_creation: { message_id: 'm', content_type: 'text', phase: 'final_answer' },+ message_creation: { message_id: 'm', content_type: 'text' },},},undefined,undefined,);+ }+ handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.handle(+ GraphEvents.ON_MESSAGE_DELTA,+ {+ id: 'parallel-text',+ delta: { content: { type: ContentTypes.TEXT, text: 'Context for the later work.' } },+ },+ undefined,+ undefined,+ );+ handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.handle(+ GraphEvents.ON_MESSAGE_DELTA,+ {+ id: 'boundary',+ delta: { content: { type: ContentTypes.TEXT, text: substantialText('Boundary result.') } },+ },+ undefined,+ undefined,+ );+ parts[5] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-3' } };+ parts[6] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-4' } };+ await wiring.hook(batch('tool-3'), new AbortController().signal);+ await wiring.hook(batch('tool-4'), new AbortController().signal);+ wiring.complete();await flushDetached();- expect(generatePhase).toHaveBeenCalledWith(expect.objectContaining({ status: 'partial' }));- expect(parts[parts.length - 1]).toMatchObject({ status: 'partial' });++ expect(payloads).toHaveLength(2);+ expect(payloads[0].assistantContext).toBeUndefined();+ expect(payloads[1].assistantContext).toEqual(['Context for the later work.']);});- it('collects usage after a committed blank phase result', async () => {+ it('retains a completed tool batch when any call crosses a substantial boundary', async () => {const parts: LooseContentPart[] = [{ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-1' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'parallel-1' } },+ { type: ContentTypes.TEXT, text: '' },+ { type: ContentTypes.TOOL_CALL, tool_call: { id: 'parallel-2' } },];- const collectUsage = jest.fn(async () => undefined);+ const payloads: GenerateActivityPhasePayload[] = [];const wiring = createActivityPhaseWiring({getContentParts: () => parts,+ getStepIndex: (stepId) => (stepId === 'boundary' ? 3 : undefined),bumpIndexOffset: jest.fn(),emitLabelEvent: jest.fn(async () => undefined),trackPendingFill: jest.fn(),- generatePhase: jest.fn(async () => ({ collectUsage })),+ generatePhase: jest.fn(async (payload: GenerateActivityPhasePayload) => {+ payloads.push(payload);+ return { label: 'Completed one phase' };+ }),});await wiring.hook(batch('tool-1'), new AbortController().signal);- parts.push({ type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-2' } });await wiring.hook(batch('tool-2'), new AbortController().signal);- wiring- .handlers({- [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },- })- ?.[GraphEvents.ON_RUN_STEP]?.handle(- GraphEvents.ON_RUN_STEP,- {- id: 'final-step',- stepDetails: {- type: StepTypes.MESSAGE_CREATION,- message_creation: { message_id: 'm', content_type: 'text', phase: 'final_answer' },- },+ const parallelBatch = batch('parallel-1');+ parallelBatch.entries.push({+ ...parallelBatch.entries[0],+ toolUseId: 'parallel-2',+ toolInput: { query: 'parallel-2' },+ });+ await wiring.hook(parallelBatch, new AbortController().signal);+ const handlers = wiring.handlers({+ [GraphEvents.ON_RUN_STEP]: { handle: jest.fn() },+ [GraphEvents.ON_MESSAGE_DELTA]: {+ handle: (_event, data) => {+ const delta = data as { delta?: { content?: { text?: string } } };+ parts[3] = { type: ContentTypes.TEXT, text: delta.delta?.content?.text ?? '' };},- undefined,- undefined,- );+ },+ });+ handlers?.[GraphEvents.ON_RUN_STEP]?.handle(+ GraphEvents.ON_RUN_STEP,+ {+ id: 'boundary',+ stepDetails: {+ type: StepTypes.MESSAGE_CREATION,+ message_creation: { message_id: 'm', content_type: 'text' },+ },+ },+ undefined,+ undefined,+ );+ handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.handle(+ GraphEvents.ON_MESSAGE_DELTA,+ {+ id: 'boundary',+ delta: { content: { type: ContentTypes.TEXT, text: substantialText('Boundary result.') } },+ },+ undefined,+ undefined,+ );+ parts[6] = { type: ContentTypes.TOOL_CALL, tool_call: { id: 'tool-3' } };+ await wiring.hook(batch('tool-3'), new AbortController().signal);+ wiring.complete();await flushDetached();- expect(collectUsage).toHaveBeenCalledWith(undefined);- expect(parts[parts.length - 1]).toMatchObject({ activity_label: '', pending: false });++ expect(payloads.map(({ totalActivityCount }) => totalActivityCount)).toEqual([2, 2]);+ expect(parts[5]).toMatchObject({ activity_end_index: 3, activity_count: 2 });+ expect(parts[7]).toMatchObject({ activity_start_index: 4, activity_count: 2 });});});diff --git a/packages/api/src/agents/activityPhases/runtime.ts b/packages/api/src/agents/activityPhases/runtime.tsindex 89037f5379..371369ce51 100644--- a/packages/api/src/agents/activityPhases/runtime.ts+++ b/packages/api/src/agents/activityPhases/runtime.ts@@ -6,7 +6,7 @@ import { stringifyActivityEvidence } from '~/agents/activityLabels/runtime';type PostToolBatchInput = HookInputByEvent['PostToolBatch'];type BatchEntry = PostToolBatchInput['entries'][number];-type AssistantContextEntry = { stepId?: string; text: string };+type AssistantContextEntry = { stepId?: string; text: string; activityPosition?: number };export type AssistantTextPhase = 'commentary' | 'final_answer';@@ -24,8 +24,21 @@ export interface ActivityPhaseEntry {status?: 'success' | 'partial' | 'error';}-type TrackedActivity = ActivityPhaseEntry & {+export type TrackedActivity = ActivityPhaseEntry & {startIndex: number;+ /** A prior boundary can retain only the materialized tail of a straddling batch. */+ partitionStartIndex?: number;+ /** Anchor-only activities keep position and status but carry no prompt evidence. */+ bounded?: boolean;+ /** Activities folded into this anchor once the anchor budget was reached.+ * Every counted activity therefore keeps a position, so a boundary can+ * partition counts instead of reconstructing them by subtraction. */+ mergedCount?: number;+ mergedFailedCount?: number;+ mergedPartialCount?: number;+ /** Agents whose activities were folded into this anchor, so attribution and+ * the summarizer payload keep every contributor the count represents. */+ mergedAgentIds?: string[];childLabelIndex?: number;/** Stable anchors survive content filtering and prepends across HITL resume. */toolCallIds?: string[];@@ -34,10 +47,16 @@ type TrackedActivity = ActivityPhaseEntry & {};export interface ActivityPhaseSnapshot {- version: 1;+ /** Version 2 introduces object-valued assistant context and overflow anchors.+ * Version 3 folds those anchors into `activities` so every counted activity+ * carries a position; readers still accept 1 and 2. */+ version: 1 | 2 | 3;generated: number;+ /** @deprecated Version 3 derives the total from positioned activities. */activityCount: number;+ /** @deprecated Version 3 derives failures from positioned activities. */failedActivityCount: number;+ /** @deprecated Version 3 derives partials from positioned activities. */partialActivityCount: number;agentIds: string[];activities: TrackedActivity[];@@ -49,7 +68,9 @@ export interface ActivityPhaseSnapshot {overflowReasoningExcerpt?: string;/** Bounded stable anchors for reasoning-only overflow after HITL content compaction. */overflowReasoningAnchors?: string[];- assistantContext: string[];+ /** Lightweight anchors retain per-activity partitioning beyond prompt evidence limits. */+ overflowActivities?: TrackedActivity[];+ assistantContext: Array<string | { text: string; activityPosition: number }>;pendingReasoning: Array<{key: string;text: string;@@ -110,11 +131,13 @@ const MIN_ACTIVITIES = 2;const MAX_CONTEXT_ITEMS = 6;const MAX_EXCERPT_CHARS = 600;const REASONING_ANCHOR_CHARS = 80;+const SUBSTANTIAL_TEXT_CHARS = 200;const OUTPUT_CHAR_LIMIT = 160;const PHASE_TIMEOUT_MS = 12_000;/** Twelve enter the SDK prompt; one extra preserves its omitted-activity row. */const MAX_RETAINED_ACTIVITIES = 13;const MAX_RETAINED_TOOL_ENTRIES = 6;+const MAX_OVERFLOW_ACTIVITY_ANCHORS = 64;export const ACTIVITY_PHASE_INSTRUCTION = `Summarize what this phase of an agent run accomplished. The result appears as the header of one collapsed parent group containing several activities.@@ -148,6 +171,12 @@ function textValue(value: unknown): string {return typeof nested === 'string' ? nested : '';}+function isSubstantialText(part: LooseContentPart | null | undefined): boolean {+ return (+ part?.type === ContentTypes.TEXT && textValue(part.text).trim().length > SUBSTANTIAL_TEXT_CHARS+ );+}+function normalizeLabel(value: string | undefined): string {const firstLine = value?.split(/\r?\n/).find((line) => line.trim().length > 0) ?? '';const normalized = firstLine.replace(/\s+/g, ' ').trim();@@ -192,86 +221,40 @@ function findLastPartIndex(return Math.max(0, parts.length - 1);}-function findBatchStart(+function findTrackedStart(parts: ReadonlyArray<LooseContentPart | null | undefined>,- toolCallIds: Set<string>,+ activity: TrackedActivity,): number {- let first = -1;- for (const index of definedPartIndices(parts)) {- const part = parts[index];- if (- part?.type === ContentTypes.TOOL_CALL &&- typeof part.tool_call?.id === 'string' &&- toolCallIds.has(part.tool_call.id)- ) {- first = first < 0 ? index : Math.min(first, index);- }- }- return first >= 0 ? first : Math.max(0, parts.length - 1);+ const materializedStart = findMaterializedActivityStart(parts, activity);+ const startIndex =+ materializedStart ?? Math.min(activity.startIndex, Math.max(0, parts.length - 1));+ return Math.max(startIndex, activity.partitionStartIndex ?? 0);}-function findTrackedStart(+function findMaterializedActivityStart(parts: ReadonlyArray<LooseContentPart | null | undefined>,activity: TrackedActivity,-): number {- const toolStart = findTrackedToolStart(parts, activity);+ toolIndices?: number[],+): number | undefined {+ const toolStart = (toolIndices ?? findTrackedToolIndices(parts, activity))[0];if (toolStart != null) {return toolStart;}const excerpt = activity.thinkingExcerpts?.[0]?.trim();if (excerpt) {- const reasoningStart = findReasoningExcerptStart(parts, excerpt);- if (reasoningStart != null) {- return reasoningStart;- }- }- return Math.min(activity.startIndex, Math.max(0, parts.length - 1));-}--function findReasoningExcerptStart(- parts: ReadonlyArray<LooseContentPart | null | undefined>,- excerpt: string,-): number | undefined {- const needle = excerpt.trim().slice(0, REASONING_ANCHOR_CHARS);- if (!needle) {- return undefined;- }- for (const index of definedPartIndices(parts)) {+ const reasoningStart = findReasoningStart(parts, excerpt, activity.startIndex);if (- parts[index]?.type === ContentTypes.THINK &&- textValue(parts[index]?.think).includes(needle)+ parts[reasoningStart]?.type === ContentTypes.THINK &&+ textValue(parts[reasoningStart]?.think).includes(+ excerpt.trim().slice(0, REASONING_ANCHOR_CHARS),+ )) {- return index;+ return reasoningStart;}}return undefined;}-function hasReasoningExcerptAtOrAfter(- parts: ReadonlyArray<LooseContentPart | null | undefined>,- excerpt: string,- minimumIndex: number,-): boolean {- const needle = excerpt.trim().slice(0, REASONING_ANCHOR_CHARS);- if (!needle) {- return false;- }- const indices = definedPartIndices(parts);- for (let position = indices.length - 1; position >= 0; position -= 1) {- const index = indices[position];- if (index < minimumIndex) {- break;- }- if (- parts[index]?.type === ContentTypes.THINK &&- textValue(parts[index]?.think).includes(needle)- ) {- return true;- }- }- return false;-}-type ReasoningAnchorIndex = Map<number, Set<string>>;function addReasoningAnchor(@@ -290,6 +273,18 @@ function addReasoningAnchor(} else {index.set(anchor.length, new Set([anchor]));}+ while (anchors.size > MAX_OVERFLOW_ACTIVITY_ANCHORS) {+ const oldest = anchors.values().next().value as string | undefined;+ if (oldest == null) {+ break;+ }+ anchors.delete(oldest);+ const matchingLength = index.get(oldest.length);+ matchingLength?.delete(oldest);+ if (matchingLength?.size === 0) {+ index.delete(oldest.length);+ }+ }}function includesReasoningAnchor(text: string, index: ReasoningAnchorIndex): boolean {@@ -303,45 +298,22 @@ function includesReasoningAnchor(text: string, index: ReasoningAnchorIndex): booreturn false;}-function hasIndexedReasoningAtOrAfter(- parts: ReadonlyArray<LooseContentPart | null | undefined>,- index: ReasoningAnchorIndex,- minimumIndex: number,-): boolean {- if (index.size === 0) {- return false;- }- const indices = definedPartIndices(parts);- for (let position = indices.length - 1; position >= 0; position -= 1) {- const partIndex = indices[position];- if (partIndex < minimumIndex) {- break;- }- const part = parts[partIndex];- if (- part?.type === ContentTypes.THINK &&- includesReasoningAnchor(textValue(part.think), index)- ) {- return true;- }- }- return false;-}--function findTrackedToolStart(+function findTrackedToolIndices(parts: ReadonlyArray<LooseContentPart | null | undefined>,activity: TrackedActivity,-): number | undefined {- if (activity.toolCallIds != null && activity.toolCallIds.length > 0) {- const toolStart = findBatchStart(parts, new Set(activity.toolCallIds));- if (- parts[toolStart]?.type === ContentTypes.TOOL_CALL &&- activity.toolCallIds.includes(String(parts[toolStart]?.tool_call?.id ?? ''))- ) {- return toolStart;- }+): number[] {+ if (activity.toolCallIds == null || activity.toolCallIds.length === 0) {+ return [];}- return undefined;+ const ids = new Set(activity.toolCallIds);+ return definedPartIndices(parts).filter((index) => {+ const part = parts[index];+ return (+ part?.type === ContentTypes.TOOL_CALL &&+ typeof part.tool_call?.id === 'string' &&+ ids.has(part.tool_call.id)+ );+ });}function findReasoningStart(@@ -363,6 +335,45 @@ function findReasoningStart(return startIndex ?? findLastPartIndex(parts, ContentTypes.THINK);}+/**+ * Locates a captured text entry in the live content, reporting whether the+ * result is authoritative. A step index anchors it exactly; a bare text match+ * only does when it is unique, because a repeated excerpt would otherwise+ * resolve to the wrong occurrence and outrank the position it was saved with.+ */+function locateTextEntry(+ parts: ReadonlyArray<LooseContentPart | null | undefined>,+ text: string,+ stepIndex?: number,+): { index?: number; authoritative: boolean } {+ const needle = text.trim().slice(-REASONING_ANCHOR_CHARS);+ if (!needle) {+ return { index: stepIndex, authoritative: false };+ }+ const matches = (part: LooseContentPart | null | undefined) =>+ part?.type === ContentTypes.TEXT && textValue(part.text).includes(needle);+ if (stepIndex != null && matches(parts[stepIndex])) {+ return { index: stepIndex, authoritative: true };+ }+ let lastMatch: number | undefined;+ let matchCount = 0;+ for (const index of definedPartIndices(parts)) {+ if (matches(parts[index])) {+ lastMatch = index;+ matchCount += 1;+ }+ }+ return { index: lastMatch, authoritative: matchCount === 1 };+}++function findTextBoundary(+ parts: ReadonlyArray<LooseContentPart | null | undefined>,+ text: string,+ stepIndex?: number,+): number | undefined {+ return locateTextEntry(parts, text, stepIndex).index;+}+/** Persists Open Responses text-phase metadata onto LibreChat text parts.* Installed for existing batch labels too, so commentary can supply intent* even when parent phase summaries are disabled. */@@ -418,6 +429,203 @@ export function createAssistantPhaseStampingHandlers(return wrapped;}+type PendingReasoning = { text: string; agentId?: string; startIndex?: number };++/** One side of a boundary split. Every piece of run state that a phase can+ * own appears here, so adding tracked state without partitioning it is a+ * type error rather than a silently mis-grouped activity. */+interface PhasePartitionSide {+ activities: TrackedActivity[];+ context: AssistantContextEntry[];+ pendingReasoning: Array<readonly [string, PendingReasoning]>;+ reasoningStepKeys: Array<readonly [string, string]>;+}++interface PhasePartition {+ closing: PhasePartitionSide;+ retained: PhasePartitionSide;+}++/**+ * Whether an activity belongs to the phase closing at `boundary`. Shared by+ * the boundary partition and the completion boundary so the two cannot drift+ * on what counts as work lying after a given index.+ */+function closesBeforeBoundary(+ parts: ReadonlyArray<LooseContentPart | null | undefined>,+ activity: TrackedActivity,+ boundary: number | undefined,+ toolIndices?: number[],+): boolean {+ if (boundary == null) {+ return true;+ }+ if (activity.unresolvedToolStartIndex != null && activity.unresolvedToolStartIndex >= boundary) {+ return false;+ }+ const materializedToolIndices = toolIndices ?? findTrackedToolIndices(parts, activity);+ if (materializedToolIndices.length > 0) {+ return materializedToolIndices.every((index) => index < boundary);+ }+ const materializedStart = findMaterializedActivityStart(parts, activity, materializedToolIndices);+ return materializedStart == null || materializedStart < boundary;+}++/** Every activity is represented by exactly one positioned item, so run totals+ * are a sum over that list rather than a separately maintained scalar. */+function countActivities(activities: ReadonlyArray<TrackedActivity>): number {+ return activities.reduce((total, activity) => total + (activity.mergedCount ?? 1), 0);+}++function countFailedActivities(activities: ReadonlyArray<TrackedActivity>): number {+ return activities.reduce((total, activity) => {+ if (activity.mergedCount == null) {+ return total + (activity.status === 'error' ? 1 : 0);+ }+ return total + (activity.mergedFailedCount ?? 0);+ }, 0);+}++function countPartialActivities(activities: ReadonlyArray<TrackedActivity>): number {+ return activities.reduce((total, activity) => {+ if (activity.mergedCount == null) {+ return total + (activity.status === 'partial' ? 1 : 0);+ }+ return total + (activity.mergedPartialCount ?? 0);+ }, 0);+}++/**+ * Rebuilds the unpositioned remainder of a version 1 or 2 snapshot as one+ * bounded anchor at the saved overflow position, so aggregate counts survive+ * without a scalar the boundary partition cannot place.+ */+function restoreLegacyOverflowAnchors(+ content: ReadonlyArray<LooseContentPart | null | undefined>,+ snapshot: ActivityPhaseSnapshot | undefined,+): TrackedActivity[] {+ if (snapshot == null || snapshot.version === 3) {+ return [];+ }+ const positioned = snapshot.activities.length + (snapshot.overflowActivities?.length ?? 0);+ const remainder = Math.max(0, snapshot.activityCount - positioned);+ if (remainder === 0) {+ return [];+ }+ const toolCallIds = snapshot.overflowToolCallIds ?? [];+ const boundaryToolCallIds = snapshot.overflowBoundaryToolCallIds ?? toolCallIds;+ const reasoningAnchors =+ snapshot.overflowReasoningAnchors ??+ (snapshot.overflowReasoningExcerpt != null ? [snapshot.overflowReasoningExcerpt] : []);+ const anchorIndex: ReasoningAnchorIndex = new Map();+ const anchors = new Set<string>();+ for (const anchor of reasoningAnchors) {+ addReasoningAnchor(anchors, anchorIndex, anchor);+ }+ const materializedToolIds = new Set<string>();+ const matchedTools: Array<{ index: number; id: string }> = [];+ let matchedReasoningIndex: number | undefined;+ for (const index of definedPartIndices(content)) {+ const part = content[index];+ const toolCallId = part?.type === ContentTypes.TOOL_CALL ? part.tool_call?.id : undefined;+ if (typeof toolCallId === 'string' && toolCallIds.includes(toolCallId)) {+ materializedToolIds.add(toolCallId);+ matchedTools.push({ index, id: toolCallId });+ }+ if (+ anchors.size > 0 &&+ part?.type === ContentTypes.THINK &&+ includesReasoningAnchor(textValue(part.think), anchorIndex)+ ) {+ matchedReasoningIndex = index;+ }+ }+ const rebased =+ matchedTools.length > 0+ ? Math.max(...matchedTools.map(({ index }) => index), matchedReasoningIndex ?? -1)+ : matchedReasoningIndex;+ const hasUnresolvedBoundaryTool = boundaryToolCallIds.some((id) => !materializedToolIds.has(id));+ /** A saved position only survives when something still locates it. An anchor+ * whose evidence was filtered out of the compacted content is stale, and+ * counting it would inflate a resumed phase with work it cannot show. */+ const resolvedStartIndex = hasUnresolvedBoundaryTool+ ? Math.max(rebased ?? -1, snapshot.overflowActivityStartIndex ?? -1)+ : (rebased ?? (anchors.size === 0 ? snapshot.overflowActivityStartIndex : undefined));+ if (resolvedStartIndex == null || resolvedStartIndex < 0) {+ return [];+ }+ const positionedFailed =+ snapshot.activities.filter((activity) => activity.status === 'error').length ++ (snapshot.overflowActivities ?? []).filter((activity) => activity.status === 'error').length;+ const positionedPartial =+ snapshot.activities.filter((activity) => activity.status === 'partial').length ++ (snapshot.overflowActivities ?? []).filter((activity) => activity.status === 'partial').length;+ const mergedFailedCount = Math.min(+ remainder,+ Math.max(0, snapshot.failedActivityCount - positionedFailed),+ );+ const mergedPartialCount = Math.min(+ remainder - mergedFailedCount,+ Math.max(0, snapshot.partialActivityCount - positionedPartial),+ );+ const uniformStatus = (): TrackedActivity['status'] => {+ if (mergedFailedCount === remainder) {+ return 'error';+ }+ return mergedPartialCount === remainder ? 'partial' : 'success';+ };+ /** The scalar remainder is only splittable where its evidence is. When every+ * saved boundary tool materialized, spread it across those positions so a+ * persisted boundary between two of them partitions the count instead of+ * dragging all of it to the latest side. An unresolved boundary tool means+ * the saved position is still a fallback, which stays atomic. */+ const splittable = !hasUnresolvedBoundaryTool && matchedTools.length > 1 && remainder > 1;+ /** Each split anchor keeps the tool id that materialized at its own+ * position; without one it cannot be located and would collapse onto the+ * earlier side of every boundary. */+ const anchorPoints = splittable+ ? matchedTools.filter(({ index }) => index <= resolvedStartIndex)+ : [{ index: resolvedStartIndex, id: undefined as string | undefined }];+ const shares = Math.min(anchorPoints.length, remainder);+ if (shares < anchorPoints.length) {+ anchorPoints.splice(0, anchorPoints.length - shares);+ }+ const perShare = Math.floor(remainder / shares);+ let remainingFailed = mergedFailedCount;+ let remainingPartial = mergedPartialCount;+ return anchorPoints.slice(0, shares).map(({ index: startIndex, id }, position) => {+ const isLast = position === shares - 1;+ const mergedCount = isLast ? remainder - perShare * (shares - 1) : perShare;+ const failed = Math.min(remainingFailed, mergedCount);+ remainingFailed -= failed;+ const partial = Math.min(remainingPartial, mergedCount - failed);+ remainingPartial -= partial;+ const splitStatus = (): TrackedActivity['status'] => {+ if (shares === 1) {+ return uniformStatus();+ }+ return failed === mergedCount ? 'error' : 'success';+ };+ const status = splitStatus();+ return {+ startIndex,+ bounded: true,+ mergedCount,+ status,+ ...(id != null && { toolCallIds: [id] }),+ ...(id == null &&+ toolCallIds.length > 0 && { toolCallIds: toolCallIds.slice(-MAX_RETAINED_TOOL_ENTRIES) }),+ ...(isLast &&+ reasoningAnchors.length > 0 && {+ thinkingExcerpts: reasoningAnchors.slice(-MAX_RETAINED_TOOL_ENTRIES),+ }),+ ...(failed > 0 && { mergedFailedCount: failed }),+ ...(partial > 0 && { mergedPartialCount: partial }),+ ...(isLast && hasUnresolvedBoundaryTool && { unresolvedToolStartIndex: resolvedStartIndex }),+ };+ });+}+/*** Collects run-wide logical activities and emits one parent summary at an* explicit final-answer boundary or root-run completion. The summary call is@@ -427,7 +635,12 @@ export function createActivityPhaseWiring(deps: ActivityPhaseHostDeps): Activityconst maxPerRun = deps.maxPerRun ?? DEFAULT_MAX_PER_RUN;const charLimit = deps.charLimit ?? DEFAULT_CHAR_LIMIT;const content = deps.getContentParts();- const initialSnapshot = deps.initialSnapshot?.version === 1 ? deps.initialSnapshot : undefined;+ const initialSnapshot =+ deps.initialSnapshot?.version === 1 ||+ deps.initialSnapshot?.version === 2 ||+ deps.initialSnapshot?.version === 3+ ? deps.initialSnapshot+ : undefined;let generated = Math.max(initialSnapshot?.generated ?? 0,definedPartIndices(content).filter((index) => {@@ -435,6 +648,15 @@ export function createActivityPhaseWiring(deps: ActivityPhaseHostDeps): Activityreturn part?.type === ContentTypes.ACTIVITY_LABEL && part.activity_label_type === 'phase';}).length,);+ const emittedContentRanges = definedPartIndices(content).flatMap((index) => {+ const part = content[index];+ return part?.type === ContentTypes.ACTIVITY_LABEL &&+ part.activity_label_type === 'phase' &&+ typeof part.activity_start_index === 'number' &&+ typeof part.activity_end_index === 'number'+ ? [{ start: part.activity_start_index, end: part.activity_end_index }]+ : [];+ });const initiallyMaterializedToolIds = new Set(definedPartIndices(content).flatMap((index) => {const part = content[index];@@ -442,93 +664,65 @@ export function createActivityPhaseWiring(deps: ActivityPhaseHostDeps): Activityreturn typeof id === 'string' ? [id] : [];}),);- let activities: TrackedActivity[] =- initialSnapshot?.activities.map((activity) => {- const { unresolvedToolStartIndex, ...retainedActivity } = activity;- const startIndex = findTrackedStart(content, activity);- const toolCallIds = activity.toolCallIds ?? [];- const hasUnresolvedTool = toolCallIds.some((id) => !initiallyMaterializedToolIds.has(id));- return {- ...retainedActivity,- startIndex,- ...(hasUnresolvedTool && {- unresolvedToolStartIndex: Math.max(- unresolvedToolStartIndex ?? activity.startIndex,- startIndex,- ),+ const restoreTrackedActivity = (activity: TrackedActivity): TrackedActivity => {+ const { unresolvedToolStartIndex, ...retainedActivity } = activity;+ const startIndex = findTrackedStart(content, activity);+ const bounded = activity.bounded === true;+ const toolCallIds = bounded+ ? (activity.toolCallIds?.slice(-MAX_RETAINED_TOOL_ENTRIES) ?? [])+ : (activity.toolCallIds ?? []);+ const hasUnresolvedTool = toolCallIds.some((id) => !initiallyMaterializedToolIds.has(id));+ return {+ ...retainedActivity,+ startIndex,+ ...(toolCallIds.length > 0 && { toolCallIds }),+ ...(bounded &&+ activity.thinkingExcerpts != null && {+ thinkingExcerpts: activity.thinkingExcerpts+ .slice(-MAX_RETAINED_TOOL_ENTRIES)+ .map((text) => text.slice(-REASONING_ANCHOR_CHARS)),}),- };- }) ?? [];- let activityCount = initialSnapshot?.activityCount ?? activities.length;- let failedActivityCount =- initialSnapshot?.failedActivityCount ??- activities.filter((activity) => activity.status === 'error').length;- let partialActivityCount =- initialSnapshot?.partialActivityCount ??- activities.filter((activity) => activity.status === 'partial').length;- const overflowToolCallIds = new Set(initialSnapshot?.overflowToolCallIds ?? []);- const overflowBoundaryToolCallIds = new Set(- initialSnapshot?.overflowBoundaryToolCallIds ?? initialSnapshot?.overflowToolCallIds ?? [],- );- const materializedOverflowToolIds = new Set<string>();- const rebasedOverflowToolIndexes = definedPartIndices(content).filter((index) => {- const part = content[index];- const toolCallId = part?.type === ContentTypes.TOOL_CALL ? part.tool_call?.id : undefined;- const matches = typeof toolCallId === 'string' && overflowToolCallIds.has(toolCallId);- if (matches) {- materializedOverflowToolIds.add(toolCallId);- }- return matches;- });- const overflowReasoningAnchors = new Set<string>();- const overflowReasoningAnchorIndex: ReasoningAnchorIndex = new Map();- const initialOverflowReasoningAnchors =- initialSnapshot?.overflowReasoningAnchors ??- (initialSnapshot?.overflowReasoningExcerpt != null- ? [initialSnapshot.overflowReasoningExcerpt]- : []);- for (const anchor of initialOverflowReasoningAnchors) {- addReasoningAnchor(overflowReasoningAnchors, overflowReasoningAnchorIndex, anchor);- }- let rebasedOverflowReasoningIndex: number | undefined;- if (overflowReasoningAnchors.size > 0) {- for (const index of definedPartIndices(content)) {- const part = content[index];- if (- part?.type === ContentTypes.THINK &&- includesReasoningAnchor(textValue(part.think), overflowReasoningAnchorIndex)- ) {- rebasedOverflowReasoningIndex = index;- }- }- }- const rebasedOverflowStartIndex =- rebasedOverflowToolIndexes.length > 0- ? Math.max(...rebasedOverflowToolIndexes, rebasedOverflowReasoningIndex ?? -1)- : rebasedOverflowReasoningIndex;- const hasUnresolvedBoundaryTool = [...overflowBoundaryToolCallIds].some(- (id) => !materializedOverflowToolIds.has(id),- );- let overflowActivityStartIndex = hasUnresolvedBoundaryTool- ? Math.max(rebasedOverflowStartIndex ?? -1, initialSnapshot?.overflowActivityStartIndex ?? -1)- : (rebasedOverflowStartIndex ??- (overflowReasoningAnchors.size === 0- ? initialSnapshot?.overflowActivityStartIndex- : undefined));- if (overflowActivityStartIndex != null && overflowActivityStartIndex < 0) {- overflowActivityStartIndex = undefined;- }+ ...(hasUnresolvedTool && {+ unresolvedToolStartIndex: Math.max(+ unresolvedToolStartIndex ?? activity.startIndex,+ startIndex,+ ),+ }),+ };+ };+ /** Versions 1 and 2 stored part of the total as bare scalars plus loose+ * anchors. Rebuild that remainder as one positioned anchor so the boundary+ * partition never has to reason about counts it cannot place. */+ const legacyAnchors = restoreLegacyOverflowAnchors(content, initialSnapshot);+ let activities: TrackedActivity[] = [+ ...(initialSnapshot?.activities ?? []).map(restoreTrackedActivity),+ ...legacyAnchors,+ ...(initialSnapshot?.overflowActivities ?? [])+ .slice(-MAX_OVERFLOW_ACTIVITY_ANCHORS)+ .map((activity) => restoreTrackedActivity({ ...activity, bounded: true })),+ ];const contributingAgentIds = new Set(initialSnapshot?.agentIds ?? []);let assistantContext: AssistantContextEntry[] = (initialSnapshot?.assistantContext ?? []).slice(-MAX_CONTEXT_ITEMS)- .map((text) => ({ text }));+ .map((entry) => (typeof entry === 'string' ? { text: entry } : { ...entry }));const pendingReasoning = new Map<string, { text: string; agentId?: string; startIndex?: number }>((initialSnapshot?.pendingReasoning ?? []).map(({ key, text, agentId, startIndex }) => {const boundedText = text.slice(-MAX_EXCERPT_CHARS);const needle = boundedText.trim().slice(0, REASONING_ANCHOR_CHARS);const rebasedStartIndex = needle ? findReasoningStart(content, boundedText, startIndex) : -1;+ /** The anchor is a prefix, so two lanes can share it. Binding to the+ * first match would replay a still-pending lane on the earlier side of+ * a boundary and delete it; an ambiguous anchor is no anchor. */+ const matchingReasoningParts =+ needle.length > 0+ ? definedPartIndices(content).filter(+ (index) =>+ content[index]?.type === ContentTypes.THINK &&+ textValue(content[index]?.think).includes(needle),+ ).length+ : 0;const hasMaterializedReasoning =- needle.length > 0 &&+ matchingReasoningParts === 1 &&content[rebasedStartIndex]?.type === ContentTypes.THINK &&textValue(content[rebasedStartIndex]?.think).includes(needle);return [@@ -544,80 +738,182 @@ export function createActivityPhaseWiring(deps: ActivityPhaseHostDeps): Activityconst reasoningStepKeys = new Map<string, string>();const stepKinds = new Map<string,- { kind: 'text' | 'think'; phase?: AssistantTextPhase; captureContext?: boolean }+ {+ kind: 'text' | 'think';+ phase?: AssistantTextPhase;+ captureContext?: boolean;+ }>();const textContextByStepId = new Map<string, AssistantContextEntry>();- let lastRootTextStepId: string | undefined;- const clear = () => {- activities = [];- assistantContext = [];- pendingReasoning.clear();- reasoningStepKeys.clear();+ const toBoundedAnchor = (activity: TrackedActivity): TrackedActivity => ({+ startIndex: activity.startIndex,+ bounded: true,+ ...(activity.partitionStartIndex != null && {+ partitionStartIndex: activity.partitionStartIndex,+ }),+ ...(activity.unresolvedToolStartIndex != null && {+ unresolvedToolStartIndex: activity.unresolvedToolStartIndex,+ }),+ ...(activity.toolCallIds != null && {+ toolCallIds: activity.toolCallIds.slice(-MAX_RETAINED_TOOL_ENTRIES),+ }),+ ...(activity.thinkingExcerpts != null && {+ thinkingExcerpts: activity.thinkingExcerpts+ .slice(-MAX_RETAINED_TOOL_ENTRIES)+ .map((text) => text.slice(-REASONING_ANCHOR_CHARS)),+ }),+ ...(activity.agentId != null && { agentId: activity.agentId }),+ ...(activity.mergedCount != null && { mergedCount: activity.mergedCount }),+ ...(activity.mergedFailedCount != null && { mergedFailedCount: activity.mergedFailedCount }),+ ...(activity.mergedPartialCount != null && { mergedPartialCount: activity.mergedPartialCount }),+ status: activity.status,+ });++ /** Keeps memory bounded without letting an activity lose its position:+ * evidence is dropped first, then the oldest anchors fold forward into their+ * successor, which is never earlier in the content and so cannot move a+ * counted activity across a boundary it already preceded. */+ const boundActivities = () => {+ let evidenceBudget = MAX_RETAINED_ACTIVITIES;+ activities = activities.map((activity) => {+ if (activity.bounded === true) {+ return activity;+ }+ if (evidenceBudget > 0) {+ evidenceBudget -= 1;+ return activity;+ }+ return toBoundedAnchor(activity);+ });+ /** Merging the closest pair keeps the folded count on the side it was+ * already on: a boundary can only fall at a content index, so merging+ * neighbours that share one is exact, and otherwise the smallest gap is+ * the least likely to have a boundary inside it. The survivor takes the+ * earlier position so the pair's own phase still starts where its first+ * activity did. */+ while (+ activities.filter((activity) => activity.bounded === true).length >+ MAX_OVERFLOW_ACTIVITY_ANCHORS+ ) {+ const anchorPositions = activities.flatMap((activity, position) =>+ activity.bounded === true ? [position] : [],+ );+ let mergeAt = 0;+ let bestGap = Number.POSITIVE_INFINITY;+ for (let pair = 1; pair < anchorPositions.length; pair += 1) {+ const earlier = activities[anchorPositions[pair - 1]];+ const later = activities[anchorPositions[pair]];+ const gap = Math.abs(later.startIndex - earlier.startIndex);+ if (gap < bestGap) {+ bestGap = gap;+ mergeAt = pair;+ }+ }+ const earlierPosition = anchorPositions[mergeAt - 1];+ const laterPosition = anchorPositions[mergeAt];+ const earlier = activities[earlierPosition];+ const later = activities[laterPosition];+ const mergedCount = (earlier.mergedCount ?? 1) + (later.mergedCount ?? 1);+ const mergedFailedCount = countFailedActivities([earlier, later]);+ const mergedPartialCount = countPartialActivities([earlier, later]);+ activities.splice(laterPosition, 1);+ const foldedAgentIds = [+ ...new Set(+ [+ ...(earlier.mergedAgentIds ?? []),+ ...(earlier.agentId != null ? [earlier.agentId] : []),+ ...(later.mergedAgentIds ?? []),+ ...(later.agentId != null ? [later.agentId] : []),+ ].filter((id) => id !== earlier.agentId),+ ),+ ];+ /** The later side may be waiting on a tool call that has not appeared.+ * Dropping its fallback would let a boundary close the whole merged+ * count on the earlier side and strand that call outside its parent;+ * resolution clears the anchor once every retained id materializes. */+ const mergedUnresolved = Math.max(+ earlier.unresolvedToolStartIndex ?? -1,+ later.unresolvedToolStartIndex ?? -1,+ );+ activities[earlierPosition] = {+ ...earlier,+ ...(mergedUnresolved >= 0 && { unresolvedToolStartIndex: mergedUnresolved }),+ ...(foldedAgentIds.length > 0 && { mergedAgentIds: foldedAgentIds }),+ toolCallIds: [...(earlier.toolCallIds ?? []), ...(later.toolCallIds ?? [])].slice(+ -MAX_RETAINED_TOOL_ENTRIES,+ ),+ ...(earlier.thinkingExcerpts != null || later.thinkingExcerpts != null+ ? {+ thinkingExcerpts: [+ ...(earlier.thinkingExcerpts ?? []),+ ...(later.thinkingExcerpts ?? []),+ ].slice(-MAX_RETAINED_TOOL_ENTRIES),+ }+ : {}),+ mergedCount,+ ...(mergedFailedCount > 0 && { mergedFailedCount }),+ ...(mergedPartialCount > 0 && { mergedPartialCount }),+ };+ }+ const folded = activities;+ activities = folded;+ };++ const applyRetained = (retained: PhasePartitionSide) => {+ const retainedStepKinds = new Map<+ string,+ { kind: 'text' | 'think'; phase?: AssistantTextPhase; captureContext?: boolean }+ >();+ for (const entry of retained.context) {+ const kind = entry.stepId == null ? undefined : stepKinds.get(entry.stepId);+ if (kind != null && entry.stepId != null) {+ retainedStepKinds.set(entry.stepId, kind);+ }+ }+ activities = retained.activities;+ assistantContext = retained.context;+ contributingAgentIds.clear();stepKinds.clear();textContextByStepId.clear();- activityCount = 0;- failedActivityCount = 0;- partialActivityCount = 0;- overflowActivityStartIndex = undefined;- overflowToolCallIds.clear();- overflowBoundaryToolCallIds.clear();- overflowReasoningAnchors.clear();- overflowReasoningAnchorIndex.clear();- contributingAgentIds.clear();- lastRootTextStepId = undefined;+ pendingReasoning.clear();+ reasoningStepKeys.clear();+ for (const activity of retained.activities) {+ if (activity.agentId != null) {+ contributingAgentIds.add(activity.agentId);+ }+ }+ for (const [stepId, kind] of retainedStepKinds) {+ stepKinds.set(stepId, kind);+ }+ for (const entry of retained.context) {+ if (entry.stepId != null) {+ textContextByStepId.set(entry.stepId, entry);+ }+ }+ for (const [key, reasoning] of retained.pendingReasoning) {+ pendingReasoning.set(key, reasoning);+ }+ for (const [stepId, key] of retained.reasoningStepKeys) {+ reasoningStepKeys.set(stepId, key);+ }};const trackActivity = (activity: TrackedActivity) => {- activityCount += 1;- if (activity.status === 'error') {- failedActivityCount += 1;- } else if (activity.status === 'partial') {- partialActivityCount += 1;- }if (activity.agentId != null) {contributingAgentIds.add(activity.agentId);}- if (activities.length < MAX_RETAINED_ACTIVITIES) {- activities.push(activity);- } else {- if (overflowActivityStartIndex == null || activity.startIndex > overflowActivityStartIndex) {- overflowActivityStartIndex = activity.startIndex;- overflowBoundaryToolCallIds.clear();- }- const reasoningExcerpts = activity.thinkingExcerpts;- const reasoningExcerpt = reasoningExcerpts?.[reasoningExcerpts.length - 1]?.trim();- if (reasoningExcerpt) {- addReasoningAnchor(- overflowReasoningAnchors,- overflowReasoningAnchorIndex,- reasoningExcerpt,- );- }- for (const id of activity.toolCallIds ?? []) {- overflowToolCallIds.add(id);- if (activity.startIndex === overflowActivityStartIndex) {- overflowBoundaryToolCallIds.add(id);- }- }- }+ activities.push(activity);+ boundActivities();};const snapshot = (): ActivityPhaseSnapshot => ({- version: 1,+ version: 3,generated,- activityCount,- failedActivityCount,- partialActivityCount,+ activityCount: countActivities(activities),+ failedActivityCount: countFailedActivities(activities),+ partialActivityCount: countPartialActivities(activities),agentIds: [...contributingAgentIds],- ...(overflowActivityStartIndex != null && { overflowActivityStartIndex }),- ...(overflowToolCallIds.size > 0 && { overflowToolCallIds: [...overflowToolCallIds] }),- ...(overflowActivityStartIndex != null && {- overflowBoundaryToolCallIds: [...overflowBoundaryToolCallIds],- }),- ...(overflowReasoningAnchors.size > 0 && {- overflowReasoningAnchors: [...overflowReasoningAnchors],- }),activities: activities.map((activity) => ({...activity,...(activity.entries != null && {@@ -634,7 +930,11 @@ export function createActivityPhaseWiring(deps: ActivityPhaseHostDeps): ActivitythinkingExcerpts: activity.thinkingExcerpts.map((text) => text.slice(-MAX_EXCERPT_CHARS)),}),})),- assistantContext: assistantContext.slice(-MAX_CONTEXT_ITEMS).map(({ text }) => text),+ assistantContext: assistantContext+ .slice(-MAX_CONTEXT_ITEMS)+ .map(({ text, activityPosition }) =>+ activityPosition == null ? text : { text, activityPosition },+ ),pendingReasoning: [...pendingReasoning].map(([key, reasoning]) => ({key,text: reasoning.text.slice(-MAX_EXCERPT_CHARS),@@ -668,65 +968,210 @@ export function createActivityPhaseWiring(deps: ActivityPhaseHostDeps): Activityconst resolveActivities = (snapshot: TrackedActivity[]): ActivityPhaseEntry[] => {const parts = deps.getContentParts();- return snapshot.map(- ({- childLabelIndex,- toolCallIds,- startIndex: _startIndex,- unresolvedToolStartIndex: _unresolvedToolStartIndex,- ...activity- }) => {- const matchesToolIds = (part: LooseContentPart | null | undefined): boolean => {- if (part?.type !== ContentTypes.ACTIVITY_LABEL || part.activity_label_type === 'phase') {- return false;+ return snapshot+ .filter((activity) => activity.bounded !== true)+ .map(+ ({+ childLabelIndex,+ toolCallIds,+ startIndex: _startIndex,+ partitionStartIndex: _partitionStartIndex,+ unresolvedToolStartIndex: _unresolvedToolStartIndex,+ bounded: _bounded,+ mergedCount: _mergedCount,+ mergedFailedCount: _mergedFailedCount,+ mergedPartialCount: _mergedPartialCount,+ ...activity+ }) => {+ const matchesToolIds = (part: LooseContentPart | null | undefined): boolean => {+ if (+ part?.type !== ContentTypes.ACTIVITY_LABEL ||+ part.activity_label_type === 'phase'+ ) {+ return false;+ }+ if (toolCallIds == null || toolCallIds.length === 0) {+ return true;+ }+ const childIds = Array.isArray(part.tool_call_ids) ? part.tool_call_ids : [];+ return childIds.some((id) => typeof id === 'string' && toolCallIds.includes(id));+ };+ let child = childLabelIndex == null ? undefined : parts[childLabelIndex];+ if (!matchesToolIds(child) && toolCallIds != null && toolCallIds.length > 0) {+ child = definedPartIndices(parts)+ .map((index) => parts[index])+ .find(matchesToolIds);}- if (toolCallIds == null || toolCallIds.length === 0) {- return true;+ if (!matchesToolIds(child)) {+ return activity;}- const childIds = Array.isArray(part.tool_call_ids) ? part.tool_call_ids : [];- return childIds.some((id) => typeof id === 'string' && toolCallIds.includes(id));+ const label =+ child?.pending !== true ? textValue(child?.[ContentTypes.ACTIVITY_LABEL]).trim() : '';+ return label ? { ...activity, label, entries: undefined } : activity;+ },+ );+ };++ /**+ * Splits every piece of tracked run state at one boundary. This is the only+ * place a phase decides what it owns: activities, their counts, assistant+ * context, and still-streaming reasoning all cross here together, so a new+ * field cannot be added on one side and forgotten on the other.+ *+ * `undefined` closes the whole run, which is the same split with a boundary+ * past every position.+ */+ const partitionAt = (requestedEndIndex: number | undefined): PhasePartition => {+ const currentParts = deps.getContentParts();+ /** Reasoning anchored before the boundary becomes an activity now; lanes+ * still streaming past it stay live so their eventual tool batch remains+ * one logical activity. */+ for (const [key, reasoning] of [...pendingReasoning]) {+ if (requestedEndIndex == null) {+ addPendingReasoning(key);+ continue;+ }+ const reasoningStart = findReasoningStart(currentParts, reasoning.text, reasoning.startIndex);+ if (reasoningStart < requestedEndIndex) {+ addPendingReasoning(key);+ }+ }+ const retainedPendingReasoning = [...pendingReasoning];+ const retainedReasoningKeys = new Set(retainedPendingReasoning.map(([key]) => key));+ const retainedReasoningStepKeys = [...reasoningStepKeys].filter(([, key]) =>+ retainedReasoningKeys.has(key),+ );+ /** Child-label and phase hooks run independently. A child label can claim+ * its slot before the corresponding tool part reaches the shared content+ * array, leaving the phase hook with a fallback start index. Re-anchor+ * from stable tool ids when they are available at close. */+ /** The materialized tool indices answer every positional question a+ * boundary asks — where the activity starts, which side it falls on, and+ * where a retained straddling batch reanchors — so the shared content+ * array is walked once per activity and the result carried through. */+ const resolved = activities.map((activity) => {+ const toolIndices = findTrackedToolIndices(currentParts, activity);+ const toolStart = toolIndices[0];+ if (toolStart != null) {+ /** The saved fallback outlives its purpose once every tracked call has+ * materialized. Keeping it would reject the activity at any boundary+ * below that stale index even though its real position is earlier. */+ const fullyMaterialized =+ (activity.toolCallIds?.length ?? 0) > 0 &&+ toolIndices.length >= (activity.toolCallIds?.length ?? 0);+ const { unresolvedToolStartIndex, ...rest } = activity;+ return {+ activity: {+ ...rest,+ ...(!fullyMaterialized &&+ unresolvedToolStartIndex != null && { unresolvedToolStartIndex }),+ startIndex: Math.max(toolStart, activity.partitionStartIndex ?? 0),+ },+ toolIndices,};- let child = childLabelIndex == null ? undefined : parts[childLabelIndex];- if (!matchesToolIds(child) && toolCallIds != null && toolCallIds.length > 0) {- child = definedPartIndices(parts)- .map((index) => parts[index])- .find(matchesToolIds);+ }+ /** Anchors carry only stable evidence and must be re-located against the+ * current content; a full activity keeps the index maintained live,+ * which repeated reasoning must not drag back across a prior phase. */+ return {+ activity:+ activity.bounded === true+ ? { ...activity, startIndex: findTrackedStart(currentParts, activity) }+ : activity,+ toolIndices,+ };+ });+ const closingActivities: TrackedActivity[] = [];+ const retainedActivities: TrackedActivity[] = [];+ for (const { activity, toolIndices } of resolved) {+ if (closesBeforeBoundary(currentParts, activity, requestedEndIndex, toolIndices)) {+ closingActivities.push(activity);+ continue;+ }+ const firstRetainedToolIndex =+ requestedEndIndex == null+ ? undefined+ : toolIndices.find((index) => index >= requestedEndIndex);+ retainedActivities.push(+ firstRetainedToolIndex != null+ ? {+ ...activity,+ startIndex: firstRetainedToolIndex,+ partitionStartIndex: firstRetainedToolIndex,+ }+ : activity,+ );+ }+ const closingCount = countActivities(closingActivities);+ const closingContext: AssistantContextEntry[] = [];+ const retainedContext: AssistantContextEntry[] = [];+ for (const entry of assistantContext) {+ const stepIndex = entry.stepId != null ? deps.getStepIndex?.(entry.stepId) : undefined;+ const located = entry.text.trim()+ ? locateTextEntry(currentParts, entry.text, stepIndex)+ : { index: stepIndex, authoritative: false };+ const entryIndex = located.index;+ /** Where the text actually rendered decides both directions, but only+ * when that position is known to be this entry's. Registration order is+ * the fallback: a parallel lane can register before the tool hooks that+ * close the phase, or after work that already rendered ahead of it. */+ const retainsEntry = (boundary: number): boolean => {+ if (located.authoritative && entryIndex != null) {+ return entryIndex > boundary;}- if (!matchesToolIds(child)) {- return activity;+ if (entry.activityPosition != null) {+ return entry.activityPosition > closingCount;}- const label =- child?.pending !== true ? textValue(child?.[ContentTypes.ACTIVITY_LABEL]).trim() : '';- return label ? { ...activity, label, entries: undefined } : activity;+ return entryIndex != null && entryIndex >= boundary;+ };+ const isRetained = requestedEndIndex != null && retainsEntry(requestedEndIndex);+ if (isRetained) {+ retainedContext.push({+ ...entry,+ ...(entry.activityPosition != null && {+ activityPosition: Math.max(0, entry.activityPosition - closingCount),+ }),+ });+ continue;+ }+ closingContext.push(entry);+ }+ return {+ closing: {+ activities: closingActivities,+ context: closingContext,+ pendingReasoning: [],+ reasoningStepKeys: [],},- );+ retained: {+ activities: retainedActivities,+ context: retainedContext,+ pendingReasoning: retainedPendingReasoning,+ reasoningStepKeys: retainedReasoningStepKeys,+ },+ };};const close = (closingTextPhase?: AssistantTextPhase, requestedEndIndex?: number) => {- addPendingReasoning();- if (generated >= maxPerRun) {- clear();- return;- }- if (activityCount < MIN_ACTIVITIES) {- clear();- return;- }-- generated += 1;- const phaseIndex = generated - 1;const currentParts = deps.getContentParts();- /** Child-label and phase hooks run independently. A child label can claim- * its slot before the corresponding tool part reaches the shared content- * array, leaving the phase hook with a fallback start index. Re-anchor- * from stable tool ids when they are available at close; the backward- * scan below claims unresolved leading slots without crossing visible- * answer content. */- const snapshot = activities.map((activity) => {- const toolStart = findTrackedToolStart(currentParts, activity);- return toolStart != null ? { ...activity, startIndex: toolStart } : activity;- });- const contextSnapshot = assistantContext.map(({ text }) => text);+ const { closing, retained } = partitionAt(requestedEndIndex);+ const snapshot = closing.activities;+ const totalActivityCount = countActivities(snapshot);+ const failedCount = countFailedActivities(snapshot);+ const partialCount = countPartialActivities(snapshot);+ const agentIds = [+ ...new Set(+ snapshot.flatMap((activity) => [+ ...(activity.agentId != null ? [activity.agentId] : []),+ ...(activity.mergedAgentIds ?? []),+ ]),+ ),+ ];+ const closingContext = closing.context;+ applyRetained(retained);+ const contextSnapshot = closingContext+ .map(({ text }) => text)+ .filter((text) => text.trim().length > 0);/** Completion-finalized phases leave the final root text outside their* UI bounds. Remove its matching retained excerpt from the label prompt* as well, or the parent can paraphrase the answer it does not contain.@@ -745,9 +1190,14 @@ export function createActivityPhaseWiring(deps: ActivityPhaseHostDeps): Activity}}}- const totalActivityCount = activityCount;- const failedCount = failedActivityCount;- const partialCount = partialActivityCount;+ if (generated >= maxPerRun || totalActivityCount < MIN_ACTIVITIES) {+ return;+ }++ generated += 1;+ const phaseIndex = generated - 1;+ /** The minimum-count guard above cannot pass on an empty partition, so+ * every emitted phase has a positioned activity to anchor on. */let startIndex = Math.min(...snapshot.map((activity) => activity.startIndex));/** Pull leading commentary/reasoning into the parent card. A prior phase* marker or steer is the only hard UI boundary; plain text can be@@ -763,6 +1213,7 @@ export function createActivityPhaseWiring(deps: ActivityPhaseHostDeps): Activityif (prior?.type === ContentTypes.STEER ||(prior?.type === ContentTypes.ACTIVITY_LABEL && prior.activity_label_type === 'phase') ||+ isSubstantialText(prior) ||(prior?.type === ContentTypes.TEXT &&prior.phase === 'final_answer' &&textValue(prior.text).trim().length > 0)@@ -772,7 +1223,6 @@ export function createActivityPhaseWiring(deps: ActivityPhaseHostDeps): Activity}}startIndex = extendedStartIndex;- const agentIds = [...contributingAgentIds];let phaseStatus: 'ok' | 'partial' | 'failed' = 'ok';if (failedCount === totalActivityCount) {phaseStatus = 'failed';@@ -793,9 +1243,9 @@ export function createActivityPhaseWiring(deps: ActivityPhaseHostDeps): Activitypending: true,};deps.getContentParts().push(part);+ emittedContentRanges.push({ start: startIndex, end: endIndex });deps.bumpIndexOffset();void Promise.resolve(deps.emitLabelEvent(index, part)).catch(() => undefined);- clear();const task = (async () => {let generatedPhase: GeneratedActivityPhase = {};@@ -853,7 +1303,8 @@ export function createActivityPhaseWiring(deps: ActivityPhaseHostDeps): Activity* subagent internals. */const reasoningKey = input.executingAgentId ?? 'root';const reasoning = pendingReasoning.get(reasoningKey)?.text.trim();- const ids = new Set(input.entries.map((entry) => entry.toolUseId));+ let trackedEntries = input.entries;+ let ids = new Set(trackedEntries.map((entry) => entry.toolUseId));const parts = deps.getContentParts();let childLabelIndex: number | undefined;let batchStartIndex: number | undefined;@@ -879,7 +1330,42 @@ export function createActivityPhaseWiring(deps: ActivityPhaseHostDeps): Activity}}}- const entries = input.entries.map((entry: BatchEntry) => ({+ const coveredToolIds = new Set<string>();+ for (const index of definedPartIndices(parts)) {+ const part = parts[index];+ if (+ part?.type === ContentTypes.TOOL_CALL &&+ typeof part.tool_call?.id === 'string' &&+ ids.has(part.tool_call.id) &&+ emittedContentRanges.some(({ start, end }) => index >= start && index < end)+ ) {+ coveredToolIds.add(part.tool_call.id);+ }+ }+ if (coveredToolIds.size > 0) {+ trackedEntries = trackedEntries.filter((entry) => !coveredToolIds.has(entry.toolUseId));+ ids = new Set(trackedEntries.map((entry) => entry.toolUseId));+ /** The batch position was found before the covered calls were dropped.+ * What remains is a different activity, and it may not have+ * materialized at all, so re-derive its start from the retained ids. */+ batchStartIndex = undefined;+ for (const index of indices) {+ const part = parts[index];+ if (+ part?.type === ContentTypes.TOOL_CALL &&+ typeof part.tool_call?.id === 'string' &&+ ids.has(part.tool_call.id)+ ) {+ batchStartIndex = index;+ break;+ }+ }+ }+ if (trackedEntries.length === 0) {+ pendingReasoning.delete(reasoningKey);+ return {};+ }+ const entries = trackedEntries.map((entry: BatchEntry) => ({toolName: entry.toolName,toolInput: entry.toolInput,toolOutput: entry.toolOutput,@@ -893,12 +1379,19 @@ export function createActivityPhaseWiring(deps: ActivityPhaseHostDeps): Activity} else if (failures > 0) {activityStatus = 'partial';}+ const trackedStartIndex = batchStartIndex ?? Math.max(0, parts.length - 1);+ /** A batch can be tracked after its child-label slot is reserved but before+ * its tool call reaches the shared array. Record where it started so a+ * later boundary keeps it on its own side instead of reading "nothing+ * materialized" as "happened earlier". */+ const awaitingMaterialization = batchStartIndex == null;trackActivity({entries,...(reasoning ? { thinkingExcerpts: [reasoning.slice(0, MAX_EXCERPT_CHARS)] } : {}),...(input.executingAgentId != null && { agentId: input.executingAgentId }),status: activityStatus,- startIndex: batchStartIndex ?? Math.max(0, parts.length - 1),+ startIndex: trackedStartIndex,+ ...(awaitingMaterialization && { unresolvedToolStartIndex: trackedStartIndex }),toolCallIds: [...ids],...(childLabelIndex != null && { childLabelIndex }),});@@ -949,37 +1442,39 @@ export function createActivityPhaseWiring(deps: ActivityPhaseHostDeps): Activity}return result;} else {- if (step.groupId == null) {- /** `final_answer` closes immediately before its text streams.- * Commentary does not: if it is the root run's last text,- * completion must leave it outside the parent like any- * unphased answer. Later activities still invalidate this- * candidate in `complete`. */- lastRootTextStepId = phase === 'final_answer' ? undefined : step.id;- }- if (phase === 'final_answer' && step.groupId == null) {+ const isRoot = step.groupId == null;+ if (phase !== 'commentary' && isRoot) {addPendingReasoning(step.agentId ?? 'root');- stepKinds.set(step.id, { kind, phase, captureContext: false });- close(phase);- } else {- if (phase == null && step.groupId == null) {- addPendingReasoning(step.agentId ?? 'root');+ }+ stepKinds.set(step.id, {+ kind,+ ...(phase != null && { phase }),+ captureContext: true,+ });+ const contextEntry: AssistantContextEntry = {+ stepId: step.id,+ text: '',+ activityPosition: countActivities(activities),+ };+ assistantContext.push(contextEntry);+ textContextByStepId.set(step.id, contextEntry);+ if (assistantContext.length > MAX_CONTEXT_ITEMS) {+ const removed = assistantContext.shift();+ if (removed?.stepId != null) {+ textContextByStepId.delete(removed.stepId);}- stepKinds.set(step.id, {- kind,- ...(phase != null && { phase }),- captureContext: true,- });- const contextEntry: AssistantContextEntry = { stepId: step.id, text: '' };- assistantContext.push(contextEntry);- textContextByStepId.set(step.id, contextEntry);- if (assistantContext.length > MAX_CONTEXT_ITEMS) {- const removed = assistantContext.shift();- if (removed?.stepId != null) {- textContextByStepId.delete(removed.stepId);- }+ }+ const result = runStepHandler.handle(event, data, metadata, graph);+ if (phase === 'final_answer' && isRoot) {+ const boundaryIndex = deps.getStepIndex?.(step.id);+ if (+ boundaryIndex != null &&+ deps.getContentParts()[boundaryIndex]?.type === ContentTypes.TEXT+ ) {+ close(phase, boundaryIndex);}}+ return result;}}return runStepHandler.handle(event, data, metadata, graph);@@ -999,6 +1494,26 @@ export function createActivityPhaseWiring(deps: ActivityPhaseHostDeps): Activityif (text && contextEntry != null) {contextEntry.text = `${contextEntry.text}${text}`.slice(-MAX_EXCERPT_CHARS);}+ const result = messageHandler.handle(event, data, metadata, graph);+ const boundaryIndex =+ id && contextEntry != null+ ? findTextBoundary(+ deps.getContentParts(),+ contextEntry.text,+ deps.getStepIndex?.(id),+ )+ : undefined;+ if (+ contextEntry != null &&+ contextEntry.text.trim().length > SUBSTANTIAL_TEXT_CHARS &&+ boundaryIndex != null+ ) {+ assistantContext = assistantContext.filter((entry) => entry !== contextEntry);+ textContextByStepId.delete(id ?? '');+ close(tracked.phase, boundaryIndex);+ stepKinds.delete(id ?? '');+ }+ return result;}return messageHandler.handle(event, data, metadata, graph);},@@ -1024,112 +1539,60 @@ export function createActivityPhaseWiring(deps: ActivityPhaseHostDeps): Activityreturn wrapped;};- const complete = () => {- let finalTextIndex =- lastRootTextStepId == null ? undefined : deps.getStepIndex?.(lastRootTextStepId);- const parts = deps.getContentParts();- if (- finalTextIndex != null &&- (parts[finalTextIndex]?.type !== ContentTypes.TEXT ||- !textValue(parts[finalTextIndex]?.text).trim())- ) {- finalTextIndex = undefined;- }- /** The host step map is an event-coordinate hint, not the authoritative- * rendered position. Activity-label reservations advance the shared- * content offset after earlier steps were indexed, and a provider can- * materialize the final text at a later slot. Always reconcile against- * the live parts so a stale-but-defined step index cannot pull the final- * answer into the parent phase. */- const definedIndices = Object.keys(parts);- for (let position = definedIndices.length - 1; position >= 0; position -= 1) {- const index = Number(definedIndices[position]);+ /**+ * The run's last visible text is its answer, so it stays outside the+ * collapsed parent whatever its length — a short "Done" must not disappear+ * into the activity card. Length only decides whether *intermediate* text+ * earns a boundary; semantic commentary is not an answer and stays inside.+ */+ const finalTextBoundary = (+ parts: ReadonlyArray<LooseContentPart | null | undefined>,+ ): number | undefined => {+ let candidate: number | undefined;+ for (const index of definedPartIndices(parts)) {const part = parts[index];- /** The UI contract is the last materialized TEXT part, not the last- * part whose provider lane metadata happens to look root-scoped.- * Some MCP runs retain a groupId on their final response, so even a- * `final_answer` part may not have taken the immediate-close branch.- * An already-closed phase has no remaining activities and completion- * is a no-op. The later-activity checks below still reject an- * intermediate lane text when tools or reasoning follow it. */if (part?.type === ContentTypes.TEXT && textValue(part.text).trim()) {- finalTextIndex = index;- break;+ candidate = index;}}- if (finalTextIndex != null) {- const candidateFinalTextIndex = finalTextIndex;- const materializedToolIds = new Set<string>();- const trailingToolIds = new Set<string>();- for (const key of Object.keys(parts)) {- const index = Number(key);- const part = parts[index];- if (part?.type !== ContentTypes.TOOL_CALL || typeof part.tool_call?.id !== 'string') {- continue;- }- materializedToolIds.add(part.tool_call.id);- if (index >= candidateFinalTextIndex) {- trailingToolIds.add(part.tool_call.id);- }+ if (candidate == null || parts[candidate]?.phase === 'commentary') {+ return undefined;+ }+ const boundary = candidate;+ if (activities.some((activity) => !closesBeforeBoundary(parts, activity, boundary))) {+ return undefined;+ }+ for (const reasoning of pendingReasoning.values()) {+ /** Empty reservations are not activities, but the SDK can still assign+ * them a later sparse index; one must not pull the answer inside. */+ if (!reasoning.text.trim()) {+ continue;}- const hasLaterTrackedActivity = activities.some((activity) => {- const toolCallIds = activity.toolCallIds ?? [];- if (toolCallIds.some((id) => trailingToolIds.has(id))) {- return true;- }- const reasoningExcerpt = activity.thinkingExcerpts?.[0];- if (toolCallIds.length === 0 && reasoningExcerpt) {- return hasReasoningExcerptAtOrAfter(parts, reasoningExcerpt, candidateFinalTextIndex);- }- return (- toolCallIds.some((id) => !materializedToolIds.has(id)) &&- (activity.unresolvedToolStartIndex ?? activity.startIndex) >= candidateFinalTextIndex- );- });- const overflowIds = [...overflowToolCallIds];- const overflowBoundaryIds = [...overflowBoundaryToolCallIds];- const hasLaterOverflowActivity =- overflowIds.some((id) => trailingToolIds.has(id)) ||- hasIndexedReasoningAtOrAfter(- parts,- overflowReasoningAnchorIndex,- candidateFinalTextIndex,- ) ||- (!overflowBoundaryIds.every((id) => materializedToolIds.has(id)) &&- overflowActivityStartIndex != null &&- overflowActivityStartIndex >= candidateFinalTextIndex);- const pendingReasoningAnchors = new Set<string>();- const pendingReasoningAnchorIndex: ReasoningAnchorIndex = new Map();- let hasLaterPendingReasoningIndex = false;- for (const reasoning of pendingReasoning.values()) {- /** Empty reasoning reservations are not activities: addPendingReasoning- * deliberately drops them. They can still receive a later sparse- * index from the SDK, so do not let that placeholder pull a fully- * materialized final answer into the completed parent phase. */- if (!reasoning.text.trim()) {- continue;- }- hasLaterPendingReasoningIndex ||=- reasoning.startIndex != null && reasoning.startIndex >= candidateFinalTextIndex;- addReasoningAnchor(- pendingReasoningAnchors,- pendingReasoningAnchorIndex,- reasoning.text,- );+ if (findReasoningStart(parts, reasoning.text, reasoning.startIndex) >= boundary) {+ return undefined;}- const hasLaterPendingReasoning =- hasLaterPendingReasoningIndex ||- hasIndexedReasoningAtOrAfter(- parts,- pendingReasoningAnchorIndex,- candidateFinalTextIndex,- );- if (hasLaterTrackedActivity || hasLaterOverflowActivity || hasLaterPendingReasoning) {- finalTextIndex = undefined;+ }+ return boundary;+ };++ const complete = () => {+ const parts = deps.getContentParts();+ /** A live substantial-text boundary normally closes its phase while+ * streaming. Reconcile persisted content as a fallback for resume paths+ * where the original delta crossed the boundary before this wiring was+ * attached. */+ for (const index of definedPartIndices(parts)) {+ if (isSubstantialText(parts[index])) {+ const phase = parts[index]?.phase;+ close(phase === 'commentary' || phase === 'final_answer' ? phase : undefined, index);}}- close(undefined, finalTextIndex);+ close(undefined, finalTextBoundary(deps.getContentParts()));+ };++ const drop = () => {+ applyRetained({ activities: [], context: [], pendingReasoning: [], reasoningStepKeys: [] });};- return { hook, handlers: wrapHandlers, drop: clear, complete, snapshot };+ return { hook, handlers: wrapHandlers, drop, complete, snapshot };}