返回 DeepSeek-Reasonix
canonical-navigation-hydration.test.tsx
根目录 / desktop / frontend / src / __tests__ / canonical-navigation-hydration.test.tsx
1 import assert from "node:assert/strict";
2 import React, { act } from "react";
3 import { createRoot } from "react-dom/client";
4 import { installRemoteSurfaceDom } from "./helpers/remoteSurfaceDom";
5 import { installDesktopHostStub } from "./desktopHostStub";
6 import { meta, tabMeta } from "./helpers/sessionSwitchFixtures";
7 import { useController } from "../lib/useController";
8 import type { FollowRequest, TranscriptFollowResponse } from "../generated/desktopContract.generated";
9
10 function deferred<T>() {
11 let resolve!: (value: T) => void;
12 const promise = new Promise<T>(done => { resolve = done; });
13 return { promise, resolve };
14 }
15 const dom = installRemoteSurfaceDom();
16 let current = "first";
17 let epoch = "first-epoch";
18 const reads: string[] = [];
19 let opened = deferred<void>();
20 let releaseOpen = deferred<void>();
21 let baseline = deferred<void>();
22 let bindingCommitted = true;
23 let controller!: ReturnType<typeof useController>;
24 const currentMeta = () => meta({ session: { hostId: "local", sessionId: current }, sessionPath: `session-id:${current}`,
25 sessionGeneration: 1, runtime: { phase: "ready", epoch } });
26 const stub = installDesktopHostStub({
27 RegisterNavigationIntent: async () => {},
28 ListTabs: async () => [tabMeta({ ...currentMeta(), active: true })],
29 MetaForTab: async () => currentMeta(),
30 ReplayPendingPrompts: async () => {}, ReplayPendingPromptsForTab: async () => {},
31 ContextUsageForTab: async () => ({ used: 0, window: 100, sessionTokens: 0 }),
32 EffortForTab: async () => ({ supported: false, current: "auto", levels: [] }),
33 BalanceForTab: async () => ({ available: false, display: "" }), JobsForTab: async () => [],
34 CheckpointsForTab: async () => [], ForkTargetsForTab: async () => ({ targets: [], verifiable: false }),
35 OpenSession: async (ref: { sessionId: string }) => {
36 bindingCommitted = false;
37 current = ref.sessionId; epoch = `${current}-epoch`;
38 stub.emit("runtime:rebuilt", "tab-a", epoch);
39 stub.emit("runtime:rebuilt", "tab-a", epoch);
40 stub.emit("agent:ready", "tab-a");
41 opened.resolve();
42 await releaseOpen.promise;
43 bindingCommitted = true;
44 },
45 TranscriptFollowForTab: async (_tab: string, request: FollowRequest): Promise<TranscriptFollowResponse> => {
46 if (request.close) return { protocolVersion: 2, subscription: request.subscription, changes: [], resetRequired: false };
47 if (request.subscription) return new Promise(() => {});
48 const id = current, boundEpoch = epoch;
49 reads.push(id);
50 if (!bindingCommitted) throw new Error("runtime changed while following transcript");
51 if (id !== "first") await baseline.promise;
52 return { protocolVersion: 2, subscription: `${id}-${reads.length}`, changes: [], resetRequired: false,
53 snapshot: { protocolVersion: 1, snapshotId: id,
54 identity: { sessionId: id, runtimeEpoch: boundEpoch, rewriteEpoch: 0, headId: "" },
55 projectionRevision: 1, coveredThroughSeq: 1, durableSeq: 1, records: [], activeRecords: [], activeAttempts: [],
56 runtime: { status: "completed", pendingEvents: [], samplingCount: 0, toolCount: 0 },
57 before: 0, hasOlder: false, totalRecords: 0, totalTurns: 0, stale: false },
58 history: { status: "ready", snapshotSequence: 1, coverageSequence: 1, generation: id,
59 totalTurns: 0, hasOlder: false, hasNewer: false, messages: [] } };
60 },
61 });
62 const root = createRoot(document.getElementById("root")!);
63 function Probe() { controller = useController(); return null; }
64 async function drain() { await act(async () => { for (let i = 0; i < 40; i++) await new Promise(resolve => setImmediate(resolve)); }); }
65 try {
66 await act(async () => root.render(<Probe />));
67 await drain();
68 assert.ok(reads.includes("first"), "startup is hydrated");
69 reads.length = 0;
70 let navigation!: Promise<void>;
71 await act(async () => {
72 const intent = controller.noteNavigationIntent();
73 navigation = controller.openCanonicalSession({ hostId: "local", sessionId: "second" }, intent);
74 await opened.promise;
75 });
76 await drain();
77 act(() => releaseOpen.resolve());
78 await drain();
79 await act(async () => { baseline.resolve(); await navigation; });
80 await drain();
81 assert.equal(reads.filter(id => id === "second").length, 1,
82 "ready/rebuilt notifications and explicit navigation share one target baseline");
83 assert.equal(controller.state.meta?.session?.sessionId, "second");
84 assert.equal(controller.state.hydrateError, undefined);
85 await act(async () => {
86 stub.emit("runtime:rebuilt", "tab-a", epoch);
87 stub.emit("agent:ready", "tab-a");
88 });
89 await drain();
90 assert.equal(reads.length, 1, "late notifications for the installed runtime do not reload its baseline");
91 epoch = "second-replacement-epoch";
92 await act(async () => stub.emit("runtime:rebuilt", "tab-a", epoch));
93 await drain();
94 assert.equal(reads.length, 2, "an actual runtime replacement still establishes a new subscription");
95
96 const slowOpened = deferred<void>(), slowReply = deferred<void>();
97 const lastOpened = deferred<void>(), lastReply = deferred<void>();
98 stub.commands.OpenSession = async (ref: { sessionId: string }) => {
99 if (ref.sessionId === "superseded") {
100 slowOpened.resolve(); await slowReply.promise; return;
101 }
102 current = ref.sessionId; epoch = `${current}-epoch`; bindingCommitted = false;
103 stub.emit("runtime:rebuilt", "tab-a", epoch);
104 stub.emit("agent:ready", "tab-a");
105 lastOpened.resolve(); await lastReply.promise; bindingCommitted = true;
106 };
107 let slow!: Promise<void>, last!: Promise<void>;
108 await act(async () => {
109 slow = controller.openCanonicalSession({ hostId: "local", sessionId: "superseded" }, controller.noteNavigationIntent());
110 await slowOpened.promise;
111 });
112 await act(async () => {
113 last = controller.openCanonicalSession({ hostId: "local", sessionId: "last" }, controller.noteNavigationIntent());
114 await lastOpened.promise;
115 });
116 await act(async () => { slowReply.resolve(); await slow; stub.emit("agent:ready", "tab-a"); });
117 await drain();
118 assert.equal(reads.filter(id => id === "last").length, 0, "stale finally cannot release the newer navigation's hydration ownership");
119 await act(async () => { lastReply.resolve(); await last; });
120 await drain();
121 assert.equal(reads.filter(id => id === "last").length, 1);
122 assert.equal(controller.state.meta?.session?.sessionId, "last", "last canonical selection wins");
123
124 stub.commands.OpenSession = async () => { throw new Error("session not found"); };
125 await act(async () => {
126 await assert.rejects(controller.openCanonicalSession({ hostId: "local", sessionId: "missing" }, controller.noteNavigationIntent()), /session not found/);
127 });
128 epoch = "after-failed-open";
129 const beforeRecovery = reads.length;
130 await act(async () => { stub.emit("runtime:rebuilt", "tab-a", epoch); });
131 await drain();
132 assert.equal(reads.length, beforeRecovery + 1, "failed navigation releases ownership so later runtime recovery works");
133 assert.equal(controller.state.meta?.session?.sessionId, "last", "failed target never replaces the source identity");
134 } finally {
135 baseline.resolve(); releaseOpen.resolve();
136 await act(async () => root.unmount());
137 stub.uninstall(); dom.window.close();
138 }
139 console.log("PASS canonical navigation performs one target baseline");
140
140 lines Plain Text