diff --git a/.changeset/dormant-terminal-start.md b/.changeset/dormant-terminal-start.md new file mode 100644 index 000000000..0dfbcb4e4 --- /dev/null +++ b/.changeset/dormant-terminal-start.md @@ -0,0 +1,5 @@ +--- +"@sapiom/harness": patch +--- + +Allow an explicit first Terminal start in a dormant Studio session, preserving its Studio and Assistant identities. Coalesce duplicate starts, revalidate workspace authority, and prevent End races or project bootstrap from starting unintended work. diff --git a/packages/harness/docs/dormant-terminal.md b/packages/harness/docs/dormant-terminal.md new file mode 100644 index 000000000..db6e77b59 --- /dev/null +++ b/packages/harness/docs/dormant-terminal.md @@ -0,0 +1,16 @@ +# Starting Terminal in a dormant session + +Recorded Continue allocates a Studio row with `terminalState: "not-started"`. +Its Assistant conversation can be prepared without launching a Terminal process. + +`POST /api/sessions/:id/terminal/start` with the boot token and an empty JSON +object explicitly starts the first Terminal in that same Studio session. The +server revalidates workspace/project authority and prepares current credentials. +It runs the normal adapter launch without an initial prompt, parent context, or +automatic project bootstrap. No workspace or launch overrides are accepted. + +Concurrent starts share one preparation. End cancels older preparation before +spawn; a failure before spawn keeps the not-started marker. The marker is removed +only when the first PTY is published. Assistant association remains unchanged. +Repeated calls while that allocated Terminal is live return it; after it exits, +use the ordinary Terminal Resume flow. Conflicts return 409, unknown IDs 404. diff --git a/packages/harness/src/core/session-manager-activate-dormant.test.ts b/packages/harness/src/core/session-manager-activate-dormant.test.ts new file mode 100644 index 000000000..62923aee2 --- /dev/null +++ b/packages/harness/src/core/session-manager-activate-dormant.test.ts @@ -0,0 +1,429 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { HarnessAdapter, HarnessSession } from "../shared/types.js"; +import { AssistantSessionStore } from "./assistant-session-store.js"; +import { IngestCredentialRegistry } from "./ingest-credentials.js"; +import { + SessionManager, + ProjectSessionScopeUnavailableError, + type PtySpawnFn, +} from "./session-manager.js"; + +function gate() { + let enter!: () => void, release!: () => void; + const entered = new Promise((done) => { + enter = done; + }); + const held = new Promise((done) => { + release = done; + }); + return { + entered, + release, + wait: async () => { + enter(); + await held; + }, + }; +} + +describe("explicit dormant Terminal activation", () => { + let root: string; + let manager: SessionManager; + let spawns: { + kill: ReturnType; + write: ReturnType; + exit: () => void; + }[]; + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), "activate-terminal-")); + spawns = []; + }); + afterEach(async () => { + spawns.forEach((spawn) => spawn.exit()); + await manager?.flush(); + await rm(root, { recursive: true, force: true }); + }); + + async function fixture() { + const path = join(root, "sessions.json"); + const identity = { + projectId: "project-1", + userId: "user-1", + sessionId: "parent", + }; + const parent: HarnessSession = { + id: "parent", + cwd: root, + harness: "claude-code", + title: "parent", + status: "exited", + ready: false, + agentSessionId: null, + boundWorkflowPath: null, + createdAt: "2020-01-01T00:00:00.000Z", + lastActiveAt: "2020-01-01T00:00:00.000Z", + agentMapIdentity: identity, + }; + await writeFile(path, JSON.stringify([parent])); + const authority = { + userId: identity.userId, + projectId: identity.projectId, + generation: 1, + }; + const resolver = vi.fn( + async (sessionId: string, cwd: string, persisted = identity) => { + if ( + cwd !== root || + persisted.userId !== authority.userId || + persisted.projectId !== authority.projectId || + persisted.sessionId !== sessionId + ) + throw new ProjectSessionScopeUnavailableError(sessionId); + return { ...persisted }; + }, + ); + const spawnPty = vi.fn(() => { + const listeners: (() => void)[] = []; + const exit = () => listeners.forEach((listener) => listener()); + const kill = vi.fn(exit), + write = vi.fn(); + spawns.push({ kill, write, exit }); + return { + pid: 900_001, + kill, + write, + resize: vi.fn(), + onData: () => ({ dispose: () => {} }), + onExit: (listener: (event: { exitCode: number }) => void) => { + listeners.push(() => listener({ exitCode: 0 })); + return { dispose: () => {} }; + }, + } as unknown as ReturnType; + }); + const hooks = { + buildLaunchOpts: vi.fn(async () => ({ + mcpCredentialLaunch: { + generation: authority.generation, + credentialBearing: true, + }, + initialPrompt: "never replay", + rehydratedFrom: "parent", + })), + writeWorkspaceContext: vi.fn(async () => {}), + ensureCanvasTemplate: vi.fn(async () => {}), + loadSpawnPty: vi.fn(async () => spawnPty), + onRuntimeEpochTransition: vi.fn(async () => {}), + prepareProjectSession: vi.fn(async () => ({})), + onProjectBootstrapSession: vi.fn(), + writeSessionRegistry: vi.fn(async (file: string, text: string) => { + await writeFile(file, text); + }), + }; + const spec = { command: "fake-terminal", args: [], env: {}, cwd: root }; + const adapter: HarnessAdapter = { + id: "claude-code", + eventSource: "hooks", + doctor: vi.fn(async () => []), + launch: vi.fn(() => spec), + resume: vi.fn(() => spec), + canResume: vi.fn(async () => true), + listPastSessions: vi.fn(async () => []), + }; + manager = new SessionManager({ + sessionsPath: path, + ingestUrl: "http://127.0.0.1:4100", + ingestCredentials: new IngestCredentialRegistry(() => "boot"), + adapters: { "claude-code": adapter }, + resolveAgentMapIdentity: resolver, + currentCredentialGeneration: () => authority.generation, + isPidAlive: () => false, + ...hooks, + }); + await manager.init(); + const child = await manager.allocateDormant("parent", { + childSessionId: "child", + harness: "claude-code", + expectedSource: { + cwd: root, + projectId: identity.projectId, + userId: identity.userId, + }, + }); + vi.clearAllMocks(); + return { child, adapter, hooks, resolver, spawnPty, authority, path }; + } + + it("coalesces the first start and preserves the child and Assistant association", async () => { + const { child, adapter, hooks, spawnPty, path } = await fixture(); + const store = new AssistantSessionStore(root); + const key = { + harnessSessionId: child.id, + contextAuthorityScope: "a".repeat(64), + cwd: root, + }; + const retained = await store.associate( + key, + "b".repeat(64), + async () => "ses_child", + ); + const held = gate(); + const initial = hooks.buildLaunchOpts.getMockImplementation()!; + hooks.buildLaunchOpts.mockImplementationOnce(async () => { + await held.wait(); + return initial(); + }); + const first = manager.activateDormant(child.id); + expect(manager.activateDormant(child.id)).toBe(first); + await held.entered; + expect(child.terminalState).toBe("not-started"); + held.release(); + expect(await first).toBe(child); + expect(await manager.activateDormant(child.id)).toBe(child); + expect(spawnPty).toHaveBeenCalledOnce(); + expect(hooks.buildLaunchOpts).toHaveBeenCalledWith( + child.id, + { cwd: root, harness: "claude-code" }, + { agentMapIdentity: child.agentMapIdentity, resume: true }, + ); + expect(adapter.launch).toHaveBeenCalledWith({ + harnessSessionId: child.id, + cwd: root, + }); + expect(adapter.resume).not.toHaveBeenCalled(); + expect(hooks.prepareProjectSession).not.toHaveBeenCalled(); + expect(hooks.onProjectBootstrapSession).not.toHaveBeenCalled(); + expect(spawns[0]!.write).not.toHaveBeenCalled(); + expect(child).toMatchObject({ + id: "child", + status: "running", + ready: false, + agentSessionId: null, + }); + expect(child.terminalState).toBeUndefined(); + expect( + JSON.parse(await readFile(path, "utf8"))[1].terminalState, + ).toBeUndefined(); + expect(await store.association(key)).toEqual(retained); + manager.setReady(child.id, manager.getRuntimeEpoch(child.id)!); + expect(child.ready).toBe(true); + }); + + it.each([ + "identity", + "persist", + "config", + "workspace", + "canvas", + "loader", + "epoch", + "authority", + ])("End fences activation paused in %s", async (stage) => { + const { child, hooks, resolver, spawnPty } = await fixture(); + const held = gate(); + const stages = { + persist: hooks.writeSessionRegistry, + config: hooks.buildLaunchOpts, + workspace: hooks.writeWorkspaceContext, + canvas: hooks.ensureCanvasTemplate, + loader: hooks.loadSpawnPty, + epoch: hooks.onRuntimeEpochTransition, + }; + if (stage === "identity" || stage === "authority") { + const original = resolver.getMockImplementation()!; + let calls = 0; + resolver.mockImplementation(async (...args) => { + if (++calls === (stage === "identity" ? 1 : 3)) await held.wait(); + return original(...args); + }); + } else { + const target = stages[stage as keyof typeof stages]; + const original = target.getMockImplementation()!; + target.mockImplementationOnce((async (...args: never[]) => { + await held.wait(); + return (original as (...args: never[]) => unknown)(...args); + }) as never); + } + const activating = manager.activateDormant(child.id); + await held.entered; + await manager.close(child.id); + held.release(); + await expect(activating).rejects.toMatchObject({ + code: "SESSION_PREPARATION_CANCELLED", + }); + expect(child.terminalState).toBe("not-started"); + expect(spawnPty).not.toHaveBeenCalled(); + if (["identity", "persist", "config"].includes(stage)) + expect(hooks.writeWorkspaceContext).not.toHaveBeenCalled(); + }); + + it.each([ + "persist", + "config", + "workspace", + "canvas", + "loader", + "epoch", + "spawn", + ])("a %s failure keeps a retryable dormant record", async (stage) => { + const { child, hooks, spawnPty } = await fixture(); + const lastActive = child.lastActiveAt; + const stages = { + persist: hooks.writeSessionRegistry, + config: hooks.buildLaunchOpts, + workspace: hooks.writeWorkspaceContext, + canvas: hooks.ensureCanvasTemplate, + loader: hooks.loadSpawnPty, + epoch: hooks.onRuntimeEpochTransition, + spawn: spawnPty, + }; + stages[stage as keyof typeof stages].mockImplementationOnce(() => { + throw new Error("activation fixture failure"); + }); + await expect(manager.activateDormant(child.id)).rejects.toThrow( + "activation fixture failure", + ); + expect(child).toMatchObject({ + terminalState: "not-started", + status: "exited", + lastActiveAt: lastActive, + }); + expect(manager.list()).toHaveLength(2); + await manager.activateDormant(child.id); + expect(spawns).toHaveLength(1); + expect(child.terminalState).toBeUndefined(); + }); + + it("revalidates authority and credentials at the final PTY boundary", async () => { + const { child, hooks, authority, spawnPty } = await fixture(); + authority.userId = "other-user"; + await expect(manager.activateDormant(child.id)).rejects.toBeInstanceOf( + ProjectSessionScopeUnavailableError, + ); + authority.userId = "user-1"; + const held = gate(); + hooks.onRuntimeEpochTransition.mockImplementationOnce(held.wait); + const activating = manager.activateDormant(child.id); + await held.entered; + authority.generation = 2; + held.release(); + await expect(activating).rejects.toMatchObject({ + code: "MCP_CREDENTIAL_GENERATION_CHANGED", + }); + expect(spawnPty).not.toHaveBeenCalled(); + await manager.activateDormant(child.id); + expect(child.mcpAuthState).toBe("current"); + }); + + it("cleans up a real PTY when its running-state write fails without claiming it never started", async () => { + const { child, hooks, spawnPty } = await fixture(); + const original = hooks.writeSessionRegistry.getMockImplementation()!; + hooks.writeSessionRegistry.mockImplementation(async (file, text) => { + if ( + JSON.parse(text).some( + (row: HarnessSession) => + row.id === child.id && row.status === "running", + ) + ) + throw new Error("running-state write failed"); + await original(file, text); + }); + await expect(manager.activateDormant(child.id)).rejects.toThrow( + "running-state write failed", + ); + expect(child.terminalState).toBeUndefined(); + expect(child.status).toBe("exited"); + expect((await manager.closeWithResult(child.id)).state).toBe("confirmed"); + await expect(manager.activateDormant(child.id)).rejects.toMatchObject({ + code: "SESSION_NOT_DORMANT", + }); + expect(spawnPty).toHaveBeenCalledOnce(); + }); + + it("End observes the started PTY while its first running-state persistence is pending", async () => { + const { child, hooks, spawnPty, path } = await fixture(); + const held = gate(), + original = hooks.writeSessionRegistry.getMockImplementation()!; + hooks.writeSessionRegistry.mockImplementation(async (file, text) => { + if ( + JSON.parse(text).some( + (row: HarnessSession) => + row.id === child.id && row.status === "running", + ) + ) + await held.wait(); + await original(file, text); + }); + const activating = manager.activateDormant(child.id); + await held.entered; + const epoch = manager.getRuntimeEpoch(child.id); + expect(child.terminalState).toBeUndefined(); + expect(await manager.closeWithResult(child.id)).toEqual({ + state: "confirmed", + runtimeEpoch: epoch, + }); + held.release(); + await expect(activating).rejects.toMatchObject({ + code: "SESSION_PREPARATION_CANCELLED", + }); + await manager.flush(); + expect(JSON.parse(await readFile(path, "utf8"))[1]).toMatchObject({ + id: child.id, + status: "exited", + }); + expect(spawnPty).toHaveBeenCalledOnce(); + await expect(manager.activateDormant(child.id)).rejects.toMatchObject({ + code: "SESSION_NOT_DORMANT", + }); + }); + + it.each(["principal", "project", "root"])( + "rejects changed %s authority after epoch persistence", + async (change) => { + const { child, hooks, authority, spawnPty } = await fixture(); + const held = gate(); + hooks.onRuntimeEpochTransition.mockImplementationOnce(held.wait); + const activating = manager.activateDormant(child.id); + await held.entered; + if (change === "principal") authority.userId = "other-user"; + if (change === "project") authority.projectId = "other-project"; + if (change === "root") child.cwd = join(root, "other-root"); + held.release(); + await expect(activating).rejects.toBeInstanceOf( + ProjectSessionScopeUnavailableError, + ); + expect(child.terminalState).toBe("not-started"); + expect(spawnPty).not.toHaveBeenCalled(); + }, + ); + + it("rejects generic Resume and unallocated rows, and blocks activation after shutdown begins", async () => { + const { child, hooks, spawnPty } = await fixture(); + await expect(manager.resume(child.id)).rejects.toMatchObject({ + code: "SESSION_NOT_RESUMEABLE", + }); + manager.get("parent")!.terminalState = "not-started"; + await expect(manager.activateDormant("parent")).rejects.toMatchObject({ + code: "SESSION_NOT_DORMANT", + }); + const held = gate(), + original = hooks.buildLaunchOpts.getMockImplementation()!; + hooks.buildLaunchOpts.mockImplementationOnce(async () => { + await held.wait(); + return original(); + }); + const activating = manager.activateDormant(child.id); + await held.entered; + manager.beginShutdown(); + await expect(manager.activateDormant(child.id)).rejects.toMatchObject({ + code: "SESSION_MANAGER_CLOSING", + }); + held.release(); + await expect(activating).rejects.toMatchObject({ + code: "SESSION_MANAGER_CLOSING", + }); + expect(spawnPty).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/harness/src/core/session-manager.ts b/packages/harness/src/core/session-manager.ts index 267d7e069..d6b845a8e 100644 --- a/packages/harness/src/core/session-manager.ts +++ b/packages/harness/src/core/session-manager.ts @@ -725,6 +725,15 @@ export class SessionCleanupUnconfirmedError extends Error { } } +/** Start Terminal applies only to allocated sessions whose first PTY has not run. */ +export class SessionNotDormantError extends Error { + readonly code = "SESSION_NOT_DORMANT"; + constructor() { + super("this Studio session is not awaiting its first Terminal start"); + this.name = "SessionNotDormantError"; + } +} + export type AdapterIdentityState = | "not-required" | "pending" @@ -1025,6 +1034,13 @@ export class SessionManager { private readonly confirmedCleanupEpochs = new Map(); private readonly dormantAllocations = new Map(); private dormantAllocationsLoaded = false; + private readonly dormantActivations = new Map< + string, + { + generation: number; + promise: Promise; + } + >(); private readonly retiringKillRetries = new WeakMap< PtyHandle, Promise @@ -1618,6 +1634,147 @@ export class SessionManager { }); } + /** Explicit first Terminal start; duplicate requests share this exact generation. */ + activateDormant(id: string): Promise { + if (this.closing) return Promise.reject(new SessionManagerClosingError()); + const generation = this.closeGenerations.get(id) ?? 0; + const existing = this.dormantActivations.get(id); + if (existing) + return existing.generation === generation + ? existing.promise + : Promise.reject(new SessionPreparationCancelledError()); + const promise = this.activateDormantPrepared(id, generation); + const entry = { generation, promise }; + this.dormantActivations.set(id, entry); + const forget = (): void => { + if (this.dormantActivations.get(id) === entry) + this.dormantActivations.delete(id); + }; + void promise.then(forget, forget); + return promise; + } + + private async activateDormantPrepared( + id: string, + generation: number, + ): Promise { + this.assertAdmission(id, generation); + const session = this.sessions.get(id); + if (!session) throw new UnknownSessionError(id); + const { cwd, harness } = session; + const identity = session.agentMapIdentity && { + ...session.agentMapIdentity, + }; + const check = (): void => { + this.assertAdmission(id, generation); + if ( + !identity || + !this.resolveAgentMapIdentity || + identity.sessionId !== id || + this.sessions.get(id) !== session || + session.cwd !== cwd || + session.harness !== harness || + !session.agentMapIdentity || + !sameProjectAgent(session.agentMapIdentity, identity) || + this.rejectedProjectSessionMetadata.has(id) + ) + throw new ProjectSessionScopeUnavailableError(id); + }; + const authorize = async (): Promise => { + check(); + await this.revalidateAgentMapIdentity(id, cwd, identity); + check(); + }; + await this.loadDormantAllocations(); + check(); + if ( + !this.dormantAllocations.has(id) || + this.subsessionBindings.has(id) || + session.projectBootstrap + ) + throw new SessionNotDormantError(); + const live = this.ptys.get(id); + if (live && !live.killed && session.terminalState === undefined) { + await authorize(); + if (this.ptys.get(id) !== live || live.killed) + throw new SessionNotDormantError(); + return session; + } + if ( + session.terminalState !== "not-started" || + session.agentSessionId !== null + ) + throw new SessionNotDormantError(); + return this.prepareSession( + id, + async () => { + await authorize(); + const previousActivity = session.lastActiveAt; + session.status = "starting"; + session.ready = false; + session.exitCode = null; + session.lastActiveAt = this.now(); + try { + await this.persist(); + check(); + this.emitStatus(session); + // The existing resume preparation flag skips first-request scaffolding + // and rotates capabilities. The adapter still receives a fresh launch. + const { mcpCredentialLaunch, ...opts } = await this.buildLaunchOpts( + id, + { + cwd, + harness, + ...(session.theme ? { theme: session.theme } : {}), + }, + { agentMapIdentity: identity, resume: true }, + ); + check(); + delete opts.initialPrompt; + delete opts.rehydratedFrom; + const spec = this.getAdapter(harness).launch({ + ...opts, + harnessSessionId: id, + cwd, + }); + await this.writeWorkspaceContext(session); + check(); + await this.ensureCanvasTemplate(cwd); + check(); + await this.spawn( + session, + spec, + generation, + mcpCredentialLaunch, + async () => { + await authorize(); + if ( + session.terminalState !== "not-started" || + session.agentSessionId !== null + ) + throw new SessionNotDormantError(); + }, + ); + check(); + return session; + } catch (error) { + // Preparation ownership excludes a replacement until this finally settles. + // If spawn succeeded but its durable publication failed, stop only our PTY. + const owned = this.ptys.get(id); + if (owned) await this.killIfRuntime(id, owned.runtimeEpoch); + if (session.terminalState === "not-started") { + session.lastActiveAt = previousActivity; + await this.transitionExited(session, null, { + stampLastActive: false, + }).catch(() => {}); + } + throw error; + } + }, + generation, + ); + } + private async loadDormantAllocations(): Promise { if (this.dormantAllocationsLoaded) return; const value = await readAssistantJson( @@ -1733,7 +1890,8 @@ export class SessionManager { if (this.closing) throw new SessionManagerClosingError(); const session = this.sessions.get(id); if (!session) throw new UnknownSessionError(id); - if (!session.agentSessionId) throw new SessionNotResumeableError(id); + if (session.terminalState === "not-started" || !session.agentSessionId) + throw new SessionNotResumeableError(id); return this.prepareSession(id, (generation) => this.resumePrepared(id, trusted, generation), ); @@ -3268,6 +3426,7 @@ export class SessionManager { this.confirmedCleanupEpochs.delete(session.id); this.ptys.set(session.id, handle); + delete session.terminalState; session.status = "running"; session.mcpAuthState = mcpCredentialLaunch && this.currentCredentialGeneration @@ -3278,10 +3437,9 @@ export class SessionManager { // way (trust dialogs can reappear, e.g. under different sandbox flags). session.ready = false; session.lastActiveAt = this.now(); - await this.persist(); - this.emitStatus(session); pty.onData((chunk) => { + if (this.ptys.get(session.id) !== handle) return; handle.bracketedPaste = trackBracketedPaste(handle.bracketedPaste, chunk); handle.buffer = (handle.buffer + chunk).slice(-SCROLLBACK_BYTES); this.recordReadinessOutput(handle, chunk, adapter); @@ -3291,6 +3449,8 @@ export class SessionManager { pty.onExit(({ exitCode }) => this.markExited(session.id, handle, exitCode)); + await this.persist(); + this.emitStatus(session); this.armReadyFallback(session.id, handle); } diff --git a/packages/harness/src/server/rest.test.ts b/packages/harness/src/server/rest.test.ts index e35eaef04..4a2f30860 100644 --- a/packages/harness/src/server/rest.test.ts +++ b/packages/harness/src/server/rest.test.ts @@ -30,6 +30,7 @@ import { SessionManager, SessionManagerClosingError, SessionNotReadyError, + SessionNotDormantError, SessionPreparationCancelledError, UnknownSessionError, } from "../core/session-manager.js"; @@ -65,6 +66,7 @@ function fakeSessionManager(initial: HarnessSession[] = []) { ), create: vi.fn(), resume: vi.fn(), + activateDormant: vi.fn(), restartForMcpCredentials: vi.fn(), kill: vi.fn(() => true), close: vi.fn(async () => true), @@ -371,6 +373,27 @@ describe("createRestRouter", () => { } }); + it("starts only the known dormant Terminal without browser launch overrides", async () => { + const sessionManager = fakeSessionManager([exitedSession()]); + vi.mocked(sessionManager.activateDormant).mockResolvedValue({ ...exitedSession(), status: "running" }); + start({ sessionManager }); + const request = (body: unknown = {}) => fetch(`${baseUrl}/sessions/sess-1/terminal/start`, { method: "POST", headers: { ...TOKEN_HEADER, "Content-Type": "application/json" }, body: JSON.stringify(body) }); + expect((await request({ cwd: "/other" })).status).toBe(400); + expect((await request([])).status).toBe(400); + expect(sessionManager.activateDormant).not.toHaveBeenCalled(); + const response = await request(); + expect(response.status).toBe(200); + expect(sessionManager.activateDormant).toHaveBeenCalledWith("sess-1"); + expect(sessionManager.create).not.toHaveBeenCalled(); + expect(sessionManager.resume).not.toHaveBeenCalled(); + for (const error of [new SessionNotDormantError(), new SessionPreparationCancelledError(), new SessionCleanupUnconfirmedError()]) { + vi.mocked(sessionManager.activateDormant).mockRejectedValueOnce(error); + expect((await request()).status).toBe(409); + } + vi.mocked(sessionManager.activateDormant).mockRejectedValueOnce(new UnknownSessionError("sess-1")); + expect((await request()).status).toBe(404); + }); + describe("DELETE /sessions/:id", () => { it("keeps the legacy close path when no End coordinator is installed", async () => { const sessionManager = fakeSessionManager([exitedSession()]); diff --git a/packages/harness/src/server/rest.ts b/packages/harness/src/server/rest.ts index d4132e439..b4502ac01 100644 --- a/packages/harness/src/server/rest.ts +++ b/packages/harness/src/server/rest.ts @@ -56,6 +56,7 @@ import { SessionInputIsolationError, SessionManagerClosingError, SessionNotReadyError, + SessionNotDormantError, SessionPreparationCancelledError, UnknownSessionError, type SessionManager, @@ -733,6 +734,7 @@ export function createRestRouter(options: RestRouterOptions): Router { err instanceof SessionAlreadyLiveError || err instanceof SessionPreparationCancelledError || err instanceof SessionCleanupUnconfirmedError || + err instanceof SessionNotDormantError || err instanceof SessionNotResumeableError ) { res @@ -869,6 +871,16 @@ export function createRestRouter(options: RestRouterOptions): Router { } }); + router.post("/sessions/:id/terminal/start", async (req, res, next) => { + const input = req.body ?? {}; + if (typeof input !== "object" || Array.isArray(input) || Object.keys(input).length || Object.keys(req.query).length) { + res.status(400).json({ error: "Start Terminal does not accept launch overrides" }); + return; + } + try { res.json(await sessionManager.activateDormant(req.params.id)); } + catch (error) { if (!sendResumeError(res, error)) next(error); } + }); + router.delete("/sessions/:id", async (req, res, next) => { const existed = sessionManager.get(req.params.id) !== undefined; if (!existed) {