fix(core): stop Claude Agent processes when their session is deleted (#62649)

Co-authored-by: WTLAIB <205451322+WTLAIB@users.noreply.github.com>
Co-authored-by: Dan Smolsky <dannysmo@gmail.com>
Co-authored-by: Dan Smolsky <78942835+Tarquinen@users.noreply.github.com>
This commit is contained in:
WTLAIB
2026-11-20 12:04:03 +08:00
committed by GitHub
Unverified
parent 2c9060237f
commit aaa9bff2a3
7 changed files with 95 additions and 12 deletions
@@ -15,6 +15,7 @@ export interface Interface {
}
const LAST = "last-account"
export const key = (sessionID: string) => `accounts/${sessionID}`
export function make(input: { readonly sessions: ClaudeSessions.Interface; readonly storage: Storage }) {
const read = Effect.fn("ClaudeAccounts.read")(function* (key: string) {
@@ -30,10 +31,10 @@ export function make(input: { readonly sessions: ClaudeSessions.Interface; reado
if (configDirs.length < 2 || connection?.ANTHROPIC_API_KEY || connection?.ANTHROPIC_AUTH_TOKEN) {
return yield* input.sessions.run(request)
}
const own = request.sessionID ? yield* read(`accounts/${request.sessionID}`) : undefined
const own = request.sessionID ? yield* read(key(request.sessionID)) : undefined
const last = yield* read(LAST)
// Side calls and new forks start on their parent chat's account, which has its transcript and prompt cache.
const parent = !own && request.sourceID ? yield* read(`accounts/${request.sourceID}`) : undefined
const parent = !own && request.sourceID ? yield* read(key(request.sourceID)) : undefined
const from = own ?? parent ?? last
const start = from ? Math.max(0, configDirs.indexOf(from)) : 0
const dirs = [...configDirs.slice(start), ...configDirs.slice(0, start)]
@@ -48,7 +49,7 @@ export function make(input: { readonly sessions: ClaudeSessions.Interface; reado
const error = attempt.error()
if (!error) {
// A side call never moves its chat, because the side call's model may have hit a limit of its own.
if (request.sessionID && dir !== own) yield* input.storage.set(`accounts/${request.sessionID}`, dir)
if (request.sessionID && dir !== own) yield* input.storage.set(key(request.sessionID), dir)
if (dir !== last) yield* input.storage.set(LAST, dir)
attempt.flush()
return
@@ -68,6 +68,8 @@ export interface Interface {
readonly run: (request: Request) => Effect.Effect<void, Error>
// OpenCode stopped running the session, so a turn still waiting for tool results will not get them.
readonly idle: (sessionID: string) => Effect.Effect<void>
// OpenCode deleted the session, so nothing can resume it.
readonly remove: (sessionID: string) => Effect.Effect<void>
}
const launch = (request: Request) =>
@@ -114,13 +116,15 @@ export function registry() {
)
})
const closeEntry = Effect.fn("ClaudeSessions.closeEntry")(function* (entry: Entry) {
if (entry.active) yield* Fiber.interrupt(entry.active)
// The active turn's finalizer can install a new idle timer.
if (entry.idle) yield* Fiber.interrupt(entry.idle)
yield* entry.lock.withPermit(stop(entry)).pipe(Effect.catch((error) => Effect.logWarning(error)))
})
const closeEntries = Effect.fn("ClaudeSessions.closeEntries")(function* () {
for (const entry of [...entries.values(), ...temporary]) {
if (entry.active) yield* Fiber.interrupt(entry.active)
// The active turn's finalizer can install a new idle timer.
if (entry.idle) yield* Fiber.interrupt(entry.idle)
yield* entry.lock.withPermit(stop(entry)).pipe(Effect.catch((error) => Effect.logWarning(error)))
}
for (const entry of [...entries.values(), ...temporary]) yield* closeEntry(entry)
entries.clear()
})
@@ -490,7 +494,14 @@ export function registry() {
yield* armIdle(entry)
})
return { run, idle } satisfies Interface
const remove = Effect.fn("ClaudeSessions.remove")(function* (sessionID: string) {
const entry = entries.get(sessionID)
entries.delete(sessionID)
if (entry) yield* closeEntry(entry)
yield* records.remove(sessionID)
})
return { run, idle, remove } satisfies Interface
})
return { attach, close }
@@ -1,5 +1,6 @@
import { define } from "@opencode/plugin/effect/plugin"
import { Effect, Option, Stream } from "effect"
import { ClaudeAccounts } from "./claude/accounts.js"
import { ClaudeIO } from "./claude/io.js"
import { ClaudeSessions } from "./claude/sessions.js"
import { ClaudeStatus } from "./claude/status.js"
@@ -35,10 +36,21 @@ export const make = (io: ClaudeIO.Interface, registry = ClaudeSessions.registry(
const sessions = yield* registry.attach({ io, status, storage: ctx.storage, directory: ctx.location.directory })
yield* ctx.event
.subscribe({
types: ["session.execution.succeeded", "session.execution.failed", "session.execution.interrupted"],
types: [
"session.execution.succeeded",
"session.execution.failed",
"session.execution.interrupted",
"session.deleted",
],
})
.pipe(
Stream.runForEach((event) => sessions.idle(event.data.sessionID)),
Stream.runForEach((event) => {
if (event.type !== "session.deleted") return sessions.idle(event.data.sessionID)
return Effect.andThen(
sessions.remove(event.data.sessionID),
ctx.storage.remove(ClaudeAccounts.key(event.data.sessionID)),
)
}),
Effect.forkScoped({ startImmediately: true }),
)
yield* ClaudeProvider.register(ctx, status, io)
@@ -15,6 +15,10 @@ export type Record = typeof Record.Type
export interface Storage {
readonly get: (key: string) => Effect.Effect<unknown>
readonly set: (key: string, value: Record) => Effect.Effect<void>
readonly remove: (key: string) => Effect.Effect<void>
readonly scan: (options: { readonly prefix: string }) => Effect.Effect<{
readonly entries: readonly { readonly key: string }[]
}>
}
export function make(storage: Storage) {
@@ -24,6 +28,11 @@ export function make(storage: Storage) {
return Option.getOrUndefined(saved)
}),
set: (sessionID: string, record: Record, configDir?: string) => storage.set(key(sessionID, configDir), record),
remove: Effect.fn("SessionRecord.remove")(function* (sessionID: string) {
yield* storage.remove(key(sessionID))
const folders = yield* storage.scan({ prefix: `${key(sessionID)}:` })
for (const entry of folders.entries) yield* storage.remove(entry.key)
}),
}
}
@@ -22,6 +22,14 @@ export function storage() {
Effect.sync(() => {
data.set(key, value)
}),
remove: (key: string) =>
Effect.sync(() => {
data.delete(key)
}),
scan: (options: { readonly prefix: string }) =>
Effect.sync(() => ({
entries: [...data.keys()].filter((key) => key.startsWith(options.prefix)).map((key) => ({ key })),
})),
}
}
@@ -308,6 +308,47 @@ describe("ClaudeAgentPlugin models", () => {
)
})
describe("ClaudeAgentPlugin deleted sessions", () => {
it.live("deleting a session stops its process and removes what was saved for it", () =>
Effect.gen(function* () {
const store = yield* storage
const claude = FakeClaude.make(
[FakeClaude.expectStartup(), FakeClaude.expectTurn(), FakeClaude.expectInterrupt()],
{ probes: true },
)
yield* addPlugin(FakeIO.make({ claude }))
const location = yield* Location.Service
const sessions = yield* Session.Service
const session = yield* sessions.create({ location: { directory: location.directory } })
const aisdk = yield* AISDK.Service
const sdk = yield* aisdk.runSDK({
model: Model.Info.make({
...Model.Info.default(ClaudeProvider.ID, haiku.id),
modelID: haiku.id,
package: Provider.aisdk(ClaudeProvider.PACKAGE),
}),
package: ClaudeProvider.PACKAGE,
options: {},
})
const model: LanguageModelV3 = sdk.sdk.languageModel("haiku")
const result = yield* Effect.promise(() =>
model.doStream({
prompt: TestSessions.prompt("Remember the marker COPPER-OTTER. Reply only with that marker."),
headers: { [RequestKind.SESSION_HEADER]: session.id, [RequestKind.HEADER]: "primary" },
}),
)
yield* Effect.promise(() => TestSessions.collect(result.stream))
yield* store.set(`sessions/${session.id}:/claude-work`, { claudeSessionID: "other-folder" })
yield* store.set(`accounts/${session.id}`, "/claude-work")
yield* sessions.remove(session.id)
yield* Effect.promise(() => claude.runs[0]!.closed)
yield* eventually(store.scan({ prefix: "" }), (saved) => saved.entries.every((entry) => entry.key === "models"))
claude.check()
}),
)
})
describe("ClaudeAgentPlugin connection", () => {
it.live("connecting without claude installed asks the user to install it", () =>
Effect.gen(function* () {
+1
View File
@@ -113,6 +113,7 @@ Users can configure the `claude-agent` provider and its models in opencode confi
### Processes
- Each session has one long-running `claude` process. It stops after 5 minutes idle, and the next message picks up the saved Claude session.
- Deleting a session stops its process right away and removes what opencode saved for it.
- While opencode runs Claude's tool calls, the process is not idle, however long the tools take. Subagents, permission prompts and questions can easily take more than 5 minutes, and stopping the process then would record the call as cancelled by the user. If opencode stops running the session before sending the results, for example because the user interrupted a tool, the 5 minutes start then.
- Why: the SDK starts one process per conversation and cannot share a process between sessions. Claude Code in a terminal works the same way.
- The process restarts when the system prompt, tools, connection settings or output limit change.