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

ws.test.ts

724 lines32.3 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import {
4 AuthSessionId,
5 EnvironmentId,
6 ProjectId,
7 ThreadId,
8 WS_METHODS,
9 WsSubscribeServerConfigRpc,
10 type OrchestrationV2StoredEvent,
11 type OrchestrationV2ThreadShell,
12 type OrchestrationProjectShell,
13 type ServerConfig,
14 type ServerConfigStreamEvent,
15} from "@t3tools/contracts";
16import * as Deferred from "effect/Deferred";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as Layer from "effect/Layer";
20import * as PubSub from "effect/PubSub";
21import * as Queue from "effect/Queue";
22import * as Stream from "effect/Stream";
23import { Headers } from "effect/http";
24import { RpcGroup, RpcMessage, RpcServer } from "effect/rpc";
25import * as SqlClient from "effect/sql/SqlClient";
26​
27import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
28import * as ServerBrowser from "./preview/ServerBrowser.ts";
29import * as AcpRegistryRuntimeCoordinator from "@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator";
30import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport";
31import * as AgentSessionImporter from "./project/AgentSessionImporter.ts";
32import * as AgentSessionScanner from "./project/AgentSessionScanner.ts";
33import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
34import * as AntigravityInstallation from "./provider/AntigravityInstallation.ts";
35import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
36import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
37import * as CommandOutputHub from "./orchestration-v2/CommandOutputHub.ts";
38import * as CodexInstallation from "./provider/CodexInstallation.ts";
39import * as DeviceService from "./device/DeviceService.ts";
40import * as DirectEndpoints from "./environment/DirectEndpoints.ts";
41import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
42import * as EnvironmentTheme from "./environmentTheme.ts";
43import * as GitWorkflowService from "./git/GitWorkflowService.ts";
44import * as HostResources from "./resourceTelemetry/HostResources.ts";
45import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts";
46import * as McpAppRequests from "./mcpApps/McpAppRequests.ts";
47import * as ModelManifest from "./provider/ModelManifest.ts";
48import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
49import * as OtlpEndpointCheck from "./observability/OtlpEndpointCheck.ts";
50import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
51import * as PortScanner from "./preview/PortScanner.ts";
52import * as PreviewManager from "./preview/Manager.ts";
53import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
54import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
55import * as ProjectCloneTracker from "./project/ProjectCloneTracker.ts";
56import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
57import * as ProviderAuthService from "./provider/ProviderAuthService.ts";
58import * as ProviderInstanceRegistry from "./provider/ProviderInstanceRegistry.ts";
59import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
60import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts";
61import * as ProviderRegistry from "./provider/ProviderRegistry.ts";
62import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
63import * as PullRequestReviewGuideService from "./pullRequest/PullRequestReviewGuideService.ts";
64import * as PullRequestService from "./pullRequest/PullRequestService.ts";
65import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts";
66import * as RelayClient from "@t3tools/shared/relayClient";
67import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
68import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
69import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
70import * as ReviewService from "./review/ReviewService.ts";
71import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts";
72import * as SecretRequests from "./secrets/SecretRequests.ts";
73import * as GuestShareService from "./guest/GuestShareService.ts";
74import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
75import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
76import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
77import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
78import * as SessionStore from "./auth/SessionStore.ts";
79import * as SourceControlDiscovery from "./sourceControl/SourceControlDiscovery.ts";
80import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
81import * as StorageCleanup from "./storageCleanup.ts";
82import * as DatabaseStorage from "./persistence/DatabaseStorage.ts";
83import * as TerminalManager from "./terminal/Manager.ts";
84import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts";
85import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts";
86import * as UsageLimitSources from "./usage/UsageLimitSources.ts";
87import * as UsageService from "./usage/UsageService.ts";
88import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
89import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
90import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
91import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
92import * as WorktreeSetupTracker from "./project/WorktreeSetupTracker.ts";
93import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
94import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
95import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
96import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
97import * as ServerConfigModule from "./config.ts";
98import * as Keybindings from "./keybindings.ts";
99import * as ServerSettings from "./serverSettings.ts";
100​
101import * as EventStore from "./orchestration-v2/EventStore.ts";
102import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts";
103import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts";
104import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts";
105import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
106import * as OrchestrationEventStore from "./persistence/OrchestrationEventStore.ts";
107import * as SqlitePersistence from "./persistence/Sqlite.ts";
108import * as ExternalLauncher from "./process/externalLauncher.ts";
109import * as ProjectEnrichment from "./project/ProjectEnrichmentService.ts";
110import * as ProjectService from "./project/ProjectService.ts";
111import {
112 layerWsRpc,
113 subscribeOrchestrationV2Shell,
114 subscribeOrchestrationV2Thread,
115 WS_RPC_SERVER_OPTIONS,
116 withLateEditorConfig,
117} from "./ws.ts";
118​
119const snapshotConfig = (fields: Partial<ServerConfig>) =>
120 ({ availableEditors: [], settings: {}, ...fields }) as unknown as ServerConfig;
121​
122const settingsUpdated = (settings: object): ServerConfigStreamEvent => ({
123 version: 1,
124 type: "settingsUpdated",
125 payload: { settings: settings as ServerConfig["settings"] },
126});
127​
128it.effect("resends late editors without rolling back updates already sent", () =>
129 Effect.gen(function* () {
130 const settingsSent = yield* Deferred.make<void>();
131 const events = yield* withLateEditorConfig(
132 snapshotConfig({ settings: { enableProviderUpdateChecks: true } as never }),
133 Stream.make(settingsUpdated({ enableProviderUpdateChecks: false })),
134 {
135 resolveAvailableEditors: () => Effect.succeed(["file-manager"]),
136 resolveFileManagerRevealKind: () =>
137 Deferred.await(settingsSent).pipe(Effect.as("file-explorer" as const)),
138 },
139 ).pipe(
140 Stream.tap((event) =>
141 event.type === "settingsUpdated" ? Deferred.succeed(settingsSent, undefined) : Effect.void,
142 ),
143 Stream.runCollect,
144 );
145​
146 const [first, second] = Array.from(events);
147 assert.equal(events.length, 2);
148 assert.equal(first?.type, "settingsUpdated");
149 assert.equal(second?.type, "snapshot");
150 if (second?.type === "snapshot") {
151 assert.deepEqual(second.config.availableEditors, ["file-manager"]);
152 assert.equal(second.config.shellRevealInFileManagerKind, "file-explorer");
153 assert.deepEqual(second.config.settings, { enableProviderUpdateChecks: false } as never);
154 }
155 }),
156);
157​
158it.effect("resends a file manager reveal kind that missed the snapshot", () =>
159 Effect.gen(function* () {
160 const events = yield* withLateEditorConfig(
161 snapshotConfig({ availableEditors: ["file-manager"] }),
162 Stream.empty,
163 {
164 resolveAvailableEditors: () => Effect.succeed(["file-manager"]),
165 resolveFileManagerRevealKind: () => Effect.succeed("file-explorer"),
166 },
167 ).pipe(Stream.runCollect);
168​
169 const [late] = Array.from(events);
170 assert.equal(events.length, 1);
171 assert.equal(late?.type, "snapshot");
172 if (late?.type === "snapshot") {
173 assert.equal(late.config.shellRevealInFileManagerKind, "file-explorer");
174 }
175 }),
176);
177​
178const ReplayTestLayer = OrchestrationEventStore.layer.pipe(
179 Layer.provideMerge(SqlitePersistence.layerMemory),
180);
181​
182it.live.each(["thread", "shell"] as const)(
183 "%s resume skips unknown types, synchronizes, and receives the live tail",
184 (scope) =>
185 Effect.gen(function* () {
186 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
187 const sql = yield* SqlClient.SqlClient;
188 const now = "2026-01-05T00:00:00.000Z";
189 const threadId = ThreadId.make("thread:replay");
190 const projectId = ProjectId.make("project:replay");
191 const project = {
192 id: projectId,
193 title: "Replay",
194 workspaceRoot: "/tmp/replay",
195 defaultModelSelection: null,
196 scripts: [],
197 createdAt: now,
198 updatedAt: now,
199 } satisfies OrchestrationProjectShell;
200 const insert = (version: number, unknown = false) => sql<{ sequence: number }>`
201 INSERT INTO orchestration_events (
202 event_id, aggregate_kind, stream_id, stream_version, event_type,
203 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
204 ) VALUES (
205 ${`replay:${version}`}, ${scope === "thread" ? "thread" : "project"},
206 ${scope === "thread" ? threadId : projectId}, ${version},
207 ${unknown ? "future.event" : scope === "thread" ? "provider-session.detached" : "project.meta-updated"},
208 ${now}, 'server', ${JSON.stringify(
209 scope === "thread"
210 ? { providerSessionId: "session:replay", detachedAt: now }
211 : { projectId, updatedAt: now },
212 )}, '{}', 2
213 ) RETURNING sequence
214 `;
215 const [before] = yield* insert(0);
216 yield* insert(1, true);
217 const [after] = yield* insert(2);
218 const [highWater] = yield* insert(3, true);
219 const updates = yield* PubSub.unbounded();
220 let liveSequence = 0;
221 const consume = <A extends { readonly kind: string; readonly sequence?: number }, E, R>(
222 stream: Stream.Stream<A, E, R>,
223 ) =>
224 stream.pipe(
225 Stream.tap((item) =>
226 Effect.gen(function* () {
227 if (item.kind !== "synchronized") return;
228 const [live] = yield* insert(4);
229 liveSequence = live!.sequence;
230 const events = yield* store
231 .readApplicationEvents({
232 afterSequence: highWater!.sequence,
233 throughSequence: liveSequence,
234 })
235 .pipe(Stream.runCollect);
236 yield* store.publishCommitted(events);
237 }),
238 ),
239 Stream.takeUntil((item) => item.sequence === liveSequence),
240 Stream.map((item) => ({ kind: item.kind as string, sequence: item.sequence })),
241 Stream.runCollect,
242 );
243 const subscription = Effect.gen(function* () {
244 return scope === "thread"
245 ? yield* subscribeOrchestrationV2Thread({
246 threadId,
247 afterSequence: before!.sequence,
248 requestCompletionMarker: true,
249 }).pipe(Effect.flatMap(consume))
250 : yield* subscribeOrchestrationV2Shell({
251 afterSequence: before!.sequence,
252 requestCompletionMarker: true,
253 }).pipe(Effect.flatMap(consume));
254 });
255 const items = yield* subscription.pipe(
256 Effect.provideService(ThreadManagement.ThreadManagementService, {
257 ensureLegacyTranscript: () => Effect.void,
258 getShellSnapshot: () => Effect.die("shell resume must not load a full snapshot"),
259 listActiveSubagentThreadIds: () => Effect.succeed([]),
260 streamStoredEventsFrom: (
261 input: Parameters<
262 ThreadManagement.ThreadManagementService["Service"]["streamStoredEventsFrom"]
263 >[0],
264 ) => {
265 assert.equal(input?.afterSequence, highWater!.sequence);
266 return store
267 .streamApplicationEvents({ afterSequence: input?.afterSequence ?? 0 })
268 .pipe(
269 Stream.filter((event): event is OrchestrationV2StoredEvent => "event" in event),
270 );
271 },
272 } as unknown as ThreadManagement.ThreadManagementService["Service"]),
273 Effect.provideService(ProjectStore.ProjectStoreV2, {
274 listShells: () => Effect.succeed([]),
275 } as unknown as ProjectStore.ProjectStoreV2["Service"]),
276 Effect.provideService(ProjectService.ProjectService, {
277 getShell: () => Effect.succeedSome(project),
278 } as unknown as ProjectService.ProjectService["Service"]),
279 Effect.provideService(ProjectEnrichment.ProjectEnrichmentService, {
280 subscribeChanges: PubSub.subscribe(updates),
281 } as ProjectEnrichment.ProjectEnrichmentService["Service"]),
282 );
283 assert.deepEqual(
284 items.map((item) => item.kind),
285 scope === "thread"
286 ? ["event", "synchronized", "event"]
287 : ["project.updated", "synchronized", "project.updated"],
288 );
289 assert.deepEqual(
290 items.flatMap((item) => (item.sequence === undefined ? [] : [item.sequence])),
291 [after!.sequence, liveSequence],
292 );
293 }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),
294);
295​
296it.effect("shell snapshots omit idle children and older settled threads only on request", () =>
297 Effect.gen(function* () {
298 const shell = (
299 id: string,
300 parent: string | null,
301 activityRunStatus: "running" | null,
302 settledDaysAgo: number | null = null,
303 ) =>
304 ({
305 id: ThreadId.make(id),
306 projectId: "project",
307 archivedAt: null,
308 status: activityRunStatus ?? "completed",
309 activityRunStatus,
310 pendingRuntimeRequest: null,
311 pendingBackgroundTasks: [],
312 settledOverride: settledDaysAgo === null ? null : "settled",
313 settledAt:
314 settledDaysAgo === null ? null : DateTime.makeUnsafe(-settledDaysAgo * 86_400_000),
315 lineage: {
316 parentThreadId: parent === null ? null : ThreadId.make(parent),
317 relationshipToParent: parent === null ? null : "subagent",
318 rootThreadId: ThreadId.make(parent ?? id),
319 },
320 }) as unknown as OrchestrationV2ThreadShell;
321 const threads = [
322 shell("parent", null, null),
323 shell("idle", "parent", null),
324 shell("live", "parent", "running"),
325 ...Array.from({ length: 25 }, (_, index) => shell(`recent-${index}`, null, null, 1)),
326 shell("old", null, null, 30),
327 ];
328 const firstSnapshot = (input: {
329 readonly omitIdleSubagents?: boolean;
330 readonly omitOlderSettled?: boolean;
331 }) =>
332 subscribeOrchestrationV2Shell(input).pipe(
333 Effect.flatMap((stream) => stream.pipe(Stream.take(1), Stream.runCollect)),
334 Effect.map(([item]) => (item?.kind === "snapshot" ? item.snapshot : null)),
335 Effect.provideService(ThreadManagement.ThreadManagementService, {
336 readShellSnapshot: () =>
337 Effect.succeed(
338 Effect.succeed({
339 schemaVersion: 1,
340 snapshotSequence: 0,
341 threads,
342 archivedThreads: [],
343 }),
344 ),
345 } as unknown as ThreadManagement.ThreadManagementService["Service"]),
346 Effect.provideService(ProjectStore.ProjectStoreV2, {
347 listShells: () => Effect.succeed([]),
348 } as unknown as ProjectStore.ProjectStoreV2["Service"]),
349 Effect.provideService(ProjectService.ProjectService, {
350 getShell: () => Effect.succeedNone,
351 } as unknown as ProjectService.ProjectService["Service"]),
352 Effect.provideServiceEffect(
353 ProjectEnrichment.ProjectEnrichmentService,
354 PubSub.unbounded().pipe(
355 Effect.map(
356 (changes) =>
357 ({
358 subscribeChanges: PubSub.subscribe(changes),
359 }) as unknown as ProjectEnrichment.ProjectEnrichmentService["Service"],
360 ),
361 ),
362 ),
363 );
364​
365 const recent = threads.slice(3, 28).map((thread) => thread.id);
366 const full = yield* firstSnapshot({});
367 assert.deepEqual(
368 full?.threads.map((thread) => thread.id),
369 threads.map((thread) => thread.id),
370 );
371 assert.isUndefined(full?.olderSettled);
372 const withoutChildren = yield* firstSnapshot({ omitIdleSubagents: true });
373 assert.deepEqual(
374 withoutChildren?.threads.map((thread) => thread.id),
375 ["parent", "live", ...recent, "old"],
376 );
377 const withoutOld = yield* firstSnapshot({ omitIdleSubagents: true, omitOlderSettled: true });
378 assert.deepEqual(
379 withoutOld?.threads.map((thread) => thread.id),
380 ["parent", "live", ...recent],
381 );
382 assert.deepEqual(withoutOld?.olderSettled?.counts, [
383 { projectId: ProjectId.make("project"), count: 1 },
384 ]);
385 }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),
386);
387​
388// Build the production RPC layer; unrelated capabilities fail if this test calls them.
389const layerUnusedConfigRpcServices = Layer.mergeAll(
390 Layer.mock(ServerSecretStore.ServerSecretStore)({}),
391 Layer.mock(WorkspacePaths.WorkspacePaths)({}),
392 Layer.mock(TraceDiagnostics.TraceDiagnostics)({}),
393 Layer.mock(ProjectFaviconResolver.ProjectFaviconResolver)({}),
394 Layer.mock(ProjectEnrichment.ProjectEnrichmentService)({}),
395 Layer.mock(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator)({}),
396 Layer.mock(AcpRegistrySupport.AcpRegistryCatalog)({}),
397 Layer.mock(AgentSessionImporter.AgentSessionImporter)({}),
398 Layer.mock(AgentSessionScanner.AgentSessionScanner)({}),
399 Layer.mock(AnalyticsService.AnalyticsService)({}),
400 Layer.mock(AntigravityInstallation.AntigravityInstallation)({ managedDirectory: "/unused" }),
401 Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
402 Layer.mock(CheckpointDiffQuery.CheckpointDiffQuery)({}),
403 Layer.mock(CommandOutputHub.CommandOutputHub)({}),
404 Layer.mock(CodexInstallation.CodexInstallation)({ managedDirectory: "/unused" }),
405 Layer.mock(DeviceService.DeviceService)({}),
406 Layer.mock(EnvironmentTheme.EnvironmentThemeService)({}),
407 Layer.mock(GitWorkflowService.GitWorkflowService)({}),
408 Layer.mock(HostResources.HostResources)({}),
409 Layer.mock(McpAppRequests.McpAppRequests)({}),
410 Layer.mock(ModelManifest.ModelManifest)({}),
411 Layer.mock(OrchestrationEventStore.OrchestrationEventStore)({}),
412 Layer.mock(Orchestrator.OrchestratorV2)({}),
413 Layer.mock(OtlpEndpointCheck.OtlpEndpointCheck)({}),
414 Layer.mock(PairingGrantStore.PairingGrantStore)({}),
415 Layer.mock(PortScanner.PortDiscovery)({}),
416 Layer.mock(PreviewManager.PreviewManager)({}),
417 Layer.mock(ProcessDiagnostics.ProcessDiagnostics)({}),
418 Layer.mock(ProcessResourceMonitor.ProcessResourceMonitor)({}),
419 Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({}),
420 Layer.mock(ProjectService.ProjectService)({}),
421 Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({}),
422 Layer.mock(ProjectStore.ProjectStoreV2)({}),
423 Layer.mock(ProviderAuthService.ProviderAuthService)({}),
424 Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({}),
425 Layer.mock(ProviderLatestVersions.ProviderLatestVersions)({}),
426 Layer.mock(ProviderMaintenanceRunner.ProviderMaintenanceRunner)({}),
427 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}),
428 Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
429 Layer.mock(PullRequestService.PullRequestService)({}),
430 Layer.mock(PullRequestSyncReactor.PullRequestSyncReactor)({}),
431 Layer.mock(RelayClient.RelayClient)({}),
432 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}),
433 Layer.mock(ResourceTelemetry.ResourceTelemetry)({}),
434 Layer.mock(ReviewService.ReviewService)({}),
435 Layer.mock(ScheduledTasks.ScheduledTaskService)({}),
436 Layer.mock(SecretRequests.SecretRequests)({}),
437 Layer.mock(GuestShareService.GuestShareService)({}),
438 Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({}),
439 Layer.mock(ServerRuntimeStartup.ServerRuntimeStartup)({}),
440 Layer.mock(ServerSelfUpdate.ServerSelfUpdate)({}),
441 Layer.mock(SessionStore.SessionStore)({ cookieName: "config-test", legacyCookieName: undefined }),
442 Layer.mock(SourceControlDiscovery.SourceControlDiscovery)({}),
443 Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({}),
444 Layer.mock(StorageCleanup.StorageCleanup)({}),
445 Layer.mock(DatabaseStorage.DatabaseStorage)({}),
446 Layer.mock(TerminalManager.TerminalManager)({}),
447 Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
448 Layer.mock(ThreadManagement.ThreadManagementService)({}),
449 Layer.mock(ThreadSearch.ThreadSearch)({}),
450 Layer.mock(UsageService.UsageService)({}),
451 Layer.mock(VcsProvisioningService.VcsProvisioningService)({}),
452 Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({}),
453 Layer.mock(WorkspaceEntries.WorkspaceEntries)({}),
454 Layer.mock(WorkspaceFileSystem.WorkspaceFileSystem)({}),
455 Layer.mock(WorktreeSetupTracker.WorktreeSetupTracker)({}),
456);
457​
458const layerConfigSources = Layer.mergeAll(
459 Keybindings.layer,
460 ServerSettings.layer.pipe(Layer.provide(ServerSecretStore.layer)),
461).pipe(
462 Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
463 Layer.provideMerge(
464 Layer.fresh(
465 ServerConfigModule.layerTest(process.cwd(), { prefix: "t3-config-subscription-test-" }),
466 ),
467 ),
468 Layer.provideMerge(NodeServices.layer),
469);
470​
471it.effect(
472 "preserves settings during discovery and keybindings during snapshot ACK at the config RPC boundary",
473 () =>
474 Effect.gen(function* () {
475 const keybindings = yield* Keybindings.Keybindings;
476 const settings = yield* ServerSettings.ServerSettingsService;
477 const keybindingsSubscribed = yield* Deferred.make<void>();
478 const settingsSubscribed = yield* Deferred.make<void>();
479 const keybindingsChanges = keybindings.subscribeChanges.pipe(
480 Effect.tap(() => Deferred.succeed(keybindingsSubscribed, undefined)),
481 );
482 const settingsChanges = settings.subscribeChanges.pipe(
483 Effect.tap(() => Deferred.succeed(settingsSubscribed, undefined)),
484 );
485 const initialKeybindings = (yield* keybindings.getSnapshot).keybindings;
486 const discoveryStarted = yield* Deferred.make<void>();
487 const finishDiscovery = yield* Deferred.make<void>();
488 const responses = yield* Queue.unbounded<ServerConfigStreamEvent>();
489 const configRpcServices = Layer.mergeAll(
490 layerUnusedConfigRpcServices,
491 Layer.mock(ExternalLauncher.ExternalLauncher)({
492 resolveAvailableEditors: () =>
493 Deferred.succeed(discoveryStarted, undefined).pipe(
494 Effect.andThen(Deferred.await(finishDiscovery)),
495 Effect.as([]),
496 ),
497 resolveFileManagerRevealKind: () => Effect.succeed(undefined),
498 }),
499 Layer.mock(ProviderRegistry.ProviderRegistry)({
500 getProviders: Effect.succeed([]),
501 streamChanges: Stream.never,
502 }),
503 Layer.mock(UsageLimitSources.UsageLimitSources)({ streamChanges: Stream.make([]) }),
504 Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({
505 resolveTargets: () => Effect.succeed([]),
506 }),
507 Layer.mock(DirectEndpoints.DirectEndpoints)({ resolve: () => Effect.succeed([]) }),
508 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
509 scratchRoot: Effect.succeedNone,
510 namedProjectsRoot: process.cwd(),
511 }),
512 Layer.mock(ServerEnvironment.ServerEnvironment)({
513 getDescriptor: Effect.succeed({
514 environmentId: EnvironmentId.make("config-test"),
515 label: "Config test",
516 platform: { os: "linux", arch: "x64" },
517 serverVersion: "0.0.0",
518 capabilities: { repositoryIdentity: false },
519 }),
520 }),
521 Layer.mock(EnvironmentAuth.EnvironmentAuth)({
522 getDescriptor: () =>
523 Effect.succeed({
524 policy: "loopback-browser",
525 bootstrapMethods: [],
526 sessionMethods: ["browser-session-cookie"],
527 sessionCookieName: "config-test-session",
528 }),
529 }),
530 // Signal subscription on either accessor so the test also fails, rather
531 // than hangs, against a handler that subscribes after the snapshot.
532 Layer.succeed(Keybindings.Keybindings, {
533 ...keybindings,
534 streamChanges: Stream.unwrap(keybindingsChanges),
535 subscribeChanges: keybindingsChanges,
536 }),
537 Layer.succeed(ServerSettings.ServerSettingsService, {
538 ...settings,
539 streamChanges: Stream.unwrap(settingsChanges),
540 subscribeChanges: settingsChanges,
541 }),
542 );
543 const server = yield* RpcServer.makeNoSerialization(
544 RpcGroup.make(WsSubscribeServerConfigRpc),
545 {
546 ...WS_RPC_SERVER_OPTIONS,
547 onFromServer: (response) =>
548 response._tag === "Chunk"
549 ? Effect.forEach(response.values, (event) => Queue.offer(responses, event), {
550 discard: true,
551 })
552 : Effect.void,
553 },
554 ).pipe(
555 Effect.provide(
556 layerWsRpc(
557 {
558 sessionId: AuthSessionId.make("config-test"),
559 subject: "config-test",
560 method: "browser-session-cookie",
561 scopes: [],
562 },
563 {},
564 {},
565 yield* PreviewAutomationBroker.PreviewAutomationBroker,
566 yield* ServerBrowser.ServerBrowser,
567 ).pipe(Layer.provide(configRpcServices)),
568 ),
569 );
570 const requestId = RpcMessage.RequestId("config");
571 const acknowledge = server.write(0, { _tag: "Ack", requestId });
572 yield* server.write(0, {
573 _tag: "Request",
574 id: requestId,
575 tag: WS_METHODS.subscribeServerConfig,
576 payload: {},
577 headers: Headers.empty,
578 });
579 yield* Deferred.await(discoveryStarted);
580​
581 const duringDiscovery = yield* settings.updateSettings({ defaultAutoPull: true });
582 yield* Deferred.succeed(finishDiscovery, undefined);
583 const snapshot = yield* Queue.take(responses);
584 assert.equal(snapshot.type, "snapshot");
585 if (snapshot.type !== "snapshot") return yield* Effect.die("Missing initial snapshot");
586 assert.isFalse(snapshot.config.settings.defaultAutoPull);
587 assert.deepEqual(snapshot.config.keybindings, initialKeybindings);
588 const duringAck = yield* keybindings.upsertKeybindingRule({
589 key: "mod+alt+y",
590 command: "terminal.toggle",
591 });
592 yield* acknowledge;
593 yield* Deferred.await(keybindingsSubscribed);
594 yield* Deferred.await(settingsSubscribed);
595​
596 // Later updates expose a dropped buffered event as a value mismatch, not a timeout.
597 const latestSettings = yield* settings.updateSettings({ enableProviderUpdateChecks: false });
598 const latestKeybindings = yield* keybindings.upsertKeybindingRule({
599 key: "mod+alt+z",
600 command: "terminal.split",
601 });
602 const expectedSettings = [duringDiscovery, latestSettings].map(
603 ServerSettings.redactServerSettingsForClient,
604 );
605 const expectedKeybindings = [duringAck, latestKeybindings];
606 // The two sources can interleave, but each must retain its own publication order.
607 for (let i = 0; i < 4; i++) {
608 const event = yield* Queue.take(responses);
609 if (event.type === "settingsUpdated") {
610 assert.deepEqual(event.payload.settings, expectedSettings.shift());
611 } else {
612 assert.equal(event.type, "keybindingsUpdated");
613 if (event.type !== "keybindingsUpdated")
614 return yield* Effect.die("Unexpected config event");
615 assert.deepEqual(event.payload.keybindings, expectedKeybindings.shift());
616 assert.deepEqual(event.payload.issues, []);
617 }
618 yield* acknowledge;
619 }
620 assert.isEmpty(expectedSettings);
621 assert.isEmpty(expectedKeybindings);
622 yield* server.write(0, { _tag: "Interrupt", requestId, interruptors: [] });
623 }).pipe(
624 Effect.provide(
625 Layer.mergeAll(
626 Layer.fresh(layerConfigSources),
627 Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}),
628 Layer.mock(ServerBrowser.ServerBrowser)({}),
629 ),
630 ),
631 Effect.scoped,
632 ),
633);
634​
635// Compaction keeps the oldest and newest event per message, so a cursor older
636// than the deleted rows still replays each message where the client would
637// first have seen it (reducers append on first sight) and reaches the same
638// final state. No snapshot fallback is needed.
639it.effect("thread resume across compacted history keeps message order and final state", () =>
640 Effect.gen(function* () {
641 const sql = yield* SqlClient.SqlClient;
642 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
643 const now = "2026-10-13T00:00:00.000Z";
644 const threadId = ThreadId.make("thread:compacted");
645 const insertMessage = (version: number, id: string, text: string) => sql<{
646 sequence: number;
647 }>`
648 INSERT INTO orchestration_events (
649 event_id, aggregate_kind, stream_id, stream_version, event_type,
650 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
651 ) VALUES (
652 ${`compacted:${version}`}, 'thread', ${threadId}, ${version}, 'message.updated',
653 ${now}, 'server', ${JSON.stringify({
654 createdBy: "user",
655 creationSource: "web",
656 id,
657 threadId,
658 runId: null,
659 nodeId: null,
660 role: "user",
661 text,
662 attachments: [],
663 streaming: false,
664 createdAt: now,
665 updatedAt: now,
666 })}, '{}', 2
667 ) RETURNING sequence
668 `;
669 const [first] = yield* insertMessage(0, "message:a", "a created");
670 const [second] = yield* insertMessage(1, "message:b", "b created");
671 yield* insertMessage(2, "message:a", "a superseded");
672 const [head] = yield* insertMessage(3, "message:a", "a final");
673 // thread.deleted is never superseded: clients switch on the event type.
674 for (const version of [0, 1]) {
675 yield* sql`
676 INSERT INTO orchestration_events (
677 event_id, aggregate_kind, stream_id, stream_version, event_type,
678 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
679 ) VALUES (
680 ${`deleted:${version}`}, 'thread', 'thread:deleted-twice', ${version}, 'thread.deleted',
681 ${now}, 'server', '{}', '{}', 2
682 )
683 `;
684 }
685 assert.equal((yield* maintenance.compactEventStore).deletedEventCount, 1);
686​
687 const items = yield* subscribeOrchestrationV2Thread({
688 threadId,
689 afterSequence: first!.sequence - 1,
690 requestCompletionMarker: true,
691 }).pipe(
692 Effect.flatMap((stream) =>
693 stream.pipe(
694 Stream.takeUntil((item) => item.kind === "synchronized"),
695 Stream.runCollect,
696 ),
697 ),
698 Effect.provideService(ThreadManagement.ThreadManagementService, {
699 ensureLegacyTranscript: () => Effect.void,
700 streamStoredEventsFrom: () => Stream.never,
701 } as unknown as ThreadManagement.ThreadManagementService["Service"]),
702 );
703 assert.deepEqual(
704 Array.from(items, (item) =>
705 item.kind === "event"
706 ? [item.sequence, item.event.type === "message.updated" ? item.event.payload.text : null]
707 : [item.kind],
708 ),
709 [
710 [first!.sequence, "a created"],
711 [second!.sequence, "b created"],
712 [head!.sequence, "a final"],
713 ["synchronized"],
714 ],
715 );
716 }).pipe(
717 Effect.provide(
718 ProjectionMaintenance.layer.pipe(
719 Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),
720 Layer.provideMerge(ReplayTestLayer),
721 ),
722 ),
723 ),
724);