The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 25, 05:00 UTC
reduce startup time by ~47% and memory usage by up to 150-300MB (#2204)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
legs committed
May 4, 2026 at 21:56 UTC
aca0fa4e5b0458ab640c2f479da0a1587c125e4a
30 files changed
+1850
-458
apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts
+9
@@ -86,10 +86,13 @@ describe("CheckpointDiffQueryLive", () => {
86
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
87
Layer.provideMerge(
88
Layer.succeed(ProjectionSnapshotQuery, {
89
+ getCommandReadModel: () =>
90
+ Effect.die("CheckpointDiffQuery should not request the command read model"),
91
getSnapshot: () =>
92
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
93
getShellSnapshot: () =>
94
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
95
+ getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
96
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
97
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
98
getProjectShellById: () => Effect.succeed(Option.none()),
@@ -163,10 +166,13 @@ describe("CheckpointDiffQueryLive", () => {
166
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
167
Layer.provideMerge(
168
Layer.succeed(ProjectionSnapshotQuery, {
169
+ getCommandReadModel: () =>
170
+ Effect.die("CheckpointDiffQuery should not request the command read model"),
171
getSnapshot: () =>
172
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
173
getShellSnapshot: () =>
174
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
175
+ getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
176
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
177
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
178
getProjectShellById: () => Effect.succeed(Option.none()),
@@ -208,10 +214,13 @@ describe("CheckpointDiffQueryLive", () => {
214
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
215
Layer.provideMerge(
216
Layer.succeed(ProjectionSnapshotQuery, {
217
+ getCommandReadModel: () =>
218
+ Effect.die("CheckpointDiffQuery should not request the command read model"),
219
getSnapshot: () =>
220
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
221
getShellSnapshot: () =>
222
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
223
+ getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
224
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
225
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
226
getProjectShellById: () => Effect.succeed(Option.none()),
apps/server/src/cli.test.ts
+2
-3
@@ -17,7 +17,6 @@ import { Command } from "effect/unstable/cli";
17
18
import { cli } from "./cli.ts";
19
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
20
-import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
20
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
21
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
22
import {
@@ -316,8 +315,8 @@ it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
315
"--base-dir",
316
baseDir,
317
]);
319
- const orchestrationEngine = yield* OrchestrationEngineService;
320
- const readModel = yield* orchestrationEngine.getReadModel();
318
+ const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
319
+ const readModel = yield* projectionSnapshotQuery.getSnapshot();
320
const addedProject = readModel.projects.find(
321
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
322
);
apps/server/src/orchestration/Layers/CheckpointReactor.test.ts
+30
-12
@@ -41,6 +41,7 @@ import {
41
type OrchestrationEngineShape,
42
} from "../Services/OrchestrationEngine.ts";
43
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
44
+import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
45
import {
46
ProviderService,
47
type ProviderServiceShape,
@@ -132,7 +133,14 @@ function createProviderServiceHarness(
133
}
134
135
async function waitForThread(
135
- engine: OrchestrationEngineShape,
136
+ readModel: () => Promise<{
137
+ readonly threads: ReadonlyArray<{
138
+ readonly id: ThreadId;
139
+ readonly latestTurn: { readonly turnId: string } | null;
140
+ readonly checkpoints: ReadonlyArray<{ readonly checkpointTurnCount: number }>;
141
+ readonly activities: ReadonlyArray<{ readonly kind: string }>;
142
+ }>;
143
+ }>,
144
predicate: (thread: {
145
latestTurn: { turnId: string } | null;
146
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
@@ -146,8 +154,8 @@ async function waitForThread(
154
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
155
activities: ReadonlyArray<{ kind: string }>;
156
}> => {
149
- const readModel = await Effect.runPromise(engine.getReadModel());
150
- const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
157
+ const snapshot = await readModel();
158
+ const thread = snapshot.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
159
if (thread && predicate(thread)) {
160
return thread;
161
}
@@ -231,7 +239,7 @@ async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000)
239
240
describe("CheckpointReactor", () => {
241
let runtime: ManagedRuntime.ManagedRuntime<
234
- OrchestrationEngineService | CheckpointReactor | CheckpointStore,
242
+ OrchestrationEngineService | CheckpointReactor | CheckpointStore | ProjectionSnapshotQuery,
243
unknown
244
> | null = null;
245
let scope: Scope.Closeable | null = null;
@@ -279,6 +287,10 @@ describe("CheckpointReactor", () => {
287
Layer.provide(RepositoryIdentityResolverLive),
288
Layer.provide(SqlitePersistenceMemory),
289
);
290
+ const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
291
+ Layer.provide(RepositoryIdentityResolverLive),
292
+ Layer.provide(SqlitePersistenceMemory),
293
+ );
294
295
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
296
prefix: "t3-checkpoint-reactor-test-",
@@ -304,6 +316,7 @@ describe("CheckpointReactor", () => {
316
317
const layer = CheckpointReactorLive.pipe(
318
Layer.provideMerge(orchestrationLayer),
319
+ Layer.provideMerge(projectionSnapshotLayer),
320
Layer.provideMerge(RuntimeReceiptBusLive),
321
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
322
Layer.provideMerge(vcsStatusBroadcasterLayer),
@@ -322,6 +335,7 @@ describe("CheckpointReactor", () => {
335
336
runtime = ManagedRuntime.make(layer);
337
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
338
+ const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
339
const reactor = await runtime.runPromise(Effect.service(CheckpointReactor));
340
const checkpointStore = await runtime.runPromise(Effect.service(CheckpointStore));
341
scope = await Effect.runPromise(Scope.make("sequential"));
@@ -387,6 +401,7 @@ describe("CheckpointReactor", () => {
401
402
return {
403
engine,
404
+ readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
405
provider,
406
cwd,
407
drain,
@@ -443,7 +458,7 @@ describe("CheckpointReactor", () => {
458
459
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
460
const thread = await waitForThread(
446
- harness.engine,
461
+ harness.readModel,
462
(entry) => entry.latestTurn?.turnId === "turn-1" && entry.checkpoints.length === 1,
463
);
464
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
@@ -541,7 +556,7 @@ describe("CheckpointReactor", () => {
556
});
557
558
await harness.drain();
544
- const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
559
+ const midReadModel = await harness.readModel();
560
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
561
expect(midThread?.checkpoints).toHaveLength(0);
562
@@ -557,7 +572,7 @@ describe("CheckpointReactor", () => {
572
});
573
574
const thread = await waitForThread(
560
- harness.engine,
575
+ harness.readModel,
576
(entry) => entry.latestTurn?.turnId === "turn-main" && entry.checkpoints.length === 1,
577
);
578
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
@@ -614,7 +629,7 @@ describe("CheckpointReactor", () => {
629
630
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
631
const thread = await waitForThread(
617
- harness.engine,
632
+ harness.readModel,
633
(entry) => entry.latestTurn?.turnId === "turn-claude-1" && entry.checkpoints.length === 1,
634
);
635
@@ -659,7 +674,7 @@ describe("CheckpointReactor", () => {
674
675
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
676
const thread = await waitForThread(
662
- harness.engine,
677
+ harness.readModel,
678
(entry) =>
679
entry.checkpoints.length === 1 &&
680
entry.activities.some((activity) => activity.kind === "checkpoint.capture.failed"),
@@ -794,7 +809,7 @@ describe("CheckpointReactor", () => {
809
});
810
811
await harness.drain();
797
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
812
+ const readModel = await harness.readModel();
813
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
814
expect(thread?.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
815
false,
@@ -923,7 +938,10 @@ describe("CheckpointReactor", () => {
938
);
939
940
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
926
- const thread = await waitForThread(harness.engine, (entry) => entry.checkpoints.length === 1);
941
+ const thread = await waitForThread(
942
+ harness.readModel,
943
+ (entry) => entry.checkpoints.length === 1,
944
+ );
945
946
expect(thread.latestTurn?.turnId).toBe("turn-1");
947
expect(thread.checkpoints).toHaveLength(1);
@@ -1105,7 +1123,7 @@ describe("CheckpointReactor", () => {
1123
}),
1124
);
1125
1108
- const thread = await waitForThread(harness.engine, (entry) =>
1126
+ const thread = await waitForThread(harness.readModel, (entry) =>
1127
entry.activities.some((activity) => activity.kind === "checkpoint.revert.failed"),
1128
);
1129
apps/server/src/orchestration/Layers/CheckpointReactor.ts
+32
-34
@@ -20,6 +20,7 @@ import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts
20
import { ProviderService } from "../../provider/Services/ProviderService.ts";
21
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
22
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
23
+import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
24
import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
25
import type { CheckpointStoreError } from "../../checkpointing/Errors.ts";
26
import type { OrchestrationDispatchError } from "../Errors.ts";
@@ -66,6 +67,7 @@ const serverCommandId = (tag: string): CommandId =>
67
68
const make = Effect.gen(function* () {
69
const orchestrationEngine = yield* OrchestrationEngineService;
70
+ const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
71
const providerService = yield* ProviderService;
72
const checkpointStore = yield* CheckpointStore;
73
const receiptBus = yield* RuntimeReceiptBus;
@@ -124,29 +126,26 @@ const make = Effect.gen(function* () {
126
const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* (
127
threadId: ThreadId,
128
): Effect.fn.Return<Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>> {
127
- const readModel = yield* orchestrationEngine.getReadModel();
128
- const thread = readModel.threads.find((entry) => entry.id === threadId);
129
-
129
const sessions = yield* providerService.listSessions();
130
+ const session = sessions.find((entry) => entry.threadId === threadId);
131
+ return session?.cwd
132
+ ? Option.some({ threadId: session.threadId, cwd: session.cwd })
133
+ : Option.none();
134
+ });
135
132
- const findSessionWithCwd = (
133
- session: (typeof sessions)[number] | undefined,
134
- ): Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }> => {
135
- if (!session?.cwd) {
136
- return Option.none();
137
- }
138
- return Option.some({ threadId: session.threadId, cwd: session.cwd });
139
- };
140
-
141
- if (thread) {
142
- const projectedSession = sessions.find((session) => session.threadId === thread.id);
143
- const fromProjected = findSessionWithCwd(projectedSession);
144
- if (Option.isSome(fromProjected)) {
145
- return fromProjected;
146
- }
147
- }
136
+ const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (threadId: ThreadId) {
137
+ return yield* projectionSnapshotQuery
138
+ .getThreadDetailById(threadId)
139
+ .pipe(Effect.map(Option.getOrUndefined));
140
+ });
141
149
- return Option.none();
142
+ const resolveThreadProjects = Effect.fn("resolveThreadProjects")(function* (
143
+ projectId: ProjectId,
144
+ ) {
145
+ const project = yield* projectionSnapshotQuery
146
+ .getProjectShellById(projectId)
147
+ .pipe(Effect.map(Option.getOrUndefined));
148
+ return project ? [project] : [];
149
});
150
151
const isGitWorkspace = (cwd: string) => isGitRepository(cwd);
@@ -331,8 +330,7 @@ const make = Effect.gen(function* () {
330
return;
331
}
332
334
- const readModel = yield* orchestrationEngine.getReadModel();
335
- const thread = readModel.threads.find((entry) => entry.id === event.threadId);
333
+ const thread = yield* resolveThreadDetail(event.threadId);
334
if (!thread) {
335
return;
336
}
@@ -353,10 +351,11 @@ const make = Effect.gen(function* () {
351
return;
352
}
353
354
+ const projects = yield* resolveThreadProjects(thread.projectId);
355
const checkpointCwd = yield* resolveCheckpointCwd({
356
threadId: thread.id,
357
thread,
359
- projects: readModel.projects,
358
+ projects,
359
preferSessionRuntime: true,
360
});
361
if (!checkpointCwd) {
@@ -407,8 +406,7 @@ const make = Effect.gen(function* () {
406
return;
407
}
408
410
- const readModel = yield* orchestrationEngine.getReadModel();
411
- const thread = readModel.threads.find((entry) => entry.id === threadId);
409
+ const thread = yield* resolveThreadDetail(threadId);
410
if (!thread) {
411
yield* Effect.logWarning("checkpoint capture from placeholder skipped: thread not found", {
412
threadId,
@@ -429,10 +427,11 @@ const make = Effect.gen(function* () {
427
return;
428
}
429
430
+ const projects = yield* resolveThreadProjects(thread.projectId);
431
const checkpointCwd = yield* resolveCheckpointCwd({
432
threadId,
433
thread,
435
- projects: readModel.projects,
434
+ projects,
435
preferSessionRuntime: true,
436
});
437
if (!checkpointCwd) {
@@ -458,16 +457,16 @@ const make = Effect.gen(function* () {
457
return;
458
}
459
461
- const readModel = yield* orchestrationEngine.getReadModel();
462
- const thread = readModel.threads.find((entry) => entry.id === event.threadId);
460
+ const thread = yield* resolveThreadDetail(event.threadId);
461
if (!thread) {
462
return;
463
}
464
465
+ const projects = yield* resolveThreadProjects(thread.projectId);
466
const checkpointCwd = yield* resolveCheckpointCwd({
467
threadId: thread.id,
468
thread,
470
- projects: readModel.projects,
469
+ projects,
470
preferSessionRuntime: false,
471
});
472
if (!checkpointCwd) {
@@ -540,16 +539,16 @@ const make = Effect.gen(function* () {
539
}
540
541
const threadId = event.payload.threadId;
543
- const readModel = yield* orchestrationEngine.getReadModel();
544
- const thread = readModel.threads.find((entry) => entry.id === threadId);
542
+ const thread = yield* resolveThreadDetail(threadId);
543
if (!thread) {
544
return;
545
}
546
547
+ const projects = yield* resolveThreadProjects(thread.projectId);
548
const checkpointCwd = yield* resolveCheckpointCwd({
549
threadId,
550
thread,
552
- projects: readModel.projects,
551
+ projects,
552
preferSessionRuntime: false,
553
});
554
if (!checkpointCwd) {
@@ -587,8 +586,7 @@ const make = Effect.gen(function* () {
586
) {
587
const now = new Date().toISOString();
588
590
- const readModel = yield* orchestrationEngine.getReadModel();
591
- const thread = readModel.threads.find((entry) => entry.id === event.payload.threadId);
589
+ const thread = yield* resolveThreadDetail(event.payload.threadId);
590
if (!thread) {
591
yield* appendRevertFailureActivity({
592
threadId: event.payload.threadId,
apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts
+82
-43
@@ -8,6 +8,7 @@ import {
8
TurnId,
9
type OrchestrationEvent,
10
ProviderInstanceId,
11
+ type OrchestrationReadModel,
12
} from "@t3tools/contracts";
13
import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect";
14
import { describe, expect, it } from "vitest";
@@ -42,9 +43,13 @@ async function createOrchestrationSystem() {
43
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
44
prefix: "t3-orchestration-engine-test-",
45
});
45
- const orchestrationLayer = OrchestrationEngineLive.pipe(
46
- Layer.provide(OrchestrationProjectionSnapshotQueryLive),
47
- Layer.provide(OrchestrationProjectionPipelineLive),
46
+ const orchestrationLayer = Layer.mergeAll(
47
+ OrchestrationEngineLive.pipe(
48
+ Layer.provide(OrchestrationProjectionSnapshotQueryLive),
49
+ Layer.provide(OrchestrationProjectionPipelineLive),
50
+ ),
51
+ OrchestrationProjectionSnapshotQueryLive,
52
+ ).pipe(
53
Layer.provide(OrchestrationEventStoreLive),
54
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
55
Layer.provide(RepositoryIdentityResolverLive),
@@ -54,8 +59,10 @@ async function createOrchestrationSystem() {
59
);
60
const runtime = ManagedRuntime.make(orchestrationLayer);
61
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
62
+ const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
63
return {
64
engine,
65
+ readModel: () => runtime.runPromise(snapshotQuery.getSnapshot()),
66
run: <A, E>(effect: Effect.Effect<A, E>) => runtime.runPromise(effect),
67
dispose: () => runtime.dispose(),
68
};
@@ -77,15 +84,18 @@ const hasMetricSnapshot = (
84
);
85
86
describe("OrchestrationEngine", () => {
80
- it("bootstraps the in-memory read model from persisted projections", async () => {
81
- const failOnHistoricalReplayStore: OrchestrationEventStoreShape = {
82
- append: () =>
83
- Effect.fail(
84
- new PersistenceSqlError({
85
- operation: "test.append",
86
- detail: "append should not be called during bootstrap",
87
- }),
88
- ),
87
+ it("bootstraps command handling from persisted projections without reading the full snapshot", async () => {
88
+ let nextSequence = 8;
89
+ const eventStore: OrchestrationEventStoreShape = {
90
+ append: (event) =>
91
+ Effect.sync(() => {
92
+ const savedEvent = {
93
+ ...event,
94
+ sequence: nextSequence,
95
+ } as OrchestrationEvent;
96
+ nextSequence += 1;
97
+ return savedEvent;
98
+ }),
99
readFromSequence: () => Stream.empty,
100
readAll: () =>
101
Stream.fail(
@@ -140,11 +150,27 @@ describe("OrchestrationEngine", () => {
150
},
151
],
152
};
153
+ const commandReadModel = {
154
+ ...projectionSnapshot,
155
+ threads: projectionSnapshot.threads.map((thread) => ({
156
+ ...thread,
157
+ messages: [],
158
+ proposedPlans: [],
159
+ activities: [],
160
+ checkpoints: [],
161
+ })),
162
+ };
163
+ let fullSnapshotReadCount = 0;
164
165
const layer = OrchestrationEngineLive.pipe(
166
Layer.provide(
167
Layer.succeed(ProjectionSnapshotQuery, {
147
- getSnapshot: () => Effect.succeed(projectionSnapshot),
168
+ getCommandReadModel: () => Effect.succeed(commandReadModel),
169
+ getSnapshot: () =>
170
+ Effect.sync(() => {
171
+ fullSnapshotReadCount += 1;
172
+ return projectionSnapshot;
173
+ }),
174
getShellSnapshot: () =>
175
Effect.succeed({
176
snapshotSequence: projectionSnapshot.snapshotSequence,
@@ -152,6 +178,8 @@ describe("OrchestrationEngine", () => {
178
threads: [],
179
updatedAt: projectionSnapshot.updatedAt,
180
}),
181
+ getSnapshotSequence: () =>
182
+ Effect.succeed({ snapshotSequence: projectionSnapshot.snapshotSequence }),
183
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
184
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
185
getProjectShellById: () => Effect.succeed(Option.none()),
@@ -167,7 +195,7 @@ describe("OrchestrationEngine", () => {
195
projectEvent: () => Effect.void,
196
} satisfies OrchestrationProjectionPipelineShape),
197
),
170
- Layer.provide(Layer.succeed(OrchestrationEventStore, failOnHistoricalReplayStore)),
198
+ Layer.provide(Layer.succeed(OrchestrationEventStore, eventStore)),
199
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
200
Layer.provide(SqlitePersistenceMemory),
201
);
@@ -175,18 +203,22 @@ describe("OrchestrationEngine", () => {
203
const runtime = ManagedRuntime.make(layer);
204
205
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
178
- const readModel = await runtime.runPromise(engine.getReadModel());
206
+ const result = await runtime.runPromise(
207
+ engine.dispatch({
208
+ type: "thread.meta.update",
209
+ commandId: CommandId.make("cmd-bootstrap-thread-update"),
210
+ threadId: ThreadId.make("thread-bootstrap"),
211
+ title: "Updated Bootstrap Thread",
212
+ }),
213
+ );
214
180
- expect(readModel.snapshotSequence).toBe(7);
181
- expect(readModel.projects).toHaveLength(1);
182
- expect(readModel.projects[0]?.title).toBe("Bootstrap Project");
183
- expect(readModel.threads).toHaveLength(1);
184
- expect(readModel.threads[0]?.title).toBe("Bootstrap Thread");
215
+ expect(result.sequence).toBe(8);
216
+ expect(fullSnapshotReadCount).toBe(0);
217
218
await runtime.dispose();
219
});
220
189
- it("returns deterministic read models for repeated reads", async () => {
221
+ it("persists deterministic read models for repeated snapshot reads", async () => {
222
const createdAt = now();
223
const system = await createOrchestrationSystem();
224
const { engine } = system;
@@ -240,8 +272,8 @@ describe("OrchestrationEngine", () => {
272
}),
273
);
274
243
- const readModelA = await system.run(engine.getReadModel());
244
- const readModelB = await system.run(engine.getReadModel());
275
+ const readModelA = await system.readModel();
276
+ const readModelB = await system.readModel();
277
expect(readModelB).toEqual(readModelA);
278
await system.dispose();
279
});
@@ -292,9 +324,8 @@ describe("OrchestrationEngine", () => {
324
}),
325
);
326
expect(
295
- (await system.run(engine.getReadModel())).threads.find(
296
- (thread) => thread.id === "thread-archive",
297
- )?.archivedAt,
327
+ (await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
328
+ ?.archivedAt,
329
).not.toBeNull();
330
331
await system.run(
@@ -305,9 +336,8 @@ describe("OrchestrationEngine", () => {
336
}),
337
);
338
expect(
308
- (await system.run(engine.getReadModel())).threads.find(
309
- (thread) => thread.id === "thread-archive",
310
- )?.archivedAt,
339
+ (await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
340
+ ?.archivedAt,
341
).toBeNull();
342
343
await system.dispose();
@@ -573,7 +603,7 @@ describe("OrchestrationEngine", () => {
603
}),
604
);
605
576
- const thread = (await system.run(engine.getReadModel())).threads.find(
606
+ const thread = (await system.readModel()).threads.find(
607
(entry) => entry.id === "thread-turn-diff",
608
);
609
expect(thread?.checkpoints).toEqual([
@@ -701,7 +731,15 @@ describe("OrchestrationEngine", () => {
731
);
732
733
expect(result.sequence).toBe(2);
704
- expect((await runtime.runPromise(engine.getReadModel())).snapshotSequence).toBe(2);
734
+ const eventsAfterRetry = await runtime.runPromise(
735
+ Stream.runCollect(engine.readEvents(0)).pipe(
736
+ Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
737
+ ),
738
+ );
739
+ expect(eventsAfterRetry.map((event) => event.type)).toEqual([
740
+ "project.created",
741
+ "thread.created",
742
+ ]);
743
await runtime.dispose();
744
});
745
@@ -801,7 +839,6 @@ describe("OrchestrationEngine", () => {
839
"project.created",
840
"thread.created",
841
]);
804
- expect((await runtime.runPromise(engine.getReadModel())).snapshotSequence).toBe(2);
842
843
const retryResult = await runtime.runPromise(engine.dispatch(turnStartCommand));
844
expect(retryResult.sequence).toBe(4);
@@ -824,7 +861,7 @@ describe("OrchestrationEngine", () => {
861
await runtime.dispose();
862
});
863
827
- it("reconciles in-memory state when append persists but projection fails", async () => {
864
+ it("reconciles command state when append persists but projection fails", async () => {
865
type StoredEvent =
866
ReturnType<OrchestrationEventStoreShape["append"]> extends Effect.Effect<infer A, any, any>
867
? A
@@ -856,7 +893,7 @@ describe("OrchestrationEngine", () => {
893
projectEvent: (event) => {
894
if (
895
shouldFailProjection &&
859
- event.commandId === CommandId.make("cmd-thread-meta-sync-fail")
896
+ event.commandId === CommandId.make("cmd-thread-archive-sync-fail")
897
) {
898
shouldFailProjection = false;
899
return Effect.fail(
@@ -919,20 +956,22 @@ describe("OrchestrationEngine", () => {
956
await expect(
957
runtime.runPromise(
958
engine.dispatch({
922
- type: "thread.meta.update",
923
- commandId: CommandId.make("cmd-thread-meta-sync-fail"),
959
+ type: "thread.archive",
960
+ commandId: CommandId.make("cmd-thread-archive-sync-fail"),
961
threadId: ThreadId.make("thread-sync"),
925
- title: "sync-after-failed-projection",
962
}),
963
),
964
).rejects.toThrow("projection failed");
965
930
- const readModelAfterFailure = await runtime.runPromise(engine.getReadModel());
931
- const updatedThread = readModelAfterFailure.threads.find(
932
- (thread) => thread.id === "thread-sync",
933
- );
934
- expect(readModelAfterFailure.snapshotSequence).toBe(3);
935
- expect(updatedThread?.title).toBe("sync-after-failed-projection");
966
+ await expect(
967
+ runtime.runPromise(
968
+ engine.dispatch({
969
+ type: "thread.archive",
970
+ commandId: CommandId.make("cmd-thread-archive-sync-retry"),
971
+ threadId: ThreadId.make("thread-sync"),
972
+ }),
973
+ ),
974
+ ).rejects.toThrow("already archived");
975
976
await runtime.dispose();
977
});
apps/server/src/orchestration/Layers/OrchestrationEngine.ts
+25
-20
@@ -34,6 +34,7 @@ import {
34
OrchestrationCommandInvariantError,
35
OrchestrationCommandPreviouslyRejectedError,
36
type OrchestrationDispatchError,
37
+ type OrchestrationProjectorDecodeError,
38
} from "../Errors.ts";
39
import { decideOrchestrationCommand } from "../decider.ts";
40
import { createEmptyReadModel, projectEvent } from "../projector.ts";
@@ -77,13 +78,25 @@ const makeOrchestrationEngine = Effect.gen(function* () {
78
const projectionPipeline = yield* OrchestrationProjectionPipeline;
79
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
80
80
- let readModel = createEmptyReadModel(new Date().toISOString());
81
+ let commandReadModel = createEmptyReadModel(new Date().toISOString());
82
83
const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
84
const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();
85
86
+ const projectEventsOntoReadModel = (
87
+ baseReadModel: OrchestrationReadModel,
88
+ events: ReadonlyArray<OrchestrationEvent>,
89
+ ): Effect.Effect<OrchestrationReadModel, OrchestrationProjectorDecodeError, never> =>
90
+ Effect.gen(function* () {
91
+ let nextReadModel = baseReadModel;
92
+ for (const event of events) {
93
+ nextReadModel = yield* projectEvent(nextReadModel, event);
94
+ }
95
+ return nextReadModel;
96
+ });
97
+
98
const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {
86
- const dispatchStartSequence = readModel.snapshotSequence;
99
+ const dispatchStartSequence = commandReadModel.snapshotSequence;
100
const processingStartedAtMs = Date.now();
101
const aggregateRef = commandToAggregateRef(envelope.command);
102
const baseMetricAttributes = {
@@ -98,11 +111,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
111
return;
112
}
113
101
- let nextReadModel = readModel;
102
- for (const persistedEvent of persistedEvents) {
103
- nextReadModel = yield* projectEvent(nextReadModel, persistedEvent);
104
- }
105
- readModel = nextReadModel;
114
+ commandReadModel = yield* projectEventsOntoReadModel(commandReadModel, persistedEvents);
115
116
for (const persistedEvent of persistedEvents) {
117
yield* PubSub.publish(eventPubSub, persistedEvent);
@@ -135,18 +144,18 @@ const makeOrchestrationEngine = Effect.gen(function* () {
144
145
const eventBase = yield* decideOrchestrationCommand({
146
command: envelope.command,
138
- readModel,
147
+ readModel: commandReadModel,
148
});
149
const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
150
const committedCommand = yield* sql
151
.withTransaction(
152
Effect.gen(function* () {
153
const committedEvents: OrchestrationEvent[] = [];
145
- let nextReadModel = readModel;
154
+ let nextCommandReadModel = commandReadModel;
155
156
for (const nextEvent of eventBases) {
157
const savedEvent = yield* eventStore.append(nextEvent);
149
- nextReadModel = yield* projectEvent(nextReadModel, savedEvent);
158
+ nextCommandReadModel = yield* projectEvent(nextCommandReadModel, savedEvent);
159
yield* projectionPipeline.projectEvent(savedEvent);
160
committedEvents.push(savedEvent);
161
}
@@ -172,7 +181,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
181
return {
182
committedEvents,
183
lastSequence: lastSavedEvent.sequence,
175
- nextReadModel,
184
+ nextCommandReadModel,
185
} as const;
186
}),
187
)
@@ -184,7 +193,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
193
),
194
);
195
187
- readModel = committedCommand.nextReadModel;
196
+ commandReadModel = committedCommand.nextCommandReadModel;
197
for (const [index, event] of committedCommand.committedEvents.entries()) {
198
yield* PubSub.publish(eventPubSub, event);
199
if (index === 0) {
@@ -242,7 +251,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
251
).pipe(
252
Effect.annotateLogs({
253
commandId: envelope.command.commandId,
245
- snapshotSequence: readModel.snapshotSequence,
254
+ snapshotSequence: commandReadModel.snapshotSequence,
255
}),
256
),
257
),
@@ -255,7 +264,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
264
aggregateKind: aggregateRef.aggregateKind,
265
aggregateId: aggregateRef.aggregateId,
266
acceptedAt: new Date().toISOString(),
258
- resultSequence: readModel.snapshotSequence,
267
+ resultSequence: commandReadModel.snapshotSequence,
268
status: "rejected",
269
error: error.message,
270
})
@@ -270,17 +279,14 @@ const makeOrchestrationEngine = Effect.gen(function* () {
279
};
280
281
yield* projectionPipeline.bootstrap;
273
- readModel = yield* projectionSnapshotQuery.getSnapshot();
282
+ commandReadModel = yield* projectionSnapshotQuery.getCommandReadModel();
283
284
const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
285
yield* Effect.forkScoped(worker);
286
yield* Effect.logDebug("orchestration engine started").pipe(
278
- Effect.annotateLogs({ sequence: readModel.snapshotSequence }),
287
+ Effect.annotateLogs({ sequence: commandReadModel.snapshotSequence }),
288
);
289
281
- const getReadModel: OrchestrationEngineShape["getReadModel"] = () =>
282
- Effect.sync((): OrchestrationReadModel => readModel);
283
-
290
const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive) =>
291
eventStore.readFromSequence(fromSequenceExclusive);
292
@@ -292,7 +298,6 @@ const makeOrchestrationEngine = Effect.gen(function* () {
298
});
299
300
return {
295
- getReadModel,
301
readEvents,
302
dispatch,
303
// Each access creates a fresh PubSub subscription so that multiple
apps/server/src/orchestration/Layers/ProjectionPipeline.ts
+23
-1
@@ -739,9 +739,31 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
739
if (Option.isNone(existingRow)) {
740
return;
741
}
742
+
743
+ const retainedTurns = yield* projectionTurnRepository.listByThreadId({
744
+ threadId: event.payload.threadId,
745
+ });
746
+ let latestTurnId: ProjectionTurn["turnId"] = null;
747
+ let latestCheckpointTurnCount = -1;
748
+ for (let index = 0; index < retainedTurns.length; index += 1) {
749
+ const turn = retainedTurns[index];
750
+ if (
751
+ !turn ||
752
+ turn.turnId === null ||
753
+ turn.checkpointTurnCount === null ||
754
+ turn.checkpointTurnCount > event.payload.turnCount
755
+ ) {
756
+ continue;
757
+ }
758
+ if (turn.checkpointTurnCount > latestCheckpointTurnCount) {
759
+ latestCheckpointTurnCount = turn.checkpointTurnCount;
760
+ latestTurnId = turn.turnId;
761
+ }
762
+ }
763
+
764
yield* projectionThreadRepository.upsert({
765
...existingRow.value,
744
- latestTurnId: null,
766
+ latestTurnId,
767
updatedAt: event.occurredAt,
768
});
769
yield* refreshThreadShellSummary(event.payload.threadId);
apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
+375
@@ -12,6 +12,7 @@ import { Effect, Layer } from "effect";
12
import * as SqlClient from "effect/unstable/sql/SqlClient";
13
14
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
15
+import { RepositoryIdentityResolver } from "../../project/Services/RepositoryIdentityResolver.ts";
16
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
17
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
18
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
@@ -1029,4 +1030,378 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
1030
}
1031
}),
1032
);
1033
+
1034
+ it.effect("uses projection_threads.latest_turn_id for bulk command and shell snapshots", () =>
1035
+ Effect.gen(function* () {
1036
+ const snapshotQuery = yield* ProjectionSnapshotQuery;
1037
+ const sql = yield* SqlClient.SqlClient;
1038
+
1039
+ yield* sql`DELETE FROM projection_projects`;
1040
+ yield* sql`DELETE FROM projection_threads`;
1041
+ yield* sql`DELETE FROM projection_turns`;
1042
+ yield* sql`DELETE FROM projection_state`;
1043
+
1044
+ yield* sql`
1045
+ INSERT INTO projection_projects (
1046
+ project_id,
1047
+ title,
1048
+ workspace_root,
1049
+ default_model_selection_json,
1050
+ scripts_json,
1051
+ created_at,
1052
+ updated_at,
1053
+ deleted_at
1054
+ )
1055
+ VALUES (
1056
+ 'project-1',
1057
+ 'Project 1',
1058
+ '/tmp/project-1',
1059
+ '{"provider":"codex","model":"gpt-5-codex"}',
1060
+ '[]',
1061
+ '2026-04-03T00:00:00.000Z',
1062
+ '2026-04-03T00:00:01.000Z',
1063
+ NULL
1064
+ )
1065
+ `;
1066
+
1067
+ yield* sql`
1068
+ INSERT INTO projection_threads (
1069
+ thread_id,
1070
+ project_id,
1071
+ title,
1072
+ model_selection_json,
1073
+ runtime_mode,
1074
+ interaction_mode,
1075
+ branch,
1076
+ worktree_path,
1077
+ latest_turn_id,
1078
+ latest_user_message_at,
1079
+ pending_approval_count,
1080
+ pending_user_input_count,
1081
+ has_actionable_proposed_plan,
1082
+ created_at,
1083
+ updated_at,
1084
+ archived_at,
1085
+ deleted_at
1086
+ )
1087
+ VALUES (
1088
+ 'thread-1',
1089
+ 'project-1',
1090
+ 'Thread 1',
1091
+ '{"provider":"codex","model":"gpt-5-codex"}',
1092
+ 'full-access',
1093
+ 'default',
1094
+ NULL,
1095
+ NULL,
1096
+ 'turn-running',
1097
+ '2026-04-03T00:00:04.000Z',
1098
+ 0,
1099
+ 0,
1100
+ 0,
1101
+ '2026-04-03T00:00:02.000Z',
1102
+ '2026-04-03T00:00:03.000Z',
1103
+ NULL,
1104
+ NULL
1105
+ )
1106
+ `;
1107
+
1108
+ yield* sql`
1109
+ INSERT INTO projection_turns (
1110
+ thread_id,
1111
+ turn_id,
1112
+ pending_message_id,
1113
+ source_proposed_plan_thread_id,
1114
+ source_proposed_plan_id,
1115
+ assistant_message_id,
1116
+ state,
1117
+ requested_at,
1118
+ started_at,
1119
+ completed_at,
1120
+ checkpoint_turn_count,
1121
+ checkpoint_ref,
1122
+ checkpoint_status,
1123
+ checkpoint_files_json
1124
+ )
1125
+ VALUES
1126
+ (
1127
+ 'thread-1',
1128
+ 'turn-running',
1129
+ 'message-user-2',
1130
+ NULL,
1131
+ NULL,
1132
+ NULL,
1133
+ 'running',
1134
+ '2026-04-03T00:00:30.000Z',
1135
+ '2026-04-03T00:00:30.000Z',
1136
+ NULL,
1137
+ NULL,
1138
+ NULL,
1139
+ NULL,
1140
+ '[]'
1141
+ ),
1142
+ (
1143
+ 'thread-1',
1144
+ 'turn-completed',
1145
+ 'message-user-1',
1146
+ NULL,
1147
+ NULL,
1148
+ 'message-assistant-1',
1149
+ 'completed',
1150
+ '2026-04-03T00:00:05.000Z',
1151
+ '2026-04-03T00:00:06.000Z',
1152
+ '2026-04-03T00:00:20.000Z',
1153
+ NULL,
1154
+ NULL,
1155
+ NULL,
1156
+ '[]'
1157
+ )
1158
+ `;
1159
+
1160
+ yield* sql`
1161
+ INSERT INTO projection_state (projector, last_applied_sequence, updated_at)
1162
+ VALUES
1163
+ (${ORCHESTRATION_PROJECTOR_NAMES.projects}, 3, '2026-04-03T00:00:40.000Z'),
1164
+ (${ORCHESTRATION_PROJECTOR_NAMES.threads}, 3, '2026-04-03T00:00:40.000Z'),
1165
+ (${ORCHESTRATION_PROJECTOR_NAMES.threadMessages}, 3, '2026-04-03T00:00:40.000Z'),
1166
+ (${ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans}, 3, '2026-04-03T00:00:40.000Z'),
1167
+ (${ORCHESTRATION_PROJECTOR_NAMES.threadActivities}, 3, '2026-04-03T00:00:40.000Z'),
1168
+ (${ORCHESTRATION_PROJECTOR_NAMES.threadSessions}, 3, '2026-04-03T00:00:40.000Z'),
1169
+ (${ORCHESTRATION_PROJECTOR_NAMES.checkpoints}, 3, '2026-04-03T00:00:40.000Z')
1170
+ `;
1171
+
1172
+ const commandReadModel = yield* snapshotQuery.getCommandReadModel();
1173
+ assert.equal(commandReadModel.threads[0]?.latestTurn?.turnId, asTurnId("turn-running"));
1174
+ assert.equal(commandReadModel.threads[0]?.latestTurn?.state, "running");
1175
+
1176
+ const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
1177
+ assert.equal(shellSnapshot.threads[0]?.latestTurn?.turnId, asTurnId("turn-running"));
1178
+ assert.equal(shellSnapshot.threads[0]?.latestTurn?.state, "running");
1179
+
1180
+ const fullSnapshot = yield* snapshotQuery.getSnapshot();
1181
+ assert.equal(fullSnapshot.threads[0]?.latestTurn?.turnId, asTurnId("turn-running"));
1182
+ assert.equal(fullSnapshot.threads[0]?.latestTurn?.state, "running");
1183
+ }),
1184
+ );
1185
+
1186
+ it.effect("keeps deleted project and thread tombstones in the command read model", () =>
1187
+ Effect.gen(function* () {
1188
+ const snapshotQuery = yield* ProjectionSnapshotQuery;
1189
+ const sql = yield* SqlClient.SqlClient;
1190
+
1191
+ yield* sql`DELETE FROM projection_projects`;
1192
+ yield* sql`DELETE FROM projection_threads`;
1193
+ yield* sql`DELETE FROM projection_turns`;
1194
+ yield* sql`DELETE FROM projection_state`;
1195
+
1196
+ yield* sql`
1197
+ INSERT INTO projection_projects (
1198
+ project_id,
1199
+ title,
1200
+ workspace_root,
1201
+ default_model_selection_json,
1202
+ scripts_json,
1203
+ created_at,
1204
+ updated_at,
1205
+ deleted_at
1206
+ )
1207
+ VALUES (
1208
+ 'project-deleted',
1209
+ 'Deleted Project',
1210
+ '/tmp/deleted-project',
1211
+ '{"provider":"codex","model":"gpt-5-codex"}',
1212
+ '[]',
1213
+ '2026-04-05T00:00:00.000Z',
1214
+ '2026-04-05T00:00:01.000Z',
1215
+ '2026-04-05T00:00:02.000Z'
1216
+ )
1217
+ `;
1218
+
1219
+ yield* sql`
1220
+ INSERT INTO projection_threads (
1221
+ thread_id,
1222
+ project_id,
1223
+ title,
1224
+ model_selection_json,
1225
+ runtime_mode,
1226
+ interaction_mode,
1227
+ branch,
1228
+ worktree_path,
1229
+ latest_turn_id,
1230
+ latest_user_message_at,
1231
+ pending_approval_count,
1232
+ pending_user_input_count,
1233
+ has_actionable_proposed_plan,
1234
+ created_at,
1235
+ updated_at,
1236
+ archived_at,
1237
+ deleted_at
1238
+ )
1239
+ VALUES (
1240
+ 'thread-deleted',
1241
+ 'project-deleted',
1242
+ 'Deleted Thread',
1243
+ '{"provider":"codex","model":"gpt-5-codex"}',
1244
+ 'full-access',
1245
+ 'default',
1246
+ NULL,
1247
+ NULL,
1248
+ 'turn-deleted',
1249
+ NULL,
1250
+ 0,
1251
+ 0,
1252
+ 0,
1253
+ '2026-04-05T00:00:03.000Z',
1254
+ '2026-04-05T00:00:04.000Z',
1255
+ NULL,
1256
+ '2026-04-05T00:00:05.000Z'
1257
+ )
1258
+ `;
1259
+
1260
+ yield* sql`
1261
+ INSERT INTO projection_turns (
1262
+ thread_id,
1263
+ turn_id,
1264
+ pending_message_id,
1265
+ source_proposed_plan_thread_id,
1266
+ source_proposed_plan_id,
1267
+ assistant_message_id,
1268
+ state,
1269
+ requested_at,
1270
+ started_at,
1271
+ completed_at,
1272
+ checkpoint_turn_count,
1273
+ checkpoint_ref,
1274
+ checkpoint_status,
1275
+ checkpoint_files_json
1276
+ )
1277
+ VALUES (
1278
+ 'thread-deleted',
1279
+ 'turn-deleted',
1280
+ 'message-deleted-user',
1281
+ NULL,
1282
+ NULL,
1283
+ 'message-deleted-assistant',
1284
+ 'completed',
1285
+ '2026-04-05T00:00:04.100Z',
1286
+ '2026-04-05T00:00:04.200Z',
1287
+ '2026-04-05T00:00:04.300Z',
1288
+ NULL,
1289
+ NULL,
1290
+ NULL,
1291
+ '[]'
1292
+ )
1293
+ `;
1294
+
1295
+ const commandReadModel = yield* snapshotQuery.getCommandReadModel();
1296
+ assert.equal(commandReadModel.projects[0]?.id, asProjectId("project-deleted"));
1297
+ assert.equal(commandReadModel.projects[0]?.deletedAt, "2026-04-05T00:00:02.000Z");
1298
+ assert.equal(commandReadModel.threads[0]?.id, ThreadId.make("thread-deleted"));
1299
+ assert.equal(commandReadModel.threads[0]?.deletedAt, "2026-04-05T00:00:05.000Z");
1300
+ assert.equal(commandReadModel.threads[0]?.latestTurn?.turnId, asTurnId("turn-deleted"));
1301
+ assert.equal(commandReadModel.threads[0]?.latestTurn?.state, "completed");
1302
+
1303
+ const fullSnapshot = yield* snapshotQuery.getSnapshot();
1304
+ assert.equal(fullSnapshot.threads[0]?.id, ThreadId.make("thread-deleted"));
1305
+ assert.equal(fullSnapshot.threads[0]?.latestTurn?.turnId, asTurnId("turn-deleted"));
1306
+ assert.equal(fullSnapshot.threads[0]?.latestTurn?.state, "completed");
1307
+
1308
+ const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
1309
+ assert.equal(shellSnapshot.projects.length, 0);
1310
+ assert.equal(shellSnapshot.threads.length, 0);
1311
+ }),
1312
+ );
1313
});
1314
+
1315
+it.effect(
1316
+ "ProjectionSnapshotQuery dedupes repository identity resolution by workspace root and skips deleted projects for shell snapshots",
1317
+ () => {
1318
+ const resolveCalls: string[] = [];
1319
+ const layer = OrchestrationProjectionSnapshotQueryLive.pipe(
1320
+ Layer.provideMerge(
1321
+ Layer.succeed(RepositoryIdentityResolver, {
1322
+ resolve: (cwd: string) =>
1323
+ Effect.sync(() => {
1324
+ resolveCalls.push(cwd);
1325
+ return {
1326
+ canonicalKey: `github.com/acme${cwd}`,
1327
+ locator: {
1328
+ source: "git-remote" as const,
1329
+ remoteName: "origin",
1330
+ remoteUrl: `https://github.com/acme${cwd}.git`,
1331
+ },
1332
+ rootPath: cwd,
1333
+ };
1334
+ }),
1335
+ }),
1336
+ ),
1337
+ Layer.provideMerge(SqlitePersistenceMemory),
1338
+ );
1339
+
1340
+ return Effect.gen(function* () {
1341
+ const snapshotQuery = yield* ProjectionSnapshotQuery;
1342
+ const sql = yield* SqlClient.SqlClient;
1343
+
1344
+ yield* sql`DELETE FROM projection_projects`;
1345
+ yield* sql`DELETE FROM projection_threads`;
1346
+ yield* sql`DELETE FROM projection_turns`;
1347
+ yield* sql`DELETE FROM projection_state`;
1348
+
1349
+ yield* sql`
1350
+ INSERT INTO projection_projects (
1351
+ project_id,
1352
+ title,
1353
+ workspace_root,
1354
+ default_model_selection_json,
1355
+ scripts_json,
1356
+ created_at,
1357
+ updated_at,
1358
+ deleted_at
1359
+ )
1360
+ VALUES
1361
+ (
1362
+ 'project-1',
1363
+ 'Shared Project 1',
1364
+ '/tmp/shared-root',
1365
+ '{"provider":"codex","model":"gpt-5-codex"}',
1366
+ '[]',
1367
+ '2026-04-04T00:00:00.000Z',
1368
+ '2026-04-04T00:00:01.000Z',
1369
+ NULL
1370
+ ),
1371
+ (
1372
+ 'project-2',
1373
+ 'Shared Project 2',
1374
+ '/tmp/shared-root',
1375
+ '{"provider":"codex","model":"gpt-5-codex"}',
1376
+ '[]',
1377
+ '2026-04-04T00:00:02.000Z',
1378
+ '2026-04-04T00:00:03.000Z',
1379
+ NULL
1380
+ ),
1381
+ (
1382
+ 'project-3',
1383
+ 'Deleted Project',
1384
+ '/tmp/deleted-root',
1385
+ '{"provider":"codex","model":"gpt-5-codex"}',
1386
+ '[]',
1387
+ '2026-04-04T00:00:04.000Z',
1388
+ '2026-04-04T00:00:05.000Z',
1389
+ '2026-04-04T00:00:06.000Z'
1390
+ )
1391
+ `;
1392
+
1393
+ const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
1394
+ assert.deepStrictEqual(resolveCalls.toSorted(), ["/tmp/shared-root"]);
1395
+ assert.equal(shellSnapshot.projects.length, 2);
1396
+ assert.equal(shellSnapshot.projects[0]?.repositoryIdentity?.rootPath, "/tmp/shared-root");
1397
+ assert.equal(shellSnapshot.projects[1]?.repositoryIdentity?.rootPath, "/tmp/shared-root");
1398
+
1399
+ resolveCalls.length = 0;
1400
+
1401
+ const fullSnapshot = yield* snapshotQuery.getSnapshot();
1402
+ assert.deepStrictEqual(resolveCalls.toSorted(), ["/tmp/deleted-root", "/tmp/shared-root"]);
1403
+ assert.equal(fullSnapshot.projects.length, 3);
1404
+ assert.equal(fullSnapshot.projects[2]?.repositoryIdentity?.rootPath, "/tmp/deleted-root");
1405
+ }).pipe(Effect.provide(layer));
1406
+ },
1407
+);
apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
+299
-43
@@ -219,6 +219,20 @@ function mapProjectShellRow(
219
};
220
}
221
222
+function mapProposedPlanRow(
223
+ row: Schema.Schema.Type<typeof ProjectionThreadProposedPlanDbRowSchema>,
224
+): OrchestrationProposedPlan {
225
+ return {
226
+ id: row.planId,
227
+ turnId: row.turnId,
228
+ planMarkdown: row.planMarkdown,
229
+ implementedAt: row.implementedAt,
230
+ implementationThreadId: row.implementationThreadId,
231
+ createdAt: row.createdAt,
232
+ updatedAt: row.updatedAt,
233
+ };
234
+}
235
+
236
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
237
return (cause: unknown): ProjectionRepositoryError =>
238
Schema.isSchemaError(cause)
@@ -230,6 +244,37 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
244
const sql = yield* SqlClient.SqlClient;
245
const repositoryIdentityResolver = yield* RepositoryIdentityResolver;
246
const repositoryIdentityResolutionConcurrency = 4;
247
+ const resolveRepositoryIdentitiesForProjects = Effect.fn(
248
+ "ProjectionSnapshotQuery.resolveRepositoryIdentitiesForProjects",
249
+ )(function* (
250
+ projectRows: ReadonlyArray<Schema.Schema.Type<typeof ProjectionProjectDbRowSchema>>,
251
+ options?: {
252
+ readonly includeDeleted?: boolean;
253
+ },
254
+ ) {
255
+ const filteredProjectRows =
256
+ options?.includeDeleted === true
257
+ ? projectRows
258
+ : projectRows.filter((row) => row.deletedAt === null);
259
+ const uniqueWorkspaceRoots = [...new Set(filteredProjectRows.map((row) => row.workspaceRoot))];
260
+ const repositoryIdentityByWorkspaceRoot = new Map(
261
+ yield* Effect.forEach(
262
+ uniqueWorkspaceRoots,
263
+ (workspaceRoot) =>
264
+ repositoryIdentityResolver
265
+ .resolve(workspaceRoot)
266
+ .pipe(Effect.map((identity) => [workspaceRoot, identity] as const)),
267
+ { concurrency: repositoryIdentityResolutionConcurrency },
268
+ ),
269
+ );
270
+
271
+ return new Map(
272
+ filteredProjectRows.map((row) => [
273
+ row.projectId,
274
+ repositoryIdentityByWorkspaceRoot.get(row.workspaceRoot) ?? null,
275
+ ]),
276
+ );
277
+ });
278
279
const listProjectRows = SqlSchema.findAll({
280
Request: Schema.Void,
@@ -335,7 +380,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
380
FROM projection_thread_activities
381
ORDER BY
382
thread_id ASC,
338
- CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
383
sequence ASC,
384
created_at ASC,
385
activity_id ASC
@@ -389,18 +433,46 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
433
execute: () =>
434
sql`
435
SELECT
392
- thread_id AS "threadId",
393
- turn_id AS "turnId",
394
- state,
395
- requested_at AS "requestedAt",
396
- started_at AS "startedAt",
397
- completed_at AS "completedAt",
398
- assistant_message_id AS "assistantMessageId",
399
- source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
400
- source_proposed_plan_id AS "sourceProposedPlanId"
401
- FROM projection_turns
402
- WHERE turn_id IS NOT NULL
403
- ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
436
+ turns.thread_id AS "threadId",
437
+ turns.turn_id AS "turnId",
438
+ turns.state,
439
+ turns.requested_at AS "requestedAt",
440
+ turns.started_at AS "startedAt",
441
+ turns.completed_at AS "completedAt",
442
+ turns.assistant_message_id AS "assistantMessageId",
443
+ turns.source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
444
+ turns.source_proposed_plan_id AS "sourceProposedPlanId"
445
+ FROM projection_threads threads
446
+ JOIN projection_turns turns
447
+ ON turns.thread_id = threads.thread_id
448
+ AND turns.turn_id = threads.latest_turn_id
449
+ WHERE threads.latest_turn_id IS NOT NULL
450
+ ORDER BY turns.thread_id ASC
451
+ `,
452
+ });
453
+
454
+ const listActiveLatestTurnRows = SqlSchema.findAll({
455
+ Request: Schema.Void,
456
+ Result: ProjectionLatestTurnDbRowSchema,
457
+ execute: () =>
458
+ sql`
459
+ SELECT
460
+ turns.thread_id AS "threadId",
461
+ turns.turn_id AS "turnId",
462
+ turns.state,
463
+ turns.requested_at AS "requestedAt",
464
+ turns.started_at AS "startedAt",
465
+ turns.completed_at AS "completedAt",
466
+ turns.assistant_message_id AS "assistantMessageId",
467
+ turns.source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
468
+ turns.source_proposed_plan_id AS "sourceProposedPlanId"
469
+ FROM projection_threads threads
470
+ JOIN projection_turns turns
471
+ ON turns.thread_id = threads.thread_id
472
+ AND turns.turn_id = threads.latest_turn_id
473
+ WHERE threads.deleted_at IS NULL
474
+ AND threads.latest_turn_id IS NOT NULL
475
+ ORDER BY turns.thread_id ASC
476
`,
477
});
478
@@ -594,7 +666,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
666
FROM projection_thread_activities
667
WHERE thread_id = ${threadId}
668
ORDER BY
597
- CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
669
sequence ASC,
670
created_at ASC,
671
activity_id ASC
@@ -892,15 +963,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
963
});
964
}
965
895
- const repositoryIdentities = new Map(
896
- yield* Effect.forEach(
897
- projectRows,
898
- (row) =>
899
- repositoryIdentityResolver
900
- .resolve(row.workspaceRoot)
901
- .pipe(Effect.map((identity) => [row.projectId, identity] as const)),
902
- { concurrency: repositoryIdentityResolutionConcurrency },
903
- ),
966
+ const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(
967
+ projectRows,
968
+ { includeDeleted: true },
969
);
970
971
const projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({
@@ -958,6 +1023,199 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
1023
}),
1024
);
1025
1026
+ const getCommandReadModel: ProjectionSnapshotQueryShape["getCommandReadModel"] = () =>
1027
+ sql
1028
+ .withTransaction(
1029
+ Effect.all([
1030
+ listProjectRows(undefined).pipe(
1031
+ Effect.mapError(
1032
+ toPersistenceSqlOrDecodeError(
1033
+ "ProjectionSnapshotQuery.getCommandReadModel:listProjects:query",
1034
+ "ProjectionSnapshotQuery.getCommandReadModel:listProjects:decodeRows",
1035
+ ),
1036
+ ),
1037
+ ),
1038
+ listThreadRows(undefined).pipe(
1039
+ Effect.mapError(
1040
+ toPersistenceSqlOrDecodeError(
1041
+ "ProjectionSnapshotQuery.getCommandReadModel:listThreads:query",
1042
+ "ProjectionSnapshotQuery.getCommandReadModel:listThreads:decodeRows",
1043
+ ),
1044
+ ),
1045
+ ),
1046
+ listThreadProposedPlanRows(undefined).pipe(
1047
+ Effect.mapError(
1048
+ toPersistenceSqlOrDecodeError(
1049
+ "ProjectionSnapshotQuery.getCommandReadModel:listThreadProposedPlans:query",
1050
+ "ProjectionSnapshotQuery.getCommandReadModel:listThreadProposedPlans:decodeRows",
1051
+ ),
1052
+ ),
1053
+ ),
1054
+ listThreadSessionRows(undefined).pipe(
1055
+ Effect.mapError(
1056
+ toPersistenceSqlOrDecodeError(
1057
+ "ProjectionSnapshotQuery.getCommandReadModel:listThreadSessions:query",
1058
+ "ProjectionSnapshotQuery.getCommandReadModel:listThreadSessions:decodeRows",
1059
+ ),
1060
+ ),
1061
+ ),
1062
+ listLatestTurnRows(undefined).pipe(
1063
+ Effect.mapError(
1064
+ toPersistenceSqlOrDecodeError(
1065
+ "ProjectionSnapshotQuery.getCommandReadModel:listLatestTurns:query",
1066
+ "ProjectionSnapshotQuery.getCommandReadModel:listLatestTurns:decodeRows",
1067
+ ),
1068
+ ),
1069
+ ),
1070
+ listProjectionStateRows(undefined).pipe(
1071
+ Effect.mapError(
1072
+ toPersistenceSqlOrDecodeError(
1073
+ "ProjectionSnapshotQuery.getCommandReadModel:listProjectionState:query",
1074
+ "ProjectionSnapshotQuery.getCommandReadModel:listProjectionState:decodeRows",
1075
+ ),
1076
+ ),
1077
+ ),
1078
+ ]),
1079
+ )
1080
+ .pipe(
1081
+ Effect.flatMap(
1082
+ ([projectRows, threadRows, proposedPlanRows, sessionRows, latestTurnRows, stateRows]) =>
1083
+ Effect.sync(() => {
1084
+ let updatedAt: string | null = null;
1085
+ const projects: OrchestrationProject[] = [];
1086
+ const threads: OrchestrationThread[] = [];
1087
+
1088
+ for (let index = 0; index < projectRows.length; index += 1) {
1089
+ const row = projectRows[index];
1090
+ if (!row) {
1091
+ continue;
1092
+ }
1093
+ updatedAt = maxIso(updatedAt, row.updatedAt);
1094
+ projects.push({
1095
+ id: row.projectId,
1096
+ title: row.title,
1097
+ workspaceRoot: row.workspaceRoot,
1098
+ defaultModelSelection: row.defaultModelSelection,
1099
+ scripts: row.scripts,
1100
+ createdAt: row.createdAt,
1101
+ updatedAt: row.updatedAt,
1102
+ deletedAt: row.deletedAt,
1103
+ });
1104
+ }
1105
+ for (let index = 0; index < threadRows.length; index += 1) {
1106
+ const row = threadRows[index];
1107
+ if (!row) {
1108
+ continue;
1109
+ }
1110
+ updatedAt = maxIso(updatedAt, row.updatedAt);
1111
+ }
1112
+ for (let index = 0; index < proposedPlanRows.length; index += 1) {
1113
+ const row = proposedPlanRows[index];
1114
+ if (!row) {
1115
+ continue;
1116
+ }
1117
+ updatedAt = maxIso(updatedAt, row.updatedAt);
1118
+ }
1119
+ for (let index = 0; index < sessionRows.length; index += 1) {
1120
+ const row = sessionRows[index];
1121
+ if (!row) {
1122
+ continue;
1123
+ }
1124
+ updatedAt = maxIso(updatedAt, row.updatedAt);
1125
+ }
1126
+ for (let index = 0; index < latestTurnRows.length; index += 1) {
1127
+ const row = latestTurnRows[index];
1128
+ if (!row) {
1129
+ continue;
1130
+ }
1131
+ updatedAt = maxIso(updatedAt, row.requestedAt);
1132
+ if (row.startedAt !== null) {
1133
+ updatedAt = maxIso(updatedAt, row.startedAt);
1134
+ }
1135
+ if (row.completedAt !== null) {
1136
+ updatedAt = maxIso(updatedAt, row.completedAt);
1137
+ }
1138
+ }
1139
+ for (let index = 0; index < stateRows.length; index += 1) {
1140
+ const row = stateRows[index];
1141
+ if (!row) {
1142
+ continue;
1143
+ }
1144
+ updatedAt = maxIso(updatedAt, row.updatedAt);
1145
+ }
1146
+
1147
+ const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();
1148
+ for (let index = 0; index < latestTurnRows.length; index += 1) {
1149
+ const row = latestTurnRows[index];
1150
+ if (!row) {
1151
+ continue;
1152
+ }
1153
+ latestTurnByThread.set(row.threadId, mapLatestTurn(row));
1154
+ }
1155
+ const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();
1156
+ const sessionByThread = new Map<string, OrchestrationSession>();
1157
+
1158
+ for (let index = 0; index < sessionRows.length; index += 1) {
1159
+ const row = sessionRows[index];
1160
+ if (!row) {
1161
+ continue;
1162
+ }
1163
+ sessionByThread.set(row.threadId, mapSessionRow(row));
1164
+ }
1165
+
1166
+ for (let index = 0; index < proposedPlanRows.length; index += 1) {
1167
+ const row = proposedPlanRows[index];
1168
+ if (!row) {
1169
+ continue;
1170
+ }
1171
+ const threadProposedPlans = proposedPlansByThread.get(row.threadId) ?? [];
1172
+ threadProposedPlans.push(mapProposedPlanRow(row));
1173
+ proposedPlansByThread.set(row.threadId, threadProposedPlans);
1174
+ }
1175
+
1176
+ for (let index = 0; index < threadRows.length; index += 1) {
1177
+ const row = threadRows[index];
1178
+ if (!row) {
1179
+ continue;
1180
+ }
1181
+ threads.push({
1182
+ id: row.threadId,
1183
+ projectId: row.projectId,
1184
+ title: row.title,
1185
+ modelSelection: row.modelSelection,
1186
+ runtimeMode: row.runtimeMode,
1187
+ interactionMode: row.interactionMode,
1188
+ branch: row.branch,
1189
+ worktreePath: row.worktreePath,
1190
+ latestTurn: latestTurnByThread.get(row.threadId) ?? null,
1191
+ createdAt: row.createdAt,
1192
+ updatedAt: row.updatedAt,
1193
+ archivedAt: row.archivedAt,
1194
+ deletedAt: row.deletedAt,
1195
+ messages: [],
1196
+ proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
1197
+ activities: [],
1198
+ checkpoints: [],
1199
+ session: sessionByThread.get(row.threadId) ?? null,
1200
+ });
1201
+ }
1202
+
1203
+ return {
1204
+ snapshotSequence: computeSnapshotSequence(stateRows),
1205
+ projects,
1206
+ threads,
1207
+ updatedAt: updatedAt ?? new Date(0).toISOString(),
1208
+ } satisfies OrchestrationReadModel;
1209
+ }),
1210
+ ),
1211
+ Effect.mapError((error) => {
1212
+ if (isPersistenceError(error)) {
1213
+ return error;
1214
+ }
1215
+ return toPersistenceSqlError("ProjectionSnapshotQuery.getCommandReadModel:query")(error);
1216
+ }),
1217
+ );
1218
+
1219
const getShellSnapshot: ProjectionSnapshotQueryShape["getShellSnapshot"] = () =>
1220
sql
1221
.withTransaction(
@@ -986,7 +1244,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
1244
),
1245
),
1246
),
989
- listLatestTurnRows(undefined).pipe(
1247
+ listActiveLatestTurnRows(undefined).pipe(
1248
Effect.mapError(
1249
toPersistenceSqlOrDecodeError(
1250
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query",
@@ -1030,16 +1288,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
1288
updatedAt = maxIso(updatedAt, row.updatedAt);
1289
}
1290
1033
- const repositoryIdentities = new Map(
1034
- yield* Effect.forEach(
1035
- projectRows,
1036
- (row) =>
1037
- repositoryIdentityResolver
1038
- .resolve(row.workspaceRoot)
1039
- .pipe(Effect.map((identity) => [row.projectId, identity] as const)),
1040
- { concurrency: repositoryIdentityResolutionConcurrency },
1041
- ),
1042
- );
1291
+ const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(projectRows);
1292
const latestTurnByThread = new Map(
1293
latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),
1294
);
@@ -1097,6 +1346,19 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
1346
}),
1347
);
1348
1349
+ const getSnapshotSequence: ProjectionSnapshotQueryShape["getSnapshotSequence"] = () =>
1350
+ listProjectionStateRows(undefined).pipe(
1351
+ Effect.mapError(
1352
+ toPersistenceSqlOrDecodeError(
1353
+ "ProjectionSnapshotQuery.getSnapshotSequence:query",
1354
+ "ProjectionSnapshotQuery.getSnapshotSequence:decodeRows",
1355
+ ),
1356
+ ),
1357
+ Effect.map((stateRows) => ({
1358
+ snapshotSequence: computeSnapshotSequence(stateRows),
1359
+ })),
1360
+ );
1361
+
1362
const getCounts: ProjectionSnapshotQueryShape["getCounts"] = () =>
1363
readProjectionCounts(undefined).pipe(
1364
Effect.mapError(
@@ -1376,15 +1638,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
1638
}
1639
return message;
1640
}),
1379
- proposedPlans: proposedPlanRows.map((row) => ({
1380
- id: row.planId,
1381
- turnId: row.turnId,
1382
- planMarkdown: row.planMarkdown,
1383
- implementedAt: row.implementedAt,
1384
- implementationThreadId: row.implementationThreadId,
1385
- createdAt: row.createdAt,
1386
- updatedAt: row.updatedAt,
1387
- })),
1641
+ proposedPlans: proposedPlanRows.map(mapProposedPlanRow),
1642
activities: activityRows.map((row) => {
1643
const activity = {
1644
id: row.activityId,
@@ -1422,8 +1676,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
1676
});
1677
1678
return {
1679
+ getCommandReadModel,
1680
getSnapshot,
1681
getShellSnapshot,
1682
+ getSnapshotSequence,
1683
getCounts,
1684
getActiveProjectByWorkspaceRoot,
1685
getProjectShellById,
apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
+32
-24
@@ -45,6 +45,7 @@ import {
45
} from "./ProviderCommandReactor.ts";
46
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
47
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
48
+import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
49
import * as NodeServices from "@effect/platform-node/NodeServices";
50
import { ServerSettingsService } from "../../serverSettings.ts";
51
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
@@ -79,7 +80,7 @@ async function waitFor(
80
81
describe("ProviderCommandReactor", () => {
82
let runtime: ManagedRuntime.ManagedRuntime<
82
- OrchestrationEngineService | ProviderCommandReactor,
83
+ OrchestrationEngineService | ProviderCommandReactor | ProjectionSnapshotQuery,
84
unknown
85
> | null = null;
86
let scope: Scope.Closeable | null = null;
@@ -318,8 +319,13 @@ describe("ProviderCommandReactor", () => {
319
Layer.provide(RepositoryIdentityResolverLive),
320
Layer.provide(SqlitePersistenceMemory),
321
);
322
+ const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
323
+ Layer.provide(RepositoryIdentityResolverLive),
324
+ Layer.provide(SqlitePersistenceMemory),
325
+ );
326
const layer = ProviderCommandReactorLive.pipe(
327
Layer.provideMerge(orchestrationLayer),
328
+ Layer.provideMerge(projectionSnapshotLayer),
329
Layer.provideMerge(Layer.succeed(ProviderService, service)),
330
Layer.provideMerge(
331
Layer.mock(GitWorkflowService)({
@@ -348,6 +354,7 @@ describe("ProviderCommandReactor", () => {
354
runtime = ManagedRuntime.make(layer);
355
356
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
357
+ const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
358
const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
359
scope = await Effect.runPromise(Scope.make("sequential"));
360
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
@@ -382,6 +389,7 @@ describe("ProviderCommandReactor", () => {
389
390
return {
391
engine,
392
+ readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
393
startSession,
394
sendTurn,
395
interruptTurn,
@@ -431,7 +439,7 @@ describe("ProviderCommandReactor", () => {
439
runtimeMode: "approval-required",
440
});
441
434
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
442
+ const readModel = await harness.readModel();
443
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
444
expect(thread?.session?.threadId).toBe("thread-1");
445
expect(thread?.session?.runtimeMode).toBe("approval-required");
@@ -476,13 +484,13 @@ describe("ProviderCommandReactor", () => {
484
});
485
486
await waitFor(async () => {
479
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
487
+ const readModel = await harness.readModel();
488
return (
489
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
490
"Generated title"
491
);
492
});
485
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
493
+ const readModel = await harness.readModel();
494
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
495
expect(thread?.title).toBe("Generated title");
496
});
@@ -522,7 +530,7 @@ describe("ProviderCommandReactor", () => {
530
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
531
expect(harness.generateThreadTitle).not.toHaveBeenCalled();
532
525
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
533
+ const readModel = await harness.readModel();
534
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
535
expect(thread?.title).toBe("Keep this custom title");
536
});
@@ -566,14 +574,14 @@ describe("ProviderCommandReactor", () => {
574
575
await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1);
576
await waitFor(async () => {
569
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
577
+ const readModel = await harness.readModel();
578
return (
579
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
580
"Reconnect spinner resume bug"
581
);
582
});
583
576
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
584
+ const readModel = await harness.readModel();
585
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
586
expect(thread?.title).toBe("Reconnect spinner resume bug");
587
});
@@ -902,7 +910,7 @@ describe("ProviderCommandReactor", () => {
910
},
911
});
912
905
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
913
+ const readModel = await harness.readModel();
914
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
915
expect(thread?.session?.providerName).toBe("claudeAgent");
916
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("claudeAgent"));
@@ -1014,7 +1022,7 @@ describe("ProviderCommandReactor", () => {
1022
resumeCursor: { opaque: "resume-1" },
1023
});
1024
1017
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
1025
+ const readModel = await harness.readModel();
1026
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
1027
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work"));
1028
});
@@ -1205,7 +1213,7 @@ describe("ProviderCommandReactor", () => {
1213
);
1214
1215
await waitFor(async () => {
1208
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
1216
+ const readModel = await harness.readModel();
1217
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
1218
return thread?.runtimeMode === "approval-required";
1219
});
@@ -1239,7 +1247,7 @@ describe("ProviderCommandReactor", () => {
1247
threadId: ThreadId.make("thread-1"),
1248
});
1249
1242
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
1250
+ const readModel = await harness.readModel();
1251
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
1252
expect(thread?.session?.threadId).toBe("thread-1");
1253
expect(thread?.session?.runtimeMode).toBe("approval-required");
@@ -1342,7 +1350,7 @@ describe("ProviderCommandReactor", () => {
1350
);
1351
1352
await waitFor(async () => {
1345
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
1353
+ const readModel = await harness.readModel();
1354
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
1355
return thread?.runtimeMode === "approval-required";
1356
});
@@ -1352,7 +1360,7 @@ describe("ProviderCommandReactor", () => {
1360
expect(harness.stopSession.mock.calls.length).toBe(0);
1361
expect(harness.sendTurn.mock.calls.length).toBe(1);
1362
1355
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
1363
+ const readModel = await harness.readModel();
1364
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
1365
expect(thread?.session?.threadId).toBe("thread-1");
1366
expect(thread?.session?.runtimeMode).toBe("full-access");
@@ -1404,7 +1412,7 @@ describe("ProviderCommandReactor", () => {
1412
);
1413
1414
await waitFor(async () => {
1407
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
1415
+ const readModel = await harness.readModel();
1416
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
1417
return (
1418
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
@@ -1416,7 +1424,7 @@ describe("ProviderCommandReactor", () => {
1424
expect(harness.sendTurn.mock.calls.length).toBe(1);
1425
expect(harness.stopSession.mock.calls.length).toBe(0);
1426
1419
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
1427
+ const readModel = await harness.readModel();
1428
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
1429
expect(thread?.session?.threadId).toBe("thread-1");
1430
expect(thread?.session?.providerName).toBe("codex");
@@ -1475,7 +1483,7 @@ describe("ProviderCommandReactor", () => {
1483
);
1484
1485
await waitFor(async () => {
1478
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
1486
+ const readModel = await harness.readModel();
1487
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
1488
return (
1489
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
@@ -1485,7 +1493,7 @@ describe("ProviderCommandReactor", () => {
1493
1494
expect(harness.startSession.mock.calls.length).toBe(0);
1495
expect(harness.sendTurn.mock.calls.length).toBe(0);
1488
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
1496
+ const readModel = await harness.readModel();
1497
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
1498
expect(
1499
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
@@ -1639,7 +1647,7 @@ describe("ProviderCommandReactor", () => {
1647
);
1648
1649
await waitFor(async () => {
1642
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
1650
+ const readModel = await harness.readModel();
1651
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
1652
return (
1653
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
@@ -1649,7 +1657,7 @@ describe("ProviderCommandReactor", () => {
1657
1658
expect(harness.startSession.mock.calls.length).toBe(0);
1659
expect(harness.sendTurn.mock.calls.length).toBe(0);
1652
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
1660
+ const readModel = await harness.readModel();
1661
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
1662
expect(
1663
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
@@ -1810,7 +1818,7 @@ describe("ProviderCommandReactor", () => {
1818
);
1819
1820
await waitFor(async () => {
1813
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
1821
+ const readModel = await harness.readModel();
1822
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
1823
if (!thread) return false;
1824
return thread.activities.some(
@@ -1818,7 +1826,7 @@ describe("ProviderCommandReactor", () => {
1826
);
1827
});
1828
1821
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
1829
+ const readModel = await harness.readModel();
1830
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
1831
expect(thread).toBeDefined();
1832
@@ -1919,7 +1927,7 @@ describe("ProviderCommandReactor", () => {
1927
);
1928
1929
await waitFor(async () => {
1922
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
1930
+ const readModel = await harness.readModel();
1931
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
1932
if (!thread) return false;
1933
return thread.activities.some(
@@ -1927,7 +1935,7 @@ describe("ProviderCommandReactor", () => {
1935
);
1936
});
1937
1930
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
1938
+ const readModel = await harness.readModel();
1939
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
1940
expect(thread).toBeDefined();
1941
@@ -1983,7 +1991,7 @@ describe("ProviderCommandReactor", () => {
1991
);
1992
1993
await waitFor(() => harness.stopSession.mock.calls.length === 1);
1986
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
1994
+ const readModel = await harness.readModel();
1995
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
1996
expect(thread?.session).not.toBeNull();
1997
expect(thread?.session?.status).toBe("stopped");
apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
+27
-20
@@ -5,6 +5,7 @@ import {
5
type ModelSelection,
6
type OrchestrationEvent,
7
ProviderDriverKind,
8
+ type ProjectId,
9
type OrchestrationSession,
10
ThreadId,
11
type ProviderSession,
@@ -22,6 +23,7 @@ import type { ProviderServiceError } from "../../provider/Errors.ts";
23
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
24
import { ProviderService } from "../../provider/Services/ProviderService.ts";
25
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
26
+import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
27
import {
28
ProviderCommandReactor,
29
type ProviderCommandReactorShape,
@@ -167,6 +169,7 @@ function buildGeneratedWorktreeBranchName(raw: string): string {
169
170
const make = Effect.gen(function* () {
171
const orchestrationEngine = yield* OrchestrationEngineService;
172
+ const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
173
const providerService = yield* ProviderService;
174
const gitWorkflow = yield* GitWorkflowService;
175
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
@@ -267,9 +270,16 @@ const make = Effect.gen(function* () {
270
});
271
});
272
273
+ const resolveProject = Effect.fnUntraced(function* (projectId: ProjectId) {
274
+ return yield* projectionSnapshotQuery
275
+ .getProjectShellById(projectId)
276
+ .pipe(Effect.map(Option.getOrUndefined));
277
+ });
278
+
279
const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {
271
- const readModel = yield* orchestrationEngine.getReadModel();
272
- return readModel.threads.find((entry) => entry.id === threadId);
280
+ return yield* projectionSnapshotQuery
281
+ .getThreadDetailById(threadId)
282
+ .pipe(Effect.map(Option.getOrUndefined));
283
});
284
285
const ensureSessionForThread = Effect.fn("ensureSessionForThread")(function* (
@@ -279,8 +289,7 @@ const make = Effect.gen(function* () {
289
readonly modelSelection?: ModelSelection;
290
},
291
) {
282
- const readModel = yield* orchestrationEngine.getReadModel();
283
- const thread = readModel.threads.find((entry) => entry.id === threadId);
292
+ const thread = yield* resolveThread(threadId);
293
if (!thread) {
294
return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
295
}
@@ -375,9 +384,10 @@ const make = Effect.gen(function* () {
384
});
385
}
386
}
387
+ const project = yield* resolveProject(thread.projectId);
388
const effectiveCwd = resolveThreadWorkspaceCwd({
389
thread,
380
- projects: readModel.projects,
390
+ projects: project ? [project] : [],
391
});
392
393
const startProviderSession = (input?: {
@@ -682,10 +692,11 @@ const make = Effect.gen(function* () {
692
const isFirstUserMessageTurn =
693
thread.messages.filter((entry) => entry.role === "user").length === 1;
694
if (isFirstUserMessageTurn) {
695
+ const project = yield* resolveProject(thread.projectId);
696
const generationCwd =
697
resolveThreadWorkspaceCwd({
698
thread,
688
- projects: (yield* orchestrationEngine.getReadModel()).projects,
699
+ projects: project ? [project] : [],
700
}) ?? process.cwd();
701
const generationInput = {
702
messageText: message.text,
@@ -819,20 +830,16 @@ const make = Effect.gen(function* () {
830
})
831
.pipe(
832
Effect.catchCause((cause) =>
822
- Effect.gen(function* () {
823
- yield* appendProviderFailureActivity({
824
- threadId: event.payload.threadId,
825
- kind: "provider.approval.respond.failed",
826
- summary: "Provider approval response failed",
827
- detail: isUnknownPendingApprovalRequestError(cause)
828
- ? stalePendingRequestDetail("approval", event.payload.requestId)
829
- : Cause.pretty(cause),
830
- turnId: null,
831
- createdAt: event.payload.createdAt,
832
- requestId: event.payload.requestId,
833
- });
834
-
835
- if (!isUnknownPendingApprovalRequestError(cause)) return;
833
+ appendProviderFailureActivity({
834
+ threadId: event.payload.threadId,
835
+ kind: "provider.approval.respond.failed",
836
+ summary: "Provider approval response failed",
837
+ detail: isUnknownPendingApprovalRequestError(cause)
838
+ ? stalePendingRequestDetail("approval", event.payload.requestId)
839
+ : Cause.pretty(cause),
840
+ turnId: null,
841
+ createdAt: event.payload.createdAt,
842
+ requestId: event.payload.requestId,
843
}),
844
),
845
);
apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts
+89
-84
@@ -36,11 +36,9 @@ import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
36
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
37
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
38
import { ProviderRuntimeIngestionLive } from "./ProviderRuntimeIngestion.ts";
39
-import {
40
- OrchestrationEngineService,
41
- type OrchestrationEngineShape,
42
-} from "../Services/OrchestrationEngine.ts";
39
+import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
40
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
41
+import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
42
import { ServerConfig } from "../../config.ts";
43
import { ServerSettingsService } from "../../serverSettings.ts";
44
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -154,16 +152,23 @@ function createProviderServiceHarness() {
152
};
153
}
154
155
+type ProviderRuntimeTestReadModel = OrchestrationReadModel;
156
+type ProviderRuntimeTestThread = ProviderRuntimeTestReadModel["threads"][number];
157
+type ProviderRuntimeTestMessage = ProviderRuntimeTestThread["messages"][number];
158
+type ProviderRuntimeTestProposedPlan = ProviderRuntimeTestThread["proposedPlans"][number];
159
+type ProviderRuntimeTestActivity = ProviderRuntimeTestThread["activities"][number];
160
+type ProviderRuntimeTestCheckpoint = ProviderRuntimeTestThread["checkpoints"][number];
161
+
162
async function waitForThread(
158
- engine: OrchestrationEngineShape,
163
+ readModel: () => Promise<ProviderRuntimeTestReadModel>,
164
predicate: (thread: ProviderRuntimeTestThread) => boolean,
165
timeoutMs = 2000,
166
threadId: ThreadId = asThreadId("thread-1"),
167
) {
168
const deadline = Date.now() + timeoutMs;
169
const poll = async (): Promise<ProviderRuntimeTestThread> => {
165
- const readModel = await Effect.runPromise(engine.getReadModel());
166
- const thread = readModel.threads.find((entry) => entry.id === threadId);
170
+ const snapshot = await readModel();
171
+ const thread = snapshot.threads.find((entry) => entry.id === threadId);
172
if (thread && predicate(thread)) {
173
return thread;
174
}
@@ -176,16 +181,9 @@ async function waitForThread(
181
return poll();
182
}
183
179
-type ProviderRuntimeTestReadModel = OrchestrationReadModel;
180
-type ProviderRuntimeTestThread = ProviderRuntimeTestReadModel["threads"][number];
181
-type ProviderRuntimeTestMessage = ProviderRuntimeTestThread["messages"][number];
182
-type ProviderRuntimeTestProposedPlan = ProviderRuntimeTestThread["proposedPlans"][number];
183
-type ProviderRuntimeTestActivity = ProviderRuntimeTestThread["activities"][number];
184
-type ProviderRuntimeTestCheckpoint = ProviderRuntimeTestThread["checkpoints"][number];
185
-
184
describe("ProviderRuntimeIngestion", () => {
185
let runtime: ManagedRuntime.ManagedRuntime<
188
- OrchestrationEngineService | ProviderRuntimeIngestionService,
186
+ OrchestrationEngineService | ProviderRuntimeIngestionService | ProjectionSnapshotQuery,
187
unknown
188
> | null = null;
189
let scope: Scope.Closeable | null = null;
@@ -223,8 +221,13 @@ describe("ProviderRuntimeIngestion", () => {
221
Layer.provide(RepositoryIdentityResolverLive),
222
Layer.provide(SqlitePersistenceMemory),
223
);
224
+ const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
225
+ Layer.provide(RepositoryIdentityResolverLive),
226
+ Layer.provide(SqlitePersistenceMemory),
227
+ );
228
const layer = ProviderRuntimeIngestionLive.pipe(
229
Layer.provideMerge(orchestrationLayer),
230
+ Layer.provideMerge(projectionSnapshotLayer),
231
Layer.provideMerge(SqlitePersistenceMemory),
232
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
233
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
@@ -233,6 +236,7 @@ describe("ProviderRuntimeIngestion", () => {
236
);
237
runtime = ManagedRuntime.make(layer);
238
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
239
+ const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
240
const ingestion = await runtime.runPromise(Effect.service(ProviderRuntimeIngestionService));
241
scope = await Effect.runPromise(Scope.make("sequential"));
242
await Effect.runPromise(ingestion.start().pipe(Scope.provide(scope)));
@@ -299,6 +303,7 @@ describe("ProviderRuntimeIngestion", () => {
303
304
return {
305
engine,
306
+ readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
307
emit: provider.emit,
308
setProviderSession: provider.setSession,
309
drain,
@@ -319,7 +324,7 @@ describe("ProviderRuntimeIngestion", () => {
324
});
325
326
await waitForThread(
322
- harness.engine,
327
+ harness.readModel,
328
(thread) => thread.session?.status === "running" && thread.session?.activeTurnId === "turn-1",
329
);
330
@@ -337,7 +342,7 @@ describe("ProviderRuntimeIngestion", () => {
342
});
343
344
const thread = await waitForThread(
340
- harness.engine,
345
+ harness.readModel,
346
(entry) =>
347
entry.session?.status === "error" &&
348
entry.session?.activeTurnId === null &&
@@ -364,7 +369,7 @@ describe("ProviderRuntimeIngestion", () => {
369
});
370
371
let thread = await waitForThread(
367
- harness.engine,
372
+ harness.readModel,
373
(entry) => entry.session?.status === "running" && entry.session?.activeTurnId === null,
374
);
375
expect(thread.session?.status).toBe("running");
@@ -383,7 +388,7 @@ describe("ProviderRuntimeIngestion", () => {
388
});
389
390
thread = await waitForThread(
386
- harness.engine,
391
+ harness.readModel,
392
(entry) =>
393
entry.session?.status === "error" &&
394
entry.session?.activeTurnId === null &&
@@ -404,7 +409,7 @@ describe("ProviderRuntimeIngestion", () => {
409
});
410
411
thread = await waitForThread(
407
- harness.engine,
412
+ harness.readModel,
413
(entry) =>
414
entry.session?.status === "stopped" &&
415
entry.session?.activeTurnId === null &&
@@ -425,7 +430,7 @@ describe("ProviderRuntimeIngestion", () => {
430
});
431
432
thread = await waitForThread(
428
- harness.engine,
433
+ harness.readModel,
434
(entry) =>
435
entry.session?.status === "ready" &&
436
entry.session?.activeTurnId === null &&
@@ -449,7 +454,7 @@ describe("ProviderRuntimeIngestion", () => {
454
});
455
456
await waitForThread(
452
- harness.engine,
457
+ harness.readModel,
458
(thread) =>
459
thread.session?.status === "running" &&
460
thread.session?.activeTurnId === "turn-midturn-lifecycle",
@@ -471,7 +476,7 @@ describe("ProviderRuntimeIngestion", () => {
476
});
477
478
await harness.drain();
474
- const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
479
+ const midReadModel = await harness.readModel();
480
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
481
expect(midThread?.session?.status).toBe("running");
482
expect(midThread?.session?.activeTurnId).toBe("turn-midturn-lifecycle");
@@ -487,7 +492,7 @@ describe("ProviderRuntimeIngestion", () => {
492
});
493
494
await waitForThread(
490
- harness.engine,
495
+ harness.readModel,
496
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
497
);
498
});
@@ -524,7 +529,7 @@ describe("ProviderRuntimeIngestion", () => {
529
});
530
531
await waitForThread(
527
- harness.engine,
532
+ harness.readModel,
533
(thread) =>
534
thread.session?.status === "running" &&
535
thread.session?.activeTurnId === "turn-claude-placeholder",
@@ -541,7 +546,7 @@ describe("ProviderRuntimeIngestion", () => {
546
});
547
548
await waitForThread(
544
- harness.engine,
549
+ harness.readModel,
550
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
551
);
552
});
@@ -560,7 +565,7 @@ describe("ProviderRuntimeIngestion", () => {
565
});
566
567
await waitForThread(
563
- harness.engine,
568
+ harness.readModel,
569
(thread) =>
570
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-primary",
571
);
@@ -576,7 +581,7 @@ describe("ProviderRuntimeIngestion", () => {
581
});
582
583
await harness.drain();
579
- const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
584
+ const midReadModel = await harness.readModel();
585
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
586
expect(midThread?.session?.status).toBe("running");
587
expect(midThread?.session?.activeTurnId).toBe("turn-primary");
@@ -592,7 +597,7 @@ describe("ProviderRuntimeIngestion", () => {
597
});
598
599
await waitForThread(
595
- harness.engine,
600
+ harness.readModel,
601
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
602
);
603
});
@@ -611,7 +616,7 @@ describe("ProviderRuntimeIngestion", () => {
616
});
617
618
await waitForThread(
614
- harness.engine,
619
+ harness.readModel,
620
(thread) =>
621
thread.session?.status === "running" &&
622
thread.session?.activeTurnId === "turn-guarded-main",
@@ -628,7 +633,7 @@ describe("ProviderRuntimeIngestion", () => {
633
});
634
635
await harness.drain();
631
- const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
636
+ const midReadModel = await harness.readModel();
637
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
638
expect(midThread?.session?.status).toBe("running");
639
expect(midThread?.session?.activeTurnId).toBe("turn-guarded-main");
@@ -644,7 +649,7 @@ describe("ProviderRuntimeIngestion", () => {
649
});
650
651
await waitForThread(
647
- harness.engine,
652
+ harness.readModel,
653
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
654
);
655
});
@@ -693,7 +698,7 @@ describe("ProviderRuntimeIngestion", () => {
698
},
699
});
700
696
- const thread = await waitForThread(harness.engine, (entry) =>
701
+ const thread = await waitForThread(harness.readModel, (entry) =>
702
entry.messages.some(
703
(message: ProviderRuntimeTestMessage) =>
704
message.id === "assistant:item-1" && !message.streaming,
@@ -725,7 +730,7 @@ describe("ProviderRuntimeIngestion", () => {
730
},
731
});
732
728
- const thread = await waitForThread(harness.engine, (entry) =>
733
+ const thread = await waitForThread(harness.readModel, (entry) =>
734
entry.messages.some(
735
(message: ProviderRuntimeTestMessage) =>
736
message.id === "assistant:item-no-delta" && !message.streaming,
@@ -764,7 +769,7 @@ describe("ProviderRuntimeIngestion", () => {
769
},
770
});
771
767
- const thread = await waitForThread(harness.engine, (entry) =>
772
+ const thread = await waitForThread(harness.readModel, (entry) =>
773
entry.activities.some(
774
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-tool-completed-with-data",
775
),
@@ -819,7 +824,7 @@ describe("ProviderRuntimeIngestion", () => {
824
},
825
});
826
822
- const thread = await waitForThread(harness.engine, (entry) =>
827
+ const thread = await waitForThread(harness.readModel, (entry) =>
828
entry.activities.some(
829
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-command-completed",
830
),
@@ -861,7 +866,7 @@ describe("ProviderRuntimeIngestion", () => {
866
},
867
});
868
864
- const thread = await waitForThread(harness.engine, (entry) =>
869
+ const thread = await waitForThread(harness.readModel, (entry) =>
870
entry.activities.some(
871
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-read-path-completed",
872
),
@@ -894,7 +899,7 @@ describe("ProviderRuntimeIngestion", () => {
899
},
900
});
901
897
- const thread = await waitForThread(harness.engine, (entry) =>
902
+ const thread = await waitForThread(harness.readModel, (entry) =>
903
entry.proposedPlans.some(
904
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
905
proposedPlan.id === "plan:thread-1:turn:turn-plan-final",
@@ -1009,7 +1014,7 @@ describe("ProviderRuntimeIngestion", () => {
1014
});
1015
1016
const sourceThreadWithPlan = await waitForThread(
1012
- harness.engine,
1017
+ harness.readModel,
1018
(thread) =>
1019
thread.proposedPlans.some(
1020
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
@@ -1050,7 +1055,7 @@ describe("ProviderRuntimeIngestion", () => {
1055
);
1056
1057
const sourceThreadBeforeStart = await waitForThread(
1053
- harness.engine,
1058
+ harness.readModel,
1059
(thread) =>
1060
thread.proposedPlans.some(
1061
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
@@ -1076,7 +1081,7 @@ describe("ProviderRuntimeIngestion", () => {
1081
});
1082
1083
const sourceThreadAfterStart = await waitForThread(
1079
- harness.engine,
1084
+ harness.readModel,
1085
(thread) =>
1086
thread.proposedPlans.some(
1087
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
@@ -1158,7 +1163,7 @@ describe("ProviderRuntimeIngestion", () => {
1163
});
1164
1165
await waitForThread(
1161
- harness.engine,
1166
+ harness.readModel,
1167
(thread) =>
1168
thread.session?.status === "running" && thread.session?.activeTurnId === activeTurnId,
1169
2_000,
@@ -1178,7 +1183,7 @@ describe("ProviderRuntimeIngestion", () => {
1183
});
1184
1185
const sourceThreadWithPlan = await waitForThread(
1181
- harness.engine,
1186
+ harness.readModel,
1187
(thread) =>
1188
thread.proposedPlans.some(
1189
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
@@ -1229,7 +1234,7 @@ describe("ProviderRuntimeIngestion", () => {
1234
1235
await harness.drain();
1236
1232
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
1237
+ const readModel = await harness.readModel();
1238
const sourceThreadAfterRejectedStart = readModel.threads.find(
1239
(entry) => entry.id === sourceThreadId,
1240
);
@@ -1340,7 +1345,7 @@ describe("ProviderRuntimeIngestion", () => {
1345
});
1346
1347
const sourceThreadWithPlan = await waitForThread(
1343
- harness.engine,
1348
+ harness.readModel,
1349
(thread) =>
1350
thread.proposedPlans.some(
1351
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
@@ -1401,7 +1406,7 @@ describe("ProviderRuntimeIngestion", () => {
1406
1407
await harness.drain();
1408
1404
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
1409
+ const readModel = await harness.readModel();
1410
const sourceThreadAfterUnrelatedStart = readModel.threads.find(
1411
(entry) => entry.id === sourceThreadId,
1412
);
@@ -1427,7 +1432,7 @@ describe("ProviderRuntimeIngestion", () => {
1432
});
1433
1434
await waitForThread(
1430
- harness.engine,
1435
+ harness.readModel,
1436
(thread) =>
1437
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-plan-buffer",
1438
);
@@ -1466,7 +1471,7 @@ describe("ProviderRuntimeIngestion", () => {
1471
},
1472
});
1473
1469
- const thread = await waitForThread(harness.engine, (entry) =>
1474
+ const thread = await waitForThread(harness.readModel, (entry) =>
1475
entry.proposedPlans.some(
1476
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
1477
proposedPlan.id === "plan:thread-1:turn:turn-plan-buffer",
@@ -1492,7 +1497,7 @@ describe("ProviderRuntimeIngestion", () => {
1497
turnId: asTurnId("turn-buffered"),
1498
});
1499
await waitForThread(
1495
- harness.engine,
1500
+ harness.readModel,
1501
(thread) =>
1502
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-buffered",
1503
);
@@ -1512,7 +1517,7 @@ describe("ProviderRuntimeIngestion", () => {
1517
});
1518
1519
await harness.drain();
1515
- const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
1520
+ const midReadModel = await harness.readModel();
1521
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
1522
expect(
1523
midThread?.messages.some(
@@ -1534,7 +1539,7 @@ describe("ProviderRuntimeIngestion", () => {
1539
},
1540
});
1541
1537
- const thread = await waitForThread(harness.engine, (entry) =>
1542
+ const thread = await waitForThread(harness.readModel, (entry) =>
1543
entry.messages.some(
1544
(message: ProviderRuntimeTestMessage) =>
1545
message.id === "assistant:item-buffered" && !message.streaming,
@@ -1560,7 +1565,7 @@ describe("ProviderRuntimeIngestion", () => {
1565
turnId: asTurnId("turn-buffered-request-flush"),
1566
});
1567
await waitForThread(
1563
- harness.engine,
1568
+ harness.readModel,
1569
(thread) =>
1570
thread.session?.status === "running" &&
1571
thread.session?.activeTurnId === "turn-buffered-request-flush",
@@ -1593,7 +1598,7 @@ describe("ProviderRuntimeIngestion", () => {
1598
},
1599
});
1600
1596
- const thread = await waitForThread(harness.engine, (entry) =>
1601
+ const thread = await waitForThread(harness.readModel, (entry) =>
1602
entry.messages.some(
1603
(message: ProviderRuntimeTestMessage) =>
1604
message.id === "assistant:item-buffered-request-flush" &&
@@ -1620,7 +1625,7 @@ describe("ProviderRuntimeIngestion", () => {
1625
turnId: asTurnId("turn-buffered-user-input-flush"),
1626
});
1627
await waitForThread(
1623
- harness.engine,
1628
+ harness.readModel,
1629
(thread) =>
1630
thread.session?.status === "running" &&
1631
thread.session?.activeTurnId === "turn-buffered-user-input-flush",
@@ -1659,7 +1664,7 @@ describe("ProviderRuntimeIngestion", () => {
1664
},
1665
});
1666
1662
- const thread = await waitForThread(harness.engine, (entry) =>
1667
+ const thread = await waitForThread(harness.readModel, (entry) =>
1668
entry.messages.some(
1669
(message: ProviderRuntimeTestMessage) =>
1670
message.id === "assistant:item-buffered-user-input-flush" &&
@@ -1688,7 +1693,7 @@ describe("ProviderRuntimeIngestion", () => {
1693
turnId: asTurnId("turn-buffered-whitespace-request"),
1694
});
1695
await waitForThread(
1691
- harness.engine,
1696
+ harness.readModel,
1697
(thread) =>
1698
thread.session?.status === "running" &&
1699
thread.session?.activeTurnId === "turn-buffered-whitespace-request",
@@ -1721,7 +1726,7 @@ describe("ProviderRuntimeIngestion", () => {
1726
},
1727
});
1728
1724
- const thread = await waitForThread(harness.engine, (entry) =>
1729
+ const thread = await waitForThread(harness.readModel, (entry) =>
1730
entry.activities.some(
1731
(activity: ProviderRuntimeTestActivity) => activity.kind === "approval.requested",
1732
),
@@ -1750,7 +1755,7 @@ describe("ProviderRuntimeIngestion", () => {
1755
turnId: asTurnId("turn-buffered-request-append"),
1756
});
1757
await waitForThread(
1753
- harness.engine,
1758
+ harness.readModel,
1759
(thread) =>
1760
thread.session?.status === "running" &&
1761
thread.session?.activeTurnId === "turn-buffered-request-append",
@@ -1783,7 +1788,7 @@ describe("ProviderRuntimeIngestion", () => {
1788
},
1789
});
1790
1786
- await waitForThread(harness.engine, (entry) =>
1791
+ await waitForThread(harness.readModel, (entry) =>
1792
entry.messages.some(
1793
(message: ProviderRuntimeTestMessage) =>
1794
message.id === "assistant:item-buffered-request-append" &&
@@ -1819,7 +1824,7 @@ describe("ProviderRuntimeIngestion", () => {
1824
},
1825
});
1826
1822
- const thread = await waitForThread(harness.engine, (entry) =>
1827
+ const thread = await waitForThread(harness.readModel, (entry) =>
1828
entry.messages.some(
1829
(message: ProviderRuntimeTestMessage) =>
1830
message.id === "assistant:item-buffered-request-append:segment:1" &&
@@ -1882,7 +1887,7 @@ describe("ProviderRuntimeIngestion", () => {
1887
turnId: asTurnId("turn-streaming-request-segment"),
1888
});
1889
await waitForThread(
1885
- harness.engine,
1890
+ harness.readModel,
1891
(thread) =>
1892
thread.session?.status === "running" &&
1893
thread.session?.activeTurnId === "turn-streaming-request-segment",
@@ -1915,7 +1920,7 @@ describe("ProviderRuntimeIngestion", () => {
1920
},
1921
});
1922
1918
- await waitForThread(harness.engine, (entry) =>
1923
+ await waitForThread(harness.readModel, (entry) =>
1924
entry.messages.some(
1925
(message: ProviderRuntimeTestMessage) =>
1926
message.id === "assistant:item-streaming-request-segment" &&
@@ -1951,7 +1956,7 @@ describe("ProviderRuntimeIngestion", () => {
1956
},
1957
});
1958
1954
- const thread = await waitForThread(harness.engine, (entry) =>
1959
+ const thread = await waitForThread(harness.readModel, (entry) =>
1960
entry.messages.some(
1961
(message: ProviderRuntimeTestMessage) =>
1962
message.id === "assistant:item-streaming-request-segment:segment:1" &&
@@ -2004,7 +2009,7 @@ describe("ProviderRuntimeIngestion", () => {
2009
turnId: asTurnId("turn-streaming-mode"),
2010
});
2011
await waitForThread(
2007
- harness.engine,
2012
+ harness.readModel,
2013
(thread) =>
2014
thread.session?.status === "running" &&
2015
thread.session?.activeTurnId === "turn-streaming-mode",
@@ -2024,7 +2029,7 @@ describe("ProviderRuntimeIngestion", () => {
2029
},
2030
});
2031
2027
- const liveThread = await waitForThread(harness.engine, (entry) =>
2032
+ const liveThread = await waitForThread(harness.readModel, (entry) =>
2033
entry.messages.some(
2034
(message: ProviderRuntimeTestMessage) =>
2035
message.id === "assistant:item-streaming-mode" &&
@@ -2052,7 +2057,7 @@ describe("ProviderRuntimeIngestion", () => {
2057
},
2058
});
2059
2055
- const finalThread = await waitForThread(harness.engine, (entry) =>
2060
+ const finalThread = await waitForThread(harness.readModel, (entry) =>
2061
entry.messages.some(
2062
(message: ProviderRuntimeTestMessage) =>
2063
message.id === "assistant:item-streaming-mode" && !message.streaming,
@@ -2079,7 +2084,7 @@ describe("ProviderRuntimeIngestion", () => {
2084
turnId: asTurnId("turn-buffer-spill"),
2085
});
2086
await waitForThread(
2082
- harness.engine,
2087
+ harness.readModel,
2088
(thread) =>
2089
thread.session?.status === "running" &&
2090
thread.session?.activeTurnId === "turn-buffer-spill",
@@ -2112,7 +2117,7 @@ describe("ProviderRuntimeIngestion", () => {
2117
},
2118
});
2119
2115
- const thread = await waitForThread(harness.engine, (entry) =>
2120
+ const thread = await waitForThread(harness.readModel, (entry) =>
2121
entry.messages.some(
2122
(message: ProviderRuntimeTestMessage) =>
2123
message.id === "assistant:item-buffer-spill" && !message.streaming,
@@ -2140,7 +2145,7 @@ describe("ProviderRuntimeIngestion", () => {
2145
});
2146
2147
await waitForThread(
2143
- harness.engine,
2148
+ harness.readModel,
2149
(thread) =>
2150
thread.session?.status === "running" &&
2151
thread.session?.activeTurnId === "turn-complete-dedup",
@@ -2185,7 +2190,7 @@ describe("ProviderRuntimeIngestion", () => {
2190
});
2191
2192
await waitForThread(
2188
- harness.engine,
2193
+ harness.readModel,
2194
(thread) =>
2195
thread.session?.status === "ready" &&
2196
thread.session?.activeTurnId === null &&
@@ -2243,7 +2248,7 @@ describe("ProviderRuntimeIngestion", () => {
2248
});
2249
2250
await waitForThread(
2246
- harness.engine,
2251
+ harness.readModel,
2252
(entry) =>
2253
entry.activities.some(
2254
(activity: ProviderRuntimeTestActivity) => activity.kind === "approval.requested",
@@ -2253,7 +2258,7 @@ describe("ProviderRuntimeIngestion", () => {
2258
),
2259
);
2260
2256
- const readModel = await Effect.runPromise(harness.engine.getReadModel());
2261
+ const readModel = await harness.readModel();
2262
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
2263
expect(thread).toBeDefined();
2264
@@ -2295,7 +2300,7 @@ describe("ProviderRuntimeIngestion", () => {
2300
});
2301
2302
const thread = await waitForThread(
2298
- harness.engine,
2303
+ harness.readModel,
2304
(entry) =>
2305
entry.session?.status === "error" &&
2306
entry.session?.activeTurnId === "turn-3" &&
@@ -2321,7 +2326,7 @@ describe("ProviderRuntimeIngestion", () => {
2326
},
2327
});
2328
2324
- const thread = await waitForThread(harness.engine, (entry) =>
2329
+ const thread = await waitForThread(harness.readModel, (entry) =>
2330
entry.activities.some((activity) => activity.id === "evt-runtime-error-activity"),
2331
);
2332
const activity = thread.activities.find(
@@ -2366,7 +2371,7 @@ describe("ProviderRuntimeIngestion", () => {
2371
});
2372
2373
const thread = await waitForThread(
2369
- harness.engine,
2374
+ harness.readModel,
2375
(entry) =>
2376
entry.session?.status === "running" &&
2377
entry.session?.activeTurnId === "turn-warning" &&
@@ -2415,7 +2420,7 @@ describe("ProviderRuntimeIngestion", () => {
2420
});
2421
2422
const thread = await waitForThread(
2418
- harness.engine,
2423
+ harness.readModel,
2424
(entry) =>
2425
entry.session?.status === "ready" &&
2426
entry.session?.activeTurnId === null &&
@@ -2508,7 +2513,7 @@ describe("ProviderRuntimeIngestion", () => {
2513
});
2514
2515
const thread = await waitForThread(
2511
- harness.engine,
2516
+ harness.readModel,
2517
(entry) =>
2518
entry.title === "Renamed by provider" &&
2519
entry.activities.some(
@@ -2595,7 +2600,7 @@ describe("ProviderRuntimeIngestion", () => {
2600
},
2601
});
2602
2598
- const thread = await waitForThread(harness.engine, (entry) =>
2603
+ const thread = await waitForThread(harness.readModel, (entry) =>
2604
entry.activities.some(
2605
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
2606
),
@@ -2647,7 +2652,7 @@ describe("ProviderRuntimeIngestion", () => {
2652
},
2653
});
2654
2650
- const thread = await waitForThread(harness.engine, (entry) =>
2655
+ const thread = await waitForThread(harness.readModel, (entry) =>
2656
entry.activities.some(
2657
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
2658
),
@@ -2697,7 +2702,7 @@ describe("ProviderRuntimeIngestion", () => {
2702
},
2703
});
2704
2700
- const thread = await waitForThread(harness.engine, (entry) =>
2705
+ const thread = await waitForThread(harness.readModel, (entry) =>
2706
entry.activities.some(
2707
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
2708
),
@@ -2732,7 +2737,7 @@ describe("ProviderRuntimeIngestion", () => {
2737
},
2738
});
2739
2735
- const thread = await waitForThread(harness.engine, (entry) =>
2740
+ const thread = await waitForThread(harness.readModel, (entry) =>
2741
entry.activities.some(
2742
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-compaction",
2743
),
@@ -2802,7 +2807,7 @@ describe("ProviderRuntimeIngestion", () => {
2807
});
2808
2809
const thread = await waitForThread(
2805
- harness.engine,
2810
+ harness.readModel,
2811
(entry) =>
2812
entry.activities.some(
2813
(activity: ProviderRuntimeTestActivity) => activity.kind === "task.completed",
@@ -2893,7 +2898,7 @@ describe("ProviderRuntimeIngestion", () => {
2898
});
2899
2900
const thread = await waitForThread(
2896
- harness.engine,
2901
+ harness.readModel,
2902
(entry) =>
2903
entry.activities.some(
2904
(activity: ProviderRuntimeTestActivity) => activity.kind === "user-input.requested",
@@ -2952,7 +2957,7 @@ describe("ProviderRuntimeIngestion", () => {
2957
});
2958
2959
const thread = await waitForThread(
2955
- harness.engine,
2960
+ harness.readModel,
2961
(entry) =>
2962
entry.session?.status === "error" &&
2963
entry.session?.activeTurnId === "turn-after-failure" &&
apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
+132
-42
@@ -4,12 +4,16 @@ import {
4
CommandId,
5
MessageId,
6
type OrchestrationEvent,
7
+ type OrchestrationMessage,
8
type OrchestrationProposedPlanId,
9
CheckpointRef,
10
isToolLifecycleItemType,
11
ThreadId,
12
type ThreadTokenUsageSnapshot,
13
TurnId,
14
+ type OrchestrationCheckpointSummary,
15
+ type OrchestrationProposedPlan,
16
+ type OrchestrationThread,
17
type OrchestrationThreadActivity,
18
type ProviderRuntimeEvent,
19
} from "@t3tools/contracts";
@@ -19,9 +23,9 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
23
import { ProviderService } from "../../provider/Services/ProviderService.ts";
24
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
25
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
22
-import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
26
import { isGitRepository } from "../../git/Utils.ts";
27
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
28
+import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
29
import {
30
ProviderRuntimeIngestionService,
31
type ProviderRuntimeIngestionShape,
@@ -77,6 +81,82 @@ function sameId(left: string | null | undefined, right: string | null | undefine
81
return left === right;
82
}
83
84
+function hasAssistantMessageForTurn(
85
+ messages: ReadonlyArray<OrchestrationMessage>,
86
+ turnId: TurnId,
87
+ options?: { readonly streamingOnly?: boolean },
88
+): boolean {
89
+ for (let index = 0; index < messages.length; index += 1) {
90
+ const message = messages[index];
91
+ if (!message) {
92
+ continue;
93
+ }
94
+ if (message.role !== "assistant" || message.turnId !== turnId) {
95
+ continue;
96
+ }
97
+ if (options?.streamingOnly === true && !message.streaming) {
98
+ continue;
99
+ }
100
+ return true;
101
+ }
102
+ return false;
103
+}
104
+
105
+function findMessageById(
106
+ messages: ReadonlyArray<OrchestrationMessage>,
107
+ messageId: MessageId,
108
+): OrchestrationMessage | undefined {
109
+ for (let index = 0; index < messages.length; index += 1) {
110
+ const message = messages[index];
111
+ if (message?.id === messageId) {
112
+ return message;
113
+ }
114
+ }
115
+ return undefined;
116
+}
117
+
118
+function findProposedPlanById(
119
+ proposedPlans: ReadonlyArray<
120
+ Pick<OrchestrationProposedPlan, "id" | "createdAt" | "implementedAt" | "implementationThreadId">
121
+ >,
122
+ planId: string,
123
+):
124
+ | Pick<OrchestrationProposedPlan, "id" | "createdAt" | "implementedAt" | "implementationThreadId">
125
+ | undefined {
126
+ for (let index = 0; index < proposedPlans.length; index += 1) {
127
+ const proposedPlan = proposedPlans[index];
128
+ if (proposedPlan?.id === planId) {
129
+ return proposedPlan;
130
+ }
131
+ }
132
+ return undefined;
133
+}
134
+
135
+function hasCheckpointForTurn(
136
+ checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
137
+ turnId: TurnId,
138
+): boolean {
139
+ for (let index = 0; index < checkpoints.length; index += 1) {
140
+ if (checkpoints[index]?.turnId === turnId) {
141
+ return true;
142
+ }
143
+ }
144
+ return false;
145
+}
146
+
147
+function maxCheckpointTurnCount(
148
+ checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
149
+): number {
150
+ let maxTurnCount = 0;
151
+ for (let index = 0; index < checkpoints.length; index += 1) {
152
+ const checkpoint = checkpoints[index];
153
+ if (checkpoint && checkpoint.checkpointTurnCount > maxTurnCount) {
154
+ maxTurnCount = checkpoint.checkpointTurnCount;
155
+ }
156
+ }
157
+ return maxTurnCount;
158
+}
159
+
160
function truncateDetail(value: string, limit = 180): string {
161
return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;
162
}
@@ -522,6 +602,7 @@ function runtimeEventToActivities(
602
603
const make = Effect.gen(function* () {
604
const orchestrationEngine = yield* OrchestrationEngineService;
605
+ const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
606
const providerService = yield* ProviderService;
607
const projectionTurnRepository = yield* ProjectionTurnRepository;
608
const serverSettingsService = yield* ServerSettingsService;
@@ -553,20 +634,16 @@ const make = Effect.gen(function* () {
634
lookup: () => Effect.succeed({ text: "", createdAt: "" }),
635
});
636
556
- const isGitRepoForThread = Effect.fn("isGitRepoForThread")(function* (threadId: ThreadId) {
557
- const readModel = yield* orchestrationEngine.getReadModel();
558
- const thread = readModel.threads.find((entry) => entry.id === threadId);
559
- if (!thread) {
560
- return false;
561
- }
562
- const workspaceCwd = resolveThreadWorkspaceCwd({
563
- thread,
564
- projects: readModel.projects,
565
- });
566
- if (!workspaceCwd) {
567
- return false;
568
- }
569
- return isGitRepository(workspaceCwd);
637
+ const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (threadId: ThreadId) {
638
+ return yield* projectionSnapshotQuery
639
+ .getThreadDetailById(threadId)
640
+ .pipe(Effect.map(Option.getOrUndefined));
641
+ });
642
+
643
+ const resolveThreadShell = Effect.fn("resolveThreadShell")(function* (threadId: ThreadId) {
644
+ return yield* projectionSnapshotQuery
645
+ .getThreadShellById(threadId)
646
+ .pipe(Effect.map(Option.getOrUndefined));
647
});
648
649
const rememberAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>
@@ -917,7 +994,7 @@ const make = Effect.gen(function* () {
994
return;
995
}
996
920
- const existingPlan = input.threadProposedPlans.find((entry) => entry.id === input.planId);
997
+ const existingPlan = findProposedPlanById(input.threadProposedPlans, input.planId);
998
yield* orchestrationEngine.dispatch({
999
type: "thread.proposed-plan.upsert",
1000
commandId: providerCommandId(input.event, "proposed-plan-upsert"),
@@ -1070,8 +1147,7 @@ const make = Effect.gen(function* () {
1147
implementationThreadId: ThreadId,
1148
implementedAt: string,
1149
) {
1073
- const readModel = yield* orchestrationEngine.getReadModel();
1074
- const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId);
1150
+ const sourceThread = yield* resolveThreadDetail(sourceThreadId);
1151
const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);
1152
if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {
1153
return;
@@ -1096,10 +1172,19 @@ const make = Effect.gen(function* () {
1172
1173
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
1174
Effect.gen(function* () {
1099
- const readModel = yield* orchestrationEngine.getReadModel();
1100
- const thread = readModel.threads.find((entry) => entry.id === event.threadId);
1175
+ const thread = yield* resolveThreadShell(event.threadId);
1176
if (!thread) return;
1177
1178
+ let loadedThreadDetail: OrchestrationThread | null | undefined;
1179
+ const getLoadedThreadDetail = () =>
1180
+ Effect.gen(function* () {
1181
+ if (loadedThreadDetail !== undefined) {
1182
+ return loadedThreadDetail;
1183
+ }
1184
+ loadedThreadDetail = (yield* resolveThreadDetail(thread.id)) ?? null;
1185
+ return loadedThreadDetail;
1186
+ });
1187
+
1188
const now = event.createdAt;
1189
const eventTurnId = toTurnId(event.turnId);
1190
const activeTurnId = thread.session?.activeTurnId ?? null;
@@ -1277,6 +1362,7 @@ const make = Effect.gen(function* () {
1362
? toTurnId(event.turnId)
1363
: undefined;
1364
if (pauseForUserTurnId) {
1365
+ const detailedThread = yield* getLoadedThreadDetail();
1366
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
1367
serverSettingsService.getSettings,
1368
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
@@ -1307,10 +1393,11 @@ const make = Effect.gen(function* () {
1393
event.type === "request.opened"
1394
? "assistant-delta-finalize-on-request-opened"
1395
: "assistant-delta-finalize-on-user-input-requested",
1310
- hasProjectedMessage: thread.messages.some(
1311
- (entry) =>
1312
- entry.role === "assistant" && entry.turnId === pauseForUserTurnId && entry.streaming,
1313
- ),
1396
+ hasProjectedMessage:
1397
+ detailedThread !== null &&
1398
+ hasAssistantMessageForTurn(detailedThread.messages, pauseForUserTurnId, {
1399
+ streamingOnly: true,
1400
+ }),
1401
flushedMessageIds,
1402
});
1403
}
@@ -1339,21 +1426,19 @@ const make = Effect.gen(function* () {
1426
: undefined;
1427
1428
if (assistantCompletion) {
1429
+ const detailedThread = yield* getLoadedThreadDetail();
1430
+ const messages = detailedThread?.messages ?? [];
1431
const turnId = toTurnId(event.turnId);
1432
const activeAssistantMessageId = turnId
1433
? yield* getActiveAssistantMessageIdForTurn(thread.id, turnId)
1434
: Option.none<MessageId>();
1435
const hasAssistantMessagesForTurn =
1347
- turnId !== undefined
1348
- ? thread.messages.some((entry) => entry.role === "assistant" && entry.turnId === turnId)
1349
- : false;
1436
+ turnId !== undefined ? hasAssistantMessageForTurn(messages, turnId) : false;
1437
const assistantMessageId = Option.getOrElse(
1438
activeAssistantMessageId,
1439
() => assistantCompletion.messageId,
1440
);
1354
- const existingAssistantMessage = thread.messages.find(
1355
- (entry) => entry.id === assistantMessageId,
1356
- );
1441
+ const existingAssistantMessage = findMessageById(messages, assistantMessageId);
1442
const shouldApplyFallbackCompletionText =
1443
!existingAssistantMessage || existingAssistantMessage.text.length === 0;
1444
@@ -1393,10 +1478,11 @@ const make = Effect.gen(function* () {
1478
}
1479
1480
if (proposedPlanCompletion) {
1481
+ const detailedThread = yield* getLoadedThreadDetail();
1482
yield* finalizeBufferedProposedPlan({
1483
event,
1484
threadId: thread.id,
1399
- threadProposedPlans: thread.proposedPlans,
1485
+ threadProposedPlans: detailedThread?.proposedPlans ?? [],
1486
planId: proposedPlanCompletion.planId,
1487
...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}),
1488
fallbackMarkdown: proposedPlanCompletion.planMarkdown,
@@ -1405,6 +1491,9 @@ const make = Effect.gen(function* () {
1491
}
1492
1493
if (event.type === "turn.completed") {
1494
+ const detailedThread = yield* getLoadedThreadDetail();
1495
+ const messages = detailedThread?.messages ?? [];
1496
+ const proposedPlans = detailedThread?.proposedPlans ?? [];
1497
const turnId = toTurnId(event.turnId);
1498
if (turnId) {
1499
const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId);
@@ -1419,9 +1508,7 @@ const make = Effect.gen(function* () {
1508
createdAt: now,
1509
commandTag: "assistant-complete-finalize",
1510
finalDeltaCommandTag: "assistant-delta-finalize-fallback",
1422
- hasProjectedMessage: thread.messages.some(
1423
- (entry) => entry.id === assistantMessageId,
1424
- ),
1511
+ hasProjectedMessage: findMessageById(messages, assistantMessageId) !== undefined,
1512
}),
1513
{ concurrency: 1 },
1514
).pipe(Effect.asVoid);
@@ -1431,7 +1518,7 @@ const make = Effect.gen(function* () {
1518
yield* finalizeBufferedProposedPlan({
1519
event,
1520
threadId: thread.id,
1434
- threadProposedPlans: thread.proposedPlans,
1521
+ threadProposedPlans: proposedPlans,
1522
planId: proposedPlanIdForTurn(thread.id, turnId),
1523
turnId,
1524
updatedAt: now,
@@ -1483,21 +1570,24 @@ const make = Effect.gen(function* () {
1570
1571
if (event.type === "turn.diff.updated") {
1572
const turnId = toTurnId(event.turnId);
1486
- if (turnId && (yield* isGitRepoForThread(thread.id))) {
1573
+ const checkpointContext = turnId
1574
+ ? yield* projectionSnapshotQuery
1575
+ .getThreadCheckpointContext(thread.id)
1576
+ .pipe(Effect.map(Option.getOrUndefined))
1577
+ : undefined;
1578
+ const workspaceCwd =
1579
+ checkpointContext?.worktreePath ?? checkpointContext?.workspaceRoot ?? undefined;
1580
+ if (turnId && checkpointContext && workspaceCwd && isGitRepository(workspaceCwd)) {
1581
// Skip if a checkpoint already exists for this turn. A real
1582
// (non-placeholder) capture from CheckpointReactor should not
1583
// be clobbered, and dispatching a duplicate placeholder for the
1584
// same turnId would produce an unstable checkpointTurnCount.
1491
- if (thread.checkpoints.some((c) => c.turnId === turnId)) {
1585
+ if (hasCheckpointForTurn(checkpointContext.checkpoints, turnId)) {
1586
// Already tracked; no-op.
1587
} else {
1588
const assistantMessageId = MessageId.make(
1589
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
1590
);
1497
- const maxTurnCount = thread.checkpoints.reduce(
1498
- (max, c) => Math.max(max, c.checkpointTurnCount),
1499
- 0,
1500
- );
1591
yield* orchestrationEngine.dispatch({
1592
type: "thread.turn.diff.complete",
1593
commandId: providerCommandId(event, "thread-turn-diff-complete"),
@@ -1508,7 +1598,7 @@ const make = Effect.gen(function* () {
1598
status: "missing",
1599
files: [],
1600
assistantMessageId,
1511
- checkpointTurnCount: maxTurnCount + 1,
1601
+ checkpointTurnCount: maxCheckpointTurnCount(checkpointContext.checkpoints) + 1,
1602
createdAt: now,
1603
});
1604
}
apps/server/src/orchestration/Services/OrchestrationEngine.ts
+2
-13
@@ -10,11 +10,7 @@
10
*
11
* @module OrchestrationEngineService
12
*/
13
-import type {
14
- OrchestrationCommand,
15
- OrchestrationEvent,
16
- OrchestrationReadModel,
17
-} from "@t3tools/contracts";
13
+import type { OrchestrationCommand, OrchestrationEvent } from "@t3tools/contracts";
14
import { Context } from "effect";
15
import type { Effect, Stream } from "effect";
16
@@ -25,13 +21,6 @@ import type { OrchestrationEventStoreError } from "../../persistence/Errors.ts";
21
* OrchestrationEngineShape - Service API for orchestration command and event flow.
22
*/
23
export interface OrchestrationEngineShape {
28
- /**
29
- * Read the current in-memory orchestration read model.
30
- *
31
- * @returns Effect containing the latest read model.
32
- */
33
- readonly getReadModel: () => Effect.Effect<OrchestrationReadModel, never, never>;
34
-
24
/**
25
* Replay persisted orchestration events from an exclusive sequence cursor.
26
*
@@ -70,7 +59,7 @@ export interface OrchestrationEngineShape {
59
* ```ts
60
* const program = Effect.gen(function* () {
61
* const engine = yield* OrchestrationEngineService
73
- * return yield* engine.getReadModel()
62
+ * return yield* engine.dispatch(command)
63
* })
64
* ```
65
*/
apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts
+22
@@ -28,6 +28,10 @@ export interface ProjectionSnapshotCounts {
28
readonly threadCount: number;
29
}
30
31
+export interface ProjectionSnapshotSequence {
32
+ readonly snapshotSequence: number;
33
+}
34
+
35
export interface ProjectionThreadCheckpointContext {
36
readonly threadId: ThreadId;
37
readonly projectId: ProjectId;
@@ -40,6 +44,15 @@ export interface ProjectionThreadCheckpointContext {
44
* ProjectionSnapshotQueryShape - Service API for read-model snapshots.
45
*/
46
export interface ProjectionSnapshotQueryShape {
47
+ /**
48
+ * Read the lightweight command snapshot used to bootstrap the in-memory
49
+ * orchestration engine without hydrating message/activity/checkpoint bodies.
50
+ */
51
+ readonly getCommandReadModel: () => Effect.Effect<
52
+ OrchestrationReadModel,
53
+ ProjectionRepositoryError
54
+ >;
55
+
56
/**
57
* Read the latest orchestration projection snapshot.
58
*
@@ -59,6 +72,15 @@ export interface ProjectionSnapshotQueryShape {
72
ProjectionRepositoryError
73
>;
74
75
+ /**
76
+ * Read the latest projection snapshot sequence without hydrating read-model
77
+ * entities.
78
+ */
79
+ readonly getSnapshotSequence: () => Effect.Effect<
80
+ ProjectionSnapshotSequence,
81
+ ProjectionRepositoryError
82
+ >;
83
+
84
/**
85
* Read aggregate projection counts without hydrating the full read model.
86
*/
apps/server/src/persistence/Migrations.ts
+2
@@ -41,6 +41,7 @@ import Migration0025 from "./Migrations/025_CleanupInvalidProjectionPendingAppro
41
import Migration0026 from "./Migrations/026_CanonicalizeModelSelectionOptions.ts";
42
import Migration0027 from "./Migrations/027_ProviderSessionRuntimeInstanceId.ts";
43
import Migration0028 from "./Migrations/028_ProjectionThreadSessionInstanceId.ts";
44
+import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexes.ts";
45
46
/**
47
* Migration loader with all migrations defined inline.
@@ -81,6 +82,7 @@ export const migrationEntries = [
82
[26, "CanonicalizeModelSelectionOptions", Migration0026],
83
[27, "ProviderSessionRuntimeInstanceId", Migration0027],
84
[28, "ProjectionThreadSessionInstanceId", Migration0028],
85
+ [29, "ProjectionThreadDetailOrderingIndexes", Migration0029],
86
] as const;
87
88
export const makeMigrationLoader = (throughId?: number) =>
apps/server/src/persistence/Migrations/029_ProjectionThreadDetailOrderingIndexes.test.ts
new
+73
@@ -0,0 +1,73 @@
1
+import { assert, it } from "@effect/vitest";
2
+import { Effect, Layer } from "effect";
3
+import * as SqlClient from "effect/unstable/sql/SqlClient";
4
+
5
+import { runMigrations } from "../Migrations.ts";
6
+import * as NodeSqliteClient from "../NodeSqliteClient.ts";
7
+
8
+const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
9
+
10
+layer("029_ProjectionThreadDetailOrderingIndexes", (it) => {
11
+ it.effect("creates indexes matching thread detail ordering queries", () =>
12
+ Effect.gen(function* () {
13
+ const sql = yield* SqlClient.SqlClient;
14
+
15
+ yield* runMigrations({ toMigrationInclusive: 28 });
16
+ yield* runMigrations({ toMigrationInclusive: 29 });
17
+
18
+ const activityIndexes = yield* sql<{
19
+ readonly seq: number;
20
+ readonly name: string;
21
+ readonly unique: number;
22
+ readonly origin: string;
23
+ readonly partial: number;
24
+ }>`
25
+ PRAGMA index_list(projection_thread_activities)
26
+ `;
27
+ assert.ok(
28
+ activityIndexes.some(
29
+ (index) => index.name === "idx_projection_thread_activities_thread_sequence_created_id",
30
+ ),
31
+ );
32
+
33
+ const activityIndexColumns = yield* sql<{
34
+ readonly seqno: number;
35
+ readonly cid: number;
36
+ readonly name: string;
37
+ }>`
38
+ PRAGMA index_info('idx_projection_thread_activities_thread_sequence_created_id')
39
+ `;
40
+ assert.deepStrictEqual(
41
+ activityIndexColumns.map((column) => column.name),
42
+ ["thread_id", "sequence", "created_at", "activity_id"],
43
+ );
44
+
45
+ const messageIndexes = yield* sql<{
46
+ readonly seq: number;
47
+ readonly name: string;
48
+ readonly unique: number;
49
+ readonly origin: string;
50
+ readonly partial: number;
51
+ }>`
52
+ PRAGMA index_list(projection_thread_messages)
53
+ `;
54
+ assert.ok(
55
+ messageIndexes.some(
56
+ (index) => index.name === "idx_projection_thread_messages_thread_created_id",
57
+ ),
58
+ );
59
+
60
+ const messageIndexColumns = yield* sql<{
61
+ readonly seqno: number;
62
+ readonly cid: number;
63
+ readonly name: string;
64
+ }>`
65
+ PRAGMA index_info('idx_projection_thread_messages_thread_created_id')
66
+ `;
67
+ assert.deepStrictEqual(
68
+ messageIndexColumns.map((column) => column.name),
69
+ ["thread_id", "created_at", "message_id"],
70
+ );
71
+ }),
72
+ );
73
+});
apps/server/src/persistence/Migrations/029_ProjectionThreadDetailOrderingIndexes.ts
new
+16
@@ -0,0 +1,16 @@
1
+import * as Effect from "effect/Effect";
2
+import * as SqlClient from "effect/unstable/sql/SqlClient";
3
+
4
+export default Effect.gen(function* () {
5
+ const sql = yield* SqlClient.SqlClient;
6
+
7
+ yield* sql`
8
+ CREATE INDEX IF NOT EXISTS idx_projection_thread_activities_thread_sequence_created_id
9
+ ON projection_thread_activities(thread_id, sequence, created_at, activity_id)
10
+ `;
11
+
12
+ yield* sql`
13
+ CREATE INDEX IF NOT EXISTS idx_projection_thread_messages_thread_created_id
14
+ ON projection_thread_messages(thread_id, created_at, message_id)
15
+ `;
16
+});
apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts
+44
-54
@@ -1,53 +1,52 @@
1
-import { Effect, Layer, Stream } from "effect";
1
+import { ProjectId, type OrchestrationProject } from "@t3tools/contracts";
2
+import { Effect, Layer, Option } from "effect";
3
import { describe, expect, it, vi } from "vitest";
3
-import type { OrchestrationReadModel } from "@t3tools/contracts";
4
5
-import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
5
+import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
6
import { TerminalManager } from "../../terminal/Services/Manager.ts";
7
import { ProjectSetupScriptRunner } from "../Services/ProjectSetupScriptRunner.ts";
8
import { ProjectSetupScriptRunnerLive } from "./ProjectSetupScriptRunner.ts";
9
10
-const emptySnapshot = (
11
- scripts: OrchestrationReadModel["projects"][number]["scripts"],
12
-): OrchestrationReadModel =>
13
- ({
14
- snapshotSequence: 1,
15
- updatedAt: "2026-01-01T00:00:00.000Z",
16
- projects: [
17
- {
18
- id: "project-1",
19
- title: "Project",
20
- workspaceRoot: "/repo/project",
21
- defaultModelSelection: null,
22
- scripts,
23
- createdAt: "2026-01-01T00:00:00.000Z",
24
- updatedAt: "2026-01-01T00:00:00.000Z",
25
- deletedAt: null,
26
- },
27
- ],
28
- threads: [],
29
- providerSessions: [],
30
- providerStatuses: [],
31
- pendingApprovals: [],
32
- latestTurnByThreadId: {},
33
- }) as unknown as OrchestrationReadModel;
10
+const makeProject = (scripts: OrchestrationProject["scripts"]): OrchestrationProject => ({
11
+ id: ProjectId.make("project-1"),
12
+ title: "Project",
13
+ workspaceRoot: "/repo/project",
14
+ defaultModelSelection: null,
15
+ scripts,
16
+ createdAt: "2026-01-01T00:00:00.000Z",
17
+ updatedAt: "2026-01-01T00:00:00.000Z",
18
+ deletedAt: null,
19
+});
20
+
21
+const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
22
+ Layer.succeed(ProjectionSnapshotQuery, {
23
+ getCommandReadModel: () => Effect.die("unused"),
24
+ getSnapshot: () => Effect.die("unused"),
25
+ getShellSnapshot: () => Effect.die("unused"),
26
+ getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 1 }),
27
+ getCounts: () => Effect.die("unused"),
28
+ getActiveProjectByWorkspaceRoot: (workspaceRoot) =>
29
+ Effect.succeed(
30
+ workspaceRoot === project.workspaceRoot ? Option.some(project) : Option.none(),
31
+ ),
32
+ getProjectShellById: (projectId) =>
33
+ Effect.succeed(projectId === project.id ? Option.some(project) : Option.none()),
34
+ getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
35
+ getThreadCheckpointContext: () => Effect.die("unused"),
36
+ getThreadShellById: () => Effect.die("unused"),
37
+ getThreadDetailById: () => Effect.die("unused"),
38
+ });
39
40
describe("ProjectSetupScriptRunner", () => {
41
it("returns no-script when no setup script exists", async () => {
42
const open = vi.fn();
43
const write = vi.fn();
44
+ const project = makeProject([]);
45
const runner = await Effect.runPromise(
46
Effect.service(ProjectSetupScriptRunner).pipe(
47
Effect.provide(
48
ProjectSetupScriptRunnerLive.pipe(
43
- Layer.provideMerge(
44
- Layer.succeed(OrchestrationEngineService, {
45
- getReadModel: () => Effect.succeed(emptySnapshot([])),
46
- readEvents: () => Stream.empty,
47
- dispatch: () => Effect.die(new Error("unused")),
48
- streamDomainEvents: Stream.empty,
49
- }),
50
- ),
49
+ Layer.provideMerge(makeProjectionSnapshotQueryLayer(project)),
50
Layer.provideMerge(
51
Layer.succeed(TerminalManager, {
52
open,
@@ -93,29 +92,20 @@ describe("ProjectSetupScriptRunner", () => {
92
}),
93
);
94
const write = vi.fn(() => Effect.void);
95
+ const project = makeProject([
96
+ {
97
+ id: "setup",
98
+ name: "Setup",
99
+ command: "bun install",
100
+ icon: "configure",
101
+ runOnWorktreeCreate: true,
102
+ },
103
+ ]);
104
const runner = await Effect.runPromise(
105
Effect.service(ProjectSetupScriptRunner).pipe(
106
Effect.provide(
107
ProjectSetupScriptRunnerLive.pipe(
100
- Layer.provideMerge(
101
- Layer.succeed(OrchestrationEngineService, {
102
- getReadModel: () =>
103
- Effect.succeed(
104
- emptySnapshot([
105
- {
106
- id: "setup",
107
- name: "Setup",
108
- command: "bun install",
109
- icon: "configure",
110
- runOnWorktreeCreate: true,
111
- },
112
- ]),
113
- ),
114
- readEvents: () => Stream.empty,
115
- dispatch: () => Effect.die(new Error("unused")),
116
- streamDomainEvents: Stream.empty,
117
- }),
118
- ),
108
+ Layer.provideMerge(makeProjectionSnapshotQueryLayer(project)),
109
Layer.provideMerge(
110
Layer.succeed(TerminalManager, {
111
open,
apps/server/src/project/Layers/ProjectSetupScriptRunner.ts
+10
-6
@@ -1,7 +1,8 @@
1
+import { ProjectId } from "@t3tools/contracts";
2
import { projectScriptRuntimeEnv, setupProjectScript } from "@t3tools/shared/projectScripts";
2
-import { Effect, Layer } from "effect";
3
+import { Effect, Layer, Option } from "effect";
4
4
-import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
5
+import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
6
import { TerminalManager } from "../../terminal/Services/Manager.ts";
7
import {
8
type ProjectSetupScriptRunnerShape,
@@ -9,18 +10,21 @@ import {
10
} from "../Services/ProjectSetupScriptRunner.ts";
11
12
const makeProjectSetupScriptRunner = Effect.gen(function* () {
12
- const orchestrationEngine = yield* OrchestrationEngineService;
13
+ const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
14
const terminalManager = yield* TerminalManager;
15
16
const runForThread: ProjectSetupScriptRunnerShape["runForThread"] = (input) =>
17
Effect.gen(function* () {
17
- const readModel = yield* orchestrationEngine.getReadModel();
18
const project =
19
(input.projectId
20
- ? readModel.projects.find((entry) => entry.id === input.projectId)
20
+ ? yield* projectionSnapshotQuery
21
+ .getProjectShellById(ProjectId.make(input.projectId))
22
+ .pipe(Effect.map(Option.getOrUndefined))
23
: null) ??
24
(input.projectCwd
23
- ? readModel.projects.find((entry) => entry.workspaceRoot === input.projectCwd)
25
+ ? yield* projectionSnapshotQuery
26
+ .getActiveProjectByWorkspaceRoot(input.projectCwd)
27
+ .pipe(Effect.map(Option.getOrUndefined))
28
: null) ??
29
null;
30
apps/server/src/provider/Layers/ProviderSessionReaper.test.ts
+26
-12
@@ -9,10 +9,7 @@ import {
9
import { Effect, Exit, Layer, ManagedRuntime, Option, Scope, Stream } from "effect";
10
import { afterEach, describe, expect, it, vi } from "vitest";
11
12
-import {
13
- OrchestrationEngineService,
14
- type OrchestrationEngineShape,
15
-} from "../../orchestration/Services/OrchestrationEngine.ts";
12
+import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
13
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
14
import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts";
15
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
@@ -92,6 +89,10 @@ function makeReadModel(
89
createdAt: now,
90
updatedAt: now,
91
archivedAt: null,
92
+ latestUserMessageAt: null,
93
+ hasPendingApprovals: false,
94
+ hasPendingUserInput: false,
95
+ hasActionableProposedPlan: false,
96
latestTurn: null,
97
messages: [],
98
session: thread.session,
@@ -163,13 +164,6 @@ describe("ProviderSessionReaper", () => {
164
streamEvents: Stream.empty,
165
};
166
166
- const orchestrationEngine: OrchestrationEngineShape = {
167
- getReadModel: () => Effect.succeed(input.readModel),
168
- readEvents: () => Stream.empty,
169
- dispatch: () => unsupported(),
170
- streamDomainEvents: Stream.empty,
171
- };
172
-
167
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
168
Layer.provide(SqlitePersistenceMemory),
169
);
@@ -183,7 +177,27 @@ describe("ProviderSessionReaper", () => {
177
Layer.provideMerge(providerSessionDirectoryLayer),
178
Layer.provideMerge(runtimeRepositoryLayer),
179
Layer.provideMerge(Layer.succeed(ProviderService, providerService)),
186
- Layer.provideMerge(Layer.succeed(OrchestrationEngineService, orchestrationEngine)),
180
+ Layer.provideMerge(
181
+ Layer.succeed(ProjectionSnapshotQuery, {
182
+ getCommandReadModel: () => Effect.die("unused"),
183
+ getSnapshot: () => Effect.die("unused"),
184
+ getShellSnapshot: () => Effect.die("unused"),
185
+ getSnapshotSequence: () =>
186
+ Effect.succeed({ snapshotSequence: input.readModel.snapshotSequence }),
187
+ getCounts: () => Effect.die("unused"),
188
+ getActiveProjectByWorkspaceRoot: () => Effect.die("unused"),
189
+ getProjectShellById: () => Effect.die("unused"),
190
+ getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
191
+ getThreadCheckpointContext: () => Effect.die("unused"),
192
+ getThreadShellById: (threadId) =>
193
+ Effect.succeed(
194
+ input.readModel.threads.find((thread) => thread.id === threadId)
195
+ ? Option.some(input.readModel.threads.find((thread) => thread.id === threadId)!)
196
+ : Option.none(),
197
+ ),
198
+ getThreadDetailById: () => Effect.die("unused"),
199
+ }),
200
+ ),
201
Layer.provideMerge(NodeServices.layer),
202
);
203
apps/server/src/provider/Layers/ProviderSessionReaper.ts
+6
-6
@@ -1,6 +1,6 @@
1
-import { Duration, Effect, Layer, Schedule } from "effect";
1
+import { Duration, Effect, Layer, Option, Schedule } from "effect";
2
3
-import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
3
+import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
4
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
5
import {
6
ProviderSessionReaper,
@@ -20,7 +20,7 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
20
Effect.gen(function* () {
21
const providerService = yield* ProviderService;
22
const directory = yield* ProviderSessionDirectory;
23
- const orchestrationEngine = yield* OrchestrationEngineService;
23
+ const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
24
25
const inactivityThresholdMs = Math.max(
26
1,
@@ -29,8 +29,6 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
29
const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);
30
31
const sweep = Effect.gen(function* () {
32
- const readModel = yield* orchestrationEngine.getReadModel();
33
- const threadsById = new Map(readModel.threads.map((thread) => [thread.id, thread] as const));
32
const bindings = yield* directory.listBindings();
33
const now = Date.now();
34
let reapedCount = 0;
@@ -55,7 +53,9 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
53
continue;
54
}
55
58
- const thread = threadsById.get(binding.threadId);
56
+ const thread = yield* projectionSnapshotQuery
57
+ .getThreadShellById(binding.threadId)
58
+ .pipe(Effect.map(Option.getOrUndefined));
59
if (thread?.session?.activeTurnId != null) {
60
yield* Effect.logDebug("provider.session.reaper.skipped-active-turn", {
61
threadId: binding.threadId,
apps/server/src/server.test.ts
+2
-1
@@ -559,7 +559,6 @@ const buildAppUnderTest = (options?: {
559
),
560
Layer.provide(
561
Layer.mock(OrchestrationEngineService)({
562
- getReadModel: () => Effect.succeed(makeDefaultOrchestrationReadModel()),
562
readEvents: () => Stream.empty,
563
dispatch: () => Effect.succeed({ sequence: 0 }),
564
streamDomainEvents: Stream.empty,
@@ -568,6 +567,7 @@ const buildAppUnderTest = (options?: {
567
),
568
Layer.provide(
569
Layer.mock(ProjectionSnapshotQuery)({
570
+ getCommandReadModel: () => Effect.succeed(makeDefaultOrchestrationReadModel()),
571
getSnapshot: () => Effect.succeed(makeDefaultOrchestrationReadModel()),
572
getShellSnapshot: () =>
573
Effect.succeed({
@@ -576,6 +576,7 @@ const buildAppUnderTest = (options?: {
576
threads: [],
577
updatedAt: new Date(0).toISOString(),
578
}),
579
+ getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
580
getProjectShellById: () => Effect.succeed(Option.none()),
581
getThreadShellById: () => Effect.succeed(Option.none()),
582
getThreadDetailById: () => Effect.succeed(Option.none()),
apps/server/src/serverRuntimeStartup.test.ts
+6
-2
@@ -77,8 +77,10 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
77
78
yield* launchStartupHeartbeat.pipe(
79
Effect.provideService(ProjectionSnapshotQuery, {
80
+ getCommandReadModel: () => Effect.die("unused"),
81
getSnapshot: () => Effect.die("unused"),
82
getShellSnapshot: () => Effect.die("unused"),
83
+ getSnapshotSequence: () => Effect.die("unused"),
84
getCounts: () =>
85
Deferred.await(releaseCounts).pipe(
86
Effect.as({
@@ -129,8 +131,10 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
131
autoBootstrapProjectFromCwd: true,
132
} as never),
133
Effect.provideService(ProjectionSnapshotQuery, {
134
+ getCommandReadModel: () => Effect.die("unused"),
135
getSnapshot: () => Effect.die("unused"),
136
getShellSnapshot: () => Effect.die("unused"),
137
+ getSnapshotSequence: () => Effect.die("unused"),
138
getCounts: () => Effect.die("unused"),
139
getActiveProjectByWorkspaceRoot: () =>
140
Effect.succeed(
@@ -152,7 +156,6 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
156
getThreadDetailById: () => Effect.die("unused"),
157
}),
158
Effect.provideService(OrchestrationEngineService, {
155
- getReadModel: () => Effect.die("unused"),
159
readEvents: () => Stream.empty,
160
dispatch: (command) =>
161
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
@@ -180,8 +183,10 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
183
autoBootstrapProjectFromCwd: true,
184
} as never),
185
Effect.provideService(ProjectionSnapshotQuery, {
186
+ getCommandReadModel: () => Effect.die("unused"),
187
getSnapshot: () => Effect.die("unused"),
188
getShellSnapshot: () => Effect.die("unused"),
189
+ getSnapshotSequence: () => Effect.die("unused"),
190
getCounts: () => Effect.die("unused"),
191
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
192
getProjectShellById: () => Effect.die("unused"),
@@ -191,7 +196,6 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
196
getThreadDetailById: () => Effect.die("unused"),
197
}),
198
Effect.provideService(OrchestrationEngineService, {
194
- getReadModel: () => Effect.die("unused"),
199
readEvents: () => Stream.empty,
200
dispatch: (command) =>
201
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
apps/server/src/ws.ts
+18
-7
@@ -236,9 +236,13 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
236
return Effect.gen(function* () {
237
const workspaceRoot =
238
event.payload.workspaceRoot ??
239
- (yield* orchestrationEngine.getReadModel()).projects.find(
240
- (project) => project.id === event.payload.projectId,
241
- )?.workspaceRoot ??
239
+ Option.match(
240
+ yield* projectionSnapshotQuery.getProjectShellById(event.payload.projectId),
241
+ {
242
+ onNone: () => null,
243
+ onSome: (project) => project.workspaceRoot,
244
+ },
245
+ ) ??
246
null;
247
if (workspaceRoot === null) {
248
return event;
@@ -252,7 +256,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
256
repositoryIdentity,
257
},
258
} satisfies OrchestrationEvent;
255
- });
259
+ }).pipe(Effect.catch(() => Effect.succeed(event)));
260
default:
261
return Effect.succeed(event);
262
}
@@ -723,9 +727,16 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
727
}),
728
),
729
),
726
- orchestrationEngine
727
- .getReadModel()
728
- .pipe(Effect.map((readModel) => readModel.snapshotSequence)),
730
+ projectionSnapshotQuery.getSnapshotSequence().pipe(
731
+ Effect.map(({ snapshotSequence }) => snapshotSequence),
732
+ Effect.mapError(
733
+ (cause) =>
734
+ new OrchestrationGetSnapshotError({
735
+ message: "Failed to load orchestration snapshot sequence",
736
+ cause,
737
+ }),
738
+ ),
739
+ ),
740
]);
741
742
if (Option.isNone(threadDetail)) {
apps/web/src/environments/runtime/connection.test.ts
+33
-4
@@ -22,14 +22,14 @@ function createTestClient() {
22
environmentId: EnvironmentId.make("env-1"),
23
},
24
})),
25
- subscribeConfig: (listener: (event: any) => void) => {
25
+ subscribeConfig: vi.fn((listener: (event: any) => void) => {
26
configListeners.add(listener);
27
return () => configListeners.delete(listener);
28
- },
29
- subscribeLifecycle: (listener: (event: any) => void) => {
28
+ }),
29
+ subscribeLifecycle: vi.fn((listener: (event: any) => void) => {
30
lifecycleListeners.add(listener);
31
return () => lifecycleListeners.delete(listener);
32
- },
32
+ }),
33
subscribeAuthAccess: () => () => undefined,
34
refreshProviders: vi.fn(async () => undefined),
35
upsertKeybinding: vi.fn(async () => undefined),
@@ -237,4 +237,33 @@ describe("createEnvironmentConnection", () => {
237
238
await connection.dispose();
239
});
240
+
241
+ it("skips primary lifecycle/config subscriptions when no handlers are registered", async () => {
242
+ const environmentId = EnvironmentId.make("env-1");
243
+ const { client } = createTestClient();
244
+
245
+ const connection = createEnvironmentConnection({
246
+ kind: "primary",
247
+ knownEnvironment: {
248
+ id: "env-1",
249
+ label: "Local env",
250
+ source: "manual",
251
+ target: {
252
+ httpBaseUrl: "http://example.test",
253
+ wsBaseUrl: "ws://example.test",
254
+ },
255
+ environmentId,
256
+ },
257
+ client,
258
+ applyShellEvent: vi.fn(),
259
+ syncShellSnapshot: vi.fn(),
260
+ applyTerminalEvent: vi.fn(),
261
+ });
262
+
263
+ expect(client.server.subscribeLifecycle).not.toHaveBeenCalled();
264
+ expect(client.server.subscribeConfig).not.toHaveBeenCalled();
265
+ expect(client.orchestration.subscribeShell).toHaveBeenCalledOnce();
266
+
267
+ await connection.dispose();
268
+ });
269
});
apps/web/src/environments/runtime/connection.ts
+31
-22
@@ -83,6 +83,8 @@ export function createEnvironmentConnection(
83
84
let disposed = false;
85
const bootstrapGate = createBootstrapGate();
86
+ const shouldObserveLifecycle = input.kind === "saved" || input.onWelcome !== undefined;
87
+ const shouldObserveConfig = input.kind === "saved" || input.onConfigSnapshot !== undefined;
88
89
const observeEnvironmentIdentity = (nextEnvironmentId: EnvironmentId, source: string) => {
90
if (environmentId !== nextEnvironmentId) {
@@ -92,28 +94,35 @@ export function createEnvironmentConnection(
94
}
95
};
96
95
- const unsubLifecycle = input.client.server.subscribeLifecycle(
96
- (event: Parameters<Parameters<WsRpcClient["server"]["subscribeLifecycle"]>[0]>[0]) => {
97
- if (event.type !== "welcome") {
98
- return;
99
- }
100
- observeEnvironmentIdentity(
101
- event.payload.environment.environmentId,
102
- "server lifecycle welcome",
103
- );
104
- input.onWelcome?.(event.payload);
105
- },
106
- );
107
-
108
- const unsubConfig = input.client.server.subscribeConfig(
109
- (event: Parameters<Parameters<WsRpcClient["server"]["subscribeConfig"]>[0]>[0]) => {
110
- if (event.type !== "snapshot") {
111
- return;
112
- }
113
- observeEnvironmentIdentity(event.config.environment.environmentId, "server config snapshot");
114
- input.onConfigSnapshot?.(event.config);
115
- },
116
- );
97
+ const unsubLifecycle = shouldObserveLifecycle
98
+ ? input.client.server.subscribeLifecycle(
99
+ (event: Parameters<Parameters<WsRpcClient["server"]["subscribeLifecycle"]>[0]>[0]) => {
100
+ if (event.type !== "welcome") {
101
+ return;
102
+ }
103
+ observeEnvironmentIdentity(
104
+ event.payload.environment.environmentId,
105
+ "server lifecycle welcome",
106
+ );
107
+ input.onWelcome?.(event.payload);
108
+ },
109
+ )
110
+ : () => undefined;
111
+
112
+ const unsubConfig = shouldObserveConfig
113
+ ? input.client.server.subscribeConfig(
114
+ (event: Parameters<Parameters<WsRpcClient["server"]["subscribeConfig"]>[0]>[0]) => {
115
+ if (event.type !== "snapshot") {
116
+ return;
117
+ }
118
+ observeEnvironmentIdentity(
119
+ event.config.environment.environmentId,
120
+ "server config snapshot",
121
+ );
122
+ input.onConfigSnapshot?.(event.config);
123
+ },
124
+ )
125
+ : () => undefined;
126
127
const unsubShell = input.client.orchestration.subscribeShell(
128
(item: Parameters<Parameters<WsRpcClient["orchestration"]["subscribeShell"]>[0]>[0]) => {
apps/web/src/environments/runtime/service.savedEnvironments.test.ts
new
+326
@@ -0,0 +1,326 @@
1
+import { QueryClient } from "@tanstack/react-query";
2
+import { EnvironmentId } from "@t3tools/contracts";
3
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
+
5
+const mockCreateEnvironmentConnection = vi.fn();
6
+const mockCreateWsRpcClient = vi.fn();
7
+const mockFetchRemoteSessionState = vi.fn();
8
+const mockWaitForSavedEnvironmentRegistryHydration = vi.fn();
9
+const mockListSavedEnvironmentRecords = vi.fn();
10
+const mockSavedEnvironmentRegistrySubscribe = vi.fn();
11
+const mockReadSavedEnvironmentBearerToken = vi.fn();
12
+const mockGetSavedEnvironmentRecord = vi.fn();
13
+
14
+function MockWsTransport() {
15
+ return undefined;
16
+}
17
+
18
+vi.mock("../primary", () => ({
19
+ getPrimaryKnownEnvironment: vi.fn(() => ({
20
+ id: "env-1",
21
+ label: "Primary environment",
22
+ source: "window-origin",
23
+ target: {
24
+ httpBaseUrl: "http://127.0.0.1:3000/",
25
+ wsBaseUrl: "ws://127.0.0.1:3000/",
26
+ },
27
+ environmentId: EnvironmentId.make("env-1"),
28
+ })),
29
+}));
30
+
31
+vi.mock("../remote/api", () => ({
32
+ bootstrapRemoteBearerSession: vi.fn(),
33
+ fetchRemoteEnvironmentDescriptor: vi.fn(),
34
+ fetchRemoteSessionState: mockFetchRemoteSessionState,
35
+ resolveRemoteWebSocketConnectionUrl: vi.fn(() => "ws://remote.example.test"),
36
+}));
37
+
38
+vi.mock("./catalog", () => ({
39
+ getSavedEnvironmentRecord: mockGetSavedEnvironmentRecord,
40
+ hasSavedEnvironmentRegistryHydrated: vi.fn(() => true),
41
+ listSavedEnvironmentRecords: mockListSavedEnvironmentRecords,
42
+ persistSavedEnvironmentRecord: vi.fn(),
43
+ readSavedEnvironmentBearerToken: mockReadSavedEnvironmentBearerToken,
44
+ removeSavedEnvironmentBearerToken: vi.fn(),
45
+ useSavedEnvironmentRegistryStore: {
46
+ subscribe: mockSavedEnvironmentRegistrySubscribe,
47
+ getState: () => ({
48
+ upsert: vi.fn(),
49
+ remove: vi.fn(),
50
+ markConnected: vi.fn(),
51
+ rename: vi.fn(),
52
+ }),
53
+ },
54
+ useSavedEnvironmentRuntimeStore: {
55
+ getState: () => ({
56
+ ensure: vi.fn(),
57
+ patch: vi.fn(),
58
+ clear: vi.fn(),
59
+ }),
60
+ },
61
+ waitForSavedEnvironmentRegistryHydration: mockWaitForSavedEnvironmentRegistryHydration,
62
+ writeSavedEnvironmentBearerToken: vi.fn(),
63
+}));
64
+
65
+vi.mock("./connection", () => ({
66
+ createEnvironmentConnection: mockCreateEnvironmentConnection,
67
+}));
68
+
69
+vi.mock("../../rpc/wsRpcClient", () => ({
70
+ createWsRpcClient: mockCreateWsRpcClient,
71
+}));
72
+
73
+vi.mock("../../rpc/wsTransport", () => ({
74
+ WsTransport: MockWsTransport,
75
+}));
76
+
77
+vi.mock("~/composerDraftStore", () => ({
78
+ markPromotedDraftThreadByRef: vi.fn(),
79
+ markPromotedDraftThreadsByRef: vi.fn(),
80
+ useComposerDraftStore: {
81
+ getState: () => ({
82
+ getDraftThreadByRef: vi.fn(() => null),
83
+ clearDraftThread: vi.fn(),
84
+ }),
85
+ },
86
+}));
87
+
88
+vi.mock("~/localApi", () => ({
89
+ ensureLocalApi: vi.fn(() => ({
90
+ persistence: {
91
+ setSavedEnvironmentRegistry: vi.fn(async () => undefined),
92
+ },
93
+ })),
94
+}));
95
+
96
+vi.mock("~/lib/terminalStateCleanup", () => ({
97
+ collectActiveTerminalThreadIds: vi.fn(() => []),
98
+}));
99
+
100
+vi.mock("~/orchestrationEventEffects", () => ({
101
+ deriveOrchestrationBatchEffects: vi.fn(() => ({
102
+ promotedThreadRefs: [],
103
+ invalidatedProviderState: false,
104
+ })),
105
+}));
106
+
107
+vi.mock("~/lib/projectReactQuery", () => ({
108
+ projectQueryKeys: {
109
+ all: ["projects"],
110
+ },
111
+}));
112
+
113
+vi.mock("~/lib/providerReactQuery", () => ({
114
+ providerQueryKeys: {
115
+ all: ["providers"],
116
+ },
117
+}));
118
+
119
+vi.mock("~/store", () => ({
120
+ useStore: {
121
+ getState: () => ({
122
+ syncServerShellSnapshot: vi.fn(),
123
+ syncServerThreadDetail: vi.fn(),
124
+ removeServerThreadDetail: vi.fn(),
125
+ applyServerShellEvent: vi.fn(),
126
+ }),
127
+ },
128
+ selectProjectsAcrossEnvironments: vi.fn(() => []),
129
+ selectSidebarThreadSummaryByRef: vi.fn(() => null),
130
+ selectThreadByRef: vi.fn(() => null),
131
+ selectThreadsAcrossEnvironments: vi.fn(() => []),
132
+}));
133
+
134
+vi.mock("~/terminalStateStore", () => ({
135
+ useTerminalStateStore: {
136
+ getState: () => ({
137
+ applyTerminalEvent: vi.fn(),
138
+ removeTerminalState: vi.fn(),
139
+ clearTerminalSelection: vi.fn(),
140
+ }),
141
+ },
142
+}));
143
+
144
+vi.mock("~/uiStateStore", () => ({
145
+ useUiStateStore: {
146
+ getState: () => ({
147
+ clearThreadUi: vi.fn(),
148
+ syncPromotedDraftThreadRefs: vi.fn(),
149
+ }),
150
+ },
151
+}));
152
+
153
+const savedRecord = {
154
+ environmentId: EnvironmentId.make("env-saved"),
155
+ label: "Remote environment",
156
+ httpBaseUrl: "https://remote.example.test/",
157
+ wsBaseUrl: "wss://remote.example.test/",
158
+};
159
+
160
+const configSnapshot = {
161
+ environment: {
162
+ environmentId: savedRecord.environmentId,
163
+ label: "Remote environment",
164
+ },
165
+};
166
+
167
+function createClient() {
168
+ return {
169
+ dispose: vi.fn(async () => undefined),
170
+ reconnect: vi.fn(async () => undefined),
171
+ server: {
172
+ getConfig: vi.fn(async () => configSnapshot),
173
+ subscribeConfig: vi.fn(() => () => undefined),
174
+ subscribeLifecycle: vi.fn(() => () => undefined),
175
+ subscribeAuthAccess: vi.fn(() => () => undefined),
176
+ refreshProviders: vi.fn(async () => undefined),
177
+ upsertKeybinding: vi.fn(async () => undefined),
178
+ getSettings: vi.fn(async () => undefined),
179
+ updateSettings: vi.fn(async () => undefined),
180
+ },
181
+ orchestration: {
182
+ subscribeShell: vi.fn(() => () => undefined),
183
+ subscribeThread: vi.fn(() => () => undefined),
184
+ dispatchCommand: vi.fn(async () => undefined),
185
+ getTurnDiff: vi.fn(async () => undefined),
186
+ getFullThreadDiff: vi.fn(async () => undefined),
187
+ },
188
+ terminal: {
189
+ open: vi.fn(async () => undefined),
190
+ write: vi.fn(async () => undefined),
191
+ resize: vi.fn(async () => undefined),
192
+ clear: vi.fn(async () => undefined),
193
+ restart: vi.fn(async () => undefined),
194
+ close: vi.fn(async () => undefined),
195
+ onEvent: vi.fn(() => () => undefined),
196
+ },
197
+ projects: {
198
+ searchEntries: vi.fn(async () => []),
199
+ writeFile: vi.fn(async () => undefined),
200
+ },
201
+ shell: {
202
+ openInEditor: vi.fn(async () => undefined),
203
+ },
204
+ git: {
205
+ pull: vi.fn(async () => undefined),
206
+ refreshStatus: vi.fn(async () => undefined),
207
+ onStatus: vi.fn(() => () => undefined),
208
+ runStackedAction: vi.fn(async () => ({})),
209
+ listBranches: vi.fn(async () => []),
210
+ createWorktree: vi.fn(async () => undefined),
211
+ removeWorktree: vi.fn(async () => undefined),
212
+ createBranch: vi.fn(async () => undefined),
213
+ checkout: vi.fn(async () => undefined),
214
+ init: vi.fn(async () => undefined),
215
+ resolvePullRequest: vi.fn(async () => undefined),
216
+ preparePullRequestThread: vi.fn(async () => undefined),
217
+ },
218
+ };
219
+}
220
+
221
+describe("saved environment startup", () => {
222
+ beforeEach(() => {
223
+ vi.useFakeTimers();
224
+ vi.resetModules();
225
+ vi.clearAllMocks();
226
+
227
+ mockFetchRemoteSessionState.mockResolvedValue({
228
+ authenticated: true,
229
+ role: "owner",
230
+ });
231
+ mockGetSavedEnvironmentRecord.mockImplementation((environmentId: EnvironmentId) =>
232
+ environmentId === savedRecord.environmentId ? savedRecord : null,
233
+ );
234
+ mockListSavedEnvironmentRecords.mockReturnValue([savedRecord]);
235
+ mockSavedEnvironmentRegistrySubscribe.mockReturnValue(() => undefined);
236
+ mockWaitForSavedEnvironmentRegistryHydration.mockResolvedValue(undefined);
237
+ mockReadSavedEnvironmentBearerToken.mockResolvedValue("saved-bearer-token");
238
+ mockCreateWsRpcClient.mockImplementation(() => createClient());
239
+ mockCreateEnvironmentConnection.mockImplementation((input) => {
240
+ if (input.kind === "saved") {
241
+ queueMicrotask(() => {
242
+ input.onConfigSnapshot?.(configSnapshot);
243
+ });
244
+ }
245
+
246
+ return {
247
+ kind: input.kind,
248
+ environmentId: input.knownEnvironment.environmentId,
249
+ knownEnvironment: input.knownEnvironment,
250
+ client: input.client,
251
+ ensureBootstrapped: vi.fn(async () => undefined),
252
+ reconnect: vi.fn(async () => undefined),
253
+ dispose: vi.fn(async () => undefined),
254
+ };
255
+ });
256
+ });
257
+
258
+ afterEach(async () => {
259
+ const { resetEnvironmentServiceForTests } = await import("./service");
260
+ await resetEnvironmentServiceForTests();
261
+ vi.useRealTimers();
262
+ });
263
+
264
+ it("uses the initial config snapshot instead of issuing an extra getConfig call", async () => {
265
+ const { startEnvironmentConnectionService, resetEnvironmentServiceForTests } =
266
+ await import("./service");
267
+
268
+ const stop = startEnvironmentConnectionService(new QueryClient());
269
+ await vi.runAllTimersAsync();
270
+
271
+ const savedConnectionCall = mockCreateEnvironmentConnection.mock.calls.find(
272
+ ([input]) => input.kind === "saved",
273
+ );
274
+ expect(savedConnectionCall).toBeDefined();
275
+
276
+ const savedClient = savedConnectionCall?.[0]?.client;
277
+ expect(savedClient.server.getConfig).not.toHaveBeenCalled();
278
+ expect(mockFetchRemoteSessionState).toHaveBeenCalledTimes(1);
279
+
280
+ stop();
281
+ await resetEnvironmentServiceForTests();
282
+ });
283
+
284
+ it("coalesces hydration and registry sync so the initial saved connection only starts once", async () => {
285
+ let finishHydration!: () => void;
286
+ let finishTokenRead!: (token: string) => void;
287
+
288
+ mockWaitForSavedEnvironmentRegistryHydration.mockImplementation(
289
+ () =>
290
+ new Promise<void>((resolve) => {
291
+ finishHydration = () => resolve();
292
+ }),
293
+ );
294
+ mockReadSavedEnvironmentBearerToken.mockImplementation(
295
+ () =>
296
+ new Promise<string>((resolve) => {
297
+ finishTokenRead = resolve;
298
+ }),
299
+ );
300
+
301
+ const { startEnvironmentConnectionService, resetEnvironmentServiceForTests } =
302
+ await import("./service");
303
+
304
+ const stop = startEnvironmentConnectionService(new QueryClient());
305
+ const registryListener = mockSavedEnvironmentRegistrySubscribe.mock.calls[0]?.[0];
306
+ expect(registryListener).toBeTypeOf("function");
307
+
308
+ registryListener?.();
309
+ finishHydration();
310
+ await vi.waitFor(() => {
311
+ expect(mockReadSavedEnvironmentBearerToken).toHaveBeenCalledTimes(1);
312
+ });
313
+
314
+ finishTokenRead("saved-bearer-token");
315
+ await vi.runAllTimersAsync();
316
+
317
+ const savedConnectionCalls = mockCreateEnvironmentConnection.mock.calls.filter(
318
+ ([input]) => input.kind === "saved",
319
+ );
320
+ expect(savedConnectionCalls).toHaveLength(1);
321
+ expect(mockFetchRemoteSessionState).toHaveBeenCalledTimes(1);
322
+
323
+ stop();
324
+ await resetEnvironmentServiceForTests();
325
+ });
326
+});
apps/web/src/environments/runtime/service.threadSubscriptions.test.ts
+3
-1
@@ -369,7 +369,9 @@ describe("retainThreadDetailSubscription", () => {
369
listEnvironmentConnections().some((connection) => connection.environmentId === environmentId),
370
).toBe(false);
371
372
- await reconnectSavedEnvironment(environmentId);
372
+ const reconnectPromise = reconnectSavedEnvironment(environmentId);
373
+ await vi.advanceTimersByTimeAsync(200);
374
+ await reconnectPromise;
375
await vi.waitFor(() => {
376
expect(mockCreateEnvironmentConnection).toHaveBeenCalledTimes(3);
377
expect(mockSubscribeThread).toHaveBeenCalledTimes(2);
apps/web/src/environments/runtime/service.ts
+73
-4
@@ -139,9 +139,70 @@ let lastBrowserResumeReconnectAt = Number.NEGATIVE_INFINITY;
139
const THREAD_DETAIL_SUBSCRIPTION_IDLE_EVICTION_MS = 15 * 60 * 1000;
140
const MAX_CACHED_THREAD_DETAIL_SUBSCRIPTIONS = 32;
141
const BROWSER_RESUME_RECONNECT_COOLDOWN_MS = 2_000;
142
+const INITIAL_SERVER_CONFIG_SNAPSHOT_WAIT_MS = 150;
143
const NOOP = () => undefined;
144
const SSH_HTTP_STATUS_RE = /^\[ssh_http:(\d+)\]\s/u;
145
146
+function createDeferredPromise<T>() {
147
+ let resolve: ((value: T) => void) | null = null;
148
+ const promise = new Promise<T>((nextResolve) => {
149
+ resolve = nextResolve;
150
+ });
151
+
152
+ return {
153
+ promise,
154
+ resolve: (value: T) => {
155
+ resolve?.(value);
156
+ resolve = null;
157
+ },
158
+ };
159
+}
160
+
161
+async function waitForConfigSnapshot(
162
+ promise: Promise<ServerConfig>,
163
+ timeoutMs: number,
164
+): Promise<ServerConfig | null> {
165
+ return await new Promise<ServerConfig | null>((resolve) => {
166
+ const timeoutId = globalThis.setTimeout(() => resolve(null), timeoutMs);
167
+ promise.then(
168
+ (config) => {
169
+ clearTimeout(timeoutId);
170
+ resolve(config);
171
+ },
172
+ () => {
173
+ clearTimeout(timeoutId);
174
+ resolve(null);
175
+ },
176
+ );
177
+ });
178
+}
179
+
180
+function createSavedEnvironmentSyncScheduler() {
181
+ let activeSync: Promise<void> | null = null;
182
+ let queued = false;
183
+
184
+ const run = async (): Promise<void> => {
185
+ do {
186
+ queued = false;
187
+ await syncSavedEnvironmentConnections(listSavedEnvironmentRecords());
188
+ } while (queued);
189
+ };
190
+
191
+ return () => {
192
+ if (activeSync) {
193
+ queued = true;
194
+ return activeSync;
195
+ }
196
+
197
+ activeSync = run()
198
+ .catch(() => undefined)
199
+ .finally(() => {
200
+ activeSync = null;
201
+ });
202
+
203
+ return activeSync;
204
+ };
205
+}
206
function compareAppliedProjectionVersion(
207
left: { readonly sequence: number; readonly updatedAt: string | null },
208
right: { readonly sequence: number; readonly updatedAt: string | null },
@@ -233,7 +294,6 @@ function markAppliedProjectionEvent(environmentId: EnvironmentId, sequence: numb
294
updatedAt: currentVersion?.updatedAt ?? null,
295
});
296
}
236
-
297
function getThreadDetailSubscriptionKey(environmentId: EnvironmentId, threadId: ThreadId): string {
298
return scopedThreadKey(scopeThreadRef(environmentId, threadId));
299
}
@@ -1284,6 +1344,7 @@ async function ensureSavedEnvironmentConnection(
1344
const client =
1345
options?.client ??
1346
createSavedEnvironmentClient(activeRecord.environmentId, activeBearerToken);
1347
+ const initialConfigSnapshot = createDeferredPromise<ServerConfig>();
1348
const knownEnvironment = createKnownEnvironment({
1349
id: activeRecord.environmentId,
1350
label: activeRecord.label,
@@ -1308,6 +1369,7 @@ async function ensureSavedEnvironmentConnection(
1369
);
1370
},
1371
onConfigSnapshot: (config) => {
1372
+ initialConfigSnapshot.resolve(config);
1373
useSavedEnvironmentRuntimeStore.getState().patch(activeRecord.environmentId, {
1374
descriptor: config.environment,
1375
serverConfig: config,
@@ -1323,12 +1385,18 @@ async function ensureSavedEnvironmentConnection(
1385
1386
try {
1387
try {
1388
+ const initialServerConfig =
1389
+ options?.serverConfig ??
1390
+ (await waitForConfigSnapshot(
1391
+ initialConfigSnapshot.promise,
1392
+ INITIAL_SERVER_CONFIG_SNAPSHOT_WAIT_MS,
1393
+ ));
1394
await refreshSavedEnvironmentMetadata(
1395
activeRecord.environmentId,
1396
activeBearerToken,
1397
client,
1398
roleHint,
1331
- options?.serverConfig ?? null,
1399
+ initialServerConfig,
1400
);
1401
} catch (error) {
1402
const isAuthError = activeRecord.desktopSsh
@@ -1699,6 +1767,7 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): ()
1767
trailing: true,
1768
},
1769
);
1770
+ const requestSavedEnvironmentSync = createSavedEnvironmentSyncScheduler();
1771
1772
maybeCreatePrimaryEnvironmentConnection();
1773
@@ -1706,11 +1775,11 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): ()
1775
if (!hasSavedEnvironmentRegistryHydrated()) {
1776
return;
1777
}
1709
- void syncSavedEnvironmentConnections(listSavedEnvironmentRecords());
1778
+ void requestSavedEnvironmentSync();
1779
});
1780
1781
void waitForSavedEnvironmentRegistryHydration()
1713
- .then(() => syncSavedEnvironmentConnections(listSavedEnvironmentRecords()))
1782
+ .then(() => requestSavedEnvironmentSync())
1783
.catch(() => undefined);
1784
1785
const unsubscribeBrowserResumeReconnects = subscribeBrowserResumeReconnects();