TypeScript
fix(server): Stop always completes, and an agent that ignores it can be force stopped (#27252)
Julius Marminge6b1245cceda1
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsxindex 27655f503bd..6695e7963ef 100644--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx@@ -46,6 +46,7 @@ import type {ScopedThreadRef,ServerConfig as T3ServerConfig,UsageLimitsReport,+ RunId,} from "@t3tools/contracts";import {appendCodexArtifactTemplateUsePrompt,@@ -156,8 +157,10 @@ import {import { appAtomRegistry } from "../../state/atom-registry";import { threadStreamHaptics } from "./threadStreamHaptics";import { useAtomCommand } from "../../state/use-atom-command";+import { orchestrationEnvironment } from "../../state/orchestration";import { useDelayedStatus } from "../../lib/useDelayedStatus";import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input";+import type { RunStopPresentation } from "@t3tools/client-runtime/state/thread-execution";import type {PendingApproval,PendingUserInput,@@ -339,6 +342,9 @@ const threadVisitTracker = createThreadVisitTracker({// Past the composer's 180 ms height animation.const COMPOSER_HEIGHT_SETTLE_MS = 220;+const NO_RUN_STOP_ATOM = Atom.make<RunStopPresentation | null>(null).pipe(+ Atom.withLabel("mobile-thread-run-stop:empty"),+);// Anchors, the submitted message, follow state and pending scrolls belong to// one thread, so the body remounts when the thread changes.@@ -528,6 +534,50 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {const unsettleThread = useAtomCommand(threadEnvironment.unsettle, { reportFailure: false });const updateMetadata = useAtomCommand(threadEnvironment.updateMetadata, { reportFailure: false });const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });+ const anyRunStop = useAtomValue(+ props.selectedThreadDetailRef === null+ ? NO_RUN_STOP_ATOM+ : environmentThreadDetails.runStopAtom(props.selectedThreadDetailRef),+ );+ // A background Stop matters only while that work is still pending.+ const runStop =+ anyRunStop?.background && props.selectedThread.pendingBackgroundTasks.length === 0+ ? null+ : anyRunStop;+ const forceStopThread = useAtomCommand(orchestrationEnvironment.forceStopThread, {+ reportFailure: false,+ });+ const canForceStop =+ useAtomValue(orchestrationEnvironment.forceStopThread.permissionAtom(props.environmentId)) &&+ props.serverConfig?.environment.capabilities.threadForceStop === true;+ const [forceStoppingKey, setForceStoppingKey] = useState<string | null>(null);+ // The run that ignored Stop, so a confirmation left open cannot hit a newer run.+ const forceStop = async (runId: RunId | undefined) => {+ const threadKey = selectedThreadKey;+ setForceStoppingKey(threadKey);+ const result = await forceStopThread({+ environmentId: props.environmentId,+ input:+ runId === undefined+ ? { threadId: props.selectedThread.id }+ : { threadId: props.selectedThread.id, runId },+ });+ setForceStoppingKey((current) => (current === threadKey ? null : current));+ if (result._tag === "Failure") {+ if (!isAtomCommandInterrupted(result)) Dialog.alert("Could not force stop the agent");+ return;+ }+ const others = result.value.sharedWithThreadIds.length;+ if (result.value.outcome === "releasing") {+ Dialog.alert("Turn stopped; the agent is still shutting down");+ }+ if (result.value.outcome === "shared") {+ Dialog.alert(+ "Turn stopped; the agent process kept running",+ `It is shared with ${others === 0 ? "other" : others} working ${others === 1 ? "thread" : "threads"}. Stop those to free it.`,+ );+ }+ };const [statusRequest, setStatusRequest] = useState<{ threadKey: string } | null>(null);const statusPending = statusRequest?.threadKey === selectedThreadKey;const [lifecycleNow, setLifecycleNow] = useState(() => new Date().toISOString());@@ -619,6 +669,32 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {if (connectionStatus !== null && !props.draftMode) {return connectionStatus;}+ // Before the request check: an agent stuck on an approval may also ignore Stop.+ if (runStop !== null && contentPresentationKind === "ready") {+ const unresponsive = runStop.state === "unresponsive";+ return {+ kind: "stop",+ unresponsive,+ label: unresponsive ? "Not responding to Stop" : "Stopping…",+ action:+ unresponsive && canForceStop+ ? {+ label: forceStoppingKey === selectedThreadKey ? "Force stopping..." : "Force stop",+ accessibilityLabel: "Force stop the agent",+ disabled: forceStoppingKey === selectedThreadKey,+ onPress: () =>+ Dialog.confirm({+ title: "Force stop the agent?",+ message:+ "It has not answered Stop. Force stop ends the turn and kills the agent's processes, unless other working threads share them.",+ confirmText: "Force stop",+ destructive: true,+ onConfirm: () => void forceStop(runStop.runId),+ }),+ }+ : null,+ };+ }if (props.activePendingApproval !== null || props.activePendingUserInput !== null) {return null;}diff --git a/apps/mobile/src/features/threads/floating-working-control.tsx b/apps/mobile/src/features/threads/floating-working-control.tsxindex 3709cf2affa..c1440535e9c 100644--- a/apps/mobile/src/features/threads/floating-working-control.tsx+++ b/apps/mobile/src/features/threads/floating-working-control.tsx@@ -83,7 +83,9 @@ export function FloatingWorkingControl(props: {const [queueWidth, setQueueWidth] = useState(0);const [actionWidth, setActionWidth] = useState(0);const action =- props.status?.kind === "background" || props.status?.kind === "lifecycle"+ props.status?.kind === "background" ||+ props.status?.kind === "lifecycle" ||+ props.status?.kind === "stop"? props.status.action: null;const [agentsWidth, setAgentsWidth] = useState(0);@@ -471,6 +473,30 @@ function FloatingStatusLabel(props: {</StatusLabelRow>);}+ if (props.status.kind === "stop") {+ return (+ <StatusLabelRow+ key="stop"+ accessibilityLabel={props.status.label}+ className="gap-2"+ onLayout={props.onLayout}+ >+ {props.status.unresponsive ? (+ <SymbolView+ name="exclamationmark.triangle"+ size={13}+ tintColorClassName="accent-warning-foreground"+ type="monochrome"+ />+ ) : (+ <AppActivityIndicator size="small" colorClassName="accent-icon-muted" />+ )}+ <Text className="shrink font-t3-medium text-xs text-foreground" numberOfLines={1}>+ {props.status.label}+ </Text>+ </StatusLabelRow>+ );+ }if (props.status.kind === "goal") {return (<StatusLabelRowdiff --git a/apps/mobile/src/features/threads/floating-working-status.ts b/apps/mobile/src/features/threads/floating-working-status.tsindex 264d110f75f..2892b4aafa5 100644--- a/apps/mobile/src/features/threads/floating-working-status.ts+++ b/apps/mobile/src/features/threads/floating-working-status.ts@@ -31,6 +31,12 @@ export type FloatingWorkingStatus =readonly label: string;readonly action: FloatingStatusAction;}+ | {+ readonly kind: "stop";+ readonly label: string;+ readonly unresponsive: boolean;+ readonly action: FloatingStatusAction | null;+ }| { readonly kind: "goal"; readonly label: string; readonly accessibilityLabel: string }| { readonly kind: "preparing"; readonly label: string }| {diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.tsindex a1b05c32a00..ecda5f8abc6 100644--- a/apps/server/src/auth/RpcAuthorization.ts+++ b/apps/server/src/auth/RpcAuthorization.ts@@ -42,6 +42,7 @@ export const RPC_REQUIRED_SCOPES = {[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,[ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,[ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: AuthOrchestrationOperateScope,+ [ORCHESTRATION_V2_WS_METHODS.forceStopThread]: AuthOrchestrationOperateScope,[ORCHESTRATION_V2_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,[ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff]: AuthOrchestrationReadScope,[ORCHESTRATION_V2_WS_METHODS.searchThreads]: AuthOrchestrationReadScope,diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.tsindex cef18fbe325..5e0bcfc742e 100644--- a/apps/server/src/environment/ServerEnvironment.ts+++ b/apps/server/src/environment/ServerEnvironment.ts@@ -240,6 +240,7 @@ export const make = Effect.gen(function* () {projectSettingsOverrides: true,projectProviderInstanceOverrides: true,threadSnooze: true,+ threadForceStop: true,environmentThemes: true,usageLimitSources: true,providerWorkspaceSnapshotsOnDemand: true,diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.tsindex 259fa92a660..028ea5a561d 100644--- a/apps/server/src/observability/RpcInstrumentation.ts+++ b/apps/server/src/observability/RpcInstrumentation.ts@@ -14,6 +14,7 @@ const RPC_AGGREGATES = {[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: "orchestrationV2",[ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: "orchestration",[ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: "orchestration",+ [ORCHESTRATION_V2_WS_METHODS.forceStopThread]: "orchestration",[ORCHESTRATION_V2_WS_METHODS.getTurnItem]: "orchestration",[ORCHESTRATION_V2_WS_METHODS.getTurnDiff]: "orchestration",[ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff]: "orchestration",diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.tsindex 8a68e92b891..b924f6efb3e 100644--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts@@ -7498,6 +7498,96 @@ describe("AcpAdapterV2", () => {}).pipe(Effect.provide(layerTest), Effect.scoped),);+ it.live("lets a caller abandon Stop while hard teardown stalls, and finishes the teardown", () =>+ Effect.gen(function* () {+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const idAllocator = yield* IdAllocator.IdAllocatorV2;+ const path = yield* Path.Path;+ const selfInvocation = yield* resolveSelfInvocation();+ const mockAgentPath = yield* path.fromFileUrl(+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),+ );+ const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);+ const teardownStarted = yield* Deferred.make<void>();+ const releaseTeardown = yield* Deferred.make<void>();+ let runtimeOrdinalSeen = 0;+ const instanceId = ProviderInstanceId.make("acp-test");+ const adapter = yield* makeAcpAdapterV2({+ instanceId,+ flavor: {+ driver: ACP_TEST_DRIVER,+ capabilities: AcpProviderCapabilitiesV2,+ interruptPromptOnCancel: true,+ restartRuntimeAfterInterrupt: true,+ terminateRuntimeProcessGroupOnInterrupt: true,+ makeRuntime: makeMockRuntime({+ childProcessSpawner,+ mockAgentPath,+ ownDetachedProcessGroup: true,+ processGroupPlatform: "win32",+ windowsProcessTreeTerminator: () =>+ Deferred.succeed(teardownStarted, undefined).pipe(+ Effect.andThen(Deferred.await(releaseTeardown)),+ ),+ environment: (runtimeOrdinal) => {+ runtimeOrdinalSeen = runtimeOrdinal;+ return runtimeOrdinal === 1 ? { T3_ACP_HANG_PROMPT_FOREVER: "1" } : {};+ },+ protocolEvents,+ }),+ },+ selfInvocation,+ });+ const threadId = ThreadId.make("thread-acp-abandoned-hard-teardown");+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({+ runtimeMode: "full-access",+ interactionMode: "default",+ cwd: process.cwd(),+ });+ const modelSelection = { instanceId, model: "default" } as const;+ const runtime = yield* adapter.openSession({+ threadId,+ providerSessionId: ProviderSessionId.make("provider-session-acp-abandoned-hard-teardown"),+ modelSelection,+ runtimePolicy,+ });+ const providerThread = yield* runtime.ensureThread({+ threadId,+ modelSelection,+ runtimePolicy,+ });+ const now = yield* DateTime.now;+ yield* runtime+ .startTurn(+ makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }),+ )+ .pipe(Effect.forkScoped);+ const providerTurnId = idAllocator.derive.providerTurn({+ driver: ACP_TEST_DRIVER,+ nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),+ });+ yield* pollProtocolMethods(protocolEvents);+ const interruptFiber = yield* runtime+ .interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true })+ .pipe(Effect.forkScoped);+ yield* Deferred.await(teardownStarted);++ // The session manager's Stop timeout interrupts this call; it must not wait for teardown.+ yield* Fiber.interrupt(interruptFiber);++ const startFiber = yield* runtime+ .startTurn(+ makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }),+ )+ .pipe(Effect.forkScoped);+ yield* Deferred.succeed(releaseTeardown, undefined);+ yield* Fiber.join(startFiber);+ assert.equal(runtimeOrdinalSeen, 2);+ const replacementMethods = yield* pollProtocolMethods(protocolEvents);+ assert.equal(replacementMethods.filter((method) => method === "session/resume").length, 1);+ }).pipe(Effect.provide(layerTest), Effect.scoped),+ );+it.effect("direct Stop on a deferred subagent hold terminalizes the subagent and does not carry it forward",() =>diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.tsindex de13c4bb6d1..a821a4713b2 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts@@ -322,6 +322,8 @@ const WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS = 500;// A steer waits at most this long, from its request, for its foreground// subagents to move to the background before it is sent.const BACKGROUND_MOVE_TIMEOUT_MS = 5_000;+// How long a Stop waits for the CLI to exit before the user is offered Force stop.+const CLAUDE_STOP_CONFIRM_TIMEOUT_MS = 10_000;const CLAUDE_GROUP_WATCH_SCRIPT = ["{ trap '' TERM; read -r _ <&3; kill -TERM 0; sleep 5; kill -KILL 0; } </dev/null >/dev/null 2>&1 &",@@ -10471,44 +10473,36 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (yield* existing.query.interrupt;yield* existing.query.close.pipe(Effect.ignore);const closed = yield* Deferred.await(existing.closed).pipe(- Effect.timeoutOption("10 seconds"),+ Effect.timeoutOption(CLAUDE_STOP_CONFIRM_TIMEOUT_MS),);if (Option.isSome(closed)) {return;}-- const completedAt = yield* DateTime.now;+ // The turn stays open: the CLI may still be working, and the user decides+ // whether to Force stop it.yield* Effect.logWarning("orchestration-v2.claude-query-interrupt-timeout", {providerSessionId: input.providerSessionId,providerThreadId: turnInput.providerThread.id,providerTurnId: turnInput.providerTurnId,});- const ownedLiveQuery = yield* Ref.modify(queryContext, (current) =>- current?.query === existing.query ? [true, null] : [false, current],- );- if (ownedLiveQuery) {- existing.stopping = true;- yield* finalizeActiveTurnAfterQueryExit(existing);- yield* endSubagentCallsOfClosedQuery(existing.nativeThreadId, "interrupted");- } else {- yield* finalizeActiveTurn({- context: currentTurn,- status: "interrupted",- completedAt,- });- }- yield* Deferred.succeed(existing.closed, undefined);+ return yield* new ProviderAdapter.ProviderAdapterInterruptTimeoutError({+ driver: CLAUDE_PROVIDER,+ providerThreadId: turnInput.providerThread.id,+ providerTurnId: turnInput.providerTurnId,+ timeoutMs: CLAUDE_STOP_CONFIRM_TIMEOUT_MS,+ });},(effect, turnInput) =>effect.pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterInterruptError({- driver: CLAUDE_PROVIDER,- providerThreadId: turnInput.providerThread.id,- providerTurnId: turnInput.providerTurnId,- cause,- }),+ Effect.mapError((cause) =>+ cause._tag === "ProviderAdapterInterruptTimeoutError"+ ? cause+ : new ProviderAdapter.ProviderAdapterInterruptError({+ driver: CLAUDE_PROVIDER,+ providerThreadId: turnInput.providerThread.id,+ providerTurnId: turnInput.providerTurnId,+ cause,+ }),),),);diff --git a/apps/server/src/orchestration-v2/EffectWorker.test.ts b/apps/server/src/orchestration-v2/EffectWorker.test.tsindex cb130930372..2329f2aa20c 100644--- a/apps/server/src/orchestration-v2/EffectWorker.test.ts+++ b/apps/server/src/orchestration-v2/EffectWorker.test.ts@@ -111,6 +111,8 @@ function layerExecutorFor(input: {closeInstance: () => Effect.void,release: () => record("release"),detach: () => record("detach"),+ otherWorkingThreads: () => Effect.succeed([]),+ releaseUnlessBusy: () => Effect.succeed(true),}),),Layer.succeed(@@ -167,7 +169,18 @@ function layerExecutorFor(input: {);}-it.effect("settles a stopped run when its adapter has already lost the native turn", () =>+it.effect.each([+ {+ name: "settles a stopped run when its adapter has already lost the native turn",+ unresponsive: false,+ dispatched: ["thread.background-work.settle"],+ },+ {+ name: "leaves the run running and flags the Stop when the provider never confirms it",+ unresponsive: true,+ dispatched: ["thread.interrupt.unresponsive"],+ },+])("$name", ({ unresponsive, dispatched }) =>Effect.gen(function* () {const now = yield* DateTime.now;const events = yield* Ref.make<ReadonlyArray<string>>([]);@@ -178,7 +191,8 @@ it.effect("settles a stopped run when its adapter has already lost the native tuthreadId,operation: "interrupt",providerTurnId,- cause: "Provider turn is not active.",+ ...(unresponsive ? { unresponsive } : {}),+ cause: unresponsive ? "Timed out." : "Provider turn is not active.",}),threads: {dispatch: (command) =>@@ -199,7 +213,7 @@ it.effect("settles a stopped run when its adapter has already lost the native tu},});}).pipe(Effect.provide(layer));- assert.deepEqual(yield* Ref.get(events), ["thread.background-work.settle"]);+ assert.deepEqual(yield* Ref.get(events), dispatched);}),);diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.tsindex d174db2fb3a..534043aeb4e 100644--- a/apps/server/src/orchestration-v2/EffectWorker.ts+++ b/apps/server/src/orchestration-v2/EffectWorker.ts@@ -177,6 +177,13 @@ export const layerExecutor: Layer.Layer<cause,}),),+ Effect.map((outcome) => ({ unresponsive: false, outcome }) as const),+ // Settling here would end the run while the agent may still be running; the+ // user decides with Force stop instead.+ Effect.catchIf(+ (cause) => request.subagent === undefined && cause.unresponsive === true,+ () => Effect.succeed({ unresponsive: true, outcome: undefined } as const),+ ),Effect.catchIf((cause) =>request.subagent === undefined &&@@ -184,27 +191,35 @@ export const layerExecutor: Layer.Layer<request.type,Cause.pretty(Cause.fail(cause)),),- () => Effect.void,+ () => Effect.succeed({ unresponsive: false, outcome: undefined } as const),),- Effect.andThen((outcome) =>- request.subagent !== undefined && outcome === undefined- ? Effect.void- : threads.dispatch({- type: "thread.background-work.settle",- commandId: CommandId.make(`${effect.id}:background-work-settled`),- ...(request.subagent === undefined || outcome === undefined- ? {}- : {- subagent: {- id: request.subagent.id,- stoppedAt: DateTime.makeUnsafe(effect.createdAt),- outcome,- },- }),+ Effect.andThen(({ unresponsive, outcome }) =>+ unresponsive+ ? threads.dispatch({+ type: "thread.interrupt.unresponsive",+ commandId: CommandId.make(`${effect.id}:unresponsive`),threadId: effect.threadId,providerThreadId: request.providerThreadId,providerTurnId: request.providerTurnId,- }),+ })+ : request.subagent !== undefined && outcome === undefined+ ? Effect.void+ : threads.dispatch({+ type: "thread.background-work.settle",+ commandId: CommandId.make(`${effect.id}:background-work-settled`),+ ...(request.subagent === undefined || outcome === undefined+ ? {}+ : {+ subagent: {+ id: request.subagent.id,+ stoppedAt: DateTime.makeUnsafe(effect.createdAt),+ outcome,+ },+ }),+ threadId: effect.threadId,+ providerThreadId: request.providerThreadId,+ providerTurnId: request.providerTurnId,+ }),),Effect.mapError((cause) =>diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.tsindex 16865229d94..50f9a2acc0f 100644--- a/apps/server/src/orchestration-v2/Orchestrator.ts+++ b/apps/server/src/orchestration-v2/Orchestrator.ts@@ -536,6 +536,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {case "checkpoint.rollback":case "checkpoint.rollback.fail":case "thread.background-work.settle":+ case "thread.interrupt.unresponsive":case "thread.stop":case "provider.switch":return command.threadId;@@ -10278,7 +10279,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiorun,rootNode,providerThread,- reason: yield* runInterruptReason(input.command, input.events, run.id),+ reason:+ (input.command.type === "thread.background-work.settle"+ ? input.command.reason+ : undefined) ?? (yield* runInterruptReason(input.command, input.events, run.id)),completedAt: input.now,}),});@@ -10525,6 +10529,55 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioyield* closePendingLinkRequests({ ...input, threadId: thread.id });});+ const dispatchInterruptUnresponsive = Effect.fn("Orchestrator.dispatchInterruptUnresponsive")(+ function* (+ command: Extract<+ OrchestrationV2InternalCommand,+ { readonly type: "thread.interrupt.unresponsive" }+ >,+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,+ ) {+ const { providerTurn } = yield* projectionStore+ .getProviderControlContext(command.threadId, {+ providerThreadId: command.providerThreadId,+ providerTurnId: command.providerTurnId,+ })+ .pipe(mapDispatchError(command));+ const { runs } = yield* projectionStore+ .getThreadRecords(command.threadId, ["runs"])+ .pipe(mapDispatchError(command));+ const run = runs.find(+ (candidate) =>+ providerTurn !== undefined && candidate.activeAttemptId === providerTurn.runAttemptId,+ );+ // A settled run still counts: Stop may have targeted its background work.+ if (run === undefined) return;+ const { turnItems } = yield* projectionStore+ .getThreadRecords(command.threadId, ["turnItems"], {+ turnItemTypes: ["run_interrupt_request", "run_interrupt_result"],+ turnItemRunIds: [run.id],+ })+ .pipe(mapDispatchError(command));+ // A provider that stopped late already wrote the result; it needs no Force stop.+ if (turnItems.some((item) => item.type === "run_interrupt_result")) return;+ const request = turnItems.find((item) => item.type === "run_interrupt_request");+ if (request?.type !== "run_interrupt_request" || request.unresponsiveAt !== undefined) return;+ const now = yield* DateTime.now;+ yield* emit(+ events,+ command,+ )({+ type: "turn-item.updated",+ threadId: command.threadId,+ runId: run.id,+ ...(request.nodeId === null ? {} : { nodeId: request.nodeId }),+ providerInstanceId: run.providerInstanceId,+ occurredAt: now,+ payload: { ...request, unresponsiveAt: now, updatedAt: now },+ });+ },+ );+const dispatchBackgroundWorkSettle = Effect.fn("Orchestrator.dispatchBackgroundWorkSettle")(function* (command: Extract<@@ -12902,6 +12955,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiocase "thread.background-work.settle":yield* dispatchBackgroundWorkSettle(command, events, effects);break;+ case "thread.interrupt.unresponsive":+ yield* dispatchInterruptUnresponsive(command, events);+ break;case "thread.fork":yield* dispatchThreadFork(command, events);break;@@ -13032,6 +13088,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio(planned) =>planned.events.length > 0 ||command.type === "thread.background-work.settle" ||+ command.type === "thread.interrupt.unresponsive" ||command.type === "thread.stop" ||command.type === "subagent.stop" ||// Closing a share again, or after it ended, is not an error.diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.tsindex 86b173f80dc..5bbb3926e2b 100644--- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts+++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts@@ -338,6 +338,7 @@ const makeProviderAdapter = Effect.fnUntraced(function* (readonly backgroundTasksEndWithProcess?: boolean;readonly hangSessionScopeClose?: boolean;readonly startTurn?: Effect.Effect<void>;+ readonly interruptTurn?: Effect.Effect<void>;readonly beforeUnload?: Effect.Effect<void>;readonly spawnBeforeOpen?: boolean;readonly scopeCloseReached?: Deferred.Deferred<void>;@@ -437,7 +438,7 @@ const makeProviderAdapter = Effect.fnUntraced(function* (Ref.update(state, (current) => ({...current,interruptCount: current.interruptCount + 1,- })),+ })).pipe(Effect.andThen(options.interruptTurn ?? Effect.void)),unloadThread: ({ providerThread }) =>(options.beforeUnload ?? Effect.void).pipe(Effect.andThen(@@ -485,6 +486,7 @@ function layerTest(input: {readonly backgroundTasksEndWithProcess?: boolean;readonly hangSessionScopeClose?: boolean;readonly startTurn?: Effect.Effect<void>;+ readonly interruptTurn?: Effect.Effect<void>;readonly beforeUnload?: Effect.Effect<void>;readonly spawnBeforeOpen?: boolean;readonly scopeCloseReached?: Deferred.Deferred<void>;@@ -520,6 +522,7 @@ function layerTest(input: {? {}: { hangSessionScopeClose: input.hangSessionScopeClose }),...(input.startTurn === undefined ? {} : { startTurn: input.startTurn }),+ ...(input.interruptTurn === undefined ? {} : { interruptTurn: input.interruptTurn }),...(input.beforeUnload === undefined ? {} : { beforeUnload: input.beforeUnload }),...(input.spawnBeforeOpen === undefined ? {} : { spawnBeforeOpen: input.spawnBeforeOpen }),...(input.scopeCloseReached === undefined@@ -1367,6 +1370,159 @@ it.effect(}),);+it.effect("ProviderSessionManagerV2 gives up on a provider that never confirms a Stop", () =>+ Effect.gen(function* () {+ const state = yield* Ref.make(emptyState);+ yield* Effect.gen(function* () {+ const eventSink = yield* EventSink.EventSinkV2;+ const idAllocator = yield* IdAllocator.IdAllocatorV2;+ const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;+ const now = yield* DateTime.now;+ const threadId = ThreadId.make("thread-provider-session-manager-unresponsive-stop");+ const providerSessionId = yield* idAllocator.allocate.providerSession({+ providerInstanceId: modelSelection.instanceId,+ threadId,+ });+ yield* eventSink.write({+ events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],+ });+ const runtime = yield* manager.open({+ threadId,+ providerSessionId,+ modelSelection,+ runtimePolicy,+ });+ const stopping = yield* runtime+ .interruptTurn({+ providerThread: makeProviderThread({ idAllocator, threadId, providerSessionId, now }),+ providerTurnId: idAllocator.derive.providerTurn({+ driver: CODEX_DRIVER,+ nativeTurnId: "native-turn-unresponsive",+ }),+ })+ .pipe(Effect.flip, Effect.forkChild);+ yield* TestClock.adjust(ProviderSessionManager.PROVIDER_INTERRUPT_TIMEOUT_MS);+ assert.equal((yield* Fiber.join(stopping))._tag, "ProviderAdapterInterruptTimeoutError");+ }).pipe(+ Effect.provide(layerTest({ state, idleTimeoutMs: 60_000, interruptTurn: Effect.never })),+ );+ }),+);++it.effect(+ "ProviderSessionManagerV2 keeps a shared session a sibling is busy on when releasing",+ () =>+ Effect.gen(function* () {+ const state = yield* Ref.make(emptyState);+ yield* Effect.gen(function* () {+ const eventSink = yield* EventSink.EventSinkV2;+ const idAllocator = yield* IdAllocator.IdAllocatorV2;+ const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;+ const projectionStore = yield* ProjectionStore.ProjectionStoreV2;+ const now = yield* DateTime.now;+ const stopping = ThreadId.make("thread-provider-session-manager-release-stopping");+ const sibling = ThreadId.make("thread-provider-session-manager-release-sibling");+ const providerSessionId = idAllocator.derive.providerSession({+ providerInstanceId: modelSelection.instanceId,+ });+ yield* eventSink.write({+ events: [+ yield* makeThreadCreatedEvent({ idAllocator, threadId: stopping, now }),+ yield* makeThreadCreatedEvent({ idAllocator, threadId: sibling, now }),+ ],+ });+ const runtime = yield* manager.open({+ threadId: stopping,+ providerSessionId,+ modelSelection,+ runtimePolicy,+ });+ yield* manager.open({+ threadId: sibling,+ providerSessionId,+ modelSelection,+ runtimePolicy,+ });+ const providerThreadOf = (threadId: ThreadId) =>+ makeProviderThread({+ idAllocator,+ threadId,+ providerSessionId,+ now,+ nativeThreadId: `native-${threadId}`,+ });+ const runId = idAllocator.derive.run({ threadId: sibling, ordinal: 1 });+ yield* runtime.startTurn({+ appThread: (yield* projectionStore.getThreadProjection(sibling)).thread,+ threadId: sibling,+ runId,+ runOrdinal: 1,+ providerTurnOrdinal: 1,+ attemptId: idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }),+ rootNodeId: idAllocator.derive.rootNode({ runId }),+ providerThread: providerThreadOf(sibling),+ message: {+ createdBy: "user",+ creationSource: "web",+ messageId: yield* idAllocator.allocate.message({ threadId: sibling, ordinal: 1 }),+ text: "turn",+ attachments: [],+ },+ modelSelection,+ runtimePolicy,+ });+ const release = (own: ThreadId) =>+ manager.releaseUnlessBusy({+ providerSessionId,+ ownProviderThreadIds: [providerThreadOf(own).id],+ reason: "manual_shutdown",+ });++ assert.isFalse(yield* release(stopping));+ assert.isTrue(yield* manager.isLive(providerSessionId));+ assert.isTrue(yield* release(sibling));+ assert.isFalse(yield* manager.isLive(providerSessionId));++ // A turn that starts on a runtime released meanwhile fails instead of running on it.+ const startOnReleasedRuntime = Effect.gen(function* () {+ const lateRunId = idAllocator.derive.run({ threadId: stopping, ordinal: 1 });+ return yield* Effect.flip(+ runtime.startTurn({+ appThread: (yield* projectionStore.getThreadProjection(stopping)).thread,+ threadId: stopping,+ runId: lateRunId,+ runOrdinal: 1,+ providerTurnOrdinal: 1,+ attemptId: idAllocator.derive.runAttempt({ runId: lateRunId, attemptOrdinal: 1 }),+ rootNodeId: idAllocator.derive.rootNode({ runId: lateRunId }),+ providerThread: providerThreadOf(stopping),+ message: {+ createdBy: "user",+ creationSource: "web",+ messageId: yield* idAllocator.allocate.message({ threadId: stopping, ordinal: 1 }),+ text: "turn",+ attachments: [],+ },+ modelSelection,+ runtimePolicy,+ }),+ );+ });+ assert.equal((yield* startOnReleasedRuntime)._tag, "ProviderAdapterTurnStartError");++ // Nor may it leave its turn busy on a replacement opened under the same id.+ yield* manager.open({+ threadId: sibling,+ providerSessionId,+ modelSelection,+ runtimePolicy,+ });+ assert.equal((yield* startOnReleasedRuntime)._tag, "ProviderAdapterTurnStartError");+ assert.isTrue(yield* release(sibling));+ }).pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 60 * 60_000 })));+ }),+);+it.effect("ProviderSessionManagerV2 stops a session still opening when its layer shuts down", () =>Effect.gen(function* () {const state = yield* Ref.make(emptyState);diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.tsindex b9887a48446..03a7278774a 100644--- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts+++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts@@ -57,11 +57,19 @@ import * as ProjectionStore from "./ProjectionStore.ts";const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000;const DEFAULT_MAX_IDLE_PIN_MS = 4 * 60 * 60 * 1000;const RELEASE_SCOPE_CLOSE_TIMEOUT_MS = 30 * 1000;+/** Past adapters' own 10 s stop fallbacks, so they settle first when the provider answers at all. */+export const PROVIDER_INTERRUPT_TIMEOUT_MS = 15 * 1000;const busyTurnPrefix = (providerThreadId: ProviderThreadId) => `${providerThreadId}#`;const busyTurnKey = (providerThreadId: ProviderThreadId, runOrdinal: number) =>`${busyTurnPrefix(providerThreadId)}${runOrdinal}`;const UNLOAD_THREAD_TIMEOUT_MS = 10 * 1000;+const WORKING_RUN_STATUSES: ReadonlySet<string> = new Set([+ "preparing",+ "starting",+ "running",+ "waiting",+]);export const ProviderSessionReleaseReason = Schema.Literals(["idle_timeout",@@ -181,6 +189,25 @@ export interface ProviderSessionManagerV2Shape {readonly detail?: string;readonly revokeMcpCredential?: boolean;}) => Effect.Effect<void, ProviderSessionManagerV2Error>;+ /**+ * Releases the session unless, at the moment of removal, a turn of a provider thread outside+ * `ownProviderThreadIds` is busy on it. Checked atomically with turn starts. Succeeds with+ * whether it was released.+ */+ readonly releaseUnlessBusy: (input: {+ readonly providerSessionId: ProviderSessionId;+ readonly ownProviderThreadIds: ReadonlyArray<ProviderThreadId>;+ readonly reason: ProviderSessionReleaseReason;+ readonly detail?: string;+ }) => Effect.Effect<boolean, ProviderSessionManagerV2Error>;+ /**+ * Other threads with a run or background work on this session's shared process; empty when+ * it serves one thread.+ */+ readonly otherWorkingThreads: (input: {+ readonly providerSessionId: ProviderSessionId;+ readonly threadId: ThreadId;+ }) => Effect.Effect<ReadonlyArray<ThreadId>>;}export class ProviderSessionManagerV2 extends Context.Service<@@ -895,6 +922,7 @@ export const layerWithOptions = (function* (input: {readonly providerSessionId: ProviderSessionId;readonly onlyIfIdleGeneration?: number;+ readonly keepIfBusyOtherThan?: ReadonlyArray<ProviderThreadId>;}): Effect.fn.Return<readonly [Option.Option<LiveSessionEntry>, DateTime.Utc]> {const key = sessionKey(input.providerSessionId);const candidate = (yield* Ref.get(sessions)).get(key);@@ -914,6 +942,15 @@ export const layerWithOptions = () {return ["kept", current] as const;}+ const own = input.keepIfBusyOtherThan;+ if (+ own !== undefined &&+ [...existing.busyTurns].some(+ (turnKey) => !own.some((id) => turnKey.startsWith(busyTurnPrefix(id))),+ )+ ) {+ return ["kept", current] as const;+ }const updated = new Map(current);updated.delete(key);return ["removed", updated] as const;@@ -972,6 +1009,7 @@ export const layerWithOptions = (readonly detachedThreadId?: ThreadId;readonly cancelIdleFiber?: boolean;readonly onlyIfIdleGeneration?: number;+ readonly keepIfBusyOtherThan?: ReadonlyArray<ProviderThreadId>;readonly gracefulSubscribers?: boolean;}) =>Effect.acquireUseRelease(@@ -1380,15 +1418,21 @@ export const layerWithOptions = (.pipe(Effect.ensuring(Effect.sync(dropReservation)));});- const markBusy = (providerSessionId: ProviderSessionId, turnKey: string) =>+ // Marks only the entry this runtime belongs to: a released or replaced session must not+ // gain a busy turn that never ends. Succeeds with whether the turn was marked.+ const markBusy = (+ providerSessionId: ProviderSessionId,+ turnKey: string,+ runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime,+ ) =>withActivityError(providerSessionId,Effect.gen(function* () {const key = sessionKey(providerSessionId);- const idleFiber = yield* Ref.modify(sessions, (current) => {+ const marked = yield* Ref.modify(sessions, (current) => {const entry = current.get(key);- if (entry === undefined) {- return [null, current] as const;+ if (entry === undefined || entry.runtime !== runtime) {+ return [undefined, current] as const;}const updated = new Map(current);updated.set(key, {@@ -1397,9 +1441,11 @@ export const layerWithOptions = (idleFiber: null,pinnedSinceMs: null,});- return [entry.idleFiber, updated] as const;+ return [{ idleFiber: entry.idleFiber }, updated] as const;});- yield* cancelIdleFiber(idleFiber);+ if (marked === undefined) return false;+ yield* cancelIdleFiber(marked.idleFiber);+ return true;}),);@@ -1785,11 +1831,31 @@ export const layerWithOptions = (),Effect.andThen(Effect.acquireUseRelease(- observeActivity(+ markBusy(providerSessionId,- markBusy(- providerSessionId,- busyTurnKey(input.providerThread.id, input.runOrdinal),+ busyTurnKey(input.providerThread.id, input.runOrdinal),+ runtime,+ ).pipe(+ Effect.catchCause((cause) =>+ Effect.logWarning("orchestration-v2.driver-session.activity-failed", {+ providerSessionId,+ cause,+ }).pipe(Effect.as(true)),+ ),+ // A release between attach and markBusy leaves nothing to mark: fail the+ // start instead of running it on a runtime being torn down.+ Effect.flatMap((marked) =>+ marked+ ? Effect.void+ : Effect.fail(+ new ProviderAdapter.ProviderAdapterTurnStartError({+ driver: runtime.driver,+ threadId: input.threadId,+ providerThreadId: input.providerThread.id,+ runId: input.runId,+ cause: "The provider session was released while the turn started.",+ }),+ ),),),() =>@@ -1808,9 +1874,26 @@ export const layerWithOptions = (observeActivity(providerSessionId, touchActivity(providerSessionId)).pipe(Effect.andThen(runtime.steerTurn(input).pipe(turnMetrics("steer"))),),+ // A provider starved of memory can stop answering, so no caller may wait on it unbounded.interruptTurn: (input) =>observeActivity(providerSessionId, touchActivity(providerSessionId)).pipe(- Effect.andThen(runtime.interruptTurn(input).pipe(turnMetrics("interrupt"))),+ Effect.andThen(+ runtime.interruptTurn(input).pipe(+ Effect.timeoutOrElse({+ duration: PROVIDER_INTERRUPT_TIMEOUT_MS,+ orElse: () =>+ Effect.fail(+ new ProviderAdapter.ProviderAdapterInterruptTimeoutError({+ driver: runtime.driver,+ providerThreadId: input.providerThread.id,+ providerTurnId: input.providerTurnId,+ timeoutMs: PROVIDER_INTERRUPT_TIMEOUT_MS,+ }),+ ),+ }),+ turnMetrics("interrupt"),+ ),+ ),),respondToRuntimeRequest: (input) =>observeActivity(providerSessionId, touchActivity(providerSessionId)).pipe(@@ -2276,6 +2359,40 @@ export const layerWithOptions = (),),release: releaseEntry,+ releaseUnlessBusy: Effect.fn("ProviderSessionManager.releaseUnlessBusy")(function* (input) {+ const key = sessionKey(input.providerSessionId);+ const before = (yield* Ref.get(sessions)).get(key);+ yield* releaseEntry({+ providerSessionId: input.providerSessionId,+ reason: input.reason,+ ...(input.detail === undefined ? {} : { detail: input.detail }),+ keepIfBusyOtherThan: input.ownProviderThreadIds,+ });+ // Identity, not presence: open can install a replacement under the same id meanwhile.+ return before !== undefined && (yield* Ref.get(sessions)).get(key) !== before;+ }),+ otherWorkingThreads: Effect.fn("ProviderSessionManager.otherWorkingThreads")(+ function* (input) {+ const entry = (yield* Ref.get(sessions)).get(sessionKey(input.providerSessionId));+ if (entry === undefined || !entry.supportsMultipleProviderThreads) return [];+ return yield* Effect.filter(+ [...entry.attachedThreadIds].filter((threadId) => threadId !== input.threadId),+ (threadId) =>+ // Runs, not the shell's activeRunId: the shell omits silent runs such as idle+ // compaction. Background work outlives its run and still needs the process.+ Effect.zipWith(+ projectionStore.getThreadRecords(threadId, ["runs"]),+ projectionStore.getThreadShell(threadId),+ ({ runs }, shell) =>+ runs.some((run) => WORKING_RUN_STATUSES.has(run.status)) ||+ (shell?.pendingBackgroundTasks?.length ?? 0) > 0,+ ).pipe(+ // An unreadable thread may still be working; never kill it unseen.+ Effect.orElseSucceed(() => true),+ ),+ );+ },+ ),detach: Effect.fn("ProviderSessionManager.detach")(function* (input) {const key = sessionKey(input.providerSessionId);diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.tsindex bab115f6e24..65da8b23676 100644--- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts+++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts@@ -284,6 +284,8 @@ it.effect(closeInstance: () => Effect.void,release: () => Effect.void,detach: () => Effect.void,+ otherWorkingThreads: () => Effect.succeed([]),+ releaseUnlessBusy: () => Effect.succeed(true),}),);const layerControl = ProviderTurnControlService.layer.pipe(diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.tsindex e1dbac21bc5..bd225bb4177 100644--- a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts+++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts@@ -38,6 +38,8 @@ export class ProviderTurnControlError extends Schema.TaggedError<ProviderTurnConoperation: Schema.Literals(["interrupt", "restart", "steer"]),providerTurnId: ProviderTurnId,turnCompleted: Schema.optional(Schema.Boolean),+ /** The provider never confirmed the stop; Force stop is the way out. */+ unresponsive: Schema.optional(Schema.Boolean),cause: Schema.optional(Schema.Defect()),},) {}@@ -218,11 +220,26 @@ export const layer: Layer.Layer<});}// Settled turns still reach adapters, which alone know whether background work remains.- yield* session.value.interruptTurn({- providerThread: loaded.providerThread,- providerTurnId: loaded.providerTurn.id,- requestRuntimeRestart: true,- });+ yield* session.value+ .interruptTurn({+ providerThread: loaded.providerThread,+ providerTurnId: loaded.providerTurn.id,+ requestRuntimeRestart: true,+ })+ .pipe(+ Effect.catchTags({+ ProviderAdapterInterruptTimeoutError: (cause) =>+ Effect.fail(+ new ProviderTurnControlError({+ threadId: input.threadId,+ operation: "interrupt",+ providerTurnId: input.providerTurnId,+ unresponsive: true,+ cause,+ }),+ ),+ }),+ );// Use real time; ingestion fibers do not advance TestClock and would leave Stop blocked.yield* Effect.gen(function* () {const deadline = (yield* Clock.currentTimeMillis) + 2_000;diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.tsindex b2daad62681..9285f72d46f 100644--- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts+++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts@@ -27,6 +27,8 @@ import * as Queue from "effect/Queue";import * as Stream from "effect/Stream";import * as TestClock from "effect/testing/TestClock";+import { AgentScope } from "@t3tools/shared/AgentScope";+import * as ServerSettings from "../serverSettings.ts";import * as SqlitePersistence from "../persistence/Sqlite.ts";import * as CommandReceiptStore from "./CommandReceiptStore.ts";@@ -596,3 +598,174 @@ it.effect.each([expect(dispatched).toEqual(settles ? ["thread.settle"] : []);}),);++it.effect.each([+ {+ name: "kills the thread's own agent and ends its turn",+ others: [] as ReadonlyArray<string>,+ killed: true,+ expected: { outcome: "killed", sharedWithThreadIds: [] },+ teardown: ["release"],+ },+ {+ name: "keeps a process another working thread shares and only ends this turn",+ others: ["thread:thread-management:force-stop:other"],+ killed: false,+ expected: {+ outcome: "shared",+ sharedWithThreadIds: ["thread:thread-management:force-stop:other"],+ },+ teardown: ["detach"],+ },+ {+ name: "still settles a finished run's background work in a shared process",+ others: ["thread:thread-management:force-stop:other"],+ killed: false,+ settledRun: true,+ expected: {+ outcome: "shared",+ sharedWithThreadIds: ["thread:thread-management:force-stop:other"],+ },+ teardown: ["detach"],+ },+ {+ name: "detaches when a sibling starts a turn just before the session is released",+ others: [] as ReadonlyArray<string>,+ killed: false,+ siblingBusy: true,+ expected: { outcome: "shared", sharedWithThreadIds: [] },+ teardown: ["release", "detach"],+ },+ {+ name: "reports a teardown that has not finished in time as still releasing",+ others: [] as ReadonlyArray<string>,+ killed: false,+ releaseHangs: true,+ expected: { outcome: "releasing", sharedWithThreadIds: [] },+ teardown: ["release"],+ },+])("Force stop $name", ({ others, killed, expected, teardown, ...row }) =>+ Effect.gen(function* () {+ const threadId = ThreadId.make("thread:thread-management:force-stop");+ const providerSessionId = ProviderSessionId.make("provider-session:force-stop");+ const providerThreadId = ProviderThreadId.make("provider-thread:force-stop");+ const runId = RunId.make("run:thread-management:force-stop");+ const dispatched: Array<OrchestrationV2Command | { readonly type: string }> = [];+ const teardowns: Array<string> = [];+ const tornDown = yield* Deferred.make<void>();+ const layerTest = ThreadManagementService.layer.pipe(+ Layer.provide(+ Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({+ isLive: () => Effect.succeed(true),+ otherWorkingThreads: () => Effect.succeed(others.map((id) => ThreadId.make(id))),+ releaseUnlessBusy: () =>+ Effect.sync(() => teardowns.push("release")).pipe(+ Effect.andThen(+ "releaseHangs" in row ? Effect.never : Effect.succeed(!("siblingBusy" in row)),+ ),+ ),+ detach: () =>+ Effect.sync(() => teardowns.push("detach")).pipe(+ Effect.andThen(Deferred.succeed(tornDown, undefined)),+ Effect.asVoid,+ ),+ }),+ ),+ Layer.provide(+ Layer.mock(Orchestrator.OrchestratorV2)({+ getThreadRecords: () =>+ Effect.succeed({+ thread: { id: threadId, deletedAt: null },+ runs: [+ {+ id: runId,+ ordinal: 1,+ status: "settledRun" in row ? "completed" : "running",+ activeAttemptId: "attempt",+ },+ // A queued follow-up neither supersedes the request nor becomes the target.+ { id: RunId.make("run:queued-follow-up"), ordinal: 2, status: "queued" },+ ],+ providerThreads: [{ id: providerThreadId, appThreadId: threadId, providerSessionId }],+ providerTurns: [+ {+ id: "provider-turn:force-stop",+ providerThreadId,+ runAttemptId: "attempt",+ status: "settledRun" in row ? "completed" : "running",+ },+ ],+ } as unknown as OrchestrationV2ThreadProjection),+ dispatch: (command) =>+ Effect.sync(() => {+ dispatched.push(command);+ return { sequence: 1, storedEvents: [] } as never;+ }),+ }),+ ),+ Layer.provide(+ Layer.succeed(AgentScope, {+ ...AgentScope.defaultValue(),+ kill: () => Effect.succeed(killed),+ }),+ ),+ Layer.provide(ServerSettings.layerTest()),+ Layer.provide(layerReceiptsTest),+ );+ yield* Effect.gen(function* () {+ const service = yield* ThreadManagementService.ThreadManagementService;+ const stopping = yield* service.forceStopThread({ threadId, runId }).pipe(Effect.forkChild);+ yield* TestClock.adjust("10 seconds");+ expect(yield* Fiber.join(stopping)).toEqual(expected);+ expect(dispatched).toMatchObject([+ {+ type: "thread.background-work.settle",+ providerThreadId,+ reason: "Force stopped by user",+ },+ ]);+ if (teardown.at(-1) === "detach") yield* Deferred.await(tornDown);+ expect(teardowns).toEqual(teardown);+ }).pipe(Effect.provide(layerTest));+ }),+);++it.effect("Force stop refuses once a newer run has started, before killing anything", () =>+ Effect.gen(function* () {+ const threadId = ThreadId.make("thread:thread-management:force-stop-superseded");+ let killed = false;+ const layerTest = ThreadManagementService.layer.pipe(+ Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),+ Layer.provide(+ Layer.mock(Orchestrator.OrchestratorV2)({+ getThreadRecords: () =>+ Effect.succeed({+ thread: { id: threadId, deletedAt: null },+ runs: [+ { id: RunId.make("run:stopped"), ordinal: 1, status: "running" },+ { id: RunId.make("run:newer"), ordinal: 2, status: "running" },+ ],+ providerThreads: [],+ providerTurns: [],+ } as unknown as OrchestrationV2ThreadProjection),+ }),+ ),+ Layer.provide(+ Layer.succeed(AgentScope, {+ ...AgentScope.defaultValue(),+ kill: () => Effect.sync(() => (killed = true)),+ }),+ ),+ Layer.provide(ServerSettings.layerTest()),+ Layer.provide(layerReceiptsTest),+ );+ const error = yield* Effect.gen(function* () {+ const service = yield* ThreadManagementService.ThreadManagementService;+ return yield* Effect.flip(+ service.forceStopThread({ threadId, runId: RunId.make("run:stopped") }),+ );+ }).pipe(Effect.provide(layerTest));+ expect(error.reason).toBe("superseded");+ expect(killed).toBe(false);+ }),+);diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.tsindex 7b79b21e881..192ed4007fc 100644--- a/apps/server/src/orchestration-v2/ThreadManagementService.ts+++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts@@ -14,6 +14,9 @@ import {MessageId,OrchestrationV2StopWorkflowError,type OrchestrationV2StopWorkflowInput,+ OrchestrationV2ForceStopThreadError,+ type OrchestrationV2ForceStopThreadInput,+ type OrchestrationV2ForceStopThreadResult,type ModelSelection,type OrchestrationV2Actor,type OrchestrationV2Command,@@ -30,6 +33,7 @@ import {ProjectId,PROVIDER_SEND_TURN_MAX_FILE_BYTES,ProviderInstanceId,+ type ProviderSessionId,resolveProjectProviderInstanceEnabled,RunId,type ScheduledTaskId,@@ -38,10 +42,13 @@ import {} from "@t3tools/contracts";import { delegatedTaskProgress } from "@t3tools/provider-core/server/subagentProjection";import { threadTranscriptHeader } from "@t3tools/shared/threadTranscript";+import { AgentScope } from "@t3tools/shared/AgentScope";+import * as Clock from "effect/Clock";import * as Context from "effect/Context";import * as DateTime from "effect/DateTime";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";+import * as Fiber from "effect/Fiber";import * as Layer from "effect/Layer";import * as Option from "effect/Option";import * as Ref from "effect/Ref";@@ -454,6 +461,13 @@ export interface ThreadManagementServiceShape {readonly stopWorkflow: (input: OrchestrationV2StopWorkflowInput,) => Effect.Effect<void, OrchestrationV2StopWorkflowError>;+ /**+ * Kills the thread's agent for a provider that no longer responds, then ends+ * its turn as interrupted. Never kills a process other working threads share.+ */+ readonly forceStopThread: (+ input: OrchestrationV2ForceStopThreadInput,+ ) => Effect.Effect<OrchestrationV2ForceStopThreadResult, OrchestrationV2ForceStopThreadError>;readonly awaitBackgroundTasks: (input: {readonly threadId: ThreadId;readonly taskIds: ReadonlyArray<string>;@@ -547,12 +561,16 @@ function latestSteerableRun(}const SETTLE_AFTER_RUN_WAIT_MS = 24 * 60 * 60 * 1_000;+const FORCE_STOP_REASON = "Force stopped by user";+const FORCE_STOP_RELEASE_WAIT = "10 seconds";+const isForceStopThreadError = Schema.is(OrchestrationV2ForceStopThreadError);const make = Effect.gen(function* () {const threadDispatch = yield* ThreadCommandExecutor.ThreadCommandExecutor;const orchestrator = yield* Orchestrator.OrchestratorV2;const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;const layerScope = yield* Effect.scope;+ const agentScope = yield* AgentScope;const legacyImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;const serverSettings = yield* ServerSettings.ServerSettingsService;const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;@@ -1072,6 +1090,153 @@ const make = Effect.gen(function* () {return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;});+ const forceStopThread: ThreadManagementServiceShape["forceStopThread"] = Effect.fn(+ "ThreadManagementService.forceStopThread",+ )(+ function* (input) {+ // Under the thread lock no new run can be created between the check and the kill. The+ // settlement below dispatches, which takes that lock itself, so it runs after release.+ const { records, target, killed } = yield* threadDispatch.withLock(+ input.threadId,+ Effect.gen(function* () {+ const records = yield* orchestrator.getThreadRecords(input.threadId, [+ "runs",+ "providerThreads",+ "providerTurns",+ ]);+ // The run Force stop acts on: the active one, else the latest that started. Queued+ // follow-ups never ran, so they neither count as targets nor supersede the request.+ const target =+ latestActiveRun(records) ??+ records.runs+ .filter((run) => run.status !== "queued")+ .reduce<OrchestrationV2Run | undefined>(+ (current, run) =>+ current === undefined || run.ordinal > current.ordinal ? run : current,+ undefined,+ );+ if (input.runId !== undefined && input.runId !== target?.id) {+ return yield* new OrchestrationV2ForceStopThreadError({+ threadId: input.threadId,+ reason: "superseded",+ });+ }+ // Shared scopes are never tracked per thread, so this only kills the thread's own agent.+ const killed = yield* agentScope.kill(input.threadId);+ return { records, target, killed };+ }),+ );+ const sessionIds = new Set(+ records.providerThreads.flatMap((providerThread) =>+ providerThread.appThreadId === input.threadId && providerThread.providerSessionId !== null+ ? [providerThread.providerSessionId]+ : [],+ ),+ );+ // A run that already ended may still hold background work; settling it is a no-op otherwise.+ const run = target;+ if (run !== undefined) {+ const active = isActiveRun(run);+ const providerTurn = records.providerTurns.findLast(+ (turn) =>+ turn.runAttemptId === run.activeAttemptId && (!active || turn.status === "running"),+ );+ const commandId = CommandId.make(+ `server:force-stop:${run.id}:${yield* Clock.currentTimeMillis}`,+ );+ yield* providerTurn === undefined && !active+ ? Effect.void+ : providerTurn === undefined+ ? orchestrator.dispatch({+ type: "run.interrupt",+ commandId,+ threadId: input.threadId,+ runId: run.id,+ reason: FORCE_STOP_REASON,+ })+ : orchestrator.dispatch({+ type: "thread.background-work.settle",+ commandId,+ threadId: input.threadId,+ providerThreadId: providerTurn.providerThreadId,+ providerTurnId: providerTurn.id,+ reason: FORCE_STOP_REASON,+ });+ }+ const ownProviderThreadIds = records.providerThreads.flatMap((providerThread) =>+ providerThread.appThreadId === input.threadId ? [providerThread.id] : [],+ );+ const detach = (providerSessionId: ProviderSessionId) =>+ sessions+ .detach({ providerSessionId, threadId: input.threadId, detail: FORCE_STOP_REASON })+ .pipe(+ Effect.catchCause((cause) =>+ Effect.logWarning("orchestration-v2.force-stop-detach-failed", {+ threadId: input.threadId,+ cause,+ }),+ ),+ Effect.forkIn(layerScope),+ );+ let shared = false;+ const sharedWith = new Set<ThreadId>();+ const releases: Array<{+ readonly providerSessionId: ProviderSessionId;+ readonly fiber: Fiber.Fiber<boolean, ProviderSessionManager.ProviderSessionManagerV2Error>;+ }> = [];+ for (const providerSessionId of sessionIds) {+ if (!(yield* sessions.isLive(providerSessionId))) continue;+ // Decided just before teardown, so the reply matches what happens to the process.+ const others = yield* sessions.otherWorkingThreads({+ providerSessionId,+ threadId: input.threadId,+ });+ for (const threadId of others) sharedWith.add(threadId);+ if (others.length > 0) {+ shared = true;+ yield* detach(providerSessionId);+ continue;+ }+ // The session manager re-checks atomically with turn starts and keeps a session a+ // sibling began using in the meantime.+ const fiber = yield* sessions+ .releaseUnlessBusy({+ providerSessionId,+ ownProviderThreadIds,+ reason: "manual_shutdown",+ detail: FORCE_STOP_REASON,+ })+ .pipe(Effect.forkIn(layerScope));+ releases.push({ providerSessionId, fiber });+ }+ // Teardown waits on the provider's own exit paths; past this bound it keeps going on its own.+ let releasing = false;+ for (const release of releases) {+ const released = yield* Fiber.join(release.fiber).pipe(+ Effect.timeoutOption(FORCE_STOP_RELEASE_WAIT),+ );+ if (Option.isNone(released)) {+ releasing = true;+ } else if (!released.value) {+ shared = true;+ yield* detach(release.providerSessionId);+ }+ }+ return {+ outcome: killed ? "killed" : shared ? "shared" : releasing ? "releasing" : "released",+ sharedWithThreadIds: [...sharedWith],+ } as const;+ },+ (effect, input) =>+ effect.pipe(+ Effect.mapError((cause) =>+ isForceStopThreadError(cause)+ ? cause+ : new OrchestrationV2ForceStopThreadError({ threadId: input.threadId, cause }),+ ),+ ),+ );+const stopWorkflow: ThreadManagementServiceShape["stopWorkflow"] = Effect.fn("ThreadManagementService.stopWorkflow",)(@@ -1354,6 +1519,7 @@ const make = Effect.gen(function* () {interruptThread,stopDelegatedTasks,stopWorkflow,+ forceStopThread,awaitBackgroundTasks,getThreadEventSequence: orchestrator.getThreadEventSequence,recoverDelegatedTask: orchestrator.recoverDelegatedTask,diff --git a/apps/server/src/orchestration-v2/ThreadStop.test.ts b/apps/server/src/orchestration-v2/ThreadStop.test.tsindex 23a52f39d33..16dcedaf8ac 100644--- a/apps/server/src/orchestration-v2/ThreadStop.test.ts+++ b/apps/server/src/orchestration-v2/ThreadStop.test.ts@@ -1552,3 +1552,115 @@ it.effect.each(["missing session", "completed", "failed", "cancelled"] as const));}).pipe(Effect.provide(layerTest)),);++it.effect("an unanswered Stop is flagged until Force stop ends the run with its own reason", () =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const projections = yield* ProjectionStore.ProjectionStoreV2;+ const threadId = ThreadId.make("thread:force-stop");+ yield* createWatchingThread(threadId, 6);+ yield* send(threadId, "work", "start_immediately");+ const now = yield* DateTime.now;+ const started = yield* orchestrator.getThreadProjection(threadId);+ const run = started.runs[0]!;+ const providerThreadId = run.providerThreadId!;+ const providerTurnId = ProviderTurnId.make("provider-turn:force-stop");+ const apply = (event: Omit<OrchestrationV2DomainEvent, "id" | "threadId">) =>+ projections.apply({+ ...event,+ id: EventId.make(`event:force-stop:${event.type}`),+ threadId,+ } as OrchestrationV2DomainEvent);+ const attempt = started.attempts[0]!;+ const attemptId = attempt.id;+ yield* apply({+ type: "run.updated",+ runId: run.id,+ occurredAt: now,+ payload: { ...run, status: "running", startedAt: now, activeAttemptId: attemptId },+ });+ yield* apply({+ type: "run-attempt.updated",+ occurredAt: now,+ payload: { ...attempt, status: "running", startedAt: now },+ });+ yield* apply({+ type: "provider-turn.updated",+ occurredAt: now,+ payload: {+ id: providerTurnId,+ providerThreadId,+ nodeId: run.rootNodeId!,+ runAttemptId: attemptId,+ nativeTurnRef: null,+ ordinal: 1,+ status: "running",+ startedAt: now,+ completedAt: null,+ },+ });+ yield* apply({+ type: "turn-item.updated",+ runId: run.id,+ occurredAt: now,+ payload: {+ id: TurnItemId.make("turn-item:force-stop:interrupt-request"),+ threadId,+ runId: run.id,+ nodeId: run.rootNodeId!,+ providerThreadId,+ providerTurnId,+ nativeItemRef: null,+ parentItemId: null,+ ordinal: 1_000,+ status: "completed",+ title: "Interrupt requested",+ startedAt: now,+ completedAt: now,+ updatedAt: now,+ type: "run_interrupt_request",+ message: "Stopped by user",+ },+ });+ const target = { threadId, providerThreadId, providerTurnId };+ const request = Effect.map(orchestrator.getThreadProjection(threadId), (projection) =>+ projection.turnItems.find((item) => item.type === "run_interrupt_request"),+ );++ yield* orchestrator.dispatch({+ ...target,+ type: "thread.interrupt.unresponsive",+ commandId: CommandId.make("force-stop:unresponsive"),+ });+ const flagged = yield* request;+ assert.isTrue(+ flagged?.type === "run_interrupt_request" && flagged.unresponsiveAt !== undefined,+ );+ assert.deepEqual((yield* threadState(threadId)).runs, ["running"]);++ yield* orchestrator.dispatch({+ ...target,+ type: "thread.background-work.settle",+ commandId: CommandId.make("force-stop:settle"),+ reason: "Force stopped by user",+ });+ const settled = yield* orchestrator.getThreadProjection(threadId);+ assert.deepEqual(+ settled.runs.map((candidate) => candidate.status),+ ["interrupted"],+ );+ const result = settled.turnItems.find((item) => item.type === "run_interrupt_result");+ assert.equal(+ result?.type === "run_interrupt_result" ? result.message : undefined,+ "Force stopped by user",+ );++ // A provider confirming late changes nothing once the run has ended.+ const late = yield* orchestrator.dispatch({+ ...target,+ type: "thread.interrupt.unresponsive",+ commandId: CommandId.make("force-stop:late-unresponsive"),+ });+ assert.lengthOf(late.storedEvents, 0);+ }).pipe(Effect.provide(layerTest)),+);diff --git a/apps/server/src/process/agentScope.test.ts b/apps/server/src/process/agentScope.test.tsindex 286452a5c57..2a9998f4cfb 100644--- a/apps/server/src/process/agentScope.test.ts+++ b/apps/server/src/process/agentScope.test.ts@@ -110,6 +110,8 @@ const withFakeSystemd = <A, E>(...fileSystem,readFileString: (path, encoding) =>fileSystem.readFileString(path.replace("/sys/fs/cgroup", cgroupRoot), encoding),+ writeFileString: (path, data, options) =>+ fileSystem.writeFileString(path.replace("/sys/fs/cgroup", cgroupRoot), data, options),}),);const { stateDir } = yield* ServerConfig.ServerConfig;@@ -213,6 +215,36 @@ describe("AgentScope service", () => {),);+ it.effect.each([{ oomPolicy: true }, { oomPolicy: false }])(+ "Force stop kills a thread's own scope but never a shared Codex scope (OOM policy $oomPolicy)",+ ({ oomPolicy }) =>+ withFakeSystemd(+ ({ scope, units, calls, cgroupRoot }) =>+ Effect.gen(function* () {+ const agent = yield* scope.wrap({+ command: "agent",+ args: [],+ name: "t",+ threadId: "a",+ });+ exitedAgent(units, cgroupRoot, unitOf(agent), { populated: true, oomKills: 0 });+ const codex = yield* launchCodex(scope, "b");+ exitedAgent(units, cgroupRoot, unitOf(codex), { populated: true, oomKills: 0 });++ expect(yield* scope.kill("a")).toBe(true);+ expect(+ NodeFS.readFileSync(NodePath.join(cgroupRoot, unitOf(agent), "cgroup.kill"), "utf8"),+ ).toBe("1");+ expect(yield* scope.kill("b")).toBe(false);+ expect(NodeFS.existsSync(NodePath.join(cgroupRoot, unitOf(codex), "cgroup.kill"))).toBe(+ false,+ );+ expect(calls.filter(([, verb]) => verb === "kill")).toEqual([]);+ }),+ { oomPolicy },+ ),+ );+it.effect("keeps a running scope while hundreds of other threads launch", () =>withFakeSystemd(({ scope, units }) =>Effect.gen(function* () {diff --git a/apps/server/src/process/agentScope.ts b/apps/server/src/process/agentScope.tsindex c72e4eed88a..b9b6b56acb1 100644--- a/apps/server/src/process/agentScope.ts+++ b/apps/server/src/process/agentScope.ts@@ -215,7 +215,8 @@ export const make = Effect.gen(function* () {}),);- const scopeByThread = new Map<string, { unit: string; oomKilled: boolean }>();+ // `shared` scopes serve other threads too: tracked only for OOM diagnosis on old systemd.+ const scopeByThread = new Map<string, { unit: string; oomKilled: boolean; shared: boolean }>();const readScope = Effect.fn("agentScope.readScope")(function* (systemctl: string, unit: string) {const shown = yield* run(systemctl, [@@ -277,10 +278,11 @@ export const make = Effect.gen(function* () {systemctl: string,threadId: string,unit: string | undefined,+ shared = false,) {const previous = scopeByThread.get(threadId);scopeByThread.delete(threadId);- if (unit !== undefined) scopeByThread.set(threadId, { unit, oomKilled: false });+ if (unit !== undefined) scopeByThread.set(threadId, { unit, oomKilled: false, shared });if (previous !== undefined) yield* forget(systemctl, previous.unit);if (scopeByThread.size > MAX_TRACKED_THREADS) yield* evictOldest(systemctl);});@@ -340,6 +342,40 @@ export const make = Effect.gen(function* () {}});+ const kill: AgentScopeShape["kill"] = Effect.fn("AgentScope.kill")(function* (threadId) {+ const tracked = scopeByThread.get(threadId);+ if (tracked === undefined || tracked.shared) return false;+ const scope = yield* systemd;+ if (scope === undefined) return false;+ const shown = yield* run(scope.systemctl, [+ "--user",+ "show",+ tracked.unit,+ "--property=ActiveState,ControlGroup",+ ]);+ if (shown._tag === "None" || shown.value.code !== 0) return false;+ const values = parseKeyValues(shown.value.stdout);+ if (values.get("ActiveState") !== "active") return false;+ const controlGroup = values.get("ControlGroup") ?? "";+ // cgroup.kill (Linux 5.14+) kills the whole tree at once; systemd's kill is the fallback.+ const killedByCgroup =+ controlGroup.length > 0 &&+ (yield* fileSystem+ .writeFileString(path.join("/sys/fs/cgroup", controlGroup, "cgroup.kill"), "1")+ .pipe(+ Effect.as(true),+ Effect.orElseSucceed(() => false),+ ));+ if (killedByCgroup) return true;+ const killed = yield* run(scope.systemctl, [+ "--user",+ "kill",+ "--signal=SIGKILL",+ tracked.unit,+ ]);+ return killed._tag === "Some" && killed.value.code === 0;+ });+const clear: AgentScopeShape["clear"] = Effect.fn("agentScope.clear")(function* (threadId) {if (!scopeByThread.has(threadId)) return;const scope = yield* systemd;@@ -365,7 +401,8 @@ export const make = Effect.gen(function* () {// Clear the launch thread's previous scope instead.const continuing = shared === true && scope.supportsOomPolicy;const owned = threadId !== undefined && !continuing;- if (threadId !== undefined) yield* track(scope.systemctl, threadId, owned ? unit : undefined);+ if (threadId !== undefined)+ yield* track(scope.systemctl, threadId, owned ? unit : undefined, shared === true);const systemdScope: AgentSystemdScope = {systemdRun: scope.systemdRun,runtimeDir: scope.runtimeDir,@@ -385,6 +422,7 @@ export const make = Effect.gen(function* () {}),oomKilled,stop,+ kill,clear,} satisfies AgentScopeShape;});diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.tsindex 48c4a5c240e..40c741fdd68 100644--- a/apps/server/src/relay/AgentAwarenessRelay.test.ts+++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts@@ -219,6 +219,7 @@ const makeTestRelay = Effect.fnUntraced(function* (settleThread: unused,interruptThread: unused,stopWorkflow: () => Effect.die("unused stopWorkflow"),+ forceStopThread: () => Effect.die("unused forceStopThread"),awaitBackgroundTasks: unused,stopDelegatedTasks: unused,getThreadEventSequence: unused,diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex a7ef5dedf24..622279d16a4 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -1914,6 +1914,8 @@ export const layerWsRpc = (),),[ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: (input) => threadManagement.stopWorkflow(input),+ [ORCHESTRATION_V2_WS_METHODS.forceStopThread]: (input) =>+ threadManagement.forceStopThread(input),[ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: (input) =>readWorkflowScript({ scriptPath: input.scriptPath }),[ORCHESTRATION_V2_WS_METHODS.getTurnItem]: (input) =>diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 1bf6f9b0fc0..fa3e7e23dae 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -2349,7 +2349,8 @@ export default function ChatView(props: ChatViewProps) {const {acknowledgeActiveThreadWoke,activeBranchMismatchKey,- backgroundWorkNow,+ attentionNow,+ workNow,childInputNow,goalNow,handleSwitchCheckoutToThread,@@ -2993,10 +2994,7 @@ export default function ChatView(props: ChatViewProps) {const onExpandTimelineImageStable = useStableCallback(onExpandTimelineImage);const shownThreadSyncPhase = activeEnvironmentUnavailable ? null : delayedThreadSyncPhase;const hasThreadNow =- childInputNow !== null ||- backgroundWorkNow !== null ||- goalNow !== null ||- shownThreadSyncPhase !== null;+ attentionNow !== null || workNow !== null || goalNow !== null || shownThreadSyncPhase !== null;const queuedRunCount = serverProjection ? getUserQueuedThreadRuns(serverProjection).length : 0;// The queue control is mounted for every server thread but joins the footer only while it shows// something, by its own rule: an optimistic message stops counting once the server has it.@@ -3035,8 +3033,8 @@ export default function ChatView(props: ChatViewProps) {)}<ThreadNowkey={routeThreadKey}- attention={childInputNow}- work={backgroundWorkNow}+ attention={attentionNow}+ work={workNow}syncPhase={shownThreadSyncPhase}goal={goalNow}/>diff --git a/apps/web/src/components/chat/ThreadActivityBanners.tsx b/apps/web/src/components/chat/ThreadActivityBanners.tsxindex 168b674d26c..8bd26e21a04 100644--- a/apps/web/src/components/chat/ThreadActivityBanners.tsx+++ b/apps/web/src/components/chat/ThreadActivityBanners.tsx@@ -7,17 +7,20 @@ import type { EnvironmentThreadShell, ThreadStructure } from "@t3tools/client-ruimport {presentPendingBackgroundWork,presentProviderGoal,+ type RunStopPresentation,} from "@t3tools/client-runtime/state/thread-execution";import { childThreadInputsTitle } from "@t3tools/client-runtime/state/threads";import { formatDuration } from "@t3tools/shared/orchestrationTiming";import * as DateTime from "effect/DateTime";import {CircleDashedIcon,+ CircleStopIcon,GitBranchIcon,MessageCircleIcon,ShieldQuestionIcon,TargetIcon,TerminalIcon,+ TriangleAlertIcon,} from "lucide-react";import { Fragment } from "react";import { tickTextContent } from "~/lib/tickTextContent";@@ -105,6 +108,46 @@ export function goalNowItem(input: {};}+/** A Stop the provider has not finished; Force stop once it stops answering. */+export function runStopNowItem(input: {+ readonly threadId: ThreadId;+ readonly stop: RunStopPresentation;+ readonly canForceStop: boolean;+ readonly forceStopping: boolean;+ readonly onForceStop: () => void;+}): ThreadNowItem {+ const unresponsive = input.stop.state === "unresponsive";+ const requestedAtMs = Date.parse(input.stop.requestedAt);+ return {+ id: `run-stop:${input.threadId}`,+ icon: unresponsive ? (+ <TriangleAlertIcon className="text-warning-foreground" />+ ) : (+ <CircleStopIcon />+ ),+ title: unresponsive ? "Agent not responding to Stop" : "Stopping",+ description: unresponsive+ ? "It may be short on memory. Force stop kills its processes."+ : undefined,+ actions: (+ <>+ <span+ ref={tickTextContent(+ (nowMs) => formatDuration(Math.max(1_000, nowMs - requestedAtMs)),+ true,+ )}+ className="tabular-nums"+ />+ {unresponsive && input.canForceStop ? (+ <InlineButton disabled={input.forceStopping} onClick={input.onForceStop}>+ {input.forceStopping ? "Force stopping..." : "Force stop"}+ </InlineButton>+ ) : null}+ </>+ ),+ };+}+/** Background commands and subagents, for the end of the timeline. */export function backgroundWorkNowItem(input: {readonly threadId: ThreadId;diff --git a/apps/web/src/components/chat/useForceStopThread.ts b/apps/web/src/components/chat/useForceStopThread.tsnew file mode 100644index 00000000000..00876c758a8--- /dev/null+++ b/apps/web/src/components/chat/useForceStopThread.ts@@ -0,0 +1,59 @@+import { useAtomValue } from "@effect/atom-react";+import type { EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";+import { useState } from "react";++import { useServerConfigs } from "../../state/entities";+import { orchestrationEnvironment } from "../../state/orchestration";+import {+ isAtomCommandInterrupted,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";+import { useAtomCommand } from "../../state/use-atom-command";+import { toastManager } from "../ui/toast";++/** Force stop for an agent that no longer answers Stop; shared by every place that offers it. */+export function useForceStopThread(environmentId: EnvironmentId) {+ const forceStop = useAtomCommand(orchestrationEnvironment.forceStopThread);+ const permitted = useAtomValue(+ orchestrationEnvironment.forceStopThread.permissionAtom(environmentId),+ );+ const supported =+ useServerConfigs().get(environmentId)?.environment.capabilities.threadForceStop === true;+ const canForceStop = permitted && supported;+ const [stoppingThreadId, setStoppingThreadId] = useState<ThreadId | null>(null);+ /** Pass the run that ignored Stop, so a Force stop left open cannot hit a newer run. */+ const forceStopThread = async (threadId: ThreadId, runId?: RunId) => {+ if (!canForceStop || stoppingThreadId !== null) return;+ setStoppingThreadId(threadId);+ const result = await forceStop({+ environmentId,+ input: runId === undefined ? { threadId } : { threadId, runId },+ });+ setStoppingThreadId(null);+ if (result._tag === "Failure") {+ if (isAtomCommandInterrupted(result)) return;+ const error = squashAtomCommandFailure(result);+ toastManager.add({+ type: "error",+ title: "Could not force stop the agent",+ description: error instanceof Error ? error.message : undefined,+ });+ return;+ }+ const others = result.value.sharedWithThreadIds.length;+ if (result.value.outcome === "releasing") {+ toastManager.add({+ type: "info",+ title: "Turn stopped; the agent is still shutting down",+ });+ }+ if (result.value.outcome === "shared") {+ toastManager.add({+ type: "info",+ title: "Turn stopped; the agent process kept running",+ description: `It is shared with ${others === 0 ? "other" : others} working ${others === 1 ? "thread" : "threads"}. Stop those to free it.`,+ });+ }+ };+ return { canForceStop, stoppingThreadId, forceStopThread };+}diff --git a/apps/web/src/components/chat/useThreadLifecycle.tsx b/apps/web/src/components/chat/useThreadLifecycle.tsxindex b1cf8a4a6af..0ad8acacf71 100644--- a/apps/web/src/components/chat/useThreadLifecycle.tsx+++ b/apps/web/src/components/chat/useThreadLifecycle.tsx@@ -58,9 +58,22 @@ import { appAtomRegistry } from "../../rpc/atomRegistry";import { readEnvironmentScope } from "../../state/session";import { useAtomCommand } from "../../state/use-atom-command";import { useOrchestrationCommand } from "../../state/use-orchestration-command";-import { backgroundWorkNowItem, childInputNowItem, goalNowItem } from "./ThreadActivityBanners";+import {+ backgroundWorkNowItem,+ childInputNowItem,+ goalNowItem,+ runStopNowItem,+} from "./ThreadActivityBanners";+import { useForceStopThread } from "./useForceStopThread";+import { useAtomValue } from "@effect/atom-react";+import type { RunStopPresentation } from "@t3tools/client-runtime/state/thread-execution";+import { Atom } from "effect/reactivity";+import { environmentThreadDetails } from "../../state/threads";import type { useLocalDispatchState } from "./useLocalDispatchState";const RELATED_THREAD_SHELL_WAIT_MS = 1_000;+const NO_RUN_STOP_ATOM = Atom.make<RunStopPresentation | null>(null).pipe(+ Atom.withLabel("web-thread-run-stop:empty"),+);type PendingThreadRequests = ReturnType<typeof usePendingThreadRequests>;type LocalDispatchState = ReturnType<typeof useLocalDispatchState>;@@ -509,6 +522,22 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {}): null;+ const forceStop = useForceStopThread(environmentId);+ const anyRunStop = useAtomValue(+ activeThreadRef ? environmentThreadDetails.runStopAtom(activeThreadRef) : NO_RUN_STOP_ATOM,+ );+ // A background Stop matters only while that work is still pending.+ const runStop = anyRunStop?.background && activeBackgroundTasks.length === 0 ? null : anyRunStop;+ const runStopNow =+ activeThread && runStop !== null+ ? runStopNowItem({+ threadId: activeThread.id,+ stop: runStop,+ canForceStop: forceStop.canForceStop,+ forceStopping: forceStop.stoppingThreadId === activeThread.id,+ onForceStop: () => void forceStop.forceStopThread(activeThread.id, runStop.runId),+ })+ : null;const backgroundWorkNow = activeThread? backgroundWorkNowItem({threadId: activeThread.id,@@ -592,7 +621,9 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {shortcuts,acknowledgeActiveThreadWoke,activeBranchMismatchKey,- backgroundWorkNow,+ // A Stop that went unanswered needs the user; one in progress is the thread's work.+ attentionNow: runStop?.state === "unresponsive" ? runStopNow : childInputNow,+ workNow: runStop?.state === "stopping" ? runStopNow : backgroundWorkNow,childInputNow,goalNow,handleSwitchCheckoutToThread,diff --git a/packages/client-runtime/src/state/orchestration.ts b/packages/client-runtime/src/state/orchestration.tsindex 4e6d3022b48..5f5c2ce3020 100644--- a/packages/client-runtime/src/state/orchestration.ts+++ b/packages/client-runtime/src/state/orchestration.ts@@ -107,6 +107,10 @@ export function createOrchestrationEnvironmentAtoms<R, E>(label: "environment-data:orchestration:stop-workflow",tag: ORCHESTRATION_V2_WS_METHODS.stopWorkflow,}),+ forceStopThread: createEnvironmentRpcCommand(runtime, {+ label: "environment-data:orchestration:force-stop-thread",+ tag: ORCHESTRATION_V2_WS_METHODS.forceStopThread,+ }),turnItem: createEnvironmentRpcQueryAtomFamily(runtime, {label: "environment-data:orchestration:turn-item",tag: ORCHESTRATION_V2_WS_METHODS.getTurnItem,diff --git a/packages/client-runtime/src/state/threadDetail.ts b/packages/client-runtime/src/state/threadDetail.tsindex e1f30998cae..3819c5d92ba 100644--- a/packages/client-runtime/src/state/threadDetail.ts+++ b/packages/client-runtime/src/state/threadDetail.ts@@ -14,6 +14,7 @@ import {type ThreadQueueWorkflowState,} from "./threadWorkflows.ts";import { deriveThreadTurnSubagents, type ThreadTurnSubagents } from "./threadSubagents.ts";+import { presentRunStop, type RunStopPresentation } from "./threadExecution.ts";import {deriveThreadCheckpointSummaries,type ThreadCheckpointSummary,@@ -294,6 +295,32 @@ export function createEnvironmentThreadDetailAtoms<E>(return value;}).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-queue:${key}`));});+ const runStopAtomFamily = Atom.family((key: string) => {+ let previous: Pick<OrchestrationV2ThreadProjection, "runs" | "turnItems"> | null = null;+ let stop: RunStopPresentation | null = null;+ return Atom.make((get) => {+ const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);+ if (projection === null) {+ previous = null;+ stop = null;+ } else if (+ projection.runs !== previous?.runs ||+ projection.turnItems !== previous?.turnItems+ ) {+ const { runs, turnItems } = projection;+ previous = { runs, turnItems };+ const next = presentRunStop(previous);+ if (+ next?.state !== stop?.state ||+ next?.runId !== stop?.runId ||+ next?.requestedAt !== stop?.requestedAt ||+ next?.background !== stop?.background+ )+ stop = next;+ }+ return stop;+ }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-run-stop:${key}`));+ });const queuedCountAtomFamily = Atom.family((key: string) => {let previous: Pick<OrchestrationV2ThreadProjection, "runs" | "messages"> | null = null;let count = 0;@@ -435,6 +462,7 @@ export function createEnvironmentThreadDetailAtoms<E>(pendingRequestsAtom: (ref: ScopedThreadRef) => pendingRequestsAtomFamily(threadKey(ref)),queueWorkflowAtom: (ref: ScopedThreadRef) => queueWorkflowAtomFamily(threadKey(ref)),queuedCountAtom: (ref: ScopedThreadRef) => queuedCountAtomFamily(threadKey(ref)),+ runStopAtom: (ref: ScopedThreadRef) => runStopAtomFamily(threadKey(ref)),turnSubagentsAtom: (ref: ScopedThreadRef) => turnSubagentsAtomFamily(threadKey(ref)),checkpointSummariesAtom: (ref: ScopedThreadRef) =>checkpointSummariesAtomFamily(threadKey(ref)),diff --git a/packages/client-runtime/src/state/threadExecution.test.ts b/packages/client-runtime/src/state/threadExecution.test.tsindex 8ef37f959cd..3f8ef2a7f9d 100644--- a/packages/client-runtime/src/state/threadExecution.test.ts+++ b/packages/client-runtime/src/state/threadExecution.test.ts@@ -25,6 +25,7 @@ import {deriveRunlessWorkStartedAt,deriveThreadActivityRun,deriveThreadRuntime,+ presentRunStop,threadRuntimeHasInterruptibleRun,} from "./threadExecution.ts";@@ -259,6 +260,74 @@ describe("thread execution presentation", () => {});});+describe("presentRunStop", () => {+ const signal = (type: "run_interrupt_request" | "run_interrupt_result", runId: RunId) => ({+ id: TurnItemId.make(`${type}:${runId}`),+ threadId: v2Projection.thread.id,+ runId,+ nodeId: null,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal: 1,+ status: type === "run_interrupt_result" ? ("interrupted" as const) : ("completed" as const),+ title: "Interrupt",+ startedAt: now,+ completedAt: now,+ updatedAt: now,+ type,+ message: "Stopped by user",+ });+ const running = run("run-stopping", 1, "running");+ const request = signal("run_interrupt_request", running.id);++ it.each([+ { name: "no Stop", runs: [running], turnItems: [], state: null },+ {+ name: "a Stop the agent is winding down",+ runs: [running],+ turnItems: [request],+ state: "stopping",+ },+ {+ name: "a Stop the provider never confirmed",+ runs: [running],+ turnItems: [{ ...request, unresponsiveAt: now }],+ state: "unresponsive",+ },+ {+ name: "a Stop that ended the run",+ runs: [running],+ turnItems: [request, signal("run_interrupt_result", running.id)],+ state: null,+ },+ {+ name: "a settled run's background work still stopping",+ runs: [{ ...running, status: "completed" as const, completedAt: now }],+ turnItems: [request],+ state: null,+ },+ {+ name: "a settled run whose background work ignored Stop",+ runs: [{ ...running, status: "completed" as const, completedAt: now }],+ turnItems: [{ ...request, unresponsiveAt: now }],+ state: "unresponsive",+ },+ {+ name: "a settled run whose background work ignored Stop, with a queued follow-up",+ runs: [+ { ...running, status: "completed" as const, completedAt: now },+ run("run-queued", 2, "queued"),+ ],+ turnItems: [{ ...request, unresponsiveAt: now }],+ state: "unresponsive",+ },+ ])("presents $name", ({ runs, turnItems, state }) => {+ expect(presentRunStop({ runs, turnItems })?.state ?? null).toBe(state);+ });+});+describe("deriveRunlessWorkStartedAt", () => {const later = DateTime.makeUnsafe("2026-07-28T10:05:00.000Z");const rootTurn = (diff --git a/packages/client-runtime/src/state/threadExecution.ts b/packages/client-runtime/src/state/threadExecution.tsindex ba87930bebb..52d07babfbb 100644--- a/packages/client-runtime/src/state/threadExecution.ts+++ b/packages/client-runtime/src/state/threadExecution.ts@@ -294,6 +294,55 @@ const BACKGROUND_WORK_KINDS: Record<background_task: { order: 3, singular: "background task", plural: "background tasks" },};+export interface RunStopPresentation {+ /** `unresponsive`: the provider did not confirm the stop in time, so Force stop is offered. */+ readonly state: "stopping" | "unresponsive";+ readonly runId: ThreadStructure["runs"][number]["id"];+ readonly requestedAt: string;+ /** The run already ended; the Stop targeted its background work. */+ readonly background: boolean;+}++/**+ * A Stop the provider has not finished yet. It stays `stopping` while the agent winds down,+ * since some providers confirm the request before the turn actually ends. On a run that+ * already ended, only an unanswered Stop of its background work counts.+ */+export function presentRunStop(+ projection: Pick<ThreadStructure, "runs" | "turnItems">,+): RunStopPresentation | null {+ let active: ThreadStructure["runs"][number] | null = null;+ let latest: ThreadStructure["runs"][number] | null = null;+ for (const candidate of projection.runs) {+ // Queued follow-ups never ran, so they hold no Stop of their own.+ if (candidate.status !== "queued" && candidate.ordinal > (latest?.ordinal ?? -1))+ latest = candidate;+ if (+ INTERRUPTIBLE_RUN_STATUSES.has(candidate.status) &&+ candidate.ordinal > (active?.ordinal ?? -1)+ )+ active = candidate;+ }+ const run = active ?? latest;+ if (run === null) return null;+ let request:+ | Extract<ThreadStructure["turnItems"][number], { type: "run_interrupt_request" }>+ | undefined;+ for (const item of projection.turnItems) {+ if (item.runId !== run.id) continue;+ if (item.type === "run_interrupt_result") return null;+ if (item.type === "run_interrupt_request") request = item;+ }+ if (request === undefined || (active === null && request.unresponsiveAt === undefined))+ return null;+ return {+ state: request.unresponsiveAt === undefined ? "stopping" : "unresponsive",+ runId: run.id,+ requestedAt: DateTime.formatIso(request.startedAt ?? request.updatedAt),+ background: active === null,+ };+}+export interface PendingBackgroundWorkItem {readonly taskId: string;readonly kind: BackgroundWorkKind;diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.tsindex f9564b2e244..d3139f2eeff 100644--- a/packages/contracts/src/clientRpcPermissions.ts+++ b/packages/contracts/src/clientRpcPermissions.ts@@ -60,6 +60,8 @@ export const CLIENT_GUARDED_RPC_SCOPES = {[WS_METHODS.scheduledTasksRunNow]: AuthOrchestrationOperateScope,[WS_METHODS.scheduledTasksRotateWebhookToken]: AuthOrchestrationOperateScope,[ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: AuthOrchestrationOperateScope,+ // Force stop kills agent processes, as Stop on a terminal does.+ [ORCHESTRATION_V2_WS_METHODS.forceStopThread]: AuthOrchestrationOperateScope,// A guest link hands thread access to someone outside, like a pairing link.[WS_METHODS.guestShareCreate]: AuthAccessWriteScope,[WS_METHODS.peerLinksLink]: AuthAccessWriteScope,diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.tsindex 75a546bed87..a10c6c2a6bc 100644--- a/packages/contracts/src/environment.ts+++ b/packages/contracts/src/environment.ts@@ -99,6 +99,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({/** Hide the switch when absent; older servers silently drop per-project provider patches. */projectProviderInstanceOverrides: Schema.optionalKey(Schema.Boolean),threadSnooze: Schema.optionalKey(Schema.Boolean),+ /** Serves `orchestration.forceStopThread`; hide Force stop where it is absent. */+ threadForceStop: Schema.optionalKey(Schema.Boolean),/** Every protocol-2 server sends this; older mobile builds still read it. */environmentThemes: Schema.optionalKey(Schema.Boolean),usageLimitSources: Schema.optionalKey(Schema.Boolean),diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.tsindex 026e7483123..d20da578025 100644--- a/packages/contracts/src/orchestrationV2.ts+++ b/packages/contracts/src/orchestrationV2.ts@@ -1676,6 +1676,8 @@ export const OrchestrationV2TurnItem = Schema.Union([...OrchestrationV2TurnItemBaseFields,type: Schema.Literal("run_interrupt_request"),message: Schema.String,+ /** Set when the provider did not confirm the stop in time; clients then offer Force stop. */+ unresponsiveAt: Schema.optionalKey(Schema.DateTimeUtc),}),Schema.Struct({...OrchestrationV2TurnItemBaseFields,@@ -2500,6 +2502,7 @@ export const OrchestrationV2TurnItemJson = Schema.Union([...OrchestrationV2TurnItemJsonBaseFields,type: Schema.Literal("run_interrupt_request"),message: Schema.String,+ unresponsiveAt: Schema.optionalKey(Schema.DateTimeUtcFromString),}),Schema.Struct({...OrchestrationV2TurnItemJsonBaseFields,@@ -3436,12 +3439,22 @@ const OrchestrationV2InternalCommand = Schema.Union([threadId: ThreadId,requestId: RuntimeRequestId,}),+ /** The provider did not confirm a Stop of this turn in time. */+ Schema.Struct({+ type: Schema.Literal("thread.interrupt.unresponsive"),+ commandId: CommandId,+ threadId: ThreadId,+ providerThreadId: ProviderThreadId,+ providerTurnId: ProviderTurnId,+ }),Schema.Struct({type: Schema.Literal("thread.background-work.settle"),commandId: CommandId,threadId: ThreadId,providerThreadId: ProviderThreadId,providerTurnId: ProviderTurnId,+ /** Replaces the Stop's own reason on the result, as Force stop does. */+ reason: Schema.optional(Schema.String),subagent: Schema.optional(Schema.Struct({id: NodeId,@@ -3521,6 +3534,7 @@ export const ORCHESTRATION_V2_WS_METHODS = {getThreadProjection: "orchestration.getThreadProjection",getWorkflowScript: "orchestration.getWorkflowScript",stopWorkflow: "orchestration.stopWorkflow",+ forceStopThread: "orchestration.forceStopThread",getTurnItem: "orchestration.getTurnItem",launchThread: "orchestration.launchThread",subscribeShell: "orchestration.subscribeShell",@@ -3908,6 +3922,41 @@ export class OrchestrationV2StopWorkflowError extends Schema.TaggedError<Orchest}}+export const OrchestrationV2ForceStopThreadInput = Schema.Struct({+ threadId: ThreadId,+ /** The run the user saw ignore Stop; Force stop refuses once a newer run has started. */+ runId: Schema.optionalKey(RunId),+});+export type OrchestrationV2ForceStopThreadInput = typeof OrchestrationV2ForceStopThreadInput.Type;++export const OrchestrationV2ForceStopThreadResult = Schema.Struct({+ /**+ * `killed`: the thread's own agent processes were killed. `released`: its provider session+ * was torn down, which kills the agent's process group. `releasing`: that teardown has not+ * finished yet and continues on the server. `shared`: the agent process also works for+ * `sharedWithThreadIds`, so only this thread's turn was ended.+ */+ outcome: Schema.Literals(["killed", "released", "releasing", "shared"]),+ sharedWithThreadIds: Schema.Array(ThreadId),+});+export type OrchestrationV2ForceStopThreadResult = typeof OrchestrationV2ForceStopThreadResult.Type;++export class OrchestrationV2ForceStopThreadError extends Schema.TaggedError<OrchestrationV2ForceStopThreadError>()(+ "OrchestrationV2ForceStopThreadError",+ {+ threadId: ThreadId,+ /** `superseded`: a newer run started since the user asked; nothing was stopped. */+ reason: Schema.optional(Schema.Literal("superseded")),+ cause: Schema.optional(Schema.Defect()),+ },+) {+ override get message(): string {+ return this.reason === "superseded"+ ? "A new turn started, so nothing was force stopped."+ : "Failed to force stop the agent.";+ }+}+export const OrchestrationV2GetWorkflowScriptInput = Schema.Struct({threadId: ThreadId,scriptPath: TrimmedNonEmptyString,@@ -4094,6 +4143,10 @@ export const OrchestrationV2RpcSchemas = {input: OrchestrationV2StopWorkflowInput,output: Schema.Void,},+ forceStopThread: {+ input: OrchestrationV2ForceStopThreadInput,+ output: OrchestrationV2ForceStopThreadResult,+ },getWorkflowScript: {input: OrchestrationV2GetWorkflowScriptInput,output: OrchestrationV2GetWorkflowScriptResult,diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex aae86bd9db4..145fe5e0608 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -220,6 +220,7 @@ import {ORCHESTRATION_V2_WS_METHODS,OrchestrationGetWorkflowScriptError,OrchestrationV2StopWorkflowError,+ OrchestrationV2ForceStopThreadError,OrchestrationV2DispatchCommandError,OrchestrationV2GetShellSnapshotError,OrchestrationV2CommandOutputError,@@ -1770,6 +1771,12 @@ const WsOrchestrationV2StopWorkflowRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS.sterror: Schema.Union([OrchestrationV2StopWorkflowError, EnvironmentAuthorizationError]),});+const WsOrchestrationV2ForceStopThreadRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS.forceStopThread, {+ payload: OrchestrationV2RpcSchemas.forceStopThread.input,+ success: OrchestrationV2RpcSchemas.forceStopThread.output,+ error: Schema.Union([OrchestrationV2ForceStopThreadError, EnvironmentAuthorizationError]),+});+const WsOrchestrationV2GetWorkflowScriptRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS.getWorkflowScript,{@@ -2122,6 +2129,7 @@ export const WsRpcGroup = RpcGroup.make(WsOrchestrationV2DispatchCommandRpc,WsOrchestrationV2GetWorkflowScriptRpc,WsOrchestrationV2StopWorkflowRpc,+ WsOrchestrationV2ForceStopThreadRpc,WsOrchestrationV2GetTurnItemRpc,WsOrchestrationV2GetTurnDiffRpc,WsOrchestrationV2GetFullThreadDiffRpc,diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.tsindex 13f0cbbc240..c895abe3f5e 100644--- a/packages/provider-acp/src/server/adapter.ts+++ b/packages/provider-acp/src/server/adapter.ts@@ -1324,6 +1324,8 @@ interface SnapshotMessageState {loadingIndex: number;}+/** How long a Stop waits for the agent to confirm before the user is offered Force stop. */+const ACP_STOP_CONFIRM_TIMEOUT_MS = 10_000;const TOOL_UPDATE_PERSIST_EVERY = 10;// Agents can resend whole calls while streaming arguments.@@ -7989,7 +7991,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (return yield* Effect.uninterruptibleMask((restore) =>Effect.gen(function* () {yield* restore(runtimeTransitionPermit.take(1));- return yield* Effect.gen(function* () {+ // Stop's caller times out on this call. The transition runs in its own fiber so+ // a stalled hard teardown keeps its state and permit without holding the caller.+ const transitionFiber = yield* Effect.gen(function* () {const transition = yield* Effect.gen(function* () {const interruptContext = yield* Ref.get(activeTurn);if (@@ -8000,8 +8004,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* () {// ACP cancel leaves native children alive; close confirms session-wide Stop.pendingStopCloseTurn = interruptContext;- const closed = yield* runtime.closeSession().pipe(- Effect.timeoutOption("10 seconds"),+ // Interruptible, or neither this timeout nor the caller's could end a hung close.+ const closed = yield* restore(+ runtime+ .closeSession()+ .pipe(Effect.timeoutOption(ACP_STOP_CONFIRM_TIMEOUT_MS)),+ ).pipe(Effect.mapError((cause) =>new ProviderAdapter.ProviderAdapterProtocolError({@@ -8013,10 +8021,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (),);if (Option.isNone(closed)) {- return yield* new ProviderAdapter.ProviderAdapterProtocolError({+ return yield* new ProviderAdapter.ProviderAdapterInterruptTimeoutError({driver,- detail:- "The agent did not confirm session close; background work may still run",+ providerThreadId: turnInput.providerThread.id,+ providerTurnId: turnInput.providerTurnId,+ timeoutMs: ACP_STOP_CONFIRM_TIMEOUT_MS,});}yield* runtimeCallbackPermit.withPermit(@@ -8246,15 +8255,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (}}const stopped = yield* Deferred.await(context.completed).pipe(- Effect.timeoutOption("10 seconds"),+ Effect.timeoutOption(ACP_STOP_CONFIRM_TIMEOUT_MS),);+ // The turn stays open: the agent may still be working, and the user+ // decides whether to Force stop it.if (Option.isNone(stopped)) {- if (!context.finalized) {- yield* finalizeTurn(context, "interrupted");- }- return yield* new ProviderAdapter.ProviderAdapterProtocolError({+ return yield* new ProviderAdapter.ProviderAdapterInterruptTimeoutError({driver,- detail: `ACP provider turn ${turnInput.providerTurnId} did not acknowledge cancellation before the interrupt timeout`,+ providerThreadId: turnInput.providerThread.id,+ providerTurnId: turnInput.providerTurnId,+ timeoutMs: ACP_STOP_CONFIRM_TIMEOUT_MS,});}});@@ -8275,20 +8285,29 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (}),),);- }).pipe(Effect.ensuring(runtimeTransitionPermit.release(1)));+ }).pipe(+ Effect.ensuring(runtimeTransitionPermit.release(1)),+ Effect.forkIn(sessionScope, { startImmediately: true, uninterruptible: true }),+ );+ return yield* restore(Fiber.join(transitionFiber)).pipe(+ Effect.onInterrupt(() =>+ Fiber.interrupt(transitionFiber).pipe(Effect.forkDetach, Effect.asVoid),+ ),+ );}),);},(effect, turnInput) =>effect.pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterInterruptError({- driver,- providerThreadId: turnInput.providerThread.id,- providerTurnId: turnInput.providerTurnId,- cause,- }),+ Effect.mapError((cause) =>+ cause._tag === "ProviderAdapterInterruptTimeoutError"+ ? cause+ : new ProviderAdapter.ProviderAdapterInterruptError({+ driver,+ providerThreadId: turnInput.providerThread.id,+ providerTurnId: turnInput.providerTurnId,+ cause,+ }),),),),diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.tsindex e168512736c..0b5459f647f 100644--- a/packages/provider-core/src/server/ProviderAdapter.ts+++ b/packages/provider-core/src/server/ProviderAdapter.ts@@ -327,6 +327,21 @@ export class ProviderAdapterInterruptError extends Schema.TaggedError<ProviderAd}}+/** The provider did not confirm a stop in time; its processes may still be running. */+export class ProviderAdapterInterruptTimeoutError extends Schema.TaggedError<ProviderAdapterInterruptTimeoutError>()(+ "ProviderAdapterInterruptTimeoutError",+ {+ driver: ProviderDriverKind,+ providerThreadId: ProviderThreadId,+ providerTurnId: ProviderTurnId,+ timeoutMs: Schema.Number,+ },+) {+ override get message(): string {+ return `The ${this.driver} provider did not confirm stopping turn ${this.providerTurnId} within ${this.timeoutMs} ms.`;+ }+}+export class ProviderAdapterRuntimeRequestResponseError extends Schema.TaggedError<ProviderAdapterRuntimeRequestResponseError>()("ProviderAdapterRuntimeRequestResponseError",{@@ -388,6 +403,7 @@ export const ProviderAdapterV2Error = Schema.Union([ProviderAdapterSteerRunUnsupportedError,ProviderAdapterSteerRunError,ProviderAdapterInterruptError,+ ProviderAdapterInterruptTimeoutError,ProviderAdapterRuntimeRequestResponseError,ProviderAdapterEventStreamError,ProviderAdapterProtocolError,diff --git a/packages/shared/src/AgentScope.ts b/packages/shared/src/AgentScope.tsindex ce2d58c017b..5f0ffca2171 100644--- a/packages/shared/src/AgentScope.ts+++ b/packages/shared/src/AgentScope.ts@@ -22,6 +22,12 @@ export interface AgentScopeShape {* descendants outside its process group. Preserves systemd OOM diagnosis.*/readonly stop: (unit: string) => Effect.Effect<void>;+ /**+ * SIGKILLs every process in the thread's own scope, which works even while+ * the kernel throttles them. Shared scopes serve other threads and are never+ * killed here. Succeeds with whether a scope was killed.+ */+ readonly kill: (threadId: string) => Effect.Effect<boolean>;/*** Forgets the thread's scope. The session manager calls it before it opens* a provider session, so a scope only answers for the session that launched@@ -42,6 +48,7 @@ export const AgentScope = Context.Reference<AgentScopeShape>("@t3tools/shared/Agwrap: ({ command, args }) => Effect.succeed({ command, args }),oomKilled: () => Effect.succeed(false),stop: () => Effect.void,+ kill: () => Effect.succeed(false),clear: () => Effect.void,}),});