Skip to content

Commit c2139fd

Browse files
georgenijoclaude
andcommitted
fix(server): stop Claude goal re-prompts while a delegated task will wake the thread
Claude Code defers its /goal Stop hook only for its own background tasks. A thread waiting on a T3 delegated task got re-prompted at every turn end, so it burned tokens polling until the task finished. When a goal is active and a delegated task's result will still be delivered to the thread, the adapter's Stop hook now ends the turn. The goal stays active and is checked again on the completion wake. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent e68e19d commit c2139fd

5 files changed

Lines changed: 203 additions & 3 deletions

File tree

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

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ import * as Option from "effect/Option";
6767
import * as Path from "effect/Path";
6868
import * as PubSub from "effect/PubSub";
6969
import * as Queue from "effect/Queue";
70+
import * as Ref from "effect/Ref";
7071
import * as Schema from "effect/Schema";
7172
import * as Scope from "effect/Scope";
7273
import * as Stream from "effect/Stream";
@@ -17902,6 +17903,83 @@ describe("ClaudeAdapterV2 background wake turns", () => {
1790217903
),
1790317904
);
1790417905

17906+
it.effect("ends a goal check without re-prompting while T3 work will wake the thread", () =>
17907+
Effect.gen(function* () {
17908+
const harness = yield* makeWakeHarness;
17909+
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
17910+
const pendingWake = yield* Ref.make(true);
17911+
yield* mcpSessions.set({
17912+
environmentId: EnvironmentId.make("environment-goal-wake"),
17913+
threadId: harness.threadId,
17914+
providerSessionId: "mcp-session-goal-wake",
17915+
providerInstanceId: ProviderInstanceId.make("claudeAgent"),
17916+
endpoint: "http://127.0.0.1:43123/mcp",
17917+
authorizationHeader: "Bearer secret-claude-token",
17918+
browserToolsAvailable: true,
17919+
hasPendingWake: Ref.get(pendingWake),
17920+
});
17921+
const stop = Effect.promise(() =>
17922+
Promise.all(
17923+
(harness.getOpenedOptions()?.hooks?.Stop ?? []).flatMap((matcher) =>
17924+
matcher.hooks.map((hook) =>
17925+
hook(
17926+
{
17927+
hook_event_name: "Stop",
17928+
stop_hook_active: true,
17929+
session_id: WAKE_NATIVE_SESSION,
17930+
transcript_path: "/transcript.jsonl",
17931+
cwd: "/workspace",
17932+
},
17933+
undefined,
17934+
{ signal: new AbortController().signal },
17935+
),
17936+
),
17937+
),
17938+
),
17939+
);
17940+
const condition = "the delegated review is addressed";
17941+
yield* harness.runtime.startTurn(
17942+
makeClaudeTestTurnInput({
17943+
threadId: harness.threadId,
17944+
providerThread: harness.providerThread,
17945+
now: yield* DateTime.now,
17946+
attemptId: RunAttemptId.make("goal-wake-attempt"),
17947+
text: `/goal ${condition}`,
17948+
attachments: [],
17949+
}),
17950+
);
17951+
// Without a goal, Stop keeps Claude Code's own behavior.
17952+
assert.deepEqual(yield* stop, [{}]);
17953+
yield* harness.offerAndWait(syntheticFrame("goal-wake-set", `Goal set: ${condition}`));
17954+
assert.deepEqual(yield* stop, [{ continue: false }]);
17955+
// The turn ends without an error and the goal waits for the wake.
17956+
yield* Queue.offer(
17957+
harness.sdkMessages,
17958+
makeResultFrame({
17959+
uuid: "goal-wake-result",
17960+
result: "Waiting for the review.",
17961+
terminalReason: "stop_hook_prevented",
17962+
}),
17963+
);
17964+
const terminal = yield* Queue.take(harness.terminalReceipts);
17965+
assert.equal(terminal.status, "completed");
17966+
assert.equal(goalStatuses(harness.events).at(-1)?.status, "active");
17967+
// Once nothing will wake the thread, the goal check runs as before.
17968+
yield* Ref.set(pendingWake, false);
17969+
assert.deepEqual(yield* stop, [{}]);
17970+
}).pipe(
17971+
Effect.scoped,
17972+
Effect.provide(
17973+
Layer.mergeAll(
17974+
IdAllocator.layer,
17975+
McpProviderSessions.layer,
17976+
NodeServices.layer,
17977+
NodeCrypto.layer,
17978+
),
17979+
),
17980+
),
17981+
);
17982+
1790517983
it.effect(
1790617984
"defers goal completion until an ambient subagent finishes and Claude checks again",
1790717985
() =>

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

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1539,6 +1539,7 @@ export function makeClaudeQueryOptions(input: {
15391539
readonly canUseTool?: CanUseTool;
15401540
readonly onUserDialog?: ClaudeQueryOptions["onUserDialog"];
15411541
readonly onElicitation?: ClaudeQueryOptions["onElicitation"];
1542+
readonly onStop?: HookCallback;
15421543
readonly supportedDialogKinds?: ClaudeQueryOptions["supportedDialogKinds"];
15431544
readonly allowDangerouslySkipPermissions?: boolean;
15441545
readonly appendSystemPromptFileText?: string;
@@ -1663,8 +1664,15 @@ export function makeClaudeQueryOptions(input: {
16631664
...launchAppendSystemPrompt,
16641665
].join("\n\n"),
16651666
},
1666-
...(deviceInstructions
1667-
? { hooks: { SubagentStart: [{ hooks: [subagentDeviceInstructions] }] } }
1667+
...(deviceInstructions || input.onStop !== undefined
1668+
? {
1669+
hooks: {
1670+
...(deviceInstructions
1671+
? { SubagentStart: [{ hooks: [subagentDeviceInstructions] }] }
1672+
: {}),
1673+
...(input.onStop === undefined ? {} : { Stop: [{ hooks: [input.onStop] }] }),
1674+
},
1675+
}
16681676
: {}),
16691677
...(Object.keys(extraArgs).length === 0 ? {} : { extraArgs }),
16701678
};
@@ -10383,6 +10391,16 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
1038310391
) {
1038410392
const queryPolicy = yield* queryPolicyForTurn(turnInput);
1038510393
const mcpSession = yield* mcpSessions.read(turnInput.threadId);
10394+
// Claude Code defers its goal Stop hook only for its own background tasks, so a goal
10395+
// re-prompts in a loop while T3 work that will wake this thread is still running.
10396+
const onStop: HookCallback = () =>
10397+
runPromise(
10398+
Effect.gen(function* () {
10399+
if (goalsByNativeThread.get(nativeThreadId)?.status !== "active") return {};
10400+
const pendingWake = (yield* mcpSessions.read(turnInput.threadId))?.hasPendingWake;
10401+
return pendingWake !== undefined && (yield* pendingWake) ? { continue: false } : {};
10402+
}),
10403+
);
1038610404
const mcpOverrides = claudeMcpQueryOverrides({
1038710405
mcpSession,
1038810406
readOnlySandbox:
@@ -10541,6 +10559,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
1054110559
canUseTool,
1054210560
onUserDialog,
1054310561
onElicitation,
10562+
onStop,
1054410563
supportedDialogKinds: ["resume_return"],
1054510564
...(appendSystemPromptFileText === undefined ? {} : { appendSystemPromptFileText }),
1054610565
...(toolSearchOverride === undefined ? {} : { toolSearchOverride }),

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

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import { assert, it } from "@effect/vitest";
55
import { AgentScope } from "@t3tools/shared/AgentScope";
66
import {
77
EnvironmentId,
8+
EventId,
9+
MessageId,
810
type ModelSelection,
911
type OrchestrationV2AppThread,
1012
type OrchestrationV2DomainEvent,
@@ -1814,6 +1816,77 @@ it.effect(
18141816
new Set(["preview", "orchestration", "worktree", "pull-requests"]),
18151817
);
18161818

1819+
// A running delegated task wakes the thread only while its completion can still be delivered.
1820+
assert.isFalse(yield* captured!.hasPendingWake!);
1821+
const runId = idAllocator.derive.run({ threadId, ordinal: 1 });
1822+
const run = (
1823+
disposition: "open" | "disposed",
1824+
): OrchestrationV2DomainEvent & { readonly type: "run.created" | "run.updated" } => ({
1825+
id: EventId.make(`event:${runId}:${disposition}`),
1826+
type: disposition === "open" ? "run.created" : "run.updated",
1827+
threadId,
1828+
runId,
1829+
occurredAt: now,
1830+
payload: {
1831+
id: runId,
1832+
threadId,
1833+
ordinal: 1,
1834+
providerInstanceId: modelSelection.instanceId,
1835+
modelSelection,
1836+
providerThreadId: null,
1837+
userMessageId: MessageId.make("message:delegating"),
1838+
rootNodeId: null,
1839+
activeAttemptId: null,
1840+
status: "completed",
1841+
queuePosition: null,
1842+
requestedAt: now,
1843+
startedAt: now,
1844+
completedAt: now,
1845+
checkpointId: null,
1846+
contextHandoffId: null,
1847+
delegatedCompletion: { disposition, nextGeneration: 1, delivery: null },
1848+
},
1849+
});
1850+
yield* eventSink.write({
1851+
events: [
1852+
run("open"),
1853+
{
1854+
id: yield* idAllocator.allocate.event({ threadId }),
1855+
type: "subagent.updated",
1856+
threadId,
1857+
occurredAt: now,
1858+
payload: {
1859+
id: idAllocator.derive.nodeFromProviderItem({
1860+
driver: CODEX_DRIVER,
1861+
nativeItemId: "delegated-task",
1862+
}),
1863+
threadId,
1864+
runId,
1865+
parentNodeId: idAllocator.derive.rootNode({ runId }),
1866+
origin: "app_owned",
1867+
createdBy: "agent",
1868+
driver: CODEX_DRIVER,
1869+
providerInstanceId: modelSelection.instanceId,
1870+
providerThreadId: null,
1871+
childThreadId: null,
1872+
nativeTaskRef: null,
1873+
prompt: "Review the diff",
1874+
title: "Delegated review",
1875+
model: null,
1876+
status: "running",
1877+
result: null,
1878+
startedAt: now,
1879+
completedAt: null,
1880+
updatedAt: now,
1881+
},
1882+
},
1883+
],
1884+
});
1885+
assert.isTrue(yield* captured!.hasPendingWake!);
1886+
// An interrupted completion wake disposes the cohort, so the result never wakes the thread.
1887+
yield* eventSink.write({ events: [run("disposed")] });
1888+
assert.isFalse(yield* captured!.hasPendingWake!);
1889+
18171890
yield* manager.close(providerSessionId);
18181891
assert.isUndefined(yield* mcpSessions.read(threadId));
18191892
assert.isUndefined(yield* registry.resolve(token!));

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

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -497,7 +497,34 @@ export const layerWithOptions = (
497497
capabilities,
498498
subagent,
499499
});
500-
yield* mcpSessions.set(credential.config);
500+
yield* mcpSessions.set({
501+
...credential.config,
502+
// Matches planDelegatedCompletionDelivery: only tasks whose result still wakes this thread.
503+
hasPendingWake: projectionStore
504+
.getThreadRecords(threadId, ["runs", "subagents"])
505+
.pipe(
506+
Effect.map(
507+
({ thread, runs, subagents }) =>
508+
thread.archivedAt === null &&
509+
thread.deletedAt === null &&
510+
subagents.some((task) => {
511+
const run = runs.find((candidate) => candidate.id === task.runId);
512+
const delivery = task.completionDelivery?.state;
513+
return (
514+
task.origin === "app_owned" &&
515+
isOrchestrationV2WorkActive(task.status) &&
516+
run !== undefined &&
517+
(run.delegatedCompletion === undefined ||
518+
run.delegatedCompletion.disposition === "open") &&
519+
delivery !== "acknowledged" &&
520+
delivery !== "delivered" &&
521+
delivery !== "disposed"
522+
);
523+
}),
524+
),
525+
Effect.orElseSucceed(() => false),
526+
),
527+
});
501528
reserveMcpCredential(threadId, credential.config.providerSessionId);
502529
return { mcpCredentialId: credential.config.providerSessionId, issued: true };
503530
}),

‎packages/provider-core/src/server/mcpSession.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
2+
import type * as Effect from "effect/Effect";
23

34
export interface McpProviderSessionConfig {
45
readonly environmentId: EnvironmentId;
@@ -11,6 +12,8 @@ export interface McpProviderSessionConfig {
1112
readonly browserToolsAvailable: boolean;
1213
readonly capabilities?: ReadonlySet<string>;
1314
readonly agentDeviceEnvironment?: Readonly<Record<string, string>>;
15+
/** True while a delegated task this thread started will wake it with its result. */
16+
readonly hasPendingWake?: Effect.Effect<boolean>;
1417
}
1518

1619
export function withAgentDeviceEnvironment(

0 commit comments

Comments
 (0)