返回 DeepSeek-Reasonix
remote-session-history-prime.test.tsx
根目录 / desktop / frontend / src / __tests__ / remote-session-history-prime.test.tsx
1 // Run: node --import ./scripts/svg-stub-register.mjs --import tsx src/__tests__/remote-session-history-prime.test.tsx
2 // The pre-activation history prime in useRemoteSession publishes a durable
3 // baseline for a blank remote tab, but the follower owns the resident store
4 // once it has published. These cases pin the ordering: a late legacy window
5 // can neither replace follower records nor bump the store generation, retries
6 // after ownership are no-ops, and a transcript that already has content is
7 // never primed.
8 import React, { act } from "react";
9 import { JSDOM } from "jsdom";
10 import { mock } from "node:test";
11 import type { AppBindings } from "../lib/bridge";
12 import type { FollowRequest, HistoryWindowPage, TranscriptFollowResponse } from "../generated/desktopContract.generated";
13 import type { TabMeta } from "../lib/types";
14 import type { RemoteSessionApi } from "../lib/useRemoteSession";
15 import { installDesktopHostStub } from "./desktopHostStub";
16
17 let passed = 0, failed = 0;
18 function ok(value: boolean, label: string) {
19 process.stdout.write(` ${value ? "PASS" : "FAIL"} ${label}\n`);
20 if (value) passed += 1; else failed += 1;
21 }
22 console.log("\nRemote session early history prime ownership");
23 const dom = new JSDOM("<!doctype html><html><body><div id=\"root\"></div></body></html>", { pretendToBeVisual: true, url: "http://localhost/" });
24 (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
25 globalThis.window = dom.window as unknown as Window & typeof globalThis;
26 globalThis.document = dom.window.document;
27 Object.defineProperty(globalThis, "navigator", { configurable: true, value: dom.window.navigator });
28 globalThis.localStorage = dom.window.localStorage;
29 globalThis.requestAnimationFrame = dom.window.requestAnimationFrame?.bind(dom.window) ?? ((cb: FrameRequestCallback) => setTimeout(() => cb(Date.now()), 16) as unknown as number);
30 globalThis.cancelAnimationFrame = dom.window.cancelAnimationFrame?.bind(dom.window) ?? ((handle: number) => clearTimeout(handle));
31
32 function deferred<T>() {
33 let resolve!: (value: T) => void;
34 let reject!: (error: unknown) => void;
35 const promise = new Promise<T>((r, j) => { resolve = r; reject = j; });
36 return { promise, resolve, reject };
37 }
38 const tape: string[] = [];
39 const followMode = new Map<string, "ok" | "deferred">();
40 const followDeferred = new Map<string, ReturnType<typeof deferred<TranscriptFollowResponse>>>();
41 const polls = new Map<string, ReturnType<typeof deferred<TranscriptFollowResponse>>>();
42 const windowDeferred = new Map<string, ReturnType<typeof deferred<HistoryWindowPage>>>();
43 const status = { running: false, label: "Model", plan: false, toolApprovalMode: "ask", goal: "" };
44 const inline = (id: string, content: string) => ({ messageId: id, position: 0, version: 1, role: "assistant", eventSequence: 1, visibleTurn: 1, preview: "", inline: { id, role: "assistant", content } });
45 function followResponse(tabId: string): TranscriptFollowResponse {
46 return {
47 protocolVersion: 2, subscription: `sub-${tabId}`, changes: [], resetRequired: false,
48 snapshot: {
49 protocolVersion: 1, snapshotId: `cut-${tabId}`, identity: { sessionId: tabId, runtimeEpoch: "epoch", rewriteEpoch: 0, headId: "" },
50 projectionRevision: 10, coveredThroughSeq: 4, durableSeq: 4, records: [], activeRecords: [], activeAttempts: [],
51 runtime: { status: "completed", pendingEvents: [], samplingCount: 0, toolCount: 0 }, before: 0, hasOlder: false, totalRecords: 1, totalTurns: 1, stale: false,
52 },
53 history: { status: "ready", snapshotSequence: 4, coverageSequence: 4, generation: "gen", totalTurns: 1, hasOlder: false, hasNewer: false, messages: [inline("follower-answer", "follower answer")] },
54 };
55 }
56 const windowPage = (): HistoryWindowPage => ({ messages: [inline("primed-answer", "primed history")], status: "ready", snapshotSequence: 2, coverageSequence: 2, generation: "legacy", totalTurns: 1, hasOlder: false, hasNewer: false, olderCursor: "", newerCursor: "" });
57 const desktopStub = installDesktopHostStub({
58 async RegisterNavigationIntent() {},
59 async SetActiveTab() {},
60 async ForkTargetsRemoteTab() { return { targets: [], verifiable: false }; },
61 async RemoteTabStatus(tabId: string) { tape.push(`status:${tabId}`); return status; },
62 async RemoteTabMetadata(tabId: string) { tape.push(`metadata:${tabId}`); return { status }; },
63 async RemoteTabSnapshot(tabId: string) { tape.push(`snapshot:${tabId}`); return { history: [], status }; },
64 async RemoteTranscriptFollowForTab(tabId: string, request: FollowRequest) {
65 if (request.close) { tape.push(`close:${tabId}`); return { protocolVersion: 2, subscription: request.subscription ?? "", changes: [], resetRequired: false }; }
66 if (request.subscription) { const poll = deferred<TranscriptFollowResponse>(); polls.set(tabId, poll); return poll.promise; }
67 tape.push(`follow:${tabId}`);
68 if (followMode.get(tabId) === "deferred") {
69 const pending = deferred<TranscriptFollowResponse>();
70 followDeferred.set(tabId, pending);
71 return pending.promise;
72 }
73 return followResponse(tabId);
74 },
75 async RemoteSessionHistoryWindowForTab(tabId: string) {
76 tape.push(`window:${tabId}`);
77 const pending = deferred<HistoryWindowPage>();
78 windowDeferred.set(tabId, pending);
79 return pending.promise;
80 },
81 } as Partial<AppBindings> as AppBindings);
82
83 const [{ createRoot }, { useRemoteSession }, { getTranscriptStore }, { initialState }, { setTranscriptBindingIdentity }] = await Promise.all([
84 import("react-dom/client"), import("../lib/useRemoteSession"), import("../lib/transcriptStore"), import("../lib/useController"),
85 import("../lib/canonicalTranscriptBackend"),
86 ]);
87 // Production resolves remote tabs through the controller's meta; this harness
88 // has no controller, so bind the canonical reads to the remote bridge directly.
89 setTranscriptBindingIdentity(() => "remote");
90
91 async function flush(ticks = 4) {
92 for (let i = 0; i < ticks; i++) await Promise.resolve();
93 await new Promise((resolve) => setTimeout(resolve, 30));
94 }
95 let probe: RemoteSessionApi | undefined;
96 function Probe({ tabId, path }: { tabId: string; path: string }) {
97 probe = useRemoteSession(tabId, "ready", path);
98 return null;
99 }
100 const root = createRoot(document.getElementById("root")!);
101 const mount = (tabId: string, path: string) => act(async () => { root.render(<Probe tabId={tabId} path={path} />); await flush(); });
102 const count = (entry: string) => tape.filter((item) => item === entry).length;
103 const texts = () => (probe?.transcript.items ?? []).flatMap((item) => item.kind === "assistant" ? [item.text] : []);
104 const meta = (id: string): TabMeta => ({ id, scope: "project", workspaceRoot: "~/app", workspaceName: "app", topicId: "", topicTitle: "app", label: "box",
105 ready: true, running: false, mode: "normal", active: true, cwd: "~/app", sessionGeneration: 1, remote: { hostId: "box", workspace: "~/app" } } as TabMeta);
106
107 // 1. Follower publishes first; the prime's window resolves later.
108 followMode.set("tab-late-window", "ok");
109 await mount("tab-late-window", "/late-window");
110 ok(texts().includes("follower answer") && probe?.transcript.transcriptProtocol === 2, "the follower installs its cut while the legacy window read is still in flight");
111 const generationAfterFollower = getTranscriptStore().generationOf("tab-late-window", "/late-window");
112 await act(async () => { windowDeferred.get("tab-late-window")?.resolve(windowPage()); await flush(); });
113 ok(!texts().includes("primed history") && texts().includes("follower answer"), "a legacy window landing after the follower cut does not replace the transcript");
114 ok(!getTranscriptStore().peek("tab-late-window", "/late-window")?.items.some((item) => item.kind === "assistant" && item.text === "primed history"),
115 "a late legacy window does not overwrite follower records in the resident store");
116 const windowReadsBefore = count("window:tab-late-window");
117 await act(async () => { desktopStub.emit("remote-tab:updated", meta("tab-late-window")); await flush(); });
118 ok(count("window:tab-late-window") === windowReadsBefore, "attach publications after follower ownership do not re-read the legacy window");
119 ok(getTranscriptStore().generationOf("tab-late-window", "/late-window") === generationAfterFollower, "retired prime attempts leave the resident session generation alone");
120
121 // 2. Existing content is never primed, so the store is not even touched.
122 getTranscriptStore().setState("tab-resident", { ...initialState, items: [{ kind: "assistant", id: "m:seed", text: "resident answer", reasoning: "", streaming: false }] });
123 followMode.set("tab-resident", "deferred");
124 await mount("tab-resident", "/resident");
125 ok(count("window:tab-resident") === 0, "a transcript that already has content skips the legacy window read entirely");
126 ok(getTranscriptStore().generationOf("tab-resident", "/resident") === undefined, "skipping the prime creates no resident session and bumps no generation");
127 ok(texts().includes("resident answer"), "resident content stays visible while the follower is still connecting");
128
129 // 3. A blank tab whose follower is slow still gets the durable baseline, and the follower supersedes it.
130 followMode.set("tab-prime-first", "deferred");
131 await mount("tab-prime-first", "/prime-first");
132 await act(async () => { windowDeferred.get("tab-prime-first")?.resolve(windowPage()); await flush(); });
133 ok(texts().includes("primed history") && probe?.transcript.transcriptProtocol !== 2, "a blank tab is primed from the legacy window before the follower connects");
134 await act(async () => { followDeferred.get("tab-prime-first")?.resolve(followResponse("tab-prime-first")); await flush(); });
135 ok(texts().includes("follower answer") && !texts().includes("primed history") && probe?.transcript.transcriptProtocol === 2, "the follower cut supersedes the primed baseline");
136 const primeReads = count("window:tab-prime-first");
137 await act(async () => { desktopStub.emit("remote-tab:updated", meta("tab-prime-first")); await flush(); });
138 ok(count("window:tab-prime-first") === primeReads, "a primed-then-followed tab does not read the legacy window again");
139
140 // 4. The remote hook uses the same shell-stop fence as local followers.
141 await mount("tab-stopping", "/stopping");
142 const readsBeforeStop = count("follow:tab-stopping"), closesBeforeStop = count("close:tab-stopping");
143 const retainedItems = probe!.transcript.items;
144 mock.timers.enable({ apis: ["setTimeout"] });
145 try {
146 await act(async () => {
147 desktopStub.emitServiceState({ phase: "stopping", generation: "test-service" });
148 polls.get("tab-stopping")!.reject(new Error("desktop service is shutting down"));
149 for (let i = 0; i < 30; i++) await Promise.resolve();
150 mock.timers.tick(1000);
151 for (let i = 0; i < 30; i++) await Promise.resolve();
152 });
153 ok(count("follow:tab-stopping") === readsBeforeStop, "remote shutdown does not retry baseline reads");
154 ok(count("close:tab-stopping") === closesBeforeStop, "remote shutdown sends no subscription cleanup RPC");
155 ok(probe!.transcript.items === retainedItems, "remote shutdown retains the displayed transcript");
156 } finally { mock.timers.reset(); }
157
158 await act(async () => { root.unmount(); });
159 desktopStub.uninstall();
160 if (failed > 0) { console.error(`\n${failed} check(s) failed`); process.exit(1); }
161 console.log(`\n${passed} passed, 0 failed`);
162 process.exit(0);
163
163 lines Plain Text