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

entities.test.ts

372 lines11.5 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";
29​
30const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
31const PROJECT_ID = ProjectId.make("project-1");
32const OTHER_PROJECT_ID = ProjectId.make("project-2");
33const THREAD_ID = ThreadId.make("thread-1");
34const OTHER_THREAD_ID = ThreadId.make("thread-2");
35​
36describe("scoped entity keys", () => {
37 it("preserves an invalid project key as structured error data", () => {
38 const key = "missing-project-key-separator";
39 let error: unknown;
40​
41 try {
42 parseProjectKey(key);
43 } catch (cause) {
44 error = cause;
45 }
46​
47 expect(error).toEqual(new InvalidScopedProjectKeyError({ key }));
48 });
49​
50 it("preserves an invalid thread key as structured error data", () => {
51 const key = "missing-thread-key-separator";
52 let error: unknown;
53​
54 try {
55 parseThreadKey(key);
56 } catch (cause) {
57 error = cause;
58 }
59​
60 expect(error).toEqual(new InvalidScopedThreadKeyError({ key }));
61 });
62​
63 it("preserves malformed project reference collection input and its cause", () => {
64 const key = "not-json";
65 let error: unknown;
66​
67 try {
68 parseProjectRefCollectionKey(key);
69 } catch (cause) {
70 error = cause;
71 }
72​
73 expect(error).toBeInstanceOf(InvalidScopedProjectRefCollectionKeyError);
74 expect(error).toMatchObject({ key, cause: expect.anything() });
75 });
76​
77 it("rejects invalid project reference collection shapes", () => {
78 const key = JSON.stringify([["environment-1"]]);
79​
80 expect(() => parseProjectRefCollectionKey(key)).toThrowError(
81 InvalidScopedProjectRefCollectionKeyError,
82 );
83 });
84});
85​
86const THREAD_SHELL = {
87 id: THREAD_ID,
88 projectId: PROJECT_ID,
89 title: "Thread",
90 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
91 runtimeMode: "full-access",
92 interactionMode: "default",
93 branch: null,
94 worktreePath: null,
95 latestTurn: null,
96 createdAt: "2026-06-01T00:00:00.000Z",
97 updatedAt: "2026-06-01T00:00:00.000Z",
98 archivedAt: null,
99 settledOverride: null,
100 settledAt: null,
101 session: null,
102 latestUserMessageAt: null,
103 hasPendingApprovals: false,
104 hasPendingUserInput: false,
105 hasActionableProposedPlan: false,
106} as const;
107​
108const SNAPSHOT: OrchestrationShellSnapshot = {
109 snapshotSequence: 1,
110 updatedAt: "2026-06-01T00:00:00.000Z",
111 projects: [
112 {
113 id: PROJECT_ID,
114 title: "Project",
115 workspaceRoot: "/repo",
116 repositoryIdentity: null,
117 defaultModelSelection: null,
118 scripts: [],
119 createdAt: "2026-06-01T00:00:00.000Z",
120 updatedAt: "2026-06-01T00:00:00.000Z",
121 },
122 {
123 id: OTHER_PROJECT_ID,
124 title: "Other project",
125 workspaceRoot: "/other-repo",
126 repositoryIdentity: null,
127 defaultModelSelection: null,
128 scripts: [],
129 createdAt: "2026-06-01T00:00:00.000Z",
130 updatedAt: "2026-06-01T00:00:00.000Z",
131 },
132 ],
133 threads: [
134 THREAD_SHELL,
135 {
136 ...THREAD_SHELL,
137 id: OTHER_THREAD_ID,
138 projectId: OTHER_PROJECT_ID,
139 title: "Other thread",
140 },
141 ],
142};
143​
144function shellState(snapshot: OrchestrationShellSnapshot): EnvironmentShellState {
145 return {
146 snapshot: Option.some(snapshot),
147 status: "live",
148 error: Option.none(),
149 };
151​
152function makeHarness() {
153 const shellStateAtoms = Atom.family((_environmentId: EnvironmentId) =>
154 Atom.make(AsyncResult.success(shellState(SNAPSHOT))),
155 );
156 const threadStateAtoms = Atom.family((_key: string) =>
157 Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)),
158 );
159 const catalogValueAtom = Atom.make({
160 isReady: true,
161 entries: new Map([
162 [
163 ENVIRONMENT_ID,
164 {
165 target: new PrimaryConnectionTarget({
166 environmentId: ENVIRONMENT_ID,
167 label: "Environment",
168 httpBaseUrl: "https://example.test",
169 wsBaseUrl: "wss://example.test",
170 }),
171 profile: Option.none(),
172 },
173 ],
174 ]),
175 });
176 const snapshotAtom = createEnvironmentSnapshotAtom(shellStateAtoms);
177 const projects = createEnvironmentProjectAtoms({
178 catalogValueAtom,
179 snapshotAtom,
180 });
181 const threadShells = createEnvironmentThreadShellAtoms({
182 catalogValueAtom,
183 snapshotAtom,
184 });
185 const threadDetails = createEnvironmentThreadDetailAtoms((environmentId, threadId) =>
186 threadStateAtoms(`${environmentId}\u0000${threadId}`),
187 );
188​
189 return {
190 registry: AtomRegistry.make(),
191 shellStateAtom: shellStateAtoms(ENVIRONMENT_ID),
192 threadStateAtom: (threadId: ThreadId) => threadStateAtoms(`${ENVIRONMENT_ID}\u0000${threadId}`),
193 projects,
194 threadShells,
195 threadDetails,
196 };
198​
199describe("environment entity projections", () => {
200 it("composes detail collections with authoritative shell workspace metadata", () => {
201 const messages: OrchestrationThread["messages"] = [];
202 const detail = {
203 ...THREAD_SHELL,
204 environmentId: ENVIRONMENT_ID,
205 title: "Cached thread",
206 branch: "stale-branch",
207 worktreePath: "/repo/stale-worktree",
208 deletedAt: null,
209 messages,
210 proposedPlans: [],
211 activities: [],
212 checkpoints: [],
213 } satisfies OrchestrationThread & { readonly environmentId: EnvironmentId };
214 const shell = {
215 ...THREAD_SHELL,
216 environmentId: ENVIRONMENT_ID,
217 title: "Current thread",
218 branch: "current-branch",
219 worktreePath: "/repo/current-worktree",
220 };
221​
222 const merged = mergeEnvironmentThread(detail, shell);
223​
224 expect(merged).toMatchObject({
225 title: "Current thread",
226 branch: "current-branch",
227 worktreePath: "/repo/current-worktree",
228 });
229 expect(merged?.messages).toBe(messages);
230 });
231​
232 it("preserves untouched project and thread identities across unrelated shell updates", () => {
233 const harness = makeHarness();
234 const projectRefsAtom = harness.projects.environmentProjectRefsAtom(ENVIRONMENT_ID);
235 const threadRefsAtom = harness.threadShells.environmentThreadRefsAtom(ENVIRONMENT_ID);
236 const projectsAtom = harness.projects.projectsAtom;
237 const projectAtom = harness.projects.projectAtom({
238 environmentId: ENVIRONMENT_ID,
239 projectId: PROJECT_ID,
240 });
241 const threadAtom = harness.threadShells.threadShellAtom({
242 environmentId: ENVIRONMENT_ID,
243 threadId: THREAD_ID,
244 });
245 const projectRefs = harness.registry.get(projectRefsAtom);
246 const threadRefs = harness.registry.get(threadRefsAtom);
247 const projects = harness.registry.get(projectsAtom);
248 const project = harness.registry.get(projectAtom);
249 const thread = harness.registry.get(threadAtom);
250​
251 harness.registry.set(
252 harness.shellStateAtom,
253 AsyncResult.success(
254 shellState({
255 ...SNAPSHOT,
256 snapshotSequence: 2,
257 threads: SNAPSHOT.threads.map((candidate) =>
258 candidate.id === OTHER_THREAD_ID
259 ? { ...candidate, title: "Renamed other thread" }
260 : candidate,
261 ),
262 }),
263 ),
264 );
265​
266 expect(harness.registry.get(projectRefsAtom)).toBe(projectRefs);
267 expect(harness.registry.get(threadRefsAtom)).toBe(threadRefs);
268 expect(harness.registry.get(projectsAtom)).toBe(projects);
269 expect(harness.registry.get(projectAtom)).toBe(project);
270 expect(harness.registry.get(threadAtom)).toBe(thread);
271 });
272​
273 it("preserves project-scoped thread collections across unrelated project updates", () => {
274 const harness = makeHarness();
275 const projectRef = {
276 environmentId: ENVIRONMENT_ID,
277 projectId: PROJECT_ID,
278 };
279 const refsByProjectAtom =
280 harness.threadShells.environmentThreadRefsByProjectAtom(ENVIRONMENT_ID);
281 const threadsAtom = harness.threadShells.threadShellsForProjectRefsAtom([projectRef]);
282 const refs = harness.registry.get(refsByProjectAtom).get(PROJECT_ID);
283 const threads = harness.registry.get(threadsAtom);
284​
285 expect(threads).toHaveLength(1);
286 expect(threads[0]?.id).toBe(THREAD_ID);
287​
288 harness.registry.set(
289 harness.shellStateAtom,
290 AsyncResult.success(
291 shellState({
292 ...SNAPSHOT,
293 snapshotSequence: 2,
294 threads: SNAPSHOT.threads.map((thread) =>
295 thread.id === OTHER_THREAD_ID ? { ...thread, title: "Updated elsewhere" } : thread,
296 ),
297 }),
298 ),
299 );
300​
301 expect(harness.registry.get(refsByProjectAtom).get(PROJECT_ID)).toBe(refs);
302 expect(harness.registry.get(threadsAtom)).toBe(threads);
303 });
304​
305 it("updates only the requested thread detail and preserves untouched field identities", () => {
306 const harness = makeHarness();
307 const threadRef = {
308 environmentId: ENVIRONMENT_ID,
309 threadId: THREAD_ID,
310 };
311 const otherThreadRef = {
312 environmentId: ENVIRONMENT_ID,
313 threadId: OTHER_THREAD_ID,
314 };
315 const threadDetailAtom = harness.threadDetails.detailAtom(threadRef);
316 const messagesAtom = harness.threadDetails.messagesAtom(threadRef);
317 const activitiesAtom = harness.threadDetails.activitiesAtom(threadRef);
318 const statusAtom = harness.threadDetails.statusAtom(threadRef);
319 const otherThreadDetailAtom = harness.threadDetails.detailAtom(otherThreadRef);
320 const otherValue = harness.registry.get(otherThreadDetailAtom);
321 const detail = {
322 ...THREAD_SHELL,
323 deletedAt: null,
324 messages: [],
325 proposedPlans: [],
326 activities: [],
327 checkpoints: [],
328 } satisfies OrchestrationThread;
329​
330 harness.registry.set(
331 harness.threadStateAtom(THREAD_ID),
332 AsyncResult.success<EnvironmentThreadState>({
333 data: Option.some(detail),
334 status: "live",
335 error: Option.none(),
336 page: Option.none(),
337 }),
338 );
339​
340 const scopedDetail = harness.registry.get(threadDetailAtom);
341 const messages = harness.registry.get(messagesAtom);
342 const activities = harness.registry.get(activitiesAtom);
343​
344 expect(scopedDetail).toEqual({ ...detail, environmentId: ENVIRONMENT_ID });
345 expect(harness.registry.get(statusAtom)).toBe("live");
346 expect(harness.registry.get(otherThreadDetailAtom)).toBe(otherValue);
347​
348 harness.registry.set(
349 harness.threadStateAtom(THREAD_ID),
350 AsyncResult.success<EnvironmentThreadState>({
351 data: Option.some({
352 ...detail,
353 session: {
354 threadId: THREAD_ID,
355 status: "ready",
356 providerName: "codex",
357 runtimeMode: "full-access",
358 activeTurnId: null,
359 lastError: null,
360 updatedAt: "2026-06-01T00:01:00.000Z",
361 },
362 }),
363 status: "live",
364 error: Option.none(),
365 page: Option.none(),
366 }),
367 );
368​
369 expect(harness.registry.get(messagesAtom)).toBe(messages);
370 expect(harness.registry.get(activitiesAtom)).toBe(activities);
371 });
372});