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

ws.test.ts

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