From 52641a90fb292b978d19dd75bd7610a7ddd4aa1b Mon Sep 17 00:00:00 2001 From: Yash Date: Mon, 14 Sep 2026 20:51:48 +0000 Subject: [PATCH] feat(harness): end both managed session engines truthfully --- .changeset/assistant-session-end.md | 7 + packages/harness/docs/assistant-end.md | 27 ++ .../harness/src/core/assistant-end.test.ts | 327 ++++++++++++++++++ packages/harness/src/core/assistant-end.ts | 172 +++++++++ .../src/core/assistant-lifecycle.test.ts | 13 + .../harness/src/core/assistant-lifecycle.ts | 9 +- .../core/assistant-state-projection.test.ts | 4 + .../src/core/assistant-state-projection.ts | 8 +- packages/harness/src/server/index.ts | 3 + packages/harness/src/server/rest.test.ts | 78 +++++ packages/harness/src/server/rest.ts | 13 + 11 files changed, 657 insertions(+), 4 deletions(-) create mode 100644 .changeset/assistant-session-end.md create mode 100644 packages/harness/docs/assistant-end.md create mode 100644 packages/harness/src/core/assistant-end.test.ts create mode 100644 packages/harness/src/core/assistant-end.ts diff --git a/.changeset/assistant-session-end.md b/.changeset/assistant-session-end.md new file mode 100644 index 000000000..435ada23e --- /dev/null +++ b/.changeset/assistant-session-end.md @@ -0,0 +1,7 @@ +--- +"@sapiom/harness": patch +--- + +Coordinate selected-session End across Terminal and Assistant with immediate +admission fencing, bounded cleanup results, and retained history on incomplete +shutdown. Return conflict responses for cancelled or unconfirmed Terminal resume. diff --git a/packages/harness/docs/assistant-end.md b/packages/harness/docs/assistant-end.md new file mode 100644 index 000000000..9eb282528 --- /dev/null +++ b/packages/harness/docs/assistant-end.md @@ -0,0 +1,27 @@ +# Ending a Studio session + +With the End coordinator installed, `DELETE /api/sessions/:id` ends the selected +Studio session's managed Terminal and Assistant runtimes. It uses the existing +per-boot token; an expired Assistant grant does not prevent local End. A normal +Terminal exit or a detached browser does not End the Assistant session. + +End fences Assistant admission and requests both runtime shutdowns synchronously, +before awaiting storage. Concurrent requests for the same ID share the complete +operation, including final persistence. A completed retry checks both engines +again, since a new Terminal incarnation can exist under the same Assistant header. +Successful repeats keep the session ended and may advance its lifecycle revision. + +The response is `200 { ok: true, lifecycle }` after confirmed cleanup and durable +`ended` metadata. Missing registry rows return `404`. Failed or incomplete cleanup, +failed storage, or the five-second operation deadline returns +`409 { ok: false, code: "cleanup_unconfirmed", error }`. The row and history remain +available. A deadline does not claim to cancel underlying filesystem writes; +admission remains fenced until confirmed cleanup and final persistence complete. + +The coordinator reads the original lifecycle before writing `ending`. A saved +`ending` from a prior host cannot be cleared merely because the current host has +no runtime: positive cleanup evidence is required for both engines. This code +does not recover missing prior-host process ownership. Such unresolved sessions +remain `ending`; restarting Studio or repeating End cannot establish missing +process evidence. Different Studio IDs remain independent, including IDs in the +same folder. Routers without the coordinator retain their legacy Terminal close. diff --git a/packages/harness/src/core/assistant-end.test.ts b/packages/harness/src/core/assistant-end.test.ts new file mode 100644 index 000000000..b4cd31c5f --- /dev/null +++ b/packages/harness/src/core/assistant-end.test.ts @@ -0,0 +1,327 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { AssistantEndCoordinator } from "./assistant-end.js"; +import { AssistantLifecycleCoordinator } from "./assistant-lifecycle.js"; +import { + AssistantSessionRevisionError, + type AssistantSessionStore, +} from "./assistant-session-store.js"; +import type { AssistantLifecycle } from "../shared/assistant-session.js"; +import type { OpenCodeRetirement } from "./opencode-host.js"; +import type { TerminalCleanupResult } from "./session-manager.js"; + +const gate = () => { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +}; +const state = ( + id: string, + lifecycle: AssistantLifecycle["lifecycle"] = "open", +): AssistantLifecycle => ({ + version: 1, + harnessSessionId: id, + revision: 1, + lifecycle, + execution: "paused", + updatedAt: 1, +}); +function fixture(prior: AssistantLifecycle | null = state("a")) { + const states = new Map(); + if (prior) states.set("a", prior); + states.set("b", state("b")); + const rows = new Map( + ["a", "b"].map((id) => [ + id, + { id, cwd: "/same/folder", status: "running" }, + ]), + ); + const signals = new Map(["a", "b"].map((id) => [id, new AbortController()])); + const store = { + lifecycle: vi.fn(async (id: string) => states.get(id) ?? null), + transition: vi.fn( + async (id, expected, next) => { + if ((states.get(id)?.revision ?? 0) !== expected) + throw new AssistantSessionRevisionError(); + const saved: AssistantLifecycle = { + ...state(id), + ...next, + revision: expected + 1, + }; + states.set(id, saved); + return saved; + }, + ), + }; + const retire = vi.fn((id: string): Promise => { + signals.get(id)?.abort(); + return Promise.resolve({ state: "confirmed" }); + }); + const close = vi.fn((id: string): Promise => { + rows.get(id)!.status = "exited"; + return Promise.resolve({ + state: "confirmed", + runtimeEpoch: `terminal-${id}`, + }); + }); + const lifecycle = new AssistantLifecycleCoordinator({ + store, + associations: { ensure: vi.fn() }, + host: { + ensure: vi.fn(() => { + throw new Error("Assistant grant expired"); + }), + current: () => null, + assertCurrent: vi.fn(), + retireExact: vi.fn(), + observe: vi.fn(), + beginShutdown: vi.fn(), + retireWithResult: retire, + }, + }); + const coordinator = () => + new AssistantEndCoordinator({ + store, + lifecycle, + sessionManager: { closeWithResult: close }, + timeoutMs: 100, + }); + return { + end: coordinator(), + coordinator, + lifecycle, + store, + states, + rows, + signals, + retire, + close, + }; +} +afterEach(() => { + vi.useRealTimers(); +}); + +it("fences both engines synchronously before a held snapshot and affects only the selected ID", async () => { + const f = fixture(); + const held = gate(); + f.store.lifecycle.mockImplementationOnce(() => held.promise); + const ending = f.end.end("a"); + expect(f.signals.get("a")!.signal.aborted).toBe(true); + expect(f.close).toHaveBeenCalledExactlyOnceWith("a"); + expect(f.store.transition).not.toHaveBeenCalled(); + expect(f.signals.get("b")!.signal.aborted).toBe(false); + expect(f.rows.get("b")!.status).toBe("running"); + await expect(f.lifecycle.attach("a", 1)).rejects.toThrow(); + held.resolve(state("a")); + await expect(ending).resolves.toMatchObject({ + ok: true, + lifecycle: { lifecycle: "ended" }, + }); + expect(f.rows.has("a")).toBe(true); + expect(f.states.get("b")).toEqual(state("b")); +}); + +it("coalesces callers through final persistence and safely rechecks a completed retry", async () => { + const f = fixture(); + const held = gate(); + const transition = f.store.transition.getMockImplementation()!; + f.store.transition.mockImplementation(async (...args) => { + if (args[2].lifecycle === "ended") await held.promise; + return transition(...args); + }); + const first = f.end.end("a"); + await vi.waitFor(() => + expect(f.store.transition).toHaveBeenCalledWith("a", 2, { + lifecycle: "ended", + execution: "paused", + }), + ); + for (let i = 0; i < 20; i++) expect(f.end.end("a")).toBe(first); + held.resolve(); + const result = await first; + expect(result.ok).toBe(true); + expect(f.retire).toHaveBeenCalledOnce(); + expect(f.close).toHaveBeenCalledOnce(); + expect(f.store.transition).toHaveBeenCalledTimes(2); + expect((await f.end.end("a")).ok).toBe(true); + expect(f.states.get("a")!.lifecycle).toBe("ended"); +}); + +it("installs coalescing before synchronous lifecycle listeners can re-enter End", async () => { + const f = fixture(); + let nested: Promise | undefined; + f.lifecycle.subscribe(() => { + nested ??= f.end.end("a"); + }); + const first = f.end.end("a"); + expect(nested).toBe(first); + expect((await first).ok).toBe(true); + expect(f.close).toHaveBeenCalledOnce(); +}); + +it("a new open revision invalidates the completed End for a later same-ID Resume", async () => { + const f = fixture(); + await f.end.end("a"); + const ended = f.states.get("a")!; + await f.store.transition("a", ended.revision, { + lifecycle: "open", + execution: "paused", + }); + await f.lifecycle.describe("a"); + expect((await f.end.end("a")).ok).toBe(true); + expect(f.close).toHaveBeenCalledTimes(2); + expect(f.retire).toHaveBeenCalledTimes(2); +}); + +it("closes a new Terminal incarnation even when its Assistant header is still ended", async () => { + const f = fixture(); + await f.end.end("a"); + const before = f.states.get("a")!; + f.rows.get("a")!.status = "running"; + f.close.mockImplementationOnce(async (id) => { + f.rows.get(id)!.status = "exited"; + return { state: "confirmed", runtimeEpoch: "replacement-terminal" }; + }); + expect((await f.end.end("a")).ok).toBe(true); + expect(f.close).toHaveBeenCalledTimes(2); + expect(f.rows.get("a")!.status).toBe("exited"); + expect(f.states.get("a")!.revision).toBeGreaterThan(before.revision); +}); + +it.each([null, state("a"), state("a", "ended")])( + "accepts current-host absence without an unresolved prior End: %j", + async (prior) => { + const f = fixture(prior); + f.retire.mockResolvedValue({ state: "absent" }); + f.close.mockResolvedValue({ state: "absent", runtimeEpoch: null }); + expect((await f.end.end("a")).ok).toBe(true); + }, +); + +it("never treats absence after a prior-host ending header as proof of old process cleanup", async () => { + const f = fixture(state("a", "ending")); + f.retire.mockResolvedValue({ state: "confirmed" }); + f.close.mockResolvedValue({ state: "absent", runtimeEpoch: null }); + expect(await f.end.end("a")).toMatchObject({ + ok: false, + code: "cleanup_unconfirmed", + }); + expect(f.states.get("a")!.lifecycle).toBe("ending"); + // A retry and another coordinator cannot erase the uncertainty by observing + // only empty current-process maps. Neither attempt may call finishEnd. + f.retire.mockResolvedValue({ state: "absent" }); + expect((await f.end.end("a")).ok).toBe(false); + expect((await f.coordinator().end("a")).ok).toBe(false); + expect( + f.store.transition.mock.calls.every( + (args) => args[2].lifecycle === "ending", + ), + ).toBe(true); +}); + +it("retains positive exact-engine evidence across an incomplete same-host retry", async () => { + const f = fixture(state("a", "ending")); + f.close.mockResolvedValueOnce({ + state: "unconfirmed", + runtimeEpoch: "terminal-a", + }); + expect((await f.end.end("a")).ok).toBe(false); + f.retire.mockResolvedValue({ state: "absent" }); + expect((await f.end.end("a")).ok).toBe(true); + expect(f.rows.has("a")).toBe(true); +}); + +it.each(["snapshot", "ending", "ended", "terminal", "native"] as const)( + "keeps a failed %s operation visible and fenced", + async (stage) => { + const f = fixture(); + if (stage === "snapshot") + f.store.lifecycle.mockRejectedValueOnce( + new Error("private storage path"), + ); + if (stage === "terminal") + f.close.mockRejectedValueOnce(new Error("private binding path")); + if (stage === "native") + f.retire.mockResolvedValueOnce({ state: "unconfirmed" }); + if (stage === "ending" || stage === "ended") { + const transition = f.store.transition.getMockImplementation()!; + f.store.transition.mockImplementation(async (...args) => { + if (args[2].lifecycle === stage) + throw new Error("private storage path"); + return transition(...args); + }); + } + const result = await f.end.end("a"); + expect(result).toMatchObject({ ok: false, code: "cleanup_unconfirmed" }); + expect(JSON.stringify(result)).not.toContain("private"); + expect(f.close).toHaveBeenCalledOnce(); + expect(f.retire).toHaveBeenCalledOnce(); + expect(f.rows.has("a")).toBe(true); + expect(f.states.get("a")!.lifecycle).not.toBe("ended"); + await expect( + f.lifecycle.attach("a", f.states.get("a")!.revision), + ).rejects.toThrow(); + }, +); + +it.each(["snapshot", "ending", "ended", "terminal", "native"] as const)( + "bounds a never-resolving %s operation without finishing an unconfirmed End", + async (stage) => { + vi.useFakeTimers(); + const f = fixture(); + if (stage === "snapshot") + f.store.lifecycle.mockImplementationOnce(() => new Promise(() => {})); + if (stage === "terminal") + f.close.mockImplementationOnce(() => new Promise(() => {})); + if (stage === "native") + f.retire.mockImplementationOnce(() => new Promise(() => {})); + if (stage === "ending" || stage === "ended") { + const transition = f.store.transition.getMockImplementation()!; + f.store.transition.mockImplementation((...args) => + args[2].lifecycle === stage + ? new Promise(() => {}) + : transition(...args), + ); + } + const first = f.end.end("a"); + expect(f.end.end("a")).toBe(first); + expect(f.close).toHaveBeenCalledOnce(); + expect(f.retire).toHaveBeenCalledOnce(); + await vi.advanceTimersByTimeAsync(100); + expect(await first).toMatchObject({ + ok: false, + code: "cleanup_unconfirmed", + }); + expect(f.states.get("a")!.lifecycle).not.toBe("ended"); + expect(f.rows.has("a")).toBe(true); + expect(vi.getTimerCount()).toBe(0); + }, +); + +it("does not let one failed cleanup skip waiting for the other engine or affect another session", async () => { + const f = fixture(); + const held = gate(); + f.retire.mockImplementationOnce(() => held.promise); + f.close.mockRejectedValueOnce(new Error("binding write failed")); + const first = f.end.end("a"); + expect((await f.end.end("b")).ok).toBe(true); + expect(f.end.end("a")).toBe(first); + held.resolve({ state: "confirmed" }); + expect((await first).ok).toBe(false); +}); + +it("expires a hung original-state read without a late write and permits a fresh retry", async () => { + vi.useFakeTimers(); + const f = fixture(); + const held = gate(); + f.store.lifecycle.mockImplementationOnce(() => held.promise); + const first = f.end.end("a"); + await vi.advanceTimersByTimeAsync(100); + expect((await first).ok).toBe(false); + held.resolve(state("a")); + await vi.advanceTimersByTimeAsync(0); + expect(f.store.transition).not.toHaveBeenCalled(); + expect((await f.end.end("a")).ok).toBe(true); +}); diff --git a/packages/harness/src/core/assistant-end.ts b/packages/harness/src/core/assistant-end.ts new file mode 100644 index 000000000..1102757bb --- /dev/null +++ b/packages/harness/src/core/assistant-end.ts @@ -0,0 +1,172 @@ +import { clearTimeout, setTimeout } from "node:timers"; +import type { AssistantLifecycle } from "../shared/assistant-session.js"; +import type { AssistantLifecycleCoordinator } from "./assistant-lifecycle.js"; +import type { AssistantSessionStore } from "./assistant-session-store.js"; +import type { SessionManager } from "./session-manager.js"; + +export type AssistantEndResult = + | { ok: true; lifecycle: AssistantLifecycle } + | { ok: false; code: "cleanup_unconfirmed"; error: string }; + +interface Options { + store: Pick; + lifecycle: Pick< + AssistantLifecycleCoordinator, + "beginEnd" | "finishEnd" | "snapshot" + >; + sessionManager: Pick; + timeoutMs?: number; +} +interface Evidence { + prior: Promise; + native: boolean; + terminal: boolean; +} +const unconfirmed = (): AssistantEndResult => ({ + ok: false, + code: "cleanup_unconfirmed", + error: + "Session cleanup could not be confirmed. The session and its history have been retained.", +}); +const call = (operation: () => Promise): Promise => { + try { + return operation(); + } catch (error) { + return Promise.reject(error); + } +}; +async function bounded( + operation: Promise, + deadline: number, +): Promise { + let timer: ReturnType | undefined; + try { + return await Promise.race([ + operation, + new Promise((resolve) => { + timer = setTimeout( + () => resolve(undefined), + Math.max(0, deadline - Date.now()), + ); + }), + ]); + } finally { + clearTimeout(timer); + } +} + +/** One owner per host for complete End operations. Completed retries check both + * engines again: Terminal can resume without changing the Assistant header. + * Local End requires boot authorization, never a current Assistant grant. */ +export class AssistantEndCoordinator { + private readonly pending = new Map>(); + private readonly evidence = new Map(); + + constructor(private readonly options: Options) {} + + end(id: string): Promise { + const pending = this.pending.get(id); + if (pending) return pending; + const current = this.options.lifecycle + .snapshot() + .find((state) => state.harnessSessionId === id); + if (current?.lifecycle === "open") this.evidence.delete(id); + + // Install the single-flight slot before any synchronous retirement callback. + let resolve!: (result: AssistantEndResult) => void; + const promise = new Promise((done) => { + resolve = done; + }); + this.pending.set(id, promise); + const finish = (result: AssistantEndResult) => { + if (result.ok) this.evidence.delete(id); + if (this.pending.get(id) === promise) this.pending.delete(id); + resolve(result); + }; + void this.run(id).then(finish, () => finish(unconfirmed())); + return promise; + } + + private async run(id: string): Promise { + const deadline = Date.now() + (this.options.timeoutMs ?? 5_000); + let evidence = this.evidence.get(id); + if (!evidence) { + // Capture the original durable state before beginEnd can write "ending". + evidence = { + prior: bounded( + call(() => this.options.store.lifecycle(id)), + deadline, + ).then((prior) => { + if (prior === undefined) throw new Error("End snapshot timed out"); + return prior; + }), + native: false, + terminal: false, + }; + this.evidence.set(id, evidence); + const owned = evidence; + void evidence.prior.catch(() => { + if (this.evidence.get(id) === owned) this.evidence.delete(id); + }); + } + const owned = evidence; + let beginning: ReturnType | undefined; + try { + beginning = this.options.lifecycle.beginEnd(id, evidence.prior); + } catch { + // Even a native retirement failure must not prevent Terminal cancellation. + } + const terminal = call(() => + this.options.sessionManager.closeWithResult(id), + ).then((result) => { + if (result.state === "confirmed") owned.terminal = true; + return result; + }); + // Both shutdown requests above run synchronously before this method awaits. + if (!beginning) { + await bounded(Promise.allSettled([evidence.prior, terminal]), deadline); + return unconfirmed(); + } + const native = beginning.native.then((result) => { + if (result.state === "confirmed") owned.native = true; + return result; + }); + const results = await bounded( + Promise.allSettled([ + evidence.prior, + beginning.persistence, + native, + terminal, + ] as const), + deadline, + ); + if (!results) return unconfirmed(); + const [prior, persistence, nativeResult, terminalResult] = results; + if ( + prior.status !== "fulfilled" || + persistence.status !== "fulfilled" || + nativeResult.status !== "fulfilled" || + terminalResult.status !== "fulfilled" || + nativeResult.value.state === "unconfirmed" || + terminalResult.value.state === "unconfirmed" + ) + return unconfirmed(); + // An old host's "ending" header carries unresolved process ownership. + // Absence in this boot cannot replace positive evidence for either engine. + if ( + prior.value?.lifecycle === "ending" && + (!owned.native || !owned.terminal) + ) + return unconfirmed(); + if (Date.now() >= deadline) return unconfirmed(); + try { + const lifecycle = await bounded( + this.options.lifecycle.finishEnd(beginning.fence), + deadline, + ); + return lifecycle ? { ok: true, lifecycle } : unconfirmed(); + } catch { + return unconfirmed(); + } + } +} diff --git a/packages/harness/src/core/assistant-lifecycle.test.ts b/packages/harness/src/core/assistant-lifecycle.test.ts index 114cad695..957433c2c 100644 --- a/packages/harness/src/core/assistant-lifecycle.test.ts +++ b/packages/harness/src/core/assistant-lifecycle.test.ts @@ -141,6 +141,19 @@ it("coalesces duplicate attach and rejects stale revisions without native work", expect(ensure).toHaveBeenCalledOnce(); }); +it("starts native retirement immediately while End waits for the original durable snapshot", async () => { + const attached = await coordinator.attach("studio-a", 0); + const held = gate(); + const read = vi.spyOn(store, "lifecycle"); + const ending = coordinator.beginEnd("studio-a", held.promise); + expect(abort.signal.aborted).toBe(true); + expect(read).not.toHaveBeenCalled(); + await expect(coordinator.use("studio-a", attached.lease)).rejects.toThrow(); + held.release(); + await ending.persistence; + expect(await store.lifecycle("studio-a")).toMatchObject({ lifecycle: "ending" }); +}); + it("rejects a late attach after End and retains its durable fence without eligibility", async () => { const held = gate(); associate.mockImplementationOnce(async () => { diff --git a/packages/harness/src/core/assistant-lifecycle.ts b/packages/harness/src/core/assistant-lifecycle.ts index 7bd589f3e..7a547cd55 100644 --- a/packages/harness/src/core/assistant-lifecycle.ts +++ b/packages/harness/src/core/assistant-lifecycle.ts @@ -264,15 +264,18 @@ export class AssistantLifecycleCoordinator { /** Fences execution and requests process termination before any persistence await. * The End orchestration owner must coalesce callers through its complete - * Terminal/native/persistence operation, including finishEnd or failure reporting. */ - beginEnd(id: string) { + * Terminal/native/persistence operation, including finishEnd or failure reporting. + * An optional original-state read delays writes only, never runtime retirement. */ + beginEnd(id: string, beforePersistence?: Promise) { const fence = { id, generation: this.generation(id) + 1 }; this.generations.set(id, fence.generation); this.ending.add(id); this.leases.delete(id); this.pending.delete(id); const native = this.options.host.retireWithResult(id); - const persistence = this.persistEnd(fence, "ending"); + const persistence = beforePersistence + ? beforePersistence.then(() => this.persistEnd(fence, "ending")) + : this.persistEnd(fence, "ending"); this.changed(); return { fence, native, persistence }; } diff --git a/packages/harness/src/core/assistant-state-projection.test.ts b/packages/harness/src/core/assistant-state-projection.test.ts index 2dab07ceb..9b728d793 100644 --- a/packages/harness/src/core/assistant-state-projection.test.ts +++ b/packages/harness/src/core/assistant-state-projection.test.ts @@ -47,6 +47,10 @@ it("orders lifecycle-only updates with observations and clears disabled projecti ); const initial = projection.get(); expect(parseAssistantState(initial)).toEqual(initial); + rows = [{ ...state, revision: 0, lifecycle: "open" }]; + expect(projection.get().lifecycles).toEqual([]); + rows = [{ ...state, revision: 0, lifecycle: "ending" }]; + expect(projection.get().lifecycles?.[0]?.lifecycle).toBe("ending"); rows = [{ ...state, revision: 3, lifecycle: "open" }]; changedLifecycle(); const resumed = publish.mock.lastCall![0] as AssistantStateSnapshot; diff --git a/packages/harness/src/core/assistant-state-projection.ts b/packages/harness/src/core/assistant-state-projection.ts index 848597184..b1ed247aa 100644 --- a/packages/harness/src/core/assistant-state-projection.ts +++ b/packages/harness/src/core/assistant-state-projection.ts @@ -15,7 +15,13 @@ export function createAssistantStateProjection( return { ...runtime, revision, - lifecycles: runtime.enabled ? lifecycle.snapshot() : [], + lifecycles: runtime.enabled + ? lifecycle + .snapshot() + .filter( + (state) => state.revision > 0 || state.lifecycle === "ending", + ) + : [], }; }; const changed = () => { diff --git a/packages/harness/src/server/index.ts b/packages/harness/src/server/index.ts index 7e9f92106..33b7243f3 100644 --- a/packages/harness/src/server/index.ts +++ b/packages/harness/src/server/index.ts @@ -198,6 +198,7 @@ import { IngestCredentialRegistry } from "../core/ingest-credentials.js"; import { AssistantAccess } from "../core/assistant-access.js"; import { AssistantSessionStore } from "../core/assistant-session-store.js"; import { AssistantLifecycleCoordinator } from "../core/assistant-lifecycle.js"; +import { AssistantEndCoordinator } from "../core/assistant-end.js"; import { createAssistantStateProjection } from "../core/assistant-state-projection.js"; import { OpenCodeAssociations } from "../core/opencode-association.js"; import { OpenCodeHost, type HostedOpenCode } from "../core/opencode-host.js"; @@ -3571,6 +3572,7 @@ export const startServer = async ( }); const openCodeAssociations = new OpenCodeAssociations(assistantSessions); const assistantLifecycle = new AssistantLifecycleCoordinator({ store: assistantSessions, host: openCodeHost, associations: openCodeAssociations }); + const assistantEnd = new AssistantEndCoordinator({ store: assistantSessions, lifecycle: assistantLifecycle, sessionManager }); // Hydrate lifecycle headers without launching runtimes. A corrupt entry fails // closed when selected rather than preventing unrelated sessions from loading. await Promise.allSettled(sessionManager.list().map((session) => assistantLifecycle.describe(session.id))); @@ -3635,6 +3637,7 @@ export const startServer = async ( "/api", createRestRouter({ getAssistantState, + endSession: (id) => assistantEnd.end(id), sessionManager, adapters, version: readVersion(), diff --git a/packages/harness/src/server/rest.test.ts b/packages/harness/src/server/rest.test.ts index 67f855160..e35eaef04 100644 --- a/packages/harness/src/server/rest.test.ts +++ b/packages/harness/src/server/rest.test.ts @@ -25,10 +25,12 @@ import type { import { ProjectSessionScopeUnavailableError, SessionBackgroundInputPreemptedError, + SessionCleanupUnconfirmedError, SessionInputIsolationError, SessionManager, SessionManagerClosingError, SessionNotReadyError, + SessionPreparationCancelledError, UnknownSessionError, } from "../core/session-manager.js"; import type { SessionRecordReader } from "../core/session-record.js"; @@ -65,6 +67,7 @@ function fakeSessionManager(initial: HarnessSession[] = []) { resume: vi.fn(), restartForMcpCredentials: vi.fn(), kill: vi.fn(() => true), + close: vi.fn(async () => true), write: vi.fn(() => true), submitInput: vi.fn(async () => true), setBoundWorkflowPath: vi.fn((id: string, workflowPath: string | null) => { @@ -346,6 +349,81 @@ describe("createRestRouter", () => { }); }); + it.each([ + new SessionPreparationCancelledError(), + new SessionCleanupUnconfirmedError(), + ])("returns 409 for cancelled or unconfirmed Terminal resume: $code", async (error) => { + const sessionManager = fakeSessionManager([exitedSession()]); + vi.mocked(sessionManager.resume).mockRejectedValue(error); + vi.mocked(sessionManager.restartForMcpCredentials).mockRejectedValue(error); + start({ sessionManager, adapters: { "claude-code": historyAdapter() } }); + for (const endpoint of ["sess-1/resume", "sess-1/restart-mcp", "adopt"]) { + const res = await fetch(`${baseUrl}/sessions/${endpoint}`, { + method: "POST", + headers: { ...TOKEN_HEADER, "Content-Type": "application/json" }, + ...(endpoint === "adopt" ? { body: JSON.stringify({ + agentSessionId: "agent-1", harness: "claude-code", cwd: "/tmp/proj", + title: "proj", lastActiveAt: "2026-01-01T00:00:00.000Z", + }) } : {}), + }); + expect(res.status).toBe(409); + expect(await res.json()).toEqual({ error: error.message, code: error.code }); + } + }); + + describe("DELETE /sessions/:id", () => { + it("keeps the legacy close path when no End coordinator is installed", async () => { + const sessionManager = fakeSessionManager([exitedSession()]); + start({ sessionManager }); + const res = await fetch(`${baseUrl}/sessions/sess-1`, { method: "DELETE", headers: TOKEN_HEADER }); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ ok: true }); + expect(sessionManager.close).toHaveBeenCalledExactlyOnceWith("sess-1"); + expect(sessionManager.get("sess-1")).toBeDefined(); + }); + + it("returns 404 before invoking End for an unknown row", async () => { + const endSession = vi.fn(); + start({ endSession }); + const res = await fetch(`${baseUrl}/sessions/missing`, { method: "DELETE", headers: TOKEN_HEADER }); + expect(res.status).toBe(404); + expect(endSession).not.toHaveBeenCalled(); + }); + + it("uses boot-authorized End without a current Assistant identity and keeps retained rows", async () => { + const sessionManager = fakeSessionManager([exitedSession()]); + const result = { ok: true as const, lifecycle: { + version: 1 as const, harnessSessionId: "sess-1", revision: 3, + lifecycle: "ended" as const, execution: "paused" as const, updatedAt: 1, + } }; + const endSession = vi.fn().mockResolvedValue(result); + start({ sessionManager, endSession, identity: null }); + const res = await fetch(`${baseUrl}/sessions/sess-1`, { method: "DELETE", headers: TOKEN_HEADER }); + expect(res.status).toBe(200); + expect(await res.json()).toEqual(result); + expect(endSession).toHaveBeenCalledExactlyOnceWith("sess-1"); + expect(sessionManager.close).not.toHaveBeenCalled(); + expect(sessionManager.get("sess-1")).toBeDefined(); + }); + + it("returns cleanup_unconfirmed without removing the selected row or same-folder history", async () => { + const a = exitedSession(); + const b = exitedSession({ id: "sess-2", agentSessionId: "agent-2" }); + const sessionManager = fakeSessionManager([a, b]); + const result = { ok: false as const, code: "cleanup_unconfirmed" as const, error: "Cleanup remains unconfirmed." }; + const endSession = vi.fn().mockResolvedValue(result); + start({ sessionManager, endSession, adapters: { "claude-code": historyAdapter() } }); + const res = await fetch(`${baseUrl}/sessions/sess-1`, { method: "DELETE", headers: TOKEN_HEADER }); + expect(res.status).toBe(409); + expect(await res.json()).toEqual(result); + expect(endSession).toHaveBeenCalledExactlyOnceWith("sess-1"); + expect(sessionManager.list()).toEqual([a, b]); + const history = await fetch(`${baseUrl}/sessions/history?cwd=${encodeURIComponent(a.cwd)}`); + const rows = await history.json() as SessionSummary[]; + expect(rows.map((row) => row.harnessSessionId).sort()).toEqual(["sess-1", "sess-2"]); + }); + }); + describe("GET/PATCH /settings", () => { it("returns defaults before anything is persisted", async () => { start(); diff --git a/packages/harness/src/server/rest.ts b/packages/harness/src/server/rest.ts index 0f7a21e7e..d4132e439 100644 --- a/packages/harness/src/server/rest.ts +++ b/packages/harness/src/server/rest.ts @@ -52,14 +52,17 @@ import { import { ProjectSessionScopeUnavailableError, SessionBackgroundInputPreemptedError, + SessionCleanupUnconfirmedError, SessionInputIsolationError, SessionManagerClosingError, SessionNotReadyError, + SessionPreparationCancelledError, UnknownSessionError, type SessionManager, } from "../core/session-manager.js"; import { normalizeCwd } from "./cwd-normalize.js"; import type { SessionRecordReader } from "../core/session-record.js"; +import type { AssistantEndResult } from "../core/assistant-end.js"; import { getHarnessAdapter, listHarnessAdapters, @@ -195,6 +198,9 @@ async function agentHoldsConversation( export interface RestRouterOptions { getAssistantState?: () => AssistantStateSnapshot; + /** Complete selected-session End, including native and Terminal cleanup. + * Uses the route's boot authorization independently of Assistant grant expiry. */ + endSession?: (id: string) => Promise; sessionManager: SessionManager; adapters: Partial>; version: string; @@ -725,6 +731,8 @@ export function createRestRouter(options: RestRouterOptions): Router { err instanceof McpSessionRestartUnavailableError || err instanceof ProjectSessionScopeUnavailableError || err instanceof SessionAlreadyLiveError || + err instanceof SessionPreparationCancelledError || + err instanceof SessionCleanupUnconfirmedError || err instanceof SessionNotResumeableError ) { res @@ -868,6 +876,11 @@ export function createRestRouter(options: RestRouterOptions): Router { return; } try { + if (options.endSession) { + const result = await options.endSession(req.params.id); + res.status(result.ok ? 200 : 409).json(result); + return; + } await sessionManager.close(req.params.id); res.json({ ok: true }); } catch (error) {