fix(orchestrator): Prevent redundant delegated completion turns #5311
Mergedmwolson(GitHub profile, opens in a new tab)merged 5 commits into
t3code/codex-turn-mapping fromrefs/pull/5311/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
mwolson(GitHub profile, opens in a new tab) changed the title
- apps/mobile/src/features/threads/ThreadQueueControl.tsx line 149OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +95,21 @@95+ <Pressable96+ accessibilityRole="button"97+ accessibilityLabel="Promote queued message to steer"98+ disabled={busyRunId !== null || !workflow.canPromoteToSteer}99+ onPress={() => void steer(run.id)}100+ className="min-h-8 flex-row items-center gap-1 rounded-lg border border-neutral-300/60 px-2 disabled:opacity-30 dark:border-white/[0.1]"101+ >102+ <SymbolView103+ name="arrow.turn.left.up"104+ size={12}105+ tintColor={iconColor}106+ type="monochrome"107+ />108+ <Text className="font-t3-medium text-2xs text-foreground">Steer</Text>109+ </Pressable>110+ </View>111+ ))}112+ </ScrollView>113+ </View>114+ );115+}
- apps/server/scripts/acp-replay-agent.ts line 260OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +240,21 @@240+function handleMessage(message: JsonRpcMessage): void {241+ if (stopped) return;242+ const actual = logicalIncoming(message);243+ if (actual === undefined) {244+ stopWithFailure("Could not identify outbound ACP frame", message);245+ return;246+ }247+ const entry = transcript.entries[cursor];248+ if (entry?.type !== "expect_outbound" || !matchesExpected(entry.frame, actual)) {249+ if (actual.kind === "request" && message.id !== undefined && message.id !== null) {250+ send({251+ jsonrpc: "2.0",252+ id: message.id,253+ error: { code: -32603, message: "ACP replay frame mismatch" },254+ });255+ }256+ stopWithFailure("Unexpected outbound ACP frame", actual);257+ return;258+ }259+ if (actual.kind === "request" && message.id !== undefined && message.id !== null) {260+ pendingClientRequestIds.set(actual.method, message.id);apps/server/scripts/record-codex-app-server-replay-fixture.ts line 198OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +178,21 @@178+ );179+}180+181+function isRecord(value: unknown): value is Record<string, unknown> {182+ return typeof value === "object" && value !== null;183+}184+185+function parseScenarios(): ReadonlyArray<ScenarioName> {186+ const rawValues = [187+ ...readArgValues("--scenario"),188+ ...(process.env.T3_CODEX_REPLAY_SCENARIOS ? [process.env.T3_CODEX_REPLAY_SCENARIOS] : []),189+ ];190+ const requested = rawValues.length > 0 ? rawValues : ["simple"];191+ const names = requested.flatMap((value) =>192+ value193+ .split(",")194+ .map((part) => part.trim())195+ .filter((part) => part.length > 0),196+ );197+198+ if (names.includes("all")) {apps/mobile/src/features/threads/ThreadFeed.tsx lines 225 to 225OutdatedResolvedby mwolson(GitHub profile, opens in a new tab)@@ -168,0 +205,21 @@205+ environmentId: props.environmentId,206+ sourceThreadId: props.projectedItem.sourceThreadId,207+ sourceItemId: props.projectedItem.sourceItemId,208+ });209+ const forkFromRun = useAtomCommand(threadEnvironment.forkFromRun, "fork from response");210+ const navigation = useNavigation();211+ const [busy, setBusy] = useState(false);212+ const canFork = canForkProjectedAssistantItem({213+ projectedItem: props.projectedItem,214+ capabilities: support.providerSession?.capabilities,215+ });216+ const runId = props.projectedItem.item.runId;217+218+ if (!canFork || runId === null) return null;219+220+ return (221+ <Pressable222+ accessibilityRole="button"223+ accessibilityLabel="Fork from this response"224+ disabled={busy}225+ onPress={() => {apps/mobile/src/state/use-thread-selection.ts line 65OutdatedResolvedby mwolson(GitHub profile, opens in a new tab)@@ -40,9 +50,16 @@4050 return null;4151 }425253+/**54+ * Builds an optimistic thread shell from the detail projection for the window55+ * where the shell list has not materialized the thread yet (e.g. a thread that56+ * was just created from this device).57+ */4358 function threadDetailToShell(4459 environmentId: EnvironmentId,45- thread: OrchestrationThread,60+ projection: OrchestrationV2ThreadProjection,4661 ): EnvironmentThreadShell {47- return {48- environmentId,62+ const thread = projection.thread;63+ const latestRun = deriveLatestThreadRun(projection);64+ const runtime = deriveThreadRuntime(projection);65+ const pendingRequest =apps/mobile/src/features/threads/ThreadActivityInspector.tsx lines 85 to 87OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +67,21 @@67+ >68+ <Text69+ selectable70+ className="text-2xs leading-[17px] text-foreground-muted"71+ style={block.monospaced ? { fontFamily: "ui-monospace" } : undefined}72+ >73+ {block.value}74+ </Text>75+ </ScrollView>76+ </View>77+ ))}78+79+ {model.fileLinks.length > 0 ? (80+ <View className="gap-1">81+ <Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">82+ Files83+ </Text>84+ {model.fileLinks.map((link) => {85+ const relativePath =86+ resolveWorkspaceRelativeFilePath(props.workspaceRoot, link.path) ??87+ (link.path.startsWith("/") ? null : link.path);apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts line 842OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +819,21 @@819+ message:820+ input.decision === "cancel"821+ ? "User cancelled tool execution."822+ : "User declined tool execution.",823+ toolUseID: input.toolUseID,824+ decisionClassification: "user_reject",825+ ...(input.decision === "cancel" ? { interrupt: true } : {}),826+ };827+}828+829+function permissionRequestFrame(input: {830+ readonly toolName: string;831+ readonly toolInput: Record<string, unknown>;832+ readonly callbackOptions: Parameters<CanUseTool>[2];833+}): ClaudePermissionRequestFrame {834+ const { callbackOptions } = input;835+ return {836+ type: "permission.request",837+ toolName: input.toolName,838+ input: input.toolInput,839+ options: {apps/server/src/checkpointing/CheckpointDiffQuery.ts line 103OutdatedResolvedby mwolson(GitHub profile, opens in a new tab)@@ -106,15 +99,5 @@10699 return emptyDiff;107100 }108101109- const threadContext = yield* projectionSnapshotQuery110- .getThreadCheckpointContext(input.threadId)111- .pipe(Effect.withSpan("checkpoint.turnDiff.lookupContext"));112- if (Option.isNone(threadContext)) {113- return yield* new CheckpointThreadNotFoundError({114- operation,115- threadId: input.threadId,116- });117- }118-119- const maxTurnCount = threadContext.value.checkpoints.reduce(120- (max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),102+ const projection = yield* threads.getThreadProjection(input.threadId).pipe(103+ Effect.mapError(apps/mobile/src/features/threads/thread-work-log.tsx line 348OutdatedResolvedby mwolson(GitHub profile, opens in a new tab)@@ -248,19 +345,4 @@248345 </View>249346 </Pressable>250347251- {fullDetail ? (252- <View className="ml-7 border-l border-neutral-300/60 pb-1 pl-3 pt-0.5 dark:border-white/[0.12]">253- <ScrollView254- nestedScrollEnabled255- directionalLockEnabled256- showsVerticalScrollIndicator257- className="max-h-60"258- contentContainerStyle={{ paddingRight: 8 }}259- >260- <Text261- selectable262- className="font-mono text-2xs leading-normal text-foreground-muted"263- >264- {fullDetail}265- </Text>266- </ScrollView>348+ {expanded && canExpand ? (apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts line 665OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +639,21 @@639+ readonly environment?: NodeJS.ProcessEnv;640+ readonly mcpServers?: ClaudeQueryOptions["mcpServers"];641+ readonly tools?: ClaudeAgentSdkQueryTools;642+ readonly allowedTools?: ReadonlyArray<string>;643+ readonly disallowedTools?: ReadonlyArray<string>;644+ readonly permissionMode?: PermissionMode;645+ readonly canUseTool?: CanUseTool;646+ readonly allowDangerouslySkipPermissions?: boolean;647+}): ClaudeAgentSdkQueryOptions {648+ const compiledSelection = compileClaudeModelSelection(input.modelSelection);649+ const extraArgs =650+ input.settings === undefined ? {} : parseCliArgs(input.settings.launchArgs).flags;651+ const threadIdentity: ClaudeAgentSdkThreadIdentity = input.resume652+ ? { resume: input.nativeThreadId }653+ : { sessionId: input.nativeThreadId };654+ const selectedTools = input.tools ?? CLAUDE_CODE_PRESET_TOOLS;655+ const selectionSettings =656+ Object.keys(compiledSelection.settings).length === 0657+ ? undefined658+ : (compiledSelection.settings as ClaudeSdkSettings);659+ const querySettings =apps/mobile/src/test-fixtures.ts lines 50 to 52OutdatedResolvedby mwolson(GitHub profile, opens in a new tab)@@ -0,0 +32,21 @@32+ activeProviderThreadId: null,33+ lineage: { rootThreadId: id, parentThreadId: null, relationshipToParent: null },34+ forkedFrom: null,35+ createdBy: "user",36+ creationSource: "mobile",37+ latestRunId: null,38+ activeRunId: null,39+ status: "idle",40+ pendingRuntimeRequest: null,41+ latestVisibleMessage: null,42+ latestUserMessageAt: null,43+ hasActionableProposedPlan: false,44+ itemCount: 0,45+ visibleItemCount: 0,46+ createdAt: now,47+ updatedAt: now,48+ archivedAt: null,49+ settledOverride: null,50+ settledAt: null,51+ deletedAt: null,52+ ...input,apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts lines 590 to 590OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +570,21 @@570+ },571+ ];572+ }),573+ );574+}575+576+export function nestedToolCallFromEnvelope(577+ envelope: Record<string, unknown>,578+): { readonly callId: string; readonly toolCall: ToolCall } | undefined {579+ const callId = typeof envelope.toolCallId === "string" ? envelope.toolCallId : undefined;580+ const wrapperEntry = Object.entries(envelope).find(([key]) => key.endsWith("ToolCall"));581+ if (wrapperEntry === undefined) {582+ return undefined;583+ }584+ const [wrapperName, rawCall] = wrapperEntry;585+ const call = unknownRecord(rawCall);586+ if (call === undefined) {587+ return undefined;588+ }589+ const args = unknownRecord(call.args) ?? {};590+ const fallbackCallId = `nested-${wrapperName}`;apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts line 48OutdatedResolvedby mwolson(GitHub profile, opens in a new tab)@@ -0,0 +28,21 @@28+29+const REPLAY_SETTINGS = Schema.decodeUnknownSync(AcpRegistrySettings)({30+ agentId: "replay-agent",31+ authMethodId: "replay",32+});33+34+export function makeAcpRegistryProviderAdapterRegistryReplayLayer(transcript: AcpReplayTranscript) {35+ const serverConfigLayer = Layer.effect(36+ ServerConfig,37+ makeReplayServerConfig(`acp-registry-${transcript.scenario}`).pipe(Effect.orDie),38+ ).pipe(Layer.provide(NodeServices.layer));39+40+ return makeProviderAdapterRegistryLayerEffect(41+ Effect.gen(function* () {42+ const fileSystem = yield* FileSystem.FileSystem;43+ const path = yield* Path.Path;44+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;45+ const crypto = yield* Crypto.Crypto;46+ const idAllocator = yield* IdAllocatorV2;47+ const serverConfig = yield* ServerConfig;48+ const replayDir = yield* fileSystemapps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts line 41OutdatedResolvedby mwolson(GitHub profile, opens in a new tab)@@ -0,0 +21,21 @@21+ makeAcpReplayRuntime,22+} from "./AcpAdapterV2.testkit.ts";23+import { GROK_DEFAULT_INSTANCE_ID, GROK_PROVIDER, makeGrokAdapterV2 } from "./GrokAdapterV2.ts";24+25+const DEFAULT_GROK_SETTINGS = Schema.decodeUnknownSync(GrokSettings)({});26+27+export function makeGrokProviderAdapterRegistryReplayLayer(transcript: AcpReplayTranscript) {28+ const serverConfigLayer = Layer.effect(29+ ServerConfig,30+ makeReplayServerConfig(`grok-${transcript.scenario}`).pipe(Effect.orDie),31+ ).pipe(Layer.provide(NodeServices.layer));32+33+ return makeProviderAdapterRegistryLayerEffect(34+ Effect.gen(function* () {35+ const fileSystem = yield* FileSystem.FileSystem;36+ const path = yield* Path.Path;37+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;38+ const crypto = yield* Crypto.Crypto;39+ const idAllocator = yield* IdAllocatorV2;40+ const serverConfig = yield* ServerConfig;41+ const replayDir = yield* fileSystem
- apps/mobile/src/features/threads/ThreadQueueControl.tsx line 141OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +121,21 @@121+ onPress={() => void move(run.id, workflow.queuedRuns[index + 2]?.run.id ?? null)}122+ className="h-9 w-9 items-center justify-center disabled:opacity-30"123+ >124+ <SymbolView name="arrow.down" size={13} tintColor={iconColor} type="monochrome" />125+ </Pressable>126+ <Pressable127+ accessibilityRole="button"128+ accessibilityLabel="Promote queued message to steer"129+ disabled={!controls.canSteer}130+ onPress={() => void steer(run.id)}131+ className="min-h-8 flex-row items-center gap-1 rounded-lg border border-neutral-300/60 px-2 disabled:opacity-30 dark:border-white/[0.1]"132+ >133+ <SymbolView134+ name="arrow.turn.left.up"135+ size={12}136+ tintColor={iconColor}137+ type="monochrome"138+ />139+ <Text className="font-t3-medium text-2xs text-foreground">Steer</Text>140+ </Pressable>141+ {controls.automaticCompletion ? (
- apps/server/src/orchestration-v2/Orchestrator.ts line 6036Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -5479,3 +5988,21 @@54795988 : undefined;54805989 });548159905991+ const planDelegatedCompletionDelivery = Effect.fn(5992+ "orchestrationV2.planDelegatedCompletionDelivery",5993+ )(function* (input: {5994+ readonly parentProjection: OrchestrationV2ThreadProjection;5995+ readonly parentRun: OrchestrationV2Run | undefined;5996+ readonly task: OrchestrationV2Subagent;5997+ readonly updatedTask: OrchestrationV2Subagent;5998+ readonly now: DateTime.Utc;5999+ }) {6000+ const taskDelivery = input.updatedTask.completionDelivery;6001+ if (taskDelivery?.state === "acknowledged" || taskDelivery?.state === "disposed") {6002+ return {6003+ task: input.updatedTask,6004+ parentRun: undefined,6005+ message: undefined,6006+ offer: false,6007+ };6008+ }apps/server/src/orchestration-v2/Orchestrator.ts line 1068Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -895,0 +1038,21 @@1038+ );1039+ const task = projection.subagents.find(1040+ (candidate) => candidate.id === command.taskId && candidate.origin === "app_owned",1041+ );1042+ if (task === undefined) {1043+ return yield* new OrchestratorDispatchError({1044+ commandId: command.commandId,1045+ commandType: command.type,1046+ cause: `Delegated task ${command.taskId} is not an app-owned task of thread ${command.parentThreadId}.`,1047+ });1048+ }1049+ const state =1050+ command.type === "delegated_task.completion-delivery.acknowledge"1051+ ? "acknowledged"1052+ : "disposed";1053+ if (task.completionDelivery?.state === state) {1054+ return yield* new OrchestratorDispatchError({1055+ commandId: command.commandId,1056+ commandType: command.type,1057+ cause: `Delegated task ${command.taskId} completion delivery is already ${state}.`,1058+ });apps/server/src/orchestration-v2/RunExecutionService.ts line 573Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -564,5 +564,10 @@564564 : [];565565 const persistedStatus =566566 input.terminal.status === "completed" ? "waiting" : input.terminal.status;567+ // Completion cohorts are advanced by Orchestrator while a provider568+ // turn is in flight. Do not replay the run snapshot captured at start569+ // over a newer acknowledgement, successor, or Stop barrier.570+ const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } =571+ input.run;567572 const finalizedRun: OrchestrationV2Run = {568- ...input.run,573+ ...runWithoutDelegatedCompletion,
- apps/server/src/orchestration-v2/Orchestrator.ts line 1091Resolvedby mwolson(GitHub profile, opens in a new tab)@@ -895,0 +1067,21 @@1067+ const updatedTask: OrchestrationV2Subagent = {1068+ ...task,1069+ completionDelivery: {1070+ state,1071+ observedByRunId:1072+ command.type === "delegated_task.completion-delivery.acknowledge"1073+ ? command.observedByRunId1074+ : null,1075+ },1076+ updatedAt: now,1077+ };1078+ yield* emitEvent({1079+ type: "subagent.updated",1080+ threadId: command.parentThreadId,1081+ ...(task.runId === null ? {} : { runId: task.runId }),1082+ nodeId: task.id,1083+ driver: task.driver,1084+ providerInstanceId: task.providerInstanceId,1085+ occurredAt: now,1086+ payload: updatedTask,1087+ });
- apps/server/src/mcp/OrchestratorMcpService.ts line 900Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -835,4 +881,19 @@835881 summary: derivedResult,836882 resultContextTransferId: resultTransfer?.id ?? null,837883 waitTimedOut,838- };884+ } satisfies OrchestratorMcpDelegateTaskResult;885+ if (886+ acknowledgeTerminal &&887+ isTerminalTaskStatus(status) &&888+ task.completionDelivery?.state !== "acknowledged" &&889+ task.completionDelivery?.state !== "disposed"890+ ) {891+ const observingRun = latestActiveRun(parentProjection);892+ yield* threadManagement893+ .dispatch({894+ type: "delegated_task.completion-delivery.acknowledge",895+ commandId: stableCommandId({896+ scope,897+ requestKey: String(taskId),898+ operation: acknowledgementOperation,899+ }),
juliusmarminge merged this99c957d
juliusmarminge closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
1b7060e3-68e2-4610-bd0a-74c7849c81cfYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share