diff --git a/.changeset/paused-assistant-reopen.md b/.changeset/paused-assistant-reopen.md new file mode 100644 index 000000000..0aea04959 --- /dev/null +++ b/.changeset/paused-assistant-reopen.md @@ -0,0 +1,5 @@ +--- +"@sapiom/harness": patch +--- + +Bind Assistant requests to the current Studio lifecycle and restore newly started runtimes paused. Reopening Studio does not automatically recover earlier work; an explicit message enables execution. Include lifecycle changes in ordered Studio state updates and fence both managed engines during shutdown. diff --git a/packages/harness/src/core/assistant-lifecycle.test.ts b/packages/harness/src/core/assistant-lifecycle.test.ts index c94339854..114cad695 100644 --- a/packages/harness/src/core/assistant-lifecycle.test.ts +++ b/packages/harness/src/core/assistant-lifecycle.test.ts @@ -280,3 +280,21 @@ it("keeps unresolved End durable across coordinator restart and global shutdown await expect(coordinator.attach("studio-b", 0)).rejects.toThrow(); expect(ensure).not.toHaveBeenCalled(); }); + +it("rejects new attaches during shutdown while old association IO ignores cancellation", async () => { + const held = gate(); + associate.mockImplementationOnce(async () => { + await held.promise; + return "ses_history"; + }); + const old = coordinator.attach("studio-a", 0); + const rejected = expect(old).rejects.toThrow(); + await vi.waitFor(() => expect(associate).toHaveBeenCalledOnce()); + coordinator.beginShutdown(); + await expect(coordinator.attach("studio-a", 0)).rejects.toMatchObject({ + failure: { code: "lifecycle_changed" }, + }); + expect(ensure).toHaveBeenCalledOnce(); + held.release(); + await rejected; +}); diff --git a/packages/harness/src/core/assistant-lifecycle.ts b/packages/harness/src/core/assistant-lifecycle.ts index 97d8fb70c..7bd589f3e 100644 --- a/packages/harness/src/core/assistant-lifecycle.ts +++ b/packages/harness/src/core/assistant-lifecycle.ts @@ -122,7 +122,11 @@ export class AssistantLifecycleCoordinator { } attach(id: string, expectedRevision: number): Promise { - if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0) + if ( + this.closed || + !Number.isSafeInteger(expectedRevision) || + expectedRevision < 0 + ) return Promise.reject(failure("lifecycle_changed")); const pending = this.pending.get(id); if (pending) @@ -305,6 +309,7 @@ export class AssistantLifecycleCoordinator { beginShutdown(): void { this.closed = true; this.leases.clear(); + this.pending.clear(); this.options.host.beginShutdown(); this.changed(); } diff --git a/packages/harness/src/core/assistant-state-projection.test.ts b/packages/harness/src/core/assistant-state-projection.test.ts new file mode 100644 index 000000000..2dab07ceb --- /dev/null +++ b/packages/harness/src/core/assistant-state-projection.test.ts @@ -0,0 +1,82 @@ +import { expect, it, vi } from "vitest"; +import type { AssistantLifecycle } from "../shared/assistant-session.js"; +import { + parseAssistantState, + type AssistantStateSnapshot, +} from "../shared/assistant-state.js"; +import { createAssistantStateProjection } from "./assistant-state-projection.js"; + +const state: AssistantLifecycle = { + version: 1, + harnessSessionId: "studio-a", + revision: 2, + lifecycle: "ended", + execution: "paused", + updatedAt: 10, +}; +const runtime: AssistantStateSnapshot = { + hostInstanceId: "host-a", + authorityRevision: "grant-a", + revision: 45, + enabled: true, + sessions: [], +}; +it("orders lifecycle-only updates with observations and clears disabled projections", () => { + let changedHost!: () => void, changedLifecycle!: () => void; + let native = runtime; + let rows = [state]; + const stopHost = vi.fn(), + stopLifecycle = vi.fn(), + publish = vi.fn(); + const projection = createAssistantStateProjection( + { + getAssistantState: () => native, + subscribeAssistantState: (fn) => { + changedHost = fn; + return stopHost; + }, + }, + { + snapshot: () => rows, + subscribe: (fn) => { + changedLifecycle = fn; + return stopLifecycle; + }, + }, + publish, + ); + const initial = projection.get(); + expect(parseAssistantState(initial)).toEqual(initial); + rows = [{ ...state, revision: 3, lifecycle: "open" }]; + changedLifecycle(); + const resumed = publish.mock.lastCall![0] as AssistantStateSnapshot; + expect(resumed.revision).toBeGreaterThan(initial.revision); + expect(resumed.lifecycles?.[0]?.lifecycle).toBe("open"); + native = { + ...native, + enabled: false, + authorityRevision: "grant-b", + revision: 46, + }; + changedHost(); + const revoked = publish.mock.lastCall![0] as AssistantStateSnapshot; + expect(revoked.revision).toBeGreaterThan(resumed.revision); + expect(revoked.lifecycles).toEqual([]); + expect(parseAssistantState(revoked)).toEqual(revoked); + projection.dispose(); + expect(stopHost).toHaveBeenCalledOnce(); + expect(stopLifecycle).toHaveBeenCalledOnce(); +}); +it.each([ + [{ ...state, lease: "private" }], + [{ ...state, execution: "enabled" }], + [{ ...state, revision: -1 }], + [{ ...state, harnessSessionId: "../private" }], + [state, state], + null, +])( + "rejects malformed or contradictory lifecycle projection %j", + (lifecycles) => { + expect(parseAssistantState({ ...runtime, lifecycles })).toBeNull(); + }, +); diff --git a/packages/harness/src/core/assistant-state-projection.ts b/packages/harness/src/core/assistant-state-projection.ts new file mode 100644 index 000000000..848597184 --- /dev/null +++ b/packages/harness/src/core/assistant-state-projection.ts @@ -0,0 +1,34 @@ +import type { AssistantStateSnapshot } from "../shared/assistant-state.js"; +import type { AssistantLifecycleCoordinator } from "./assistant-lifecycle.js"; +import type { OpenCodeHost } from "./opencode-host.js"; + +/** One ordering clock for runtime observations and durable lifecycle changes. */ +export function createAssistantStateProjection( + host: Pick, + lifecycle: Pick, + publish: (snapshot: AssistantStateSnapshot) => void, +) { + let revision = 0; + const get = (): AssistantStateSnapshot => { + // Reading access may synchronously revoke it and notify host subscribers. + const runtime = host.getAssistantState(); + return { + ...runtime, + revision, + lifecycles: runtime.enabled ? lifecycle.snapshot() : [], + }; + }; + const changed = () => { + revision++; + publish(get()); + }; + const stopHost = host.subscribeAssistantState(changed); + const stopLifecycle = lifecycle.subscribe(changed); + return { + get, + dispose: () => { + stopHost(); + stopLifecycle(); + }, + }; +} diff --git a/packages/harness/src/server/index.ts b/packages/harness/src/server/index.ts index ea5238d79..9faeb8265 100644 --- a/packages/harness/src/server/index.ts +++ b/packages/harness/src/server/index.ts @@ -197,6 +197,8 @@ import { 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 { createAssistantStateProjection } from "../core/assistant-state-projection.js"; import { OpenCodeAssociations } from "../core/opencode-association.js"; import { OpenCodeHost, type HostedOpenCode } from "../core/opencode-host.js"; import { AssistantRecordStore } from "../core/assistant-record-store.js"; @@ -3566,10 +3568,15 @@ export const startServer = async ( stateRoot: statePaths.root, authorize: authorizeAssistantWorkspace, }); - const getAssistantState = () => openCodeHost.getAssistantState(); - const unsubscribeAssistant = openCodeHost.subscribeAssistantState(() => - bus.publish({ type: "assistant.state", snapshot: getAssistantState() }), + const openCodeAssociations = new OpenCodeAssociations(assistantSessions); + const assistantLifecycle = new AssistantLifecycleCoordinator({ store: assistantSessions, host: openCodeHost, associations: openCodeAssociations }); + // 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))); + const assistantProjection = createAssistantStateProjection(openCodeHost, assistantLifecycle, (snapshot) => + bus.publish({ type: "assistant.state", snapshot }), ); + const getAssistantState = assistantProjection.get; const app: Express = express(); app.disable("x-powered-by"); app.use("/opencode-runtime", openCodeBridge.router); @@ -3585,8 +3592,12 @@ export const startServer = async ( getEnvironment: () => assistantAccess.get()?.environment ?? null, loadSystemPrompt: options.loadSystemPrompt, }), - new OpenCodeAssociations(assistantSessions), - new OpenCodeFinalResponse({ onPersisted: async (hosted) => { await recordCaptures.get(hosted)?.checkpoint(); } }), + openCodeAssociations, + new OpenCodeFinalResponse({ + assertCurrent: (hosted) => assistantLifecycle.assertRuntime(hosted, true), + onPersisted: async (hosted) => { await recordCaptures.get(hosted)?.checkpoint(); }, + }), + assistantLifecycle, ), ); @@ -4321,11 +4332,14 @@ export const startServer = async ( credentialStoreObserver?.close(); unsubscribeCredentialChanges(); + // Fence both engines synchronously. Native ownership cleanup can wait on + // process proof and must not leave Terminal admission open during that wait. + assistantLifecycle.beginShutdown(); + sessionManager.beginShutdown(); assistantAccess.close(); - await settle(() => openCodeHost.close()); - unsubscribeAssistant(); + const nativeClosing = settle(() => openCodeHost.close()); + assistantProjection.dispose(); openCodeBridge.close(); - await settle(() => sessionManager.beginShutdown()); const bootstrapClosing = settle(() => projectBootstrap?.close()); const registrationClosing = settle(() => createdAgentRegistration.close()); coordinatorActive = false; @@ -4353,6 +4367,7 @@ export const startServer = async ( // socket if an adapter misses its own exit acknowledgement. const SHUTDOWN_KILL_TIMEOUT_MS = 5_000; const killsSettled = Promise.all([ + nativeClosing, settle(() => sessionManager.killAll()), settle(() => taskManager.killAll()), ]).then(() => {}); diff --git a/packages/harness/src/shared/assistant-session.ts b/packages/harness/src/shared/assistant-session.ts index a181bd325..e01521433 100644 --- a/packages/harness/src/shared/assistant-session.ts +++ b/packages/harness/src/shared/assistant-session.ts @@ -14,3 +14,36 @@ export interface AssistantSessionView extends Omit< history: "available" | "partial" | "missing" | "unavailable"; nativeResume: "unchecked" | "available" | "missing" | "unavailable"; } + +/** Strict public lifecycle decoding; a descriptor never carries execution credentials. */ +export function parseAssistantLifecycle( + value: unknown, +): AssistantLifecycle | null { + if (!value || typeof value !== "object" || Array.isArray(value)) return null; + const row = value as Record; + if ( + Object.keys(row).some( + (key) => + ![ + "version", + "harnessSessionId", + "revision", + "lifecycle", + "execution", + "updatedAt", + ].includes(key), + ) || + row.version !== 1 || + typeof row.harnessSessionId !== "string" || + !/^[A-Za-z0-9_-]{1,256}$/.test(row.harnessSessionId) || + !Number.isSafeInteger(row.revision) || + (row.revision as number) < 0 || + !Number.isSafeInteger(row.updatedAt) || + (row.updatedAt as number) < 0 || + !["open", "ending", "ended"].includes(row.lifecycle as string) || + !["enabled", "paused"].includes(row.execution as string) || + (row.lifecycle !== "open" && row.execution !== "paused") + ) + return null; + return { ...row } as unknown as AssistantLifecycle; +} diff --git a/packages/harness/src/shared/assistant-state.ts b/packages/harness/src/shared/assistant-state.ts index fbbcf7b7d..2be1faa18 100644 --- a/packages/harness/src/shared/assistant-state.ts +++ b/packages/harness/src/shared/assistant-state.ts @@ -2,6 +2,10 @@ import { parseOpenCodeTransportFailure, type OpenCodeTransportFailure, } from "./opencode-errors.js"; +import { + parseAssistantLifecycle, + type AssistantLifecycle, +} from "./assistant-session.js"; export interface AssistantSessionSummary { harnessSessionId: string; @@ -18,6 +22,7 @@ export interface AssistantStateSnapshot { revision: number; enabled: boolean; sessions: readonly AssistantSessionSummary[]; + lifecycles?: readonly AssistantLifecycle[]; } export type AssistantObservation = Omit< AssistantSessionSummary, @@ -53,6 +58,7 @@ export function parseAssistantState( "revision", "enabled", "sessions", + "lifecycles", ]); if ( !input || @@ -110,11 +116,27 @@ export function parseAssistantState( ...(failure ? { failure } : {}), }); } + const lifecycles: AssistantLifecycle[] = []; + if (input.lifecycles !== undefined) { + if ( + !Array.isArray(input.lifecycles) || + (!input.enabled && input.lifecycles.length) + ) + return null; + const identities = new Set(); + for (const raw of input.lifecycles) { + const lifecycle = parseAssistantLifecycle(raw); + if (!lifecycle || identities.has(lifecycle.harnessSessionId)) return null; + identities.add(lifecycle.harnessSessionId); + lifecycles.push(lifecycle); + } + } return { hostInstanceId: input.hostInstanceId, authorityRevision: input.authorityRevision, revision: input.revision, enabled: input.enabled, sessions, + ...(input.lifecycles !== undefined ? { lifecycles } : {}), }; } diff --git a/packages/harness/web/e2e/opencode-chat.spec.ts b/packages/harness/web/e2e/opencode-chat.spec.ts index 0078b65d1..c379568bc 100644 --- a/packages/harness/web/e2e/opencode-chat.spec.ts +++ b/packages/harness/web/e2e/opencode-chat.spec.ts @@ -1,6 +1,8 @@ import { expect, test, type Page } from "@playwright/test"; import express, { type Response } from "express"; import type { Server } from "node:http"; +import { randomUUID } from "node:crypto"; +import type { AssistantLifecycle } from "../../src/shared/assistant-session"; import { openCodeCompletionPrompt } from "../../src/shared/opencode-completion"; import { openCodeTransportFailure } from "../../src/shared/opencode-errors"; @@ -8,6 +10,7 @@ import { openCodeTransportFailure } from "../../src/shared/opencode-errors"; test.describe.configure({ mode: "serial" }); type Conversation = { id: string; + lease: string; turns: Array<{ info: Record; parts: Array>; @@ -35,6 +38,23 @@ let accessCalls: number; let recoveryReply: ((text: string, agent?: string) => void) | undefined; const historyReplies: Array<() => void> = []; let routeCalls: number; +let lifecycleState: AssistantLifecycle["lifecycle"]; +let execution: AssistantLifecycle["execution"]; +let lifecycleRevision: number; +let endBeforeAttach: boolean; +let holdAttach: boolean; +let holdPromptPublication: boolean; +let holdPromptAck: boolean; +let announceExecution: boolean; +const attachReplies: Array<() => void> = []; +const promptPublications: Array<() => void> = []; +const promptAcks: Array<() => void> = []; +const attachRevisions: number[] = []; +const leasedRequests: Array<{ + path: string; + actual: string | undefined; + expected: string; +}> = []; const conversations = new Map(); const emit = (c: Conversation, type: string, properties: object) => { if (type === "session.status") @@ -75,12 +95,24 @@ test.beforeEach(async ({ page }) => { recoveryReply = undefined; historyReplies.length = 0; routeCalls = 0; + lifecycleState = "open"; + execution = "enabled"; + lifecycleRevision = 0; + endBeforeAttach = holdAttach = holdPromptPublication = holdPromptAck = false; + announceExecution = true; + attachReplies.length = + promptPublications.length = + promptAcks.length = + attachRevisions.length = + leasedRequests.length = + 0; const app = express(); app.use(express.json()); app.use((req, res, next) => { res.set({ "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "*", + "Access-Control-Expose-Headers": "X-Assistant-Execution", }); if (req.method === "OPTIONS") { res.end(); @@ -94,11 +126,41 @@ test.beforeEach(async ({ page }) => { res.status(401).end(); return; } + const path = req.params[0]; + const lifecycle: AssistantLifecycle = { + version: 1, + harnessSessionId: req.params.studioId, + revision: lifecycleRevision, + lifecycle: lifecycleState, + execution, + updatedAt: 1, + }; + if (path === "lifecycle") { + res.json(lifecycle); + if (endBeforeAttach) { + lifecycleState = "ended"; + lifecycleRevision++; + } + return; + } + if (path === "attach") { + attachRevisions.push(req.body.expectedRevision); + if ( + req.body.expectedRevision !== lifecycleRevision || + lifecycleState !== "open" + ) { + res + .status(409) + .json({ error: openCodeTransportFailure("lifecycle_changed") }); + return; + } + } const id = `ses_${req.params.studioId.replaceAll("-", "_")}`; let c = conversations.get(id); if (!c) { c = { id, + lease: randomUUID(), turns: [], streams: new Set(), prompts: [], @@ -108,7 +170,6 @@ test.beforeEach(async ({ page }) => { }; conversations.set(id, c); } - const path = req.params[0]; const session = { id, title: "Studio conversation", @@ -119,7 +180,23 @@ test.beforeEach(async ({ page }) => { res.status(503).json(attachError); return; } - res.status(failAttach ? 502 : 200).json({ conversationId: id }); + const reply = () => + res + .status(failAttach ? 502 : 200) + .json({ conversationId: id, lease: c!.lease, lifecycle }); + if (holdAttach) attachReplies.push(reply); + else reply(); + return; + } + leasedRequests.push({ + path, + actual: req.header("X-Assistant-Lease"), + expected: c.lease, + }); + if (req.header("X-Assistant-Lease") !== c.lease) { + res + .status(409) + .json({ error: openCodeTransportFailure("lifecycle_changed") }); return; } if (path === "experimental/session") { @@ -262,21 +339,30 @@ test.beforeEach(async ({ page }) => { }, ], }; - c.turns.push(user, assistant); - res.status(204).end(); - emit(c, "session.status", { sessionID: id, status: { type: "busy" } }); - for (const turn of [user, assistant]) { - emit(c, "message.updated", { info: turn.info }); - emit(c, "message.part.updated", { part: turn.parts[0] }); - } - assistant.parts[0].text = "First chunk"; - emit(c, "message.part.delta", { - sessionID: id, - messageID: assistantId, - partID: assistant.parts[0].id, - field: "text", - delta: "First chunk", - }); + const acknowledge = () => { + if (announceExecution) res.set("X-Assistant-Execution", "enabled"); + res.status(204).end(); + }; + if (holdPromptAck) promptAcks.push(acknowledge); + else acknowledge(); + const publish = () => { + c!.turns.push(user, assistant); + emit(c, "session.status", { sessionID: id, status: { type: "busy" } }); + for (const turn of [user, assistant]) { + emit(c, "message.updated", { info: turn.info }); + emit(c, "message.part.updated", { part: turn.parts[0] }); + } + assistant.parts[0].text = "First chunk"; + emit(c, "message.part.delta", { + sessionID: id, + messageID: assistantId, + partID: assistant.parts[0].id, + field: "text", + delta: "First chunk", + }); + }; + if (holdPromptPublication) promptPublications.push(publish); + else publish(); return; } res.status(404).end(); @@ -900,6 +986,176 @@ async function openAssistant(page: Page) { ).toBeEnabled(); } +for (const state of ["ending", "ended"] as const) { + test(`lifecycle handshake never attaches an ${state} session`, async ({ + page, + }, testInfo) => { + lifecycleState = state; + execution = "paused"; + await page.goto("/?seed=0"); + await page.getByRole("button", { name: "Assistant", exact: true }).click(); + await expect(page.getByRole("alert")).toContainText( + openCodeTransportFailure("session_ended").message, + ); + expect(attachRevisions).toEqual([]); + expect(conversations.size).toBe(0); + await expect( + page.getByRole("textbox", { name: "Message Assistant" }), + ).toHaveCount(0); + await page.screenshot({ path: testInfo.outputPath(`${state}.png`) }); + }); +} + +test("lifecycle handshake binds the old revision when End wins before attach", async ({ + page, +}, testInfo) => { + endBeforeAttach = true; + await page.goto("/?seed=0"); + await page.getByRole("button", { name: "Assistant", exact: true }).click(); + await expect(page.getByRole("alert")).toContainText( + openCodeTransportFailure("lifecycle_changed").message, + ); + expect(attachRevisions).toEqual([0]); + expect(conversations.size).toBe(0); + expect(leasedRequests).toEqual([]); + await page.screenshot({ + path: testInfo.outputPath("ended-before-attach.png"), + }); +}); + +test("lifecycle handshake discards an attach response after leaving Assistant", async ({ + page, +}, testInfo) => { + holdAttach = true; + await page.goto("/?seed=0"); + await page.getByRole("button", { name: "Assistant", exact: true }).click(); + await expect.poll(() => attachReplies.length).toBe(1); + await page.getByRole("button", { name: "Terminal", exact: true }).click(); + attachReplies.shift()!(); + await expect(page.locator(".harness-terminal")).toBeVisible(); + await expect( + page.getByRole("textbox", { name: "Message Assistant" }), + ).toHaveCount(0); + expect(leasedRequests).toEqual([]); + await page.screenshot({ + path: testInfo.outputPath("late-attach-discarded.png"), + }); +}); + +async function restorePausedHistory(page: Page) { + await openAssistant(page); + await page + .getByRole("textbox", { name: "Message Assistant" }) + .fill("Original task"); + await page.getByRole("button", { name: "Send message" }).click(); + await expect(page.getByText("First chunk", { exact: true })).toBeVisible(); + const c = conversations.get("ses_sess_boot")!; + useCompletionContract(c); + const previous = c.turns.at(-1)!; + previous.parts[0].text = "I'll finish the original task next."; + previous.info.agent = "build"; + previous.info.time.created = c.turns[0].info.time.created + 1; + previous.info.time.completed = Date.now(); + previous.info.finish = "stop"; + c.busy = false; + c.lease = randomUUID(); + execution = "paused"; + await page.reload(); + await page.getByRole("button", { name: "Assistant", exact: true }).click(); + await expect( + page.getByRole("status", { name: "Assistant status" }), + ).toHaveText("Paused"); + await expect( + page.getByRole("textbox", { name: "Message Assistant" }), + ).toBeEnabled(); + await expect( + page.getByText(previous.parts[0].text, { exact: true }), + ).toBeVisible(); + return c; +} + +test("paused restoration makes no recovery and leases only the new explicit turn", async ({ + page, +}, testInfo) => { + const c = await restorePausedHistory(page); + expect(c.prompts).toEqual(["Original task"]); + expect(c.recoveries).toEqual([]); + await page.screenshot({ path: testInfo.outputPath("restored-paused.png") }); + holdPromptPublication = true; + await page + .getByRole("textbox", { name: "Message Assistant" }) + .fill("New explicit task"); + await page.getByRole("button", { name: "Send message" }).click(); + await expect.poll(() => promptPublications.length).toBe(1); + await expect( + page.getByRole("status", { name: "Assistant status" }), + ).not.toHaveText("Paused"); + // ACK enabled admission, but the adapter still holds only the old history. + expect(c.recoveries).toEqual([]); + promptPublications.shift()!(); + await expect(page.getByText("First chunk", { exact: true })).toBeVisible(); + useCompletionContract(c); + endWithoutAnswer(c); + await expect.poll(() => c.recoveries).toEqual(["msg_empty"]); + expect( + c.turns.find((turn) => turn.info.id === "msg_empty")!.info.parentID, + ).toBe("msg_user_2"); + expect( + leasedRequests.some((request) => request.path.endsWith("/final-response")), + ).toBe(true); + expect( + leasedRequests.every((request) => request.actual === request.expected), + ).toBe(true); + expect(c.prompts).toEqual(["Original task", "New explicit task"]); + recoveryReply!("Finished the new task."); +}); + +test("paused restoration admits the new turn when history arrives before its acknowledgment", async ({ + page, +}, testInfo) => { + const c = await restorePausedHistory(page); + holdPromptAck = true; + await page + .getByRole("textbox", { name: "Message Assistant" }) + .fill("New explicit task"); + await page.getByRole("button", { name: "Send message" }).click(); + await expect(page.getByText("First chunk", { exact: true })).toBeVisible(); + useCompletionContract(c); + endWithoutAnswer(c); + const status = page.getByRole("status", { name: "Assistant status" }); + await expect(status).toHaveText("Paused"); + expect(c.recoveries).toEqual([]); + await expect.poll(() => promptAcks.length).toBe(1); + promptAcks.shift()!(); + await expect.poll(() => c.recoveries).toEqual(["msg_empty"]); + await expect(status).toContainText("Working"); + await page.screenshot({ + path: testInfo.outputPath("new-turn-after-ack.png"), + }); + recoveryReply!("Finished the new task."); +}); + +test("paused restoration stays paused without the server execution acknowledgment", async ({ + page, +}, testInfo) => { + const c = await restorePausedHistory(page); + announceExecution = false; + await page + .getByRole("textbox", { name: "Message Assistant" }) + .fill("New explicit task"); + await page.getByRole("button", { name: "Send message" }).click(); + await expect(page.getByText("First chunk", { exact: true })).toBeVisible(); + useCompletionContract(c); + endWithoutAnswer(c); + await expect( + page.getByRole("status", { name: "Assistant status" }), + ).toHaveText("Paused"); + expect(c.recoveries).toEqual([]); + await page.screenshot({ + path: testInfo.outputPath("paused-without-ack.png"), + }); +}); + test("sibling selection survives mounted recovery and reaches each accepted send", async ({ page, }) => { diff --git a/packages/harness/web/src/components/OpenCodeChat.tsx b/packages/harness/web/src/components/OpenCodeChat.tsx index a65e70515..533324b38 100644 --- a/packages/harness/web/src/components/OpenCodeChat.tsx +++ b/packages/harness/web/src/components/OpenCodeChat.tsx @@ -24,6 +24,11 @@ import { import { Icon } from "./Icon"; import { Markdown } from "./Markdown"; import { EmptyState } from "./EmptyState"; +import { + parseAssistantAttachment, + parseAssistantLifecycle, + type AssistantAttachment, +} from "../lib/assistant-lifecycle-client"; import { finalResponseAgent, turnRecoveryAgent, @@ -36,6 +41,7 @@ import { openCodeVisibleText, } from "../../../src/shared/opencode-completion"; import { + openCodeTransportFailure, parseOpenCodeStudioErrorEvent, parseOpenCodeTransportErrorBody, type OpenCodeTransportAction, @@ -102,7 +108,9 @@ export function OpenCodeChat({ onOpenSettings, onOpenTerminal, }: Props) { - const [conversationId, setConversationId] = useState(null); + const [attachment, setAttachment] = useState( + null, + ); const [error, setError] = useState(null); const [attempt, setAttempt] = useState(0); const baseUrl = new URL( @@ -111,45 +119,75 @@ export function OpenCodeChat({ ).toString(); useEffect(() => { const abort = new AbortController(); - setConversationId(null); + setAttachment(null); setError(null); - void fetch(`${baseUrl}/attach`, { - method: "POST", - headers: { "X-Harness-Token": bootToken }, - credentials: "omit", - signal: abort.signal, - }) - .then(async (response) => { - if (!response.ok) { - const failure = await responseFailure(response); - if (!abort.signal.aborted) - setError(failure ? trustedNotice(failure) : openError); - return; - } - const data = await response.json(); - if ( - typeof data.conversationId !== "string" || - !data.conversationId.startsWith("ses_") - ) - throw new Error("invalid association"); - if (!abort.signal.aborted) setConversationId(data.conversationId); - }) - .catch(() => { - if (!abort.signal.aborted) setError(openError); + void (async () => { + const options = { + headers: { "X-Harness-Token": bootToken }, + credentials: "omit" as const, + cache: "no-store" as const, + signal: abort.signal, + }; + let response = await fetch(`${baseUrl}/lifecycle`, options); + if (!response.ok) { + const failure = await responseFailure(response); + if (!abort.signal.aborted) + setError(failure ? trustedNotice(failure) : openError); + return; + } + const lifecycle = parseAssistantLifecycle( + await response.json(), + harnessSessionId, + ); + if (abort.signal.aborted) return; + if (!lifecycle) throw new Error("invalid lifecycle"); + if (lifecycle.lifecycle !== "open") { + setError(trustedNotice(openCodeTransportFailure("session_ended"))); + return; + } + response = await fetch(`${baseUrl}/attach`, { + ...options, + method: "POST", + headers: { ...options.headers, "Content-Type": "application/json" }, + body: JSON.stringify({ expectedRevision: lifecycle.revision }), }); + if (!response.ok) { + const failure = await responseFailure(response); + if (!abort.signal.aborted) + setError(failure ? trustedNotice(failure) : openError); + return; + } + const attached = parseAssistantAttachment( + await response.json(), + harnessSessionId, + lifecycle.revision, + ); + if (!attached) { + if (!abort.signal.aborted) + setError( + trustedNotice(openCodeTransportFailure("lifecycle_changed")), + ); + return; + } + if (!abort.signal.aborted) setAttachment(attached); + })().catch(() => { + if (!abort.signal.aborted) setError(openError); + }); return () => abort.abort(); - }, [baseUrl, bootToken, attempt]); + }, [baseUrl, bootToken, attempt, harnessSessionId]); const retry = useCallback(() => { - setConversationId(null); + setAttachment(null); setError(null); setAttempt((value) => value + 1); }, []); - return conversationId ? ( + return attachment?.lifecycle.harnessSessionId === harnessSessionId ? ( void; draft: ChatDraft; onSignIn: () => void; @@ -205,6 +247,7 @@ function RuntimeChat({ ); const [actionError, setActionError] = useState(null); const [connected, setConnected] = useState(false); + const [execution, setExecution] = useState(initialExecution); const eventAbort = useRef(null); const reconcile = useCallback(() => { // The adapter reconnects this display stream and reloads history/status. @@ -220,13 +263,15 @@ function RuntimeChat({ const client = useMemo(() => { const client = createOpencodeClient({ baseUrl, - headers: { "X-Harness-Token": bootToken }, + headers: { "X-Harness-Token": bootToken, "X-Assistant-Lease": lease }, credentials: "omit", fetch: async (input, init) => { let request = new Request(input, init); const path = new URL(request.url).pathname; const root = new URL(`${baseUrl}/session/${conversationId}`).pathname; - if (request.method === "POST" && path === `${root}/prompt_async`) { + const explicitPrompt = + request.method === "POST" && path === `${root}/prompt_async`; + if (explicitPrompt) { const selectedAgentPath = selection.current; const body = await request.clone().json(); request = new Request(request, { @@ -239,6 +284,12 @@ function RuntimeChat({ path.endsWith("/experimental/session"); try { const response = await globalThis.fetch(request); + if ( + explicitPrompt && + response.ok && + response.headers.get("X-Assistant-Execution") === "enabled" + ) + setExecution("enabled"); if (!response.ok) { const failure = await responseFailure(response); if (failure) onTypedError(failure); @@ -313,7 +364,7 @@ function RuntimeChat({ // generates titles; suppress that unrelated model action, as in the POC. client.session.summarize = async () => ({ data: true }) as never; return client; - }, [baseUrl, bootToken, conversationId, onError, onTypedError]); + }, [baseUrl, bootToken, conversationId, lease, onError, onTypedError]); const runtime = useOpenCodeRuntime({ client, initialSessionId: conversationId, @@ -325,6 +376,8 @@ function RuntimeChat({ baseUrl={baseUrl} bootToken={bootToken} conversationId={conversationId} + lease={lease} + execution={execution} connected={connected} reconcile={reconcile} error={actionError ?? transportError} @@ -363,6 +416,8 @@ function ChatSurface({ baseUrl, bootToken, conversationId, + lease, + execution, connected, reconcile, error, @@ -377,6 +432,8 @@ function ChatSurface({ baseUrl: string; bootToken: string; conversationId: string; + lease: string; + execution: AssistantAttachment["lifecycle"]["execution"]; connected: boolean; reconcile: () => void; error: RecoveryNotice | null; @@ -419,19 +476,28 @@ function ChatSurface({ const recoveryAbort = useRef(null); const [recovering, setRecovering] = useState(false); const [recoveryFailed, setRecoveryFailed] = useState(false); - const missing = turn.missing; + // Capture restored history once: the explicit Send ACK and its new history + // can arrive in either order. Only the restored old turn stays suppressed. + const restoredMissing = useRef(undefined); + if (execution === "paused" && ready && restoredMissing.current === undefined) + restoredMissing.current = turn.missing ?? null; + const missing = + turn.missing && turn.missing !== restoredMissing.current + ? turn.missing + : null; const pending = Object.values(native.pendingUserMessages).some( (message) => message.status === "pending", ); useEffect(() => { - if (!error) return; + if (!error && execution !== "paused") return; recoveryAbort.current?.abort(); recoveryAbort.current = null; setRecovering(false); - }, [error]); + }, [error, execution]); useEffect(() => { if ( !ready || + execution === "paused" || !connected || error || running || @@ -452,6 +518,7 @@ function ChatSurface({ method: "POST", headers: { "X-Harness-Token": bootToken, + "X-Assistant-Lease": lease, "Content-Type": "application/json", }, credentials: "omit", @@ -484,6 +551,8 @@ function ChatSurface({ bootToken, connected, conversationId, + lease, + execution, error, missing, pending, @@ -514,6 +583,7 @@ function ChatSurface({ native.loadState.type === "loading" && native.messageOrder.length > 0; const working = + execution === "enabled" && !visibleError && (running || recovering || @@ -526,17 +596,19 @@ function ChatSurface({ ? catchingUp ? "Catching up…" : "Checking status…" - : waiting - ? "Waiting for input" - : working - ? "Working" - : turn.status === "finished" - ? "Finished" - : turn.status === "failed" || recoveryFailed - ? "Failed" - : turn.status === "stopped" - ? "Stopped" - : "Ready"; + : execution === "paused" + ? "Paused" + : waiting + ? "Waiting for input" + : working + ? "Working" + : turn.status === "finished" + ? "Finished" + : turn.status === "failed" || recoveryFailed + ? "Failed" + : turn.status === "stopped" + ? "Stopped" + : "Ready"; return ( { + it("reads the exact Studio lifecycle without adopting arbitrary wire fields", () => { + expect( + parseAssistantLifecycle({ ...lifecycle, secret: "ignored" }, "studio-a"), + ).toEqual(lifecycle); + expect(parseAssistantLifecycle(lifecycle, "studio-b")).toBeNull(); + }); + it.each([ + { revision: -1 }, + { revision: 0.5 }, + { revision: Number.MAX_SAFE_INTEGER + 1 }, + { lifecycle: "running" }, + { execution: "true" }, + { updatedAt: "yesterday" }, + { version: 2 }, + ])("rejects malformed lifecycle %j", (patch) => { + expect( + parseAssistantLifecycle({ ...lifecycle, ...patch }, "studio-a"), + ).toBeNull(); + }); + it("accepts existing or newly committed attachment revisions", () => { + expect(parseAssistantAttachment(attachment, "studio-a", 2)).toEqual( + attachment, + ); + expect(parseAssistantAttachment(attachment, "studio-a", 1)).toEqual( + attachment, + ); + }); + it.each([0, 3])( + "rejects an attachment from another operation revision %i", + (expected) => { + expect( + parseAssistantAttachment(attachment, "studio-a", expected), + ).toBeNull(); + }, + ); + it("rejects ended, foreign, and unleased attachments", () => { + expect(parseAssistantAttachment(attachment, "studio-b", 2)).toBeNull(); + expect( + parseAssistantAttachment( + { ...attachment, lifecycle: { ...lifecycle, lifecycle: "ended" } }, + "studio-a", + 2, + ), + ).toBeNull(); + expect( + parseAssistantAttachment( + { ...attachment, lease: "not-a-lease" }, + "studio-a", + 2, + ), + ).toBeNull(); + expect( + parseAssistantAttachment( + { ...attachment, conversationId: "studio-a" }, + "studio-a", + 2, + ), + ).toBeNull(); + }); +}); diff --git a/packages/harness/web/src/lib/assistant-lifecycle-client.ts b/packages/harness/web/src/lib/assistant-lifecycle-client.ts new file mode 100644 index 000000000..77acdee70 --- /dev/null +++ b/packages/harness/web/src/lib/assistant-lifecycle-client.ts @@ -0,0 +1,64 @@ +import type { AssistantLifecycle } from "../../../src/shared/assistant-session"; + +export interface AssistantAttachment { + conversationId: string; + lease: string; + lifecycle: AssistantLifecycle; +} + +const object = (value: unknown): value is Record => + value !== null && typeof value === "object" && !Array.isArray(value); + +/** A foreign or malformed descriptor must never authorize an attach. */ +export function parseAssistantLifecycle( + value: unknown, + harnessSessionId: string, +): AssistantLifecycle | null { + if ( + !object(value) || + value.version !== 1 || + value.harnessSessionId !== harnessSessionId || + !Number.isSafeInteger(value.revision) || + (value.revision as number) < 0 || + !["open", "ending", "ended"].includes(value.lifecycle as string) || + !["enabled", "paused"].includes(value.execution as string) || + !Number.isSafeInteger(value.updatedAt) || + (value.updatedAt as number) < 0 + ) + return null; + return { + version: 1, + harnessSessionId, + revision: value.revision as number, + lifecycle: value.lifecycle as AssistantLifecycle["lifecycle"], + execution: value.execution as AssistantLifecycle["execution"], + updatedAt: value.updatedAt as number, + }; +} + +/** Starting a runtime advances once; attaching its existing lease does not. */ +export function parseAssistantAttachment( + value: unknown, + harnessSessionId: string, + expectedRevision: number, +): AssistantAttachment | null { + if (!object(value)) return null; + const lifecycle = parseAssistantLifecycle(value.lifecycle, harnessSessionId); + if ( + !lifecycle || + lifecycle.lifecycle !== "open" || + ![expectedRevision, expectedRevision + 1].includes(lifecycle.revision) || + typeof value.conversationId !== "string" || + !/^ses_[A-Za-z0-9_-]{1,128}$/.test(value.conversationId) || + typeof value.lease !== "string" || + !/^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/i.test( + value.lease, + ) + ) + return null; + return { + conversationId: value.conversationId, + lease: value.lease, + lifecycle, + }; +}