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 session: null,
103 latestUserMessageAt: null,
104 hasPendingApprovals: false,
105 hasPendingUserInput: false,
106 hasActionableProposedPlan: false,
107} as const;
108
109const SNAPSHOT: OrchestrationShellSnapshot = {
110 snapshotSequence: 1,
111 updatedAt: "2026-06-01T00:00:00.000Z",
112 projects: [
113 {
114 id: PROJECT_ID,
115 title: "Project",
116 workspaceRoot: "/repo",
117 repositoryIdentity: null,
118 defaultModelSelection: null,
119 scripts: [],
120 createdAt: "2026-06-01T00:00:00.000Z",
121 updatedAt: "2026-06-01T00:00:00.000Z",
122 },
123 {
124 id: OTHER_PROJECT_ID,
125 title: "Other project",
126 workspaceRoot: "/other-repo",
127 repositoryIdentity: null,
128 defaultModelSelection: null,
129 scripts: [],
130 createdAt: "2026-06-01T00:00:00.000Z",
131 updatedAt: "2026-06-01T00:00:00.000Z",
132 },
133 ],
134 threads: [
135 THREAD_SHELL,
136 {
137 ...THREAD_SHELL,
138 id: OTHER_THREAD_ID,
139 projectId: OTHER_PROJECT_ID,
140 title: "Other thread",
141 },
142 ],
143};
144
145function shellState(snapshot: OrchestrationShellSnapshot): EnvironmentShellState {
146 return {
147 snapshot: Option.some(snapshot),
148 status: "live",
149 error: Option.none(),
150 };
151}
152
153function makeHarness(environmentIds: ReadonlyArray<EnvironmentId> = [ENVIRONMENT_ID]) {
154 const shellStateAtoms = Atom.family((_environmentId: EnvironmentId) =>
155 Atom.make(AsyncResult.success(shellState(SNAPSHOT))),
156 );
157 const threadStateAtoms = Atom.family((_key: string) =>
158 Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)),
159 );
160 const catalogValueAtom = Atom.make({
161 isReady: true,
162 entries: new Map(
163 environmentIds.map((environmentId) => [
164 environmentId,
165 {
166 target: new PrimaryConnectionTarget({
167 environmentId,
168 label: "Environment",
169 httpBaseUrl: "https://example.test",
170 wsBaseUrl: "wss://example.test",
171 }),
172 profile: Option.none(),
173 },
174 ]),
175 ),
176 });
177 const snapshotAtom = createEnvironmentSnapshotAtom(shellStateAtoms);
178 const projects = createEnvironmentProjectAtoms({
179 catalogValueAtom,
180 snapshotAtom,
181 });
182 const threadShells = createEnvironmentThreadShellAtoms({
183 catalogValueAtom,
184 snapshotAtom,
185 });
186 const threadDetails = createEnvironmentThreadDetailAtoms((environmentId, threadId) =>
187 threadStateAtoms(`${environmentId}\u0000${threadId}`),
188 );
189
190 return {
191 registry: AtomRegistry.make(),
192 catalogValueAtom,
193 shellStateAtom: shellStateAtoms(ENVIRONMENT_ID),
194 shellStateAtomForEnvironment: shellStateAtoms,
195 threadStateAtom: (threadId: ThreadId) => threadStateAtoms(`${ENVIRONMENT_ID}\u0000${threadId}`),
196 projects,
197 threadShells,
198 threadDetails,
199 };
200}
201
202describe("environment entity projections", () => {
203 it("composes detail collections with authoritative shell workspace metadata", () => {
204 const messages: OrchestrationThread["messages"] = [];
205 const detail = {
206 ...THREAD_SHELL,
207 environmentId: ENVIRONMENT_ID,
208 title: "Cached thread",
209 branch: "stale-branch",
210 worktreePath: "/repo/stale-worktree",
211 deletedAt: null,
212 messages,
213 proposedPlans: [],
214 activities: [],
215 checkpoints: [],
216 } satisfies OrchestrationThread & { readonly environmentId: EnvironmentId };
217 const shell = {
218 ...THREAD_SHELL,
219 environmentId: ENVIRONMENT_ID,
220 title: "Current thread",
221 branch: "current-branch",
222 worktreePath: "/repo/current-worktree",
223 };
224
225 const merged = mergeEnvironmentThread(detail, shell);
226
227 expect(merged).toMatchObject({
228 title: "Current thread",
229 branch: "current-branch",
230 worktreePath: "/repo/current-worktree",
231 });
232 expect(merged?.messages).toBe(messages);
233 });
234
235 it("preserves untouched project and thread identities across unrelated shell updates", () => {
236 const harness = makeHarness();
237 const projectRefsAtom = harness.projects.environmentProjectRefsAtom(ENVIRONMENT_ID);
238 const threadRefsAtom = harness.threadShells.environmentThreadRefsAtom(ENVIRONMENT_ID);
239 const projectsAtom = harness.projects.projectsAtom;
240 const projectAtom = harness.projects.projectAtom({
241 environmentId: ENVIRONMENT_ID,
242 projectId: PROJECT_ID,
243 });
244 const threadAtom = harness.threadShells.threadShellAtom({
245 environmentId: ENVIRONMENT_ID,
246 threadId: THREAD_ID,
247 });
248 const projectRefs = harness.registry.get(projectRefsAtom);
249 const threadRefs = harness.registry.get(threadRefsAtom);
250 const projects = harness.registry.get(projectsAtom);
251 const project = harness.registry.get(projectAtom);
252 const thread = harness.registry.get(threadAtom);
253
254 harness.registry.set(
255 harness.shellStateAtom,
256 AsyncResult.success(
257 shellState({
258 ...SNAPSHOT,
259 snapshotSequence: 2,
260 threads: SNAPSHOT.threads.map((candidate) =>
261 candidate.id === OTHER_THREAD_ID
262 ? { ...candidate, title: "Renamed other thread" }
263 : candidate,
264 ),
265 }),
266 ),
267 );
268
269 expect(harness.registry.get(projectRefsAtom)).toBe(projectRefs);
270 expect(harness.registry.get(threadRefsAtom)).toBe(threadRefs);
271 expect(harness.registry.get(projectsAtom)).toBe(projects);
272 expect(harness.registry.get(projectAtom)).toBe(project);
273 expect(harness.registry.get(threadAtom)).toBe(thread);
274 });
275
276 it("preserves project-scoped thread collections across unrelated project updates", () => {
277 const harness = makeHarness();
278 const projectRef = {
279 environmentId: ENVIRONMENT_ID,
280 projectId: PROJECT_ID,
281 };
282 const refsByProjectAtom =
283 harness.threadShells.environmentThreadRefsByProjectAtom(ENVIRONMENT_ID);
284 const threadsAtom = harness.threadShells.threadShellsForProjectRefsAtom([projectRef]);
285 const membership = harness.registry.get(refsByProjectAtom);
286 const refs = membership.get(PROJECT_ID);
287 const threads = harness.registry.get(threadsAtom);
288
289 expect(threads).toHaveLength(1);
290 expect(threads[0]?.id).toBe(THREAD_ID);
291
292 harness.registry.set(
293 harness.shellStateAtom,
294 AsyncResult.success(
295 shellState({
296 ...SNAPSHOT,
297 snapshotSequence: 2,
298 threads: SNAPSHOT.threads.map((thread) =>
299 thread.id === OTHER_THREAD_ID ? { ...thread, title: "Updated elsewhere" } : thread,
300 ),
301 }),
302 ),
303 );
304
305 expect(harness.registry.get(refsByProjectAtom).get(PROJECT_ID)).toBe(refs);
306 expect(harness.registry.get(refsByProjectAtom)).toBe(membership);
307 expect(harness.registry.get(threadsAtom)).toBe(threads);
308 });
309
310 it("shares list values with point reads without retaining one atom per listed thread", () => {
311 const harness = makeHarness();
312 let snapshot: OrchestrationShellSnapshot = {
313 ...SNAPSHOT,
314 threads: Array.from({ length: 200 }, (_, index) => ({
315 ...THREAD_SHELL,
316 id: ThreadId.make(`listed-${index}`),
317 })),
318 };
319 harness.registry.set(harness.shellStateAtom, AsyncResult.success(shellState(snapshot)));
320 const listAtom = harness.threadShells.threadShellsAtom;
321 const projectListAtom = harness.threadShells.threadShellsForProjectRefsAtom([
322 { environmentId: ENVIRONMENT_ID, projectId: PROJECT_ID },
323 ]);
324 const disposeList = harness.registry.mount(listAtom);
325 const disposeProjectList = harness.registry.mount(projectListAtom);
326 try {
327 const before = harness.registry.get(listAtom);
328 expect(before).toHaveLength(200);
329 expect(harness.registry.get(projectListAtom)).toEqual(before);
330 expect(harness.registry.getNodes().size).toBeLessThan(20);
331 const firstAtom = harness.threadShells.threadShellAtom({
332 environmentId: ENVIRONMENT_ID,
333 threadId: snapshot.threads[0]!.id,
334 });
335 expect(harness.registry.get(firstAtom)).toBe(before[0]);
336
337 snapshot = applyShellStreamEvent(snapshot, {
338 kind: "thread-upserted",
339 sequence: 2,
340 thread: { ...snapshot.threads.at(-1)!, title: "Updated last thread" },
341 });
342 harness.registry.set(harness.shellStateAtom, AsyncResult.success(shellState(snapshot)));
343 const after = harness.registry.get(listAtom);
344 expect(after[0]).toBe(before[0]);
345 expect(after.at(-1)).not.toBe(before.at(-1));
346 expect(after.at(-1)?.title).toBe("Updated last thread");
347 expect(harness.registry.get(projectListAtom).at(-1)).toBe(after.at(-1));
348 expect(harness.registry.get(firstAtom)).toBe(after[0]);
349 expect(harness.registry.getNodes().size).toBeLessThan(20);
350 } finally {
351 disposeProjectList();
352 disposeList();
353 harness.registry.dispose();
354 }
355 });
356
357 it("keeps scoped identities and list order across project and environment changes", () => {
358 const remoteEnvironmentId = EnvironmentId.make("remote-environment");
359 const harness = makeHarness([ENVIRONMENT_ID, remoteEnvironmentId]);
360 const listAtom = harness.threadShells.threadShellsAtom;
361 const localRef = { environmentId: ENVIRONMENT_ID, threadId: THREAD_ID };
362 const remoteRef = { environmentId: remoteEnvironmentId, threadId: THREAD_ID };
363 const selectedAtom = harness.threadShells.threadShellsForProjectRefsAtom([
364 { environmentId: remoteEnvironmentId, projectId: PROJECT_ID },
365 { environmentId: ENVIRONMENT_ID, projectId: OTHER_PROJECT_ID },
366 { environmentId: remoteEnvironmentId, projectId: PROJECT_ID },
367 { environmentId: ENVIRONMENT_ID, projectId: PROJECT_ID },
368 ]);
369 const disposeList = harness.registry.mount(listAtom);
370 const disposeSelected = harness.registry.mount(selectedAtom);
371 try {
372 const original = harness.registry.get(listAtom);
373 const local = harness.registry.get(harness.threadShells.threadShellAtom(localRef));
374 const remote = harness.registry.get(harness.threadShells.threadShellAtom(remoteRef));
375 expect(original).toHaveLength(4);
376 expect(original[0]).toBe(local);
377 expect(original[2]).toBe(remote);
378 expect(local).not.toBe(remote);
379 expect(local?.environmentId).toBe(ENVIRONMENT_ID);
380 expect(remote?.environmentId).toBe(remoteEnvironmentId);
381 expect(harness.registry.get(selectedAtom)).toEqual([remote, original[1], local]);
382
383 harness.registry.set(
384 harness.shellStateAtomForEnvironment(remoteEnvironmentId),
385 AsyncResult.success(shellState({ ...SNAPSHOT, threads: SNAPSHOT.threads.toReversed() })),
386 );
387 expect([
388 ...harness.registry
389 .get(harness.threadShells.environmentThreadRefsByProjectAtom(remoteEnvironmentId))
390 .keys(),
391 ]).toEqual([OTHER_PROJECT_ID, PROJECT_ID]);
392 harness.registry.set(
393 harness.shellStateAtomForEnvironment(remoteEnvironmentId),
394 AsyncResult.success(shellState(SNAPSHOT)),
395 );
396
397 let snapshot = applyShellStreamEvent(SNAPSHOT, {
398 kind: "thread-upserted",
399 sequence: 2,
400 thread: { ...THREAD_SHELL, projectId: OTHER_PROJECT_ID, title: "Moved thread" },
401 });
402 harness.registry.set(harness.shellStateAtom, AsyncResult.success(shellState(snapshot)));
403 const moved = harness.registry.get(harness.threadShells.threadShellAtom(localRef));
404 expect(harness.registry.get(selectedAtom)).toEqual([remote, moved, original[1]]);
405 expect(harness.registry.get(listAtom)[2]).toBe(remote);
406
407 snapshot = applyShellStreamEvent(snapshot, {
408 kind: "thread-removed",
409 sequence: 3,
410 threadId: OTHER_THREAD_ID,
411 });
412 harness.registry.set(harness.shellStateAtom, AsyncResult.success(shellState(snapshot)));
413 expect(harness.registry.get(selectedAtom)).toEqual([remote, moved]);
414 expect(
415 harness.registry.get(
416 harness.threadShells.threadShellAtom({
417 environmentId: ENVIRONMENT_ID,
418 threadId: OTHER_THREAD_ID,
419 }),
420 ),
421 ).toBeNull();
422
423 const createdId = ThreadId.make("created-thread");
424 snapshot = applyShellStreamEvent(snapshot, {
425 kind: "thread-upserted",
426 sequence: 4,
427 thread: { ...THREAD_SHELL, id: createdId },
428 });
429 harness.registry.set(harness.shellStateAtom, AsyncResult.success(shellState(snapshot)));
430 const created = harness.registry.get(listAtom)[1];
431 expect(created?.id).toBe(createdId);
432 expect(harness.registry.get(selectedAtom)).toEqual([remote, moved, created]);
433
434 const catalog = harness.registry.get(harness.catalogValueAtom);
435 harness.registry.set(harness.catalogValueAtom, {
436 ...catalog,
437 entries: new Map([...catalog.entries].toReversed()),
438 });
439 expect(harness.registry.get(listAtom)).toEqual([remote, original[3], moved, created]);
440 harness.registry.set(harness.catalogValueAtom, {
441 ...catalog,
442 entries: new Map([[remoteEnvironmentId, catalog.entries.get(remoteEnvironmentId)!]]),
443 });
444 expect(harness.registry.get(listAtom)).toEqual([remote, original[3]]);
445 harness.registry.set(
446 harness.shellStateAtomForEnvironment(remoteEnvironmentId),
447 AsyncResult.success(shellState({ ...SNAPSHOT, threads: [] })),
448 );
449 expect(harness.registry.get(listAtom)).toEqual([]);
450 expect(harness.registry.get(harness.threadShells.threadShellAtom(remoteRef))).toBeNull();
451 } finally {
452 disposeSelected();
453 disposeList();
454 harness.registry.dispose();
455 }
456 });
457
458 it("updates only the requested thread detail and preserves untouched field identities", () => {
459 const harness = makeHarness();
460 const threadRef = {
461 environmentId: ENVIRONMENT_ID,
462 threadId: THREAD_ID,
463 };
464 const otherThreadRef = {
465 environmentId: ENVIRONMENT_ID,
466 threadId: OTHER_THREAD_ID,
467 };
468 const threadDetailAtom = harness.threadDetails.detailAtom(threadRef);
469 const messagesAtom = harness.threadDetails.messagesAtom(threadRef);
470 const activitiesAtom = harness.threadDetails.activitiesAtom(threadRef);
471 const statusAtom = harness.threadDetails.statusAtom(threadRef);
472 const otherThreadDetailAtom = harness.threadDetails.detailAtom(otherThreadRef);
473 const otherValue = harness.registry.get(otherThreadDetailAtom);
474 const detail = {
475 ...THREAD_SHELL,
476 deletedAt: null,
477 messages: [],
478 proposedPlans: [],
479 activities: [],
480 checkpoints: [],
481 } satisfies OrchestrationThread;
482
483 harness.registry.set(
484 harness.threadStateAtom(THREAD_ID),
485 AsyncResult.success<EnvironmentThreadState>({
486 data: Option.some(detail),
487 status: "live",
488 error: Option.none(),
489 page: Option.none(),
490 }),
491 );
492
493 const scopedDetail = harness.registry.get(threadDetailAtom);
494 const messages = harness.registry.get(messagesAtom);
495 const activities = harness.registry.get(activitiesAtom);
496
497 expect(scopedDetail).toEqual({ ...detail, environmentId: ENVIRONMENT_ID });
498 expect(harness.registry.get(statusAtom)).toBe("live");
499 expect(harness.registry.get(otherThreadDetailAtom)).toBe(otherValue);
500
501 harness.registry.set(
502 harness.threadStateAtom(THREAD_ID),
503 AsyncResult.success<EnvironmentThreadState>({
504 data: Option.some({
505 ...detail,
506 session: {
507 threadId: THREAD_ID,
508 status: "ready",
509 providerName: "codex",
510 runtimeMode: "full-access",
511 activeTurnId: null,
512 lastError: null,
513 updatedAt: "2026-06-01T00:01:00.000Z",
514 },
515 }),
516 status: "live",
517 error: Option.none(),
518 page: Option.none(),
519 }),
520 );
521
522 expect(harness.registry.get(messagesAtom)).toBe(messages);
523 expect(harness.registry.get(activitiesAtom)).toBe(activities);
524 });
525});