The best way to control Claude Code, Codex and more from any computer or phone

main
ts 2,639 lines 109 KB
Raw
1 import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
2 import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
3 import { WebSocket } from "@effect/platform-node/NodeWS";
4 // @effect-diagnostics-next-line nodeBuiltinImport:off -- Bind an isolated WebSocket negotiation fixture.
5 import * as NodeHttp from "node:http";
6 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
7 import * as NodeServices from "@effect/platform-node/NodeServices";
8 import { assert, it } from "@effect/vitest";
9 import {
10 AuthAccessReadScope,
11 AuthOrchestrationOperateScope,
12 AuthOrchestrationReadScope,
13 AuthSessionId,
14 AuthSourceControlWriteScope,
15 ORCHESTRATION_PROTOCOL_VERSION,
16 ORCHESTRATION_PROTOCOL_QUERY_PARAM,
17 EnvironmentId,
18 EventId,
19 GitManagerError,
20 VcsProcessSpawnError,
21 MessageId,
22 ProjectId,
23 ThreadId,
24 TurnItemId,
25 ProviderDriverKind,
26 ProviderInstanceId,
27 ProviderThreadId,
28 RunId,
29 SourceControlRepositoryError,
30 WS_METHODS,
31 WsRpcGroup,
32 WsServerRefreshProvidersRpc,
33 WsSubscribeServerConfigRpc,
34 type AuthAccessStreamEvent,
35 type OrchestrationV2AppThread,
36 type OrchestrationV2DomainEvent,
37 type OrchestrationV2StoredEvent,
38 type OrchestrationV2ThreadShell,
39 type OrchestrationProjectShell,
40 type ServerConfig,
41 type ServerConfigStreamEvent,
42 type ServerProvider,
43 } from "@t3tools/contracts";
44 import { SOCKET_FRAME_PARTS_QUERY_PARAM } from "@t3tools/shared/socketFrameParts";
45 import * as Deferred from "effect/Deferred";
46 import type { ProviderInstance } from "@t3tools/provider-core/server/driver";
47 import * as DateTime from "effect/DateTime";
48 import * as Effect from "effect/Effect";
49 import * as Exit from "effect/Exit";
50 import * as Cause from "effect/Cause";
51 import * as Fiber from "effect/Fiber";
52 import * as FileSystem from "effect/FileSystem";
53 import * as Layer from "effect/Layer";
54 import * as Path from "effect/Path";
55 import * as PubSub from "effect/PubSub";
56 import * as Queue from "effect/Queue";
57 import * as Stream from "effect/Stream";
58 import * as TestClock from "effect/testing/TestClock";
59 import { Headers, HttpRouter, HttpServer } from "effect/http";
60 import * as Context from "effect/Context";
61 import * as FetchHttpClient from "effect/http/FetchHttpClient";
62 import * as VcsProcess from "./vcs/VcsProcess.ts";
63 import * as ProviderInstallationGate from "./provider/ProviderInstallationGate.ts";
64 import * as Ws from "./ws.ts";
65 import { RpcGroup, RpcMessage, RpcServer } from "effect/rpc";
66 import * as RpcTest from "effect/rpc/RpcTest";
67 import * as SqlClient from "effect/sql/SqlClient";
68 import * as Statement from "effect/sql/Statement";
69 import { vi } from "vite-plus/test";
70
71 import * as AssetSigner from "./assets/AssetSigner.ts";
72 import * as WorkspacePreviewRevisions from "./assets/WorkspacePreviewRevisions.ts";
73 import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
74 import * as ServerBrowser from "./preview/ServerBrowser.ts";
75 import * as AcpRegistryRuntimeCoordinator from "@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator";
76 import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport";
77 import * as AgentSessionImporter from "./project/AgentSessionImporter.ts";
78 import * as AgentSessionScanner from "./project/AgentSessionScanner.ts";
79 import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
80 import * as AntigravityInstallation from "./provider/AntigravityInstallation.ts";
81 import * as ProviderInstallation from "./provider/providerInstallation.ts";
82 import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
83 import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
84 import * as NativeChildWorkQuery from "./orchestration-v2/NativeChildWorkQuery.ts";
85 import * as CommandOutputHub from "./orchestration-v2/CommandOutputHub.ts";
86 import * as ThreadViewers from "./orchestration-v2/ThreadViewers.ts";
87 import * as CodexInstallation from "./provider/CodexInstallation.ts";
88 import * as DeviceService from "./device/DeviceService.ts";
89 import * as DocumentText from "./provider/DocumentText.ts";
90 import * as DirectEndpoints from "./environment/DirectEndpoints.ts";
91 import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
92 import * as EnvironmentTheme from "./environmentTheme.ts";
93 import * as GitWorkflowService from "./git/GitWorkflowService.ts";
94 import * as HostResources from "./resourceTelemetry/HostResources.ts";
95 import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts";
96 import * as ScratchThreadPromotion from "./project/ScratchThreadPromotion.ts";
97 import * as McpAppRequests from "./mcpApps/McpAppRequests.ts";
98 import * as McpSignIn from "./mcpApps/McpSignIn.ts";
99 import * as ModelManifest from "./provider/ModelManifest.ts";
100 import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
101 import * as OtlpEndpointCheck from "./observability/OtlpEndpointCheck.ts";
102 import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
103 import * as RpcAuthorization from "./auth/RpcAuthorization.ts";
104 import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts";
105 import * as PeerThreadRelay from "./peer/PeerThreadRelay.ts";
106 import * as PeerClientPairing from "./peer/PeerClientPairing.ts";
107 import * as PeerLinks from "./peer/PeerLinks.ts";
108 import * as PortScanner from "./preview/PortScanner.ts";
109 import * as PreviewManager from "./preview/Manager.ts";
110 import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
111 import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
112 import * as ProjectCloneTracker from "./project/ProjectCloneTracker.ts";
113 import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
114 import * as ProviderAuthService from "./provider/ProviderAuthService.ts";
115 import * as AcpRegistrySessions from "./provider/AcpRegistrySessions.ts";
116 import * as ProviderInstanceRegistry from "./provider/ProviderInstanceRegistry.ts";
117 import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
118 import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts";
119 import * as ProviderRegistry from "./provider/ProviderRegistry.ts";
120 import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
121 import * as PullRequestReviewGuideService from "./pullRequest/PullRequestReviewGuideService.ts";
122 import * as IssueService from "./issue/IssueService.ts";
123 import * as ThreadIssueService from "./orchestration-v2/ThreadIssueService.ts";
124 import * as IssueTrackerConnections from "./issue/IssueTrackerConnections.ts";
125 import * as PullRequestService from "./pullRequest/PullRequestService.ts";
126 import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts";
127 import * as RelayClient from "@t3tools/shared/relayClient";
128 import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
129 import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
130 import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
131 import * as ReviewService from "./review/ReviewService.ts";
132 import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts";
133 import * as SecretRequests from "./secrets/SecretRequests.ts";
134 import * as GuestShareService from "./guest/GuestShareService.ts";
135 import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
136 import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
137 import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
138 import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
139 import * as NpmRelease from "./cloud/npmRelease.ts";
140 import * as SessionStore from "./auth/SessionStore.ts";
141 import * as SourceControlDiscovery from "./sourceControl/SourceControlDiscovery.ts";
142 import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
143 import * as SourceControlSignIn from "./sourceControl/SourceControlSignIn.ts";
144 import * as StorageCleanup from "./storageCleanup.ts";
145 import * as DatabaseStorage from "./persistence/DatabaseStorage.ts";
146 import * as TerminalManager from "./terminal/Manager.ts";
147 import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts";
148 import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts";
149 import * as UsageLimitSources from "./usage/UsageLimitSources.ts";
150 import * as UsageService from "./usage/UsageService.ts";
151 import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
152 import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
153 import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
154 import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
155 import * as WorktreeSetupTracker from "./project/WorktreeSetupTracker.ts";
156 import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
157 import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
158 import * as TriageService from "./triage/TriageService.ts";
159 import * as TextGenerators from "./textGeneration/TextGenerators.ts";
160 import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
161 import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
162 import * as SecretCheck from "./secrets/SecretCheck.ts";
163 import * as ServerConfigModule from "./config.ts";
164 import * as Keybindings from "./keybindings.ts";
165 import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits";
166 import * as ServerSettings from "./serverSettings.ts";
167 import * as ManagedPolicy from "./policy/ManagedPolicy.ts";
168
169 import * as EventStore from "./orchestration-v2/EventStore.ts";
170 import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts";
171 import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
172 import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts";
173 import * as EventSink from "./orchestration-v2/EventSink.ts";
174 import * as LegacyV1ThreadImporter from "./orchestration-v2/legacy/LegacyV1ThreadImporter.ts";
175 import * as ThreadCommandExecutor from "./orchestration-v2/ThreadCommandExecutor.ts";
176 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
177 import { projectIdentitiesDigest } from "./orchestration-v2/ShellStream.ts";
178 import * as OrchestrationEventStore from "./persistence/OrchestrationEventStore.ts";
179 import * as SqlitePersistence from "./persistence/Sqlite.ts";
180 import * as ExternalLauncher from "./process/externalLauncher.ts";
181 import * as ProjectEnrichment from "./project/ProjectEnrichmentService.ts";
182 import * as ProjectService from "./project/ProjectService.ts";
183 import {
184 layerWsRpc,
185 resolveOpenDiscoveryForConfig,
186 subscribeOrchestrationV2Shell,
187 subscribeOrchestrationV2Thread,
188 WS_RPC_SERVER_OPTIONS,
189 withLateConfigDiscovery,
190 } from "./ws.ts";
191
192 const snapshotConfig = (fields: Partial<ServerConfig>) =>
193 ({ availableEditors: [], settings: {}, ...fields }) as unknown as ServerConfig;
194
195 const settingsUpdated = (settings: object): ServerConfigStreamEvent => ({
196 version: 1,
197 type: "settingsUpdated",
198 payload: { settings: settings as ServerConfig["settings"] },
199 });
200
201 it.effect("resends late editors without rolling back updates already sent", () =>
202 Effect.gen(function* () {
203 const settingsSent = yield* Deferred.make<void>();
204 const events = yield* withLateConfigDiscovery(
205 snapshotConfig({ settings: { enableProviderUpdateChecks: true } as never }),
206 Stream.make(settingsUpdated({ enableProviderUpdateChecks: false })),
207 {
208 resolveAvailableEditors: () => Effect.succeed(["file-manager"]),
209 resolveFileManagerRevealKind: () =>
210 Deferred.await(settingsSent).pipe(Effect.as("file-explorer" as const)),
211 },
212 { resolveTargets: () => Effect.succeed([]) },
213 { resolve: () => Effect.succeed([]) },
214 ).pipe(
215 Stream.tap((event) =>
216 event.type === "settingsUpdated" ? Deferred.succeed(settingsSent, undefined) : Effect.void,
217 ),
218 Stream.runCollect,
219 );
220
221 const [first, second] = Array.from(events);
222 assert.equal(events.length, 2);
223 assert.equal(first?.type, "settingsUpdated");
224 assert.equal(second?.type, "snapshot");
225 if (second?.type === "snapshot") {
226 assert.deepEqual(second.config.availableEditors, ["file-manager"]);
227 assert.equal(second.config.shellRevealInFileManagerKind, "file-explorer");
228 assert.deepEqual(second.config.settings, { enableProviderUpdateChecks: false } as never);
229 }
230 }),
231 );
232
233 it.effect("resends a reveal kind and remote targets that outlast the snapshot timeout", () =>
234 Effect.gen(function* () {
235 const targets = [{ kind: "mdns" as const, host: "test.local" }];
236 const finishDiscovery = yield* Deferred.make<typeof targets>();
237 const collecting = yield* withLateConfigDiscovery(
238 snapshotConfig({ availableEditors: ["file-manager"] }),
239 Stream.empty,
240 {
241 resolveAvailableEditors: () => Effect.succeed(["file-manager"]),
242 resolveFileManagerRevealKind: () => Effect.succeed("file-explorer"),
243 },
244 { resolveTargets: () => Deferred.await(finishDiscovery) },
245 { resolve: () => Effect.succeed([]) },
246 ).pipe(Stream.runCollect, Effect.forkScoped({ startImmediately: true }));
247 yield* TestClock.adjust("6 seconds");
248 yield* Deferred.succeed(finishDiscovery, targets);
249 const events = yield* Fiber.join(collecting);
250
251 const [late, remote] = Array.from(events);
252 assert.equal(events.length, 2);
253 assert.equal(late?.type, "snapshot");
254 if (late?.type === "snapshot") {
255 assert.equal(late.config.shellRevealInFileManagerKind, "file-explorer");
256 }
257 assert.equal(remote?.type, "snapshot");
258 if (remote?.type === "snapshot") {
259 assert.deepEqual(remote.config.remoteOpenTargets, targets);
260 assert.equal(remote.config.shellRevealInFileManagerKind, "file-explorer");
261 }
262 }),
263 );
264
265 it.effect("runs editor, remote open target and direct endpoint discovery side by side", () =>
266 Effect.gen(function* () {
267 // Each discovery finishes only once the other two have started, so a
268 // config that ran them one after another would never resolve.
269 const editorsStarted = yield* Deferred.make<void>();
270 const targetsStarted = yield* Deferred.make<void>();
271 const endpointsStarted = yield* Deferred.make<void>();
272 const startThenAwait = <A>(started: Deferred.Deferred<void>, value: A) =>
273 Deferred.succeed(started, undefined).pipe(
274 Effect.andThen(
275 Effect.forEach([editorsStarted, targetsStarted, endpointsStarted], Deferred.await),
276 ),
277 Effect.as(value),
278 );
279
280 const discovery = yield* resolveOpenDiscoveryForConfig({
281 editors: startThenAwait(editorsStarted, ["file-manager" as const]),
282 fileManagerRevealKind: Effect.succeed("finder" as const),
283 remoteOpenTargets: startThenAwait(targetsStarted, []),
284 directEndpoints: startThenAwait(endpointsStarted, []),
285 });
286
287 assert.deepEqual(discovery, {
288 availableEditors: ["file-manager"],
289 shellRevealInFileManager: true,
290 shellRevealInFileManagerKind: "finder",
291 remoteOpenTargets: [],
292 directEndpoints: [],
293 });
294 }),
295 );
296
297 const ReplayTestLayer = OrchestrationEventStore.layer.pipe(
298 Layer.provideMerge(SqlitePersistence.layerMemory),
299 );
300
301 const resumeSkipsUnknownTypes = (scope: "thread" | "shell") =>
302 Effect.gen(function* () {
303 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
304 const sql = yield* SqlClient.SqlClient;
305 const now = "2026-01-05T00:00:00.000Z";
306 const threadId = ThreadId.make("thread:replay");
307 const projectId = ProjectId.make("project:replay");
308 const project = {
309 id: projectId,
310 title: "Replay",
311 workspaceRoot: "/tmp/replay",
312 defaultModelSelection: null,
313 scripts: [],
314 createdAt: now,
315 updatedAt: now,
316 } satisfies OrchestrationProjectShell;
317 const insert = (version: number, unknown = false) => sql<{ sequence: number }>`
318 INSERT INTO orchestration_events (
319 event_id, aggregate_kind, stream_id, stream_version, event_type,
320 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
321 ) VALUES (
322 ${`replay:${version}`}, ${scope === "thread" ? "thread" : "project"},
323 ${scope === "thread" ? threadId : projectId}, ${version},
324 ${unknown ? "future.event" : scope === "thread" ? "provider-session.detached" : "project.meta-updated"},
325 ${now}, 'server', ${JSON.stringify(
326 scope === "thread"
327 ? { providerSessionId: "session:replay", detachedAt: now }
328 : { projectId, updatedAt: now },
329 )}, '{}', 2
330 ) RETURNING sequence
331 `;
332 const [before] = yield* insert(0);
333 yield* insert(1, true);
334 const [after] = yield* insert(2);
335 const [highWater] = yield* insert(3, true);
336 const updates = yield* PubSub.unbounded();
337 let liveSequence = 0;
338 const consume = <A extends { readonly kind: string; readonly sequence?: number }, E, R>(
339 stream: Stream.Stream<A, E, R>,
340 ) =>
341 stream.pipe(
342 Stream.tap((item) =>
343 Effect.gen(function* () {
344 if (item.kind !== "synchronized") return;
345 const [live] = yield* insert(4);
346 liveSequence = live!.sequence;
347 const events = yield* store
348 .readApplicationEvents({
349 afterSequence: highWater!.sequence,
350 throughSequence: liveSequence,
351 })
352 .pipe(Stream.runCollect);
353 yield* store.publishCommitted(events);
354 }),
355 ),
356 Stream.takeUntil((item) => item.sequence === liveSequence),
357 Stream.map((item) => ({ kind: item.kind as string, sequence: item.sequence })),
358 Stream.runCollect,
359 );
360 const subscription = Effect.gen(function* () {
361 return scope === "thread"
362 ? yield* subscribeOrchestrationV2Thread({
363 threadId,
364 afterSequence: before!.sequence,
365 requestCompletionMarker: true,
366 }).pipe(Effect.flatMap(consume))
367 : yield* subscribeOrchestrationV2Shell({
368 afterSequence: before!.sequence,
369 requestCompletionMarker: true,
370 }).pipe(Effect.flatMap(consume));
371 });
372 const items = yield* subscription.pipe(
373 Effect.provideService(ThreadManagement.ThreadManagementService, {
374 ensureLegacyTranscript: () => Effect.void,
375 getShellSnapshot: () => Effect.die("shell resume must not load a full snapshot"),
376 listActiveSubagentThreadIds: () => Effect.succeed([]),
377 streamStoredEventsFrom: (
378 input: Parameters<
379 ThreadManagement.ThreadManagementService["Service"]["streamStoredEventsFrom"]
380 >[0],
381 ) => {
382 assert.equal(input?.afterSequence, highWater!.sequence);
383 return store
384 .streamApplicationEvents({ afterSequence: input?.afterSequence ?? 0 })
385 .pipe(Stream.filter((event): event is OrchestrationV2StoredEvent => "event" in event));
386 },
387 } as unknown as ThreadManagement.ThreadManagementService["Service"]),
388 Effect.provideService(ProjectStore.ProjectStoreV2, {
389 listShells: () => Effect.succeed([]),
390 } as unknown as ProjectStore.ProjectStoreV2["Service"]),
391 Effect.provideService(ProjectService.ProjectService, {
392 getShell: () => Effect.succeedSome(project),
393 } as unknown as ProjectService.ProjectService["Service"]),
394 Effect.provideService(ProjectEnrichment.ProjectEnrichmentService, {
395 subscribeChanges: PubSub.subscribe(updates),
396 } as ProjectEnrichment.ProjectEnrichmentService["Service"]),
397 );
398 assert.deepEqual(
399 items.map((item) => item.kind),
400 scope === "thread"
401 ? ["event", "synchronized", "event"]
402 : ["project.updated", "synchronized", "project.updated"],
403 );
404 assert.deepEqual(
405 items.flatMap((item) => (item.sequence === undefined ? [] : [item.sequence])),
406 [after!.sequence, liveSequence],
407 );
408 }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer));
409
410 it.effect("thread resume skips unknown types, synchronizes, and receives the live tail", () =>
411 resumeSkipsUnknownTypes("thread"),
412 );
413
414 // Shell updates batch through `Stream.groupedWithin`, whose window needs real time to close.
415 it.live("shell resume skips unknown types, synchronizes, and receives the live tail", () =>
416 resumeSkipsUnknownTypes("shell"),
417 );
418
419 it.effect("coalesces streaming replay before synchronization and the live tail", () =>
420 Effect.gen(function* () {
421 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
422 const sql = yield* SqlClient.SqlClient;
423 const threadId = ThreadId.make("thread:streaming-replay");
424 const now = "2026-10-27T00:00:00.000Z";
425 const insert = (version: number, text: string, streaming: boolean) => sql<{
426 sequence: number;
427 }>`
428 INSERT INTO orchestration_events (
429 event_id, aggregate_kind, stream_id, stream_version, event_type,
430 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
431 ) VALUES (
432 ${`streaming-replay:${version}`}, 'thread', ${threadId}, ${version}, 'message.updated',
433 ${now}, 'server', ${JSON.stringify({
434 createdBy: "agent",
435 creationSource: "web",
436 id: "message:streaming-replay",
437 threadId,
438 runId: null,
439 nodeId: null,
440 role: "assistant",
441 text,
442 attachments: [],
443 streaming,
444 createdAt: now,
445 updatedAt: now,
446 })}, '{}', 2
447 ) RETURNING sequence
448 `;
449 yield* insert(0, "H", true);
450 yield* insert(1, "He", true);
451 const [latest] = yield* insert(2, "Hello", true);
452 const [completed] = yield* insert(3, "Hello!", false);
453 const items = yield* subscribeOrchestrationV2Thread({
454 threadId,
455 afterSequence: 0,
456 requestCompletionMarker: true,
457 }).pipe(
458 Effect.flatMap(Stream.runCollect),
459 Effect.provideService(ThreadManagement.ThreadManagementService, {
460 ensureLegacyTranscript: () => Effect.void,
461 streamStoredEventsFrom: () =>
462 Stream.unwrap(
463 insert(4, "Next", false).pipe(
464 Effect.map(() =>
465 store.readAgentEvents({ threadId, afterSequence: completed!.sequence }),
466 ),
467 ),
468 ),
469 } as unknown as ThreadManagement.ThreadManagementService["Service"]),
470 );
471 assert.deepEqual(
472 items.map((item) =>
473 item.kind === "event"
474 ? [item.sequence, item.event.type === "message.updated" ? item.event.payload.text : null]
475 : [item.kind],
476 ),
477 [
478 [latest!.sequence, "Hello"],
479 [completed!.sequence, "Hello!"],
480 ["synchronized"],
481 [completed!.sequence + 1, "Next"],
482 ],
483 );
484 }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),
485 );
486
487 it.effect("shell groups read distinct threads once and keep each event's own sequence", () =>
488 Effect.gen(function* () {
489 const sql = yield* SqlClient.SqlClient;
490 const now = "2026-10-27T00:00:00.000Z";
491 const insert = (aggregateKind: "thread" | "project", streamId: string, version: number) =>
492 sql<{ sequence: number }>`
493 INSERT INTO orchestration_events (
494 event_id, aggregate_kind, stream_id, stream_version, event_type,
495 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
496 ) VALUES (
497 ${`shell-group:${streamId}:${version}`}, ${aggregateKind}, ${streamId}, ${version},
498 ${aggregateKind === "thread" ? "provider-session.detached" : "project.meta-updated"},
499 ${now}, 'server', ${JSON.stringify(
500 aggregateKind === "thread"
501 ? { providerSessionId: "session:shell-group", detachedAt: now }
502 : { projectId: streamId, updatedAt: now },
503 )}, '{}', 2
504 ) RETURNING sequence
505 `.pipe(Effect.map(([row]) => row!.sequence));
506 const shell = (id: string, archivedAt: string | null = null) =>
507 ({ id: ThreadId.make(id), archivedAt }) as unknown as OrchestrationV2ThreadShell;
508 const project = {
509 id: ProjectId.make("project:group"),
510 } as unknown as OrchestrationProjectShell;
511
512 const after = yield* insert("project", "project:before", 0);
513 yield* insert("thread", "thread:active", 0);
514 const archived = yield* insert("thread", "thread:archived", 0);
515 const projectUpdated = yield* insert("project", project.id, 0);
516 const active = yield* insert("thread", "thread:active", 1);
517 const missing = yield* insert("thread", "thread:missing", 0);
518
519 const shellReads: Array<ReadonlyArray<string> | undefined> = [];
520 let batchFails = false;
521 const collect = (afterSequence: number) =>
522 subscribeOrchestrationV2Shell({ afterSequence, requestCompletionMarker: true }).pipe(
523 Effect.flatMap((stream) =>
524 stream.pipe(
525 Stream.takeUntil((item) => item.kind === "synchronized"),
526 Stream.runCollect,
527 ),
528 ),
529 Effect.provideService(ThreadManagement.ThreadManagementService, {
530 listActiveSubagentThreadIds: () => Effect.succeed([]),
531 getShellSnapshot: (options?: { readonly threadIds?: ReadonlyArray<string> }) =>
532 Effect.suspend(() => {
533 shellReads.push(options?.threadIds);
534 return batchFails
535 ? Effect.fail("batch failed")
536 : Effect.succeed({
537 schemaVersion: 1,
538 snapshotSequence: Number.MAX_SAFE_INTEGER,
539 threads: [shell("thread:active")],
540 archivedThreads: [shell("thread:archived", now)],
541 });
542 }),
543 getThreadShell: (threadId: string) =>
544 Effect.sync(() => {
545 shellReads.push([`scalar:${threadId}`]);
546 return threadId === "thread:missing"
547 ? null
548 : shell(threadId, threadId === "thread:archived" ? now : null);
549 }),
550 } as unknown as ThreadManagement.ThreadManagementService["Service"]),
551 Effect.provideService(ProjectStore.ProjectStoreV2, {
552 listShells: () => Effect.succeed([]),
553 } as unknown as ProjectStore.ProjectStoreV2["Service"]),
554 Effect.provideService(ProjectService.ProjectService, {
555 getShell: () => Effect.succeedSome(project),
556 } as unknown as ProjectService.ProjectService["Service"]),
557 Effect.provideServiceEffect(
558 ProjectEnrichment.ProjectEnrichmentService,
559 PubSub.unbounded().pipe(
560 Effect.map(
561 (changes) =>
562 ({
563 subscribeChanges: PubSub.subscribe(changes),
564 }) as unknown as ProjectEnrichment.ProjectEnrichmentService["Service"],
565 ),
566 ),
567 ),
568 );
569
570 const collectSummary = (afterSequence: number) =>
571 collect(afterSequence).pipe(
572 Effect.map((items) =>
573 items.flatMap((item): ReadonlyArray<ReadonlyArray<string | number>> =>
574 item.kind === "thread.updated"
575 ? [[item.kind, item.sequence, item.thread.id]]
576 : item.kind === "thread.removed"
577 ? [[item.kind, item.sequence, item.threadId]]
578 : item.kind === "project.updated"
579 ? [[item.kind, item.sequence, item.project.id]]
580 : [],
581 ),
582 ),
583 );
584 const expectedGroup = [
585 ["thread.removed", archived, "thread:archived"],
586 ["project.updated", projectUpdated, project.id],
587 ["thread.updated", active, "thread:active"],
588 ["thread.removed", missing, "thread:missing"],
589 ];
590
591 assert.deepEqual(yield* collectSummary(after), expectedGroup);
592 assert.deepEqual(shellReads, [["thread:archived", "thread:active", "thread:missing"]]);
593
594 shellReads.length = 0;
595 assert.deepEqual(yield* collectSummary(active), [
596 ["thread.removed", missing, "thread:missing"],
597 ]);
598 assert.deepEqual(shellReads, [["scalar:thread:missing"]]);
599
600 shellReads.length = 0;
601 batchFails = true;
602 assert.deepEqual(yield* collectSummary(after), expectedGroup);
603 assert.deepEqual(shellReads, [
604 ["thread:archived", "thread:active", "thread:missing"],
605 ["scalar:thread:archived"],
606 ["scalar:thread:active"],
607 ["scalar:thread:missing"],
608 ]);
609 }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),
610 );
611
612 it.effect("shares each live event item across subscribers and dedupes bodies per subscriber", () =>
613 Effect.gen(function* () {
614 const threadId = ThreadId.make("thread:shared-live");
615 const messageId = MessageId.make("message:shared-live");
616 const at = DateTime.makeUnsafe("2026-10-31T00:00:00.000Z");
617 const owner = { threadId, runId: null, nodeId: null, createdAt: at, updatedAt: at };
618 // DateTime memoizes its formatted parts, so only the plain records are frozen.
619 const freeze = <A>(value: A): A => {
620 if (typeof value === "object" && value !== null && !DateTime.isDateTime(value)) {
621 for (const child of Object.values(value)) freeze(child);
622 Object.freeze(value);
623 }
624 return value;
625 };
626 const live: ReadonlyArray<OrchestrationV2StoredEvent> = freeze([
627 {
628 sequence: 1,
629 commandId: null,
630 event: {
631 id: EventId.make("event:shared-live:message"),
632 type: "message.updated",
633 threadId,
634 occurredAt: at,
635 payload: {
636 ...owner,
637 id: messageId,
638 role: "assistant",
639 text: "Done",
640 attachments: [],
641 streaming: false,
642 createdBy: "agent",
643 creationSource: "provider",
644 },
645 },
646 },
647 {
648 sequence: 2,
649 commandId: null,
650 event: {
651 id: EventId.make("event:shared-live:reply"),
652 type: "turn-item.updated",
653 threadId,
654 occurredAt: at,
655 payload: {
656 ...owner,
657 id: TurnItemId.make("item:shared-live:reply"),
658 type: "assistant_message",
659 providerThreadId: null,
660 providerTurnId: null,
661 nativeItemRef: null,
662 parentItemId: null,
663 ordinal: 1,
664 title: null,
665 status: "completed",
666 messageId,
667 text: "Done",
668 streaming: false,
669 startedAt: at,
670 completedAt: at,
671 },
672 },
673 },
674 ] as ReadonlyArray<OrchestrationV2StoredEvent>);
675 const stringify = yield* Effect.acquireRelease(
676 Effect.sync(() => vi.spyOn(JSON, "stringify")),
677 (spy) => Effect.sync(() => spy.mockRestore()),
678 );
679 // The EventSink hands every subscriber the same projected objects.
680 const subscribe = (acceptDedupedBodies: boolean) =>
681 subscribeOrchestrationV2Thread({ threadId, afterSequence: 0, acceptDedupedBodies }).pipe(
682 Effect.flatMap(Stream.runCollect),
683 Effect.map((items) => Array.from(items)),
684 Effect.provideService(ThreadManagement.ThreadManagementService, {
685 ensureLegacyTranscript: () => Effect.void,
686 streamStoredEventsFrom: () => Stream.fromIterable(live),
687 } as unknown as ThreadManagement.ThreadManagementService["Service"]),
688 );
689 const [deduped, first, second] = yield* Effect.forEach([true, false, false], subscribe);
690
691 assert.lengthOf(first!, live.length);
692 first!.forEach((item, index) => {
693 assert.strictEqual(item, second![index]);
694 assert.strictEqual(item.kind === "event" && item.event, live[index]!.event);
695 });
696 assert.strictEqual(deduped![0], first![0]);
697 const reply = deduped![1];
698 assert.deepInclude(reply?.kind === "event" ? reply.event.payload : undefined, {
699 text: "",
700 textOmitted: true,
701 });
702 // The live buffer sizes each shared item once, not once per subscriber.
703 assert.lengthOf(
704 stringify.mock.calls.filter(([value]) => value?.kind === "event"),
705 live.length,
706 );
707 }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),
708 );
709
710 it.effect("shell snapshots omit idle children and older settled threads only on request", () =>
711 Effect.gen(function* () {
712 const shell = (
713 id: string,
714 parent: string | null,
715 activityRunStatus: "running" | null,
716 settledDaysAgo: number | null = null,
717 ) =>
718 ({
719 id: ThreadId.make(id),
720 projectId: "project",
721 archivedAt: null,
722 status: activityRunStatus ?? "completed",
723 activityRunStatus,
724 pendingRuntimeRequest: null,
725 pendingBackgroundTasks: [],
726 settledOverride: settledDaysAgo === null ? null : "settled",
727 settledAt:
728 settledDaysAgo === null ? null : DateTime.makeUnsafe(-settledDaysAgo * 86_400_000),
729 lineage: {
730 parentThreadId: parent === null ? null : ThreadId.make(parent),
731 relationshipToParent: parent === null ? null : "subagent",
732 rootThreadId: ThreadId.make(parent ?? id),
733 },
734 }) as unknown as OrchestrationV2ThreadShell;
735 const threads = [
736 shell("parent", null, null),
737 shell("idle", "parent", null),
738 shell("live", "parent", "running"),
739 ...Array.from({ length: 25 }, (_, index) => shell(`recent-${index}`, null, null, 1)),
740 shell("old", null, null, 30),
741 shell("remote-parent", null, null, 40),
742 shell("remote-child-parent", "parent", null),
743 ];
744 const firstSnapshot = (input: {
745 readonly omitIdleSubagents?: boolean;
746 readonly omitOlderSettled?: boolean;
747 }) =>
748 subscribeOrchestrationV2Shell(input).pipe(
749 Effect.flatMap((stream) => stream.pipe(Stream.take(1), Stream.runCollect)),
750 Effect.map(([item]) => (item?.kind === "snapshot" ? item.snapshot : null)),
751 Effect.provideService(ThreadManagement.ThreadManagementService, {
752 listActiveShellIndex: () =>
753 Effect.succeed(
754 threads.map((thread) => ({
755 ...thread,
756 pinnedAt: null,
757 snoozedUntil: null,
758 mayBeLive: thread.activityRunStatus !== null,
759 hasRemoteTasks: thread.id.startsWith("remote-"),
760 })),
761 ),
762 readShellSnapshot: (options?: { readonly threadIds?: ReadonlyArray<string> }) =>
763 Effect.succeed(
764 Effect.succeed({
765 schemaVersion: 1,
766 snapshotSequence: 0,
767 threads: threads.filter(
768 (thread) => options?.threadIds?.includes(thread.id) ?? true,
769 ),
770 archivedThreads: [],
771 }),
772 ),
773 } as unknown as ThreadManagement.ThreadManagementService["Service"]),
774 Effect.provideService(ProjectStore.ProjectStoreV2, {
775 listShells: () => Effect.succeed([]),
776 } as unknown as ProjectStore.ProjectStoreV2["Service"]),
777 Effect.provideService(ProjectService.ProjectService, {
778 getShell: () => Effect.succeedNone,
779 } as unknown as ProjectService.ProjectService["Service"]),
780 Effect.provideServiceEffect(
781 ProjectEnrichment.ProjectEnrichmentService,
782 PubSub.unbounded().pipe(
783 Effect.map(
784 (changes) =>
785 ({
786 subscribeChanges: PubSub.subscribe(changes),
787 }) as unknown as ProjectEnrichment.ProjectEnrichmentService["Service"],
788 ),
789 ),
790 ),
791 );
792
793 const recent = threads.slice(3, 28).map((thread) => thread.id);
794 const full = yield* firstSnapshot({});
795 assert.deepEqual(
796 full?.threads.map((thread) => thread.id),
797 threads.map((thread) => thread.id),
798 );
799 assert.isUndefined(full?.olderSettled);
800 const withoutChildren = yield* firstSnapshot({ omitIdleSubagents: true });
801 assert.deepEqual(
802 withoutChildren?.threads.map((thread) => thread.id),
803 ["parent", "live", ...recent, "old", "remote-parent", "remote-child-parent"],
804 );
805 // A linked environment's clients nest its task under its parent, so that parent stays: an
806 // older settled thread or an idle subagent.
807 const withoutOld = yield* firstSnapshot({ omitIdleSubagents: true, omitOlderSettled: true });
808 assert.deepEqual(
809 withoutOld?.threads.map((thread) => thread.id),
810 ["parent", "live", ...recent, "remote-parent", "remote-child-parent"],
811 );
812 assert.deepEqual(withoutOld?.olderSettled?.counts, [
813 { projectId: ProjectId.make("project"), count: 2 },
814 ]);
815 }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),
816 );
817
818 // Build the production RPC layer; unrelated capabilities fail if this test calls them.
819 const layerUnusedConfigRpcServices = Layer.mergeAll(
820 Layer.mock(DocumentText.DocumentText)({}),
821 Layer.mock(ServerSecretStore.ServerSecretStore)({}),
822 Layer.mock(SecretCheck.SecretCheck)({}),
823 Layer.mock(WorkspacePaths.WorkspacePaths)({}),
824 Layer.mock(TraceDiagnostics.TraceDiagnostics)({}),
825 Layer.mock(TriageService.TriageService)({}),
826 Layer.mock(TextGenerators.TextGenerators)({}),
827 Layer.mock(ProjectFaviconResolver.ProjectFaviconResolver)({}),
828 Layer.mock(ProjectEnrichment.ProjectEnrichmentService)({}),
829 Layer.mock(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator)({}),
830 Layer.mock(AcpRegistrySupport.AcpRegistryCatalog)({}),
831 Layer.mock(AcpRegistrySessions.AcpRegistrySessions)({}),
832 Layer.mock(AgentSessionImporter.AgentSessionImporter)({}),
833 Layer.mock(AgentSessionScanner.AgentSessionScanner)({}),
834 Layer.mock(AnalyticsService.AnalyticsService)({}),
835 Layer.mock(AntigravityInstallation.AntigravityInstallation)({ managedDirectory: "/unused" }),
836 Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
837 Layer.mock(CheckpointDiffQuery.CheckpointDiffQuery)({}),
838 Layer.mock(NativeChildWorkQuery.NativeChildWorkQuery)({}),
839 Layer.mock(CommandOutputHub.CommandOutputHub)({}),
840 ThreadViewers.layer,
841 Layer.mock(CodexInstallation.CodexInstallation)({ managedDirectory: "/unused" }),
842 Layer.mock(DeviceService.DeviceService)({}),
843 Layer.mock(EnvironmentTheme.EnvironmentThemeService)({}),
844 Layer.mock(GitWorkflowService.GitWorkflowService)({}),
845 Layer.mock(HostResources.HostResources)({}),
846 Layer.mock(McpAppRequests.McpAppRequests)({}),
847 Layer.mock(McpSignIn.McpSignIn)({}),
848 Layer.mock(ModelManifest.ModelManifest)({}),
849 Layer.mock(OrchestrationEventStore.OrchestrationEventStore)({}),
850 Layer.mock(Orchestrator.OrchestratorV2)({}),
851 Layer.mock(OtlpEndpointCheck.OtlpEndpointCheck)({}),
852 Layer.mock(PairingGrantStore.PairingGrantStore)({}),
853 Layer.mock(PeerLinks.PeerLinks)({}),
854 Layer.mock(PeerLinkRequests.PeerLinkRequests)({}),
855 Layer.mock(PeerThreadRelay.PeerThreadRelay)({}),
856 Layer.mock(PeerClientPairing.PeerClientPairing)({}),
857 Layer.mock(PortScanner.PortDiscovery)({ trackAgent: () => () => undefined }),
858 Layer.mock(PreviewManager.PreviewManager)({}),
859 Layer.mock(ProcessDiagnostics.ProcessDiagnostics)({}),
860 Layer.mock(ProcessResourceMonitor.ProcessResourceMonitor)({}),
861 Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({}),
862 Layer.mock(ProjectService.ProjectService)({}),
863 Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({}),
864 Layer.mock(ProjectStore.ProjectStoreV2)({}),
865 Layer.mock(ProviderAuthService.ProviderAuthService)({}),
866 Layer.mock(ProviderInstallation.ProviderInstallation)({}),
867 Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({}),
868 Layer.mock(ProviderLatestVersions.ProviderLatestVersions)({}),
869 Layer.mock(ProviderMaintenanceRunner.ProviderMaintenanceRunner)({}),
870 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}),
871 Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
872 Layer.mock(PullRequestService.PullRequestService)({}),
873 Layer.mock(IssueService.IssueService)({}),
874 Layer.mock(ThreadIssueService.ThreadIssueService)({}),
875 Layer.mock(IssueTrackerConnections.IssueTrackerConnections)({}),
876 Layer.mock(PullRequestSyncReactor.PullRequestSyncReactor)({}),
877 Layer.mock(RelayClient.RelayClient)({}),
878 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}),
879 Layer.mock(ResourceTelemetry.ResourceTelemetry)({}),
880 Layer.mock(ReviewService.ReviewService)({}),
881 Layer.mock(ScheduledTasks.ScheduledTaskService)({}),
882 Layer.mock(SecretRequests.SecretRequests)({}),
883 Layer.mock(SecretResolver.SecretResolver)({}),
884 Layer.mock(GuestShareService.GuestShareService)({}),
885 Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({}),
886 Layer.mock(ServerRuntimeStartup.ServerRuntimeStartup)({}),
887 Layer.mock(ServerSelfUpdate.ServerSelfUpdate)({}),
888 Layer.mock(NpmRelease.NpmRelease)({}),
889 Layer.mock(SessionStore.SessionStore)({ cookieName: "config-test", legacyCookieName: undefined }),
890 Layer.mock(SourceControlDiscovery.SourceControlDiscovery)({}),
891 Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({}),
892 Layer.mock(SourceControlSignIn.SourceControlSignIn)({}),
893 Layer.mock(StorageCleanup.StorageCleanup)({}),
894 Layer.mock(DatabaseStorage.DatabaseStorage)({}),
895 Layer.mock(TerminalManager.TerminalManager)({}),
896 Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
897 Layer.mock(ThreadManagement.ThreadManagementService)({}),
898 Layer.mock(ThreadSearch.ThreadSearch)({}),
899 Layer.mock(UsageService.UsageService)({}),
900 Layer.mock(VcsProvisioningService.VcsProvisioningService)({}),
901 Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({}),
902 Layer.mock(WorkspaceEntries.WorkspaceEntries)({}),
903 Layer.mock(WorkspaceFileSystem.WorkspaceFileSystem)({}),
904 Layer.mock(WorktreeSetupTracker.WorktreeSetupTracker)({}),
905 );
906
907 const layerConfigSources = Layer.mergeAll(
908 Keybindings.layer,
909 AssetSigner.layer.pipe(Layer.provide(ServerSecretStore.layer)),
910 WorkspacePreviewRevisions.layer,
911 ServerSettings.layer.pipe(
912 Layer.provide(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layerTest())),
913 ),
914 ).pipe(
915 Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
916 Layer.provideMerge(
917 Layer.fresh(
918 ServerConfigModule.layerTest(process.cwd(), { prefix: "t3-config-subscription-test-" }),
919 ),
920 ),
921 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
922 );
923
924 it.live.each([
925 { subject: "desktop-bootstrap", extensions: "", framed: false },
926 { subject: "desktop-bootstrap", extensions: "", framed: true },
927 { subject: "one-time-token", extensions: "permessage-deflate", framed: false },
928 { subject: "cloud-connect", extensions: "permessage-deflate", framed: false },
929 ])(
930 "negotiates compression for $subject sessions (framed=$framed)",
931 ({ subject, extensions, framed }) =>
932 Effect.gen(function* () {
933 const services = Layer.mergeAll(
934 layerUnusedConfigRpcServices,
935 Layer.mock(ServerBrowser.ServerBrowser)({
936 profileReporter: Effect.succeed(() => Effect.void),
937 }),
938 Layer.mock(EnvironmentAuth.EnvironmentAuth)({
939 authenticateWebSocketUpgrade: () =>
940 Effect.succeed({
941 sessionId: AuthSessionId.make("compression-test"),
942 subject,
943 method: "bearer-access-token",
944 scopes: [],
945 }),
946 }),
947 Layer.mock(SessionStore.SessionStore)({
948 cookieName: "compression-test",
949 legacyCookieName: undefined,
950 markConnected: () => Effect.void,
951 markDisconnected: () => Effect.void,
952 awaitInvalidation: () => Effect.never,
953 }),
954 Layer.mock(AnalyticsService.AnalyticsService)({ recordOwners: () => Effect.void }),
955 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
956 namedProjectsRoot: process.cwd(),
957 }),
958 Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}),
959 Layer.mock(ProviderRegistry.ProviderRegistry)({}),
960 Layer.mock(UsageLimitSources.UsageLimitSources)({}),
961 Layer.mock(ExternalLauncher.ExternalLauncher)({}),
962 Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}),
963 Layer.mock(DirectEndpoints.DirectEndpoints)({}),
964 Layer.mock(ServerEnvironment.ServerEnvironment)({}),
965 Layer.mock(VcsProcess.VcsProcess)({
966 run: (input) =>
967 Effect.fail(
968 new VcsProcessSpawnError({
969 operation: input.operation,
970 command: input.command,
971 cwd: input.cwd,
972 cause: "No VCS commands in the compression fixture",
973 }),
974 ),
975 }),
976 ProviderInstallationGate.layer,
977 FetchHttpClient.layer,
978 );
979 const context = yield* Layer.build(
980 HttpRouter.serve(Ws.layer, { disableListenLog: true }).pipe(
981 Layer.provideMerge(
982 NodeHttpServer.layer(NodeHttp.createServer, {
983 host: "127.0.0.1",
984 port: 0,
985 websocket: { perMessageDeflate: true },
986 }),
987 ),
988 Layer.provide(services),
989 Layer.provide(layerConfigSources),
990 ),
991 );
992 const server = Context.get(context, HttpServer.HttpServer);
993 const origin = HttpServer.formatAddress(server.address).replace(/^http/, "ws");
994 const socket = yield* Effect.acquireRelease(
995 Effect.sync(
996 () =>
997 new WebSocket(
998 `${origin}/ws?${ORCHESTRATION_PROTOCOL_QUERY_PARAM}=${ORCHESTRATION_PROTOCOL_VERSION}${framed ? `&${SOCKET_FRAME_PARTS_QUERY_PARAM}=1` : ""}`,
999 {
1000 origin: "t3code://app",
1001 },
1002 ),
1003 ),
1004 (socket) => Effect.sync(() => socket.terminate()),
1005 );
1006 yield* Effect.promise(
1007 () =>
1008 new Promise<void>((resolve, reject) => {
1009 socket.once("open", resolve);
1010 socket.once("error", reject);
1011 }),
1012 );
1013 assert.equal(socket.extensions, extensions);
1014 }).pipe(Effect.scoped),
1015 );
1016
1017 it.effect.each([
1018 "pending",
1019 "cached",
1020 "direct-pending",
1021 "direct-cached",
1022 "direct-failed",
1023 "direct-interrupted",
1024 ] as const)(
1025 "%s endpoint discovery preserves initial config and updates through discovery and ACK",
1026 (discovery) =>
1027 Effect.gen(function* () {
1028 const keybindings = yield* Keybindings.Keybindings;
1029 const settings = yield* ServerSettings.ServerSettingsService;
1030 const keybindingsSubscribed = yield* Deferred.make<void>();
1031 const settingsSubscribed = yield* Deferred.make<void>();
1032 const keybindingsChanges = keybindings.subscribeChanges.pipe(
1033 Effect.tap(() => Deferred.succeed(keybindingsSubscribed, undefined)),
1034 );
1035 const settingsChanges = settings.subscribeChanges.pipe(
1036 Effect.tap(() => Deferred.succeed(settingsSubscribed, undefined)),
1037 );
1038 const initialKeybindings = (yield* keybindings.getSnapshot).keybindings;
1039 const discoveryStarted = yield* Deferred.make<void>();
1040 const finishDiscovery = yield* Deferred.make<void>();
1041 const remoteDiscoveryStarted = yield* Deferred.make<void>();
1042 const finishRemoteDiscovery = yield* Deferred.make<void>();
1043 const targets = [{ kind: "mdns" as const, host: "test.local" }];
1044 const direct = discovery.startsWith("direct-");
1045 const bound = [{ kind: "lan" as const, httpBaseUrl: "http://192.168.1.10:3773/" }];
1046 const endpoints = [
1047 ...bound,
1048 { kind: "tailnet" as const, httpBaseUrl: "https://test.ts.net/" },
1049 ];
1050 const directStarted = yield* Deferred.make<void>();
1051 const finishDirect = yield* Deferred.make<void>();
1052 const directStopped = yield* Deferred.make<void>();
1053 const responses = yield* Queue.unbounded<ServerConfigStreamEvent>();
1054 const configRpcServices = Layer.mergeAll(
1055 layerUnusedConfigRpcServices,
1056 Layer.mock(ExternalLauncher.ExternalLauncher)({
1057 resolveAvailableEditors: () =>
1058 Deferred.succeed(discoveryStarted, undefined).pipe(
1059 Effect.andThen(Deferred.await(finishDiscovery)),
1060 Effect.as([]),
1061 ),
1062 resolveFileManagerRevealKind: () => Effect.undefined,
1063 }),
1064 Layer.mock(ProviderRegistry.ProviderRegistry)({
1065 getProviders: Effect.succeed([]),
1066 streamChanges: Stream.never,
1067 }),
1068 Layer.mock(UsageLimitSources.UsageLimitSources)({ streamChanges: Stream.make([]) }),
1069 Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({
1070 resolveTargets: () =>
1071 Deferred.succeed(remoteDiscoveryStarted, undefined).pipe(
1072 Effect.andThen(
1073 discovery === "cached" || direct
1074 ? Effect.void
1075 : Deferred.await(finishRemoteDiscovery),
1076 ),
1077 Effect.as(targets),
1078 ),
1079 }),
1080 Layer.mock(DirectEndpoints.DirectEndpoints)({
1081 resolveAvailable: () => Effect.succeed(discovery === "direct-cached" ? endpoints : bound),
1082 resolve: () =>
1083 direct
1084 ? Deferred.succeed(directStarted, undefined).pipe(
1085 Effect.andThen(
1086 discovery === "direct-cached" ? Effect.void : Deferred.await(finishDirect),
1087 ),
1088 Effect.andThen(
1089 discovery === "direct-failed"
1090 ? Effect.die("probe failed")
1091 : Effect.succeed(endpoints),
1092 ),
1093 Effect.onExit(() => Deferred.succeed(directStopped, undefined)),
1094 )
1095 : Effect.succeed(bound),
1096 }),
1097 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
1098 scratchRoot: Effect.succeedNone,
1099 namedProjectsRoot: process.cwd(),
1100 }),
1101 Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}),
1102 Layer.mock(ServerEnvironment.ServerEnvironment)({
1103 getDescriptor: Effect.succeed({
1104 environmentId: EnvironmentId.make("config-test"),
1105 label: "Config test",
1106 platform: { os: "linux", arch: "x64" },
1107 serverVersion: "0.0.0",
1108 capabilities: { repositoryIdentity: false },
1109 }),
1110 }),
1111 Layer.mock(EnvironmentAuth.EnvironmentAuth)({
1112 getDescriptor: () =>
1113 Effect.succeed({
1114 policy: "loopback-browser",
1115 bootstrapMethods: [],
1116 sessionMethods: ["browser-session-cookie"],
1117 sessionCookieName: "config-test-session",
1118 }),
1119 }),
1120 // Signal subscription on either accessor so the test also fails, rather
1121 // than hangs, against a handler that subscribes after the snapshot.
1122 Layer.succeed(Keybindings.Keybindings, {
1123 ...keybindings,
1124 streamChanges: Stream.unwrap(keybindingsChanges),
1125 subscribeChanges: keybindingsChanges,
1126 }),
1127 Layer.succeed(ServerSettings.ServerSettingsService, {
1128 ...settings,
1129 streamChanges: Stream.unwrap(settingsChanges),
1130 subscribeChanges: settingsChanges,
1131 }),
1132 );
1133 const server = yield* RpcServer.makeNoSerialization(
1134 RpcGroup.make(WsSubscribeServerConfigRpc),
1135 {
1136 ...WS_RPC_SERVER_OPTIONS,
1137 onFromServer: (response) =>
1138 response._tag === "Chunk"
1139 ? Effect.forEach(response.values, (event) => Queue.offer(responses, event), {
1140 discard: true,
1141 })
1142 : Effect.void,
1143 },
1144 ).pipe(
1145 Effect.provide(
1146 layerWsRpc(
1147 {
1148 sessionId: AuthSessionId.make("config-test"),
1149 subject: "config-test",
1150 method: "browser-session-cookie",
1151 scopes: [],
1152 },
1153 {},
1154 yield* ServerBrowser.ServerBrowser,
1155 () => Effect.void,
1156 { secretReferences: true },
1157 ).pipe(Layer.provide(configRpcServices)),
1158 ),
1159 );
1160 const requestId = RpcMessage.RequestId("config");
1161 const acknowledge = server.write(0, { _tag: "Ack", requestId });
1162 yield* server.write(0, {
1163 _tag: "Request",
1164 id: requestId,
1165 tag: WS_METHODS.subscribeServerConfig,
1166 payload: {},
1167 headers: Headers.empty,
1168 });
1169 yield* Deferred.await(discoveryStarted);
1170 assert.isTrue(yield* Deferred.isDone(remoteDiscoveryStarted));
1171
1172 const duringDiscovery = yield* settings.updateSettings({ defaultAutoPull: true });
1173 yield* Deferred.succeed(finishDiscovery, undefined);
1174 const snapshot = yield* Queue.take(responses);
1175 assert.equal(snapshot.type, "snapshot");
1176 if (snapshot.type !== "snapshot") return yield* Effect.die("Missing initial snapshot");
1177 assert.deepEqual(
1178 snapshot.config.remoteOpenTargets,
1179 discovery === "cached" || direct ? targets : [],
1180 );
1181 assert.deepEqual(
1182 snapshot.config.directEndpoints,
1183 discovery === "direct-cached" ? endpoints : bound,
1184 );
1185 assert.isFalse(snapshot.config.settings.defaultAutoPull);
1186 assert.deepEqual(snapshot.config.keybindings, initialKeybindings);
1187 const duringAck = yield* keybindings.upsertKeybindingRule({
1188 key: "mod+alt+y",
1189 command: "terminal.toggle",
1190 });
1191 yield* acknowledge;
1192 yield* Deferred.await(keybindingsSubscribed);
1193 yield* Deferred.await(settingsSubscribed);
1194
1195 // Later updates expose a dropped buffered event as a value mismatch, not a timeout.
1196 const latestSettings = yield* settings.updateSettings({ enableProviderUpdateChecks: false });
1197 const latestKeybindings = yield* keybindings.upsertKeybindingRule({
1198 key: "mod+alt+z",
1199 command: "terminal.split",
1200 });
1201 const expectedSettings = [duringDiscovery, latestSettings].map((value) =>
1202 ServerSettings.redactServerSettingsForClient(value, { secretReferences: true }),
1203 );
1204 const expectedKeybindings = [duringAck.keybindings, latestKeybindings.keybindings];
1205 // The two sources can interleave, but each must retain its own publication order.
1206 for (let i = 0; i < 4; i++) {
1207 const event = yield* Queue.take(responses);
1208 if (event.type === "settingsUpdated") {
1209 assert.deepEqual(event.payload.settings, expectedSettings.shift());
1210 } else {
1211 assert.equal(event.type, "keybindingsUpdated");
1212 if (event.type !== "keybindingsUpdated")
1213 return yield* Effect.die("Unexpected config event");
1214 assert.deepEqual(event.payload.keybindings, expectedKeybindings.shift());
1215 assert.deepEqual(event.payload.issues, []);
1216 }
1217 yield* acknowledge;
1218 }
1219 assert.isEmpty(expectedSettings);
1220 assert.isEmpty(expectedKeybindings);
1221 if (discovery === "pending") {
1222 yield* Deferred.await(remoteDiscoveryStarted);
1223 yield* Deferred.succeed(finishRemoteDiscovery, undefined);
1224 const resolved = yield* Queue.take(responses);
1225 assert.equal(resolved.type, "snapshot");
1226 if (resolved.type !== "snapshot") return yield* Effect.die("Missing remote targets");
1227 assert.deepEqual(resolved.config.remoteOpenTargets, targets);
1228 assert.deepEqual(
1229 resolved.config.settings,
1230 ServerSettings.redactServerSettingsForClient(latestSettings, { secretReferences: true }),
1231 );
1232 assert.deepEqual(resolved.config.keybindings, latestKeybindings.keybindings);
1233 yield* acknowledge;
1234 }
1235 if (direct) {
1236 yield* Deferred.await(directStarted);
1237 if (discovery === "direct-pending") {
1238 yield* Deferred.succeed(finishDirect, undefined);
1239 const resolved = yield* Queue.take(responses);
1240 assert.equal(resolved.type, "snapshot");
1241 if (resolved.type !== "snapshot") return yield* Effect.die("Missing direct endpoints");
1242 assert.deepEqual(resolved.config.directEndpoints, endpoints);
1243 assert.deepEqual(
1244 resolved.config.settings,
1245 ServerSettings.redactServerSettingsForClient(latestSettings, {
1246 secretReferences: true,
1247 }),
1248 );
1249 assert.deepEqual(resolved.config.keybindings, latestKeybindings.keybindings);
1250 yield* acknowledge;
1251 } else if (discovery === "direct-failed") {
1252 yield* Deferred.succeed(finishDirect, undefined);
1253 yield* Deferred.await(directStopped);
1254 yield* settings.updateSettings({ defaultAutoPull: false });
1255 const event = yield* Queue.take(responses);
1256 assert.equal(event.type, "settingsUpdated");
1257 yield* acknowledge;
1258 }
1259 }
1260 yield* server.write(0, { _tag: "Interrupt", requestId, interruptors: [] });
1261 if (direct) yield* Deferred.await(directStopped);
1262 }).pipe(
1263 Effect.provide(
1264 Layer.mergeAll(
1265 Layer.fresh(layerConfigSources),
1266 Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}),
1267 Layer.mock(ServerBrowser.ServerBrowser)({}),
1268 ),
1269 ),
1270 ),
1271 );
1272
1273 it.effect("access changes made while the snapshot loads reach the client after it", () =>
1274 Effect.gen(function* () {
1275 const pairingChanges = yield* PubSub.unbounded<PairingGrantStore.BootstrapCredentialChange>();
1276 const sessionChanges = yield* PubSub.unbounded<SessionStore.SessionCredentialChange>();
1277 const subscribed = yield* Queue.unbounded<void>();
1278 const subscribe = <A>(changes: PubSub.PubSub<A>) =>
1279 Stream.unwrap(
1280 PubSub.subscribe(changes).pipe(
1281 Effect.tap(() => Queue.offer(subscribed, undefined)),
1282 Effect.map(Stream.fromSubscription),
1283 ),
1284 );
1285 const revokedElsewhere = AuthSessionId.make("revoked-elsewhere");
1286 const responses = yield* Queue.unbounded<AuthAccessStreamEvent>();
1287 const server = yield* RpcServer.makeNoSerialization(WsRpcGroup, {
1288 ...WS_RPC_SERVER_OPTIONS,
1289 onFromServer: (response) =>
1290 response._tag === "Chunk"
1291 ? Effect.forEach(
1292 response.values,
1293 (event) => Queue.offer(responses, event as AuthAccessStreamEvent),
1294 {
1295 discard: true,
1296 },
1297 )
1298 : Effect.void,
1299 }).pipe(
1300 Effect.provide(
1301 layerWsRpc(
1302 {
1303 sessionId: AuthSessionId.make("current"),
1304 subject: "current",
1305 method: "browser-session-cookie",
1306 scopes: [],
1307 },
1308 {},
1309 yield* ServerBrowser.ServerBrowser,
1310 () => Effect.void,
1311 { secretReferences: true },
1312 ).pipe(
1313 Layer.merge(RpcAuthorization.layer([AuthAccessReadScope])),
1314 Layer.provide(
1315 Layer.mergeAll(
1316 layerUnusedConfigRpcServices,
1317 Layer.mock(ExternalLauncher.ExternalLauncher)({}),
1318 Layer.mock(ProviderRegistry.ProviderRegistry)({}),
1319 Layer.mock(UsageLimitSources.UsageLimitSources)({}),
1320 Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}),
1321 Layer.mock(DirectEndpoints.DirectEndpoints)({}),
1322 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
1323 namedProjectsRoot: "/unused",
1324 }),
1325 Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}),
1326 Layer.mock(ServerEnvironment.ServerEnvironment)({}),
1327 Layer.mock(EnvironmentAuth.EnvironmentAuth)({
1328 listPairingLinks: () => Effect.succeed([]),
1329 listConnectDevices: () => Effect.succeed([]),
1330 // Another client revokes a session after the snapshot read it.
1331 listClientSessions: () =>
1332 PubSub.publish(sessionChanges, {
1333 type: "clientRemoved",
1334 sessionId: revokedElsewhere,
1335 }).pipe(Effect.as([])),
1336 }),
1337 Layer.mock(PairingGrantStore.PairingGrantStore)({
1338 streamChanges: subscribe(pairingChanges),
1339 }),
1340 Layer.mock(SessionStore.SessionStore)({
1341 cookieName: "auth-access-test",
1342 legacyCookieName: undefined,
1343 streamChanges: subscribe(sessionChanges),
1344 }),
1345 ),
1346 ),
1347 ),
1348 ),
1349 );
1350 const requestId = RpcMessage.RequestId("auth-access");
1351 yield* server.write(0, {
1352 _tag: "Request",
1353 id: requestId,
1354 tag: WS_METHODS.subscribeAuthAccess,
1355 payload: {},
1356 headers: Headers.empty,
1357 });
1358 const snapshot = yield* Queue.take(responses);
1359 assert.equal(snapshot.type, "snapshot");
1360 yield* server.write(0, { _tag: "Ack", requestId });
1361 yield* Queue.take(subscribed);
1362 yield* Queue.take(subscribed);
1363
1364 // A later change arrives either way, so a dropped revocation fails as a mismatch.
1365 yield* PubSub.publish(pairingChanges, { type: "pairingLinkRemoved", id: "later" });
1366 const next = yield* Queue.take(responses);
1367 assert.deepEqual(next, {
1368 version: 1,
1369 revision: 2,
1370 type: "clientRemoved",
1371 payload: { sessionId: revokedElsewhere },
1372 });
1373 yield* server.write(0, { _tag: "Ack", requestId });
1374 assert.equal((yield* Queue.take(responses)).type, "pairingLinkRemoved");
1375 yield* server.write(0, { _tag: "Ack", requestId });
1376
1377 // Device trust has no incremental event, so a change re-sends the whole snapshot.
1378 yield* PubSub.publish(pairingChanges, { type: "connectDevicesChanged" });
1379 assert.deepEqual(yield* Queue.take(responses), {
1380 version: 1,
1381 revision: 4,
1382 type: "snapshot",
1383 payload: { pairingLinks: [], clientSessions: [], connectDevices: [] },
1384 });
1385 yield* server.write(0, { _tag: "Interrupt", requestId, interruptors: [] });
1386 }).pipe(
1387 Effect.provide(
1388 Layer.mergeAll(
1389 Layer.fresh(layerConfigSources),
1390 Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}),
1391 Layer.mock(ServerBrowser.ServerBrowser)({}),
1392 ),
1393 ),
1394 ),
1395 );
1396
1397 it.effect("on-demand clients get provider config without workspace snapshots", () =>
1398 Effect.gen(function* () {
1399 const instanceId = ProviderInstanceId.make("claudeAgent");
1400 const snapshotFor = (cwd: string, checkedAt: string) => ({
1401 cwd,
1402 checkedAt,
1403 slashCommands: [{ name: `${cwd.slice(1)}-command` }],
1404 skills: [],
1405 });
1406 const provider: ServerProvider = {
1407 instanceId,
1408 driver: ProviderDriverKind.make("claudeAgent"),
1409 enabled: true,
1410 installed: true,
1411 version: "1.0.0",
1412 status: "ready",
1413 auth: { status: "authenticated" },
1414 checkedAt: "2026-10-25T00:00:00.000Z",
1415 models: [],
1416 slashCommands: [{ name: "machine-command", description: "A machine command" }],
1417 skills: [
1418 {
1419 name: "machine-skill",
1420 description: "Machine skill",
1421 path: "/skills/machine-skill",
1422 enabled: true,
1423 },
1424 ],
1425 workspaceSnapshots: [
1426 snapshotFor("/a", "2026-10-25T00:00:00.000Z"),
1427 snapshotFor("/b", "2026-10-25T00:00:00.000Z"),
1428 ],
1429 };
1430 let scansCwd = true;
1431 let registryProviders: ReadonlyArray<ServerProvider> = [provider];
1432 const providerChanges = yield* Queue.unbounded<ReadonlyArray<ServerProvider>>();
1433 const pulled = yield* Queue.unbounded<void>();
1434 const responses = yield* Queue.unbounded<unknown>();
1435 const configRpcServices = Layer.mergeAll(
1436 layerUnusedConfigRpcServices,
1437 Layer.mock(ExternalLauncher.ExternalLauncher)({
1438 resolveAvailableEditors: () => Effect.succeed([]),
1439 resolveFileManagerRevealKind: () => Effect.undefined,
1440 }),
1441 Layer.mock(ProviderRegistry.ProviderRegistry)({
1442 getProviders: Effect.sync(() => registryProviders),
1443 streamChanges: Stream.fromQueue(providerChanges).pipe(
1444 Stream.tap(() => Queue.offer(pulled, undefined)),
1445 ),
1446 refresh: () => Effect.sync(() => registryProviders),
1447 refreshWorkspaceSnapshot: () => Effect.sync(() => registryProviders),
1448 }),
1449 Layer.mock(ProjectService.ProjectService)({
1450 workspaceScanDirectory: (cwd) => Effect.succeed(cwd),
1451 }),
1452 Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({
1453 listInstances: Effect.sync(() => [
1454 (scansCwd
1455 ? { instanceId, snapshotForCwd: () => Effect.die("unused") }
1456 : { instanceId }) as never,
1457 ]),
1458 getInstance: () =>
1459 Effect.sync(
1460 () =>
1461 (scansCwd
1462 ? { instanceId, snapshotForCwd: () => Effect.die("unused") }
1463 : { instanceId }) as never,
1464 ),
1465 }),
1466 Layer.mock(UsageLimitSources.UsageLimitSources)({
1467 current: Effect.succeed([]),
1468 streamChanges: Stream.make([]),
1469 refresh: Effect.void,
1470 }),
1471 Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({
1472 resolveTargets: () => Effect.succeed([]),
1473 }),
1474 Layer.mock(DirectEndpoints.DirectEndpoints)({
1475 resolve: () => Effect.succeed([]),
1476 resolveAvailable: () => Effect.succeed([]),
1477 }),
1478 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
1479 scratchRoot: Effect.succeedNone,
1480 namedProjectsRoot: process.cwd(),
1481 }),
1482 Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}),
1483 Layer.mock(ServerEnvironment.ServerEnvironment)({
1484 getDescriptor: Effect.succeed({
1485 environmentId: EnvironmentId.make("config-test"),
1486 label: "Config test",
1487 platform: { os: "linux", arch: "x64" },
1488 serverVersion: "0.0.0",
1489 capabilities: { repositoryIdentity: false },
1490 }),
1491 }),
1492 Layer.mock(EnvironmentAuth.EnvironmentAuth)({
1493 getDescriptor: () =>
1494 Effect.succeed({
1495 policy: "loopback-browser",
1496 bootstrapMethods: [],
1497 sessionMethods: ["browser-session-cookie"],
1498 sessionCookieName: "config-test-session",
1499 }),
1500 }),
1501 );
1502 const server = yield* RpcServer.makeNoSerialization(
1503 RpcGroup.make(WsSubscribeServerConfigRpc, WsServerRefreshProvidersRpc),
1504 {
1505 ...WS_RPC_SERVER_OPTIONS,
1506 onFromServer: (response) =>
1507 response._tag === "Chunk"
1508 ? Effect.forEach(response.values, (value) => Queue.offer(responses, value), {
1509 discard: true,
1510 })
1511 : response._tag === "Exit" && response.exit._tag === "Success"
1512 ? Queue.offer(responses, response.exit.value)
1513 : Effect.void,
1514 },
1515 ).pipe(
1516 Effect.provide(
1517 layerWsRpc(
1518 {
1519 sessionId: AuthSessionId.make("config-test"),
1520 subject: "config-test",
1521 method: "browser-session-cookie",
1522 scopes: [],
1523 },
1524 {},
1525 yield* ServerBrowser.ServerBrowser,
1526 () => Effect.void,
1527 { secretReferences: true },
1528 ).pipe(Layer.provide(configRpcServices)),
1529 ),
1530 );
1531 const configRequest = RpcMessage.RequestId("config");
1532 yield* server.write(0, {
1533 _tag: "Request",
1534 id: configRequest,
1535 tag: WS_METHODS.subscribeServerConfig,
1536 payload: { workspaceSnapshotsOnDemand: true, providerCatalogsOnDemand: true },
1537 headers: Headers.empty,
1538 });
1539 const snapshot = (yield* Queue.take(responses)) as ServerConfigStreamEvent;
1540 if (snapshot.type !== "snapshot") return yield* Effect.die("Missing initial snapshot");
1541 assert.isUndefined(snapshot.config.providers[0]?.workspaceSnapshots);
1542 // The cwd snapshot the client fetches carries the catalog, so only command names are sent.
1543 assert.deepEqual(snapshot.config.providers[0]?.slashCommands, [{ name: "machine-command" }]);
1544 assert.deepEqual(snapshot.config.providers[0]?.skills, [
1545 { name: "machine-skill", path: "/skills/machine-skill", enabled: true },
1546 ]);
1547 yield* server.write(0, { _tag: "Ack", requestId: configRequest });
1548
1549 // A rescan that only touches a snapshot sends nothing; the next real change does.
1550 yield* Queue.offer(providerChanges, [
1551 { ...provider, workspaceSnapshots: [snapshotFor("/a", "2026-10-25T00:05:00.000Z")] },
1552 ]);
1553 yield* Queue.take(pulled);
1554 yield* TestClock.adjust("1 second");
1555 // Late /usage-limits discovery still reaches the client, so it refetches its cwd snapshot.
1556 yield* Queue.offer(providerChanges, [
1557 {
1558 ...provider,
1559 status: "warning",
1560 slashCommands: [...provider.slashCommands, USAGE_LIMITS_COMMAND],
1561 },
1562 ]);
1563 yield* Queue.take(pulled);
1564 yield* TestClock.adjust("1 second");
1565 const update = (yield* Queue.take(responses)) as ServerConfigStreamEvent;
1566 if (update.type !== "providerStatuses") return yield* Effect.die("Expected provider update");
1567 assert.equal(update.payload.providers[0]?.status, "warning");
1568 assert.isUndefined(update.payload.providers[0]?.workspaceSnapshots);
1569 assert.deepEqual(update.payload.providers[0]?.slashCommands, [
1570 { name: "machine-command" },
1571 { name: USAGE_LIMITS_COMMAND.name },
1572 ]);
1573 yield* server.write(0, { _tag: "Ack", requestId: configRequest });
1574 // A replacement that cannot scan a cwd sends its full machine catalog.
1575 scansCwd = false;
1576 yield* Queue.offer(providerChanges, [{ ...provider, status: "warning" }]);
1577 yield* Queue.take(pulled);
1578 yield* TestClock.adjust("1 second");
1579 const replaced = (yield* Queue.take(responses)) as ServerConfigStreamEvent;
1580 if (replaced.type !== "providerStatuses") return yield* Effect.die("Expected provider update");
1581 assert.deepEqual(replaced.payload.providers[0]?.slashCommands, provider.slashCommands);
1582 assert.deepEqual(replaced.payload.providers[0]?.skills, provider.skills);
1583
1584 yield* server.write(0, {
1585 _tag: "Request",
1586 id: RpcMessage.RequestId("refresh"),
1587 tag: WS_METHODS.serverRefreshProviders,
1588 payload: { instanceId, cwd: "/b", workspaceSnapshotsOnDemand: true },
1589 headers: Headers.empty,
1590 });
1591 const refreshed = (yield* Queue.take(responses)) as {
1592 readonly providers: ReadonlyArray<ServerProvider>;
1593 };
1594 assert.deepEqual(
1595 refreshed.providers.map((entry) => [entry.workspaceSnapshots, entry.slashCommands]),
1596 [[[snapshotFor("/b", "2026-10-25T00:00:00.000Z")], []]],
1597 );
1598 // A failed scan still gives a client without the machine catalog its commands.
1599 scansCwd = true;
1600 yield* server.write(0, {
1601 _tag: "Request",
1602 id: RpcMessage.RequestId("refresh-failed-scan"),
1603 tag: WS_METHODS.serverRefreshProviders,
1604 payload: {
1605 instanceId,
1606 cwd: "/c",
1607 workspaceSnapshotsOnDemand: true,
1608 providerCatalogsOnDemand: true,
1609 },
1610 headers: Headers.empty,
1611 });
1612 const fallback = (yield* Queue.take(responses)) as {
1613 readonly providers: ReadonlyArray<ServerProvider>;
1614 };
1615 assert.deepEqual(fallback.providers[0]?.workspaceSnapshots, [
1616 {
1617 cwd: "/c",
1618 checkedAt: provider.checkedAt,
1619 slashCommands: provider.slashCommands,
1620 slashCommandsPending: true,
1621 skills: provider.skills,
1622 },
1623 ]);
1624 yield* server.write(0, { _tag: "Interrupt", requestId: configRequest, interruptors: [] });
1625
1626 // A client that takes digests and deltas, against a catalog of over 200 KB.
1627 const heavy: ServerProvider = {
1628 ...provider,
1629 slashCommands: Array.from({ length: 250 }, (_, index) => ({
1630 name: `command-${index}`,
1631 description: "d".repeat(400),
1632 })),
1633 skills: Array.from({ length: 200 }, (_, index) => ({
1634 name: `skill-${index}`,
1635 description: "d".repeat(500),
1636 path: `/home/user/.claude/skills/skill-${index}/SKILL.md`,
1637 enabled: true,
1638 })),
1639 };
1640 registryProviders = [heavy];
1641 const lightRequest = RpcMessage.RequestId("light-config");
1642 yield* server.write(0, {
1643 _tag: "Request",
1644 id: lightRequest,
1645 tag: WS_METHODS.subscribeServerConfig,
1646 payload: {
1647 workspaceSnapshotsOnDemand: true,
1648 providerCatalogsOnDemand: true,
1649 providerCatalogDigests: true,
1650 providerStatusDeltas: true,
1651 },
1652 headers: Headers.empty,
1653 });
1654 const light = (yield* Queue.take(responses)) as ServerConfigStreamEvent;
1655 if (light.type !== "snapshot") return yield* Effect.die("Missing light snapshot");
1656 const digest = light.config.providers[0]?.catalogDigest;
1657 assert.isString(digest);
1658 assert.deepEqual(
1659 [light.config.providers[0]?.slashCommands, light.config.providers[0]?.skills],
1660 [[], []],
1661 );
1662 // Budget for the first config a phone decodes: the catalog stays out of it.
1663 assert.isBelow(JSON.stringify(light.config.providers).length, 1024);
1664 yield* server.write(0, { _tag: "Ack", requestId: lightRequest });
1665
1666 // A health check sends the provider without the lists the client already holds.
1667 yield* Queue.offer(providerChanges, [{ ...heavy, checkedAt: "2026-10-25T00:10:00.000Z" }]);
1668 yield* Queue.take(pulled);
1669 yield* TestClock.adjust("1 second");
1670 const delta = (yield* Queue.take(responses)) as ServerConfigStreamEvent;
1671 if (delta.type !== "providerStatusDeltas") return yield* Effect.die("Expected provider deltas");
1672 assert.deepEqual(
1673 delta.payload.providers.map((entry) => [
1674 entry.checkedAt,
1675 entry.catalogDigest,
1676 entry.models,
1677 entry.slashCommands,
1678 entry.skills,
1679 ]),
1680 [["2026-10-25T00:10:00.000Z", digest, undefined, undefined, undefined]],
1681 );
1682 yield* server.write(0, { _tag: "Ack", requestId: lightRequest });
1683
1684 // A changed description changes the digest, so the client loads the lists again.
1685 yield* Queue.offer(providerChanges, [
1686 {
1687 ...heavy,
1688 checkedAt: "2026-10-25T00:20:00.000Z",
1689 skills: heavy.skills.map((skill, index) =>
1690 index === 0 ? { ...skill, description: "changed" } : skill,
1691 ),
1692 },
1693 ]);
1694 yield* Queue.take(pulled);
1695 yield* TestClock.adjust("1 second");
1696 const redescribed = (yield* Queue.take(responses)) as ServerConfigStreamEvent;
1697 if (redescribed.type !== "providerStatusDeltas") {
1698 return yield* Effect.die("Expected provider deltas");
1699 }
1700 assert.notEqual(redescribed.payload.providers[0]?.catalogDigest, digest);
1701 yield* server.write(0, { _tag: "Ack", requestId: lightRequest });
1702
1703 // A caller that only waits for a machine refresh gets no provider list back.
1704 yield* server.write(0, {
1705 _tag: "Request",
1706 id: RpcMessage.RequestId("refresh-omitted"),
1707 tag: WS_METHODS.serverRefreshProviders,
1708 payload: { workspaceSnapshotsOnDemand: true, omitProviders: true },
1709 headers: Headers.empty,
1710 });
1711 assert.deepEqual(yield* Queue.take(responses), { providers: [] });
1712
1713 // The cwd snapshot brings the lists the digest stands for, under the same digest.
1714 yield* server.write(0, {
1715 _tag: "Request",
1716 id: RpcMessage.RequestId("refresh-machine-catalog"),
1717 tag: WS_METHODS.serverRefreshProviders,
1718 payload: {
1719 instanceId,
1720 cwd: "/b",
1721 workspaceSnapshotsOnDemand: true,
1722 providerCatalogsOnDemand: true,
1723 omitProviders: true,
1724 machineCatalog: true,
1725 },
1726 headers: Headers.empty,
1727 });
1728 const loaded = (yield* Queue.take(responses)) as {
1729 readonly providers: ReadonlyArray<ServerProvider>;
1730 };
1731 assert.equal(loaded.providers[0]?.catalogDigest, digest);
1732 assert.deepEqual(loaded.providers[0]?.slashCommands[0], { name: "command-0" });
1733 assert.deepEqual(loaded.providers[0]?.skills[0], {
1734 name: "skill-0",
1735 path: "/home/user/.claude/skills/skill-0/SKILL.md",
1736 enabled: true,
1737 });
1738 assert.lengthOf(loaded.providers[0]?.workspaceSnapshots ?? [], 1);
1739 yield* server.write(0, { _tag: "Interrupt", requestId: lightRequest, interruptors: [] });
1740 }).pipe(
1741 Effect.provide(
1742 Layer.mergeAll(
1743 Layer.fresh(layerConfigSources),
1744 Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}),
1745 Layer.mock(ServerBrowser.ServerBrowser)({}),
1746 ),
1747 ),
1748 ),
1749 );
1750
1751 it.effect("a missing thread worktree gets its project's skills in the cwd snapshot", () =>
1752 Effect.gen(function* () {
1753 const fileSystem = yield* FileSystem.FileSystem;
1754 const path = yield* Path.Path;
1755 const serverConfig = yield* ServerConfigModule.ServerConfig;
1756 const instanceId = ProviderInstanceId.make("claudeAgent");
1757 const projectId = ProjectId.make("project:skills");
1758 const workspaceRoot = yield* fileSystem.makeTempDirectoryScoped({
1759 prefix: "t3-missing-worktree-project-",
1760 });
1761 const skillPath = path.join(workspaceRoot, ".claude", "skills", "finalize", "SKILL.md");
1762 yield* fileSystem.makeDirectory(path.dirname(skillPath), { recursive: true });
1763 yield* fileSystem.writeFileString(skillPath, "---\nname: finalize\n---\n");
1764 // Removed with `git worktree remove`; only the next turn start recreates it.
1765 const worktreePath = path.join(serverConfig.worktreesDir, "proj", "t3-6f94fb95");
1766 const thread = {
1767 id: ThreadId.make("thread:worktree"),
1768 projectId,
1769 archivedAt: null,
1770 worktreePath,
1771 branch: "t3/reply-ok",
1772 } as unknown as OrchestrationV2ThreadShell;
1773 const project = {
1774 id: projectId,
1775 title: "proj",
1776 workspaceRoot,
1777 defaultModelSelection: null,
1778 scripts: [],
1779 createdAt: "2026-11-07T00:00:00.000Z",
1780 updatedAt: "2026-11-07T00:00:00.000Z",
1781 } satisfies OrchestrationProjectShell;
1782 const provider: ServerProvider = {
1783 instanceId,
1784 driver: ProviderDriverKind.make("claudeAgent"),
1785 enabled: true,
1786 installed: true,
1787 version: "1.0.0",
1788 status: "ready",
1789 auth: { status: "authenticated" },
1790 checkedAt: "2026-11-07T00:00:00.000Z",
1791 models: [],
1792 slashCommands: [],
1793 skills: [],
1794 };
1795 // Like Claude's probe: project skills come from the scanned cwd, and a missing cwd is final.
1796 const scan = (cwd: string) =>
1797 fileSystem.exists(path.join(cwd, ".claude", "skills", "finalize", "SKILL.md")).pipe(
1798 Effect.orDie,
1799 Effect.map((found) => ({
1800 cwd,
1801 checkedAt: "2026-11-07T00:00:00.000Z",
1802 slashCommands: [],
1803 slashCommandsPending: false,
1804 skills: found
1805 ? [{ name: "finalize", path: path.join(cwd, ".claude/skills/finalize"), enabled: true }]
1806 : [],
1807 })),
1808 );
1809 const responses = yield* Queue.unbounded<unknown>();
1810 const services = Layer.mergeAll(
1811 layerUnusedConfigRpcServices,
1812 Layer.mock(ProviderRegistry.ProviderRegistry)({
1813 getProviders: Effect.succeed([provider]),
1814 refreshWorkspaceSnapshot: (input) =>
1815 Effect.map(scan(input.scanCwd ?? input.cwd), (snapshot) => [
1816 { ...provider, workspaceSnapshots: [{ ...snapshot, cwd: input.cwd }] },
1817 ]),
1818 }),
1819 Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({
1820 listInstances: Effect.succeed([]),
1821 getInstance: () => Effect.succeed({ instanceId, snapshotForCwd: scan } as never),
1822 }),
1823 Layer.effect(ProjectService.ProjectService, ProjectService.make).pipe(
1824 Layer.provide(
1825 Layer.mergeAll(
1826 Layer.mock(ProjectionStore.ProjectionStoreV2)({
1827 readShellSnapshot: (options) =>
1828 Effect.succeed(
1829 Effect.succeed({
1830 schemaVersion: 1,
1831 snapshotSequence: 0,
1832 threads: [thread].filter(
1833 (candidate) =>
1834 options?.worktreePath === undefined ||
1835 candidate.worktreePath === options.worktreePath,
1836 ),
1837 archivedThreads: [],
1838 } as never),
1839 ),
1840 }),
1841 Layer.mock(ProjectStore.ProjectStoreV2)({
1842 get: () => Effect.succeedSome(project as never),
1843 }),
1844 Layer.mock(ProjectEnrichment.ProjectEnrichmentService)({}),
1845 Layer.mock(WorkspacePaths.WorkspacePaths)({}),
1846 Layer.mock(EventSink.EventSinkV2)({}),
1847 IdAllocator.layer,
1848 Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({}),
1849 Layer.mock(ThreadCommandExecutor.ThreadCommandExecutor)({}),
1850 ),
1851 ),
1852 ),
1853 Layer.mock(UsageLimitSources.UsageLimitSources)({ current: Effect.succeed([]) }),
1854 Layer.mock(ExternalLauncher.ExternalLauncher)({}),
1855 Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}),
1856 Layer.mock(DirectEndpoints.DirectEndpoints)({}),
1857 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
1858 scratchRoot: Effect.succeedNone,
1859 namedProjectsRoot: process.cwd(),
1860 }),
1861 Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}),
1862 Layer.mock(ServerEnvironment.ServerEnvironment)({}),
1863 Layer.mock(EnvironmentAuth.EnvironmentAuth)({}),
1864 );
1865 const server = yield* RpcServer.makeNoSerialization(
1866 RpcGroup.make(WsServerRefreshProvidersRpc),
1867 {
1868 ...WS_RPC_SERVER_OPTIONS,
1869 onFromServer: (response) =>
1870 response._tag === "Exit" && response.exit._tag === "Success"
1871 ? Queue.offer(responses, response.exit.value)
1872 : response._tag === "Exit"
1873 ? Queue.offer(responses, response.exit)
1874 : Effect.void,
1875 },
1876 ).pipe(
1877 Effect.provide(
1878 layerWsRpc(
1879 {
1880 sessionId: AuthSessionId.make("worktree-skills-test"),
1881 subject: "worktree-skills-test",
1882 method: "browser-session-cookie",
1883 scopes: [],
1884 },
1885 {},
1886 yield* ServerBrowser.ServerBrowser,
1887 () => Effect.void,
1888 { secretReferences: true },
1889 ).pipe(Layer.provide(services)),
1890 ),
1891 );
1892
1893 yield* server.write(0, {
1894 _tag: "Request",
1895 id: RpcMessage.RequestId("refresh"),
1896 tag: WS_METHODS.serverRefreshProviders,
1897 payload: { instanceId, cwd: worktreePath, workspaceSnapshotsOnDemand: true },
1898 headers: Headers.empty,
1899 });
1900 const refreshed = (yield* Queue.take(responses)) as {
1901 readonly providers: ReadonlyArray<ServerProvider>;
1902 };
1903 const snapshot = refreshed.providers[0]?.workspaceSnapshots?.find(
1904 (candidate) => candidate.cwd === worktreePath,
1905 );
1906 assert.deepEqual(
1907 snapshot?.skills?.map((skill) => skill.name),
1908 ["finalize"],
1909 "the thread's removed worktree should list the project's skills",
1910 );
1911 }).pipe(
1912 Effect.provide(
1913 Layer.mergeAll(
1914 Layer.fresh(layerConfigSources),
1915 Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}),
1916 Layer.mock(ServerBrowser.ServerBrowser)({}),
1917 ),
1918 ),
1919 ),
1920 );
1921
1922 it.effect("a git action that fails partway still refreshes the repository status", () =>
1923 Effect.gen(function* () {
1924 const failure = new GitManagerError({ operation: "test", cwd: "/repo", detail: "push failed" });
1925 const refreshFailure = new GitManagerError({
1926 operation: "refresh",
1927 cwd: "/repo",
1928 detail: "refresh failed",
1929 });
1930 const refreshed = yield* Deferred.make<string>();
1931 const exits = yield* Queue.unbounded<Exit.Exit<unknown, unknown>>();
1932 const services = Layer.mergeAll(
1933 layerUnusedConfigRpcServices,
1934 Layer.mock(GitWorkflowService.GitWorkflowService)({
1935 runStackedAction: () => Effect.fail(failure),
1936 }),
1937 Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
1938 refreshStatus: (cwd) =>
1939 Deferred.succeed(refreshed, cwd).pipe(Effect.andThen(Effect.fail(refreshFailure))),
1940 }),
1941 Layer.mock(ExternalLauncher.ExternalLauncher)({}),
1942 Layer.mock(ProviderRegistry.ProviderRegistry)({}),
1943 Layer.mock(UsageLimitSources.UsageLimitSources)({}),
1944 Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}),
1945 Layer.mock(DirectEndpoints.DirectEndpoints)({}),
1946 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }),
1947 Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}),
1948 Layer.mock(ServerEnvironment.ServerEnvironment)({}),
1949 Layer.mock(EnvironmentAuth.EnvironmentAuth)({}),
1950 );
1951 const server = yield* RpcServer.makeNoSerialization(WsRpcGroup, {
1952 ...WS_RPC_SERVER_OPTIONS,
1953 onFromServer: (response) =>
1954 response._tag === "Exit" ? Queue.offer(exits, response.exit) : Effect.void,
1955 }).pipe(
1956 Effect.provide(
1957 layerWsRpc(
1958 {
1959 sessionId: AuthSessionId.make("git-test"),
1960 subject: "git-test",
1961 method: "browser-session-cookie",
1962 scopes: [AuthSourceControlWriteScope],
1963 },
1964 {},
1965 yield* ServerBrowser.ServerBrowser,
1966 () => Effect.void,
1967 { secretReferences: true },
1968 ).pipe(
1969 Layer.provide(services),
1970 Layer.merge(RpcAuthorization.layer([AuthSourceControlWriteScope])),
1971 ),
1972 ),
1973 );
1974 yield* server.write(0, {
1975 _tag: "Request",
1976 id: RpcMessage.RequestId("git"),
1977 tag: WS_METHODS.gitRunStackedAction,
1978 payload: { actionId: "action", cwd: "/repo", action: "commit_push" },
1979 headers: Headers.empty,
1980 });
1981 const exit = yield* Queue.take(exits);
1982 assert.deepEqual(Exit.isFailure(exit) ? Cause.squash(exit.cause) : exit, failure);
1983 assert.equal(yield* Deferred.await(refreshed), "/repo");
1984 }).pipe(
1985 Effect.provide(
1986 Layer.mergeAll(
1987 Layer.fresh(layerConfigSources),
1988 Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}),
1989 Layer.mock(ServerBrowser.ServerBrowser)({}),
1990 ),
1991 ),
1992 ),
1993 );
1994
1995 it.effect("a publish whose push fails still refreshes the new remote", () =>
1996 Effect.gen(function* () {
1997 const refreshes = yield* Queue.unbounded<string>();
1998 const exits = yield* Queue.unbounded<string>();
1999 const services = Layer.mergeAll(
2000 layerUnusedConfigRpcServices,
2001 Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
2002 publishRepository: (input) =>
2003 Effect.fail(
2004 new SourceControlRepositoryError({
2005 provider: input.provider,
2006 operation: "publishRepository",
2007 detail: 'Created owner/repo and added it as remote "origin", but the push failed.',
2008 }),
2009 ),
2010 }),
2011 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
2012 resolve: (cwd, options) =>
2013 Queue.offer(refreshes, `identity ${cwd} refresh=${options?.refresh === true}`).pipe(
2014 Effect.as(null),
2015 ),
2016 }),
2017 Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
2018 refreshStatus: (cwd) =>
2019 Queue.offer(refreshes, `status ${cwd}`).pipe(Effect.andThen(Effect.die("unused"))),
2020 }),
2021 Layer.mock(ExternalLauncher.ExternalLauncher)({}),
2022 Layer.mock(ProviderRegistry.ProviderRegistry)({}),
2023 Layer.mock(UsageLimitSources.UsageLimitSources)({}),
2024 Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}),
2025 Layer.mock(DirectEndpoints.DirectEndpoints)({}),
2026 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }),
2027 Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}),
2028 Layer.mock(ServerEnvironment.ServerEnvironment)({}),
2029 Layer.mock(EnvironmentAuth.EnvironmentAuth)({}),
2030 );
2031 const server = yield* RpcServer.makeNoSerialization(WsRpcGroup, {
2032 ...WS_RPC_SERVER_OPTIONS,
2033 onFromServer: (response) =>
2034 response._tag === "Exit" ? Queue.offer(exits, response.exit._tag) : Effect.void,
2035 }).pipe(
2036 Effect.provide(
2037 layerWsRpc(
2038 {
2039 sessionId: AuthSessionId.make("publish-test"),
2040 subject: "publish-test",
2041 method: "browser-session-cookie",
2042 scopes: [AuthSourceControlWriteScope],
2043 },
2044 {},
2045 yield* ServerBrowser.ServerBrowser,
2046 () => Effect.void,
2047 { secretReferences: true },
2048 ).pipe(
2049 Layer.provide(services),
2050 Layer.merge(RpcAuthorization.layer([AuthSourceControlWriteScope])),
2051 ),
2052 ),
2053 );
2054 yield* server.write(0, {
2055 _tag: "Request",
2056 id: RpcMessage.RequestId("publish"),
2057 tag: WS_METHODS.sourceControlPublishRepository,
2058 payload: {
2059 cwd: "/repo",
2060 provider: "github",
2061 repository: "owner/repo",
2062 visibility: "private",
2063 },
2064 headers: Headers.empty,
2065 });
2066 assert.equal(yield* Queue.take(exits), "Failure");
2067 assert.deepEqual(
2068 [yield* Queue.take(refreshes), yield* Queue.take(refreshes)],
2069 ["identity /repo refresh=true", "status /repo"],
2070 );
2071 }).pipe(
2072 Effect.provide(
2073 Layer.mergeAll(
2074 Layer.fresh(layerConfigSources),
2075 Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}),
2076 Layer.mock(ServerBrowser.ServerBrowser)({}),
2077 ),
2078 ),
2079 ),
2080 );
2081
2082 // Pruned history cannot be replayed: a cursor below the boundary must resync from a snapshot,
2083 // or, for a shell client that loads it over HTTP, be told to without the server building one.
2084 it.effect.each([
2085 { scope: "thread", httpSnapshotFallback: false },
2086 { scope: "shell", httpSnapshotFallback: false },
2087 { scope: "shell", httpSnapshotFallback: true },
2088 ] as const)(
2089 "$scope resume from a cursor below the pruned boundary (HTTP fallback: $httpSnapshotFallback)",
2090 ({ scope, httpSnapshotFallback }) =>
2091 Effect.gen(function* () {
2092 const sql = yield* SqlClient.SqlClient;
2093 const now = "2026-10-13T00:00:00.000Z";
2094 const threadId = ThreadId.make("thread:pruned");
2095 const insert = (version: number) => sql<{ sequence: number }>`
2096 INSERT INTO orchestration_events (
2097 event_id, aggregate_kind, stream_id, stream_version, event_type,
2098 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
2099 ) VALUES (
2100 ${`pruned:${version}`}, 'thread', ${threadId}, ${version}, 'provider-session.detached',
2101 ${now}, 'server', ${JSON.stringify({ providerSessionId: "session:pruned", detachedAt: now })},
2102 '{}', 2
2103 ) RETURNING sequence
2104 `;
2105 const [first] = yield* insert(0);
2106 const [second] = yield* insert(1);
2107 yield* insert(2);
2108 yield* sql`
2109 INSERT INTO orchestration_v2_projection_metadata (
2110 projection_name, schema_version, last_sequence, updated_at
2111 ) VALUES (${OrchestrationEventStore.EVENT_LOG_PRUNED_THROUGH}, 2, ${second!.sequence}, ${now})
2112 `;
2113 const subscription = Effect.gen(function* () {
2114 const items: ReadonlyArray<unknown> =
2115 scope === "thread"
2116 ? yield* Stream.runCollect(
2117 yield* subscribeOrchestrationV2Thread({ threadId, afterSequence: first!.sequence }),
2118 )
2119 : yield* Stream.runCollect(
2120 yield* subscribeOrchestrationV2Shell({
2121 afterSequence: first!.sequence,
2122 ...(httpSnapshotFallback ? { httpSnapshotFallback: true as const } : {}),
2123 }),
2124 );
2125 return items;
2126 });
2127 const exit = yield* subscription.pipe(
2128 Effect.provideService(ThreadManagement.ThreadManagementService, {
2129 ensureLegacyTranscript: () => Effect.void,
2130 getThreadSnapshot: () => Effect.die("snapshot"),
2131 listActiveShellIndex: () => Effect.die("snapshot"),
2132 readShellSnapshot: () => Effect.die("snapshot"),
2133 listActiveSubagentThreadIds: () => Effect.die("replay"),
2134 } as unknown as ThreadManagement.ThreadManagementService["Service"]),
2135 Effect.provideService(ProjectStore.ProjectStoreV2, {
2136 listShells: () => Effect.succeed([]),
2137 } as unknown as ProjectStore.ProjectStoreV2["Service"]),
2138 Effect.provideService(
2139 ProjectService.ProjectService,
2140 {} as ProjectService.ProjectService["Service"],
2141 ),
2142 Effect.provideService(ProjectEnrichment.ProjectEnrichmentService, {
2143 subscribeChanges: PubSub.subscribe(yield* PubSub.unbounded()),
2144 } as ProjectEnrichment.ProjectEnrichmentService["Service"]),
2145 Effect.exit,
2146 );
2147 assert.deepEqual(
2148 Exit.isFailure(exit) ? Cause.squash(exit.cause) : Array.from(exit.value),
2149 httpSnapshotFallback ? [{ kind: "snapshot-required" }] : "snapshot",
2150 );
2151 }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),
2152 );
2153
2154 // A prune pass can delete replayed rows after the boundary check; the read must not be trusted.
2155 it.effect.each(["thread", "shell"] as const)(
2156 "%s resume loads a snapshot when pruning advances during the replay read",
2157 (scope) =>
2158 Effect.gen(function* () {
2159 const sql = yield* SqlClient.SqlClient;
2160 const now = "2026-10-13T00:00:00.000Z";
2161 const threadId = ThreadId.make("thread:prune-race");
2162 const insert = (version: number) => sql<{ sequence: number }>`
2163 INSERT INTO orchestration_events (
2164 event_id, aggregate_kind, stream_id, stream_version, event_type,
2165 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
2166 ) VALUES (
2167 ${`prune-race:${version}`}, 'thread', ${threadId}, ${version}, 'provider-session.detached',
2168 ${now}, 'server', ${JSON.stringify({ providerSessionId: "session:race", detachedAt: now })},
2169 '{}', 2
2170 ) RETURNING sequence
2171 `;
2172 const [first] = yield* insert(0);
2173 const [second] = yield* insert(1);
2174 yield* insert(2);
2175
2176 const readStarted = yield* Deferred.make<void>();
2177 const releaseRead = yield* Deferred.make<void>();
2178 let gated = false;
2179 const gateReplayRead: Statement.Transformer = (statement) => {
2180 const [query] = statement.compile();
2181 // The paged replay read (readApplicationRows), not the stats or high-water queries.
2182 if (!gated && /^\s*SELECT\s+sequence,\s+event_id,/.test(query)) {
2183 gated = true;
2184 return Deferred.succeed(readStarted, undefined).pipe(
2185 Effect.andThen(Deferred.await(releaseRead)),
2186 Effect.as(statement),
2187 );
2188 }
2189 return Effect.succeed(statement);
2190 };
2191 const subscription = Effect.gen(function* () {
2192 const stream =
2193 scope === "thread"
2194 ? yield* subscribeOrchestrationV2Thread({ threadId, afterSequence: first!.sequence })
2195 : yield* subscribeOrchestrationV2Shell({ afterSequence: first!.sequence });
2196 return stream;
2197 }).pipe(
2198 Effect.provideService(Statement.CurrentTransformer, gateReplayRead),
2199 Effect.provideService(ThreadManagement.ThreadManagementService, {
2200 ensureLegacyTranscript: () => Effect.void,
2201 getThreadSnapshot: () => Effect.die("snapshot"),
2202 listActiveShellIndex: () => Effect.die("snapshot"),
2203 readShellSnapshot: () => Effect.die("snapshot"),
2204 listActiveSubagentThreadIds: () => Effect.succeed([]),
2205 } as unknown as ThreadManagement.ThreadManagementService["Service"]),
2206 Effect.provideService(ProjectStore.ProjectStoreV2, {
2207 listShells: () => Effect.succeed([]),
2208 } as unknown as ProjectStore.ProjectStoreV2["Service"]),
2209 Effect.provideService(
2210 ProjectService.ProjectService,
2211 {} as ProjectService.ProjectService["Service"],
2212 ),
2213 Effect.provideService(ProjectEnrichment.ProjectEnrichmentService, {
2214 subscribeChanges: PubSub.subscribe(yield* PubSub.unbounded()),
2215 } as ProjectEnrichment.ProjectEnrichmentService["Service"]),
2216 Effect.exit,
2217 Effect.forkChild,
2218 );
2219 const fiber = yield* subscription;
2220 yield* Deferred.await(readStarted);
2221 // A pass publishes its boundary, then deletes the rows it covers.
2222 yield* sql`
2223 INSERT INTO orchestration_v2_projection_metadata (
2224 projection_name, schema_version, last_sequence, updated_at
2225 ) VALUES (${OrchestrationEventStore.EVENT_LOG_PRUNED_THROUGH}, 2, ${second!.sequence}, ${now})
2226 `;
2227 yield* sql`DELETE FROM orchestration_events WHERE sequence = ${second!.sequence}`;
2228 yield* Deferred.succeed(releaseRead, undefined);
2229 const exit = yield* Fiber.join(fiber);
2230 assert.deepEqual(Exit.isFailure(exit) ? Cause.squash(exit.cause) : exit, "snapshot");
2231 }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),
2232 );
2233
2234 // A cursor at the high-water missed nothing, even below the boundary; resuming must not resend
2235 // a snapshot. The shell cases are a client that just loaded the HTTP snapshot of a pruned
2236 // database: it gets the marker, and the project identities only when it does not name them.
2237 it.effect.each([
2238 { scope: "thread", knowsIdentities: false, isRepository: true, kinds: [] },
2239 {
2240 scope: "shell",
2241 knowsIdentities: false,
2242 isRepository: true,
2243 kinds: ["snapshot", "synchronized"],
2244 },
2245 { scope: "shell", knowsIdentities: true, isRepository: true, kinds: ["synchronized"] },
2246 // The client keeps a cached identity over an absent one, so "resolved to none" still goes out.
2247 {
2248 scope: "shell",
2249 knowsIdentities: true,
2250 isRepository: false,
2251 kinds: ["snapshot", "synchronized"],
2252 },
2253 ] as const)(
2254 "$scope resume at its own high-water below the pruned boundary skips the snapshot (knows identities: $knowsIdentities, repository: $isRepository)",
2255 ({ scope, knowsIdentities, isRepository, kinds }) =>
2256 Effect.gen(function* () {
2257 const sql = yield* SqlClient.SqlClient;
2258 const now = "2026-10-13T00:00:00.000Z";
2259 const threadId = ThreadId.make("thread:idle");
2260 const [last] = yield* sql<{ sequence: number }>`
2261 INSERT INTO orchestration_events (
2262 event_id, aggregate_kind, stream_id, stream_version, event_type,
2263 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
2264 ) VALUES (
2265 'idle:0', 'thread', ${threadId}, 0, 'provider-session.detached',
2266 ${now}, 'server', ${JSON.stringify({ providerSessionId: "session:idle", detachedAt: now })},
2267 '{}', 2
2268 ) RETURNING sequence
2269 `;
2270 yield* sql`
2271 INSERT INTO orchestration_v2_projection_metadata (
2272 projection_name, schema_version, last_sequence, updated_at
2273 ) VALUES (${OrchestrationEventStore.EVENT_LOG_PRUNED_THROUGH}, 2, ${last!.sequence + 10}, ${now})
2274 `;
2275 const identity = isRepository
2276 ? ({
2277 canonicalKey: "github.com/t3/idle",
2278 locator: {
2279 source: "git-remote",
2280 remoteName: "origin",
2281 remoteUrl: "git@github.com:t3/idle",
2282 },
2283 } as const)
2284 : null;
2285 const project = {
2286 id: ProjectId.make("project:idle"),
2287 title: "Idle",
2288 workspaceRoot: "/tmp/idle",
2289 defaultModelSelection: null,
2290 scripts: [],
2291 createdAt: now,
2292 updatedAt: now,
2293 } satisfies OrchestrationProjectShell;
2294 const subscription = Effect.gen(function* () {
2295 if (scope === "thread") {
2296 return yield* subscribeOrchestrationV2Thread({
2297 threadId,
2298 afterSequence: last!.sequence,
2299 }).pipe(Effect.as([]));
2300 }
2301 const stream = yield* subscribeOrchestrationV2Shell({
2302 afterSequence: last!.sequence,
2303 requestCompletionMarker: true,
2304 ...(knowsIdentities
2305 ? {
2306 knownProjectIdentities: projectIdentitiesDigest([
2307 { ...project, repositoryIdentity: identity },
2308 ]),
2309 }
2310 : {}),
2311 });
2312 return yield* stream.pipe(
2313 Stream.takeUntil((item) => item.kind === "synchronized"),
2314 Stream.map((item) => item.kind),
2315 Stream.runCollect,
2316 );
2317 });
2318 const exit = yield* subscription.pipe(
2319 Effect.provideService(ThreadManagement.ThreadManagementService, {
2320 ensureLegacyTranscript: () => Effect.void,
2321 getThreadSnapshot: () => Effect.die("snapshot"),
2322 listActiveShellIndex: () => Effect.die("snapshot"),
2323 readShellSnapshot: () => Effect.die("snapshot"),
2324 listActiveSubagentThreadIds: () => Effect.succeed([]),
2325 streamStoredEventsFrom: () => Stream.empty,
2326 } as unknown as ThreadManagement.ThreadManagementService["Service"]),
2327 Effect.provideService(ProjectStore.ProjectStoreV2, {
2328 listShells: () => Effect.succeed([project]),
2329 } as unknown as ProjectStore.ProjectStoreV2["Service"]),
2330 Effect.provideService(
2331 ProjectService.ProjectService,
2332 {} as ProjectService.ProjectService["Service"],
2333 ),
2334 Effect.provideService(ProjectEnrichment.ProjectEnrichmentService, {
2335 subscribeChanges: PubSub.subscribe(yield* PubSub.unbounded()),
2336 getAvailable: () =>
2337 Effect.succeed({
2338 repositoryIdentity: identity,
2339 faviconPath: null,
2340 repositoryIdentityResolved: true,
2341 }),
2342 } as unknown as ProjectEnrichment.ProjectEnrichmentService["Service"]),
2343 Effect.exit,
2344 );
2345 // A snapshot load dies with "snapshot", so success means the resume replayed nothing.
2346 assert.deepEqual(
2347 Exit.isFailure(exit) ? Cause.squash(exit.cause) : Array.from(exit.value),
2348 kinds,
2349 );
2350 }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),
2351 );
2352
2353 const acpDriver = ProviderDriverKind.make("acpRegistry");
2354 const acpInstanceId = ProviderInstanceId.make("acpRegistry_test");
2355 const acpProjectId = ProjectId.make("project:acp");
2356 const acpThreadId = (sessionId: string) =>
2357 IdAllocator.deriveThreadFromProviderThread({
2358 driver: acpDriver,
2359 providerInstanceId: acpInstanceId,
2360 nativeThreadId: sessionId,
2361 });
2362 const acpSessionTags = [
2363 WS_METHODS.serverListAcpRegistrySessions,
2364 WS_METHODS.serverImportAcpRegistrySession,
2365 WS_METHODS.serverDeleteAcpRegistrySession,
2366 ] as const;
2367 const acpSessionRpcs = WsRpcGroup.omit(
2368 ...[...WsRpcGroup.requests.keys()].filter(
2369 (
2370 tag,
2371 ): tag is Exclude<
2372 keyof typeof RpcAuthorization.RPC_REQUIRED_SCOPES,
2373 (typeof acpSessionTags)[number]
2374 > => !(acpSessionTags as ReadonlyArray<string>).includes(tag),
2375 ),
2376 );
2377 const acpStores = Layer.mergeAll(EventStore.layer, ProjectionStore.layer).pipe(
2378 Layer.provideMerge(SqlitePersistence.layerMemory),
2379 );
2380
2381 const seedAcpThread = Effect.fn(function* (
2382 sessionId: string,
2383 state: { readonly imported: boolean; readonly ran: boolean; readonly nativeId?: string },
2384 ) {
2385 const sink = yield* EventSink.EventSinkV2;
2386 const now = DateTime.makeUnsafe("2026-10-23T00:00:00.000Z");
2387 const threadId = acpThreadId(sessionId);
2388 const thread: OrchestrationV2AppThread = {
2389 createdBy: "user",
2390 creationSource: "web",
2391 id: threadId,
2392 projectId: acpProjectId,
2393 title: sessionId,
2394 providerInstanceId: acpInstanceId,
2395 modelSelection: { instanceId: acpInstanceId, model: "default" },
2396 runtimeMode: "approval-required",
2397 interactionMode: "default",
2398 branch: null,
2399 worktreePath: null,
2400 activeProviderThreadId: null,
2401 ...(state.imported ? { historyOrigin: "v1_import" as const } : {}),
2402 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
2403 forkedFrom: null,
2404 createdAt: now,
2405 updatedAt: now,
2406 archivedAt: null,
2407 deletedAt: null,
2408 settledOverride: null,
2409 settledAt: null,
2410 lastVisitedAt: null,
2411 };
2412 const events: Array<OrchestrationV2DomainEvent> = [
2413 {
2414 id: EventId.make(`${threadId}:created`),
2415 type: "thread.created",
2416 threadId,
2417 occurredAt: now,
2418 payload: thread,
2419 },
2420 ];
2421 if (state.nativeId !== undefined) {
2422 events.push({
2423 id: EventId.make(`${threadId}:provider`),
2424 type: "provider-thread.updated",
2425 threadId,
2426 occurredAt: now,
2427 payload: {
2428 id: ProviderThreadId.make(`${threadId}:provider`),
2429 appThreadId: threadId,
2430 ownerNodeId: null,
2431 driver: acpDriver,
2432 providerInstanceId: acpInstanceId,
2433 providerSessionId: null,
2434 nativeThreadRef: { driver: acpDriver, nativeId: state.nativeId, strength: "strong" },
2435 nativeConversationHeadRef: null,
2436 status: "idle",
2437 firstRunOrdinal: null,
2438 lastRunOrdinal: null,
2439 handoffIds: [],
2440 forkedFrom: null,
2441 createdAt: now,
2442 updatedAt: now,
2443 pendingBackgroundTasks: [],
2444 },
2445 });
2446 }
2447 if (state.ran) {
2448 events.push({
2449 id: EventId.make(`${threadId}:run`),
2450 type: "run.updated",
2451 threadId,
2452 occurredAt: now,
2453 payload: {
2454 id: RunId.make(`${threadId}:run`),
2455 threadId,
2456 ordinal: 1,
2457 providerInstanceId: acpInstanceId,
2458 modelSelection: thread.modelSelection,
2459 providerThreadId: null,
2460 userMessageId: MessageId.make(`${threadId}:prompt`),
2461 rootNodeId: null,
2462 activeAttemptId: null,
2463 status: "completed",
2464 requestedAt: now,
2465 startedAt: now,
2466 completedAt: now,
2467 checkpointId: null,
2468 contextHandoffId: null,
2469 },
2470 });
2471 }
2472 yield* sink.write({ events });
2473 return threadId;
2474 });
2475
2476 it.effect("ACP session RPCs list a thread missing its history and repair it on import", () =>
2477 Effect.gen(function* () {
2478 const projections = yield* ProjectionStore.ProjectionStoreV2;
2479 const sql = yield* SqlClient.SqlClient;
2480 const pending = yield* seedAcpThread("pending", { imported: false, ran: false });
2481 const complete = yield* seedAcpThread("complete", { imported: true, ran: false });
2482 const ran = yield* seedAcpThread("ran", { imported: false, ran: true });
2483 const owned = yield* seedAcpThread("existing-t3-thread", {
2484 imported: false,
2485 ran: true,
2486 nativeId: "owned-session",
2487 });
2488 const repaired: Array<ThreadId> = [];
2489 const deleted: Array<string> = [];
2490 const session = (sessionId: string) => ({
2491 sessionId,
2492 cwd: "/workspace/acp",
2493 additionalDirectories: [],
2494 title: null,
2495 updatedAt: null,
2496 importedThreadId: null,
2497 });
2498 const instance = {
2499 driverKind: acpDriver,
2500 snapshot: {
2501 getSnapshot: Effect.succeed({ nativeSessions: { canLoad: true, canDelete: true } }),
2502 },
2503 acpSessionManagement: {
2504 listSessions: () =>
2505 Effect.succeed({
2506 sessions: ["new", "pending", "complete", "ran", "owned-session"].map(session),
2507 nextCursor: null,
2508 canLoad: true,
2509 canResume: true,
2510 canDelete: true,
2511 }),
2512 deleteSession: ({ sessionId }: { readonly sessionId: string }) =>
2513 Effect.sync(() => {
2514 deleted.push(sessionId);
2515 }),
2516 },
2517 } as unknown as ProviderInstance;
2518 const dependencies = Layer.mergeAll(
2519 layerUnusedConfigRpcServices,
2520 Layer.fresh(layerConfigSources),
2521 Layer.mock(ExternalLauncher.ExternalLauncher)({}),
2522 Layer.mock(ProviderRegistry.ProviderRegistry)({}),
2523 Layer.mock(UsageLimitSources.UsageLimitSources)({}),
2524 Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}),
2525 Layer.mock(DirectEndpoints.DirectEndpoints)({}),
2526 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }),
2527 Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}),
2528 Layer.mock(ServerEnvironment.ServerEnvironment)({}),
2529 Layer.mock(EnvironmentAuth.EnvironmentAuth)({}),
2530 Layer.mock(ProjectService.ProjectService)({
2531 getById: () =>
2532 Effect.succeedSome({
2533 id: acpProjectId,
2534 title: "ACP",
2535 workspaceRoot: "/workspace/acp",
2536 defaultModelSelection: null,
2537 scripts: [],
2538 createdAt: "2026-10-23T00:00:00.000Z",
2539 updatedAt: "2026-10-23T00:00:00.000Z",
2540 deletedAt: null,
2541 }),
2542 }),
2543 Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({
2544 getInstance: () => Effect.succeed(instance),
2545 }),
2546 Layer.mock(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator)({
2547 withSessionMutation: (effect) => effect,
2548 }),
2549 Layer.mock(ThreadManagement.ThreadManagementService)({
2550 getThreadShell: (threadId) =>
2551 projections
2552 .getThreadShell(threadId)
2553 .pipe(
2554 Effect.mapError(
2555 (cause) => new Orchestrator.OrchestratorProjectionError({ threadId, cause }),
2556 ),
2557 ),
2558 }),
2559 // Repairing an existing thread must not launch another one.
2560 Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
2561 Layer.mock(AgentSessionImporter.AgentSessionImporter)({
2562 importNativeHistory: ({ threadId }) =>
2563 Effect.sync(() => repaired.push(threadId)).pipe(Effect.as(1)),
2564 }),
2565 Layer.succeed(SqlClient.SqlClient, sql),
2566 );
2567 const services = AcpRegistrySessions.layer.pipe(Layer.provideMerge(dependencies));
2568 const client = yield* RpcTest.makeClient(acpSessionRpcs).pipe(
2569 Effect.provide(
2570 layerWsRpc(
2571 {
2572 sessionId: AuthSessionId.make("acp-test"),
2573 subject: "acp-test",
2574 method: "browser-session-cookie",
2575 scopes: [],
2576 },
2577 {},
2578 yield* ServerBrowser.ServerBrowser,
2579 () => Effect.void,
2580 { secretReferences: true },
2581 ).pipe(
2582 Layer.provide(services),
2583 Layer.merge(
2584 RpcAuthorization.layer([AuthOrchestrationReadScope, AuthOrchestrationOperateScope]),
2585 ),
2586 ),
2587 ),
2588 );
2589
2590 const listed = yield* client[WS_METHODS.serverListAcpRegistrySessions]({
2591 instanceId: acpInstanceId,
2592 projectId: acpProjectId,
2593 });
2594 assert.deepEqual(
2595 listed.sessions.map(({ sessionId, importedThreadId, nativeHistoryPending }) => [
2596 sessionId,
2597 importedThreadId,
2598 nativeHistoryPending,
2599 ]),
2600 [
2601 ["new", null, undefined],
2602 ["pending", pending, true],
2603 ["complete", complete, undefined],
2604 ["ran", ran, undefined],
2605 ["owned-session", owned, undefined],
2606 ],
2607 );
2608
2609 const imported = yield* client[WS_METHODS.serverImportAcpRegistrySession]({
2610 instanceId: acpInstanceId,
2611 projectId: acpProjectId,
2612 sessionId: "pending",
2613 });
2614 assert.deepEqual(imported, { threadId: pending, imported: true });
2615 assert.deepEqual(repaired, [pending]);
2616 const reopened = yield* client[WS_METHODS.serverImportAcpRegistrySession]({
2617 instanceId: acpInstanceId,
2618 projectId: acpProjectId,
2619 sessionId: "owned-session",
2620 });
2621 assert.deepEqual(reopened, { threadId: owned, imported: false });
2622 assert.deepEqual(repaired, [pending]);
2623 const deletion = yield* client[WS_METHODS.serverDeleteAcpRegistrySession]({
2624 instanceId: acpInstanceId,
2625 projectId: acpProjectId,
2626 sessionId: "owned-session",
2627 }).pipe(Effect.exit);
2628 assert.isTrue(Exit.isFailure(deletion));
2629 assert.deepEqual(deleted, []);
2630 }).pipe(
2631 Effect.provide(
2632 Layer.mergeAll(
2633 EventSink.layer.pipe(Layer.provideMerge(acpStores)),
2634 Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}),
2635 Layer.mock(ServerBrowser.ServerBrowser)({}),
2636 ),
2637 ),
2638 ),
2639 );