fix(server): Stop always completes, and an agent that ignores it can be force stopped #27252
Mergedjuliusmarmingemerged 1 commit into
main fromrefs/pull/27252/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/orchestration-v2/Orchestrator.ts line 10466OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -10439,0 +10446,21 @@10446+ command: Extract<10447+ OrchestrationV2InternalCommand,10448+ { readonly type: "thread.interrupt.unresponsive" }10449+ >,10450+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,10451+ ) {10452+ const { providerTurn } = yield* projectionStore10453+ .getProviderControlContext(command.threadId, {10454+ providerThreadId: command.providerThreadId,10455+ providerTurnId: command.providerTurnId,10456+ })10457+ .pipe(mapDispatchError(command));10458+ const { runs } = yield* projectionStore10459+ .getThreadRecords(command.threadId, ["runs"])10460+ .pipe(mapDispatchError(command));10461+ const run = runs.find(10462+ (candidate) =>10463+ providerTurn !== undefined && candidate.activeAttemptId === providerTurn.runAttemptId,10464+ );10465+ // A provider that stopped late already settled the run; it needs no Force stop.10466+ if (run === undefined || run.status !== "running" || providerTurn?.status !== "running")apps/server/src/orchestration-v2/ThreadManagementService.ts line 1153OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1074,0 +1133,21 @@1133+ ? orchestrator.dispatch({1134+ type: "run.interrupt",1135+ commandId,1136+ threadId: input.threadId,1137+ runId: run.id,1138+ reason: FORCE_STOP_REASON,1139+ })1140+ : orchestrator.dispatch({1141+ type: "thread.background-work.settle",1142+ commandId,1143+ threadId: input.threadId,1144+ providerThreadId: providerTurn.providerThreadId,1145+ providerTurnId: providerTurn.id,1146+ reason: FORCE_STOP_REASON,1147+ });1148+ }1149+ // Teardown waits on the provider's own exit paths, so it must not hold up the reply.1150+ yield* Effect.forEach(1151+ [1152+ ...releasable.map((providerSessionId) =>1153+ sessions.release({apps/server/src/process/agentScope.ts line 332Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -326,3 +326,5 @@326326 }327327 });328328329+ const kill: AgentScopeShape["kill"] = Effect.fn("AgentScope.kill")(function* (threadId) {330+ const tracked = scopeByThread.get(threadId);
- apps/server/src/orchestration-v2/ThreadManagementService.ts line 1191OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1074,0 +1171,21 @@1171+ sessions.detach({1172+ providerSessionId,1173+ threadId: input.threadId,1174+ detail: FORCE_STOP_REASON,1175+ }),1176+ ),1177+ ],1178+ (teardown) =>1179+ teardown.pipe(1180+ Effect.catchCause((cause) =>1181+ Effect.logWarning("orchestration-v2.force-stop-teardown-failed", {1182+ threadId: input.threadId,1183+ cause,1184+ }),1185+ ),1186+ Effect.forkIn(layerScope),1187+ ),1188+ { discard: true },1189+ );1190+ return {1191+ outcome: killed ? "killed" : shared.length > 0 ? "shared" : "released",
- apps/mobile/src/features/threads/ThreadDetailScreen.tsx lines 558 to 564Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -530,0 +539,21 @@539+ : environmentThreadDetails.runStopAtom(props.selectedThreadDetailRef),540+ );541+ // A background Stop matters only while that work is still pending.542+ const runStop =543+ anyRunStop?.background && props.selectedThread.pendingBackgroundTasks.length === 0544+ ? null545+ : anyRunStop;546+ const forceStopThread = useAtomCommand(orchestrationEnvironment.forceStopThread, {547+ reportFailure: false,548+ });549+ const canForceStop =550+ useAtomValue(orchestrationEnvironment.forceStopThread.permissionAtom(props.environmentId)) &&551+ props.serverConfig?.environment.capabilities.threadForceStop === true;552+ const [forceStoppingKey, setForceStoppingKey] = useState<string | null>(null);553+ const forceStop = async () => {554+ const threadKey = selectedThreadKey;555+ setForceStoppingKey(threadKey);556+ const result = await forceStopThread({557+ environmentId: props.environmentId,558+ input: { threadId: props.selectedThread.id },559+ });apps/mobile/src/features/threads/ThreadDetailScreen.tsx lines 692 to 695OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -647,3 +689,7 @@647689 },648690 };649691 }692+ if (runStop !== null && contentPresentationKind === "ready") {693+ const unresponsive = runStop.state === "unresponsive";694+ return {695+ kind: "stop",apps/mobile/src/features/threads/ThreadDetailScreen.tsx lines 707 to 709OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -647,3 +689,21 @@647689 },648690 };649691 }692+ if (runStop !== null && contentPresentationKind === "ready") {693+ const unresponsive = runStop.state === "unresponsive";694+ return {695+ kind: "stop",696+ unresponsive,697+ label: unresponsive ? "Not responding to Stop" : "Stopping…",698+ action:699+ unresponsive && canForceStop700+ ? {701+ label: forceStoppingKey === selectedThreadKey ? "Force stopping..." : "Force stop",702+ accessibilityLabel: "Force stop the agent",703+ disabled: forceStoppingKey === selectedThreadKey,704+ onPress: () =>705+ Dialog.confirm({706+ title: "Force stop the agent?",707+ message:708+ "It has not answered Stop. Force stop kills its processes and ends the turn.",709+ confirmText: "Force stop",apps/server/src/orchestration-v2/ProviderSessionManager.ts lines 2303 to 2305OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -2269,3 +2293,13 @@22692293 ),22702294 ),22712295 release: releaseEntry,2296+ otherWorkingThreads: Effect.fn("ProviderSessionManager.otherWorkingThreads")(2297+ function* (input) {2298+ const entry = (yield* Ref.get(sessions)).get(sessionKey(input.providerSessionId));2299+ if (entry === undefined || !entry.supportsMultipleProviderThreads) return [];2300+ return yield* Effect.filter(2301+ [...entry.attachedThreadIds].filter((threadId) => threadId !== input.threadId),2302+ (threadId) =>2303+ projectionStore.getThreadShell(threadId).pipe(2304+ Effect.map((shell) => shell !== null && shell.activeRunId !== null),2305+ // An unreadable thread may still be working; never kill it unseen.packages/contracts/src/orchestrationV2.ts lines 3932 to 3934OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -3908,3 +3922,13 @@39083922 }39093923 }391039243925+export const OrchestrationV2ForceStopThreadInput = Schema.Struct({3926+ threadId: ThreadId,3927+});3928+export type OrchestrationV2ForceStopThreadInput = typeof OrchestrationV2ForceStopThreadInput.Type;3929+3930+export const OrchestrationV2ForceStopThreadResult = Schema.Struct({3931+ /**3932+ * `killed`: the thread's own agent processes were killed. `released`: its provider session3933+ * was torn down, which kills the agent's process group. `shared`: the agent process also3934+ * works for `sharedWithThreadIds`, so only this thread's turn was ended.packages/provider-acp/src/server/adapter.ts line 8006OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -8001,4 +8003,4 @@80018003 // ACP cancel leaves native children alive; close confirms session-wide Stop.80028004 pendingStopCloseTurn = interruptContext;80038005 const closed = yield* runtime.closeSession().pipe(8004- Effect.timeoutOption("10 seconds"),8006+ Effect.timeoutOption(ACP_STOP_CONFIRM_TIMEOUT_MS),
- apps/server/src/orchestration-v2/ThreadManagementService.ts line 1107OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1073,2 +1087,21 @@10731087 });107410881089+ const forceStopThread: ThreadManagementServiceShape["forceStopThread"] = Effect.fn(1090+ "ThreadManagementService.forceStopThread",1091+ )(1092+ function* (input) {1093+ const records = yield* orchestrator.getThreadRecords(input.threadId, [1094+ "runs",1095+ "providerThreads",1096+ "providerTurns",1097+ ]);1098+ const sessionIds = new Set(1099+ records.providerThreads.flatMap((providerThread) =>1100+ providerThread.appThreadId === input.threadId && providerThread.providerSessionId !== null1101+ ? [providerThread.providerSessionId]1102+ : [],1103+ ),1104+ );1105+ // Shared scopes are never tracked per thread, so this only kills the thread's own agent.1106+ const killed = yield* agentScope.kill(input.threadId);1107+ const run = latestActiveRun(records);
- apps/server/src/orchestration-v2/ThreadManagementService.ts line 1101OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1072,3 +1089,13 @@10721089 return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;10731090 });107410911092+ const forceStopThread: ThreadManagementServiceShape["forceStopThread"] = Effect.fn(1093+ "ThreadManagementService.forceStopThread",1094+ )(1095+ function* (input) {1096+ const records = yield* orchestrator.getThreadRecords(input.threadId, [1097+ "runs",1098+ "providerThreads",1099+ "providerTurns",1100+ ]);1101+ const latestRunId = records.runs.reduce<OrchestrationV2Run | undefined>(
- apps/server/src/orchestration-v2/ThreadManagementService.ts lines 1230 to 1238Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1074,0 +1189,21 @@1189+ }1190+ }1191+ // Teardown waits on the provider's own exit paths; past this bound it keeps going on its own.1192+ const released = yield* Effect.forEach(releases, (release) =>1193+ Fiber.join(release).pipe(Effect.timeoutOption(FORCE_STOP_RELEASE_WAIT)),1194+ );1195+ const releasing = released.some(Option.isNone);1196+ return {1197+ outcome: killed ? "killed" : shared ? "shared" : releasing ? "releasing" : "released",1198+ sharedWithThreadIds: [...sharedWith],1199+ } as const;1200+ },1201+ (effect, input) =>1202+ effect.pipe(1203+ Effect.mapError((cause) =>1204+ isForceStopThreadError(cause)1205+ ? cause1206+ : new OrchestrationV2ForceStopThreadError({ threadId: input.threadId, cause }),1207+ ),1208+ ),1209+ );
- apps/server/src/orchestration-v2/ProviderSessionManager.ts line 2328OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2269,3 +2318,11 @@22692318 ),22702319 ),22712320 release: releaseEntry,2321+ releaseUnlessBusy: Effect.fn("ProviderSessionManager.releaseUnlessBusy")(function* (input) {2322+ yield* releaseEntry({2323+ providerSessionId: input.providerSessionId,2324+ reason: input.reason,2325+ ...(input.detail === undefined ? {} : { detail: input.detail }),2326+ keepIfBusyOtherThan: input.ownProviderThreadIds,2327+ });2328+ return !(yield* Ref.get(sessions)).has(sessionKey(input.providerSessionId));
- apps/server/src/orchestration-v2/ProviderSessionManager.ts line 1836OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1790,3 +1828,9 @@17901828 providerSessionId,17911829 busyTurnKey(input.providerThread.id, input.runOrdinal),17921830 ),1831+ ).pipe(1832+ // A release between attach and markBusy leaves nothing to mark: fail the1833+ // start instead of running it on a runtime being torn down.1834+ Effect.andThen(Ref.get(sessions)),1835+ Effect.flatMap((current) =>1836+ current.get(sessionKey(providerSessionId))?.runtime === runtime
macroscopeapp[bot](GitHub profile, opens in a new tab) approved these changes
juliusmarminge merged this6b1245c
juliusmarminge closed this
Sign in to join this conversation.




macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed