import { ContextHandoffId, MessageId, CheckpointId, CheckpointScopeId, RuntimeRequestId, NodeId, PlanId, ProviderInstanceId, ProviderDriverKind, ProviderThreadId, ProviderTurnId, RunId, RunAttemptId, ScheduledTaskId, ThreadId, TurnItemId, type OrchestrationV2RunAttempt, type OrchestrationV2ProjectedTurnItem, type OrchestrationV2TurnItem, } from "@t3tools/contracts"; import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message"; import { summarizeToolGroup } from "@t3tools/client-runtime/work-log/presentation"; import * as DateTime from "effect/DateTime"; import { describe, expect, it } from "vite-plus/test"; import { workEntryRowLabel, isContextHandoffActivityGroup, buildThreadFeed, deriveThreadFeedPresentation, threadFeedActivityIsVisible, threadFeedRunIsUnsettled, type ThreadFeedActivity, type ThreadFeedEntry, togglePendingUserInputOptionSelection, setPendingUserInputCustomAnswer, isPendingUserInputOptionSelected, buildPendingUserInputAnswers, } from "./threadActivity"; const threadId = ThreadId.make("thread-1"); const sourceThreadId = ThreadId.make("thread-source"); const runId = RunId.make("run-1"); it("keeps historical plan detail accessible from its paged turn item", () => { const item = { ...base("historical-plan", "2026-08-29T00:00:00.000Z", 1), type: "proposed_plan", planId: "plan-historical", markdown: "Full historical plan text", streaming: false, } as OrchestrationV2TurnItem; const entries = buildThreadFeed([projected(item, 0)]); const activity = entries.flatMap((entry) => entry.type === "activity-group" ? entry.activities : [], )[0]; expect(activity?.detail).toBe("Full historical plan text"); expect(activity?.getFullDetail()).toContain("Full historical plan text"); }); it("shows only the structured path in expanded mobile read details", () => { const item: OrchestrationV2TurnItem = { ...base("read-detail", "2026-06-20T00:00:03.000Z", 2), type: "dynamic_tool", toolName: "Read", title: "Read src/env.ts", input: { path: "src/env.ts" }, output: "---\nname: env\n---\nsecret content", }; const activity = buildThreadFeed([projected(item, 0)]).flatMap((entry) => entry.type === "activity-group" ? entry.activities : [], )[0]; expect(activity?.getFullDetail()).toBe("src/env.ts"); expect(activity?.canExpand).toBe(true); expect(activity?.getCopyText()).not.toContain("secret content"); expect(activity?.getFullDetail()).not.toContain("sourceThreadId"); const withoutPath = buildThreadFeed([ projected({ ...item, id: TurnItemId.make("read-without-path"), input: {} }, 0), ]).flatMap((entry) => (entry.type === "activity-group" ? entry.activities : []))[0]; expect(withoutPath?.getFullDetail()).toBeNull(); expect(withoutPath?.canExpand).toBe(false); }); it("labels file searches with the adapter title and its search target", () => { const item: OrchestrationV2TurnItem = { ...base("file-search", "2026-06-20T00:00:03.000Z", 2), type: "file_search", title: "Searched TODO in web", pattern: "TODO", }; const activity = buildThreadFeed([projected(item, 0)]).flatMap((entry) => entry.type === "activity-group" ? entry.activities : [], )[0]; expect(activity?.summary).toBe("Searched TODO in web"); expect(activity ? workEntryRowLabel(activity.workEntry) : null).toBe("Searched TODO in web"); }); it("keeps approval prompts rather than presenting them as tool work", () => { const approval = ( id: string, requestKind: "file-read" | "command" | "file-change", ordinal: number, ) => ({ ...base(id, `2026-06-20T00:00:0${ordinal}.000Z`, ordinal), type: "approval_request", requestId: RuntimeRequestId.make(`request-${id}`), requestKind, prompt: `Allow ${requestKind}?`, }) satisfies OrchestrationV2TurnItem; const feed = buildThreadFeed([ projected(approval("approve-read", "file-read", 1), 0), projected(approval("approve-command", "command", 2), 1), projected(approval("approve-edit", "file-change", 3), 2), ]); const activities = feed.flatMap((entry) => entry.type === "activity-group" ? entry.activities : [], ); expect(activities.map((activity) => workEntryRowLabel(activity.workEntry))).toEqual([ "Allow file-read?", "Allow command?", "Allow file-change?", ]); expect(activities[0]?.canExpand).toBe(true); expect( summarizeToolGroup(activities.slice(1).map((activity) => activity.workEntry)).summary, ).not.toMatch(/Ran|changed/); }); function base(id: string, updatedAt: string, ordinal: number) { const timestamp = DateTime.makeUnsafe(updatedAt); return { id: TurnItemId.make(id), threadId, runId, nodeId: null, providerThreadId: null, providerTurnId: null, nativeItemRef: null, parentItemId: null, ordinal, status: "completed" as const, title: null, startedAt: timestamp, completedAt: timestamp, updatedAt: timestamp, }; } function projected( item: OrchestrationV2TurnItem, position: number, visibility: OrchestrationV2ProjectedTurnItem["visibility"] = "local", ): OrchestrationV2ProjectedTurnItem { return { position, visibility, sourceThreadId: visibility === "local" ? threadId : sourceThreadId, sourceItemId: item.id, item, }; } function userMessage(updatedAt = "2026-06-20T00:00:01.000Z") { return { ...base("item-user", updatedAt, 0), type: "user_message" as const, messageId: MessageId.make("message-user"), createdBy: "user" as const, creationSource: "mobile" as const, inputIntent: "turn_start" as const, text: "Run checks", attachments: [], }; } function command(updatedAt = "2026-06-20T00:00:02.000Z") { return { ...base("item-command", updatedAt, 1), type: "command_execution" as const, input: "vp check", output: "ok", exitCode: 0, }; } function assistantMessage(updatedAt = "2026-06-20T00:00:03.000Z") { return { ...base("item-assistant", updatedAt, 2), type: "assistant_message" as const, messageId: MessageId.make("message-assistant"), text: "Done", streaming: false, }; } describe("buildThreadFeed", () => { it("keeps async answers in question history instead of user bubbles", () => { const requestId = RuntimeRequestId.make("question"); const question: OrchestrationV2TurnItem = { ...base("question", "2026-06-20T00:00:01.000Z", 0), type: "user_input_request", requestId, questions: [], questionAnswer: { requestId, answers: { color: "Blue" }, attachmentsByQuestionId: {} }, }; const reply: OrchestrationV2TurnItem = { ...userMessage(), id: TurnItemId.make("answer"), messageId: MessageId.make(`async-answer:${requestId}`), }; const feed = buildThreadFeed([projected(question, 0), projected(reply, 1)]); expect(feed).toHaveLength(1); expect(feed[0]).toMatchObject({ type: "activity-group", activities: [{ workEntry: { questionAnswer: question.questionAnswer } }], }); expect(buildThreadFeed([projected(reply, 0)])[0]?.type).toBe("message"); }); it("does not create a work group for a message and checkpoint", () => { const checkpoint: OrchestrationV2TurnItem = { ...base("checkpoint", "2026-06-20T00:00:04.000Z", 3), type: "checkpoint", checkpointId: CheckpointId.make("checkpoint"), scopeId: CheckpointScopeId.make("scope"), files: [], }; const feed = buildThreadFeed([projected(assistantMessage(), 0), projected(checkpoint, 1)]); expect(feed.map((entry) => entry.type)).toEqual(["message"]); }); it("omits cached tool output and patch bodies from expanded and copied activity", () => { const rawOutput = "RAW_TOOL_OUTPUT"; const items: OrchestrationV2TurnItem[] = [ { ...command(), output: rawOutput }, { ...base("dynamic-output", "2026-06-20T00:00:03.000Z", 2), type: "dynamic_tool", toolName: "example", input: { query: "keep input" }, output: { text: rawOutput }, }, { ...base("file-output", "2026-06-20T00:00:04.000Z", 3), type: "file_change", fileName: "src/example.ts", diffStr: rawOutput, oldStr: rawOutput, newStr: rawOutput, }, ]; const activities = buildThreadFeed(items.map((item, index) => projected(item, index))).flatMap( (entry) => (entry.type === "activity-group" ? entry.activities : []), ); expect(activities).toHaveLength(3); for (const activity of activities) { expect(activity.workEntry.detail).toBeUndefined(); expect(activity.getFullDetail()).not.toContain(rawOutput); expect(activity.getCopyText()).not.toContain(rawOutput); } expect(activities[0]?.detail).toBe("vp check"); expect(activities[1]?.getFullDetail()).toContain("keep input"); expect(activities[2]?.detail).toBe("src/example.ts"); expect(items[0]).toMatchObject({ output: rawOutput }); }); it("expands tool rows only when they have detail or withheld output", () => { const items: OrchestrationV2TurnItem[] = [ { ...command(), input: "", outputOmitted: true }, { ...base("dynamic-empty", "2026-06-20T00:00:03.000Z", 2), type: "dynamic_tool", toolName: "example", input: {}, }, { ...base("read-omitted", "2026-06-20T00:00:04.000Z", 3), type: "dynamic_tool", toolName: "Read", input: { path: "src/env.ts" }, outputOmitted: true, }, ]; const activities = buildThreadFeed(items.map((item, index) => projected(item, index))).flatMap( (entry) => (entry.type === "activity-group" ? entry.activities : []), ); expect( activities.map(({ canExpand, fetchesDetail }) => ({ canExpand, fetchesDetail })), ).toEqual([ { canExpand: true, fetchesDetail: true }, { canExpand: false, fetchesDetail: false }, { canExpand: true, fetchesDetail: true }, ]); }); it("recognizes automation attribution after projecting a user message", () => { const feed = buildThreadFeed([ projected( { ...userMessage(), createdBy: "agent", creationSource: "server", scheduledTaskId: ScheduledTaskId.make("daily-audit"), }, 0, ), ]); const messageEntry = feed.find((entry) => entry.type === "message"); expect(messageEntry).toBeDefined(); expect(resolveUserMessagePresentation(messageEntry!.message)).toMatchObject({ text: "Run checks", isAutomation: true, }); }); it("keeps the sender of an agent message distinct from its timeline source", () => { const feed = buildThreadFeed([ projected( { ...userMessage(), createdBy: "agent", creationSource: "mcp", senderThreadId: sourceThreadId, }, 0, ), ]); const messageEntry = feed.find((entry) => entry.type === "message"); expect(messageEntry?.message.senderThreadId).toBe(sourceThreadId); expect(messageEntry?.message.sourceThreadId).toBe(threadId); }); it("anchors feedback before later committed turns", () => { const laterUser = { ...userMessage("2026-08-29T00:00:05.000Z"), id: TurnItemId.make("item-later-user"), messageId: MessageId.make("message-later-user"), ordinal: 2, text: "Later user turn", }; const laterAssistant = { ...assistantMessage("2026-08-29T00:00:04.000Z"), id: TurnItemId.make("item-later-assistant"), messageId: MessageId.make("message-later-assistant"), ordinal: 3, text: "Later assistant turn", }; const localMessage = (id: string, role: "user" | "assistant") => ({ id: MessageId.make(id), role, text: id, turnId: null, streaming: false, createdAt: "2026-08-29T00:00:03.000Z", updatedAt: "2026-08-29T00:00:03.000Z", }); const feed = buildThreadFeed( [ projected(userMessage("2026-08-29T00:00:01.000Z"), 0), projected(laterUser, 1), projected(laterAssistant, 2), ], { anchoredMessages: [ localMessage("feedback-user", "user"), localMessage("feedback-assistant", "assistant"), localMessage("message-later-user", "user"), ], }, ); const messages = feed.filter((entry) => entry.type === "message"); expect(messages.map((entry) => entry.id)).toEqual([ "message-user", "feedback-user", "feedback-assistant", "message-later-user", "message-later-assistant", ]); expect( messages .filter((entry) => entry.id.startsWith("feedback-")) .every((entry) => entry.message.projectedItem === undefined), ).toBe(true); }); it("keeps prominent activity visible while it is running", () => { expect( threadFeedActivityIsVisible({ prominent: true, status: "neutral", toolLike: true }), ).toBe(true); expect( threadFeedActivityIsVisible({ prominent: false, status: "neutral", toolLike: true }), ).toBe(false); }); it("keeps provider notices visible outside completed work folds without failure styling", () => { const message = "Safeguards flagged this message. Switched to Opus 4.8."; const item = { ...base("item-system-notice", "2026-06-20T00:00:02.000Z", 1), type: "system_notice" as const, message, }; const feed = buildThreadFeed([projected(item, 0)]); const presented = deriveThreadFeedPresentation(feed, null, new Set()); const activities = presented.flatMap((entry) => entry.type === "activity-group" ? entry.activities : [], ); expect(activities).toHaveLength(1); expect(activities[0]).toMatchObject({ summary: message, detail: message, prominent: true, toolLike: false, status: null, icon: "warning", workEntry: { tone: "info", itemType: "system_notice" }, }); expect(presented.some((entry) => entry.type === "run-fold")).toBe(false); }); it("presents a usage-limit stop as a warning while preserving its explanation", () => { const message = "Plan usage limit reached. Try again after reset."; const entries = buildThreadFeed([ projected( { ...base("item-limit", "2026-06-20T00:00:02.000Z", 1), type: "error", status: "failed", title: "Usage limit reached", failure: { class: "usage_limit", message, code: "usageLimitExceeded", retryable: null }, }, 0, ), ]); const activity = entries.flatMap((entry) => entry.type === "activity-group" ? entry.activities : [], )[0]; expect(activity).toMatchObject({ summary: "Usage limit reached", status: "neutral", icon: "warning", }); expect(activity?.getFullDetail()).toContain(message); }); it.each(["transport_error", "usage_limit"] as const)( "presents %s retries and clears warning markers on recovery", (failureClass) => { const retryBase = { ...base("item-provider-retry", "2026-06-20T00:00:02.000Z", 1), type: "error" as const, failure: { class: failureClass, message: "The response stream disconnected.", code: "responseStreamDisconnected", retryable: true, }, retry: { attempt: 2, maxAttempts: 5, retryDelayMs: null, }, }; const runningFeed = buildThreadFeed([ projected( { ...retryBase, status: "running", title: "Provider retry", completedAt: null, }, 0, ), ]); const recoveredFeed = buildThreadFeed([ projected( { ...retryBase, status: "completed", title: "Provider recovered", }, 0, ), ]); if (failureClass === "usage_limit") { const recoveredActivity = recoveredFeed.flatMap((entry) => entry.type === "activity-group" ? entry.activities : [], )[0]; expect(recoveredActivity).toMatchObject({ status: "success", icon: "check" }); } const failedFeed = buildThreadFeed([ projected( { ...retryBase, status: "failed", title: "Provider retry failed", }, 0, ), projected(command("2026-06-20T00:00:03.000Z"), 1), ]); const runningActivity = runningFeed.find((entry) => entry.type === "activity-group") ?.activities[0]; const recoveredActivity = recoveredFeed.find((entry) => entry.type === "activity-group") ?.activities[0]; if (runningActivity === undefined || recoveredActivity === undefined) { throw new Error("Expected provider retry work-log activities."); } expect(runningActivity).toMatchObject({ summary: "Provider retry", status: "neutral", toolLike: false, }); expect(threadFeedActivityIsVisible(runningActivity)).toBe(true); expect(recoveredActivity).toMatchObject({ summary: "Provider recovered", status: "success", toolLike: false, }); const failedPresentation = deriveThreadFeedPresentation( failedFeed, { runId, status: "running", startedAt: null, completedAt: null }, new Set(), ); expect(failedPresentation.map((entry) => entry.type)).toEqual([ "activity-group", "activity-group", ]); expect( failedPresentation[0]?.type === "activity-group" ? failedPresentation[0].activities[0]?.summary : null, ).toBe("Provider retry failed"); }, ); it.each(["pending", "running", "completed"] as const)( "omits %s task progress without hiding adjacent conversation items", (stepStatus) => { const todoItem = { ...base("item-tasks", "2026-06-20T00:00:02.500Z", 2), type: "todo_list" as const, planId: PlanId.make("plan-tasks"), steps: [{ id: "step-1", text: "Verify the change", status: stepStatus }], } satisfies OrchestrationV2TurnItem; const user = projected(userMessage(), 0); const tool = projected(command(), 1); const assistant = projected(assistantMessage(), 3); expect(buildThreadFeed([user, tool, projected(todoItem, 2), assistant])).toEqual( buildThreadFeed([user, tool, assistant]), ); }, ); it("hides synthetic workspace preparation activity", () => { const workspacePreparation = projected( { ...command(), title: "Workspace ready", input: "Preparing workspace", output: "Workspace preparation completed.", }, 0, ); expect(buildThreadFeed([workspacePreparation])).toEqual([]); }); it("does not treat a queued-only run as live feed activity", () => { expect( threadFeedRunIsUnsettled({ runId, status: "queued", startedAt: null, completedAt: null, }), ).toBe(false); expect( threadFeedRunIsUnsettled({ runId, status: "running", startedAt: "2026-06-20T00:00:01.000Z", completedAt: null, }), ).toBe(true); expect( threadFeedRunIsUnsettled({ runId, status: "completed", startedAt: "2026-06-20T00:00:01.000Z", completedAt: null, }), ).toBe(true); expect( threadFeedRunIsUnsettled({ runId, status: "waiting", startedAt: "2026-06-20T00:00:01.000Z", completedAt: null, }), ).toBe(true); }); it("adds queued input only after dispatch creates its turn item", () => { const dispatchedRunId = RunId.make("run-dispatched-queued"); const dispatchedMessageId = MessageId.make("message-dispatched-queued"); expect(buildThreadFeed([])).toEqual([]); const promotedEntries = buildThreadFeed([ projected( { ...userMessage(), id: TurnItemId.make("item-dispatched-queued"), runId: dispatchedRunId, messageId: dispatchedMessageId, inputIntent: "turn_start", }, 0, ), ]); expect(promotedEntries.map((entry) => entry.id)).toEqual([dispatchedMessageId]); expect( promotedEntries[0]?.type === "message" ? promotedEntries[0].message.inputIntent : undefined, ).toBe("turn_start"); }); it("hides the interruption request and keeps the terminal result", () => { const request = projected( { ...base("item-interrupt-request", "2026-06-20T00:00:02.000Z", 1), type: "run_interrupt_request", message: "Interrupt requested", }, 0, ); const result = projected( { ...base("item-interrupt-result", "2026-06-20T00:00:03.000Z", 2), type: "run_interrupt_result", message: "Run interrupted before provider start", }, 1, ); const activities = buildThreadFeed([request, result]).flatMap((entry) => entry.type === "activity-group" ? entry.activities : [], ); expect(activities).toHaveLength(1); expect(activities[0]?.summary).toBe("Run interrupted"); expect(activities[0]?.detail).toBe("Run interrupted before provider start"); expect( deriveThreadFeedPresentation( buildThreadFeed([request, result]), { runId, status: "interrupted", startedAt: "2026-06-20T00:00:01.000Z", completedAt: "2026-06-20T00:00:03.000Z", }, new Set(), ).some((entry) => entry.type === "run-fold"), ).toBe(false); }); it("preserves authoritative V2 order instead of sorting reconstructed collections", () => { const rows = [ projected(userMessage("2026-06-20T00:00:03.000Z"), 0), projected(command("2026-06-20T00:00:01.000Z"), 1), projected(assistantMessage("2026-06-20T00:00:02.000Z"), 2), ]; const feed = buildThreadFeed(rows); expect(feed.map((entry) => entry.type)).toEqual(["message", "activity-group", "message"]); expect(feed.map((entry) => entry.id)).toEqual([ "message-user", "local:thread-1:item-command", "message-assistant", ]); const activity = feed.find((entry) => entry.type === "activity-group")?.activities[0]; expect(activity?.projectedItem).toBe(rows[1]); expect(activity?.getFullDetail()).toContain('"input": "vp check"'); }); it("keeps adjacent work from different V2 attempts in separate groups", () => { const firstRootNodeId = NodeId.make("node-attempt-1"); const secondRootNodeId = NodeId.make("node-attempt-2"); const firstCommand = { ...command(), nodeId: firstRootNodeId }; const secondCommand = { ...command("2026-06-20T00:00:03.000Z"), id: TurnItemId.make("item-command-retry"), ordinal: 2, nodeId: secondRootNodeId, }; const attempts = [ { id: RunAttemptId.make("attempt-1"), runId, attemptOrdinal: 1, rootNodeId: firstRootNodeId, providerInstanceId: ProviderInstanceId.make("provider-instance-1"), providerThreadId: ProviderThreadId.make("provider-thread-1"), providerTurnId: null, reason: "initial", status: "completed", startedAt: DateTime.makeUnsafe("2026-06-20T00:00:01.000Z"), completedAt: DateTime.makeUnsafe("2026-06-20T00:00:02.000Z"), }, { id: RunAttemptId.make("attempt-2"), runId, attemptOrdinal: 2, rootNodeId: secondRootNodeId, providerInstanceId: ProviderInstanceId.make("provider-instance-1"), providerThreadId: ProviderThreadId.make("provider-thread-1"), providerTurnId: null, reason: "retry", status: "completed", startedAt: DateTime.makeUnsafe("2026-06-20T00:00:02.000Z"), completedAt: DateTime.makeUnsafe("2026-06-20T00:00:03.000Z"), }, ] satisfies ReadonlyArray; const feed = buildThreadFeed([projected(firstCommand, 0), projected(secondCommand, 1)], { attempts, }); expect(feed).toHaveLength(2); expect( feed.map((entry) => entry.type === "activity-group" ? entry.activities[0]?.attemptId : null, ), ).toEqual(["attempt-1", "attempt-2"]); }); it("retains inherited and synthetic rows with their original projected identity", () => { const inherited = projected(command(), 0, "inherited"); const { providerThreadId: _providerThreadId, ...forkBase } = base( "item-fork", "2026-06-20T00:00:03.000Z", 2, ); const synthetic = projected( { ...forkBase, type: "fork", source: { type: "run", threadId: sourceThreadId, runId }, targetThreadId: threadId, }, 1, "synthetic", ); const feed = buildThreadFeed([inherited, synthetic]); const activities = feed.flatMap((entry) => entry.type === "activity-group" ? entry.activities : [], ); expect(activities.map((activity) => activity.projectedItem)).toEqual([inherited, synthetic]); expect(activities.map((activity) => activity.projectedItem.visibility)).toEqual([ "inherited", "synthetic", ]); expect(activities.at(-1)?.prominent).toBe(true); }); it("keeps orchestration relationship cards visible when a completed run is folded", () => { const { providerThreadId: _providerThreadId, ...forkBase } = base( "item-fork", "2026-06-20T00:00:02.500Z", 2, ); const feed = buildThreadFeed([ projected(userMessage(), 0), projected(command(), 1), projected( { ...forkBase, type: "fork", source: { type: "run", threadId, runId }, targetThreadId: sourceThreadId, }, 2, ), projected(assistantMessage(), 3), ]); const collapsed = deriveThreadFeedPresentation( feed, { runId, status: "completed", startedAt: "2026-06-20T00:00:01.000Z", completedAt: "2026-06-20T00:00:03.000Z", }, new Set(), ); expect( collapsed.some( (entry) => entry.type === "activity-group" && entry.activities.some((activity) => activity.projectedItem.item.type === "fork"), ), ).toBe(true); expect( collapsed.some( (entry) => entry.type === "activity-group" && entry.activities.some( (activity) => activity.projectedItem.item.type === "command_execution", ), ), ).toBe(false); }); it("keeps opening and final assistant messages around the first hidden work", () => { const opening = { ...assistantMessage("2026-06-20T00:00:01.500Z"), id: TurnItemId.make("item-opening"), messageId: MessageId.make("message-opening"), text: "I will check the deployment configuration.", }; const middle = { ...assistantMessage("2026-06-20T00:00:02.500Z"), id: TurnItemId.make("item-middle"), messageId: MessageId.make("message-middle"), text: "The configuration is valid; checking the build next.", }; const feed = buildThreadFeed([ projected(userMessage(), 0), projected(opening, 1), projected(command(), 2), projected(middle, 3), projected(assistantMessage(), 4), ]); const latestRun = { runId, status: "completed" as const, startedAt: "2026-06-20T00:00:01.000Z", completedAt: "2026-06-20T00:00:03.000Z", }; const collapsed = deriveThreadFeedPresentation(feed, latestRun, new Set()); expect(collapsed.map((entry) => entry.id)).toEqual([ "message-user", "message-opening", "run-fold:run-1", "message-assistant", ]); expect(collapsed[1]).toMatchObject({ message: { text: opening.text } }); expect(collapsed[2]).toMatchObject({ type: "run-fold", createdAt: "2026-06-20T00:00:02.000Z", label: "Worked for 2.0s", }); const expanded = deriveThreadFeedPresentation(feed, latestRun, new Set([runId])); expect(expanded.map((entry) => entry.type)).toEqual([ "message", "message", "run-fold", "work-toggle", "message", "message", ]); expect(expanded[4]).toMatchObject({ message: { id: middle.messageId, text: middle.text } }); }); it("does not fold a response that only has opening and final messages", () => { const feed = buildThreadFeed([ projected(userMessage(), 0), projected( { ...assistantMessage("2026-06-20T00:00:02.000Z"), id: TurnItemId.make("item-opening"), messageId: MessageId.make("message-opening"), text: "The result is ready.", }, 1, ), projected(assistantMessage(), 2), ]); const presented = deriveThreadFeedPresentation(feed, null, new Set()); expect(presented.map((entry) => entry.id)).toEqual([ "message-user", "message-opening", "message-assistant", ]); }); it("folds subagents while keeping created-thread and fork cards visible", () => { const { providerThreadId: _providerThreadId, ...forkBase } = base( "item-fork", "2026-06-20T00:00:02.000Z", 2, ); const resourceItems = [ { ...base("item-subagent", "2026-06-20T00:00:01.500Z", 1), type: "subagent", subagentId: NodeId.make("child-agent"), origin: "app_owned", driver: ProviderDriverKind.make("codex"), providerInstanceId: ProviderInstanceId.make("codex"), childThreadId: sourceThreadId, prompt: "Inspect the deployment configuration", result: "Configuration is valid", }, { ...forkBase, type: "fork", source: { type: "run", threadId, runId }, targetThreadId: sourceThreadId, }, { ...base("item-created-thread", "2026-06-20T00:00:04.000Z", 4), type: "thread_created", targetThreadId: sourceThreadId, targetRunId: null, targetProviderInstanceId: ProviderInstanceId.make("codex"), targetModel: "gpt-5.4", }, ] satisfies ReadonlyArray; const projectedResources = [ projected(resourceItems[0]!, 1), projected(resourceItems[1]!, 2), projected(resourceItems[2]!, 4), ]; const feed = buildThreadFeed([ projected(userMessage(), 0), projectedResources[0]!, projectedResources[1]!, projected(command("2026-06-20T00:00:03.000Z"), 3), projectedResources[2]!, projected(assistantMessage("2026-06-20T00:00:05.000Z"), 5), ]); const collapsed = deriveThreadFeedPresentation(feed, null, new Set()); expect(collapsed.map((entry) => entry.type)).toEqual([ "message", "run-fold", "activity-group", "activity-group", "message", ]); expect(collapsed[1]).toMatchObject({ type: "run-fold", createdAt: "2026-06-20T00:00:01.500Z", }); expect( collapsed.flatMap((entry) => entry.type === "activity-group" ? entry.activities.map((activity) => activity.projectedItem) : [], ), ).toEqual(projectedResources.slice(1)); const expanded = deriveThreadFeedPresentation(feed, null, new Set([runId])); expect( expanded.some( (entry) => entry.type === "activity-group" && entry.activities.some((activity) => activity.projectedItem.item.type === "subagent"), ), ).toBe(true); }); it("folds settled V2 run work while keeping the terminal assistant message visible", () => { const feed = buildThreadFeed([ projected(userMessage(), 0), projected(command(), 1), projected(assistantMessage(), 2), ]); const latestRun = { runId, status: "completed" as const, startedAt: "2026-06-20T00:00:01.000Z", completedAt: "2026-06-20T00:00:03.000Z", }; const collapsed = deriveThreadFeedPresentation(feed, latestRun, new Set()); expect(collapsed.map((entry) => entry.type)).toEqual(["message", "run-fold", "message"]); const expanded = deriveThreadFeedPresentation(feed, latestRun, new Set([runId])); expect(expanded.map((entry) => entry.type)).toEqual([ "message", "run-fold", "work-toggle", "message", ]); }); it("keeps an active run expanded and detects failures from completed command output", () => { const failedCommand: OrchestrationV2TurnItem = { ...command(), output: "sh: missing-command: command not found", }; const feed = buildThreadFeed([projected(userMessage(), 0), projected(failedCommand, 1)]); const presented = deriveThreadFeedPresentation( feed, { runId, status: "running", startedAt: "2026-06-20T00:00:01.000Z", completedAt: null, }, new Set(), ); expect(presented.some((entry) => entry.type === "run-fold")).toBe(false); expect(presented.find((entry) => entry.type === "work-toggle")).toMatchObject({ summary: "vp check", hiddenCount: 1, hasFailure: true, live: false, }); }); it("folds each run of a provider-native subagent thread like a normal turn", () => { // A Claude subagent's child thread, as projected: no runs, and a user // prompt for the launch and for a SendMessage resume. const runless = (item: T, id: string, ordinal: number) => ({ ...item, id: TurnItemId.make(id), runId: null, ordinal, }); const prompt = (id: string, ordinal: number, at: string) => runless( { ...userMessage(at), messageId: MessageId.make(id), creationSource: "provider" as const }, id, ordinal, ); const answer = (id: string, ordinal: number, at: string) => runless({ ...assistantMessage(at), messageId: MessageId.make(id) }, id, ordinal); const { exitCode: _exitCode, ...completedCommand } = command("2026-06-20T00:01:17.000Z"); const feed = (resumeRunning: boolean) => buildThreadFeed( [ prompt("launch", 1, "2026-06-20T00:00:00.000Z"), runless(command("2026-06-20T00:00:04.000Z"), "launch-ls", 2), answer("launch-answer", 3, "2026-06-20T00:00:08.000Z"), prompt("resume", 4, "2026-06-20T00:01:12.000Z"), resumeRunning ? runless( { ...completedCommand, status: "running", completedAt: null, output: "" }, "resume-ls", 5, ) : runless(command("2026-06-20T00:01:17.000Z"), "resume-ls", 5), ...(resumeRunning ? [] : [answer("resume-answer", 6, "2026-06-20T00:01:20.000Z")]), ].map((item, position) => projected(item, position)), ); const shape = (entries: ReadonlyArray) => entries.map((entry) => entry.type === "run-fold" ? `fold:${entry.label}` : entry.type === "message" ? `${entry.message.role}:${entry.message.id}` : entry.type, ); const settled = deriveThreadFeedPresentation(feed(false), null, new Set()); expect(shape(settled)).toEqual([ "user:launch", "fold:Worked for 8.0s", "assistant:launch-answer", "user:resume", "fold:Worked for 8.0s", "assistant:resume-answer", ]); const launchFold = settled.find((entry) => entry.type === "run-fold"); if (launchFold?.type !== "run-fold") throw new Error("Expected the launch fold"); expect( shape(deriveThreadFeedPresentation(feed(false), null, new Set([launchFold.runId]))), ).toEqual([ "user:launch", "fold:Worked for 8.0s", "work-toggle", "assistant:launch-answer", "user:resume", "fold:Worked for 8.0s", "assistant:resume-answer", ]); // While the resume runs, only the settled launch folds. expect( shape( deriveThreadFeedPresentation( feed(true), null, new Set(), new Set(), "2026-06-20T00:01:12.000Z", true, ), ), ).toEqual([ "user:launch", "fold:Worked for 8.0s", "assistant:launch-answer", "user:resume", "work-toggle", ]); }); it("keeps imported V1 turns folded once the thread's first V2 run starts", () => { const imported = (item: T, id: string) => ({ ...item, id: TurnItemId.make(id), runId: null, }); const presented = (start: OrchestrationV2TurnItem) => deriveThreadFeedPresentation( buildThreadFeed( [ imported(userMessage("2026-06-20T00:00:00.000Z"), "imported-prompt"), imported( { ...assistantMessage("2026-06-20T00:00:02.000Z"), messageId: MessageId.make("update"), }, "imported-update", ), imported(command("2026-06-20T00:00:04.000Z"), "imported-ls"), imported( { ...assistantMessage("2026-06-20T00:00:08.000Z"), messageId: MessageId.make("answer"), }, "imported-answer", ), start, ].map((item, position) => projected(item, position)), ), { runId, status: "running", startedAt: "2026-06-20T00:01:00.000Z", completedAt: null }, new Set(), new Set(), "2026-06-20T00:01:00.000Z", ) .slice(0, 4) .map((entry) => (entry.type === "message" ? entry.message.role : entry.type)); // A sent prompt and an automatic wake both start V2 work below the import. expect( presented({ ...userMessage("2026-06-20T00:01:00.000Z"), id: TurnItemId.make("new-prompt"), messageId: MessageId.make("new-prompt"), }), ).toEqual(["user", "assistant", "run-fold", "assistant"]); expect( presented({ ...base("wake", "2026-06-20T00:01:00.000Z", 4), type: "notification", source: { kind: "background_task" }, outcome: "completed", summary: "Background task finished", }), ).toEqual(["user", "assistant", "run-fold", "assistant"]); }); it("keeps a provider-native subagent's runless tool call live while it works", () => { const startedAt = "2026-06-20T00:00:01.000Z"; const { exitCode: _exitCode, ...completedCommand } = command(); const runningCommand: OrchestrationV2TurnItem = { ...completedCommand, runId: null, status: "running", completedAt: null, output: "", }; const feed = buildThreadFeed([ projected({ ...userMessage(), runId: null }, 0), projected(runningCommand, 1), ]); const presented = deriveThreadFeedPresentation( feed, null, new Set(), new Set(), startedAt, true, ); expect(presented.find((entry) => entry.type === "work-toggle")).toMatchObject({ summary: "Running vp", live: true, shimmer: true, }); expect(presented.some((entry) => entry.type === "thinking")).toBe(false); }); it("keeps a runless tail folded while a normal thread waits for its sent run", () => { // Right after a send the local clock runs before the server creates the // run, and the latest run may still be queued: neither is runless work, // so the settled tail must not reopen and shift the feed. const startedAt = "2026-06-20T00:00:05.000Z"; const feed = buildThreadFeed([ projected({ ...userMessage(), runId: null }, 0), projected({ ...command(), runId: null }, 1), ]); for (const latestRun of [ null, { runId, status: "queued" as const, startedAt: null, completedAt: null }, ]) { const presented = deriveThreadFeedPresentation( feed, latestRun, new Set(), new Set(), startedAt, ); expect(presented.map((entry) => entry.type)).toEqual(["message", "run-fold", "thinking"]); } }); it("waits for workspace preparation before showing provider activity", () => { const startedAt = "2026-04-01T00:00:01.000Z"; const run = { runId, status: "preparing" as const, startedAt: null, completedAt: null }; expect(deriveThreadFeedPresentation([], run, new Set(), new Set(), startedAt)).toEqual([]); expect( deriveThreadFeedPresentation( [], { ...run, status: "running", startedAt }, new Set(), new Set(), startedAt, ), ).toEqual([{ type: "thinking", id: "live-activity-row", createdAt: startedAt, runId }]); }); it("uses a stable Thinking row while work has started without a projected item", () => { const startedAt = "2026-04-01T00:00:01.000Z"; const presented = deriveThreadFeedPresentation([], null, new Set(), new Set(), startedAt); expect(presented).toEqual([ { type: "thinking", id: "live-activity-row", createdAt: startedAt, runId: null }, ]); expect(deriveThreadFeedPresentation([], null, new Set(), new Set(), startedAt)[0]).toBe( presented[0], ); }); it("keeps expanded work in one group with stable row identities", () => { const activity = ( id: string, createdAt: string, status: ThreadFeedActivity["status"] = "success", ): ThreadFeedActivity => ({ id, createdAt, runId: null, attemptId: null, summary: `Tool ${id}`, detail: null, canExpand: false, fetchesDetail: false, getFullDetail: () => null, getCopyText: () => id, icon: "command", logo: null, toolLike: true, prominent: false, status, lifecycleStatus: status === "neutral" ? "inProgress" : "completed", workEntry: { id, createdAt, label: `Tool ${id}`, tone: "tool", command: "vp check", itemType: "command_execution", toolLifecycleStatus: status === "neutral" ? "inProgress" : "completed", }, projectedItem: projected(command(createdAt), 0), }); const feed: ThreadFeedEntry[] = [ { type: "activity-group", id: "work-group-1", createdAt: "2026-04-01T00:00:01.000Z", runId: null, activities: [ activity("activity-neutral", "2026-04-01T00:00:01.000Z", "neutral"), activity("activity-1", "2026-04-01T00:00:02.000Z"), activity("activity-2", "2026-04-01T00:00:03.000Z"), activity("activity-3", "2026-04-01T00:00:04.000Z"), ], }, ]; const collapsed = deriveThreadFeedPresentation(feed, null, new Set()); expect(collapsed.map((entry) => entry.id)).toEqual(["work-toggle:work-group:activity-neutral"]); expect(collapsed[0]).toMatchObject({ type: "work-toggle", groupId: "work-group:activity-neutral", hiddenCount: 3, expanded: false, summary: "Ran 3 commands", }); const expanded = deriveThreadFeedPresentation( feed, null, new Set(), new Set(["work-group:activity-neutral"]), ); expect(expanded.map((entry) => entry.id)).toEqual([ "work-toggle:work-group:activity-neutral", "work-details:work-group:activity-neutral", ]); expect(expanded[0]).toMatchObject({ type: "work-toggle", expanded: true, }); expect(expanded[1]).toMatchObject({ type: "activity-group", activities: [ { id: "activity-1", groupedToolDetail: true, live: false }, { id: "activity-2", groupedToolDetail: true, live: false }, { id: "activity-3", groupedToolDetail: true, live: false }, ], }); }); it("retains Claude Read image previews without tool output", () => { const item = { ...base("image-read", "2026-06-20T00:00:04.000Z", 3), type: "dynamic_tool" as const, toolName: "Read", input: { file_path: "/workspace/reference.png" }, viewedImagePath: "/workspace/reference.png", } satisfies OrchestrationV2TurnItem; const feed = buildThreadFeed([projected(item, 0)]); const activity = feed[0]?.type === "activity-group" ? feed[0].activities[0] : null; expect(activity?.workEntry.viewedImagePath).toBe("/workspace/reference.png"); }); it("pretty prints T3 MCP dynamic tool activities and attaches the product logo", () => { const toolItem: OrchestrationV2TurnItem = { ...base("item-t3-tool", "2026-06-20T00:00:04.000Z", 3), type: "dynamic_tool", toolName: "mcp__t3-code__t3_thread_read", input: { threadId: "thread-child" }, output: { messages: [] }, }; const feed = buildThreadFeed([projected(toolItem, 0)]); const activity = feed[0]?.type === "activity-group" ? feed[0].activities[0] : null; expect(activity?.summary).toBe("Read a T3 thread"); expect(activity?.logo).toBe("t3-code"); expect(activity?.getCopyText().split("\n")[0]).toBe("Read a T3 thread"); }); it("uses the CUA action title in the mobile feed", () => { const item: OrchestrationV2TurnItem = { ...base("cua", "2026-09-23T20:20:00.000Z", 1), type: "dynamic_tool", toolName: "cua_repl.js", input: { code: "await game.getAXStateAndScreenshot();", title: "Inspect Saga music screen" }, }; const feed = buildThreadFeed([projected(item, 0)]); const activity = feed[0]?.type === "activity-group" ? feed[0].activities[0] : null; expect(activity?.summary).toBe("Inspect Saga music screen"); }); it("uses canonical T3 orchestration summaries in compact work groups", () => { const rows = [ projected(command("2026-06-20T00:00:01.000Z"), 0), ...["mcp__t3-code__t3_thread_send", "t3_code.t3_thread_send", "t3_thread_send"].map( (toolName, index) => projected( { ...base(`item-send-${index}`, `2026-06-20T00:00:0${index + 2}.000Z`, index + 2), type: "dynamic_tool" as const, toolName, input: { threadId: `thread-${index}`, message: "Continue" }, output: { threadId: `thread-${index}`, messageId: `message-${index}` }, }, index + 1, ), ), projected( { ...command("2026-06-20T00:00:06.000Z"), id: TurnItemId.make("item-command-2"), ordinal: 6, }, 4, ), ]; const presented = deriveThreadFeedPresentation( buildThreadFeed(rows), { runId, status: "running", startedAt: null, completedAt: null }, new Set(), ); expect(presented).toMatchObject([ { type: "work-toggle", summary: "Ran 2 commands and sent messages to 3 threads", hiddenCount: 5, hasFailure: false, }, ]); }); it("presents project calls and summarizes successful clones through the mobile feed", () => { const items: OrchestrationV2TurnItem[] = [ { ...base("list", "2026-09-19T00:00:01.000Z", 1), type: "dynamic_tool", title: "Custom provider title", toolName: "T3-code.t3_project_list", input: {}, output: { projects: [] }, }, { ...base("clone", "2026-09-19T00:00:02.000Z", 2), type: "dynamic_tool", title: "Custom provider title", toolName: "mcp__t3_code__t3_project_clone", input: {}, output: { cwd: "/tmp/repo" }, }, { ...base("failed-clone", "2026-09-19T00:00:03.000Z", 3), type: "dynamic_tool", title: "Custom provider title", toolName: "t3_project_clone", input: {}, output: { isError: true }, }, ]; const feed = buildThreadFeed(items.map((item, position) => projected(item, position))); const activities = feed.flatMap((entry) => entry.type === "activity-group" ? entry.activities : [], ); expect(workEntryRowLabel(activities[0]!.workEntry)).toBe("Listed projects"); expect(workEntryRowLabel(activities[1]!.workEntry)).toBe("Cloned a repository"); expect(workEntryRowLabel(activities[2]!.workEntry)).toBe("Failed to clone a repository"); expect(activities.every((activity) => activity.logo === "t3-code")).toBe(true); const presented = deriveThreadFeedPresentation( feed, { runId, status: "running", startedAt: null, completedAt: null }, new Set(), ); expect(presented.find((entry) => entry.type === "work-toggle")).toMatchObject({ summary: "Listed projects 1 time and cloned 1 repository", hasFailure: true, }); }); }); describe("retained v2 feed presentation", () => { it("retains unchanged rows while the assistant streams", () => { const rows = [ projected(userMessage(), 0), projected(command(), 1), projected({ ...assistantMessage(), streaming: true }, 2), ]; const latestRun = { runId, status: "running" as const, startedAt: "2026-06-20T00:00:01.000Z", completedAt: null, }; const before = buildThreadFeed(rows); const beforePresentation = deriveThreadFeedPresentation( before, latestRun, new Set(), new Set(), latestRun.startedAt, ); const after = buildThreadFeed([ rows[0]!, rows[1]!, projected( { ...assistantMessage("2026-06-20T00:00:04.000Z"), text: "Still working", streaming: true }, 2, ), ]); const afterPresentation = deriveThreadFeedPresentation( after, latestRun, new Set(), new Set(), latestRun.startedAt, ); expect(after[0]).toBe(before[0]); expect(after[1]).toBe(before[1]); expect(after[2]).not.toBe(before[2]); expect(afterPresentation[0]).toBe(beforePresentation[0]); expect(afterPresentation[1]).toBe(beforePresentation[1]); }); it.each(["running", "completed", "interrupted"] as const)( "uses the compaction row as the live activity only while %s", (status) => { const compact = projected( { ...base("compacted", "2026-06-20T00:00:02.000Z", 1), type: "compaction", status, driver: null, beforeTokenCount: 899_000, ...(status === "completed" ? { afterTokenCount: 19_000 } : {}), }, 1, ); const latestRun = { runId, status: "running" as const, startedAt: "2026-06-20T00:00:01.000Z", completedAt: null, }; const rows = deriveThreadFeedPresentation( buildThreadFeed([projected(userMessage(), 0), compact]), latestRun, new Set(), new Set(), latestRun.startedAt, ); expect(rows.some((row) => row.type === "thinking")).toBe(status !== "running"); expect(rows.find((row) => row.type === "activity-group")).toMatchObject({ activities: [ { summary: status === "running" ? "Compacting context" : status === "completed" ? "Context compacted 899K → 19K tokens" : "Context compacted", }, ], }); }, ); it.each(["running", "completed", "failed"] as const)( "keeps a %s handoff separate from commands and visible through folds", (status) => { const handoff = projected( { ...base("handoff", "2026-06-20T00:00:02.000Z", 1), type: "handoff", status, contextHandoffId: ContextHandoffId.make("handoff"), fromProviderThreadIds: [], toProviderThreadId: ProviderThreadId.make("target"), fromProviderInstanceIds: [ProviderInstanceId.make("codex")], toProviderInstanceId: ProviderInstanceId.make("claudeAgent"), strategy: "full_thread_summary", summary: "Private full conversation summary", }, 1, ); const feed = buildThreadFeed([ projected(userMessage(), 0), handoff, projected(command("2026-06-20T00:00:03.000Z"), 2), projected(assistantMessage("2026-06-20T00:00:04.000Z"), 3), ]); for (const expanded of [new Set(), new Set([runId])]) { const rows = deriveThreadFeedPresentation(feed, null, expanded); const divider = rows.filter( (entry) => entry.type === "activity-group" && isContextHandoffActivityGroup(entry), ); expect(divider).toHaveLength(1); expect(divider[0]).toMatchObject({ activities: [{ projectedItem: handoff }] }); } const alone = deriveThreadFeedPresentation( buildThreadFeed([projected(userMessage(), 0), handoff]), null, new Set(), ); expect(alone.map((entry) => entry.type)).toEqual(["message", "activity-group"]); }, ); it("keeps a standalone compaction visible and folds it with other completed work", () => { const compact = projected( { ...base("compacted", "2026-06-20T00:00:02.000Z", 1), type: "compaction", driver: null, summary: "Shorter context", }, 1, ); const latestRun = { runId, status: "completed" as const, startedAt: "2026-06-20T00:00:01.000Z", completedAt: "2026-06-20T00:00:04.000Z", }; const onlyCompaction = deriveThreadFeedPresentation( buildThreadFeed([projected(userMessage(), 0), compact]), latestRun, new Set(), ); expect(onlyCompaction.map((entry) => entry.type)).toEqual(["message", "activity-group"]); const feed = buildThreadFeed([ projected(userMessage(), 0), compact, projected(command("2026-06-20T00:00:03.000Z"), 2), projected(assistantMessage("2026-06-20T00:00:04.000Z"), 3), ]); expect( deriveThreadFeedPresentation(feed, latestRun, new Set()).map((entry) => entry.type), ).toEqual(["message", "run-fold", "message"]); const expanded = deriveThreadFeedPresentation(feed, latestRun, new Set([runId])); expect( expanded.find( (entry) => entry.type === "activity-group" && entry.activities[0]?.projectedItem.item.type === "compaction", ), ).toMatchObject({ activities: [{ summary: "Context compacted" }] }); }); it("retains assistant image attachments from the wire", () => { const image = { type: "image" as const, id: "assistant-image", name: "result.png", mimeType: "image/png", sizeBytes: 100, }; const feed = buildThreadFeed([ projected({ ...assistantMessage(), text: "", attachments: [image] }, 0), ]); expect(feed).toMatchObject([ { type: "message", message: { role: "assistant", attachments: [image] } }, ]); }); it("keeps native application icons and source identity in collapsed and expanded work", () => { const icon = { _tag: "native-app" as const, app: { _tag: "app-id" as const, appId: "com.example.Editor" }, }; const source = { key: "native-app:com.example.editor", name: "Editor", kind: "computer" as const, icon, }; const rows = [0, 1].map((index) => projected( { ...base(`native-${index}`, `2026-06-20T00:00:0${index + 2}.000Z`, index + 1), type: "dynamic_tool" as const, toolName: "computer.click", input: { x: index, y: 1 }, output: null, toolSurface: "computer" as const, toolIcon: icon, toolSource: source, }, index, ), ); const feed = buildThreadFeed(rows); const latestRun = { runId, status: "running" as const, startedAt: null, completedAt: null }; const collapsed = deriveThreadFeedPresentation(feed, latestRun, new Set()); const toggle = collapsed[0]; if (toggle?.type !== "work-toggle") throw new Error("Expected a collapsed work group"); const presented = deriveThreadFeedPresentation( feed, latestRun, new Set(), new Set([toggle.groupId]), ); expect(presented[0]).toMatchObject({ type: "work-toggle", summary: "Used Editor", toolSurface: "computer", toolIcon: icon, }); expect(presented[1]).toMatchObject({ type: "activity-group", activities: [ { icon: "computer", workEntry: { toolSource: source, toolIcon: icon } }, { icon: "computer", workEntry: { toolSource: source, toolIcon: icon } }, ], }); }); it.each([ ["failed", "Failed to click in the preview browser", true], ["cancelled", "Stopped clicking in the preview browser", false], ] as const)( "keeps %s calls terminal while the parent run remains live", (status, summary, hasFailure) => { const feed = buildThreadFeed([ projected( { ...base("preview-click", "2026-06-20T00:00:02.000Z", 1), type: "dynamic_tool", status, toolName: "mcp__t3-code__preview_click", input: { element: "button" }, output: null, }, 0, ), ]); const rows = deriveThreadFeedPresentation( feed, { runId, status: "running", startedAt: "2026-06-20T00:00:01.000Z", completedAt: null }, new Set(), new Set(), "2026-06-20T00:00:01.000Z", ); expect(rows[0]).toMatchObject({ type: "work-toggle", summary, hasFailure, shimmer: false }); }, ); it.each([ { envelope: "direct", output: { taskId: "a" } }, { envelope: "structured", output: { structuredContent: { taskId: "a" } } }, { envelope: "text", output: { content: [{ type: "text", text: '{"taskId":"a"}' }] } }, ])( "folds matched $envelope delegations without hiding pending, failed or unmatched calls", ({ output }) => { const agent = ( id: string, index: number, origin = "app_owned" as "app_owned" | "provider_native", ) => projected( { ...base(id, "2026-06-20T00:00:01.000Z", index), type: "subagent", subagentId: NodeId.make(id), origin, driver: ProviderDriverKind.make("codex"), providerInstanceId: ProviderInstanceId.make("codex"), childThreadId: ThreadId.make(`child-${id}`), prompt: "Identical task", result: "Done", }, index, ); const delegation = ( id: string, index: number, overrides: Partial> = {}, ) => projected( { ...base(id, "2026-06-20T00:00:02.000Z", index), type: "dynamic_tool", toolName: "t3-code.delegate_task", input: { task: "Identical task" }, output, ...overrides, }, index, ); const feed = buildThreadFeed([ agent("a", 1), delegation("matched", 2), agent("b", 3), delegation("pending", 4, { status: "running", output: null }), delegation("unmatched", 5, { output: { taskId: "missing" } }), delegation("failed", 6, { status: "failed" }), delegation("error-output", 7, { output: { taskId: "a", isError: true } }), delegation("other-run", 8, { runId: RunId.make("other-run") }), agent("native", 9, "provider_native"), delegation("native-delegation", 10, { output: { taskId: "native" } }), ]); const groups = feed.flatMap((entry) => entry.type === "activity-group" ? [entry.activities.map((activity) => activity.projectedItem.item.id)] : [], ); expect(groups[0]).toEqual(["a", "b"]); expect(groups.flat()).toEqual([ "a", "b", "pending", "unmatched", "failed", "error-output", "other-run", "native", "native-delegation", ]); const presented = deriveThreadFeedPresentation( feed, null, new Set([runId, RunId.make("other-run")]), ); expect( presented.find( (entry) => entry.type === "activity-group" && entry.activities[0]?.projectedItem.item.id === "a", )?.continuesWorkLog, ).toBeUndefined(); }, ); it("keeps subagents from different provider turns in separate cards", () => { const agent = (id: string, index: number) => projected( { ...base(id, "2026-06-20T00:00:01.000Z", index), type: "subagent", subagentId: NodeId.make(id), origin: "provider_native", driver: ProviderDriverKind.make("codex"), providerInstanceId: ProviderInstanceId.make("codex"), providerTurnId: ProviderTurnId.make(id), childThreadId: null, prompt: "Task", result: null, }, index, ); expect( buildThreadFeed([agent("a", 1), agent("b", 2)]).flatMap((entry) => entry.type === "activity-group" ? [entry.activities.map((activity) => activity.projectedItem.item.id)] : [], ), ).toEqual([["a"], ["b"]]); }); it("groups only adjacent subagents in the same run, keeping their child links", () => { const agent = (id: string, index: number, agentRunId = runId) => projected( { ...base(id, `2026-06-20T00:00:0${index}.000Z`, index), type: "subagent", runId: agentRunId, subagentId: NodeId.make(id), origin: "app_owned", driver: ProviderDriverKind.make("codex"), providerInstanceId: ProviderInstanceId.make("codex"), childThreadId: ThreadId.make(`child-${id}`), prompt: "Solve the puzzle", result: "Done", }, index, ); const feed = buildThreadFeed([ agent("a", 1), agent("b", 2), projected(command("2026-06-20T00:00:03.000Z"), 3), agent("c", 4), agent("d", 5, RunId.make("other-run")), ]); expect( feed.flatMap((entry) => entry.type === "activity-group" ? [entry.activities.map((activity) => activity.projectedItem.item.id)] : [], ), ).toEqual([["a", "b"], ["item-command"], ["c"], ["d"]]); const presented = deriveThreadFeedPresentation( feed, null, new Set([runId, RunId.make("other-run")]), ); const groups = presented.flatMap((entry) => entry.type === "activity-group" && entry.activities[0]?.projectedItem.item.type === "subagent" ? [entry] : [], ); expect(groups.map((entry) => entry.activities.length)).toEqual([2, 1, 1]); expect(groups[0]?.activities.map((activity) => activity.projectedItem.item)).toMatchObject([ { childThreadId: "child-a" }, { childThreadId: "child-b" }, ]); }); it("shows an idle native subagent without claiming completion", () => { const rows = buildThreadFeed([ projected( { ...base("native-agent", "2026-06-20T00:00:02.000Z", 1), type: "subagent", status: "idle", subagentId: NodeId.make("native-agent"), origin: "provider_native", driver: ProviderDriverKind.make("antigravity"), providerInstanceId: ProviderInstanceId.make("antigravity"), childThreadId: null, title: "Search", prompt: "Find relevant files", result: null, }, 0, ), ]); expect(rows[0]).toMatchObject({ type: "activity-group", activities: [{ status: "neutral", lifecycleStatus: "idle", prominent: false }], }); expect(deriveThreadFeedPresentation(rows, null, new Set([runId]))).toMatchObject([ { type: "run-fold", expanded: true }, { type: "activity-group", activities: [{ lifecycleStatus: "idle" }] }, ]); }); }); const singleSelectQuestion = { id: "runtime", header: "Runtime", question: "Which runtime should be used?", options: [ { label: "Go", description: "One binary" }, { label: "Node.js", description: "Reuse TypeScript" }, ], multiSelect: false, } as const; const multiSelectQuestion = { id: "scope", header: "Scope", question: "Which data should be collected?", options: [ { label: "Orders", description: "Receipts" }, { label: "Listings", description: "Inventory" }, ], multiSelect: true, } as const; describe("pending user input answers", () => { it("replaces single-select options and toggles multi-select options", () => { expect( togglePendingUserInputOptionSelection( singleSelectQuestion, { selectedOptionValues: ["Go"] }, "Node.js", ), ).toEqual({ customAnswer: "", selectedOptionValues: ["Node.js"] }); const orders = togglePendingUserInputOptionSelection(multiSelectQuestion, undefined, "Orders"); const ordersAndListings = togglePendingUserInputOptionSelection( multiSelectQuestion, orders, "Listings", ); expect(ordersAndListings).toEqual({ customAnswer: "", selectedOptionValues: ["Orders", "Listings"], }); expect( togglePendingUserInputOptionSelection(multiSelectQuestion, ordersAndListings, "Orders"), ).toEqual({ customAnswer: "", selectedOptionValues: ["Listings"] }); const paddedOrders = togglePendingUserInputOptionSelection( multiSelectQuestion, undefined, " Orders ", ); expect(paddedOrders).toEqual({ customAnswer: "", selectedOptionValues: ["Orders"] }); expect( togglePendingUserInputOptionSelection(multiSelectQuestion, paddedOrders, " Orders "), ).toEqual({ customAnswer: "" }); }); it("builds array answers for multi-select questions", () => { expect( buildPendingUserInputAnswers([singleSelectQuestion, multiSelectQuestion], { runtime: { selectedOptionValues: ["Go"] }, scope: { selectedOptionValues: ["Orders", "Listings"] }, }), ).toEqual({ runtime: "Go", scope: ["Orders", "Listings"], }); }); it("clears selected options while a custom answer is active", () => { expect( setPendingUserInputCustomAnswer( multiSelectQuestion, { selectedOptionValues: ["Orders", "Listings"] }, "Orders first", ), ).toEqual({ customAnswer: "Orders first" }); }); it("matches selected chips against normalized option labels", () => { expect( isPendingUserInputOptionSelected( multiSelectQuestion, { selectedOptionValues: ["Orders"] }, " Orders ", ), ).toBe(true); expect( isPendingUserInputOptionSelected( multiSelectQuestion, { selectedOptionValues: ["Orders"], customAnswer: "Orders first" }, " Orders ", ), ).toBe(false); }); }); describe("provider question values", () => { const question = { ...singleSelectQuestion, allowCustomAnswer: false, options: [ { label: "Same label", value: " exact first ", description: "First" }, { label: "Same label", value: "second", description: "Second" }, ], } as const; it("submits raw option values and distinguishes duplicate labels", () => { const first = togglePendingUserInputOptionSelection(question, undefined, " exact first "); expect(isPendingUserInputOptionSelected(question, first, " exact first ")).toBe(true); expect(isPendingUserInputOptionSelected(question, first, "second")).toBe(false); expect(buildPendingUserInputAnswers([question], { runtime: first })).toEqual({ runtime: " exact first ", }); expect(togglePendingUserInputOptionSelection(question, first, "Same label")).toBe(first); }); it("rejects arbitrary text when the provider only accepts offered options", () => { expect(setPendingUserInputCustomAnswer(question, undefined, "Other")).toEqual({}); expect( buildPendingUserInputAnswers([question], { runtime: { customAnswer: "Other" } }), ).toBeNull(); expect( buildPendingUserInputAnswers([question], { runtime: { selectedOptionValues: ["unknown"] } }), ).toBeNull(); expect( buildPendingUserInputAnswers([question], { runtime: { selectedOptionValues: ["second"], customAnswer: "stale draft" }, }), ).toEqual({ runtime: "second" }); }); }); it("accepts ready attachment-only answers while preserving selected options", () => { const question = { id: "q", header: "Spec", question: "Provide a specification", options: [{ label: "Yes", description: "Approve" }], multiSelect: false, }; expect(buildPendingUserInputAnswers([question], { q: { attachmentCount: 1 } })).toEqual({ q: "", }); expect( buildPendingUserInputAnswers([question], { q: { attachmentCount: 1, selectedOptionValues: ["Yes"] }, }), ).toEqual({ q: "Yes" }); expect( buildPendingUserInputAnswers([question], { q: { attachmentCount: 1, attachmentsBlocked: true }, }), ).toBeNull(); expect( buildPendingUserInputAnswers([{ ...question, allowCustomAnswer: false }], { q: { attachmentCount: 1 }, }), ).toBeNull(); }); it("makes attachment-only question answers expandable in the mobile feed", () => { const answer = { requestId: RuntimeRequestId.make("question-request"), answers: { q: "" }, questionTextById: { q: "Attach the specification" }, attachmentsByQuestionId: { q: [ { type: "file" as const, id: "question-file", name: "spec.txt", mimeType: "text/plain", sizeBytes: 4, }, ], }, }; const [group] = buildThreadFeed([ projected( { ...base("answer-history", "2026-09-08T00:00:00.000Z", 0), type: "user_input_request", requestId: answer.requestId, questions: [], questionAnswer: answer, }, 0, ), ]); expect(group?.type).toBe("activity-group"); if (group?.type !== "activity-group") return; expect(group.activities[0]).toMatchObject({ canExpand: true, workEntry: { questionAnswer: answer }, }); expect(group.activities[0]?.getFullDetail()).toContain("spec.txt"); }); it("renders automatic completion as a neutral activity while retaining its details", () => { const item = { ...base("notification", "2026-06-20T00:00:01.000Z", 0), type: "notification" as const, source: { kind: "monitor" as const }, outcome: "updated" as const, summary: "Monitor reported an update", detail: "Build checks changed", }; const feed = buildThreadFeed([ projected(item, 0), projected(command(), 1), projected(assistantMessage(), 2), ]); expect(feed[0]?.type).toBe("activity-group"); if (feed[0]?.type !== "activity-group") throw new Error("Expected notification activity"); const activity = feed[0].activities[0]!; expect(activity.summary).toBe("Monitor reported an update"); expect(activity.detail).toBeNull(); expect(activity.status).toBeNull(); expect(activity.getFullDetail()).toContain(item.detail); const presented = deriveThreadFeedPresentation( feed, { runId, status: "completed", startedAt: "2026-06-20T00:00:01.000Z", completedAt: "2026-06-20T00:00:03.000Z", }, new Set(), ); expect( presented.some( (entry) => entry.type === "activity-group" && entry.activities.some((activity) => activity.summary === "Monitor reported an update"), ), ).toBe(true); expect(buildThreadFeed([projected(userMessage(), 0)])[0]?.type).toBe("message"); }); it("uses a compact reasoning preview and a short expanded heading", () => { const entry = { id: "thought", label: "Thinking", createdAt: "2026-09-17T12:00:00Z", itemType: "reasoning" as const, tone: "thinking" as const, detail: "Check **ordering**.\nThen run the test.", toolLifecycleStatus: "inProgress" as const, }; expect(workEntryRowLabel(entry)).toBe("Check **ordering**. Then run the test."); expect(workEntryRowLabel(entry, true)).toBe("Thinking"); expect(workEntryRowLabel({ ...entry, toolLifecycleStatus: "completed" }, true)).toBe("Thought"); }); it("keeps search output in expanded details rather than the compact label", () => { const entry = { id: "search", label: "Grep", toolTitle: "Grep", createdAt: "2026-09-17T12:00:00Z", itemType: "dynamic_tool" as const, tone: "tool" as const, detail: "---\nfile body", toolData: {}, }; expect(workEntryRowLabel(entry)).toBe("Grep"); expect(workEntryRowLabel(entry, true)).toBe("---\nfile body"); }); it.each(["First paragraph.\n\nSecond paragraph.", ""])( "previews live reasoning text %j", (text) => { const thought: OrchestrationV2TurnItem = { ...base("live-thought", "2026-06-20T00:00:02.000Z", 1), type: "reasoning", status: "running", completedAt: null, streaming: true, text, }; const feed = buildThreadFeed([projected(userMessage(), 0), projected(thought, 1)]); const rows = deriveThreadFeedPresentation( feed, { runId, status: "running", startedAt: "2026-06-20T00:00:01.000Z", completedAt: null }, new Set(), new Set(), "2026-06-20T00:00:01.000Z", ); if (text) { expect(rows.find((row) => row.type === "work-toggle")).toMatchObject({ summary: "First paragraph. Second paragraph.", live: true, }); } else { expect( rows.some( (row) => row.type === "thinking" || (row.type === "work-toggle" && row.summary === "Thinking"), ), ).toBe(true); } }, ); it("stops stranded thinking after a steer and follows the next thought or tool", () => { const at = "2026-06-20T00:00:02.000Z"; const thought = (id: string): OrchestrationV2TurnItem => ({ ...base(id, at, 1), type: "reasoning", status: "running", completedAt: null, streaming: true, text: id, }); const first = thought("first-thought"); const next = thought("next-thought"); const steer = { ...userMessage(at), inputIntent: "steer" as const }; const tool = { ...command(at), status: "running" as const, completedAt: null }; const rows = (items: ReadonlyArray, expanded = new Set()) => deriveThreadFeedPresentation( buildThreadFeed(items.map((item, position) => projected(item, position))), { runId, status: "running", startedAt: at, completedAt: null }, new Set(), expanded, at, ); expect(rows([first]).find((row) => row.type === "work-toggle")).toMatchObject({ summary: "first-thought", live: true, shimmer: true, }); const afterSteer = rows([first, steer]); expect(afterSteer.find((row) => row.type === "work-toggle")).toMatchObject({ live: false, shimmer: false, }); expect(afterSteer.at(-1)?.type).toBe("thinking"); const header = afterSteer.find((row) => row.type === "work-toggle"); if (header?.type !== "work-toggle") throw new Error("Expected thought toggle"); const expanded = rows([first, steer], new Set([header.groupId])); expect(expanded.find((row) => row.type === "work-toggle")).toMatchObject({ summary: "Thought" }); expect(expanded.find((row) => row.type === "activity-group")).toMatchObject({ activities: [{ lifecycleStatus: "completed", workEntry: { toolLifecycleStatus: "completed" } }], }); for (const items of [ [first, steer, next], [first, next], [first, steer, next, tool], ]) { const live = rows(items).filter((row) => row.type === "work-toggle" && row.shimmer); expect(live).toHaveLength(1); expect(live[0]).toMatchObject({ summary: items.at(-1)!.type === "reasoning" ? "next-thought" : "Running vp", }); } expect(first.status).toBe("running"); }); it("previews a settled thought in its collapsed header and labels its expanded header", () => { const thought: OrchestrationV2TurnItem = { ...base("thought-preview", "2026-06-20T00:00:02.000Z", 1), type: "reasoning", streaming: false, text: "First paragraph.\n\nSecond paragraph.", }; const feed = buildThreadFeed([ projected(userMessage(), 0), projected(thought, 1), projected(assistantMessage(), 2), ]); const run = { runId, status: "completed" as const, startedAt: "2026-06-20T00:00:01.000Z", completedAt: "2026-06-20T00:00:03.000Z", }; const collapsed = deriveThreadFeedPresentation(feed, run, new Set([runId])); const header = collapsed.find((row) => row.type === "work-toggle"); expect(header).toMatchObject({ summary: "First paragraph. Second paragraph." }); if (header?.type !== "work-toggle") throw new Error("Expected thought toggle"); const expanded = deriveThreadFeedPresentation( feed, run, new Set([runId]), new Set([header.groupId]), ); expect(expanded.find((row) => row.type === "work-toggle")).toMatchObject({ summary: "Thought", continuesWorkLog: true, }); const detail = expanded.find((row) => row.type === "activity-group"); expect(detail?.continuesWorkLog).toBeUndefined(); if (detail?.type !== "activity-group") throw new Error("Expected full thought"); expect(detail.activities[0]?.detail).toBe(thought.text); }); it.each(["provider_error", "usage_limit"] as const)( "keeps a historical %s failure and preceding work visible without disclosures", (failureClass) => { const at = "2026-06-20T00:00:03.000Z"; const error: OrchestrationV2TurnItem = { ...base("failure", at, 2), type: "error", status: "failed", failure: { class: failureClass, message: "The provider stopped this turn.\nRetry later.", code: null, retryable: true, }, }; const command: OrchestrationV2TurnItem = { ...base("command", "2026-06-20T00:00:02.000Z", 1), type: "command_execution", input: "pwd", output: "", exitCode: 0, }; const sourceFeed = buildThreadFeed([ projected(userMessage(), 0), projected(command, 1), projected(error, 2), ]); const feed = deriveThreadFeedPresentation( sourceFeed, { runId: RunId.make("newer-run"), status: "completed", startedAt: at, completedAt: at }, new Set(), ); const whileWorking = deriveThreadFeedPresentation( sourceFeed, { runId: RunId.make("newer-run"), status: "running", startedAt: at, completedAt: null }, new Set(), ); for (const entry of feed) { expect(whileWorking.find((row) => row.id === entry.id)).toBe(entry); } expect(feed.some((entry) => entry.type === "run-fold" || entry.type === "work-toggle")).toBe( false, ); const activities = feed.flatMap((entry) => entry.type === "activity-group" ? entry.activities : [], ); expect(activities.map((activity) => activity.projectedItem.item.id)).toEqual([ "command", "failure", ]); expect(activities.at(-1)).toMatchObject({ detail: error.failure.message, createdAt: at, canExpand: false, prominent: true, }); }, );