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