Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

entities.test.ts

553 lines19.7 KB

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