From 8f2ba47e6a82d211bbb092b533660b36491d7f57 Mon Sep 17 00:00:00 2001 From: Yash Date: Mon, 14 Sep 2026 22:01:20 +0000 Subject: [PATCH] feat(harness): resume Assistant from retained history --- .changeset/assistant-resume-controls.md | 5 + packages/harness/docs/assistant-history.md | 7 + .../harness/web/e2e/assistant-end.spec.ts | 31 ++ .../harness/web/e2e/assistant-history.spec.ts | 422 +++++++++++++++++- packages/harness/web/src/App.tsx | 24 +- .../components/AssistantHistoryActions.tsx | 137 ++++++ .../src/components/AssistantHistoryPane.tsx | 2 +- .../web/src/components/AssistantPane.tsx | 12 +- .../web/src/lib/assistant-history-client.ts | 9 + .../web/src/lib/assistant-resume-client.ts | 126 ++++++ .../harness/web/src/lib/use-harness-state.ts | 32 +- 11 files changed, 794 insertions(+), 13 deletions(-) create mode 100644 .changeset/assistant-resume-controls.md create mode 100644 packages/harness/web/src/components/AssistantHistoryActions.tsx create mode 100644 packages/harness/web/src/lib/assistant-resume-client.ts diff --git a/.changeset/assistant-resume-controls.md b/.changeset/assistant-resume-controls.md new file mode 100644 index 000000000..6c8b34fea --- /dev/null +++ b/.changeset/assistant-resume-controls.md @@ -0,0 +1,5 @@ +--- +"@sapiom/harness": patch +--- + +Check saved Assistant availability and resume the same conversation from session history. diff --git a/packages/harness/docs/assistant-history.md b/packages/harness/docs/assistant-history.md index 89174201d..e19cc1881 100644 --- a/packages/harness/docs/assistant-history.md +++ b/packages/harness/docs/assistant-history.md @@ -87,3 +87,10 @@ before and after IO. Missing native history never creates a replacement session; missing retained context blocks execution while public history remains readable. An empty saved conversation needs no invented context. Public attachments contain only native identity, lease and lifecycle state, never saved system text. + +History review offers an explicit availability check before Resume. Missing +native history and missing execution context remain distinct readable states. +Resume reuses an operation UUID after an uncertain response and reveals Assistant +only if the same account, navigation and foreground intent still own the result. +Newer bus state owns Terminal status. A restored Assistant stays paused until an +explicit message; existing live execution keeps its current state. diff --git a/packages/harness/web/e2e/assistant-end.spec.ts b/packages/harness/web/e2e/assistant-end.spec.ts index ba05edc8c..c95e4bf4f 100644 --- a/packages/harness/web/e2e/assistant-end.spec.ts +++ b/packages/harness/web/e2e/assistant-end.spec.ts @@ -277,3 +277,34 @@ test("Terminal-only End keeps its existing confirmation and sibling selection", await expect(page.locator(".harness-terminal")).toBeVisible(); expect(fixture.unexpected).toEqual([]); }); + +test("late End cannot remove or select a row after an auth barrier", async ({ + page, +}) => { + const fixture = await openStudio(page); + await project(page, 1, [lifecycle("sess-boot")]); + await openEnd(page); + await page.getByTestId("end-session-confirm-btn").click(); + await expect.poll(() => fixture.requests.length).toBe(1); + await publish(page, { + type: "auth.changed", + authenticated: true, + organizationName: "Account B", + }); + await publish(page, { + type: "session.status", + session: session("sess-boot", { title: "Current account session" }), + }); + await fixture.settle(200); + await expect + .poll(() => + page.evaluate(() => (window as any).__HARNESS_TEST__.killSessionCalls), + ) + .toContain("sess-boot"); + await expect(page.getByTestId("session-tab-sess-boot")).toContainText( + "Current account session", + ); + await expect(selected(page)).toHaveAttribute("data-session-id", "sess-boot"); + await expect(page.locator(".harness-terminal")).toBeVisible(); + expect(fixture.unexpected).toEqual([]); +}); diff --git a/packages/harness/web/e2e/assistant-history.spec.ts b/packages/harness/web/e2e/assistant-history.spec.ts index 001980ad8..822457bdb 100644 --- a/packages/harness/web/e2e/assistant-history.spec.ts +++ b/packages/harness/web/e2e/assistant-history.spec.ts @@ -1,5 +1,12 @@ import { expect, test, type Page, type Route } from "@playwright/test"; import type { AssistantHistoryEntry } from "../../src/shared/assistant-history"; +import { openCodeTransportFailure } from "../../src/shared/opencode-errors"; +import { createServer, type ServerResponse } from "node:http"; + +const closeEvents: Array<() => Promise> = []; +test.afterEach(async () => { + await Promise.all(closeEvents.splice(0).map((close) => close())); +}); const cwd = "/Users/demo/acme-app"; const entry = (id: string): AssistantHistoryEntry => ({ @@ -110,13 +117,166 @@ const rows = async (page: Page) => { await page.getByTestId("past-sessions-trigger").hover(); }; async function setup(page: Page, mode = "valid") { + const streams = new Set(); + const events = createServer((req, res) => { + res.writeHead(200, { + "Content-Type": "text/event-stream", + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Headers": "*", + }); + if (req.method === "OPTIONS") { + res.end(); + return; + } + streams.add(res); + res.on("close", () => streams.delete(res)); + res.write('data: {"type":"server.connected","properties":{}}\n\n'); + }); + await new Promise((resolve) => events.listen(0, "127.0.0.1", resolve)); + const eventOrigin = `http://127.0.0.1:${(events.address() as { port: number }).port}`; + closeEvents.push(async () => { + for (const stream of streams) stream.end(); + await new Promise((resolve) => events.close(() => resolve())); + }); const probe = { calls: [] as string[], holdList: false, holdRecord: false, lists: [] as Route[], records: [] as Route[], + inspectState: "available" as "available" | "missing" | "unavailable", + inspections: [] as Route[], + resumes: [] as Route[], + holdInspect: false, + holdResume: false, + failResume: false, + resumedRevision: 3, }; + const attachment = (id: string) => ({ + conversationId: `ses_${id}`, + lease: "11111111-1111-4111-8111-111111111111", + lifecycle: { + ...entry(id).lifecycle, + lifecycle: "open", + revision: probe.resumedRevision, + }, + }); + const resumed = (id: string) => ({ + session: { + id, + cwd, + title: `Saved ${id}`, + harness: "claude-code", + agentSessionId: null, + boundWorkflowPath: null, + status: "exited", + ready: false, + createdAt: entry(id).createdAt, + lastActiveAt: entry(id).updatedAt, + }, + attachment: attachment(id), + }); + await page.route("**/api/sessions/*/assistant/inspect", (route) => { + probe.inspections.push(route); + if (probe.holdInspect) return; + const id = new URL(route.request().url()).pathname.split("/")[3]!; + return route.fulfill({ + json: { + entry: { + ...entry(id), + nativeResume: probe.inspectState, + ...(probe.inspectState !== "available" + ? { + resumeFailure: openCodeTransportFailure( + probe.inspectState === "missing" + ? "native_history_missing" + : "context_unavailable", + ), + } + : {}), + }, + }, + }); + }); + await page.route("**/api/sessions/*/assistant/resume", (route) => { + probe.resumes.push(route); + if (probe.holdResume) return; + const id = new URL(route.request().url()).pathname.split("/")[3]!; + return route.fulfill( + probe.failResume ? { status: 503, json: {} } : { json: resumed(id) }, + ); + }); + await page.route("**/api/assistant/access", (route) => + route.fulfill({ json: { enabled: true, authorityRevision: "account-a" } }), + ); + await page.route( + (url) => url.pathname.startsWith("/opencode/"), + (route) => { + const [, , id, ...parts] = new URL(route.request().url()).pathname.split( + "/", + ); + const path = parts.join("/"); + const native = { + id: `ses_${id}`, + title: "Native restored history", + time: { created: 1, updated: 2 }, + }; + if (path === "lifecycle") + return route.fulfill({ json: attachment(id!).lifecycle }); + if (path === "attach") return route.fulfill({ json: attachment(id!) }); + if (path === "event") + return route.continue({ url: `${eventOrigin}/event` }); + if (path === "session/status") + return route.fulfill({ json: { [native.id]: { type: "idle" } } }); + if (path === `session/${native.id}`) + return route.fulfill({ json: native }); + if (path === `session/${native.id}/message`) + return route.fulfill({ + json: [ + { + info: { + id: "msg_saved_user", + sessionID: native.id, + role: "user", + time: { created: 1 }, + }, + parts: [ + { + id: "prt_saved_user", + messageID: "msg_saved_user", + sessionID: native.id, + type: "text", + text: "Prior saved task", + }, + ], + }, + { + info: { + id: "msg_saved_answer", + parentID: "msg_saved_user", + sessionID: native.id, + role: "assistant", + agent: "build", + time: { created: 2, completed: 3 }, + finish: "tool-calls", + }, + parts: [ + { + id: "prt_saved_answer", + messageID: "msg_saved_answer", + sessionID: native.id, + type: "text", + text: `Native saved answer ${id}`, + }, + ], + }, + ], + }); + return route.fulfill({ + json: path === "experimental/session" ? [native] : [], + }); + }, + ); await page.route("**/api/sessions/assistant-history?**", (route) => { if (new URL(route.request().url()).searchParams.get("cwd") !== cwd) return route.fulfill({ json: { entries: [] } }); @@ -125,7 +285,13 @@ async function setup(page: Page, mode = "valid") { return; } return route.fulfill({ - json: { entries: [entry("assistant-only"), entry("sess-leasing")] }, + json: { + entries: [ + entry("assistant-only"), + entry("sess-leasing"), + ...(mode === "foreground" ? [entry("sess-boot")] : []), + ], + }, }); }); await page.route("**/api/sessions/*/assistant/record", (route) => { @@ -150,7 +316,7 @@ async function setup(page: Page, mode = "valid") { await page.goto("/?seed=0"); await expect(page.locator(".harness-terminal")).toBeVisible(); await authority(page, 1); - return probe; + return Object.assign(probe, { resumed }); } test("groups mixed records by Studio ID and reads pure Assistant history without native work", async ({ @@ -174,7 +340,9 @@ test("groups mixed records by Studio ID and reads pure Assistant history without await expect(pane).toContainText("A recorded excerpt"); await expect(pane).not.toContainText("PRIVATE_"); await expect( - pane.getByRole("button", { name: /Resume|Continue|New session/ }), + pane.getByRole("button", { + name: /^(Resume Assistant|Continue|New session)$/, + }), ).toHaveCount(0); await page.screenshot({ path: testInfo.outputPath("assistant-record.png") }); await pane.getByRole("button", { name: "Close" }).click(); @@ -236,3 +404,251 @@ test("late history and record reads cannot cross account or navigation barriers" await expect(page.getByText("Saved answer assistant-only")).toHaveCount(0); expect(probe.calls).toEqual([]); }); + +const review = async (page: Page, id = "assistant-only") => { + await rows(page); + await page.getByTestId(`assistant-history-${id}`).click(); + await expect(page.getByTestId("assistant-transcript")).toBeVisible(); +}; +const checkResume = (page: Page) => + page.getByRole("button", { name: "Check Resume availability", exact: true }); +const resumeButton = (page: Page) => + page.getByRole("button", { name: "Resume Assistant", exact: true }); + +test("Resume verifies availability, preserves identity and opens paused without submitting work", async ({ + page, +}, testInfo) => { + const probe = await setup(page); + await review(page); + await expect(resumeButton(page)).toHaveCount(0); + expect(probe.inspections).toHaveLength(0); + probe.holdInspect = true; + await checkResume(page).click(); + await expect( + page.getByRole("button", { name: "Checking Resume availability…" }), + ).toBeDisabled(); + await expect.poll(() => probe.inspections.length).toBe(1); + await probe.inspections[0]!.fulfill({ + json: { entry: { ...entry("assistant-only"), nativeResume: "available" } }, + }); + await expect(resumeButton(page)).toBeEnabled(); + await page.screenshot({ path: testInfo.outputPath("resume-verified.png") }); + await page.setViewportSize({ width: 390, height: 844 }); + await expect(resumeButton(page)).toBeVisible(); + await page.screenshot({ path: testInfo.outputPath("resume-mobile.png") }); + await page.setViewportSize({ width: 1280, height: 720 }); + probe.holdResume = true; + await resumeButton(page).click(); + await expect.poll(() => probe.resumes.length).toBe(1); + await publish(page, { + type: "assistant.state", + snapshot: { + hostInstanceId: "history-host", + authorityRevision: "account-a", + revision: 2, + enabled: true, + sessions: [], + lifecycles: [probe.resumed("assistant-only").attachment.lifecycle], + }, + }); + await probe.resumes[0]!.fulfill({ json: probe.resumed("assistant-only") }); + await expect( + page.getByRole("button", { name: "Assistant", exact: true }), + ).toHaveAttribute("aria-pressed", "true"); + await expect(page.getByText("Paused", { exact: true })).toBeVisible(); + await expect( + page.getByText("Native saved answer assistant-only", { exact: true }), + ).toBeVisible(); + await expect(page.getByText("Session ended", { exact: true })).toHaveCount(0); + await expect(page.getByTestId("session-context")).toHaveAttribute( + "data-session-id", + "assistant-only", + ); + await page.screenshot({ path: testInfo.outputPath("resumed-paused.png") }); + expect(probe.resumes[0]!.request().postDataJSON()).toMatchObject({ + expectedRevision: 2, + operationId: expect.stringMatching(/^[a-f0-9-]{36}$/), + }); + expect( + probe.calls.filter((url) => /prompt_async|final-response/.test(url)), + ).toEqual([]); +}); + +for (const native of ["missing", "unavailable"] as const) { + test(`${native} native context leaves saved history readable without Resume`, async ({ + page, + }, testInfo) => { + const probe = await setup(page); + probe.inspectState = native; + await review(page); + await checkResume(page).click(); + await expect(page.getByTestId("assistant-history-actions")).toContainText( + "Your saved record remains readable", + ); + await expect(page.getByTestId("assistant-transcript")).toContainText( + "Saved answer assistant-only", + ); + await expect(resumeButton(page)).toHaveCount(0); + expect(probe.resumes).toHaveLength(0); + await page.screenshot({ + path: testInfo.outputPath(`resume-${native}.png`), + }); + }); +} + +test("uncertain Resume retries the same operation and accepts reconciled later revision", async ({ + page, +}) => { + const probe = await setup(page); + probe.failResume = true; + await review(page, "sess-leasing"); + await checkResume(page).click(); + await resumeButton(page).click(); + await expect(page.getByRole("alert")).toContainText( + "Retry to check the same operation", + ); + await expect(page.getByTestId("assistant-transcript")).toContainText( + "Saved answer sess-leasing", + ); + const request = probe.resumes[0]!.request().postDataJSON(); + await page + .getByTestId("assistant-history-pane") + .getByRole("button", { name: "Close", exact: true }) + .click(); + await page.getByRole("button", { name: "Go back" }).click(); + await checkResume(page).click(); + probe.failResume = false; + probe.resumedRevision = 4; + await resumeButton(page).click(); + await expect(page.getByText("Paused", { exact: true })).toBeVisible(); + expect(probe.resumes[1]!.request().postDataJSON()).toEqual(request); + await page.getByRole("button", { name: "Terminal", exact: true }).click(); + await expect(page.getByTestId("dead-session-pane")).toBeVisible(); +}); + +for (const barrier of ["navigation", "account", "lifecycle"] as const) { + test(`late Resume cannot cross the ${barrier} barrier`, async ({ page }) => { + const probe = await setup(page); + probe.holdResume = true; + await review(page); + await checkResume(page).click(); + await resumeButton(page).click(); + await expect.poll(() => probe.resumes.length).toBe(1); + if (barrier === "navigation") + await page + .getByTestId("assistant-history-pane") + .getByRole("button", { name: "Close", exact: true }) + .click(); + if (barrier === "account") await authority(page, 2, "account-b"); + if (barrier === "lifecycle") + await publish(page, { + type: "assistant.state", + snapshot: { + hostInstanceId: "history-host", + authorityRevision: "account-a", + revision: 3, + enabled: true, + sessions: [], + lifecycles: [{ ...entry("assistant-only").lifecycle, revision: 4 }], + }, + }); + await probe.resumes[0]!.fulfill({ json: probe.resumed("assistant-only") }); + if (barrier === "lifecycle") await expect(checkResume(page)).toBeEnabled(); + else + await expect(page.getByTestId("assistant-history-pane")).toHaveCount(0); + await expect( + page + .getByRole("button", { name: "Assistant", exact: true }) + .and(page.locator('[aria-pressed="true"]')), + ).toHaveCount(0); + expect(probe.calls.filter((url) => /\/opencode\//.test(url))).toEqual([]); + }); +} + +for (const invalid of ["studio", "cwd", "lease", "revision"] as const) { + test(`an invalid Resume ${invalid} cannot activate a conversation`, async ({ + page, + }) => { + const probe = await setup(page); + probe.holdResume = true; + await review(page); + await checkResume(page).click(); + await resumeButton(page).click(); + await expect.poll(() => probe.resumes.length).toBe(1); + const value = probe.resumed("assistant-only"); + if (invalid === "studio") value.session.id = "foreign-studio"; + if (invalid === "cwd") value.session.cwd = "/foreign-project"; + if (invalid === "lease") value.attachment.lease = "not-a-lease"; + if (invalid === "revision") value.attachment.lifecycle.revision = 2; + await probe.resumes[0]!.fulfill({ json: value }); + await expect(page.getByRole("alert")).toContainText( + "restored Assistant could not be verified", + ); + await expect(page.getByTestId("assistant-transcript")).toContainText( + "Saved answer assistant-only", + ); + expect(probe.calls.filter((url) => /\/opencode\//.test(url))).toEqual([]); + }); +} + +test("late availability and untrusted failure text never authorize Resume", async ({ + page, +}) => { + const probe = await setup(page); + probe.holdInspect = true; + await review(page); + await checkResume(page).click(); + await expect.poll(() => probe.inspections.length).toBe(1); + await probe.inspections[0]!.fulfill({ + json: { + entry: { + ...entry("assistant-only"), + nativeResume: "unavailable", + resumeFailure: { + ...openCodeTransportFailure("context_unavailable"), + message: "PRIVATE_RAW_FAILURE", + }, + }, + }, + }); + await expect(page.getByRole("alert")).toContainText( + "Resume availability could not be verified", + ); + await expect(page.getByText("PRIVATE_RAW_FAILURE")).toHaveCount(0); + await checkResume(page).click(); + await expect.poll(() => probe.inspections.length).toBe(2); + await page + .getByTestId("assistant-history-pane") + .getByRole("button", { name: "Close", exact: true }) + .click(); + await probe.inspections[1]!.fulfill({ + json: { entry: { ...entry("assistant-only"), nativeResume: "available" } }, + }); + await expect(resumeButton(page)).toHaveCount(0); + expect(probe.resumes).toHaveLength(0); +}); + +test("resumed Assistant yields to newer foreground Terminal work", async ({ + page, +}) => { + await setup(page, "foreground"); + await review(page, "sess-boot"); + await checkResume(page).click(); + await resumeButton(page).click(); + await expect(page.getByText("Paused", { exact: true })).toBeVisible(); + await publish(page, { + type: "canvas.reload", + harnessSessionId: "sess-boot", + }); + await expect(page.locator(".canvas-frame-wrap")).toHaveAttribute( + "data-view", + "board", + ); + await page.getByTestId("canvas-chat-toggle").click(); + await page.getByTestId("canvas-freeform-input").fill("Explain this agent"); + await page.getByTestId("canvas-freeform-ask").click(); + await expect( + page.getByRole("button", { name: "Terminal", exact: true }), + ).toHaveAttribute("aria-pressed", "true"); + await expect(page.locator(".harness-terminal")).toBeVisible(); +}); diff --git a/packages/harness/web/src/App.tsx b/packages/harness/web/src/App.tsx index 69cb11609..c57f19222 100644 --- a/packages/harness/web/src/App.tsx +++ b/packages/harness/web/src/App.tsx @@ -88,6 +88,7 @@ import { Terminal } from "./components/Terminal"; import { AssistantPane } from "./components/AssistantPane"; import { AssistantHistoryPane } from "./components/AssistantHistoryPane"; import type { AssistantHistoryEntry } from "../../src/shared/assistant-history"; +import { AssistantHistoryActions } from "./components/AssistantHistoryActions"; import type { ChatDraftStore } from "./components/OpenCodeChat"; import { Toast } from "./components/Toast"; import { TooltipLayer } from "./components/TooltipLayer"; @@ -739,6 +740,7 @@ export const App = (): JSX.Element => { const [assistantReview, setAssistantReview] = useState<{ entry: AssistantHistoryEntry; authority: string; navigation: number; } | null>(null); + const assistantResumeOperations = useMemo(() => new Map(), [harness.assistantHistoryAuthority, harness.bootToken]); const setReviewSummary = useCallback((summary: SessionSummary | null) => { setAssistantReview(null); setTerminalReviewSummary(summary); @@ -2428,12 +2430,12 @@ export const App = (): JSX.Element => { // Switch to a session (history-menu pick, palette hit): focus follows it so // the main panel shows its context (its bound agent, or its own folder). - const openSession = (id: string): void => { + const openSession = (id: string, restored?: HarnessSession): void => { setComposing(false); setReviewSummary(null); setTemplatesOpen(false); setOverviewOpen(false); - const session = state.sessions.find((s) => s.id === id); + const session = restored ?? state.sessions.find((s) => s.id === id); studioRestoreGenerationRef.current += 1; setSelectedProject(null); setStudioSelection(null); @@ -3385,6 +3387,20 @@ export const App = (): JSX.Element => { entry={activeAssistantReview.entry} bootToken={harness.bootToken} onClose={() => setAssistantReview(null)} + actions={ row.harnessSessionId === activeAssistantReview.entry.harnessSessionId)} + bootToken={harness.bootToken} + operations={assistantResumeOperations} + onResume={async (entry, operationId, signal) => { + const review = activeAssistantReview; + const current = () => studioRestoreGenerationRef.current === review.navigation; + const session = await harness.resumeAssistant(entry, operationId, signal, review.authority, current); + if (!session || !current() || signal.aborted) return false; + openSession(session.id, session); + return true; + }} + />} terminalNotStarted={state.sessions.find((session) => session.id === activeAssistantReview.entry.harnessSessionId)?.terminalState === "not-started"} terminalLabel={state.sessions.find((session) => session.id === activeAssistantReview.entry.harnessSessionId)?.status !== "exited" ? "Open Terminal" : "View Terminal history"} onOpenTerminal={state.sessions.some((session) => session.id === activeAssistantReview.entry.harnessSessionId && session.terminalState !== "not-started") @@ -3420,6 +3436,7 @@ export const App = (): JSX.Element => { conversationSession.id, ) ?? 0 } + assistantRevision={harness.assistantRevealBySession.get(conversationSession.id) ?? 0} > { conversationSession.id, ) ?? 0 } + assistantRevision={harness.assistantRevealBySession.get(conversationSession.id) ?? 0} > { source={canvasSource} loadWorkflowGraph={shellApi.getWorkflowGraph.bind(shellApi)} overviewActive={showComposer} - sessionExited={showDead} + sessionExited={showDead && !!conversationSession && !assistantNeedsEnd(conversationSession.id)} onCanvasState={(hasContent) => { // The board keeps its mount behind the map; its probe must // not reveal or collapse the pane while the PROJECT is what diff --git a/packages/harness/web/src/components/AssistantHistoryActions.tsx b/packages/harness/web/src/components/AssistantHistoryActions.tsx new file mode 100644 index 000000000..235ab2d79 --- /dev/null +++ b/packages/harness/web/src/components/AssistantHistoryActions.tsx @@ -0,0 +1,137 @@ +import { useEffect, useRef, useState } from "react"; +import type { AssistantHistoryEntry } from "../../../src/shared/assistant-history"; +import type { AssistantLifecycle } from "../../../src/shared/assistant-session"; +import { inspectAssistant } from "../lib/assistant-resume-client"; + +export function AssistantHistoryActions({ + entry, + lifecycle, + bootToken, + operations, + onResume, +}: { + entry: AssistantHistoryEntry; + lifecycle?: AssistantLifecycle; + bootToken: string; + operations: Map; + onResume: ( + entry: AssistantHistoryEntry, + operationId: string, + signal: AbortSignal, + ) => Promise; +}) { + const current = + lifecycle && lifecycle.revision >= entry.lifecycle.revision + ? { ...entry, lifecycle } + : entry; + const [inspected, setInspected] = useState( + null, + ); + const [busy, setBusy] = useState<"inspect" | "resume" | null>(null); + const [failure, setFailure] = useState(null); + const request = useRef(null); + const observedRevision = useRef(current.lifecycle.revision); + useEffect(() => { + setInspected(null); + setFailure(null); + setBusy(null); + return () => { + request.current?.abort(); + request.current = null; + }; + }, [entry.harnessSessionId, bootToken, operations]); + useEffect(() => { + // Resume publishes its own committed revision before its HTTP response. + // Let the hook compare that result with current bus truth before resetting. + if ( + observedRevision.current === current.lifecycle.revision || + busy === "resume" + ) + return; + operations.delete(`${entry.harnessSessionId}:${observedRevision.current}`); + observedRevision.current = current.lifecycle.revision; + request.current?.abort(); + request.current = null; + setInspected(null); + setFailure(null); + setBusy(null); + }, [entry.harnessSessionId, current.lifecycle.revision, busy, operations]); + const run = async (action: "inspect" | "resume") => { + if (request.current) return; + const abort = new AbortController(); + request.current = abort; + setBusy(action); + setFailure(null); + try { + if (action === "inspect") { + const next = await inspectAssistant(current, bootToken, abort.signal); + if (!abort.signal.aborted) setInspected(next); + } else if (inspected?.nativeResume === "available") { + const key = `${entry.harnessSessionId}:${inspected.lifecycle.revision}`; + const operationId = operations.get(key) ?? crypto.randomUUID(); + operations.set(key, operationId); + const opened = await onResume(inspected, operationId, abort.signal); + if (!abort.signal.aborted && opened) operations.delete(key); + else if (!abort.signal.aborted) + setFailure("This session changed. Check Resume availability again."); + } + } catch (error) { + if (!abort.signal.aborted) + setFailure( + error instanceof Error + ? error.message + : "Assistant is unavailable. Check again.", + ); + } finally { + if (request.current === abort) { + request.current = null; + setBusy(null); + } + } + }; + const available = inspected?.nativeResume === "available"; + return ( +
+ {current.lifecycle.lifecycle === "ending" ? ( +

+ Session cleanup is incomplete. Retry End before resuming Assistant. +

+ ) : ( + <> + + {available && ( +

+ Restores the same conversation. Restarted Assistant stays paused + until you send a message. +

+ )} + {inspected && !available && ( +

+ {inspected.resumeFailure?.message ?? + "The original Assistant conversation is unavailable."}{" "} + Your saved record remains readable; it may contain only part of + the original context. +

+ )} + + )} + {failure && ( +

+ {failure} +

+ )} +
+ ); +} diff --git a/packages/harness/web/src/components/AssistantHistoryPane.tsx b/packages/harness/web/src/components/AssistantHistoryPane.tsx index d3409e1de..dbdcea38d 100644 --- a/packages/harness/web/src/components/AssistantHistoryPane.tsx +++ b/packages/harness/web/src/components/AssistantHistoryPane.tsx @@ -73,7 +73,6 @@ export function AssistantHistoryPane({
- {actions} {onOpenTerminal && (