Skip to content

Commit 265fb70

Browse files
authored
fix(server): apply confirmed Claude subagent outcomes (pingdotgg#18778)
1 parent 5d6e419 commit 265fb70

10 files changed

Lines changed: 979 additions & 84 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts‎

Lines changed: 414 additions & 16 deletions
Large diffs are not rendered by default.

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts‎

Lines changed: 155 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2957,6 +2957,8 @@ interface ActiveClaudeProviderRetry {
29572957

29582958
interface ActiveClaudeSubagent {
29592959
task: OrchestrationV2Subagent;
2960+
// Local parent-turn cleanup can end the card without a native task outcome.
2961+
readonly confirmedOutcome: ProviderAdapter.ProviderAdapterV2SubagentOutcome | undefined;
29602962
// The launch run's root node. task.parentNodeId is that same node, or the
29612963
// owning subagent's node for a subagent another subagent started.
29622964
readonly rootNodeId: OrchestrationV2ExecutionNode["id"];
@@ -3497,6 +3499,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
34973499
// idle, a running subagent's frames are projected through it at once
34983500
// instead of waiting in the wake buffer for a continuation run.
34993501
const settledTurnByNativeThread = new Map<string, ActiveClaudeTurnContext>();
3502+
const subagentStopOutcomes = new Map<
3503+
string,
3504+
Deferred.Deferred<ProviderAdapter.ProviderAdapterV2SubagentOutcome>
3505+
>();
3506+
// An idle outcome stays buffered for the parent's wake, but must not
3507+
// settle the child again after that child resumes.
3508+
const appliedSubagentOutcomes = new WeakSet<SDKMessage>();
35003509
// Subagent frames can precede the task_started that registers their
35013510
// subagent (the same race rememberPendingClaudeSubagentLaunch covers).
35023511
// They wait here and replay once task_started registers the owner.
@@ -4419,6 +4428,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
44194428
const ids = claudeSubagentIds(resume.context, resume.taskId);
44204429
const now = yield* DateTime.now;
44214430
const subagent: ActiveClaudeSubagent = {
4431+
confirmedOutcome: undefined,
44224432
childThread: null,
44234433
task: {
44244434
id: ids.nodeId,
@@ -4805,6 +4815,39 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
48054815
}
48064816
});
48074817

4818+
const confirmedSubagentOutcome = (task: OrchestrationV2Subagent | undefined) => {
4819+
if (
4820+
task === undefined ||
4821+
task.completedAt === null ||
4822+
(task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled")
4823+
)
4824+
return;
4825+
return { status: task.status, completedAt: task.completedAt, result: task.result };
4826+
};
4827+
4828+
const discardBufferedSubagentStarts = (
4829+
nativeThreadId: string,
4830+
taskId: string,
4831+
outcome: SDKMessage,
4832+
) =>
4833+
Ref.update(wakeBuffers, (current) => {
4834+
const entry = current.get(nativeThreadId);
4835+
if (entry === undefined) return current;
4836+
const outcomeIndex = entry.messages.indexOf(outcome);
4837+
const messages = entry.messages.filter(
4838+
(buffered, index) =>
4839+
!(
4840+
(outcomeIndex === -1 || index < outcomeIndex) &&
4841+
buffered.type === "system" &&
4842+
(buffered.subtype === "task_started" || buffered.subtype === "task_progress") &&
4843+
buffered.task_id === taskId
4844+
),
4845+
);
4846+
return messages.length === entry.messages.length
4847+
? current
4848+
: new Map(current).set(nativeThreadId, { ...entry, messages });
4849+
});
4850+
48084851
const updateClaudeSubagentNode = Effect.fnUntraced(function* (input: {
48094852
readonly context: ActiveClaudeTurnContext;
48104853
readonly taskId: string;
@@ -4827,6 +4870,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
48274870
"running" | "completed" | "failed" | "cancelled"
48284871
>;
48294872
readonly reopen?: boolean;
4873+
readonly nativeOutcome?: Extract<
4874+
SDKMessage,
4875+
{ readonly type: "system"; readonly subtype: "task_notification" }
4876+
>;
48304877
readonly onlyIfRunningInRun?: RunId | null;
48314878
}) {
48324879
// The session registry lets a wake-replay turn (fresh context maps)
@@ -4993,6 +5040,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
49935040
} satisfies OrchestrationV2Subagent;
49945041
const subagent = {
49955042
task,
5043+
confirmedOutcome:
5044+
input.nativeOutcome !== undefined
5045+
? confirmedSubagentOutcome(task)
5046+
: isReopen
5047+
? undefined
5048+
: existingSubagent?.confirmedOutcome,
49965049
rootNodeId: existingSubagent?.rootNodeId ?? input.context.input.rootNodeId,
49975050
childThreadId,
49985051
childRootNodeId,
@@ -5037,6 +5090,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
50375090
return [true, new Map(current).set(input.taskId, subagent)] as const;
50385091
});
50395092
if (!accepted) return;
5093+
if (input.nativeOutcome !== undefined) appliedSubagentOutcomes.add(input.nativeOutcome);
50405094
// A call the subagent left open never returns once it ends. It ends
50415095
// first, while the run that owns the child thread still takes its
50425096
// events.
@@ -5210,6 +5264,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
52105264
},
52115265
});
52125266

5267+
if (input.nativeOutcome !== undefined && subagent.confirmedOutcome !== undefined) {
5268+
const outcome = subagentStopOutcomes.get(input.taskId);
5269+
if (outcome !== undefined) yield* Deferred.succeed(outcome, subagent.confirmedOutcome);
5270+
}
5271+
52135272
// A completed subagent's result is normally its final assistant
52145273
// message, which is already in the child thread when its text was
52155274
// routed there. Failures and cancellations always get the message.
@@ -6230,6 +6289,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
62306289
const { progress: _staleProgress, ...priorTask } = registered.task;
62316290
return new Map(current).set(message.task_id, {
62326291
...registered,
6292+
confirmedOutcome: undefined,
62336293
task: {
62346294
...priorTask,
62356295
status: "running",
@@ -6699,6 +6759,41 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
66996759
message,
67006760
activeContext: null,
67016761
});
6762+
// Wake delivery must not delay a known child's actual outcome.
6763+
// Record wake evidence first, while the child is still running.
6764+
const registered = (yield* Ref.get(sessionSubagentsByTaskId)).get(message.task_id);
6765+
const settled = settledTurnByNativeThread.get(liveQuery.nativeThreadId);
6766+
const hasBufferedStart =
6767+
(yield* Ref.get(wakeBuffers))
6768+
.get(liveQuery.nativeThreadId)
6769+
?.messages.some(
6770+
(entry) =>
6771+
entry.type === "system" &&
6772+
entry.subtype === "task_started" &&
6773+
entry.task_id === message.task_id,
6774+
) ?? false;
6775+
// Starts and workflow transcripts still need the continuation's
6776+
// context. A pending Stop must receive its native outcome now.
6777+
const canApplyOutcome =
6778+
subagentStopOutcomes.has(message.task_id) ||
6779+
(!hasBufferedStart && registered?.task.workflow === undefined);
6780+
if (registered !== undefined && settled !== undefined && canApplyOutcome) {
6781+
yield* discardBufferedSubagentStarts(
6782+
liveQuery.nativeThreadId,
6783+
message.task_id,
6784+
message,
6785+
);
6786+
yield* updateClaudeSubagentNode({
6787+
context: settled,
6788+
taskId: message.task_id,
6789+
...(message.tool_use_id === undefined ? {} : { toolUseId: message.tool_use_id }),
6790+
workflowFrame: message,
6791+
nativeOutcome: message,
6792+
result: message.summary,
6793+
status: claudeTaskOutcome(message.status),
6794+
onlyIfRunningInRun: registered.task.runId,
6795+
});
6796+
}
67026797
} else {
67036798
yield* applyBackgroundTaskRosterMessage({
67046799
nativeThreadId: liveQuery.nativeThreadId,
@@ -7186,6 +7281,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
71867281
}
71877282

71887283
if (message.type === "system" && message.subtype === "task_notification") {
7284+
// A live outcome supersedes earlier idle starts. During replay only
7285+
// remove frames before this notification, preserving a later resume.
7286+
if (
7287+
!appliedSubagentOutcomes.has(message) &&
7288+
(yield* Ref.get(sessionSubagentsByTaskId)).has(message.task_id)
7289+
) {
7290+
yield* discardBufferedSubagentStarts(
7291+
liveQuery.nativeThreadId,
7292+
message.task_id,
7293+
message,
7294+
);
7295+
}
71897296
// A wake-replay turn has empty ignoredTaskIds, so opaque-task
71907297
// tracking (live roster, wake eligibility, or the short-lived
71917298
// post-buffer replay tombstone) classifies local_bash before any
@@ -7228,13 +7335,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
72287335
message,
72297336
activeContext: context,
72307337
});
7231-
if (!wasBackgroundTask && !context.ignoredTaskIds.has(message.task_id)) {
7338+
if (
7339+
!wasBackgroundTask &&
7340+
!context.ignoredTaskIds.has(message.task_id) &&
7341+
!appliedSubagentOutcomes.has(message)
7342+
) {
72327343
yield* updateClaudeSubagentNode({
72337344
context,
72347345
taskId: message.task_id,
72357346
...(message.tool_use_id === undefined ? {} : { toolUseId: message.tool_use_id }),
72367347
// Terminal usage totals arrive here, after the last snapshot.
72377348
workflowFrame: message,
7349+
nativeOutcome: message,
72387350
result: message.summary,
72397351
status:
72407352
message.status === "completed"
@@ -8973,11 +9085,24 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
89739085
const existing = yield* Ref.get(queryContext);
89749086
const nativeThreadId = input.providerThread.nativeThreadRef?.nativeId;
89759087
const subagent = (yield* Ref.get(sessionSubagentsByTaskId)).get(input.nativeTaskId);
8976-
if (subagent === undefined || subagent.task.status !== "running") return;
9088+
if (subagent?.task.threadId !== input.providerThread.appThreadId) {
9089+
return yield* new ProviderAdapter.ProviderAdapterProtocolError({
9090+
driver: CLAUDE_PROVIDER,
9091+
detail: "Claude subagent has no known owning task to confirm its outcome.",
9092+
});
9093+
}
9094+
if (
9095+
input.requestedAt !== undefined &&
9096+
subagent.task.startedAt !== null &&
9097+
DateTime.toEpochMillis(subagent.task.startedAt) >
9098+
DateTime.toEpochMillis(input.requestedAt)
9099+
)
9100+
return;
9101+
const confirmed = subagent.confirmedOutcome;
9102+
if (confirmed !== undefined) return confirmed;
89779103
if (
89789104
existing === null ||
89799105
existing.nativeThreadId !== nativeThreadId ||
8980-
subagent.task.threadId !== input.providerThread.appThreadId ||
89819106
existing.subagentsFromEarlierProcesses.has(subagent) ||
89829107
existing.query.stopTask === undefined
89839108
) {
@@ -8986,16 +9111,41 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
89869111
detail: "Claude subagent has no live owning query with task stopping support.",
89879112
});
89889113
}
8989-
yield* existing.query.stopTask(input.nativeTaskId).pipe(
9114+
const outcome =
9115+
subagentStopOutcomes.get(input.nativeTaskId) ??
9116+
(yield* Deferred.make<ProviderAdapter.ProviderAdapterV2SubagentOutcome>());
9117+
subagentStopOutcomes.set(input.nativeTaskId, outcome);
9118+
const recorded = (yield* Ref.get(sessionSubagentsByTaskId)).get(input.nativeTaskId);
9119+
if (
9120+
recorded?.task.startedAt === subagent.task.startedAt &&
9121+
recorded.confirmedOutcome !== undefined
9122+
) {
9123+
if (subagentStopOutcomes.get(input.nativeTaskId) === outcome)
9124+
subagentStopOutcomes.delete(input.nativeTaskId);
9125+
return recorded.confirmedOutcome;
9126+
}
9127+
const confirmedOutcome = yield* existing.query.stopTask(input.nativeTaskId).pipe(
9128+
Effect.andThen(Deferred.await(outcome)),
9129+
Effect.timeout("2 seconds"),
89909130
Effect.mapError(
89919131
(cause) =>
89929132
new ProviderAdapter.ProviderAdapterProtocolError({
89939133
driver: CLAUDE_PROVIDER,
8994-
detail: "Claude native subagent stop failed.",
9134+
detail: "Claude subagent Stop was not confirmed by a native outcome.",
89959135
cause,
89969136
}),
89979137
),
9138+
Effect.ensuring(
9139+
Effect.sync(() => {
9140+
if (subagentStopOutcomes.get(input.nativeTaskId) === outcome)
9141+
subagentStopOutcomes.delete(input.nativeTaskId);
9142+
}),
9143+
),
89989144
);
9145+
const current = (yield* Ref.get(sessionSubagentsByTaskId)).get(input.nativeTaskId);
9146+
return current?.task.startedAt === subagent.task.startedAt
9147+
? confirmedOutcome
9148+
: undefined;
89999149
}),
90009150
respondToRuntimeRequest: Effect.fn("ClaudeAdapterV2.respondToRuntimeRequest")(
90019151
function* (requestInput) {

‎apps/server/src/orchestration-v2/EffectWorker.test.ts‎

Lines changed: 65 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -839,31 +839,71 @@ it.effect("settles a delegated child once its restart continuation fails for goo
839839
}),
840840
);
841841

842-
it.effect("a native subagent stop does not settle its owner's background work", () =>
843-
Effect.gen(function* () {
844-
const now = yield* DateTime.now;
845-
const events = yield* Ref.make<ReadonlyArray<string>>([]);
846-
const layer = layerExecutorFor({
847-
events,
848-
interrupt: (input) => {
849-
assert.equal(input.subagent?.nativeTaskId, "native-task");
850-
return Ref.update(events, (current) => [...current, "stop-child"]);
851-
},
852-
threads: { dispatch: () => Effect.die("The owner's background work must stay running") },
853-
});
854-
yield* Effect.gen(function* () {
855-
const executor = yield* EffectWorker.OrchestrationEffectExecutorV2;
856-
yield* executor.execute({
857-
...restartEffect(now, { type: "detach" }),
858-
request: {
859-
type: "provider-turn.interrupt",
860-
providerSessionId: oldSessionId,
861-
providerThreadId,
862-
providerTurnId,
863-
subagent: { id: NodeId.make("subagent"), nativeTaskId: "native-task" },
842+
it.effect.each(["confirmed", "unconfirmed", "failed"] as const)(
843+
"a native subagent stop only repairs %s provider evidence",
844+
(outcome) =>
845+
Effect.gen(function* () {
846+
const now = yield* DateTime.now;
847+
const events = yield* Ref.make<ReadonlyArray<string>>([]);
848+
const layer = layerExecutorFor({
849+
events,
850+
interrupt: (input) => {
851+
assert.equal(input.subagent?.nativeTaskId, "native-task");
852+
return Ref.update(events, (current) => [...current, "stop-child"]).pipe(
853+
Effect.andThen(
854+
outcome === "failed"
855+
? new ProviderTurnControlService.ProviderTurnControlError({
856+
threadId,
857+
providerTurnId,
858+
operation: "interrupt",
859+
cause: "SDK stop failed",
860+
})
861+
: Effect.succeed(
862+
outcome === "confirmed"
863+
? {
864+
status: "cancelled" as const,
865+
completedAt: now,
866+
result: "Stopped by Claude",
867+
}
868+
: undefined,
869+
),
870+
),
871+
);
872+
},
873+
threads: {
874+
dispatch: (command) => {
875+
assert.equal(command.type, "thread.background-work.settle");
876+
if (command.type === "thread.background-work.settle") {
877+
assert.equal(command.subagent?.id, "subagent");
878+
assert.deepEqual(command.subagent?.outcome, {
879+
status: "cancelled",
880+
completedAt: now,
881+
result: "Stopped by Claude",
882+
});
883+
}
884+
return Ref.update(events, (current) => [...current, "settle-child"]).pipe(
885+
Effect.as({ sequence: 1, storedEvents: [] }),
886+
);
887+
},
864888
},
865889
});
866-
}).pipe(Effect.provide(layer));
867-
assert.deepEqual(yield* Ref.get(events), ["stop-child"]);
868-
}),
890+
const execution = yield* Effect.gen(function* () {
891+
const executor = yield* EffectWorker.OrchestrationEffectExecutorV2;
892+
yield* executor.execute({
893+
...restartEffect(now, { type: "detach" }),
894+
request: {
895+
type: "provider-turn.interrupt",
896+
providerSessionId: oldSessionId,
897+
providerThreadId,
898+
providerTurnId,
899+
subagent: { id: NodeId.make("subagent"), nativeTaskId: "native-task" },
900+
},
901+
});
902+
}).pipe(Effect.provide(layer), Effect.exit);
903+
assert.equal(Exit.isFailure(execution), outcome === "failed");
904+
assert.deepEqual(
905+
yield* Ref.get(events),
906+
outcome === "confirmed" ? ["stop-child", "settle-child"] : ["stop-child"],
907+
);
908+
}),
869909
);

0 commit comments

Comments
 (0)