diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 04d55bc66e..dc51e7f5a9 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -445,8 +445,10 @@ function turnItemText(item: OrchestrationV2TurnItem): string | null { return item.summary ?? `${item.strategy} handoff to ${item.toProviderInstanceId}`; case "fork": return `Forked to thread ${item.targetThreadId}.`; + case "thread_created": + return `Created thread ${item.targetThreadId} with ${item.targetProviderInstanceId} (${item.targetModel}).`; case "subagent": - return item.result ?? item.prompt; + return item.result ?? item.progress ?? item.prompt; case "dynamic_tool": return jsonText({ toolName: item.toolName, input: item.input, output: item.output }); } @@ -863,6 +865,18 @@ const make = Effect.gen(function* () { Effect.gen(function* () { yield* requireCapability(scope); const parent = yield* loadProjection(scope.threadId); + const parentRun = latestActiveRun(parent); + if ( + parentRun === undefined || + parentRun.rootNodeId === null || + parentRun.providerInstanceId !== scope.providerInstanceId + ) { + return yield* failure( + "parent_not_active", + "Thread creation requires an active run owned by this MCP provider session.", + ); + } + const parentNodeId = parentRun.rootNodeId; const providers = yield* loadProviders; const key = yield* requestKey(input.clientRequestId); const created = yield* Effect.forEach( @@ -955,6 +969,29 @@ const make = Effect.gen(function* () { } const projection = yield* loadProjection(threadId); const run = projection.runs.at(-1); + yield* threadManagement + .dispatch({ + type: "thread.created.record", + commandId: stableCommandId({ + scope, + requestKey: key, + operation: "record-created-thread", + index, + }), + parentThreadId: scope.threadId, + parentRunId: parentRun.id, + parentNodeId, + targetThreadId: threadId, + targetRunId: run?.id ?? null, + }) + .pipe( + Effect.mapError((error) => + failure( + "orchestration_error", + `Unable to record thread ${index + 1} in the parent timeline: ${errorMessage(error)}`, + ), + ), + ); return { threadId, runId: run?.id ?? null, diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts index 28d6021aaa..2c4e8d9583 100644 --- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts @@ -730,6 +730,35 @@ describe("orchestrator MCP toolkit", () => { .filter((message) => message.role === "user") .map((message) => message.text), ).toEqual([createdThreadPrompt]); + const createdThreadItems = (yield* orchestrator.getThreadProjection( + parentThreadId, + )).visibleTurnItems + .map((row) => row.item) + .filter((item) => item.type === "thread_created"); + expect( + createdThreadItems.map((item) => ({ + targetThreadId: item.targetThreadId, + targetRunId: item.targetRunId, + title: item.title, + providerInstanceId: item.targetProviderInstanceId, + model: item.targetModel, + })), + ).toEqual([ + { + targetThreadId: emptyThread.threadId, + targetRunId: null, + title: emptyThread.title, + providerInstanceId: codexInstanceId, + model: codexModel, + }, + { + targetThreadId: promptedThread.threadId, + targetRunId: promptedThread.runId, + title: promptedThread.title, + providerInstanceId: claudeInstanceId, + model: claudeModel, + }, + ]); const repeatedCreateCall = yield* invoke("create_threads", createInput); const repeatedCreated = yield* decodeCreateThreadsResult( @@ -738,6 +767,15 @@ describe("orchestrator MCP toolkit", () => { expect(repeatedCreated.threads.map((thread) => thread.threadId)).toEqual( created.threads.map((thread) => thread.threadId), ); + expect( + (yield* orchestrator.getThreadProjection(parentThreadId)).visibleTurnItems.filter( + (row) => { + if (row.item.type !== "thread_created") return false; + const targetThreadId = row.item.targetThreadId; + return created.threads.some((thread) => thread.threadId === targetThreadId); + }, + ), + ).toHaveLength(2); const promptedReadCall = yield* invoke("t3_thread_read", { threadId: promptedThread.threadId, @@ -814,6 +852,22 @@ describe("orchestrator MCP toolkit", () => { const activeThread = yield* decodeCreatedThread( activeThreadCall.structuredContent, ).pipe(Effect.orDie); + const activeThreadItem = (yield* orchestrator.getThreadProjection( + parentThreadId, + )).visibleTurnItems + .map((row) => row.item) + .find( + (item) => + item.type === "thread_created" && item.targetThreadId === activeThread.threadId, + ); + expect(activeThreadItem).toMatchObject({ + type: "thread_created", + title: "Managed active thread", + targetThreadId: activeThread.threadId, + targetRunId: activeThread.runId, + targetProviderInstanceId: codexInstanceId, + targetModel: codexModel, + }); const activeProjection = yield* waitForProjection( orchestrator, activeThread.threadId, diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 746b6f8a1b..325715cf07 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -1769,6 +1769,8 @@ interface ActiveClaudeSubagent { readonly turnItemId: OrchestrationV2TurnItem["id"]; readonly turnItemOrdinal: number; nextChildItemOrdinal: number; + progressItemOrdinal: number | null; + progressStartedAt: DateTime.Utc | null; resultItemOrdinal: number | null; } @@ -2038,6 +2040,7 @@ export function makeClaudeAdapterV2( readonly toolUseId?: string; readonly prompt?: string; readonly title?: string; + readonly progress?: string; readonly result?: string; readonly status: Extract< OrchestrationV2ExecutionNode["status"], @@ -2052,6 +2055,8 @@ export function makeClaudeAdapterV2( if (existingSubagent === undefined && input.status !== "running") { return; } + const lifecycleChanged = + existingSubagent === undefined || existingSubagent.task.status !== input.status; const now = yield* DateTime.now; const nativeItemId = `task:${input.taskId}`; @@ -2105,6 +2110,7 @@ export function makeClaudeAdapterV2( status: input.status, ...(input.prompt === undefined ? {} : { prompt: input.prompt }), ...(input.title === undefined ? {} : { title: input.title }), + ...(input.progress === undefined ? {} : { progress: input.progress }), ...(input.result === undefined ? {} : { result: input.result }), completedAt: input.status === "running" ? null : now, updatedAt: now, @@ -2121,6 +2127,8 @@ export function makeClaudeAdapterV2( }), turnItemOrdinal, nextChildItemOrdinal: existingSubagent?.nextChildItemOrdinal ?? 100, + progressItemOrdinal: existingSubagent?.progressItemOrdinal ?? null, + progressStartedAt: existingSubagent?.progressStartedAt ?? null, resultItemOrdinal: existingSubagent?.resultItemOrdinal ?? null, } satisfies ActiveClaudeSubagent; input.context.subagentsByTaskId.set(input.taskId, subagent); @@ -2153,52 +2161,54 @@ export function makeClaudeAdapterV2( }); } - yield* emitProviderEvent({ - type: "node.updated", - driver: CLAUDE_PROVIDER, - node: { - id: nodeId, - threadId: input.context.input.threadId, - runId: input.context.input.runId, - parentNodeId: input.context.input.rootNodeId, - rootNodeId: input.context.input.rootNodeId, - kind: "subagent", - status: input.status, - countsForRun: false, - providerThreadId: input.context.input.providerThread.id, - providerTurnId: input.context.providerTurnId, - nativeItemRef: { - driver: CLAUDE_PROVIDER, - nativeId: input.taskId, - strength: "strong", + if (lifecycleChanged) { + yield* emitProviderEvent({ + type: "node.updated", + driver: CLAUDE_PROVIDER, + node: { + id: nodeId, + threadId: input.context.input.threadId, + runId: input.context.input.runId, + parentNodeId: input.context.input.rootNodeId, + rootNodeId: input.context.input.rootNodeId, + kind: "subagent", + status: input.status, + countsForRun: false, + providerThreadId: input.context.input.providerThread.id, + providerTurnId: input.context.providerTurnId, + nativeItemRef: { + driver: CLAUDE_PROVIDER, + nativeId: input.taskId, + strength: "strong", + }, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: task.startedAt, + completedAt: input.status === "running" ? null : now, }, - runtimeRequestId: null, - checkpointScopeId: null, - startedAt: task.startedAt, - completedAt: input.status === "running" ? null : now, - }, - }); - yield* emitProviderEvent({ - type: "node.updated", - driver: CLAUDE_PROVIDER, - node: { - id: childRootNodeId, - threadId: childThreadId, - runId: null, - parentNodeId: null, - rootNodeId: childRootNodeId, - kind: "root_turn", - status: input.status, - countsForRun: false, - providerThreadId: null, - providerTurnId: null, - nativeItemRef: task.nativeTaskRef, - runtimeRequestId: null, - checkpointScopeId: null, - startedAt: task.startedAt, - completedAt: input.status === "running" ? null : now, - }, - }); + }); + yield* emitProviderEvent({ + type: "node.updated", + driver: CLAUDE_PROVIDER, + node: { + id: childRootNodeId, + threadId: childThreadId, + runId: null, + parentNodeId: null, + rootNodeId: childRootNodeId, + kind: "root_turn", + status: input.status, + countsForRun: false, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: task.nativeTaskRef, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: task.startedAt, + completedAt: input.status === "running" ? null : now, + }, + }); + } if (existingSubagent === undefined) { const promptNativeItemId = `${nativeItemId}:prompt`; const promptArtifacts = makeSubagentConversationArtifacts({ @@ -2265,10 +2275,55 @@ export function makeClaudeAdapterV2( providerInstanceId: task.providerInstanceId, childThreadId: task.childThreadId, prompt: task.prompt, + ...(task.progress === undefined ? {} : { progress: task.progress }), result: task.result, }, }); + const progress = task.progress?.trim(); + if ( + progress !== undefined && + progress.length > 0 && + (input.progress !== undefined || (lifecycleChanged && input.status !== "running")) + ) { + const progressNativeItemId = `${nativeItemId}:progress`; + const progressItemOrdinal = + subagent.progressItemOrdinal ?? ++subagent.nextChildItemOrdinal; + const progressStartedAt = subagent.progressStartedAt ?? now; + subagent.progressItemOrdinal = progressItemOrdinal; + subagent.progressStartedAt = progressStartedAt; + yield* emitProviderEvent({ + type: "turn_item.updated", + driver: CLAUDE_PROVIDER, + turnItem: { + id: idAllocator.derive.turnItemFromProviderItem({ + driver: CLAUDE_PROVIDER, + nativeItemId: progressNativeItemId, + }), + threadId: childThreadId, + runId: null, + nodeId: childRootNodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: { + driver: CLAUDE_PROVIDER, + nativeId: progressNativeItemId, + strength: "strong", + }, + parentItemId: null, + ordinal: progressItemOrdinal, + status: input.status, + title: "Subagent progress", + startedAt: progressStartedAt, + completedAt: input.status === "running" ? null : now, + updatedAt: now, + type: "reasoning", + text: progress, + streaming: input.status === "running", + }, + }); + } + if ( input.result !== undefined && input.result.trim().length > 0 && @@ -2670,6 +2725,19 @@ export function makeClaudeAdapterV2( }); } + if (message.type === "system" && message.subtype === "task_progress") { + const progress = message.description.trim(); + if (progress.length > 0) { + yield* updateClaudeSubagentNode({ + context, + taskId: message.task_id, + ...(message.tool_use_id === undefined ? {} : { toolUseId: message.tool_use_id }), + progress, + status: "running", + }); + } + } + if (message.type === "system" && message.subtype === "task_notification") { yield* updateClaudeSubagentNode({ context, diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts index 3ad27a3f4e..48d8e46048 100644 --- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts +++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts @@ -4,6 +4,7 @@ import { CheckpointRef, CheckpointScopeId, CommandId, + ContextTransferId, EventId, MessageId, type ModelSelection, @@ -258,6 +259,177 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => { }), ); + it.effect("verifies and rebuilds projections with cross-thread subagent relations", () => + Effect.gen(function* () { + const eventSink = yield* EventSinkV2; + const projectionStore = yield* ProjectionStoreV2; + const maintenance = yield* ProjectionMaintenanceV2; + const now = yield* DateTime.now; + const parentThreadId = ThreadId.make("thread:foundation-cross-thread:parent"); + const childThreadId = ThreadId.make("thread:foundation-cross-thread:child"); + const childProviderThreadId = ProviderThreadId.make( + "provider-thread:foundation-cross-thread:child", + ); + const subagentId = NodeId.make("subagent:foundation-cross-thread"); + const spawnTransferId = ContextTransferId.make("transfer:foundation-cross-thread:spawn"); + const resultTransferId = ContextTransferId.make("transfer:foundation-cross-thread:result"); + const parentThread = makeThread(parentThreadId, now); + const childThread = { + ...makeThread(childThreadId, now), + createdBy: "agent" as const, + creationSource: "provider" as const, + lineage: { + parentThreadId, + relationshipToParent: "subagent" as const, + rootThreadId: parentThreadId, + }, + }; + + yield* eventSink.write({ + events: [ + threadCreatedEvent({ + id: "event:foundation-cross-thread:parent", + thread: parentThread, + now, + }), + threadCreatedEvent({ + id: "event:foundation-cross-thread:child", + thread: childThread, + now, + }), + { + id: EventId.make("event:foundation-cross-thread:subagent"), + type: "subagent.updated", + threadId: parentThreadId, + nodeId: subagentId, + providerInstanceId, + occurredAt: now, + payload: { + id: subagentId, + threadId: parentThreadId, + runId: null, + parentNodeId: NodeId.make("node:foundation-cross-thread:parent"), + origin: "app_owned", + createdBy: "agent", + driver: providerDriver, + providerInstanceId, + providerThreadId: childProviderThreadId, + childThreadId, + nativeTaskRef: null, + prompt: "Inspect the child flow", + title: "Cross-thread child", + model: modelSelection.model, + status: "completed", + result: "done", + startedAt: now, + completedAt: now, + updatedAt: now, + }, + }, + { + id: EventId.make("event:foundation-cross-thread:spawn-transfer"), + type: "context-transfer.created", + threadId: childThreadId, + providerInstanceId, + occurredAt: now, + payload: { + id: spawnTransferId, + type: "subagent_spawn", + sourceThreadId: parentThreadId, + targetThreadId: childThreadId, + sourcePoint: { threadId: parentThreadId }, + basePoint: null, + sourceProviderInstanceId: providerInstanceId, + targetProviderInstanceId: providerInstanceId, + targetRunId: null, + status: "consumed", + resolution: null, + createdBy: "agent", + error: null, + createdAt: now, + updatedAt: now, + consumedAt: now, + }, + }, + { + id: EventId.make("event:foundation-cross-thread:provider-thread"), + type: "provider-thread.updated", + threadId: parentThreadId, + driver: providerDriver, + providerInstanceId, + occurredAt: now, + payload: { + id: childProviderThreadId, + driver: providerDriver, + providerInstanceId, + providerSessionId: null, + appThreadId: childThreadId, + ownerNodeId: null, + nativeThreadRef: null, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }, + }, + { + id: EventId.make("event:foundation-cross-thread:result-transfer"), + type: "context-transfer.created", + threadId: parentThreadId, + providerInstanceId, + occurredAt: now, + payload: { + id: resultTransferId, + type: "subagent_result", + sourceThreadId: childThreadId, + targetThreadId: parentThreadId, + sourcePoint: { threadId: childThreadId }, + basePoint: null, + sourceProviderInstanceId: providerInstanceId, + targetProviderInstanceId: providerInstanceId, + targetRunId: null, + status: "consumed", + resolution: null, + createdBy: "system", + error: null, + createdAt: now, + updatedAt: now, + consumedAt: now, + }, + }, + ], + }); + + const assertCrossThreadProjection = Effect.gen(function* () { + const parent = yield* projectionStore.getThreadProjection(parentThreadId); + const child = yield* projectionStore.getThreadProjection(childThreadId); + const expectedTransferIds = [spawnTransferId, resultTransferId].toSorted(); + assert.deepEqual( + parent.contextTransfers.map((transfer) => transfer.id).toSorted(), + expectedTransferIds, + ); + assert.deepEqual( + child.contextTransfers.map((transfer) => transfer.id).toSorted(), + expectedTransferIds, + ); + assert.deepEqual( + parent.providerThreads.map((providerThread) => providerThread.id), + [childProviderThreadId], + ); + assert.equal(child.thread.activeProviderThreadId, childProviderThreadId); + }); + + yield* assertCrossThreadProjection; + assert.isTrue((yield* maintenance.verify).valid); + assert.isTrue((yield* maintenance.rebuild).valid); + yield* assertCrossThreadProjection; + }), + ); + it.effect( "rolls back events, projections, receipts, and effects after a projection failure", () => @@ -1138,12 +1310,13 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => { assert.equal((yield* maintenance.verify).valid, true); yield* sql` - DELETE FROM orchestration_v2_projection_turn_items + UPDATE orchestration_v2_projection_turn_items + SET payload_json = '{}' WHERE turn_item_id = ${items[75]!.id} `; const broken = yield* maintenance.verify; assert.isFalse(broken.valid); - assert.deepEqual(broken.differingThreadIds, [threadId]); + assert.deepEqual(broken.unreadableThreadIds, [threadId]); const rebuilt = yield* maintenance.rebuild; assert.isTrue(rebuilt.valid); diff --git a/apps/server/src/orchestration-v2/IdAllocator.ts b/apps/server/src/orchestration-v2/IdAllocator.ts index 7e07c76590..a3369b04f5 100644 --- a/apps/server/src/orchestration-v2/IdAllocator.ts +++ b/apps/server/src/orchestration-v2/IdAllocator.ts @@ -134,6 +134,7 @@ export interface IdAllocatorV2DeriveShape { readonly delegatedTaskThread: (input: { readonly commandId: CommandId }) => ThreadId; readonly delegatedTaskMessage: (input: { readonly commandId: CommandId }) => MessageId; readonly delegatedTaskTurnItem: (input: { readonly commandId: CommandId }) => TurnItemId; + readonly createdThreadTurnItem: (input: { readonly commandId: CommandId }) => TurnItemId; readonly threadFromProviderThread: (input: { readonly driver: ProviderDriverKind; readonly nativeThreadId: string; @@ -357,6 +358,8 @@ export const layer: Layer.Layer = Layer.succeed( MessageId.make(joinId("message", "delegated-task", input.commandId)), delegatedTaskTurnItem: (input) => TurnItemId.make(joinId("turn-item", "delegated-task", input.commandId)), + createdThreadTurnItem: (input) => + TurnItemId.make(joinId("turn-item", "created-thread", input.commandId)), threadFromProviderThread: (input) => ThreadId.make( joinId("thread", "provider", input.driver, "native-thread", input.nativeThreadId), diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 9443e6d77b..b10e370cc5 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -193,6 +193,7 @@ function commandThreadId(command: OrchestrationV2Command): ThreadId { case "provider.switch": return command.threadId; case "delegated_task.request": + case "thread.created.record": return command.parentThreadId; case "thread.fork": case "thread.merge_back": @@ -3691,6 +3692,108 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }, ); + const dispatchCreatedThreadRecord = Effect.fn("orchestrationV2.dispatch.createdThreadRecord")( + function* ( + command: Extract, + events: Ref.Ref>, + ) { + const parentProjection = yield* projectionStore + .getThreadProjection(command.parentThreadId) + .pipe( + Effect.mapError( + (cause) => + new OrchestratorProjectionError({ + threadId: command.parentThreadId, + cause, + }), + ), + ); + const targetProjection = yield* projectionStore + .getThreadProjection(command.targetThreadId) + .pipe( + Effect.mapError( + (cause) => + new OrchestratorProjectionError({ + threadId: command.targetThreadId, + cause, + }), + ), + ); + const parentRun = parentProjection.runs.find( + (candidate) => candidate.id === command.parentRunId, + ); + const parentNode = parentProjection.nodes.find( + (candidate) => candidate.id === command.parentNodeId, + ); + if ( + parentRun === undefined || + parentNode === undefined || + parentNode.runId !== command.parentRunId || + parentRun.rootNodeId !== command.parentNodeId + ) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Parent node ${command.parentNodeId} is not the root of run ${command.parentRunId}.`, + }); + } + if (parentProjection.thread.projectId !== targetProjection.thread.projectId) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Target thread ${command.targetThreadId} belongs to another project.`, + }); + } + if ( + command.targetRunId !== null && + !targetProjection.runs.some((candidate) => candidate.id === command.targetRunId) + ) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Target run ${command.targetRunId} does not belong to thread ${command.targetThreadId}.`, + }); + } + + const now = yield* DateTime.now; + const parentProviderTurn = providerTurnForRun(parentProjection, parentRun); + const turnItem: OrchestrationV2TurnItem = { + id: idAllocator.derive.createdThreadTurnItem({ commandId: command.commandId }), + threadId: command.parentThreadId, + runId: command.parentRunId, + nodeId: command.parentNodeId, + providerThreadId: parentRun.providerThreadId, + providerTurnId: parentProviderTurn?.id ?? null, + nativeItemRef: null, + parentItemId: null, + ordinal: nextTurnItemOrdinal(parentProjection), + status: "completed", + title: targetProjection.thread.title, + startedAt: now, + completedAt: now, + updatedAt: now, + type: "thread_created", + targetThreadId: command.targetThreadId, + targetRunId: command.targetRunId, + targetProviderInstanceId: targetProjection.thread.modelSelection.instanceId, + targetModel: targetProjection.thread.modelSelection.model, + }; + + yield* emit( + events, + command, + )({ + type: "turn-item.updated", + threadId: command.parentThreadId, + runId: command.parentRunId, + nodeId: command.parentNodeId, + providerInstanceId: parentRun.providerInstanceId, + occurredAt: now, + payload: turnItem, + }); + }, + ); + const dispatchRuntimeRequestRespond = ( command: Extract, events: Ref.Ref>, @@ -4920,6 +5023,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "delegated_task.request": yield* dispatchDelegatedTaskRequest(command, events, effects); break; + case "thread.created.record": + yield* dispatchCreatedThreadRecord(command, events); + break; default: return yield* dispatchUnsupported(command); } diff --git a/apps/server/src/orchestration-v2/ProjectionMaintenance.ts b/apps/server/src/orchestration-v2/ProjectionMaintenance.ts index 023d8ffd26..84260f5ac8 100644 --- a/apps/server/src/orchestration-v2/ProjectionMaintenance.ts +++ b/apps/server/src/orchestration-v2/ProjectionMaintenance.ts @@ -1,8 +1,4 @@ -import { - type OrchestrationV2StoredEvent, - type OrchestrationV2ThreadProjection, - ThreadId, -} from "@t3tools/contracts"; +import { type OrchestrationV2StoredEvent, ThreadId } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -13,8 +9,6 @@ import * as SqlClient from "effect/unstable/sql/SqlClient"; import { EventStoreV2 } from "./EventStore.ts"; import { - applyToProjectionReplayState, - makeProjectionReplayState, ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION, ProjectionStoreV2, } from "./ProjectionStore.ts"; @@ -24,7 +18,7 @@ export interface ProjectionVerificationV2 { readonly schemaVersion: number; readonly expectedSequence: number; readonly projectionSequence: number; - readonly differingThreadIds: ReadonlyArray; + readonly unreadableThreadIds: ReadonlyArray; readonly missingThreadIds: ReadonlyArray; readonly unexpectedThreadIds: ReadonlyArray; } @@ -52,45 +46,6 @@ type ProjectionMetadataRow = { readonly last_sequence: number; }; -function sortedProjection(projection: OrchestrationV2ThreadProjection): unknown { - const sortById = (values: ReadonlyArray) => - values.toSorted((left, right) => left.id.localeCompare(right.id)); - return { - ...projection, - runs: sortById(projection.runs), - attempts: sortById(projection.attempts), - nodes: sortById(projection.nodes), - subagents: sortById(projection.subagents), - providerSessions: sortById(projection.providerSessions), - providerThreads: sortById(projection.providerThreads), - providerTurns: sortById(projection.providerTurns), - runtimeRequests: sortById(projection.runtimeRequests), - messages: sortById(projection.messages), - plans: sortById(projection.plans), - turnItems: sortById(projection.turnItems), - checkpointScopes: sortById(projection.checkpointScopes), - checkpoints: sortById(projection.checkpoints), - contextHandoffs: sortById(projection.contextHandoffs), - contextTransfers: sortById(projection.contextTransfers), - // This is a derived lineage view. Its source entities are compared above. - visibleTurnItems: [], - }; -} - -function stableStringify(value: unknown): string { - if (Array.isArray(value)) { - return `[${value.map(stableStringify).join(",")}]`; - } - if (typeof value === "object" && value !== null) { - const record = value as Record; - return `{${Object.keys(record) - .toSorted() - .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`) - .join(",")}}`; - } - return JSON.stringify(value); -} - export const layer: Layer.Layer< ProjectionMaintenanceV2, never, @@ -120,50 +75,49 @@ export const layer: Layer.Layer< return events; }); - const expectedProjections = (events: ReadonlyArray) => { - const state = makeProjectionReplayState(); - for (const stored of events) { - applyToProjectionReplayState(state, stored.event); - } - return state.projections; - }; - + /** + * EventSink commits the event, its projection updates, and projection metadata in one SQL + * transaction. Startup verification therefore checks that transaction boundary and that every + * stored projection can be decoded. It intentionally does not replay domain events through a + * second projector: doing so creates another implementation of projection semantics that must + * evolve in lockstep with ProjectionStore. + */ const verify = Effect.gen(function* () { - const events = yield* readAllEvents; - const expected = expectedProjections(events); + const expectedThreadRows = yield* sql<{ readonly thread_id: string }>` + SELECT DISTINCT stream_id AS thread_id + FROM orchestration_events + WHERE application_event_version = 2 + AND aggregate_kind = 'thread' + AND event_type = 'thread.created' + ORDER BY stream_id ASC + `; const projectionRows = yield* sql<{ readonly thread_id: string }>` SELECT thread_id FROM orchestration_v2_projection_threads ORDER BY thread_id ASC `; const actualIds = projectionRows.map((row) => ThreadId.make(row.thread_id)); - const expectedIds = [...expected.keys()].toSorted((left, right) => left.localeCompare(right)); + const expectedIds = expectedThreadRows.map((row) => ThreadId.make(row.thread_id)); const actualSet = new Set(actualIds); const expectedSet = new Set(expectedIds); const missingThreadIds = expectedIds.filter((threadId) => !actualSet.has(threadId)); const unexpectedThreadIds = actualIds.filter((threadId) => !expectedSet.has(threadId)); - const differingThreadIds: Array = []; - for (const threadId of expectedIds) { - if (!actualSet.has(threadId)) { - continue; - } - const actual = yield* projectionStore.getThreadProjection(threadId); - const expectedProjection = expected.get(threadId); - if ( - expectedProjection === undefined || - stableStringify(sortedProjection(actual)) !== - stableStringify(sortedProjection(expectedProjection)) - ) { - differingThreadIds.push(threadId); - } - } + const unreadableThreadIds = (yield* Effect.forEach( + actualIds, + (threadId) => + projectionStore.getThreadProjection(threadId).pipe( + Effect.as(null), + Effect.orElseSucceed((): ThreadId | null => threadId), + ), + { concurrency: 8 }, + )).filter((threadId): threadId is ThreadId => threadId !== null); const metadata = yield* sql` SELECT schema_version, last_sequence FROM orchestration_v2_projection_metadata WHERE projection_name = 'thread-projections' LIMIT 1 `; - const expectedSequence = events.at(-1)?.sequence ?? 0; + const expectedSequence = yield* eventStore.latestSequence(); const schemaVersion = metadata[0]?.schema_version ?? 0; const projectionSequence = metadata[0]?.last_sequence ?? 0; return { @@ -172,11 +126,11 @@ export const layer: Layer.Layer< projectionSequence === expectedSequence && missingThreadIds.length === 0 && unexpectedThreadIds.length === 0 && - differingThreadIds.length === 0, + unreadableThreadIds.length === 0, schemaVersion, expectedSequence, projectionSequence, - differingThreadIds, + unreadableThreadIds, missingThreadIds, unexpectedThreadIds, } satisfies ProjectionVerificationV2; diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts index 073ac63995..0f1a3e3839 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts @@ -118,6 +118,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray item.type === "reasoning"); + assert.lengthOf( + progressItems, + 1, + `child thread ${subagent.childThreadId} must coalesce progress into one item`, + ); + const progressItem = progressItems[0]; + if (progressItem === undefined) { + throw new Error(`Missing progress item for subagent ${subagent.id}`); + } + assert.equal(progressItem.text, expectedProgress); + assert.equal(progressItem.status, "completed"); + assert.isFalse(progressItem.streaming); + assert.isNotNull(progressItem.completedAt); + + const parentItem = projection.turnItems.find( + (item) => item.type === "subagent" && item.subagentId === subagent.id, + ); + assert.isDefined(parentItem); + if (parentItem?.type !== "subagent") { + throw new Error(`Missing parent lifecycle item for subagent ${subagent.id}`); + } + assert.equal(parentItem.progress, expectedProgress); } } diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent/claude_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/subagent/claude_transcript.ndjson index 26773f4b22..c22e4aeed8 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent/claude_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent/claude_transcript.ndjson @@ -19,6 +19,7 @@ {"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_019MHopVQzAkpKERfKvRB1cj","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01P6KQcUPy8t2bCbFjv8K4Jz","name":"Read","input":{"file_path":"/private/var/folders/b3/b51_pdxj7dl0t981zpqkxxhr0000gn/T/t3-orchestrator-v2-claude-agent-sdk-record-subagent-jAoxxI/tsconfig.json"},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":1140,"cache_read_input_tokens":7492,"cache_creation":{"ephemeral_5m_input_tokens":1140,"ephemeral_1h_input_tokens":0},"output_tokens":73,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":"toolu_0113VSWTCamvp1adXDZrK5NG","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"a5d6d0ed-bc30-43fb-9295-f338fedbf020"}} {"type":"emit_inbound","label":"user","frame":{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01P6KQcUPy8t2bCbFjv8K4Jz","type":"tool_result","content":"1\t{\"compilerOptions\":{\"module\":\"ESNext\",\"strict\":true,\"target\":\"ES2022\"}}"}]},"parent_tool_use_id":"toolu_0113VSWTCamvp1adXDZrK5NG","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"6814c55d-46df-4aeb-b594-f8819f353925","timestamp":"2026-05-27T00:24:46.995Z"}} {"type":"emit_inbound","label":"user","frame":{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01EV8j88CPEmhoWF3iuvaFSC","type":"tool_result","content":"1\t{\"name\":\"claude-read-only-fixture\",\"private\":true,\"scripts\":{\"typecheck\":\"tsc --noEmit\"}}"}]},"parent_tool_use_id":"toolu_01FfHTrUeymLi4LfqJVmTZjz","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"cd552b77-8f0a-4984-b2e1-8eeea3e63148","timestamp":"2026-05-27T00:24:46.875Z"}} +{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"task_progress","task_id":"a35c9b7d354c20172","tool_use_id":"toolu_01FfHTrUeymLi4LfqJVmTZjz","description":"Summarizing package.json","usage":{"total_tokens":9250,"tool_uses":1,"duration_ms":3090},"last_tool_name":"Read","uuid":"9de3f10b-1955-4be3-a046-0e064e2d0e0d","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d"}} {"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"task_notification","task_id":"a3d3213ffad1bd057","tool_use_id":"toolu_0113VSWTCamvp1adXDZrK5NG","status":"completed","output_file":"","summary":"Read tsconfig.json","usage":{"total_tokens":10750,"tool_uses":1,"duration_ms":5183},"uuid":"71cc121b-cc9f-42ad-aaea-40730ef81125","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d"}} {"type":"emit_inbound","label":"user","frame":{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_0113VSWTCamvp1adXDZrK5NG","type":"tool_result","content":[{"type":"text","text":"Here are the full contents of `tsconfig.json`:\n\n```json\n{\"compilerOptions\":{\"module\":\"ESNext\",\"strict\":true,\"target\":\"ES2022\"}}\n```\n\nIt is a minimal TypeScript configuration with three compiler options set:\n- `module`: `ESNext` — uses ES module syntax\n- `strict`: `true` — enables all strict type-checking options\n- `target`: `ES2022` — compiles down to ES2022 JavaScript"},{"type":"text","text":"agentId: a3d3213ffad1bd057 (use SendMessage with to: 'a3d3213ffad1bd057' to continue this agent)\ntotal_tokens: 10783\ntool_uses: 1\nduration_ms: 5186"}]}]},"parent_tool_use_id":null,"session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"526e0d3c-7688-4b39-8b54-4aa438b93f07","timestamp":"2026-05-27T00:24:50.087Z","tool_use_result":{"status":"completed","prompt":"Read the file `tsconfig.json` in the current working directory and return its full contents.","agentId":"a3d3213ffad1bd057","agentType":"general-purpose","content":[{"type":"text","text":"Here are the full contents of `tsconfig.json`:\n\n```json\n{\"compilerOptions\":{\"module\":\"ESNext\",\"strict\":true,\"target\":\"ES2022\"}}\n```\n\nIt is a minimal TypeScript configuration with three compiler options set:\n- `module`: `ESNext` — uses ES module syntax\n- `strict`: `true` — enables all strict type-checking options\n- `target`: `ES2022` — compiles down to ES2022 JavaScript"}],"totalDurationMs":5186,"totalTokens":10783,"totalToolUseCount":1,"usage":{"input_tokens":1,"cache_creation_input_tokens":2043,"cache_read_input_tokens":8632,"output_tokens":107,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":2043},"inference_geo":"","iterations":[{"input_tokens":1,"output_tokens":107,"cache_read_input_tokens":8632,"cache_creation_input_tokens":2043,"cache_creation":{"ephemeral_5m_input_tokens":2043,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"toolStats":{"readCount":1,"searchCount":0,"bashCount":0,"editFileCount":0,"linesAdded":0,"linesRemoved":0,"otherToolCount":0}}}} {"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"task_notification","task_id":"a35c9b7d354c20172","tool_use_id":"toolu_01FfHTrUeymLi4LfqJVmTZjz","status":"completed","output_file":"","summary":"Read package.json","usage":{"total_tokens":10755,"tool_uses":1,"duration_ms":6211},"uuid":"5fd5a6f9-6045-4b50-99d9-a0bbe8991047","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d"}} diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index 6db5d0f22e..080618e5eb 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -394,14 +394,17 @@ export const make = Effect.gen(function* () { Effect.tap((verification) => verification.valid ? Effect.void - : Effect.logWarning("V2 orchestration projections are stale; rebuilding", { - expectedSequence: verification.expectedSequence, - projectionSequence: verification.projectionSequence, - schemaVersion: verification.schemaVersion, - missingThreadCount: verification.missingThreadIds.length, - unexpectedThreadCount: verification.unexpectedThreadIds.length, - differingThreadCount: verification.differingThreadIds.length, - }), + : Effect.logWarning( + "V2 orchestration projection metadata or structure is invalid; rebuilding", + { + expectedSequence: verification.expectedSequence, + projectionSequence: verification.projectionSequence, + schemaVersion: verification.schemaVersion, + missingThreadCount: verification.missingThreadIds.length, + unexpectedThreadCount: verification.unexpectedThreadIds.length, + unreadableThreadCount: verification.unreadableThreadIds.length, + }, + ), ), ), ), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index e7f3d40987..257a9945cf 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -885,7 +885,8 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => "orchestration_v2.thread_id": command.type === "thread.fork" || command.type === "thread.merge_back" ? command.targetThreadId - : command.type === "delegated_task.request" + : command.type === "delegated_task.request" || + command.type === "thread.created.record" ? command.parentThreadId : command.threadId, ...(command.type === "thread.fork" || command.type === "thread.merge_back" diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 658a68988f..2fd8c4cfe6 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -217,6 +217,7 @@ import { useProject, useProjects, useThread, + useThreadShell, useThreadProposedPlans, useThreadRefs, useThreadVisibleTurnItems, @@ -1432,11 +1433,30 @@ function ChatViewContent(props: ChatViewProps) { : undefined, [draftThread, fallbackDraftProject?.defaultModelSelection, threadId], ); - // Promotion is data-driven: the draft route keeps rendering while the - // server thread (same pre-allocated ref) starts, so live state must not - // depend on which route is mounted. - const isServerThread = activeServerThread !== null; - const activeThread = activeServerThread ?? localDraftThread; + const isServerThread = routeKind === "server" && serverThread !== null; + const activeThread = isServerThread ? serverThread : localDraftThread; + const parentSubagentThreadId = + activeThread?.lineage.relationshipToParent === "subagent" + ? activeThread.lineage.parentThreadId + : null; + const parentSubagentEnvironmentId = activeThread?.environmentId ?? null; + const parentSubagentThreadRef = useMemo(() => { + if (parentSubagentEnvironmentId === null || parentSubagentThreadId === null) { + return null; + } + return scopeThreadRef(parentSubagentEnvironmentId, parentSubagentThreadId); + }, [parentSubagentEnvironmentId, parentSubagentThreadId]); + const parentSubagentThread = useThreadShell(parentSubagentThreadRef); + const parentThreadLink = useMemo( + () => + parentSubagentThreadRef === null + ? null + : { + threadId: parentSubagentThreadRef.threadId, + title: parentSubagentThread?.title ?? "Parent thread", + }, + [parentSubagentThread?.title, parentSubagentThreadRef], + ); const threadError = isServerThread ? (localServerError ?? serverThread?.runtime?.lastError ?? null) : localDraftError; @@ -5921,6 +5941,7 @@ function ChatViewContent(props: ChatViewProps) { routeThreadKey={routeThreadKey} onOpenTurnDiff={onOpenTurnDiff} onOpenThread={onOpenRelatedThread} + parentThreadLink={parentThreadLink} onForkFromRun={onForkFromRun} onRollbackCheckpoint={(input) => void onRollbackCheckpoint(input)} revertTurnCountByUserMessageId={revertTurnCountByUserMessageId} diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 8a42479eda..05ae11370a 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -482,6 +482,16 @@ describe("deriveMessagesTimelineRows", () => { tone: "tool" as const, }, }, + { + id: "thread-created-entry", + kind: "event" as const, + createdAt: "2026-01-01T00:00:10Z", + projectedItem: { + item: { + type: "thread_created", + }, + } as never, + }, { id: "assistant-final-entry", kind: "message" as const, @@ -517,6 +527,7 @@ describe("deriveMessagesTimelineRows", () => { expect(collapsedRows.map((row) => row.id)).toEqual([ "user-entry", "turn-fold:turn-1", + "thread-created-entry", "assistant-final-entry", ]); @@ -534,6 +545,7 @@ describe("deriveMessagesTimelineRows", () => { "turn-fold:turn-1", "assistant-thought-entry", "work-entry-1", + "thread-created-entry", "assistant-final-entry", ]); expect( @@ -604,6 +616,17 @@ describe("deriveMessagesTimelineRows", () => { tone: "tool" as const, }, }, + { + id: "superseded-thread-created-entry", + kind: "event" as const, + createdAt: "2026-01-01T00:00:04.500Z", + attempt: supersededAttempt, + projectedItem: { + item: { + type: "thread_created", + }, + } as never, + }, { id: "steer-user-entry", kind: "message" as const, @@ -654,6 +677,7 @@ describe("deriveMessagesTimelineRows", () => { expect(collapsedRows.map((row) => row.id)).toEqual([ "initial-user-entry", `attempt-fold:${supersededAttemptId}`, + "superseded-thread-created-entry", "steer-user-entry", "active-assistant-entry", ]); @@ -673,6 +697,7 @@ describe("deriveMessagesTimelineRows", () => { `attempt-fold:${supersededAttemptId}`, "superseded-assistant-entry", "superseded-work-entry", + "superseded-thread-created-entry", "steer-user-entry", "active-assistant-entry", ]); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index b87719d1f3..f1e48b32c2 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -1,8 +1,7 @@ import * as Equal from "effect/Equal"; import { formatDuration, - workEntryIndicatesToolNeutralStatus, - workLogEntryIsToolLike, + timelineEntryIsPersistentResourceCard, type TimelineEntry, type WorkLogEntry, } from "../../session-logic"; @@ -297,7 +296,8 @@ function deriveSupersededAttemptFolds( for (const entry of timelineEntries) { if ( entry.attempt?.status !== "superseded" || - (entry.kind === "message" && entry.message.role === "user") + (entry.kind === "message" && entry.message.role === "user") || + timelineEntryIsPersistentResourceCard(entry) ) { continue; } diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx index 6c1bc991fe..846a3ac535 100644 --- a/apps/web/src/components/chat/MessagesTimeline.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx @@ -1,4 +1,4 @@ -import { EnvironmentId, MessageId, RunId } from "@t3tools/contracts"; +import { EnvironmentId, MessageId, RunId, ThreadId } from "@t3tools/contracts"; import { createRef, type ReactNode, type Ref } from "react"; import { renderToStaticMarkup } from "react-dom/server"; import { beforeAll, describe, expect, it, vi } from "vite-plus/test"; @@ -439,6 +439,48 @@ describe("MessagesTimeline", () => { expect(markup).toContain("rounded-2xl bg-accent p-3"); }); + it("identifies user-role messages sent by another agent", async () => { + const { MessagesTimeline } = await import("./MessagesTimeline"); + const entry = buildUserTimelineEntry("Review this area"); + const agentMarkup = renderToStaticMarkup( + , + ); + const userMarkup = renderToStaticMarkup( + , + ); + + expect(agentMarkup).toContain('data-user-message-attribution="agent"'); + expect(agentMarkup).toContain("Sent by another agent"); + expect(userMarkup).not.toContain("Sent by another agent"); + }); + + it("keeps a subagent parent-thread link at the top of an empty timeline", async () => { + const { MessagesTimeline } = await import("./MessagesTimeline"); + const markup = renderToStaticMarkup( + , + ); + + expect(markup).toContain('aria-label="Open parent thread"'); + expect(markup).toContain("Subagent of"); + expect(markup).toContain("Architecture audit"); + expect(markup).not.toContain("Send a message to start the conversation"); + }); + it("keeps steer intent visible on committed user messages", async () => { const { MessagesTimeline } = await import("./MessagesTimeline"); const entry = buildUserTimelineEntry("Adjust the current turn"); @@ -714,6 +756,108 @@ describe("MessagesTimeline", () => { expect(markup).not.toContain("Structured details"); }); + it("renders created threads as linked cards outside the work log", async () => { + const { MessagesTimeline } = await import("./MessagesTimeline"); + const markup = renderToStaticMarkup( + , + ); + + expect(markup).toContain('data-v2-item-type="thread_created"'); + expect(markup).toContain('aria-label="Open Claude research thread"'); + expect(markup).toContain("Claude research thread"); + expect(markup).toContain("claude-default · claude-sonnet-4-6"); + expect(markup).not.toContain("Work Log"); + }); + + it("renders live subagent progress on the persistent linked card", async () => { + const { MessagesTimeline } = await import("./MessagesTimeline"); + const markup = renderToStaticMarkup( + , + ); + + expect(markup).toContain('data-v2-item-type="subagent"'); + expect(markup).toContain('aria-label="Open Package audit"'); + expect(markup).toContain("Reading src/index.ts"); + expect(markup).not.toContain("Inspect the package"); + expect(markup).not.toContain("Work Log"); + }); + it("renders V2 provider failures as standalone error rows", async () => { const { MessagesTimeline } = await import("./MessagesTimeline"); const markup = renderToStaticMarkup( diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 28b3219b90..67212e998a 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -105,6 +105,7 @@ import { formatChatTimestampTooltip, formatShortTimestamp } from "../../timestam import { V2ItemInspector } from "./V2ItemInspector"; import { useV2ItemSupport } from "../../state/v2ItemSupport"; import { isV2LifecycleItem, V2LifecycleRow } from "./V2LifecycleRow"; +import { TimelineSystemDivider } from "./TimelineSystemDivider"; import { buildInlineTerminalContextText, @@ -181,6 +182,10 @@ interface MessagesTimelineProps { routeThreadKey: string; onOpenTurnDiff: (runId: RunId, filePath?: string) => void; onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void; + parentThreadLink?: { + readonly threadId: ThreadId; + readonly title: string; + } | null; onForkFromRun: (input: { readonly sourceThreadId: ThreadId; readonly runId: RunId; @@ -224,6 +229,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ routeThreadKey, onOpenTurnDiff, onOpenThread, + parentThreadLink = null, onForkFromRun, onRollbackCheckpoint, revertTurnCountByUserMessageId, @@ -499,6 +505,23 @@ export const MessagesTimeline = memo(function MessagesTimeline({ }), [activeTurnInProgress, isRevertingCheckpoint, isWorking, latestTurn?.turnId], ); + const listHeader = useMemo( + () => + parentThreadLink === null ? ( + TIMELINE_LIST_HEADER + ) : ( +
+ onOpenThread(parentThreadLink.threadId)} + /> +
+ ), + [onOpenThread, parentThreadLink], + ); // Stable renderItem — no closure deps. Row components read shared state // from TimelineRowCtx, which propagates through LegendList's memo. @@ -511,10 +534,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ [], ); - if (rows.length === 0 && !isWorking) { - if (hideEmptyPlaceholder) { - return null; - } + if (rows.length === 0 && !isWorking && parentThreadLink === null) { return (

@@ -527,57 +547,24 @@ export const MessagesTimeline = memo(function MessagesTimeline({ return ( -

- - ref={listRef} - data={rows} - keyExtractor={keyExtractor} - getItemType={getItemType} - renderItem={renderItem} - estimatedItemSize={90} - initialScrollAtEnd - {...(anchoredEndSpace ? { anchoredEndSpace } : {})} - contentInsetEndAdjustment={contentInsetEndAdjustment} - maintainScrollAtEnd={ - anchoredEndSpace - ? false - : { - animated: false, - on: { - dataChange: true, - itemLayout: true, - layout: true, - }, - } - } - maintainVisibleContentPosition={{ - data: true, - size: false, - }} - onScroll={handleScroll} - className={cn( - "scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5", - topFadeEnabled && "chat-timeline-scroll-fade", - )} - ListHeaderComponent={topFadeEnabled ? TIMELINE_LIST_FADE_HEADER : TIMELINE_LIST_HEADER} - ListFooterComponent={TIMELINE_LIST_FOOTER} - /> - { - onManualNavigation(); - void listRef.current?.scrollToIndex({ - index: item.rowIndex, - animated: true, - viewOffset: 24, - }); - }} - /> -
+ + ref={listRef} + data={rows} + keyExtractor={keyExtractor} + getItemType={getItemType} + renderItem={renderItem} + estimatedItemSize={90} + initialScrollAtEnd + {...(anchoredEndSpace ? { anchoredEndSpace } : {})} + contentInsetEndAdjustment={contentInsetEndAdjustment} + maintainScrollAtEnd={!foldToggleSettling} + maintainScrollAtEndThreshold={0.1} + maintainVisibleContentPosition + onScroll={handleScroll} + className="scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 sm:px-5" + ListHeaderComponent={listHeader} + ListFooterComponent={TIMELINE_LIST_FOOTER} + /> ); @@ -937,7 +924,15 @@ function UserTimelineRow({ row }: { row: Extract -
+ {row.message.createdBy === "agent" ? ( +

+ Sent by another agent +

+ ) : null} +
{regularImages.length > 0 && (
{regularImages.map((image: NonNullable[number]) => ( @@ -1332,7 +1327,7 @@ function v2EventPresentation(item: OrchestrationV2TurnItem): { case "subagent": return { label: item.title ?? "Subagent", - detail: item.result ?? item.prompt, + detail: item.result ?? item.progress ?? item.prompt, tone: item.status === "failed" ? "danger" : item.status === "completed" ? "success" : "muted", icon: HammerIcon, diff --git a/apps/web/src/components/chat/TimelineSystemDivider.tsx b/apps/web/src/components/chat/TimelineSystemDivider.tsx new file mode 100644 index 0000000000..fbf5a46bd0 --- /dev/null +++ b/apps/web/src/components/chat/TimelineSystemDivider.tsx @@ -0,0 +1,46 @@ +import type { LucideIcon } from "lucide-react"; + +import { cn } from "~/lib/utils"; + +export function TimelineSystemDivider(props: { + readonly label: string; + readonly detail?: string | null; + readonly tone?: "neutral" | "danger"; + readonly icon?: LucideIcon; + readonly actionLabel?: string; + readonly onAction?: () => void; +}) { + const Icon = props.icon; + const content = ( + <> + {Icon ? : null} + {props.label} + {props.detail ? · {props.detail} : null} + + ); + + return ( +
+
+ ); +} diff --git a/apps/web/src/components/chat/V2LifecycleRow.tsx b/apps/web/src/components/chat/V2LifecycleRow.tsx index 652143dd59..ef366f9c17 100644 --- a/apps/web/src/components/chat/V2LifecycleRow.tsx +++ b/apps/web/src/components/chat/V2LifecycleRow.tsx @@ -1,9 +1,17 @@ import type { OrchestrationV2TurnItem, ThreadId } from "@t3tools/contracts"; import type { TimestampFormat } from "@t3tools/contracts/settings"; -import { GitForkIcon, HammerIcon, MinusIcon, XIcon, ZapIcon } from "lucide-react"; +import { + ExternalLinkIcon, + GitForkIcon, + HammerIcon, + MessageSquareIcon, + MinusIcon, + XIcon, + ZapIcon, +} from "lucide-react"; -import { cn } from "~/lib/utils"; import { formatShortTimestamp } from "../../timestampFormat"; +import { TimelineSystemDivider } from "./TimelineSystemDivider"; const LIFECYCLE_TYPES = new Set([ "run_interrupt_request", @@ -12,6 +20,7 @@ const LIFECYCLE_TYPES = new Set([ "handoff", "fork", "subagent", + "thread_created", ]); export function isV2LifecycleItem(item: OrchestrationV2TurnItem): boolean { @@ -46,7 +55,12 @@ export function V2LifecycleRow(props: { } if (item.type === "run_interrupt_result") { return ( - + ); } if (item.type === "compaction") { @@ -55,7 +69,7 @@ export function V2LifecycleRow(props: { ? null : `${item.beforeTokenCount ?? "?"} → ${item.afterTokenCount ?? "?"} tokens`; return ( - ); } - if (item.type === "subagent") { - const content = ( - <> - - - {item.title ?? "Subagent"} - - - {item.result ?? item.prompt} - - - {item.status} - - + if (item.type === "thread_created") { + return ( + ); - return item.childThreadId === null ? ( -
- {content} -
- ) : ( - + } + if (item.type === "subagent") { + return ( + ); } return null; } -function SystemDivider(props: { - readonly label: string; - readonly detail?: string | null; - readonly tone?: "neutral" | "danger"; - readonly icon?: typeof GitForkIcon; - readonly actionLabel?: string; - readonly onAction?: () => void; +function RelatedThreadCard(props: { + readonly itemType: "subagent" | "thread_created"; + readonly icon: typeof HammerIcon; + readonly title: string; + readonly detail: string; + readonly badge: string; + readonly threadId: ThreadId | null; + readonly onOpenThread: (threadId: ThreadId) => void; }) { const Icon = props.icon; + const threadId = props.threadId; const content = ( <> - {Icon ? : null} - {props.label} - {props.detail ? · {props.detail} : null} + + {props.title} + {props.detail} + + {props.badge} + + {threadId === null ? null : ( +