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

ws.test.ts

461 lines17.9 KB

1import { assert, it } from "@effect/vitest";
2import {
3 ORCHESTRATION_PROTOCOL_VERSION,
4 ProjectId,
5 ThreadId,
6 type OrchestrationV2StoredEvent,
7 type OrchestrationProjectShell,
8 type ServerConfig,
9 type ServerConfigStreamEvent,
10} from "@t3tools/contracts";
11import * as HostProcess from "@t3tools/shared/HostProcess";
12import * as ConfigProvider from "effect/ConfigProvider";
13import * as Deferred from "effect/Deferred";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Fiber from "effect/Fiber";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Path from "effect/Path";
20import * as PubSub from "effect/PubSub";
21import * as Queue from "effect/Queue";
22import * as Stream from "effect/Stream";
23import * as TestClock from "effect/testing/TestClock";
24import { ChildProcessSpawner } from "effect/process";
25import * as SqlClient from "effect/sql/SqlClient";
26​
27import * as EventStore from "./orchestration-v2/EventStore.ts";
28import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts";
29import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts";
30import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts";
31import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
32import * as OrchestrationEventStore from "./persistence/OrchestrationEventStore.ts";
33import * as SqlitePersistence from "./persistence/Sqlite.ts";
34import * as ExternalLauncher from "./process/externalLauncher.ts";
35import * as ProjectEnrichment from "./project/ProjectEnrichmentService.ts";
36import * as ProjectService from "./project/ProjectService.ts";
37import {
38 hasCompatibleOrchestrationProtocol,
39 resolveAvailableEditorsForConfig,
40 shouldUseBoundedThreadSnapshot,
41 subscribeOrchestrationV2Shell,
42 subscribeOrchestrationV2Thread,
43 withLateEditorConfig,
44} from "./ws.ts";
45​
46it("accepts only the current orchestration protocol before websocket RPC setup", () => {
47 assert.isTrue(
48 hasCompatibleOrchestrationProtocol(
49 new URL(`https://host.test/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}`),
50 ),
51 );
52 assert.isFalse(hasCompatibleOrchestrationProtocol(new URL("https://host.test/ws")));
53 assert.isFalse(
54 hasCompatibleOrchestrationProtocol(
55 new URL(`https://host.test/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION - 1}`),
56 ),
57 );
58});
59​
60it("keeps full thread snapshot fallback unless the client opts into bounded history", () => {
61 assert.isFalse(shouldUseBoundedThreadSnapshot({}));
62 assert.isFalse(shouldUseBoundedThreadSnapshot({ acceptBoundedSnapshot: false }));
63 assert.isTrue(shouldUseBoundedThreadSnapshot({ acceptBoundedSnapshot: true }));
64});
65​
66it.effect("does not block server config when editor discovery never resolves", () =>
67 Effect.gen(function* () {
68 const discoveryInterrupted = yield* Deferred.make<void>();
69 const responseFiber = yield* resolveAvailableEditorsForConfig(
70 Effect.never.pipe(
71 Effect.onInterrupt(() => Deferred.succeed(discoveryInterrupted, undefined)),
72 ),
73 ).pipe(Effect.forkChild);
74​
75 yield* TestClock.adjust(Duration.seconds(5));
76​
77 const availableEditors = yield* Fiber.join(responseFiber);
78 yield* Deferred.await(discoveryInterrupted);
79 assert.deepEqual(availableEditors, []);
80 }),
81);
82​
83// Only the fields the late-editor fold reads or rewrites.
84const snapshotConfig = (fields: Partial<ServerConfig>) =>
85 ({ availableEditors: [], settings: {}, ...fields }) as unknown as ServerConfig;
86​
87const settingsUpdated = (settings: object): ServerConfigStreamEvent => ({
88 version: 1,
89 type: "settingsUpdated",
90 payload: { settings: settings as ServerConfig["settings"] },
91});
92​
93it.effect("resends late editors without rolling back updates already sent", () =>
94 Effect.gen(function* () {
95 const settingsSent = yield* Deferred.make<void>();
96 const events = yield* withLateEditorConfig(
97 snapshotConfig({ settings: { enableProviderUpdateChecks: true } as never }),
98 Stream.make(settingsUpdated({ enableProviderUpdateChecks: false })),
99 {
100 resolveAvailableEditors: () => Effect.succeed(["file-manager"]),
101 // Holds the late snapshot until the settings change has gone out.
102 resolveFileManagerRevealKind: () =>
103 Deferred.await(settingsSent).pipe(Effect.as("file-explorer" as const)),
104 },
105 ).pipe(
106 Stream.tap((event) =>
107 event.type === "settingsUpdated" ? Deferred.succeed(settingsSent, undefined) : Effect.void,
108 ),
109 Stream.runCollect,
110 );
111​
112 const [first, second] = Array.from(events);
113 assert.equal(events.length, 2);
114 assert.equal(first?.type, "settingsUpdated");
115 assert.equal(second?.type, "snapshot");
116 if (second?.type === "snapshot") {
117 assert.deepEqual(second.config.availableEditors, ["file-manager"]);
118 assert.equal(second.config.shellRevealInFileManagerKind, "file-explorer");
119 assert.deepEqual(second.config.settings, { enableProviderUpdateChecks: false } as never);
120 }
121 }),
122);
123​
124it.effect("sends no late snapshot when the scan matches the snapshot", () =>
125 Effect.gen(function* () {
126 const events = yield* withLateEditorConfig(
127 snapshotConfig({ availableEditors: ["vscode"] }),
128 Stream.empty,
129 {
130 resolveAvailableEditors: () => Effect.succeed(["vscode"]),
131 resolveFileManagerRevealKind: () => Effect.succeed(undefined),
132 },
133 ).pipe(Stream.runCollect);
134​
135 assert.equal(events.length, 0);
136 }),
137);
138​
139it.effect("resends a file manager reveal kind that missed the snapshot", () =>
140 Effect.gen(function* () {
141 const events = yield* withLateEditorConfig(
142 snapshotConfig({ availableEditors: ["file-manager"] }),
143 Stream.empty,
144 {
145 resolveAvailableEditors: () => Effect.succeed(["file-manager"]),
146 resolveFileManagerRevealKind: () => Effect.succeed("file-explorer"),
147 },
148 ).pipe(Stream.runCollect);
149​
150 const [late] = Array.from(events);
151 assert.equal(events.length, 1);
152 assert.equal(late?.type, "snapshot");
153 if (late?.type === "snapshot") {
154 assert.equal(late.config.shellRevealInFileManagerKind, "file-explorer");
155 }
156 }),
157);
158​
159// The real launcher on Windows over a filesystem whose probes park until
160// released, like a host too busy to finish discovery inside the snapshot timeout.
161const makeParkedWindowsLauncher = Effect.gen(function* () {
162 const parkedProbes = yield* Queue.unbounded<void>();
163 const release = yield* Deferred.make<void>();
164 const launcher = yield* ExternalLauncher.make.pipe(
165 Effect.provide(
166 Layer.mergeAll(
167 FileSystem.layerNoop({
168 stat: () =>
169 Queue.offer(parkedProbes, undefined).pipe(
170 Effect.andThen(Deferred.await(release)),
171 Effect.as({ type: "File" } as FileSystem.File.Info),
172 ),
173 }),
174 Path.layer,
175 Layer.succeed(
176 ChildProcessSpawner.ChildProcessSpawner,
177 ChildProcessSpawner.make(() => Effect.die("unexpected spawn")),
178 ),
179 ),
180 ),
181 );
182 const onWindows = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
183 effect.pipe(
184 Effect.provideService(HostProcess.Platform, "win32"),
185 Effect.provide(
186 ConfigProvider.layer(
187 ConfigProvider.fromEnv({
188 env: { PATH: "C:\\t3-late-editors-test", PATHEXT: ".EXE" },
189 }),
190 ),
191 ),
192 );
193 return {
194 editors: {
195 resolveAvailableEditors: () => onWindows(launcher.resolveAvailableEditors()),
196 resolveFileManagerRevealKind: () => onWindows(launcher.resolveFileManagerRevealKind()),
197 },
198 probeParked: Queue.take(parkedProbes),
199 releaseProbes: Deferred.succeed(release, undefined),
200 };
201});
202​
203it.effect("recovers editors after a real scan outlasts the config timeout", () =>
204 Effect.gen(function* () {
205 const { editors, probeParked, releaseProbes } = yield* makeParkedWindowsLauncher;
206​
207 const snapshotFiber = yield* resolveAvailableEditorsForConfig(
208 editors.resolveAvailableEditors(),
209 ).pipe(Effect.forkChild);
210 yield* probeParked;
211 yield* TestClock.adjust(Duration.seconds(5));
212 const snapshotEditors = yield* Fiber.join(snapshotFiber);
213 assert.deepEqual(snapshotEditors, []);
214​
215 const lateFiber = yield* withLateEditorConfig(
216 snapshotConfig({ availableEditors: snapshotEditors }),
217 Stream.empty,
218 editors,
219 ).pipe(Stream.runCollect, Effect.forkChild);
220 yield* releaseProbes;
221​
222 const [late] = Array.from(yield* Fiber.join(lateFiber));
223 assert.equal(late?.type, "snapshot");
224 if (late?.type === "snapshot") {
225 assert.equal(late.config.availableEditors.includes("vscode"), true);
226 }
227 }).pipe(Effect.scoped),
228);
229​
230it.effect("recovers a reveal kind whose real probe outlasts the config timeout", () =>
231 Effect.gen(function* () {
232 const { editors, probeParked, releaseProbes } = yield* makeParkedWindowsLauncher;
233​
234 // The snapshot's bounded probe timed out: file manager, but no reveal kind.
235 const lateFiber = yield* withLateEditorConfig(
236 snapshotConfig({ availableEditors: ["file-manager"] }),
237 Stream.empty,
238 {
239 resolveAvailableEditors: () => Effect.succeed(["file-manager"]),
240 resolveFileManagerRevealKind: editors.resolveFileManagerRevealKind,
241 },
242 ).pipe(Stream.runCollect, Effect.forkChild);
243 yield* probeParked;
244 yield* TestClock.adjust(Duration.seconds(6));
245 yield* releaseProbes;
246​
247 const [late] = Array.from(yield* Fiber.join(lateFiber));
248 assert.equal(late?.type, "snapshot");
249 if (late?.type === "snapshot") {
250 assert.equal(late.config.shellRevealInFileManagerKind, "file-explorer");
251 }
252 }).pipe(Effect.scoped),
253);
254​
255const ReplayTestLayer = OrchestrationEventStore.layer.pipe(
256 Layer.provideMerge(SqlitePersistence.layerMemory),
257);
258​
259it.live.each(["thread", "shell"] as const)(
260 "%s resume skips unknown types, synchronizes, and receives the live tail",
261 (scope) =>
262 Effect.gen(function* () {
263 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
264 const sql = yield* SqlClient.SqlClient;
265 const now = "2026-01-05T00:00:00.000Z";
266 const threadId = ThreadId.make("thread:replay");
267 const projectId = ProjectId.make("project:replay");
268 const project = {
269 id: projectId,
270 title: "Replay",
271 workspaceRoot: "/tmp/replay",
272 defaultModelSelection: null,
273 scripts: [],
274 createdAt: now,
275 updatedAt: now,
276 } satisfies OrchestrationProjectShell;
277 const insert = (version: number, unknown = false) => sql<{ sequence: number }>`
278 INSERT INTO orchestration_events (
279 event_id, aggregate_kind, stream_id, stream_version, event_type,
280 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
281 ) VALUES (
282 ${`replay:${version}`}, ${scope === "thread" ? "thread" : "project"},
283 ${scope === "thread" ? threadId : projectId}, ${version},
284 ${unknown ? "future.event" : scope === "thread" ? "provider-session.detached" : "project.meta-updated"},
285 ${now}, 'server', ${JSON.stringify(
286 scope === "thread"
287 ? { providerSessionId: "session:replay", detachedAt: now }
288 : { projectId, updatedAt: now },
289 )}, '{}', 2
290 ) RETURNING sequence
291 `;
292 const [before] = yield* insert(0);
293 yield* insert(1, true);
294 const [after] = yield* insert(2);
295 const [highWater] = yield* insert(3, true);
296 const updates = yield* PubSub.unbounded();
297 let liveSequence = 0;
298 const consume = <A extends { readonly kind: string; readonly sequence?: number }, E, R>(
299 stream: Stream.Stream<A, E, R>,
300 ) =>
301 stream.pipe(
302 Stream.tap((item) =>
303 Effect.gen(function* () {
304 if (item.kind !== "synchronized") return;
305 const [live] = yield* insert(4);
306 liveSequence = live!.sequence;
307 const events = yield* store
308 .readApplicationEvents({
309 afterSequence: highWater!.sequence,
310 throughSequence: liveSequence,
311 })
312 .pipe(Stream.runCollect);
313 yield* store.publishCommitted(events);
314 }),
315 ),
316 Stream.takeUntil((item) => item.sequence === liveSequence),
317 Stream.map((item) => ({ kind: item.kind as string, sequence: item.sequence })),
318 Stream.runCollect,
319 );
320 const subscription = Effect.gen(function* () {
321 return scope === "thread"
322 ? yield* subscribeOrchestrationV2Thread({
323 threadId,
324 afterSequence: before!.sequence,
325 requestCompletionMarker: true,
326 }).pipe(Effect.flatMap(consume))
327 : yield* subscribeOrchestrationV2Shell({
328 afterSequence: before!.sequence,
329 requestCompletionMarker: true,
330 }).pipe(Effect.flatMap(consume));
331 });
332 const items = yield* subscription.pipe(
333 Effect.provideService(ThreadManagement.ThreadManagementService, {
334 ensureLegacyTranscript: () => Effect.void,
335 streamStoredEventsFrom: (
336 input: Parameters<
337 ThreadManagement.ThreadManagementService["Service"]["streamStoredEventsFrom"]
338 >[0],
339 ) => {
340 assert.equal(input?.afterSequence, highWater!.sequence);
341 return store
342 .streamApplicationEvents({ afterSequence: input?.afterSequence ?? 0 })
343 .pipe(
344 Stream.filter((event): event is OrchestrationV2StoredEvent => "event" in event),
345 );
346 },
347 } as unknown as ThreadManagement.ThreadManagementService["Service"]),
348 Effect.provideService(ProjectStore.ProjectStoreV2, {
349 listShells: () => Effect.succeed([]),
350 } as unknown as ProjectStore.ProjectStoreV2["Service"]),
351 Effect.provideService(ProjectService.ProjectService, {
352 getShell: () => Effect.succeedSome(project),
353 } as unknown as ProjectService.ProjectService["Service"]),
354 Effect.provideService(ProjectEnrichment.ProjectEnrichmentService, {
355 subscribeChanges: PubSub.subscribe(updates),
356 } as ProjectEnrichment.ProjectEnrichmentService["Service"]),
357 );
358 assert.deepEqual(
359 items.map((item) => item.kind),
360 scope === "thread"
361 ? ["event", "synchronized", "event"]
362 : ["project.updated", "synchronized", "project.updated"],
363 );
364 assert.deepEqual(
365 items.flatMap((item) => (item.sequence === undefined ? [] : [item.sequence])),
366 [after!.sequence, liveSequence],
367 );
368 }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),
369);
370​
371// Compaction keeps the oldest and newest event per message, so a cursor older
372// than the deleted rows still replays each message where the client would
373// first have seen it (reducers append on first sight) and reaches the same
374// final state. No snapshot fallback is needed.
375it.effect("thread resume across compacted history keeps message order and final state", () =>
376 Effect.gen(function* () {
377 const sql = yield* SqlClient.SqlClient;
378 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
379 const now = "2026-10-13T00:00:00.000Z";
380 const threadId = ThreadId.make("thread:compacted");
381 const insertMessage = (version: number, id: string, text: string) => sql<{
382 sequence: number;
383 }>`
384 INSERT INTO orchestration_events (
385 event_id, aggregate_kind, stream_id, stream_version, event_type,
386 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
387 ) VALUES (
388 ${`compacted:${version}`}, 'thread', ${threadId}, ${version}, 'message.updated',
389 ${now}, 'server', ${JSON.stringify({
390 createdBy: "user",
391 creationSource: "web",
392 id,
393 threadId,
394 runId: null,
395 nodeId: null,
396 role: "user",
397 text,
398 attachments: [],
399 streaming: false,
400 createdAt: now,
401 updatedAt: now,
402 })}, '{}', 2
403 ) RETURNING sequence
404 `;
405 const [first] = yield* insertMessage(0, "message:a", "a created");
406 const [second] = yield* insertMessage(1, "message:b", "b created");
407 yield* insertMessage(2, "message:a", "a superseded");
408 const [head] = yield* insertMessage(3, "message:a", "a final");
409 // thread.deleted is never superseded: clients switch on the event type.
410 for (const version of [0, 1]) {
411 yield* sql`
412 INSERT INTO orchestration_events (
413 event_id, aggregate_kind, stream_id, stream_version, event_type,
414 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
415 ) VALUES (
416 ${`deleted:${version}`}, 'thread', 'thread:deleted-twice', ${version}, 'thread.deleted',
417 ${now}, 'server', '{}', '{}', 2
418 )
419 `;
420 }
421 // Only the event between a's first and newest is deleted.
422 assert.equal((yield* maintenance.compactEventStore).deletedEventCount, 1);
423​
424 const items = yield* subscribeOrchestrationV2Thread({
425 threadId,
426 afterSequence: first!.sequence - 1,
427 requestCompletionMarker: true,
428 }).pipe(
429 Effect.flatMap((stream) =>
430 stream.pipe(
431 Stream.takeUntil((item) => item.kind === "synchronized"),
432 Stream.runCollect,
433 ),
434 ),
435 Effect.provideService(ThreadManagement.ThreadManagementService, {
436 ensureLegacyTranscript: () => Effect.void,
437 streamStoredEventsFrom: () => Stream.never,
438 } as unknown as ThreadManagement.ThreadManagementService["Service"]),
439 );
440 assert.deepEqual(
441 Array.from(items, (item) =>
442 item.kind === "event"
443 ? [item.sequence, item.event.type === "message.updated" ? item.event.payload.text : null]
444 : [item.kind],
445 ),
446 [
447 [first!.sequence, "a created"],
448 [second!.sequence, "b created"],
449 [head!.sequence, "a final"],
450 ["synchronized"],
451 ],
452 );
453 }).pipe(
454 Effect.provide(
455 ProjectionMaintenance.layer.pipe(
456 Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),
457 Layer.provideMerge(ReplayTestLayer),
458 ),
459 ),
460 ),
461);