Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

replay.js

292 lines10.5 KB

1/** Capture-only protocol fixture. Install before modules; never import in product code.
2 * Pass options through sessionStorage sidebar-capture-config.replay. Real server
3 * frames still travel through the real RPC decoder and client reducers.
4 */
5(() => {
6 const options = JSON.parse(sessionStorage.getItem("sidebar-capture-config") || "{}").replay || {};
7 const NativeWebSocket = WebSocket;
8 const held = [];
9 globalThis.__sidebarWire = [];
10 const frames = [];
11 globalThis.__sidebarReplay = {
12 frames,
13 held,
14 release() {
15 if (delayedThread && delayedStream) {
16 releaseThread(delayedStream, delayedThread);
17 delayedThread = null;
18 delayedStream = null;
19 }
20 for (const run of held.splice(0)) run();
21 },
22 };
23​
24 let delayedThread = null;
25 let delayedStream = null;
26 let latestShellStream = null;
27 let shellSequence = 0;
28 const releaseThread = (stream, thread, emit = stream.emit) => {
29 // Insert one fixture event into this subscription's sequence space; later
30 // server events must carry the same offset or the reducer drops the next one.
31 stream.offset++;
32 emit({
33 kind: "thread.updated",
34 sequence: ++stream.sequence,
35 location: "active",
36 thread,
37 });
38 };
39 const parseFrame = (data) => {
40 try {
41 const value = JSON.parse(data);
42 const ndjson = data.endsWith("\n") && !Array.isArray(value);
43 return { value: ndjson ? [value] : value, ndjson };
44 } catch {
45 return {
46 value: data
47 .trim()
48 .split("\n")
49 .map((line) => JSON.parse(line)),
50 ndjson: true,
51 };
52 }
53 };
54 const transformSnapshot = (
55 snapshot,
56 hold = (thread) => {
57 delayedThread = thread;
58 },
59 ) => {
60 snapshot.threads = snapshot.threads.filter(
61 (t) =>
62 t.id.startsWith("triage-") && (options.lineage || !/^triage-A-(9|10|11|12)$/.test(t.id)),
63 );
64 if (options.shelf === "settled") {
65 const source = snapshot.threads.find((t) => t.id === "triage-A-8");
66 if (source)
67 for (let i = 13; i <= 26; i++)
68 snapshot.threads.push({
69 ...source,
70 id: "triage-A-" + i,
71 title: "Triage A thread " + i,
72 latestMessageAt: "2026-10-21T23:" + String(i).padStart(2, "0") + ":00.000Z",
73 updatedAt: "2026-10-21T23:" + String(i).padStart(2, "0") + ":00.000Z",
74 });
75 }
76 snapshot.projects = snapshot.projects?.filter((p) => p.id?.startsWith("triage-")) || [];
77 for (const thread of snapshot.threads) {
78 if (thread.id === "triage-A-1" && options.shelf) {
79 Object.assign(thread, {
80 pinnedAt: null,
81 snoozedUntil: null,
82 settledOverride: null,
83 settledAt: null,
84 });
85 if (options.shelf === "pinned")
86 Object.assign(thread, { pinnedAt: "2026-10-22T00:00:00.000Z", pinOrderKey: "a0" });
87 if (options.shelf === "snoozed")
88 Object.assign(thread, {
89 snoozedUntil: "2099-01-01T00:00:00.000Z",
90 snoozedAt: "2026-10-22T00:00:00.000Z",
91 });
92 if (options.shelf === "working")
93 Object.assign(thread, {
94 status: "running",
95 activeRunId: "triage-run-working",
96 latestRunId: "triage-run-working",
97 activityRunStatus: "running",
98 latestRunRequestedAt: "2026-10-21T23:00:00.000Z",
99 latestRunStartedAt: "2026-10-21T23:00:00.000Z",
100 });
101 }
102 if (options.shelf === "settled" && thread.projectId === "triage-project-A") {
103 Object.assign(thread, { settledOverride: "settled", settledAt: thread.createdAt });
104 }
105 if (options.status && ["triage-A-1", "triage-A-2"].includes(thread.id)) {
106 Object.assign(thread, {
107 status: thread.id === "triage-A-1" ? "failed" : "completed",
108 latestRunId: "triage-run-" + thread.id,
109 latestRunRequestedAt: "2026-10-21T23:00:00.000Z",
110 latestRunCompletedAt: "2026-10-21T23:01:00.000Z",
111 lastVisitedAt: null,
112 });
113 }
114 }
115 if (options.delay) {
116 const target = snapshot.threads.find((t) => t.id === "triage-A-1");
117 if (target) hold(target);
118 snapshot.threads = snapshot.threads.filter((t) => t.id !== "triage-A-1");
119 }
120 return snapshot;
121 };
122 const nativeFetch = fetch;
123 globalThis.fetch = async (...args) => {
124 const response = await nativeFetch(...args);
125 const url = String(args[0]?.url ?? args[0]);
126 if (!options.enabled || !url.includes("/api/orchestration/shell") || !response.ok)
127 return response;
128 const value = await response.clone().json();
129 if (!Array.isArray(value.threads)) return response;
130 frames.push({
131 kind: "http.shell",
132 count: value.threads.length,
133 sequence: value.snapshotSequence,
134 });
135 shellSequence = value.snapshotSequence;
136 transformSnapshot(value);
137 if (delayedThread && latestShellStream) {
138 delayedStream = latestShellStream;
139 delayedStream.sequence = Math.max(delayedStream.sequence, shellSequence);
140 }
141 return new Response(JSON.stringify(value), {
142 status: response.status,
143 headers: { "content-type": "application/json" },
144 });
145 };
146​
147 globalThis.WebSocket = class extends NativeWebSocket {
148 send(data) {
149 if (!options.enabled || typeof data !== "string") return super.send(data);
150 try {
151 const { value, ndjson } = parseFrame(data);
152 let changed = false;
153 for (const request of Array.isArray(value) ? value : [value]) {
154 if (request?._tag === "Request" && request.tag === "orchestration.subscribeShell") {
155 const afterSequence = request.payload?.afterSequence;
156 // Foreground resumes reuse this socket's client cursor. A new RPC
157 // session owns a new socket and reloads the authoritative HTTP shell.
158 const offset =
159 typeof afterSequence === "number" ? (this.latestShellStream?.offset ?? 0) : 0;
160 if (offset !== 0) {
161 request.payload.afterSequence -= offset;
162 changed = true;
163 }
164 const stream = {
165 sequence: afterSequence ?? shellSequence,
166 offset,
167 emit: (node) =>
168 this.replayDeliver({
169 _tag: "Chunk",
170 requestId: request.id,
171 values: [node],
172 }),
173 };
174 this.shellStreams.set(request.id, stream);
175 this.latestShellStream = stream;
176 latestShellStream = stream;
177 if (delayedThread && !delayedStream) delayedStream = stream;
178 } else if (
179 request?._tag === "Request" &&
180 request.tag === "orchestration.subscribeThread"
181 ) {
182 this.threadRequests.add(request.id);
183 }
184 }
185 if (changed)
186 data = ndjson
187 ? value.map((item) => JSON.stringify(item)).join("\n") + "\n"
188 : JSON.stringify(value);
189 } catch {
190 // Non-JSON socket traffic belongs to the native protocol handler.
191 }
192 super.send(data);
193 }
194 latestShellStream = null;
195 shellStreams = new Map();
196 threadRequests = new Set();
197 replayDeliver;
198 constructor(...args) {
199 super(...args);
200 let replaying = false;
201 this.replayDeliver = (data) => {
202 replaying = true;
203 try {
204 this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify(data) }));
205 } finally {
206 replaying = false;
207 }
208 };
209 this.addEventListener("message", (event) => {
210 if (replaying) return;
211 frames.push({
212 kind: "frame",
213 type: typeof event.data,
214 constructor: event.data?.constructor?.name,
215 length: event.data?.length,
216 });
217 if (typeof event.data !== "string") return;
218 let value;
219 let ndjson;
220 try {
221 ({ value, ndjson } = parseFrame(event.data));
222 } catch {
223 frames.push({ kind: "unparsed", length: event.data.length });
224 return;
225 }
226 globalThis.__sidebarWire.push(value);
227 frames.push({
228 kind: "parsed",
229 tag: value?._tag,
230 keys: Object.keys(value || {}),
231 count: Array.isArray(value) ? value.length : undefined,
232 });
233 let changed = false;
234 const deliver = (data) => {
235 replaying = true;
236 try {
237 this.dispatchEvent(
238 new MessageEvent("message", {
239 data: ndjson
240 ? data.map((item) => JSON.stringify(item)).join("\n") + "\n"
241 : JSON.stringify(data),
242 }),
243 );
244 } finally {
245 replaying = false;
246 }
247 };
248 if (options.enabled) {
249 for (const chunk of Array.isArray(value) ? value : [value]) {
250 if (chunk?._tag !== "Chunk" || !Array.isArray(chunk.values)) continue;
251 if (this.threadRequests.has(chunk.requestId)) continue;
252 let stream = this.shellStreams.get(chunk.requestId);
253 if (!stream && chunk.values.some((node) => Array.isArray(node?.snapshot?.threads))) {
254 stream = { sequence: 0, offset: 0 };
255 this.shellStreams.set(chunk.requestId, stream);
256 }
257 if (!stream) continue;
258 stream.emit = (node) => {
259 const update = { ...chunk, values: [node] };
260 deliver(Array.isArray(value) ? [update] : update);
261 };
262 for (const node of chunk.values) {
263 if (typeof node?.sequence === "number") {
264 node.sequence += stream.offset;
265 stream.sequence = Math.max(stream.sequence, node.sequence);
266 changed ||= stream.offset !== 0;
267 }
268 if (node?.kind !== "snapshot" || !Array.isArray(node.snapshot?.threads)) continue;
269 node.snapshot.snapshotSequence += stream.offset;
270 stream.sequence = Math.max(stream.sequence, node.snapshot.snapshotSequence);
271 const snapshot = node.snapshot;
272 frames.push({
273 kind: "shell.snapshot",
274 count: snapshot.threads.length,
275 sequence: snapshot.snapshotSequence,
276 });
277 transformSnapshot(snapshot, (thread) => {
278 const emit = stream.emit;
279 held.push(() => releaseThread(stream, thread, emit));
280 });
281 changed = true;
282 }
283 }
284 }
285 if (changed) {
286 event.stopImmediatePropagation();
287 deliver(value);
288 }
289 });
290 }
291 };
292})();