Skip to content

Commit 86b4f38

Browse files
committed
fix(server): a finished delegated task no longer shows its child's question
1 parent f79f37a commit 86b4f38

2 files changed

Lines changed: 147 additions & 30 deletions

File tree

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 62 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -11115,6 +11115,63 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1111511115
: threadDispatch.withLock(parentThreadId, dispatch);
1111611116
});
1111711117

11118+
const delegatedTaskResultPending = (childThreadId: ThreadId, taskId?: NodeId) =>
11119+
Effect.gen(function* () {
11120+
const child = yield* projectionStore.getThreadRecords(
11121+
childThreadId,
11122+
["runs", "messages", "subagents", "providerThreads", "providerTurns", "attempts"],
11123+
{ messageRoles: ["user"] },
11124+
);
11125+
if (taskId !== undefined) {
11126+
const runs = child.runs.filter((run) => run.delegatedTaskId === taskId);
11127+
const run = runs.toSorted((a, b) => b.ordinal - a.ordinal)[0];
11128+
if (run === undefined || delegatedTaskTerminalStatus(run.status) === null) return true;
11129+
return yield* childAwaitsRestartContinuation(runs, run);
11130+
}
11131+
const progress = delegatedTaskProgress(child);
11132+
// A caller's older read saw a result; newer work since then means it is not final.
11133+
if (progress.state !== "result_available") return true;
11134+
if (progress.resultRun === undefined) return false;
11135+
return yield* childAwaitsRestartContinuation(child.runs, progress.resultRun);
11136+
}).pipe(
11137+
Effect.mapError(
11138+
(cause) => new OrchestratorProjectionError({ threadId: childThreadId, cause }),
11139+
),
11140+
);
11141+
11142+
// Async questions do not stop a delegated child's run. Once its task result is
11143+
// final, nothing reads the answers, so the questions close instead of
11144+
// showing on the parent forever.
11145+
const finishAppOwnedSubagent = (
11146+
parentThreadId: ThreadId,
11147+
childThreadId: ThreadId,
11148+
options?: { readonly settledContinuationOf?: RunId },
11149+
) =>
11150+
Effect.gen(function* () {
11151+
yield* threadDispatch.withLock(
11152+
parentThreadId,
11153+
finalizeAppOwnedSubagent(childThreadId, options),
11154+
);
11155+
if (yield* delegatedTaskResultPending(childThreadId)) return;
11156+
const { runtimeRequests } = yield* projectionStore.getThreadRecords(childThreadId, [
11157+
"runtimeRequests",
11158+
]);
11159+
for (const request of runtimeRequests) {
11160+
if (
11161+
request.status !== "pending" ||
11162+
request.kind !== "user_input" ||
11163+
request.responseCapability.type !== "message"
11164+
)
11165+
continue;
11166+
yield* dispatchWithReceipt({
11167+
type: "thread.user-input.dismiss",
11168+
commandId: CommandId.make(`command:system:delegated-task-question:${request.id}`),
11169+
threadId: childThreadId,
11170+
requestId: request.id,
11171+
});
11172+
}
11173+
});
11174+
1111811175
const handleTerminalRun = (stored: OrchestrationV2StoredEvent) =>
1111911176
Effect.gen(function* () {
1112011177
const threadId = stored.event.threadId;
@@ -11154,7 +11211,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1115411211
// wakes, and only then is the failed run the task's result.
1115511212
const parentThreadId = yield* appOwnedSubagentParentThreadId(threadId);
1115611213
if (parentThreadId !== undefined) {
11157-
yield* threadDispatch.withLock(parentThreadId, finalizeAppOwnedSubagent(threadId));
11214+
yield* finishAppOwnedSubagent(parentThreadId, threadId);
1115811215
}
1115911216
}).pipe(
1116011217
Effect.catchCause((cause) =>
@@ -11204,7 +11261,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1120411261
const thread = yield* projectionStore.getThreadShell(threadId);
1120511262
const parentThreadId = thread?.lineage.parentThreadId;
1120611263
if (parentThreadId === undefined || parentThreadId === null) return;
11207-
yield* threadDispatch.withLock(parentThreadId, finalizeAppOwnedSubagent(threadId));
11264+
yield* finishAppOwnedSubagent(parentThreadId, threadId);
1120811265
}).pipe(
1120911266
Effect.catchCause((cause) =>
1121011267
Effect.logWarning("Failed to recover terminal app-owned subagent", {
@@ -11283,38 +11340,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1128311340
);
1128411341
});
1128511342

11286-
const delegatedTaskResultPending = (childThreadId: ThreadId, taskId?: NodeId) =>
11287-
Effect.gen(function* () {
11288-
const child = yield* projectionStore.getThreadRecords(
11289-
childThreadId,
11290-
["runs", "messages", "subagents", "providerThreads", "providerTurns", "attempts"],
11291-
{ messageRoles: ["user"] },
11292-
);
11293-
if (taskId !== undefined) {
11294-
const runs = child.runs.filter((run) => run.delegatedTaskId === taskId);
11295-
const run = runs.toSorted((a, b) => b.ordinal - a.ordinal)[0];
11296-
if (run === undefined || delegatedTaskTerminalStatus(run.status) === null) return true;
11297-
return yield* childAwaitsRestartContinuation(runs, run);
11298-
}
11299-
const progress = delegatedTaskProgress(child);
11300-
// A caller's older read saw a result; newer work since then means it is not final.
11301-
if (progress.state !== "result_available") return true;
11302-
if (progress.resultRun === undefined) return false;
11303-
return yield* childAwaitsRestartContinuation(child.runs, progress.resultRun);
11304-
}).pipe(
11305-
Effect.mapError(
11306-
(cause) => new OrchestratorProjectionError({ threadId: childThreadId, cause }),
11307-
),
11308-
);
11309-
1131011343
const recoverDelegatedTask = (threadId: ThreadId, sourceRunId: RunId) =>
1131111344
Effect.gen(function* () {
1131211345
const parentThreadId = yield* appOwnedSubagentParentThreadId(threadId);
1131311346
if (parentThreadId === undefined) return;
11314-
yield* threadDispatch.withLock(
11315-
parentThreadId,
11316-
finalizeAppOwnedSubagent(threadId, { settledContinuationOf: sourceRunId }),
11317-
);
11347+
yield* finishAppOwnedSubagent(parentThreadId, threadId, {
11348+
settledContinuationOf: sourceRunId,
11349+
});
1131811350
}).pipe(
1131911351
Effect.catchCause((cause) =>
1132011352
Effect.logWarning("Failed to recover delegated task after restart", {

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

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
ProviderInstanceId,
1010
ProviderSessionId,
1111
ProviderTurnId,
12+
RuntimeRequestId,
1213
ThreadId,
1314
TurnItemId,
1415
} from "@t3tools/contracts";
@@ -477,6 +478,90 @@ it.effect.each(["thread.stop", "run.interrupt"] as const)(
477478
}).pipe(Effect.provide(layerTest.pipe(Layer.provideMerge(TestClock.layer())))),
478479
);
479480

481+
it.effect("a delegated task's async question closes once Stop ends the task", () =>
482+
Effect.gen(function* () {
483+
const orchestrator = yield* Orchestrator.OrchestratorV2;
484+
const projections = yield* ProjectionStore.ProjectionStoreV2;
485+
const parentThreadId = ThreadId.make("thread:stop-question-parent");
486+
yield* createWatchingThread(parentThreadId, 20);
487+
yield* send(parentThreadId, "first", "start_immediately");
488+
const childThreadId = yield* delegate(parentThreadId, "question task");
489+
const childRun = (yield* orchestrator.getThreadProjection(childThreadId)).runs[0]!;
490+
491+
// A Codex async question: the run keeps going while it waits for an answer.
492+
const now = yield* DateTime.now;
493+
const requestId = RuntimeRequestId.make("request:stop-question");
494+
const nodeId = NodeId.make("node:stop-question");
495+
yield* projections.apply({
496+
id: EventId.make("event:stop-question:node"),
497+
type: "node.updated",
498+
threadId: childThreadId,
499+
runId: childRun.id,
500+
nodeId,
501+
occurredAt: now,
502+
payload: {
503+
id: nodeId,
504+
threadId: childThreadId,
505+
runId: childRun.id,
506+
parentNodeId: childRun.rootNodeId,
507+
rootNodeId: childRun.rootNodeId!,
508+
kind: "user_input_request",
509+
status: "waiting",
510+
countsForRun: false,
511+
providerThreadId: childRun.providerThreadId,
512+
providerTurnId: null,
513+
nativeItemRef: null,
514+
runtimeRequestId: requestId,
515+
checkpointScopeId: null,
516+
startedAt: now,
517+
completedAt: null,
518+
},
519+
});
520+
yield* projections.apply({
521+
id: EventId.make("event:stop-question:request"),
522+
type: "runtime-request.updated",
523+
threadId: childThreadId,
524+
runId: childRun.id,
525+
nodeId,
526+
occurredAt: now,
527+
payload: {
528+
id: requestId,
529+
nodeId,
530+
providerTurnId: null,
531+
nativeRequestRef: null,
532+
kind: "user_input",
533+
status: "pending",
534+
responseCapability: { type: "message" },
535+
createdAt: now,
536+
resolvedAt: null,
537+
},
538+
});
539+
const pendingRequest = Effect.map(
540+
orchestrator.getThreadProjection(childThreadId),
541+
(projection) => projection.runtimeRequests.find((request) => request.id === requestId),
542+
);
543+
544+
// While the task runs, its question stays open.
545+
yield* orchestrator.recoverDelegatedTask(childThreadId, childRun.id);
546+
assert.equal((yield* pendingRequest)?.status, "pending");
547+
548+
// What task_cancel dispatches.
549+
yield* orchestrator.dispatch({
550+
type: "thread.stop",
551+
commandId: CommandId.make("stop-question-child"),
552+
threadId: childThreadId,
553+
});
554+
yield* orchestrator.recoverDelegatedTask(childThreadId, childRun.id);
555+
const parent = yield* orchestrator.getThreadProjection(parentThreadId);
556+
assert.equal(parent.subagents[0]?.status, "interrupted");
557+
const request = yield* pendingRequest;
558+
assert.equal(request?.status, "resolved");
559+
assert.equal(request?.decision, "cancel");
560+
const child = yield* projections.getThreadShell(childThreadId);
561+
assert.isNull(child?.pendingRuntimeRequest);
562+
}).pipe(Effect.provide(layerTest)),
563+
);
564+
480565
it.effect("a delegated task that cannot be stopped fails the walk after its siblings stop", () =>
481566
Effect.gen(function* () {
482567
const orchestrator = yield* Orchestrator.OrchestratorV2;

0 commit comments

Comments
 (0)