Open History to see the last commit
1import {
2 EnvironmentId,
3 ProjectId,
4 ProviderInstanceId,
5 ThreadId,
6 type OrchestrationShellSnapshot,
7 type OrchestrationThread,
8} from "@t3tools/contracts";
9import { describe, expect, it } from "@effect/vitest";
10import * as Option from "effect/Option";
11import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
12
13import { PrimaryConnectionTarget } from "../connection/model.ts";
14import {
15 InvalidScopedProjectKeyError,
16 InvalidScopedProjectRefCollectionKeyError,
17 InvalidScopedThreadKeyError,
18 parseProjectKey,
19 parseProjectRefCollectionKey,
20 parseThreadKey,
21} from "./entities.ts";
22import type { EnvironmentShellState } from "./shell.ts";
23import { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState } from "./threads.ts";
24import { createEnvironmentProjectAtoms } from "./projectEntities.ts";
25import { createEnvironmentSnapshotAtom } from "./snapshots.ts";
26import { createEnvironmentThreadDetailAtoms } from "./threadDetail.ts";
27import { mergeEnvironmentThread } from "./threadDetail.ts";
28import { createEnvironmentThreadShellAtoms } from "./threadShell.ts";
29import { applyShellStreamEvent } from "./shellReducer.ts";
30
31const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
32const PROJECT_ID = ProjectId.make("project-1");
33const OTHER_PROJECT_ID = ProjectId.make("project-2");
34const THREAD_ID = ThreadId.make("thread-1");
35const OTHER_THREAD_ID = ThreadId.make("thread-2");
36
37describe("scoped entity keys", () => {
38 it("preserves an invalid project key as structured error data", () => {
39 const key = "missing-project-key-separator";
40 let error: unknown;
41
42 try {
43 parseProjectKey(key);
44 } catch (cause) {
45 error = cause;
46 }
47
48 expect(error).toEqual(new InvalidScopedProjectKeyError({ key }));
49 });
50
51 it("preserves an invalid thread key as structured error data", () => {
52 const key = "missing-thread-key-separator";
53 let error: unknown;
54
55 try {
56 parseThreadKey(key);
57 } catch (cause) {
58 error = cause;
59 }
60
61 expect(error).toEqual(new InvalidScopedThreadKeyError({ key }));
62 });
63
64 it("preserves malformed project reference collection input and its cause", () => {
65 const key = "not-json";
66 let error: unknown;
67
68 try {
69 parseProjectRefCollectionKey(key);
70 } catch (cause) {
71 error = cause;
72 }
73
74 expect(error).toBeInstanceOf(InvalidScopedProjectRefCollectionKeyError);
75 expect(error).toMatchObject({ key, cause: expect.anything() });
76 });
77
78 it("rejects invalid project reference collection shapes", () => {
79 const key = JSON.stringify([["environment-1"]]);
80
81 expect(() => parseProjectRefCollectionKey(key)).toThrowError(
82 InvalidScopedProjectRefCollectionKeyError,
83 );
84 });
85});
86
87const THREAD_SHELL = {
88 id: THREAD_ID,
89 projectId: PROJECT_ID,
90 title: "Thread",
91 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
92 runtimeMode: "full-access",
93 interactionMode: "default",
94 branch: null,
95 worktreePath: null,
96 latestTurn: null,
97 createdAt: "2026-06-01T00:00:00.000Z",
98 updatedAt: "2026-06-01T00:00:00.000Z",
99 archivedAt: null,
100 settledOverride: null,
101 settledAt: null,
102 pullRequests: [],
103 session: null,
104 latestUserMessageAt: null,
105 hasPendingApprovals: false,
106 hasPendingUserInput: false,
107 hasActionableProposedPlan: false,
108} as const;
109
110const SNAPSHOT: OrchestrationShellSnapshot = {
111 snapshotSequence: 1,
112 updatedAt: "2026-06-01T00:00:00.000Z",
113 projects: [
114 {
115 id: PROJECT_ID,
116 title: "Project",
117 workspaceRoot: "/repo",
118 repositoryIdentity: null,
119 defaultModelSelection: null,
120 scripts: [],
121 createdAt: "2026-06-01T00:00:00.000Z",
122 updatedAt: "2026-06-01T00:00:00.000Z",
123 },
124 {
125 id: OTHER_PROJECT_ID,
126 title: "Other project",
127 workspaceRoot: "/other-repo",
128 repositoryIdentity: null,
129 defaultModelSelection: null,
130 scripts: [],
131 createdAt: "2026-06-01T00:00:00.000Z",
132 updatedAt: "2026-06-01T00:00:00.000Z",
133 },
134 ],
135 threads: [
136 THREAD_SHELL,
137 {
138 ...THREAD_SHELL,
139 id: OTHER_THREAD_ID,
140 projectId: OTHER_PROJECT_ID,
141 title: "Other thread",
142 },
143 ],
144};
145
146function shellState(snapshot: OrchestrationShellSnapshot): EnvironmentShellState {
147 return {
148 snapshot: Option.some(snapshot),
149 status: "live",
150 error: Option.none(),
151 };
152}
153
154function makeHarness(environmentIds: ReadonlyArray<EnvironmentId> = [ENVIRONMENT_ID]) {
155 const shellStateAtoms = Atom.family((_environmentId: EnvironmentId) =>
156 Atom.make(AsyncResult.success(shellState(SNAPSHOT))),
157 );
158 const threadStateAtoms = Atom.family((_key: string) =>
159 Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)),
160 );
161 const catalogValueAtom = Atom.make({
162 isReady: true,
163 entries: new Map(
164 environmentIds.map((environmentId) => [
165 environmentId,
166 {
167 target: new PrimaryConnectionTarget({
168 environmentId,
169 label: "Environment",
170 httpBaseUrl: "https://example.test",
171 wsBaseUrl: "wss://example.test",
172 }),
173 profile: Option.none(),
174 },
175 ]),
176 ),
177 });
178 const snapshotAtom = createEnvironmentSnapshotAtom(shellStateAtoms);
179 const projects = createEnvironmentProjectAtoms({
180 catalogValueAtom,
181 snapshotAtom,
182 });
183 const threadShells = createEnvironmentThreadShellAtoms({
184 catalogValueAtom,
185 snapshotAtom,
186 });
187 const threadDetails = createEnvironmentThreadDetailAtoms((environmentId, threadId) =>
188 threadStateAtoms(`${environmentId}\u0000${threadId}`),
189 );
190
191 return {
192 registry: AtomRegistry.make(),
193 catalogValueAtom,
194 shellStateAtom: shellStateAtoms(ENVIRONMENT_ID),
195 shellStateAtomForEnvironment: shellStateAtoms,
196 threadStateAtom: (threadId: ThreadId) => threadStateAtoms(`${ENVIRONMENT_ID}\u0000${threadId}`),
197 projects,
198 threadShells,
199 threadDetails,
200 };
201}
202
203describe("environment entity projections", () => {
204 it("composes detail collections with authoritative shell workspace metadata", () => {
205 const messages: OrchestrationThread["messages"] = [];
206 const detail = {
207 ...THREAD_SHELL,
208 environmentId: ENVIRONMENT_ID,
209 title: "Cached thread",
210 branch: "stale-branch",
211 worktreePath: "/repo/stale-worktree",
212 activeOrderKey: "t",
213 unsettledAt: "2026-03-09T10:00:00.000Z",
214 deletedAt: null,
215 messages,
216 proposedPlans: [],
217 activities: [],
218 checkpoints: [],
219 } satisfies OrchestrationThread & { readonly environmentId: EnvironmentId };
220 const shell = {
221 ...THREAD_SHELL,
222 environmentId: ENVIRONMENT_ID,
223 title: "Current thread",
224 branch: "current-branch",
225 worktreePath: "/repo/current-worktree",
226 activeOrderKey: "f",
227 unsettledAt: "2026-03-09T12:00:00.000Z",
228 };
229
230 const merged = mergeEnvironmentThread(detail, shell);
231
232 expect(merged).toMatchObject({
233 title: "Current thread",
234 branch: "current-branch",
235 worktreePath: "/repo/current-worktree",
236 activeOrderKey: "f",
237 unsettledAt: "2026-03-09T12:00:00.000Z",
238 });
239 expect(merged?.messages).toBe(messages);
240 });
241
242 it("preserves untouched project and thread identities across unrelated shell updates", () => {
243 const harness = makeHarness();
244 const projectRefsAtom = harness.projects.environmentProjectRefsAtom(ENVIRONMENT_ID);
245 const threadRefsAtom = harness.threadShells.environmentThreadRefsAtom(ENVIRONMENT_ID);
246 const projectsAtom = harness.projects.projectsAtom;
247 const projectAtom = harness.projects.projectAtom({
248 environmentId: ENVIRONMENT_ID,
249 projectId: PROJECT_ID,
250 });
251 const threadAtom = harness.threadShells.threadShellAtom({
252 environmentId: ENVIRONMENT_ID,
253 threadId: THREAD_ID,
254 });
255 const projectRefs = harness.registry.get(projectRefsAtom);
256 const threadRefs = harness.registry.get(threadRefsAtom);
257 const projects = harness.registry.get(projectsAtom);
258 const project = harness.registry.get(projectAtom);
259 const thread = harness.registry.get(threadAtom);
260
261 harness.registry.set(
262 harness.shellStateAtom,
263 AsyncResult.success(
264 shellState({
265 ...SNAPSHOT,
266 snapshotSequence: 2,
267 threads: SNAPSHOT.threads.map((candidate) =>
268 candidate.id === OTHER_THREAD_ID
269 ? { ...candidate, title: "Renamed other thread" }
270 : candidate,
271 ),
272 }),
273 ),
274 );
275
276 expect(harness.registry.get(projectRefsAtom)).toBe(projectRefs);
277 expect(harness.registry.get(threadRefsAtom)).toBe(threadRefs);
278 expect(harness.registry.get(projectsAtom)).toBe(projects);
279 expect(harness.registry.get(projectAtom)).toBe(project);
280 expect(harness.registry.get(threadAtom)).toBe(thread);
281 });
282
283 it("preserves project-scoped thread collections across unrelated project updates", () => {
284 const harness = makeHarness();
285 const projectRef = {
286 environmentId: ENVIRONMENT_ID,
287 projectId: PROJECT_ID,
288 };
289 const refsByProjectAtom =
290 harness.threadShells.environmentThreadRefsByProjectAtom(ENVIRONMENT_ID);
291 const threadsAtom = harness.threadShells.threadShellsForProjectRefsAtom([projectRef]);
292 const membership = harness.registry.get(refsByProjectAtom);
293 const refs = membership.get(PROJECT_ID);
294 const threads = harness.registry.get(threadsAtom);
295
296 expect(threads).toHaveLength(1);
297 expect(threads[0]?.id).toBe(THREAD_ID);
298
299 harness.registry.set(
300 harness.shellStateAtom,
301 AsyncResult.success(
302 shellState({
303 ...SNAPSHOT,
304 snapshotSequence: 2,
305 threads: SNAPSHOT.threads.map((thread) =>
306 thread.id === OTHER_THREAD_ID ? { ...thread, title: "Updated elsewhere" } : thread,
307 ),
308 }),
309 ),
310 );
311
312 expect(harness.registry.get(refsByProjectAtom).get(PROJECT_ID)).toBe(refs);
313 expect(harness.registry.get(refsByProjectAtom)).toBe(membership);
314 expect(harness.registry.get(threadsAtom)).toBe(threads);
315 });
316
317 it("shares list values with point reads without retaining one atom per listed thread", () => {
318 const harness = makeHarness();
319 let snapshot: OrchestrationShellSnapshot = {
320 ...SNAPSHOT,
321 threads: Array.from({ length: 200 }, (_, index) => ({
322 ...THREAD_SHELL,
323 id: ThreadId.make(`listed-${index}`),
324 })),
325 };
326 harness.registry.set(harness.shellStateAtom, AsyncResult.success(shellState(snapshot)));
327 const listAtom = harness.threadShells.threadShellsAtom;
328 const projectListAtom = harness.threadShells.threadShellsForProjectRefsAtom([
329 { environmentId: ENVIRONMENT_ID, projectId: PROJECT_ID },
330 ]);
331 const disposeList = harness.registry.mount(listAtom);
332 const disposeProjectList = harness.registry.mount(projectListAtom);
333 try {
334 const before = harness.registry.get(listAtom);
335 expect(before).toHaveLength(200);
336 expect(harness.registry.get(projectListAtom)).toEqual(before);
337 expect(harness.registry.getNodes().size).toBeLessThan(20);
338 const firstAtom = harness.threadShells.threadShellAtom({
339 environmentId: ENVIRONMENT_ID,
340 threadId: snapshot.threads[0]!.id,
341 });
342 expect(harness.registry.get(firstAtom)).toBe(before[0]);
343
344 snapshot = applyShellStreamEvent(snapshot, {
345 kind: "thread-upserted",
346 sequence: 2,
347 thread: { ...snapshot.threads.at(-1)!, title: "Updated last thread" },
348 });
349 harness.registry.set(harness.shellStateAtom, AsyncResult.success(shellState(snapshot)));
350 const after = harness.registry.get(listAtom);
351 expect(after[0]).toBe(before[0]);
352 expect(after.at(-1)).not.toBe(before.at(-1));
353 expect(after.at(-1)?.title).toBe("Updated last thread");
354 expect(harness.registry.get(projectListAtom).at(-1)).toBe(after.at(-1));
355 expect(harness.registry.get(firstAtom)).toBe(after[0]);
356 expect(harness.registry.getNodes().size).toBeLessThan(20);
357 } finally {
358 disposeProjectList();
359 disposeList();
360 harness.registry.dispose();
361 }
362 });
363
364 it("keeps scoped identities and list order across project and environment changes", () => {
365 const remoteEnvironmentId = EnvironmentId.make("remote-environment");
366 const harness = makeHarness([ENVIRONMENT_ID, remoteEnvironmentId]);
367 const listAtom = harness.threadShells.threadShellsAtom;
368 const localRef = { environmentId: ENVIRONMENT_ID, threadId: THREAD_ID };
369 const remoteRef = { environmentId: remoteEnvironmentId, threadId: THREAD_ID };
370 const selectedAtom = harness.threadShells.threadShellsForProjectRefsAtom([
371 { environmentId: remoteEnvironmentId, projectId: PROJECT_ID },
372 { environmentId: ENVIRONMENT_ID, projectId: OTHER_PROJECT_ID },
373 { environmentId: remoteEnvironmentId, projectId: PROJECT_ID },
374 { environmentId: ENVIRONMENT_ID, projectId: PROJECT_ID },
375 ]);
376 const disposeList = harness.registry.mount(listAtom);
377 const disposeSelected = harness.registry.mount(selectedAtom);
378 try {
379 const original = harness.registry.get(listAtom);
380 const local = harness.registry.get(harness.threadShells.threadShellAtom(localRef));
381 const remote = harness.registry.get(harness.threadShells.threadShellAtom(remoteRef));
382 expect(original).toHaveLength(4);
383 expect(original[0]).toBe(local);
384 expect(original[2]).toBe(remote);
385 expect(local).not.toBe(remote);
386 expect(local?.environmentId).toBe(ENVIRONMENT_ID);
387 expect(remote?.environmentId).toBe(remoteEnvironmentId);
388 expect(harness.registry.get(selectedAtom)).toEqual([remote, original[1], local]);
389
390 harness.registry.set(
391 harness.shellStateAtomForEnvironment(remoteEnvironmentId),
392 AsyncResult.success(shellState({ ...SNAPSHOT, threads: SNAPSHOT.threads.toReversed() })),
393 );
394 expect([
395 ...harness.registry
396 .get(harness.threadShells.environmentThreadRefsByProjectAtom(remoteEnvironmentId))
397 .keys(),
398 ]).toEqual([OTHER_PROJECT_ID, PROJECT_ID]);
399 harness.registry.set(
400 harness.shellStateAtomForEnvironment(remoteEnvironmentId),
401 AsyncResult.success(shellState(SNAPSHOT)),
402 );
403
404 let snapshot = applyShellStreamEvent(SNAPSHOT, {
405 kind: "thread-upserted",
406 sequence: 2,
407 thread: { ...THREAD_SHELL, projectId: OTHER_PROJECT_ID, title: "Moved thread" },
408 });
409 harness.registry.set(harness.shellStateAtom, AsyncResult.success(shellState(snapshot)));
410 const moved = harness.registry.get(harness.threadShells.threadShellAtom(localRef));
411 expect(harness.registry.get(selectedAtom)).toEqual([remote, moved, original[1]]);
412 expect(harness.registry.get(listAtom)[2]).toBe(remote);
413
414 snapshot = applyShellStreamEvent(snapshot, {
415 kind: "thread-removed",
416 sequence: 3,
417 threadId: OTHER_THREAD_ID,
418 });
419 harness.registry.set(harness.shellStateAtom, AsyncResult.success(shellState(snapshot)));
420 expect(harness.registry.get(selectedAtom)).toEqual([remote, moved]);
421 expect(
422 harness.registry.get(
423 harness.threadShells.threadShellAtom({
424 environmentId: ENVIRONMENT_ID,
425 threadId: OTHER_THREAD_ID,
426 }),
427 ),
428 ).toBeNull();
429
430 const createdId = ThreadId.make("created-thread");
431 snapshot = applyShellStreamEvent(snapshot, {
432 kind: "thread-upserted",
433 sequence: 4,
434 thread: { ...THREAD_SHELL, id: createdId },
435 });
436 harness.registry.set(harness.shellStateAtom, AsyncResult.success(shellState(snapshot)));
437 const created = harness.registry.get(listAtom)[1];
438 expect(created?.id).toBe(createdId);
439 expect(harness.registry.get(selectedAtom)).toEqual([remote, moved, created]);
440
441 const catalog = harness.registry.get(harness.catalogValueAtom);
442 harness.registry.set(harness.catalogValueAtom, {
443 ...catalog,
444 entries: new Map([...catalog.entries].toReversed()),
445 });
446 expect(harness.registry.get(listAtom)).toEqual([remote, original[3], moved, created]);
447 harness.registry.set(harness.catalogValueAtom, {
448 ...catalog,
449 entries: new Map([[remoteEnvironmentId, catalog.entries.get(remoteEnvironmentId)!]]),
450 });
451 expect(harness.registry.get(listAtom)).toEqual([remote, original[3]]);
452 harness.registry.set(
453 harness.shellStateAtomForEnvironment(remoteEnvironmentId),
454 AsyncResult.success(shellState({ ...SNAPSHOT, threads: [] })),
455 );
456 expect(harness.registry.get(listAtom)).toEqual([]);
457 expect(harness.registry.get(harness.threadShells.threadShellAtom(remoteRef))).toBeNull();
458 } finally {
459 disposeSelected();
460 disposeList();
461 harness.registry.dispose();
462 }
463 });
464
465 it("updates only the requested thread detail and preserves untouched field identities", () => {
466 const harness = makeHarness();
467 const threadRef = {
468 environmentId: ENVIRONMENT_ID,
469 threadId: THREAD_ID,
470 };
471 const otherThreadRef = {
472 environmentId: ENVIRONMENT_ID,
473 threadId: OTHER_THREAD_ID,
474 };
475 const threadDetailAtom = harness.threadDetails.detailAtom(threadRef);
476 const messagesAtom = harness.threadDetails.messagesAtom(threadRef);
477 const activitiesAtom = harness.threadDetails.activitiesAtom(threadRef);
478 const statusAtom = harness.threadDetails.statusAtom(threadRef);
479 const otherThreadDetailAtom = harness.threadDetails.detailAtom(otherThreadRef);
480 const otherValue = harness.registry.get(otherThreadDetailAtom);
481 const detail = {
482 ...THREAD_SHELL,
483 deletedAt: null,
484 messages: [],
485 proposedPlans: [],
486 activities: [],
487 checkpoints: [],
488 } satisfies OrchestrationThread;
489
490 harness.registry.set(
491 harness.threadStateAtom(THREAD_ID),
492 AsyncResult.success<EnvironmentThreadState>({
493 data: Option.some(detail),
494 status: "live",
495 error: Option.none(),
496 page: Option.none(),
497 }),
498 );
499
500 const scopedDetail = harness.registry.get(threadDetailAtom);
501 const messages = harness.registry.get(messagesAtom);
502 const activities = harness.registry.get(activitiesAtom);
503
504 expect(scopedDetail).toEqual({ ...detail, environmentId: ENVIRONMENT_ID });
505 expect(harness.registry.get(statusAtom)).toBe("live");
506 expect(harness.registry.get(otherThreadDetailAtom)).toBe(otherValue);
507
508 harness.registry.set(
509 harness.threadStateAtom(THREAD_ID),
510 AsyncResult.success<EnvironmentThreadState>({
511 data: Option.some({
512 ...detail,
513 session: {
514 threadId: THREAD_ID,
515 status: "ready",
516 providerName: "codex",
517 runtimeMode: "full-access",
518 activeTurnId: null,
519 lastError: null,
520 updatedAt: "2026-06-01T00:01:00.000Z",
521 },
522 }),
523 status: "live",
524 error: Option.none(),
525 page: Option.none(),
526 }),
527 );
528
529 expect(harness.registry.get(messagesAtom)).toBe(messages);
530 expect(harness.registry.get(activitiesAtom)).toBe(activities);
531 });
532});