Record created threads and subagent progress
- Add parent-thread records for spawned child threads - Persist Claude subagent progress as reasoning items - Tighten projection verification around readable thread projections
This commit is contained in:
1 parent
c529c610e3
commit
fc23be8184
26 files changed
+1066
-206
No files matched your search
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<IdAllocatorV2> = 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),
|
||||
|
||||
@@ -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<OrchestrationV2Command, { readonly type: "thread.created.record" }>,
|
||||
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
|
||||
) {
|
||||
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<OrchestrationV2Command, { readonly type: "runtime-request.respond" }>,
|
||||
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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<ThreadId>;
|
||||
readonly unreadableThreadIds: ReadonlyArray<ThreadId>;
|
||||
readonly missingThreadIds: ReadonlyArray<ThreadId>;
|
||||
readonly unexpectedThreadIds: ReadonlyArray<ThreadId>;
|
||||
}
|
||||
@@ -52,45 +46,6 @@ type ProjectionMetadataRow = {
|
||||
readonly last_sequence: number;
|
||||
};
|
||||
|
||||
function sortedProjection(projection: OrchestrationV2ThreadProjection): unknown {
|
||||
const sortById = <A extends { readonly id: string }>(values: ReadonlyArray<A>) =>
|
||||
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<string, unknown>;
|
||||
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<OrchestrationV2StoredEvent>) => {
|
||||
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<ThreadId> = [];
|
||||
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<ThreadId | null>(null),
|
||||
Effect.orElseSucceed((): ThreadId | null => threadId),
|
||||
),
|
||||
{ concurrency: 8 },
|
||||
)).filter((threadId): threadId is ThreadId => threadId !== null);
|
||||
const metadata = yield* sql<ProjectionMetadataRow>`
|
||||
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;
|
||||
|
||||
@@ -118,6 +118,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<Thread
|
||||
case "provider.switch":
|
||||
return [command.threadId];
|
||||
case "delegated_task.request":
|
||||
case "thread.created.record":
|
||||
return [command.parentThreadId];
|
||||
case "thread.fork":
|
||||
case "thread.merge_back":
|
||||
|
||||
@@ -67,10 +67,14 @@ export function assertClaudeSubagentOutput(
|
||||
),
|
||||
);
|
||||
for (const subagent of projection.subagents) {
|
||||
const expectedProgress = subagent.prompt.includes("package.json")
|
||||
? "Summarizing package.json"
|
||||
: "Reading tsconfig.json";
|
||||
assert.equal(subagent.origin, "provider_native");
|
||||
assert.equal(subagent.createdBy, "agent");
|
||||
assert.equal(subagent.driver, "claudeAgent");
|
||||
assert.equal(subagent.status, "completed");
|
||||
assert.equal(subagent.progress, expectedProgress);
|
||||
assert.isNull(subagent.providerThreadId);
|
||||
assert.isNotNull(subagent.childThreadId);
|
||||
assert.isNotNull(subagent.nativeTaskRef);
|
||||
@@ -88,7 +92,12 @@ export function assertClaudeSubagentOutput(
|
||||
assert.lengthOf(childProjection.providerThreads, 0);
|
||||
assert.lengthOf(childProjection.providerTurns, 0);
|
||||
assertExecutionNodeKinds(childProjection, ["root_turn", "tool_call"]);
|
||||
assertTurnItemTypes(childProjection, ["user_message", "dynamic_tool", "assistant_message"]);
|
||||
assertTurnItemTypes(childProjection, [
|
||||
"user_message",
|
||||
"reasoning",
|
||||
"dynamic_tool",
|
||||
"assistant_message",
|
||||
]);
|
||||
assertUserMessagesInclude(childProjection, [subagent.prompt]);
|
||||
assert.isTrue(
|
||||
childProjection.turnItems.some(
|
||||
@@ -99,5 +108,28 @@ export function assertClaudeSubagentOutput(
|
||||
),
|
||||
`child thread ${subagent.childThreadId} must contain the subagent response`,
|
||||
);
|
||||
const progressItems = childProjection.turnItems.filter((item) => 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);
|
||||
}
|
||||
}
|
||||
@@ -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)\n<usage>total_tokens: 10783\ntool_uses: 1\nduration_ms: 5186</usage>"}]}]},"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"}}
|
||||
|
||||
@@ -408,14 +408,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,
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -896,7 +896,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"
|
||||
|
||||
@@ -197,6 +197,7 @@ import {
|
||||
useProject,
|
||||
useProjects,
|
||||
useThread,
|
||||
useThreadShell,
|
||||
useThreadProposedPlans,
|
||||
useThreadRefs,
|
||||
useThreadVisibleTurnItems,
|
||||
@@ -1247,6 +1248,28 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
);
|
||||
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;
|
||||
@@ -4928,6 +4951,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
routeThreadKey={routeThreadKey}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
onOpenThread={onOpenRelatedThread}
|
||||
parentThreadLink={parentThreadLink}
|
||||
onForkFromRun={onForkFromRun}
|
||||
onRollbackCheckpoint={(input) => void onRollbackCheckpoint(input)}
|
||||
revertTurnCountByUserMessageId={revertTurnCountByUserMessageId}
|
||||
|
||||
@@ -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",
|
||||
]);
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import * as Equal from "effect/Equal";
|
||||
import { formatDuration, type TimelineEntry, type WorkLogEntry } from "../../session-logic";
|
||||
import {
|
||||
formatDuration,
|
||||
timelineEntryIsPersistentResourceCard,
|
||||
type TimelineEntry,
|
||||
type WorkLogEntry,
|
||||
} from "../../session-logic";
|
||||
import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
|
||||
import {
|
||||
type MessageId,
|
||||
@@ -190,7 +195,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;
|
||||
}
|
||||
|
||||
@@ -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";
|
||||
@@ -218,6 +218,48 @@ describe("MessagesTimeline", () => {
|
||||
expect(markup).toContain('data-user-message-collapsible="false"');
|
||||
});
|
||||
|
||||
it("identifies user-role messages sent by another agent", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const entry = buildUserTimelineEntry("Review this area");
|
||||
const agentMarkup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
timelineEntries={[
|
||||
{
|
||||
...entry,
|
||||
message: { ...entry.message, createdBy: "agent", creationSource: "provider" },
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
const userMarkup = renderToStaticMarkup(
|
||||
<MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
|
||||
);
|
||||
|
||||
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(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
timelineEntries={[]}
|
||||
parentThreadLink={{
|
||||
threadId: ThreadId.make("thread-parent"),
|
||||
title: "Architecture audit",
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
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");
|
||||
@@ -496,6 +538,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(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "thread-created",
|
||||
kind: "event",
|
||||
createdAt: MESSAGE_CREATED_AT,
|
||||
projectedItem: {
|
||||
position: 0,
|
||||
visibility: "local",
|
||||
sourceThreadId: "thread-1",
|
||||
sourceItemId: "thread-created",
|
||||
item: {
|
||||
id: "thread-created",
|
||||
threadId: "thread-1",
|
||||
runId: "run-1",
|
||||
nodeId: "node-1",
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: 1,
|
||||
status: "completed",
|
||||
title: "Claude research thread",
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
updatedAt: {},
|
||||
type: "thread_created",
|
||||
targetThreadId: "thread-2",
|
||||
targetRunId: "run-2",
|
||||
targetProviderInstanceId: "claude-default",
|
||||
targetModel: "claude-sonnet-4-6",
|
||||
},
|
||||
} as never,
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
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(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "subagent-progress",
|
||||
kind: "event",
|
||||
createdAt: MESSAGE_CREATED_AT,
|
||||
projectedItem: {
|
||||
position: 0,
|
||||
visibility: "local",
|
||||
sourceThreadId: "thread-1",
|
||||
sourceItemId: "subagent-progress",
|
||||
item: {
|
||||
id: "subagent-progress",
|
||||
threadId: "thread-1",
|
||||
runId: "run-1",
|
||||
nodeId: "node-subagent-1",
|
||||
providerThreadId: "provider-thread-1",
|
||||
providerTurnId: "provider-turn-1",
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: 1,
|
||||
status: "running",
|
||||
title: "Package audit",
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
updatedAt: {},
|
||||
type: "subagent",
|
||||
subagentId: "node-subagent-1",
|
||||
origin: "provider_native",
|
||||
driver: "claudeAgent",
|
||||
providerInstanceId: "claudeAgent",
|
||||
childThreadId: "thread-subagent-1",
|
||||
prompt: "Inspect the package",
|
||||
progress: "Reading src/index.ts",
|
||||
result: null,
|
||||
},
|
||||
} as never,
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
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(
|
||||
|
||||
@@ -100,6 +100,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,
|
||||
@@ -174,6 +175,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;
|
||||
@@ -212,6 +217,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
routeThreadKey,
|
||||
onOpenTurnDiff,
|
||||
onOpenThread,
|
||||
parentThreadLink = null,
|
||||
onForkFromRun,
|
||||
onRollbackCheckpoint,
|
||||
revertTurnCountByUserMessageId,
|
||||
@@ -395,6 +401,23 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
}),
|
||||
[activeTurnInProgress, isRevertingCheckpoint, isWorking],
|
||||
);
|
||||
const listHeader = useMemo(
|
||||
() =>
|
||||
parentThreadLink === null ? (
|
||||
TIMELINE_LIST_HEADER
|
||||
) : (
|
||||
<div className="mx-auto w-full min-w-0 max-w-3xl pt-1 sm:pt-2">
|
||||
<TimelineSystemDivider
|
||||
label="Subagent of"
|
||||
detail={parentThreadLink.title}
|
||||
icon={GitForkIcon}
|
||||
actionLabel="Open parent thread"
|
||||
onAction={() => onOpenThread(parentThreadLink.threadId)}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
[onOpenThread, parentThreadLink],
|
||||
);
|
||||
|
||||
// Stable renderItem — no closure deps. Row components read shared state
|
||||
// from TimelineRowCtx, which propagates through LegendList's memo.
|
||||
@@ -407,7 +430,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
[],
|
||||
);
|
||||
|
||||
if (rows.length === 0 && !isWorking) {
|
||||
if (rows.length === 0 && !isWorking && parentThreadLink === null) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-sm text-muted-foreground/30">
|
||||
@@ -435,7 +458,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
maintainVisibleContentPosition
|
||||
onScroll={handleScroll}
|
||||
className="scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 sm:px-5"
|
||||
ListHeaderComponent={TIMELINE_LIST_HEADER}
|
||||
ListHeaderComponent={listHeader}
|
||||
ListFooterComponent={TIMELINE_LIST_FOOTER}
|
||||
/>
|
||||
</TimelineRowActivityCtx>
|
||||
@@ -517,6 +540,14 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
|
||||
|
||||
return (
|
||||
<div className="group flex flex-col items-end gap-1">
|
||||
{row.message.createdBy === "agent" ? (
|
||||
<p
|
||||
className="me-1 text-[11px] text-muted-foreground/70"
|
||||
data-user-message-attribution="agent"
|
||||
>
|
||||
Sent by another agent
|
||||
</p>
|
||||
) : null}
|
||||
<div className="relative max-w-[80%] rounded-2xl border border-border bg-secondary p-3">
|
||||
{regularImages.length > 0 && (
|
||||
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
|
||||
@@ -912,7 +943,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,
|
||||
|
||||
@@ -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 ? <Icon className="size-3 shrink-0" /> : null}
|
||||
<span className="font-medium">{props.label}</span>
|
||||
{props.detail ? <span className="max-w-80 truncate opacity-70">· {props.detail}</span> : null}
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-w-0 items-center gap-2 py-2 text-[11px] text-muted-foreground",
|
||||
props.tone === "danger" && "text-destructive",
|
||||
)}
|
||||
>
|
||||
<span aria-hidden="true" className="h-px flex-1 bg-border/70" />
|
||||
{props.onAction ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={props.actionLabel}
|
||||
onClick={props.onAction}
|
||||
className="flex min-w-0 items-center gap-1.5 rounded-full border border-border/70 bg-background px-2.5 py-1 transition-colors hover:bg-muted"
|
||||
title={props.actionLabel}
|
||||
>
|
||||
{content}
|
||||
</button>
|
||||
) : (
|
||||
<span className="flex min-w-0 items-center gap-1.5 rounded-full px-2 py-1">{content}</span>
|
||||
)}
|
||||
<span aria-hidden="true" className="h-px flex-1 bg-border/70" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<OrchestrationV2TurnItem["type"]>([
|
||||
"run_interrupt_request",
|
||||
@@ -12,6 +20,7 @@ const LIFECYCLE_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
|
||||
"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 (
|
||||
<SystemDivider label="Run interrupted" detail={item.message} tone="danger" icon={XIcon} />
|
||||
<TimelineSystemDivider
|
||||
label="Run interrupted"
|
||||
detail={item.message}
|
||||
tone="danger"
|
||||
icon={XIcon}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (item.type === "compaction") {
|
||||
@@ -55,7 +69,7 @@ export function V2LifecycleRow(props: {
|
||||
? null
|
||||
: `${item.beforeTokenCount ?? "?"} → ${item.afterTokenCount ?? "?"} tokens`;
|
||||
return (
|
||||
<SystemDivider
|
||||
<TimelineSystemDivider
|
||||
label="Context compacted"
|
||||
detail={item.summary ?? tokenDetail}
|
||||
icon={MinusIcon}
|
||||
@@ -64,7 +78,7 @@ export function V2LifecycleRow(props: {
|
||||
}
|
||||
if (item.type === "handoff") {
|
||||
return (
|
||||
<SystemDivider
|
||||
<TimelineSystemDivider
|
||||
label="Context handoff"
|
||||
icon={ZapIcon}
|
||||
tone={item.status === "failed" ? "danger" : "neutral"}
|
||||
@@ -78,7 +92,7 @@ export function V2LifecycleRow(props: {
|
||||
if (item.type === "fork") {
|
||||
const relatedThreadId = item.source.type === "run" ? item.source.threadId : item.targetThreadId;
|
||||
return (
|
||||
<SystemDivider
|
||||
<TimelineSystemDivider
|
||||
label={item.source.type === "run" ? "Forked from conversation" : "Conversation fork"}
|
||||
icon={GitForkIcon}
|
||||
actionLabel={item.source.type === "run" ? "Open source conversation" : "Open fork"}
|
||||
@@ -86,75 +100,76 @@ export function V2LifecycleRow(props: {
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (item.type === "subagent") {
|
||||
const content = (
|
||||
<>
|
||||
<HammerIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
<span className="min-w-0 flex-1 truncate text-xs font-medium">
|
||||
{item.title ?? "Subagent"}
|
||||
</span>
|
||||
<span className="max-w-[50%] truncate text-xs text-muted-foreground">
|
||||
{item.result ?? item.prompt}
|
||||
</span>
|
||||
<span className="rounded-full border border-border/70 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">
|
||||
{item.status}
|
||||
</span>
|
||||
</>
|
||||
if (item.type === "thread_created") {
|
||||
return (
|
||||
<RelatedThreadCard
|
||||
itemType={item.type}
|
||||
icon={MessageSquareIcon}
|
||||
title={item.title ?? "Created thread"}
|
||||
detail={`${item.targetProviderInstanceId} · ${item.targetModel}`}
|
||||
badge="created"
|
||||
threadId={item.targetThreadId}
|
||||
onOpenThread={props.onOpenThread}
|
||||
/>
|
||||
);
|
||||
return item.childThreadId === null ? (
|
||||
<div className="flex min-w-0 items-center gap-2 rounded-lg border border-border/60 bg-card/30 px-3 py-2">
|
||||
{content}
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => item.childThreadId && props.onOpenThread(item.childThreadId)}
|
||||
className="flex w-full min-w-0 items-center gap-2 rounded-lg border border-border/60 bg-card/30 px-3 py-2 text-left transition-colors hover:bg-muted/50"
|
||||
>
|
||||
{content}
|
||||
</button>
|
||||
}
|
||||
if (item.type === "subagent") {
|
||||
return (
|
||||
<RelatedThreadCard
|
||||
itemType={item.type}
|
||||
icon={HammerIcon}
|
||||
title={item.title ?? "Subagent"}
|
||||
detail={item.result ?? item.progress ?? item.prompt}
|
||||
badge={item.status}
|
||||
threadId={item.childThreadId}
|
||||
onOpenThread={props.onOpenThread}
|
||||
/>
|
||||
);
|
||||
}
|
||||
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 ? <Icon className="size-3 shrink-0" /> : null}
|
||||
<span className="font-medium">{props.label}</span>
|
||||
{props.detail ? <span className="max-w-80 truncate opacity-70">· {props.detail}</span> : null}
|
||||
<Icon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
<span className="min-w-0 flex-1 truncate text-xs font-medium">{props.title}</span>
|
||||
<span className="max-w-[50%] truncate text-xs text-muted-foreground">{props.detail}</span>
|
||||
<span className="rounded-full border border-border/70 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">
|
||||
{props.badge}
|
||||
</span>
|
||||
{threadId === null ? null : (
|
||||
<ExternalLinkIcon className="size-3 shrink-0 text-muted-foreground" aria-hidden="true" />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
return (
|
||||
|
||||
return threadId === null ? (
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-w-0 items-center gap-2 py-2 text-[11px] text-muted-foreground",
|
||||
props.tone === "danger" && "text-destructive",
|
||||
)}
|
||||
data-v2-item-type={props.itemType}
|
||||
className="flex min-w-0 items-center gap-2 rounded-lg border border-border/60 bg-card/30 px-3 py-2"
|
||||
>
|
||||
<span aria-hidden="true" className="h-px flex-1 bg-border/70" />
|
||||
{props.onAction ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={props.onAction}
|
||||
className="flex min-w-0 items-center gap-1.5 rounded-full border border-border/70 bg-background px-2.5 py-1 transition-colors hover:bg-muted"
|
||||
title={props.actionLabel}
|
||||
>
|
||||
{content}
|
||||
</button>
|
||||
) : (
|
||||
<span className="flex min-w-0 items-center gap-1.5 rounded-full px-2 py-1">{content}</span>
|
||||
)}
|
||||
<span aria-hidden="true" className="h-px flex-1 bg-border/70" />
|
||||
{content}
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
data-v2-item-type={props.itemType}
|
||||
aria-label={`Open ${props.title}`}
|
||||
onClick={() => props.onOpenThread(threadId)}
|
||||
className="flex w-full min-w-0 items-center gap-2 rounded-lg border border-border/60 bg-card/30 px-3 py-2 text-left transition-colors hover:bg-muted/50"
|
||||
>
|
||||
{content}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -3162,11 +3162,18 @@ function workLogRowContent(item: OrchestrationV2TurnItem): WorkLogRowContent {
|
||||
preview: `→ ${compactId(item.targetThreadId) ?? item.targetThreadId}`,
|
||||
tone: "muted",
|
||||
};
|
||||
case "thread_created":
|
||||
return {
|
||||
glyph: "↗",
|
||||
label: item.title ?? "Thread created",
|
||||
preview: `${item.targetProviderInstanceId} · ${item.targetModel}`,
|
||||
tone: "emerald",
|
||||
};
|
||||
case "subagent":
|
||||
return {
|
||||
glyph: "↳",
|
||||
label: item.title ?? "Subagent",
|
||||
preview: clipOneLine(item.result ?? item.prompt, 120),
|
||||
preview: clipOneLine(item.result ?? item.progress ?? item.prompt, 120),
|
||||
tone: item.status === "completed" ? "emerald" : "sky",
|
||||
};
|
||||
case "user_message":
|
||||
@@ -3626,7 +3633,7 @@ function ChatSubagentItem(props: {
|
||||
readonly onOpenThread: (threadId: ThreadId) => void;
|
||||
}) {
|
||||
const label = props.item.title ?? "Subagent";
|
||||
const detail = props.item.result ?? props.item.prompt;
|
||||
const detail = props.item.result ?? props.item.progress ?? props.item.prompt;
|
||||
const content = (
|
||||
<>
|
||||
<ToolKindPill kind="AGENT" />
|
||||
|
||||
@@ -145,7 +145,7 @@ describe("V2 session presentation", () => {
|
||||
expect(targets.has(steerMessageId)).toBe(false);
|
||||
});
|
||||
|
||||
it("uses visible turn item order and keeps interruption lifecycle entries standalone", () => {
|
||||
it("uses visible turn item order and keeps lifecycle resource entries standalone", () => {
|
||||
const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
|
||||
const threadId = ThreadId.make("thread-visible");
|
||||
const runId = RunId.make("run-visible");
|
||||
@@ -213,6 +213,15 @@ describe("V2 session presentation", () => {
|
||||
retryable: false,
|
||||
},
|
||||
} satisfies OrchestrationV2TurnItem;
|
||||
const threadCreatedItem = {
|
||||
...base("item-thread-created", 6),
|
||||
type: "thread_created" as const,
|
||||
title: "Follow-up thread",
|
||||
targetThreadId: ThreadId.make("thread-follow-up"),
|
||||
targetRunId: RunId.make("run-follow-up"),
|
||||
targetProviderInstanceId: ProviderInstanceId.make("claude-default"),
|
||||
targetModel: "claude-sonnet-4-6",
|
||||
} satisfies OrchestrationV2TurnItem;
|
||||
const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = [
|
||||
userItem,
|
||||
requestItem,
|
||||
@@ -220,6 +229,7 @@ describe("V2 session presentation", () => {
|
||||
resultItem,
|
||||
todoItem,
|
||||
errorItem,
|
||||
threadCreatedItem,
|
||||
].map((item, position) => ({
|
||||
position,
|
||||
visibility: "local" as const,
|
||||
@@ -240,6 +250,7 @@ describe("V2 session presentation", () => {
|
||||
["event", resultItem.id],
|
||||
["work", todoItem.id],
|
||||
["event", errorItem.id],
|
||||
["event", threadCreatedItem.id],
|
||||
]);
|
||||
const commandEntry = entries[2];
|
||||
const userEntry = entries[0];
|
||||
@@ -247,6 +258,8 @@ describe("V2 session presentation", () => {
|
||||
if (userEntry?.kind === "message") {
|
||||
expect(userEntry.projectedItem).toBe(visibleTurnItems[0]);
|
||||
expect(userEntry.message.inputIntent).toBe("turn_start");
|
||||
expect(userEntry.message.createdBy).toBe("user");
|
||||
expect(userEntry.message.creationSource).toBe("web");
|
||||
}
|
||||
expect(commandEntry?.kind).toBe("work");
|
||||
if (commandEntry?.kind === "work") {
|
||||
@@ -268,6 +281,11 @@ describe("V2 session presentation", () => {
|
||||
expect(errorEntry.projectedItem.item.failure.message).toBe("Invalid reasoning effort.");
|
||||
}
|
||||
}
|
||||
const threadCreatedEntry = entries[6];
|
||||
expect(threadCreatedEntry?.kind).toBe("event");
|
||||
if (threadCreatedEntry?.kind === "event") {
|
||||
expect(threadCreatedEntry.projectedItem.item.type).toBe("thread_created");
|
||||
}
|
||||
});
|
||||
|
||||
it("resolves attempt identity through V2 execution nodes", () => {
|
||||
|
||||
@@ -338,9 +338,22 @@ const STANDALONE_V2_ITEM_TYPES = new Set<OrchestrationV2ProjectedTurnItem["item"
|
||||
"run_interrupt_request",
|
||||
"run_interrupt_result",
|
||||
"subagent",
|
||||
"thread_created",
|
||||
"user_input_request",
|
||||
]);
|
||||
|
||||
const PERSISTENT_RESOURCE_V2_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
|
||||
"fork",
|
||||
"subagent",
|
||||
"thread_created",
|
||||
]);
|
||||
|
||||
export function timelineEntryIsPersistentResourceCard(entry: TimelineEntry): boolean {
|
||||
return (
|
||||
entry.kind === "event" && PERSISTENT_RESOURCE_V2_ITEM_TYPES.has(entry.projectedItem.item.type)
|
||||
);
|
||||
}
|
||||
|
||||
function projectedItemCreatedAt(row: OrchestrationV2ProjectedTurnItem): string {
|
||||
return DateTime.formatIso(row.item.startedAt ?? row.item.updatedAt);
|
||||
}
|
||||
@@ -530,6 +543,9 @@ export function deriveTimelineEntriesFromVisibleTurnItems(input: {
|
||||
: {}),
|
||||
runId: item.runId,
|
||||
streaming: item.type === "assistant_message" && item.streaming,
|
||||
...(item.type === "user_message"
|
||||
? { createdBy: item.createdBy, creationSource: item.creationSource }
|
||||
: {}),
|
||||
createdAt,
|
||||
updatedAt: DateTime.formatIso(item.updatedAt),
|
||||
...(item.type === "user_message" ? { inputIntent: item.inputIntent } : {}),
|
||||
|
||||
@@ -65,7 +65,12 @@ describe("V2 client presentation", () => {
|
||||
expect(thread.runtime?.status).toBe("running");
|
||||
expect(thread.runs).toHaveLength(1);
|
||||
expect(thread.availableActions.canInterrupt).toBe(true);
|
||||
expect(thread.messages[0]).toMatchObject({ text: "Hello", runId });
|
||||
expect(thread.messages[0]).toMatchObject({
|
||||
text: "Hello",
|
||||
runId,
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the complete payload for generic V2 work-item rendering", () => {
|
||||
|
||||
@@ -7,6 +7,8 @@ import type {
|
||||
MessageId,
|
||||
OrchestrationProjectShell,
|
||||
OrchestrationV2PlanArtifact,
|
||||
OrchestrationV2Actor,
|
||||
OrchestrationV2CreationSource,
|
||||
OrchestrationV2ProviderCapabilities,
|
||||
OrchestrationV2RunStatus,
|
||||
OrchestrationV2ShellSnapshot,
|
||||
@@ -83,6 +85,8 @@ export interface ThreadConversationMessage {
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||
readonly runId: RunId | null;
|
||||
readonly streaming: boolean;
|
||||
readonly createdBy?: OrchestrationV2Actor;
|
||||
readonly creationSource?: OrchestrationV2CreationSource;
|
||||
readonly createdAt: string;
|
||||
readonly updatedAt: string;
|
||||
}
|
||||
@@ -371,10 +375,16 @@ function summarizeWorkItem(item: OrchestrationV2TurnItem): {
|
||||
};
|
||||
case "fork":
|
||||
return { label: title ?? "Thread forked", detail: item.targetThreadId, toolData: item };
|
||||
case "thread_created":
|
||||
return {
|
||||
label: title ?? "Thread created",
|
||||
detail: `${item.targetProviderInstanceId} · ${item.targetModel}`,
|
||||
toolData: item,
|
||||
};
|
||||
case "subagent":
|
||||
return {
|
||||
label: title ?? "Subagent",
|
||||
detail: item.result ?? item.prompt,
|
||||
detail: item.result ?? item.progress ?? item.prompt,
|
||||
toolTitle: title ?? "Subagent",
|
||||
toolData: item,
|
||||
};
|
||||
@@ -535,6 +545,8 @@ function presentMessages(
|
||||
attachments: message.attachments,
|
||||
runId: message.runId,
|
||||
streaming: message.streaming,
|
||||
createdBy: message.createdBy,
|
||||
creationSource: message.creationSource,
|
||||
createdAt: iso(message.createdAt),
|
||||
updatedAt: iso(message.updatedAt),
|
||||
}));
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
|
||||
const now = DateTime.makeUnsafe("2026-04-20T00:00:00.000Z");
|
||||
const decodeOrchestrationV2Command = Schema.decodeUnknownSync(OrchestrationV2Command);
|
||||
const decodeOrchestrationV2TurnItem = Schema.decodeUnknownSync(OrchestrationV2TurnItem);
|
||||
|
||||
describe("orchestration V2 contracts", () => {
|
||||
it("decodes nested checkpoint scopes without making child scopes advance app run count", () => {
|
||||
@@ -163,6 +164,50 @@ describe("orchestration V2 contracts", () => {
|
||||
expect(command.parentNodeId).toBe(NodeId.make("node-parent-1"));
|
||||
});
|
||||
|
||||
it("decodes durable created-thread timeline records", () => {
|
||||
const command = decodeOrchestrationV2Command({
|
||||
type: "thread.created.record",
|
||||
commandId: "command-thread-record-1",
|
||||
parentThreadId: "thread-parent-1",
|
||||
parentRunId: "run-parent-1",
|
||||
parentNodeId: "node-parent-1",
|
||||
targetThreadId: "thread-child-1",
|
||||
targetRunId: "run-child-1",
|
||||
});
|
||||
const item = decodeOrchestrationV2TurnItem({
|
||||
id: "turn-item-thread-created-1",
|
||||
type: "thread_created",
|
||||
threadId: "thread-parent-1",
|
||||
runId: "run-parent-1",
|
||||
nodeId: "node-parent-1",
|
||||
providerThreadId: "provider-thread-parent-1",
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: 4,
|
||||
status: "completed",
|
||||
title: "Child thread",
|
||||
targetThreadId: "thread-child-1",
|
||||
targetRunId: "run-child-1",
|
||||
targetProviderInstanceId: "claude-default",
|
||||
targetModel: "claude-sonnet-4-6",
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
expect(command.type).toBe("thread.created.record");
|
||||
if (command.type !== "thread.created.record") {
|
||||
throw new Error("expected thread.created.record");
|
||||
}
|
||||
expect(command.targetThreadId).toBe(ThreadId.make("thread-child-1"));
|
||||
expect(item.type).toBe("thread_created");
|
||||
if (item.type !== "thread_created") {
|
||||
throw new Error("expected thread_created");
|
||||
}
|
||||
expect(item.targetRunId).toBe(RunId.make("run-child-1"));
|
||||
});
|
||||
|
||||
it("decodes provider-neutral replay transcripts", () => {
|
||||
const transcript = Schema.decodeUnknownSync(ProviderReplayTranscript)({
|
||||
provider: "codex",
|
||||
@@ -303,6 +348,7 @@ describe("orchestration V2 contracts", () => {
|
||||
title: "Package audit",
|
||||
model: "gpt-5.4",
|
||||
status: "completed",
|
||||
progress: "Inspecting package metadata",
|
||||
result: "Package is private.",
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
@@ -327,6 +373,7 @@ describe("orchestration V2 contracts", () => {
|
||||
providerInstanceId: subagent.providerInstanceId,
|
||||
childThreadId: subagent.childThreadId,
|
||||
prompt: subagent.prompt,
|
||||
progress: subagent.progress,
|
||||
result: subagent.result,
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
@@ -334,8 +381,11 @@ describe("orchestration V2 contracts", () => {
|
||||
});
|
||||
|
||||
expect(subagent.origin).toBe("provider_native");
|
||||
expect(subagent.progress).toBe("Inspecting package metadata");
|
||||
expect(subagent.childThreadId).toBeNull();
|
||||
expect(turnItem.type).toBe("subagent");
|
||||
if (turnItem.type !== "subagent") throw new Error("expected subagent item");
|
||||
expect(turnItem.progress).toBe("Inspecting package metadata");
|
||||
});
|
||||
|
||||
it("decodes thread projections with an ordered turn item rendering stream", () => {
|
||||
|
||||
@@ -441,6 +441,7 @@ export const OrchestrationV2Subagent = Schema.Struct({
|
||||
"cancelled",
|
||||
"interrupted",
|
||||
]),
|
||||
progress: Schema.optional(Schema.String),
|
||||
result: Schema.NullOr(Schema.String),
|
||||
startedAt: Schema.NullOr(Schema.DateTimeUtc),
|
||||
completedAt: Schema.NullOr(Schema.DateTimeUtc),
|
||||
@@ -902,6 +903,14 @@ export const OrchestrationV2TurnItem = Schema.Union([
|
||||
targetThreadId: ThreadId,
|
||||
providerThreadId: Schema.optional(ProviderThreadId),
|
||||
}),
|
||||
Schema.Struct({
|
||||
...OrchestrationV2TurnItemBaseFields,
|
||||
type: Schema.Literal("thread_created"),
|
||||
targetThreadId: ThreadId,
|
||||
targetRunId: Schema.NullOr(RunId),
|
||||
targetProviderInstanceId: ProviderInstanceId,
|
||||
targetModel: TrimmedNonEmptyString,
|
||||
}),
|
||||
Schema.Struct({
|
||||
...OrchestrationV2TurnItemBaseFields,
|
||||
type: Schema.Literal("subagent"),
|
||||
@@ -911,6 +920,7 @@ export const OrchestrationV2TurnItem = Schema.Union([
|
||||
providerInstanceId: ProviderInstanceId,
|
||||
childThreadId: Schema.NullOr(ThreadId),
|
||||
prompt: Schema.String,
|
||||
progress: Schema.optional(Schema.String),
|
||||
result: Schema.NullOr(Schema.String),
|
||||
}),
|
||||
Schema.Struct({
|
||||
@@ -1487,6 +1497,14 @@ export const OrchestrationV2TurnItemJson = Schema.Union([
|
||||
targetThreadId: ThreadId,
|
||||
providerThreadId: Schema.optional(ProviderThreadId),
|
||||
}),
|
||||
Schema.Struct({
|
||||
...OrchestrationV2TurnItemJsonBaseFields,
|
||||
type: Schema.Literal("thread_created"),
|
||||
targetThreadId: ThreadId,
|
||||
targetRunId: Schema.NullOr(RunId),
|
||||
targetProviderInstanceId: ProviderInstanceId,
|
||||
targetModel: TrimmedNonEmptyString,
|
||||
}),
|
||||
Schema.Struct({
|
||||
...OrchestrationV2TurnItemJsonBaseFields,
|
||||
type: Schema.Literal("subagent"),
|
||||
@@ -1496,6 +1514,7 @@ export const OrchestrationV2TurnItemJson = Schema.Union([
|
||||
providerInstanceId: ProviderInstanceId,
|
||||
childThreadId: Schema.NullOr(ThreadId),
|
||||
prompt: Schema.String,
|
||||
progress: Schema.optional(Schema.String),
|
||||
result: Schema.NullOr(Schema.String),
|
||||
}),
|
||||
Schema.Struct({
|
||||
@@ -1820,6 +1839,15 @@ export const OrchestrationV2Command = Schema.Union([
|
||||
interactionMode: ProviderInteractionMode,
|
||||
createdAt: Schema.optional(Schema.DateTimeUtc),
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("thread.created.record"),
|
||||
commandId: CommandId,
|
||||
parentThreadId: ThreadId,
|
||||
parentRunId: RunId,
|
||||
parentNodeId: NodeId,
|
||||
targetThreadId: ThreadId,
|
||||
targetRunId: Schema.NullOr(RunId),
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("provider.switch"),
|
||||
commandId: CommandId,
|
||||
|
||||
Reference in new issue
Block a user