| 1 | import assert from "node:assert/strict"; |
| 2 | import React, { act } from "react"; |
| 3 | import { createRoot } from "react-dom/client"; |
| 4 | import { JSDOM } from "jsdom"; |
| 5 | import { useSessionUndo, type RewindResultView } from "../app-runtime/useSessionUndo"; |
| 6 | import type { ForkTargetView } from "../lib/forkTargets"; |
| 7 | import type { Item } from "../lib/useController"; |
| 8 | |
| 9 | const dom = new JSDOM("<div id='root'></div>"); |
| 10 | Object.assign(globalThis, { window: dom.window, document: dom.window.document, IS_REACT_ACT_ENVIRONMENT: true }); |
| 11 | const root = createRoot(document.getElementById("root")!); |
| 12 | function deferred() { |
| 13 | let resolve!: (value: RewindResultView) => void; |
| 14 | const promise = new Promise<RewindResultView>((yes) => { resolve = yes; }); |
| 15 | return { promise, resolve }; |
| 16 | } |
| 17 | function user(text: string, checkpointTurn: number): Item { |
| 18 | return { kind: "user", id: `u:${text}`, text, submitText: text, checkpointTurn } as Item; |
| 19 | } |
| 20 | const calls: string[] = []; |
| 21 | const outcomes = new Map<string, { outcome?: RewindResultView; gate?: ReturnType<typeof deferred> }>(); |
| 22 | let states!: ReturnType<typeof useSessionUndo>; |
| 23 | function Probe({ readOnly = false, hydrating = false }: { readOnly?: boolean; hydrating?: boolean }) { |
| 24 | const items: Item[] = hydrating ? [] : [user("one", 1), user("two", 2)]; |
| 25 | states = useSessionUndo({ |
| 26 | activeTabId: "A", activeTabReadOnly: readOnly, items, |
| 27 | hydratePlaceholderActive: hydrating, controllerReady: true, running: false, |
| 28 | messageActionOpen: false, approvalOpen: false, askOpen: false, clearContextPending: false, |
| 29 | ports: { |
| 30 | rewindForTab: async () => { calls.push("rewind"); return true; }, |
| 31 | rewindForTabDetailed: async (tabId, turn, scope) => { |
| 32 | calls.push(`detailed:${tabId}:${turn}:${scope}`); |
| 33 | const entry = outcomes.get(`${turn}:${scope}`); |
| 34 | if (entry?.gate) return entry.gate.promise; |
| 35 | return entry?.outcome ?? { ok: true }; |
| 36 | }, |
| 37 | forkTurnForTab: async (tabId, target) => { calls.push(`fork:${tabId}:${target.turnId}`); return true; }, |
| 38 | refreshTabMetas: () => { calls.push("refresh-metas"); }, |
| 39 | undoRewindForTab: async () => { calls.push("undo"); return true; }, |
| 40 | sendToTab: async () => { calls.push("send"); }, |
| 41 | composeInsert: (_tabId, text) => { calls.push(`insert:${text}`); }, |
| 42 | refreshDock: () => { calls.push("dock"); }, |
| 43 | refreshProject: () => { calls.push("project"); }, |
| 44 | }, |
| 45 | }); |
| 46 | return null; |
| 47 | } |
| 48 | const paint = (options?: { readOnly?: boolean; hydrating?: boolean }) => act(async () => root.render(<Probe {...options} />)); |
| 49 | try { |
| 50 | await paint(); |
| 51 | await act(async () => { await states.handleMessageAction(0, "code"); }); |
| 52 | assert.equal(states.rewindState?.turnDiff, 0, "code-only rewind stores a zero-turn undo banner"); |
| 53 | assert.equal(states.rewindState?.transactionId, undefined, "empty backend result leaves no transaction id"); |
| 54 | assert.ok(calls.includes("dock") && calls.includes("project"), "code rewind refreshes files and project after success"); |
| 55 | assert.ok(!calls.some((call) => call.startsWith("insert:")), "code rewind never fills the composer"); |
| 56 | |
| 57 | outcomes.set("0:code", { outcome: { ok: true, transactionId: "tx-9", undoAvailable: true, written: ["a.txt"], deleted: [] } }); |
| 58 | calls.length = 0; |
| 59 | await act(async () => { await states.handleMessageAction(0, "code"); }); |
| 60 | assert.equal(states.rewindState?.transactionId, "tx-9", "code-only rewind retains the committed transaction id for real undo"); |
| 61 | assert.equal(states.rewindState?.undoAvailable, true, "undo stays available when the backend reports it"); |
| 62 | |
| 63 | calls.length = 0; |
| 64 | await act(async () => { states.setRewindStateForTab("A", null); }); |
| 65 | assert.equal(states.rewindState, null, "setRewindStateForTab clears the source banner"); |
| 66 | |
| 67 | await act(async () => { await states.handleMessageAction(5, "both"); }); |
| 68 | assert.ok(calls.includes("rewind"), "a turn with no matching user boundary falls back to the controller rewind"); |
| 69 | assert.ok(calls.includes("dock") && calls.includes("project"), "fallback refresh still runs for scope both"); |
| 70 | |
| 71 | outcomes.set("1:both", { gate: deferred() }); |
| 72 | calls.length = 0; |
| 73 | const full = states.handleMessageAction(1, "both"); |
| 74 | await act(async () => {}); |
| 75 | await act(async () => { |
| 76 | outcomes.get("1:both")!.gate!.resolve({ ok: true, transactionId: "tx-2", undoAvailable: true, written: [], deleted: [] }); |
| 77 | await full; |
| 78 | }); |
| 79 | assert.equal(states.rewindState?.transactionId, "tx-2", "full rewind records the committed transaction id"); |
| 80 | assert.ok(calls.includes("insert:one"), "successful full rewind fills the composer with the original prompt"); |
| 81 | assert.ok(!calls.includes("refresh-metas"), "full rewind does not trigger a tab-list refresh"); |
| 82 | assert.equal(states.rewindCommitting, false, "committing flag clears after success"); |
| 83 | |
| 84 | outcomes.set("2:both", { gate: deferred() }); |
| 85 | calls.length = 0; |
| 86 | const failed = states.handleMessageAction(2, "both"); |
| 87 | await act(async () => {}); |
| 88 | await act(async () => { |
| 89 | outcomes.get("2:both")!.gate!.resolve({ ok: false }); |
| 90 | await failed; |
| 91 | }); |
| 92 | assert.equal(states.rewindState?.transactionId, "tx-2", "failed rewind leaves the previous banner untouched"); |
| 93 | assert.ok(!calls.some((call) => call.startsWith("insert:")), "failed rewind inserts nothing"); |
| 94 | assert.equal(states.rewindCommitting, false, "committing flag clears after failure"); |
| 95 | |
| 96 | calls.length = 0; |
| 97 | await act(async () => { states.setRewindStateForTab("A", { turnDiff: 1, transactionId: "pending-tx", undoAvailable: true }); }); |
| 98 | await act(async () => { await states.handleEditPrompt(0, " edited ", " submit "); }); |
| 99 | assert.deepEqual(calls, [], "edit prompt is blocked while an undo banner owns the source tab"); |
| 100 | |
| 101 | await act(async () => { states.setRewindStateForTab("A", null); }); |
| 102 | calls.length = 0; |
| 103 | outcomes.set("0:conversation", { outcome: { ok: true, tabId: "A", transactionId: "edit-tx", undoAvailable: true } }); |
| 104 | await act(async () => { await states.handleEditPrompt(0, " edited ", " submit "); }); |
| 105 | assert.ok(calls.includes("detailed:A:0:conversation"), "allowed edit rewinds through the detailed backend"); |
| 106 | assert.ok(calls.includes("send"), "allowed edit resends the edited prompt after the conversation rewind"); |
| 107 | |
| 108 | const forkTarget: ForkTargetView = { sourceSessionId: "session-A", sessionGeneration: 1, |
| 109 | turnId: "turn-9", boundarySequence: 99, turnNumber: 9, status: "committed", available: true }; |
| 110 | const forkTurn = async () => { |
| 111 | await act(async () => { |
| 112 | states.handleForkTurn(forkTarget); |
| 113 | await new Promise((resolve) => setTimeout(resolve, 0)); |
| 114 | }); |
| 115 | }; |
| 116 | |
| 117 | calls.length = 0; |
| 118 | await forkTurn(); |
| 119 | assert.deepEqual(calls, ["fork:A:turn-9", "refresh-metas", "project"], "a turn fork creates the child from its turn identity and refreshes the tab list"); |
| 120 | |
| 121 | // A fork never writes into the source, so a read-only source still forks. |
| 122 | await paint({ readOnly: true }); |
| 123 | calls.length = 0; |
| 124 | await forkTurn(); |
| 125 | assert.ok(calls.includes("fork:A:turn-9"), "read-only sources fork: the child is written from the source, never into it"); |
| 126 | |
| 127 | console.log("session undo lifecycle: code transaction retention, banners, failed rewinds, edit gates and turn forks passed"); |
| 128 | } finally { dom.window.close(); } |
| 129 |