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

entities.test.ts

531 lines18.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 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 };
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 };
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 activeOrderKey: "t",
212 unsettledAt: "2026-03-09T10:00:00.000Z",
213 deletedAt: null,
214 messages,
215 proposedPlans: [],
216 activities: [],
217 checkpoints: [],
218 } satisfies OrchestrationThread & { readonly environmentId: EnvironmentId };
219 const shell = {
220 ...THREAD_SHELL,
221 environmentId: ENVIRONMENT_ID,
222 title: "Current thread",
223 branch: "current-branch",
224 worktreePath: "/repo/current-worktree",
225 activeOrderKey: "f",
226 unsettledAt: "2026-03-09T12:00:00.000Z",
227 };
228​
229 const merged = mergeEnvironmentThread(detail, shell);
230​
231 expect(merged).toMatchObject({
232 title: "Current thread",
233 branch: "current-branch",
234 worktreePath: "/repo/current-worktree",
235 activeOrderKey: "f",
236 unsettledAt: "2026-03-09T12:00:00.000Z",
237 });
238 expect(merged?.messages).toBe(messages);
239 });
240​
241 it("preserves untouched project and thread identities across unrelated shell updates", () => {
242 const harness = makeHarness();
243 const projectRefsAtom = harness.projects.environmentProjectRefsAtom(ENVIRONMENT_ID);
244 const threadRefsAtom = harness.threadShells.environmentThreadRefsAtom(ENVIRONMENT_ID);
245 const projectsAtom = harness.projects.projectsAtom;
246 const projectAtom = harness.projects.projectAtom({
247 environmentId: ENVIRONMENT_ID,
248 projectId: PROJECT_ID,
249 });
250 const threadAtom = harness.threadShells.threadShellAtom({
251 environmentId: ENVIRONMENT_ID,
252 threadId: THREAD_ID,
253 });
254 const projectRefs = harness.registry.get(projectRefsAtom);
255 const threadRefs = harness.registry.get(threadRefsAtom);
256 const projects = harness.registry.get(projectsAtom);
257 const project = harness.registry.get(projectAtom);
258 const thread = harness.registry.get(threadAtom);
259​
260 harness.registry.set(
261 harness.shellStateAtom,
262 AsyncResult.success(
263 shellState({
264 ...SNAPSHOT,
265 snapshotSequence: 2,
266 threads: SNAPSHOT.threads.map((candidate) =>
267 candidate.id === OTHER_THREAD_ID
268 ? { ...candidate, title: "Renamed other thread" }
269 : candidate,
270 ),
271 }),
272 ),
273 );
274​
275 expect(harness.registry.get(projectRefsAtom)).toBe(projectRefs);
276 expect(harness.registry.get(threadRefsAtom)).toBe(threadRefs);
277 expect(harness.registry.get(projectsAtom)).toBe(projects);
278 expect(harness.registry.get(projectAtom)).toBe(project);
279 expect(harness.registry.get(threadAtom)).toBe(thread);
280 });
281​
282 it("preserves project-scoped thread collections across unrelated project updates", () => {
283 const harness = makeHarness();
284 const projectRef = {
285 environmentId: ENVIRONMENT_ID,
286 projectId: PROJECT_ID,
287 };
288 const refsByProjectAtom =
289 harness.threadShells.environmentThreadRefsByProjectAtom(ENVIRONMENT_ID);
290 const threadsAtom = harness.threadShells.threadShellsForProjectRefsAtom([projectRef]);
291 const membership = harness.registry.get(refsByProjectAtom);
292 const refs = membership.get(PROJECT_ID);
293 const threads = harness.registry.get(threadsAtom);
294​
295 expect(threads).toHaveLength(1);
296 expect(threads[0]?.id).toBe(THREAD_ID);
297​
298 harness.registry.set(
299 harness.shellStateAtom,
300 AsyncResult.success(
301 shellState({
302 ...SNAPSHOT,
303 snapshotSequence: 2,
304 threads: SNAPSHOT.threads.map((thread) =>
305 thread.id === OTHER_THREAD_ID ? { ...thread, title: "Updated elsewhere" } : thread,
306 ),
307 }),
308 ),
309 );
310​
311 expect(harness.registry.get(refsByProjectAtom).get(PROJECT_ID)).toBe(refs);
312 expect(harness.registry.get(refsByProjectAtom)).toBe(membership);
313 expect(harness.registry.get(threadsAtom)).toBe(threads);
314 });
315​
316 it("shares list values with point reads without retaining one atom per listed thread", () => {
317 const harness = makeHarness();
318 let snapshot: OrchestrationShellSnapshot = {
319 ...SNAPSHOT,
320 threads: Array.from({ length: 200 }, (_, index) => ({
321 ...THREAD_SHELL,
322 id: ThreadId.make(`listed-${index}`),
323 })),
324 };
325 harness.registry.set(harness.shellStateAtom, AsyncResult.success(shellState(snapshot)));
326 const listAtom = harness.threadShells.threadShellsAtom;
327 const projectListAtom = harness.threadShells.threadShellsForProjectRefsAtom([
328 { environmentId: ENVIRONMENT_ID, projectId: PROJECT_ID },
329 ]);
330 const disposeList = harness.registry.mount(listAtom);
331 const disposeProjectList = harness.registry.mount(projectListAtom);
332 try {
333 const before = harness.registry.get(listAtom);
334 expect(before).toHaveLength(200);
335 expect(harness.registry.get(projectListAtom)).toEqual(before);
336 expect(harness.registry.getNodes().size).toBeLessThan(20);
337 const firstAtom = harness.threadShells.threadShellAtom({
338 environmentId: ENVIRONMENT_ID,
339 threadId: snapshot.threads[0]!.id,
340 });
341 expect(harness.registry.get(firstAtom)).toBe(before[0]);
342​
343 snapshot = applyShellStreamEvent(snapshot, {
344 kind: "thread-upserted",
345 sequence: 2,
346 thread: { ...snapshot.threads.at(-1)!, title: "Updated last thread" },
347 });
348 harness.registry.set(harness.shellStateAtom, AsyncResult.success(shellState(snapshot)));
349 const after = harness.registry.get(listAtom);
350 expect(after[0]).toBe(before[0]);
351 expect(after.at(-1)).not.toBe(before.at(-1));
352 expect(after.at(-1)?.title).toBe("Updated last thread");
353 expect(harness.registry.get(projectListAtom).at(-1)).toBe(after.at(-1));
354 expect(harness.registry.get(firstAtom)).toBe(after[0]);
355 expect(harness.registry.getNodes().size).toBeLessThan(20);
356 } finally {
357 disposeProjectList();
358 disposeList();
359 harness.registry.dispose();
360 }
361 });
362​
363 it("keeps scoped identities and list order across project and environment changes", () => {
364 const remoteEnvironmentId = EnvironmentId.make("remote-environment");
365 const harness = makeHarness([ENVIRONMENT_ID, remoteEnvironmentId]);
366 const listAtom = harness.threadShells.threadShellsAtom;
367 const localRef = { environmentId: ENVIRONMENT_ID, threadId: THREAD_ID };
368 const remoteRef = { environmentId: remoteEnvironmentId, threadId: THREAD_ID };
369 const selectedAtom = harness.threadShells.threadShellsForProjectRefsAtom([
370 { environmentId: remoteEnvironmentId, projectId: PROJECT_ID },
371 { environmentId: ENVIRONMENT_ID, projectId: OTHER_PROJECT_ID },
372 { environmentId: remoteEnvironmentId, projectId: PROJECT_ID },
373 { environmentId: ENVIRONMENT_ID, projectId: PROJECT_ID },
374 ]);
375 const disposeList = harness.registry.mount(listAtom);
376 const disposeSelected = harness.registry.mount(selectedAtom);
377 try {
378 const original = harness.registry.get(listAtom);
379 const local = harness.registry.get(harness.threadShells.threadShellAtom(localRef));
380 const remote = harness.registry.get(harness.threadShells.threadShellAtom(remoteRef));
381 expect(original).toHaveLength(4);
382 expect(original[0]).toBe(local);
383 expect(original[2]).toBe(remote);
384 expect(local).not.toBe(remote);
385 expect(local?.environmentId).toBe(ENVIRONMENT_ID);
386 expect(remote?.environmentId).toBe(remoteEnvironmentId);
387 expect(harness.registry.get(selectedAtom)).toEqual([remote, original[1], local]);
388​
389 harness.registry.set(
390 harness.shellStateAtomForEnvironment(remoteEnvironmentId),
391 AsyncResult.success(shellState({ ...SNAPSHOT, threads: SNAPSHOT.threads.toReversed() })),
392 );
393 expect([
394 ...harness.registry
395 .get(harness.threadShells.environmentThreadRefsByProjectAtom(remoteEnvironmentId))
396 .keys(),
397 ]).toEqual([OTHER_PROJECT_ID, PROJECT_ID]);
398 harness.registry.set(
399 harness.shellStateAtomForEnvironment(remoteEnvironmentId),
400 AsyncResult.success(shellState(SNAPSHOT)),
401 );
402​
403 let snapshot = applyShellStreamEvent(SNAPSHOT, {
404 kind: "thread-upserted",
405 sequence: 2,
406 thread: { ...THREAD_SHELL, projectId: OTHER_PROJECT_ID, title: "Moved thread" },
407 });
408 harness.registry.set(harness.shellStateAtom, AsyncResult.success(shellState(snapshot)));
409 const moved = harness.registry.get(harness.threadShells.threadShellAtom(localRef));
410 expect(harness.registry.get(selectedAtom)).toEqual([remote, moved, original[1]]);
411 expect(harness.registry.get(listAtom)[2]).toBe(remote);
412​
413 snapshot = applyShellStreamEvent(snapshot, {
414 kind: "thread-removed",
415 sequence: 3,
416 threadId: OTHER_THREAD_ID,
417 });
418 harness.registry.set(harness.shellStateAtom, AsyncResult.success(shellState(snapshot)));
419 expect(harness.registry.get(selectedAtom)).toEqual([remote, moved]);
420 expect(
421 harness.registry.get(
422 harness.threadShells.threadShellAtom({
423 environmentId: ENVIRONMENT_ID,
424 threadId: OTHER_THREAD_ID,
425 }),
426 ),
427 ).toBeNull();
428​
429 const createdId = ThreadId.make("created-thread");
430 snapshot = applyShellStreamEvent(snapshot, {
431 kind: "thread-upserted",
432 sequence: 4,
433 thread: { ...THREAD_SHELL, id: createdId },
434 });
435 harness.registry.set(harness.shellStateAtom, AsyncResult.success(shellState(snapshot)));
436 const created = harness.registry.get(listAtom)[1];
437 expect(created?.id).toBe(createdId);
438 expect(harness.registry.get(selectedAtom)).toEqual([remote, moved, created]);
439​
440 const catalog = harness.registry.get(harness.catalogValueAtom);
441 harness.registry.set(harness.catalogValueAtom, {
442 ...catalog,
443 entries: new Map([...catalog.entries].toReversed()),
444 });
445 expect(harness.registry.get(listAtom)).toEqual([remote, original[3], moved, created]);
446 harness.registry.set(harness.catalogValueAtom, {
447 ...catalog,
448 entries: new Map([[remoteEnvironmentId, catalog.entries.get(remoteEnvironmentId)!]]),
449 });
450 expect(harness.registry.get(listAtom)).toEqual([remote, original[3]]);
451 harness.registry.set(
452 harness.shellStateAtomForEnvironment(remoteEnvironmentId),
453 AsyncResult.success(shellState({ ...SNAPSHOT, threads: [] })),
454 );
455 expect(harness.registry.get(listAtom)).toEqual([]);
456 expect(harness.registry.get(harness.threadShells.threadShellAtom(remoteRef))).toBeNull();
457 } finally {
458 disposeSelected();
459 disposeList();
460 harness.registry.dispose();
461 }
462 });
463​
464 it("updates only the requested thread detail and preserves untouched field identities", () => {
465 const harness = makeHarness();
466 const threadRef = {
467 environmentId: ENVIRONMENT_ID,
468 threadId: THREAD_ID,
469 };
470 const otherThreadRef = {
471 environmentId: ENVIRONMENT_ID,
472 threadId: OTHER_THREAD_ID,
473 };
474 const threadDetailAtom = harness.threadDetails.detailAtom(threadRef);
475 const messagesAtom = harness.threadDetails.messagesAtom(threadRef);
476 const activitiesAtom = harness.threadDetails.activitiesAtom(threadRef);
477 const statusAtom = harness.threadDetails.statusAtom(threadRef);
478 const otherThreadDetailAtom = harness.threadDetails.detailAtom(otherThreadRef);
479 const otherValue = harness.registry.get(otherThreadDetailAtom);
480 const detail = {
481 ...THREAD_SHELL,
482 deletedAt: null,
483 messages: [],
484 proposedPlans: [],
485 activities: [],
486 checkpoints: [],
487 } satisfies OrchestrationThread;
488​
489 harness.registry.set(
490 harness.threadStateAtom(THREAD_ID),
491 AsyncResult.success<EnvironmentThreadState>({
492 data: Option.some(detail),
493 status: "live",
494 error: Option.none(),
495 page: Option.none(),
496 }),
497 );
498​
499 const scopedDetail = harness.registry.get(threadDetailAtom);
500 const messages = harness.registry.get(messagesAtom);
501 const activities = harness.registry.get(activitiesAtom);
502​
503 expect(scopedDetail).toEqual({ ...detail, environmentId: ENVIRONMENT_ID });
504 expect(harness.registry.get(statusAtom)).toBe("live");
505 expect(harness.registry.get(otherThreadDetailAtom)).toBe(otherValue);
506​
507 harness.registry.set(
508 harness.threadStateAtom(THREAD_ID),
509 AsyncResult.success<EnvironmentThreadState>({
510 data: Option.some({
511 ...detail,
512 session: {
513 threadId: THREAD_ID,
514 status: "ready",
515 providerName: "codex",
516 runtimeMode: "full-access",
517 activeTurnId: null,
518 lastError: null,
519 updatedAt: "2026-06-01T00:01:00.000Z",
520 },
521 }),
522 status: "live",
523 error: Option.none(),
524 page: Option.none(),
525 }),
526 );
527​
528 expect(harness.registry.get(messagesAtom)).toBe(messages);
529 expect(harness.registry.get(activitiesAtom)).toBe(activities);
530 });
531});