返回 DeepSeek-Reasonix
remote-session-badges.test.tsx
根目录 / desktop / frontend / src / __tests__ / remote-session-badges.test.tsx
1 import assert from "node:assert/strict";
2 import React, { act, useEffect } from "react";
3 import { JSDOM } from "jsdom";
4 import { installDesktopHostStub } from "./desktopHostStub";
5 import type { RemoteSessionView } from "../lib/types";
6 import type { RuntimeProjection, RuntimeSession } from "../lib/runtimeStateStore";
7
8 const dom = new JSDOM('<div id="root"></div>', { url: "http://localhost/" });
9 globalThis.window = dom.window as unknown as Window & typeof globalThis;
10 globalThis.document = dom.window.document;
11 globalThis.localStorage = dom.window.localStorage;
12 Object.defineProperty(globalThis, "navigator", { configurable: true, value: dom.window.navigator });
13 (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
14 const row = (id: string, resultSequence: number) => ({ name: id, sessionId: id, title: id, turns: 1, resultSequence, metadataReady: true });
15 let rows: RemoteSessionView[] = [row("a", 3), row("b", 0)];
16 let loads = 0;
17 let deferred = false;
18 const pending: Array<(rows: RemoteSessionView[]) => void> = [];
19 const host = installDesktopHostStub({
20 async RemoteConnectionStatuses() { return [{ hostId: "host", state: "connected" }]; },
21 async RemoteServerStatus() { return { hostId: "host", state: "ready" }; },
22 async RemoteProjectSessions() {
23 loads++;
24 if (deferred) return new Promise<RemoteSessionView[]>(resolve => pending.push(resolve));
25 return rows;
26 },
27 });
28 const [{ createRoot }, groups, reads, topics, runtime, { useRemoteStore }] = await Promise.all([
29 import("react-dom/client"), import("../components/ProjectTreeRemoteGroups"),
30 import("../components/useProjectTreeReadActivity"), import("../lib/projectTreeTopic"),
31 import("../lib/runtimeStateStore"), import("../store/remote"),
32 ]);
33 const tree = [{ key: "remote", kind: "project" as const, label: "Remote", remote: { hostId: "host", workspace: "/repo" } }];
34 const expanded = new Set(["remote"]);
35 const toast = () => {};
36 const t = (key: string) => key;
37 function session(id: string, phase: "executing" | "idle", seq: number): RuntimeSession {
38 return { tabId: "tab", scope: "remote", workspaceRoot: "/repo", topicId: id, sessionId: id,
39 sessionPath: `session-id:${id}`, sessionGeneration: 1, open: id === "b", remote: true, hostId: "host", freshness: "synced",
40 state: { schemaVersion: 1, runtimeEpoch: id, revision: seq + 1, activityRevision: seq,
41 phase, running: phase === "executing", turnId: id, turnStatus: phase === "idle" ? "completed" : "running",
42 turnEventSeq: seq, durableEventSeq: seq, pendingPrompt: false, cancelRequested: false,
43 cancellable: phase === "executing", backgroundJobs: 0, activity: "" } };
44 }
45 let revision = 0;
46 const publish = (sessions: RuntimeSession[]) => runtime.runtimeStateStore.commit({ epoch: "desktop", revision: ++revision, topics: [], sessions } satisfies RuntimeProjection);
47 publish([session("a", "executing", 3), session("b", "executing", 0)]);
48 useRemoteStore.getState().hydrateStatuses([{ hostId: "host", state: "connected" }]);
49 function Probe({ active = "b" }: { active?: string }) {
50 const group = groups.useRemoteProjectGroups(tree, toast, expanded, "");
51 const nodes = groups.useRemoteRuntimeTree(tree, group.remoteSessions, t);
52 const read = reads.useProjectTreeReadActivity(nodes);
53 useEffect(() => {
54 const node = nodes[0].children?.find(node => node.remoteSession?.sessionId === active);
55 if (node) read.markNodeRead(node);
56 }, [active, nodes, read.markNodeRead]);
57 return <>{nodes[0].children?.map(node => <span key={node.key} data-session={node.remoteSession!.sessionId}
58 data-unread={topics.projectTreeTopicHasUnreadActivity(node, read.readActivity, undefined, undefined, undefined, undefined, read.readBaselineAt,
59 { hostId: "host", workspace: "/repo", sessionId: active })} data-status={node.status ?? ""} />)}</>;
60 }
61 const root = createRoot(document.getElementById("root")!);
62 const flush = async () => { for (let i = 0; i < 15; i++) await Promise.resolve(); await new Promise(resolve => setTimeout(resolve, 0)); };
63 const unread = (id: string) => document.querySelector(`[data-session="${id}"]`)?.getAttribute("data-unread");
64 await act(async () => { root.render(<Probe />); await flush(); });
65 assert.equal(unread("a"), "false");
66 const baselineLoads = loads;
67 await act(async () => {
68 host.emit("remote-tab:updated", { id: "tab", remote: tree[0].remote, running: true });
69 publish([session("a", "executing", 4), session("b", "executing", 1)]);
70 await flush();
71 });
72 assert.equal(loads, baselineLoads, "streaming does not continuously reload the listing");
73 rows = [row("a", 6), row("b", 0)];
74 await act(async () => {
75 publish([session("a", "idle", 6), session("b", "executing", 2)]);
76 publish([session("a", "idle", 6), session("b", "executing", 3)]);
77 await flush();
78 });
79 assert.equal(loads, baselineLoads + 1, "background completion refreshes once while foreground is still busy");
80 assert.equal(unread("a"), "true", "A gains a blue dot without selecting it");
81 assert.equal(document.querySelector('[data-session="a"]')?.getAttribute("data-status"), "", "normal completion is not disconnected");
82 await act(async () => { root.render(<Probe active="a" />); await flush(); });
83 assert.equal(unread("a"), "false", "selecting A clears the blue dot");
84 await act(async () => { root.render(<Probe />); await flush(); });
85
86 // Removal of a completed detached runtime is also an authoritative refresh
87 // boundary, including when its terminal SSE was missed.
88 rows = [row("a", 9), row("b", 0)];
89 await act(async () => { publish([session("b", "executing", 4)]); await flush(); });
90 assert.equal(unread("a"), "true");
91
92 // A listing started before a later completion cannot replace its result count.
93 deferred = true;
94 await act(async () => { publish([session("a", "executing", 9), session("b", "executing", 4)]); await flush(); });
95 await act(async () => { publish([session("a", "idle", 12), session("b", "executing", 4)]); await flush(); });
96 await act(async () => { publish([session("a", "idle", 15), session("b", "executing", 4)]); await flush(); });
97 assert.equal(pending.length, 2);
98 await act(async () => { pending[1]([row("a", 15), row("b", 0)]); await flush(); });
99 await act(async () => { root.render(<Probe active="a" />); await flush(); });
100 await act(async () => { pending[0]([row("a", 12), row("b", 0)]); await flush(); });
101 const stored = JSON.parse(localStorage.getItem("projectTree:readActivity:v3")!);
102 assert.equal(stored.records["ref\0host\0a"].value, 15, "stale listing cannot lower the confirmed read");
103
104 // Drive metadata retry timers explicitly: a pending catalog must not seed a
105 // placeholder baseline, and a permanently pending catalog has a finite budget.
106 deferred = false;
107 const nativeTimeout = globalThis.setTimeout, nativeClearTimeout = globalThis.clearTimeout;
108 const retryTimers = new Map<number, () => void>();
109 let timerId = -1;
110 globalThis.setTimeout = ((callback: (...args: unknown[]) => void, delay?: number, ...args: unknown[]) => {
111 if (delay !== 1000) return nativeTimeout(callback, delay, ...args);
112 const id = timerId--;
113 retryTimers.set(id, () => callback(...args));
114 return id;
115 }) as typeof setTimeout;
116 globalThis.clearTimeout = ((id: ReturnType<typeof setTimeout>) => {
117 if (!retryTimers.delete(Number(id))) nativeClearTimeout(id);
118 }) as typeof clearTimeout;
119 const advanceRetry = async () => {
120 assert.equal(retryTimers.size, 1);
121 const [id, callback] = [...retryTimers.entries()][0];
122 retryTimers.delete(id);
123 await act(async () => { callback(); await flush(); });
124 };
125 await act(async () => { root.render(<Probe />); await flush(); });
126 rows = [{ ...row("a", 0), metadataReady: false }, row("b", 0)];
127 await act(async () => { publish([session("a", "idle", 18), session("b", "executing", 4)]); await flush(); });
128 assert.equal(unread("a"), "false");
129 rows = [row("a", 18), row("b", 0)];
130 await advanceRetry();
131 assert.equal(unread("a"), "true", "ready metadata reveals the completed result without another runtime event");
132 assert.equal(retryTimers.size, 0);
133 rows = [{ ...row("a", 0), metadataReady: false }, row("b", 0)];
134 await act(async () => { publish([session("a", "idle", 21), session("b", "executing", 4)]); await flush(); });
135 for (let retry = 0; retry < 5; retry++) await advanceRetry();
136 assert.equal(retryTimers.size, 0, "metadata retries stop after five requests");
137 await act(async () => root.unmount());
138 globalThis.setTimeout = nativeTimeout;
139 globalThis.clearTimeout = nativeClearTimeout;
140 host.uninstall();
141 dom.window.close();
142 console.log("remote badges: background completion, read clearing, runtime retirement and stale listing passed");
143
143 lines Plain Text