fix(orchestration-v2): settle subagent lifecycle races
This commit is contained in:
1 parent
a1e1ab5f04
commit
e4a4c60121
7 files changed
+123
-19
No files matched your search
@@ -107,6 +107,30 @@ describe("ClaudeAdapterV2 subagent registry", () => {
|
||||
assert.strictEqual((yield* Ref.get(registry)).get("task-race"), terminal);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects a stale terminal update after the subagent has resumed", () =>
|
||||
Effect.gen(function* () {
|
||||
type RegistryEntry = {
|
||||
readonly task: { readonly status: "running" | "completed" };
|
||||
};
|
||||
const observed: RegistryEntry = { task: { status: "running" } };
|
||||
const resumed: RegistryEntry = { task: { status: "running" } };
|
||||
const staleTerminal: RegistryEntry = { task: { status: "completed" } };
|
||||
const registry = yield* Ref.make(new Map<string, RegistryEntry>([["task-race", resumed]]));
|
||||
|
||||
const committed = yield* commitClaudeSubagentRegistryEntry({
|
||||
registry,
|
||||
taskId: "task-race",
|
||||
observed,
|
||||
candidate: staleTerminal,
|
||||
activeStart: false,
|
||||
isReopen: false,
|
||||
});
|
||||
|
||||
assert.isFalse(committed);
|
||||
assert.strictEqual((yield* Ref.get(registry)).get("task-race"), resumed);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
function makeClaudeTestAppThread(input: {
|
||||
@@ -3375,6 +3399,16 @@ describe("ClaudeAdapterV2 background wake turns", () => {
|
||||
task_id: SUBAGENT_TASK_ID,
|
||||
tool_use_id: SUBAGENT_TOOL_USE_ID,
|
||||
description: "Stale progress line",
|
||||
workflow_progress: [
|
||||
{
|
||||
type: "workflow_agent",
|
||||
index: 0,
|
||||
label: "Stale worker",
|
||||
state: "active",
|
||||
phaseIndex: 0,
|
||||
attempt: 1,
|
||||
},
|
||||
],
|
||||
uuid: "00000000-0000-4000-8000-000000000409",
|
||||
session_id: WAKE_NATIVE_SESSION,
|
||||
}),
|
||||
@@ -3389,6 +3423,11 @@ describe("ClaudeAdapterV2 background wake turns", () => {
|
||||
yield* awaitUntil(() => harness.terminalEvents().length === 5, "final turn terminal");
|
||||
assert.equal(subagentEvents().at(-1)?.subagent.status, "completed");
|
||||
assert.equal(subagentEvents().at(-1)?.subagent.result, SECOND_SUMMARY);
|
||||
assert.lengthOf(
|
||||
new Set(subagentEvents().map((event) => event.subagent.id)),
|
||||
1,
|
||||
"late workflow progress must not create workers under a settled coordinator",
|
||||
);
|
||||
assert.isFalse(yield* harness.hasPendingBackgroundWork);
|
||||
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
|
||||
),
|
||||
|
||||
@@ -2220,9 +2220,8 @@ export const commitClaudeSubagentRegistryEntry = Effect.fnUntraced(function* <
|
||||
registered.task.status === "failed" ||
|
||||
registered.task.status === "cancelled");
|
||||
if (
|
||||
registeredSettled &&
|
||||
input.activeStart &&
|
||||
!(input.isReopen && registered === input.observed)
|
||||
(!input.activeStart && registered !== input.observed) ||
|
||||
(registeredSettled && input.activeStart && !(input.isReopen && registered === input.observed))
|
||||
) {
|
||||
return [false, current] as const;
|
||||
}
|
||||
@@ -4270,7 +4269,12 @@ export function makeClaudeAdapterV2(
|
||||
: context.subagentsByToolUseId.get(message.tool_use_id)) ??
|
||||
(yield* Ref.get(sessionSubagentsByTaskId)).get(message.task_id))
|
||||
: undefined;
|
||||
if (workflowParent !== undefined) {
|
||||
if (
|
||||
workflowParent !== undefined &&
|
||||
(workflowParent.task.status === "pending" ||
|
||||
workflowParent.task.status === "running" ||
|
||||
workflowParent.task.status === "waiting")
|
||||
) {
|
||||
for (const entry of workflowEntries) {
|
||||
if (recordField(entry, "type") !== "workflow_agent") continue;
|
||||
const index = nonNegativeInteger(recordField(entry, "index"));
|
||||
|
||||
@@ -52,6 +52,7 @@ import {
|
||||
CODEX_DRIVER_KIND,
|
||||
codexBackgroundCommandDetail,
|
||||
codexCollabAgentStatus,
|
||||
codexSubagentRebindPatch,
|
||||
codexThreadRuntimeParams,
|
||||
type CodexAgentMessageDeltaUpdate,
|
||||
type CodexAppServerClientFactoryShape,
|
||||
@@ -73,6 +74,24 @@ describe("CodexAdapterV2 subagent status mapping", () => {
|
||||
["pending", "running", "idle", "interrupted", "failed", "cancelled", "failed"],
|
||||
);
|
||||
});
|
||||
|
||||
it("rebinds a reused subagent when only the provider turn context changes", () => {
|
||||
const runId = RunId.make("run-codex-same-run-rebind");
|
||||
const previousContext = {
|
||||
projectionRunId: runId,
|
||||
itemParentNodeId: NodeId.make("node-codex-previous-turn"),
|
||||
};
|
||||
const nextContext = {
|
||||
projectionRunId: runId,
|
||||
itemParentNodeId: NodeId.make("node-codex-next-turn"),
|
||||
};
|
||||
|
||||
assert.deepEqual(codexSubagentRebindPatch(previousContext, nextContext), {
|
||||
runId,
|
||||
parentNodeId: nextContext.itemParentNodeId,
|
||||
});
|
||||
assert.isNull(codexSubagentRebindPatch(nextContext, nextContext));
|
||||
});
|
||||
});
|
||||
|
||||
describe("CodexAdapterV2 assistant message streaming", () => {
|
||||
|
||||
@@ -883,6 +883,19 @@ interface CodexSubagentThreadContext {
|
||||
task: OrchestrationV2Subagent;
|
||||
}
|
||||
|
||||
export function codexSubagentRebindPatch(
|
||||
currentContext: object,
|
||||
nextContext: Pick<ActiveCodexTurnContext, "projectionRunId" | "itemParentNodeId">,
|
||||
): Pick<OrchestrationV2Subagent, "runId" | "parentNodeId"> | null {
|
||||
if (currentContext === nextContext) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
runId: nextContext.projectionRunId,
|
||||
parentNodeId: nextContext.itemParentNodeId,
|
||||
};
|
||||
}
|
||||
|
||||
const isDescendantCodexTurn = (
|
||||
candidate: ActiveCodexTurnContext,
|
||||
ancestor: ActiveCodexTurnContext,
|
||||
@@ -2397,12 +2410,12 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
subagent: CodexSubagentThreadContext,
|
||||
context: ActiveCodexTurnContext,
|
||||
) => {
|
||||
if (subagent.parentContext.projectionRunId === context.projectionRunId) return;
|
||||
const patch = codexSubagentRebindPatch(subagent.parentContext, context);
|
||||
if (patch === null) return;
|
||||
subagent.parentContext = context;
|
||||
subagent.task = {
|
||||
...subagent.task,
|
||||
runId: context.projectionRunId,
|
||||
parentNodeId: context.itemParentNodeId,
|
||||
...patch,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
type OrchestrationV2Subagent,
|
||||
type OrchestrationV2SubagentActivation,
|
||||
type OrchestrationV2TurnItem,
|
||||
orchestrationV2SubagentStatusAsTurnItemStatus,
|
||||
type ProviderInstanceId,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -96,6 +97,11 @@ export const CURSOR_DRIVER_KIND = CURSOR_PROVIDER;
|
||||
export const CURSOR_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CURSOR_DRIVER_KIND);
|
||||
const DEFAULT_CURSOR_SETTINGS = Schema.decodeSync(CursorSettings)({});
|
||||
|
||||
type CursorTerminalStatus = Extract<
|
||||
OrchestrationV2ProviderTurn["status"],
|
||||
"completed" | "interrupted" | "failed" | "cancelled"
|
||||
>;
|
||||
|
||||
export const CursorProviderCapabilitiesV2 = {
|
||||
sessions: {
|
||||
supportsMultipleProviderThreadsPerSession: false,
|
||||
@@ -762,6 +768,7 @@ interface ActiveCursorToolCall {
|
||||
interface ActiveCursorSubagent {
|
||||
task: OrchestrationV2Subagent;
|
||||
readonly callId: string;
|
||||
readonly toolCall: Extract<ToolCall, { readonly type: "task" }>;
|
||||
readonly childThreadId: ThreadId;
|
||||
readonly childRootNodeId: OrchestrationV2ExecutionNode["id"];
|
||||
readonly turnItemId: OrchestrationV2TurnItem["id"];
|
||||
@@ -1440,17 +1447,17 @@ export function makeCursorAdapterV2(
|
||||
readonly callId: string;
|
||||
readonly toolCall: Extract<ToolCall, { readonly type: "task" }>;
|
||||
readonly completed: boolean;
|
||||
readonly terminalStatus?: CursorTerminalStatus;
|
||||
}) {
|
||||
const args = input.toolCall.args;
|
||||
const result =
|
||||
input.toolCall.result?.status === "success" ? input.toolCall.result.value : undefined;
|
||||
const existing = input.context.subagents.get(input.callId);
|
||||
const now = yield* DateTime.now;
|
||||
const status: OrchestrationV2Subagent["status"] = input.completed
|
||||
? cursorToolFailed(input.toolCall)
|
||||
? "failed"
|
||||
: "completed"
|
||||
: "running";
|
||||
const completed = input.completed || input.terminalStatus !== undefined;
|
||||
const status: OrchestrationV2Subagent["status"] =
|
||||
input.terminalStatus ??
|
||||
(completed ? (cursorToolFailed(input.toolCall) ? "failed" : "completed") : "running");
|
||||
const resultText = [
|
||||
...assistantTextsFromConversationSteps(result?.conversationSteps ?? []),
|
||||
...(result?.resultSuffix === undefined ? [] : [result.resultSuffix]),
|
||||
@@ -1515,13 +1522,14 @@ export function makeCursorAdapterV2(
|
||||
},
|
||||
status,
|
||||
result: resultText.length === 0 ? (existing?.task.result ?? null) : resultText,
|
||||
currentActivationId: input.completed ? null : activationId,
|
||||
completedAt: input.completed ? now : null,
|
||||
currentActivationId: completed ? null : activationId,
|
||||
completedAt: completed ? now : null,
|
||||
updatedAt: now,
|
||||
};
|
||||
const subagent: ActiveCursorSubagent = {
|
||||
task,
|
||||
callId: input.callId,
|
||||
toolCall: input.toolCall,
|
||||
childThreadId,
|
||||
childRootNodeId,
|
||||
turnItemId:
|
||||
@@ -1613,7 +1621,7 @@ export function makeCursorAdapterV2(
|
||||
runtimeRequestId: null,
|
||||
checkpointScopeId: null,
|
||||
startedAt: task.startedAt,
|
||||
completedAt: input.completed ? now : null,
|
||||
completedAt: completed ? now : null,
|
||||
},
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
@@ -1634,7 +1642,7 @@ export function makeCursorAdapterV2(
|
||||
runtimeRequestId: null,
|
||||
checkpointScopeId: null,
|
||||
startedAt: task.startedAt,
|
||||
completedAt: input.completed ? now : null,
|
||||
completedAt: completed ? now : null,
|
||||
},
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
@@ -1655,7 +1663,7 @@ export function makeCursorAdapterV2(
|
||||
status,
|
||||
usage: null,
|
||||
startedAt: task.startedAt,
|
||||
completedAt: input.completed ? now : null,
|
||||
completedAt: completed ? now : null,
|
||||
updatedAt: now,
|
||||
} satisfies OrchestrationV2SubagentActivation,
|
||||
});
|
||||
@@ -1672,7 +1680,7 @@ export function makeCursorAdapterV2(
|
||||
nativeItemRef: task.nativeTaskRef,
|
||||
parentItemId: null,
|
||||
ordinal: subagent.turnItemOrdinal,
|
||||
status,
|
||||
status: orchestrationV2SubagentStatusAsTurnItemStatus[status],
|
||||
title: task.title,
|
||||
startedAt: task.startedAt,
|
||||
completedAt: task.completedAt,
|
||||
@@ -1688,7 +1696,7 @@ export function makeCursorAdapterV2(
|
||||
},
|
||||
});
|
||||
|
||||
if (input.completed && !subagent.resultProjected) {
|
||||
if (completed && !subagent.resultProjected) {
|
||||
for (const [index, nestedTool] of toolCallsFromConversationSteps(
|
||||
result?.conversationSteps ?? [],
|
||||
).entries()) {
|
||||
@@ -1914,6 +1922,19 @@ export function makeCursorAdapterV2(
|
||||
yield* emitToolArtifacts({ active: tool, completed: true });
|
||||
}
|
||||
input.context.tools.clear();
|
||||
for (const subagent of input.context.subagents.values()) {
|
||||
if (subagent.task.currentActivationId === null) {
|
||||
continue;
|
||||
}
|
||||
yield* emitSubagent({
|
||||
context: input.context,
|
||||
callId: subagent.callId,
|
||||
toolCall: subagent.toolCall,
|
||||
completed: true,
|
||||
terminalStatus: input.status,
|
||||
});
|
||||
}
|
||||
input.context.subagents.clear();
|
||||
yield* completeReasoning(input.context);
|
||||
yield* completeAssistant(input.context);
|
||||
yield* emitProviderEvent({
|
||||
|
||||
+7
@@ -48,6 +48,7 @@ export function assertTurnInterruptMidToolCursorOutput(
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
|
||||
assertTurnItemTypes(projection, [
|
||||
"user_message",
|
||||
"subagent",
|
||||
"command_execution",
|
||||
"run_interrupt_request",
|
||||
"run_interrupt_result",
|
||||
@@ -72,4 +73,10 @@ export function assertTurnInterruptMidToolCursorOutput(
|
||||
);
|
||||
assert.equal(projection.providerThreads[0]?.status, "idle");
|
||||
assert.equal(projection.providerTurns[0]?.status, "interrupted");
|
||||
assert.lengthOf(projection.subagents, 1);
|
||||
assert.equal(projection.subagents[0]?.status, "interrupted");
|
||||
assert.isNull(projection.subagents[0]?.currentActivationId);
|
||||
assert.lengthOf(projection.subagentActivations, 1);
|
||||
assert.equal(projection.subagentActivations[0]?.status, "interrupted");
|
||||
assert.isNotNull(projection.subagentActivations[0]?.completedAt);
|
||||
}
|
||||
+1
@@ -37,6 +37,7 @@
|
||||
{"type":"emit_inbound","label":"token-delta","frame":{"type":"interaction.update","runId":"run-3735f72d-3c3a-40b3-ae4a-caed784e6ea2","update":{"type":"token-delta","tokens":9}}}
|
||||
{"type":"emit_inbound","label":"token-delta","frame":{"type":"interaction.update","runId":"run-3735f72d-3c3a-40b3-ae4a-caed784e6ea2","update":{"type":"token-delta","tokens":5}}}
|
||||
{"type":"emit_inbound","label":"token-delta","frame":{"type":"interaction.update","runId":"run-3735f72d-3c3a-40b3-ae4a-caed784e6ea2","update":{"type":"token-delta","tokens":1}}}
|
||||
{"type":"emit_inbound","label":"tool-call-started/subagent","frame":{"type":"interaction.update","runId":"run-3735f72d-3c3a-40b3-ae4a-caed784e6ea2","update":{"type":"tool-call-started","callId":"tool_interrupted_subagent","toolCall":{"type":"task","args":{"description":"Delegate command observation","prompt":"Observe the long-running command and report when it finishes.","subagentType":{"kind":"unspecified"},"model":"composer-2.5-fast","agentId":"agent-interrupted-subagent","mode":"unspecified"}},"modelCallId":"d7f78da1-7ccd-45fc-a021-a0f7c333bd1d-0-kteu"}}}
|
||||
{"type":"emit_inbound","label":"tool-call-started","frame":{"type":"interaction.update","runId":"run-3735f72d-3c3a-40b3-ae4a-caed784e6ea2","update":{"type":"tool-call-started","callId":"tool_6ecf0e02-3c15-448d-8994-2d041457475","toolCall":{"type":"shell","args":{"command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","timeout":35000}},"modelCallId":"d7f78da1-7ccd-45fc-a021-a0f7c333bd1d-0-kteu"}}}
|
||||
{"type":"expect_outbound","label":"run.cancel:1","frame":{"type":"run.cancel","runId":"run-3735f72d-3c3a-40b3-ae4a-caed784e6ea2"}}
|
||||
{"type":"emit_inbound","label":"run.completed:1","frame":{"type":"run.completed","result":{"id":"run-3735f72d-3c3a-40b3-ae4a-caed784e6ea2","requestId":"d7f78da1-7ccd-45fc-a021-a0f7c333bd1d","status":"cancelled","model":{"id":"composer-2.5"},"durationMs":4496}}}
|
||||
|
||||
Reference in new issue
Block a user