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

entities.test.ts

368 lines11.4 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 session: null,
100 latestUserMessageAt: null,
101 hasPendingApprovals: false,
102 hasPendingUserInput: false,
103 hasActionableProposedPlan: false,
104} as const;
105​
106const SNAPSHOT: OrchestrationShellSnapshot = {
107 snapshotSequence: 1,
108 updatedAt: "2026-06-01T00:00:00.000Z",
109 projects: [
110 {
111 id: PROJECT_ID,
112 title: "Project",
113 workspaceRoot: "/repo",
114 repositoryIdentity: null,
115 defaultModelSelection: null,
116 scripts: [],
117 createdAt: "2026-06-01T00:00:00.000Z",
118 updatedAt: "2026-06-01T00:00:00.000Z",
119 },
120 {
121 id: OTHER_PROJECT_ID,
122 title: "Other project",
123 workspaceRoot: "/other-repo",
124 repositoryIdentity: null,
125 defaultModelSelection: null,
126 scripts: [],
127 createdAt: "2026-06-01T00:00:00.000Z",
128 updatedAt: "2026-06-01T00:00:00.000Z",
129 },
130 ],
131 threads: [
132 THREAD_SHELL,
133 {
134 ...THREAD_SHELL,
135 id: OTHER_THREAD_ID,
136 projectId: OTHER_PROJECT_ID,
137 title: "Other thread",
138 },
139 ],
140};
141​
142function shellState(snapshot: OrchestrationShellSnapshot): EnvironmentShellState {
143 return {
144 snapshot: Option.some(snapshot),
145 status: "live",
146 error: Option.none(),
147 };
149​
150function makeHarness() {
151 const shellStateAtoms = Atom.family((_environmentId: EnvironmentId) =>
152 Atom.make(AsyncResult.success(shellState(SNAPSHOT))),
153 );
154 const threadStateAtoms = Atom.family((_key: string) =>
155 Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)),
156 );
157 const catalogValueAtom = Atom.make({
158 isReady: true,
159 entries: new Map([
160 [
161 ENVIRONMENT_ID,
162 {
163 target: new PrimaryConnectionTarget({
164 environmentId: ENVIRONMENT_ID,
165 label: "Environment",
166 httpBaseUrl: "https://example.test",
167 wsBaseUrl: "wss://example.test",
168 }),
169 profile: Option.none(),
170 },
171 ],
172 ]),
173 });
174 const snapshotAtom = createEnvironmentSnapshotAtom(shellStateAtoms);
175 const projects = createEnvironmentProjectAtoms({
176 catalogValueAtom,
177 snapshotAtom,
178 });
179 const threadShells = createEnvironmentThreadShellAtoms({
180 catalogValueAtom,
181 snapshotAtom,
182 });
183 const threadDetails = createEnvironmentThreadDetailAtoms((environmentId, threadId) =>
184 threadStateAtoms(`${environmentId}\u0000${threadId}`),
185 );
186​
187 return {
188 registry: AtomRegistry.make(),
189 shellStateAtom: shellStateAtoms(ENVIRONMENT_ID),
190 threadStateAtom: (threadId: ThreadId) => threadStateAtoms(`${ENVIRONMENT_ID}\u0000${threadId}`),
191 projects,
192 threadShells,
193 threadDetails,
194 };
196​
197describe("environment entity projections", () => {
198 it("composes detail collections with authoritative shell workspace metadata", () => {
199 const messages: OrchestrationThread["messages"] = [];
200 const detail = {
201 ...THREAD_SHELL,
202 environmentId: ENVIRONMENT_ID,
203 title: "Cached thread",
204 branch: "stale-branch",
205 worktreePath: "/repo/stale-worktree",
206 deletedAt: null,
207 messages,
208 proposedPlans: [],
209 activities: [],
210 checkpoints: [],
211 } satisfies OrchestrationThread & { readonly environmentId: EnvironmentId };
212 const shell = {
213 ...THREAD_SHELL,
214 environmentId: ENVIRONMENT_ID,
215 title: "Current thread",
216 branch: "current-branch",
217 worktreePath: "/repo/current-worktree",
218 };
219​
220 const merged = mergeEnvironmentThread(detail, shell);
221​
222 expect(merged).toMatchObject({
223 title: "Current thread",
224 branch: "current-branch",
225 worktreePath: "/repo/current-worktree",
226 });
227 expect(merged?.messages).toBe(messages);
228 });
229​
230 it("preserves untouched project and thread identities across unrelated shell updates", () => {
231 const harness = makeHarness();
232 const projectRefsAtom = harness.projects.environmentProjectRefsAtom(ENVIRONMENT_ID);
233 const threadRefsAtom = harness.threadShells.environmentThreadRefsAtom(ENVIRONMENT_ID);
234 const projectsAtom = harness.projects.projectsAtom;
235 const projectAtom = harness.projects.projectAtom({
236 environmentId: ENVIRONMENT_ID,
237 projectId: PROJECT_ID,
238 });
239 const threadAtom = harness.threadShells.threadShellAtom({
240 environmentId: ENVIRONMENT_ID,
241 threadId: THREAD_ID,
242 });
243 const projectRefs = harness.registry.get(projectRefsAtom);
244 const threadRefs = harness.registry.get(threadRefsAtom);
245 const projects = harness.registry.get(projectsAtom);
246 const project = harness.registry.get(projectAtom);
247 const thread = harness.registry.get(threadAtom);
248​
249 harness.registry.set(
250 harness.shellStateAtom,
251 AsyncResult.success(
252 shellState({
253 ...SNAPSHOT,
254 snapshotSequence: 2,
255 threads: SNAPSHOT.threads.map((candidate) =>
256 candidate.id === OTHER_THREAD_ID
257 ? { ...candidate, title: "Renamed other thread" }
258 : candidate,
259 ),
260 }),
261 ),
262 );
263​
264 expect(harness.registry.get(projectRefsAtom)).toBe(projectRefs);
265 expect(harness.registry.get(threadRefsAtom)).toBe(threadRefs);
266 expect(harness.registry.get(projectsAtom)).toBe(projects);
267 expect(harness.registry.get(projectAtom)).toBe(project);
268 expect(harness.registry.get(threadAtom)).toBe(thread);
269 });
270​
271 it("preserves project-scoped thread collections across unrelated project updates", () => {
272 const harness = makeHarness();
273 const projectRef = {
274 environmentId: ENVIRONMENT_ID,
275 projectId: PROJECT_ID,
276 };
277 const refsByProjectAtom =
278 harness.threadShells.environmentThreadRefsByProjectAtom(ENVIRONMENT_ID);
279 const threadsAtom = harness.threadShells.threadShellsForProjectRefsAtom([projectRef]);
280 const refs = harness.registry.get(refsByProjectAtom).get(PROJECT_ID);
281 const threads = harness.registry.get(threadsAtom);
282​
283 expect(threads).toHaveLength(1);
284 expect(threads[0]?.id).toBe(THREAD_ID);
285​
286 harness.registry.set(
287 harness.shellStateAtom,
288 AsyncResult.success(
289 shellState({
290 ...SNAPSHOT,
291 snapshotSequence: 2,
292 threads: SNAPSHOT.threads.map((thread) =>
293 thread.id === OTHER_THREAD_ID ? { ...thread, title: "Updated elsewhere" } : thread,
294 ),
295 }),
296 ),
297 );
298​
299 expect(harness.registry.get(refsByProjectAtom).get(PROJECT_ID)).toBe(refs);
300 expect(harness.registry.get(threadsAtom)).toBe(threads);
301 });
302​
303 it("updates only the requested thread detail and preserves untouched field identities", () => {
304 const harness = makeHarness();
305 const threadRef = {
306 environmentId: ENVIRONMENT_ID,
307 threadId: THREAD_ID,
308 };
309 const otherThreadRef = {
310 environmentId: ENVIRONMENT_ID,
311 threadId: OTHER_THREAD_ID,
312 };
313 const threadDetailAtom = harness.threadDetails.detailAtom(threadRef);
314 const messagesAtom = harness.threadDetails.messagesAtom(threadRef);
315 const activitiesAtom = harness.threadDetails.activitiesAtom(threadRef);
316 const statusAtom = harness.threadDetails.statusAtom(threadRef);
317 const otherThreadDetailAtom = harness.threadDetails.detailAtom(otherThreadRef);
318 const otherValue = harness.registry.get(otherThreadDetailAtom);
319 const detail = {
320 ...THREAD_SHELL,
321 deletedAt: null,
322 messages: [],
323 proposedPlans: [],
324 activities: [],
325 checkpoints: [],
326 } satisfies OrchestrationThread;
327​
328 harness.registry.set(
329 harness.threadStateAtom(THREAD_ID),
330 AsyncResult.success<EnvironmentThreadState>({
331 data: Option.some(detail),
332 status: "live",
333 error: Option.none(),
334 }),
335 );
336​
337 const scopedDetail = harness.registry.get(threadDetailAtom);
338 const messages = harness.registry.get(messagesAtom);
339 const activities = harness.registry.get(activitiesAtom);
340​
341 expect(scopedDetail).toEqual({ ...detail, environmentId: ENVIRONMENT_ID });
342 expect(harness.registry.get(statusAtom)).toBe("live");
343 expect(harness.registry.get(otherThreadDetailAtom)).toBe(otherValue);
344​
345 harness.registry.set(
346 harness.threadStateAtom(THREAD_ID),
347 AsyncResult.success<EnvironmentThreadState>({
348 data: Option.some({
349 ...detail,
350 session: {
351 threadId: THREAD_ID,
352 status: "ready",
353 providerName: "codex",
354 runtimeMode: "full-access",
355 activeTurnId: null,
356 lastError: null,
357 updatedAt: "2026-06-01T00:01:00.000Z",
358 },
359 }),
360 status: "live",
361 error: Option.none(),
362 }),
363 );
364​
365 expect(harness.registry.get(messagesAtom)).toBe(messages);
366 expect(harness.registry.get(activitiesAtom)).toBe(activities);
367 });
368});