fix(server): stop kills lingering Claude work

This commit is contained in:
Theo Browne committed 2026-08-09 14:50:57 -07:00
1 parent 83d769f02d
commit 8c572b038d
2 files changed
+152 -96

No files matched your search

@@ -54,8 +54,6 @@ class FakeClaudeQuery implements AsyncIterable<SDKMessage> {
private done = false;
private failure: unknown | undefined;
public readonly interruptCalls: Array<void> = [];
public readonly stopTaskCalls: Array<string> = [];
public readonly setModelCalls: Array<string | undefined> = [];
public readonly setPermissionModeCalls: Array<string> = [];
public readonly setMaxThinkingTokensCalls: Array<number | null> = [];
@@ -95,14 +93,6 @@ class FakeClaudeQuery implements AsyncIterable<SDKMessage> {
}
}
readonly interrupt = async (): Promise<void> => {
this.interruptCalls.push(undefined);
};
readonly stopTask = async (taskId: string): Promise<void> => {
this.stopTaskCalls.push(taskId);
};
readonly setModel = async (model?: string): Promise<void> => {
this.setModelCalls.push(model);
};
@@ -1580,7 +1570,7 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("interruptTurn settles every acknowledged live task before interrupting", () => {
it.effect("interruptTurn settles live tasks and closes the provider session", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
@@ -1645,9 +1635,12 @@ describe("ClaudeAdapterLive", () => {
);
yield* adapter.interruptTurn(session.threadId);
// Only the still-live task is stopped; interrupt always fires after.
assert.deepEqual(harness.query.stopTaskCalls, ["task-live"]);
assert.equal(harness.query.interruptCalls.length, 1);
// Closing the session is the hard stop because SDK interrupt can leave
// resumed background work alive.
assert.equal(harness.query.closeCalls, 1);
const sessions = yield* adapter.listSessions();
assert.equal(sessions.length, 0);
const stoppedTaskEvents = Array.from(yield* Fiber.join(stoppedTaskEventFiber));
assert.equal(stoppedTaskEvents.length, 1);
@@ -1665,6 +1658,100 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("keeps a resumed replacement session during slow stop cleanup", () => {
const queries: FakeClaudeQuery[] = [];
let signalUsageStarted: () => void = () => undefined;
let releaseUsage: () => void = () => undefined;
const usageStarted = new Promise<void>((resolve) => {
signalUsageStarted = resolve;
});
const usageGate = new Promise<void>((resolve) => {
releaseUsage = resolve;
});
const layer = Layer.effect(
ClaudeAdapter,
Effect.gen(function* () {
const claudeConfig = decodeClaudeSettings({});
return yield* makeClaudeAdapter(claudeConfig, {
createQuery: () => {
const query = new FakeClaudeQuery();
if (queries.length === 0) {
Object.assign(query, {
getContextUsage: async () => {
signalUsageStarted();
await usageGate;
throw new Error("query closed");
},
});
}
queries.push(query);
return query;
},
});
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(NodeServices.layer),
);
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 8).pipe(
Stream.runCollect,
Effect.forkChild,
);
const firstSession = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: firstSession.threadId,
input: "hello",
attachments: [],
});
const interruptFiber = yield* adapter
.interruptTurn(firstSession.threadId)
.pipe(Effect.forkChild);
yield* Effect.promise(() => usageStarted);
assert.equal(queries[0]?.closeCalls, 1);
const replacement = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
resumeCursor: firstSession.resumeCursor,
});
releaseUsage();
yield* Fiber.join(interruptFiber);
const activeSessions = yield* adapter.listSessions();
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
assert.equal(queries.length, 2);
assert.equal(queries[1]?.closeCalls, 0);
assert.equal(activeSessions.length, 1);
assert.deepEqual(activeSessions[0]?.resumeCursor, replacement.resumeCursor);
assert.deepEqual(
runtimeEvents
.filter((event) => event.type.startsWith("session."))
.map((event) => event.type),
[
"session.started",
"session.configured",
"session.state.changed",
"session.started",
"session.configured",
"session.state.changed",
],
);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(layer),
);
});
it.effect("workflow member coalescing: identical snapshots suppress, changes emit", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -65,7 +65,6 @@ import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
@@ -249,9 +248,6 @@ interface ClaudeSessionContext {
}
interface ClaudeQueryRuntime extends AsyncIterable<SDKMessage> {
readonly interrupt: () => Promise<void>;
/** SDK Query.stopTask — present on real queries; optional for test doubles. */
readonly stopTask?: (taskId: string) => Promise<void>;
readonly setModel: (model?: string) => Promise<void>;
readonly setPermissionMode: (mode: PermissionMode) => Promise<void>;
readonly setMaxThinkingTokens: (maxThinkingTokens: number | null) => Promise<void>;
@@ -3600,6 +3596,49 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
context.stopped = true;
// Schedule process termination before any cleanup that can wait on the
// provider. The SDK closes stdin, then escalates from SIGTERM to SIGKILL.
yield* Effect.try({
try: () => context.query.close(),
catch: (cause) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: context.session.threadId,
detail: "Failed to close Claude runtime query.",
cause,
}),
}).pipe(
Effect.catch((error) =>
emitRuntimeError(context, "Failed to close Claude runtime query.", {
errorTag: error._tag,
provider: error.provider,
threadId: error.threadId,
detail: error.detail,
}),
),
);
for (const taskId of Array.from(context.liveTaskIds)) {
if (!context.liveTaskIds.delete(taskId)) {
continue;
}
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "task.completed",
eventId: stamp.eventId,
provider: PROVIDER,
createdAt: stamp.createdAt,
threadId: context.session.threadId,
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
payload: {
taskId: RuntimeTaskId.make(taskId),
status: "stopped",
...taskLinkageFor(context.taskAgents, taskId),
},
providerRefs: nativeProviderRefs(context),
});
}
for (const [requestId, pending] of context.pendingApprovals) {
yield* Deferred.succeed(pending.decision, "cancel");
const stamp = yield* makeEventStamp();
@@ -3632,26 +3671,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
yield* Fiber.interrupt(streamFiber);
}
yield* Effect.try({
try: () => context.query.close(),
catch: (cause) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: context.session.threadId,
detail: "Failed to close Claude runtime query.",
cause,
}),
}).pipe(
Effect.catch((error) =>
emitRuntimeError(context, "Failed to close Claude runtime query.", {
errorTag: error._tag,
provider: error.provider,
threadId: error.threadId,
detail: error.detail,
}),
),
);
const updatedAt = yield* nowIso;
context.session = {
...context.session,
@@ -3660,7 +3679,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
updatedAt,
};
if (options?.emitExitEvent !== false) {
if (options?.emitExitEvent !== false && sessions.get(context.session.threadId) === context) {
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "session.exited",
@@ -3676,7 +3695,9 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
}
sessions.delete(context.session.threadId);
if (sessions.get(context.session.threadId) === context) {
sessions.delete(context.session.threadId);
}
});
const requireSession = (
@@ -4413,62 +4434,10 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const interruptTurn: ClaudeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")(
function* (threadId, _turnId) {
const context = yield* requireSession(threadId);
// Stop-everything semantics: users reach for Stop precisely when a
// fleet ran away. interrupt() alone only ends the parent turn —
// background subagents/shells keep running and keep burning tokens.
// Stop every live task first (best-effort per task: one refusal must
// not strand the rest or block the turn interrupt), then interrupt.
if (context.query.stopTask && context.liveTaskIds.size > 0) {
const liveIds = Array.from(context.liveTaskIds);
// Bounded: a wedged child's stopTask promise may never settle
// (Effect.ignore handles rejection, not non-resolution), and the
// parent interrupt below MUST still run — Stop matters most during
// runaway fleets (review finding). Per-task timeout keeps one hung
// child from consuming the whole budget.
yield* Effect.forEach(
liveIds,
(taskId) =>
Effect.gen(function* () {
const stopAcknowledged = yield* Effect.tryPromise({
// Invoke through the query object: SDK methods rely on `this`.
try: () => context.query.stopTask!(taskId),
catch: () => undefined,
}).pipe(
Effect.timeoutOption("3 seconds"),
Effect.orElseSucceed(() => Option.none()),
);
if (Option.isNone(stopAcknowledged) || !context.liveTaskIds.delete(taskId)) {
return;
}
// stopTask only acknowledges the control request. Its separate
// task_notification can lose the race with interrupt(), so make
// the acknowledged stop authoritative for the durable UI state.
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "task.completed",
eventId: stamp.eventId,
provider: PROVIDER,
createdAt: stamp.createdAt,
threadId: context.session.threadId,
...(context.turnState
? { turnId: asCanonicalTurnId(context.turnState.turnId) }
: {}),
payload: {
taskId: RuntimeTaskId.make(taskId),
status: "stopped",
...taskLinkageFor(context.taskAgents, taskId),
},
providerRefs: nativeProviderRefs(context),
});
}).pipe(Effect.ignore),
{ concurrency: 8, discard: true },
).pipe(Effect.timeoutOption("10 seconds"), Effect.ignore);
}
yield* Effect.tryPromise({
try: () => context.query.interrupt(),
catch: (cause) => toRequestError(threadId, "turn/interrupt", cause),
});
// interrupt() can acknowledge while resumed background tasks keep the
// CLI alive. Stop is a hard session boundary for Claude, so close the
// query and let the SDK escalate to SIGKILL when graceful exit fails.
yield* stopSessionInternal(context);
},
);