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