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

entities.test.ts

605 lines19.0 KB

1import {
2 EnvironmentId,
3 MessageId,
4 NodeId,
5 ProviderInstanceId,
6 ProviderSessionId,
7 RunId,
8 RuntimeRequestId,
9 TurnItemId,
10} from "@t3tools/contracts";
11import * as DateTime from "effect/DateTime";
12import { describe, expect, it } from "vite-plus/test";
13​
14import {
15 InvalidScopedProjectRefCollectionKeyError,
16 InvalidScopedThreadKeyError,
17 parseProjectRefCollectionKey,
18 parseThreadKey,
19} from "./entities.ts";
20import {
21 presentThreadShell,
22 resolveThreadProviderStack,
23 resolveThreadWorkingStartedAt,
24} from "./models.ts";
25import { v2Projection, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
26import { deriveLatestThreadRun, deriveThreadRuntime } from "./threadExecution.ts";
27import { derivePendingThreadRequests } from "./threadRequests.ts";
28​
29const environmentId = EnvironmentId.make("environment-v2");
30​
31describe("scoped entity keys", () => {
32 it("preserves an invalid thread key as structured error data", () => {
33 const key = "missing-thread-key-separator";
34 let error: unknown;
35​
36 try {
37 parseThreadKey(key);
38 } catch (cause) {
39 error = cause;
40 }
41​
42 expect(error).toEqual(new InvalidScopedThreadKeyError({ key }));
43 });
44​
45 it("preserves malformed project reference collection input and its cause", () => {
46 const key = "not-json";
47 let error: unknown;
48​
49 try {
50 parseProjectRefCollectionKey(key);
51 } catch (cause) {
52 error = cause;
53 }
54​
55 expect(error).toBeInstanceOf(InvalidScopedProjectRefCollectionKeyError);
56 expect(error).toMatchObject({ key, cause: expect.anything() });
57 });
58​
59 it("rejects invalid project reference collection shapes", () => {
60 const key = JSON.stringify([["environment-1"]]);
61​
62 expect(() => parseProjectRefCollectionKey(key)).toThrowError(
63 InvalidScopedProjectRefCollectionKeyError,
64 );
65 });
66});
67​
68describe("V2 client presentation", () => {
69 it("presents shell timestamps and status without constructing V1 state", () => {
70 const shell = presentThreadShell(environmentId, v2ThreadShell);
71 expect(shell.environmentId).toBe(environmentId);
72 expect(shell.createdAt).toBe("2026-06-20T00:00:00.000Z");
73 expect(shell.runtime).toBeNull();
74 expect(shell.source).toBe(v2ThreadShell);
75 });
76​
77 it("preserves active ordering and both pull-request sources", () => {
78 const linkedPullRequest = {
79 projectId: v2ThreadShell.projectId,
80 repository: "pingdotgg/t3code",
81 number: 42,
82 url: "https://github.com/pingdotgg/t3code/pull/42",
83 };
84 const branchPullRequest = { ...linkedPullRequest, number: 43 };
85 const shell = presentThreadShell(environmentId, {
86 ...v2ThreadShell,
87 activeOrderKey: "m",
88 linkedPullRequest,
89 branchPullRequest,
90 });
91​
92 expect(shell.activeOrderKey).toBe("m");
93 expect(shell.linkedPullRequest).toEqual(linkedPullRequest);
94 expect(shell.branchPullRequest).toEqual(branchPullRequest);
95 });
96​
97 it("presents provider errors carried by failed thread shells", () => {
98 const runId = RunId.make("run-failed");
99 const shell = presentThreadShell(environmentId, {
100 ...v2ThreadShell,
101 latestRunId: runId,
102 status: "failed",
103 lastError: "provider process exited",
104 });
105​
106 expect(shell.runtime).toMatchObject({
107 status: "failed",
108 lastError: "provider process exited",
109 });
110 });
111​
112 it("preserves shell run timestamps for sidebar activity clocks", () => {
113 const runId = RunId.make("run-working-clock");
114 const requestedAt = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
115 const startedAt = DateTime.makeUnsafe("2026-06-20T01:00:02.000Z");
116 const shell = presentThreadShell(environmentId, {
117 ...v2ThreadShell,
118 latestRunId: runId,
119 latestRunRequestedAt: requestedAt,
120 latestRunStartedAt: startedAt,
121 latestRunCompletedAt: null,
122 activeRunId: runId,
123 status: "running",
124 updatedAt: DateTime.makeUnsafe("2026-06-20T01:04:45.000Z"),
125 });
126​
127 expect(shell.latestRun).toMatchObject({
128 runId,
129 status: "running",
130 requestedAt: "2026-06-20T01:00:00.000Z",
131 startedAt: "2026-06-20T01:00:02.000Z",
132 completedAt: null,
133 });
134 });
135​
136 it("parks presented runtime at idle when a settled shell has pending background tasks", () => {
137 const runId = RunId.make("run-completed");
138 const shell = presentThreadShell(environmentId, {
139 ...v2ThreadShell,
140 latestRunId: runId,
141 activeRunId: null,
142 status: "completed",
143 pendingBackgroundTasks: [{ taskId: "bg-1", description: "sleep 20" }],
144 });
145​
146 expect(shell.latestRun).toMatchObject({ runId, status: "completed" });
147 expect(shell.runtime).toMatchObject({
148 status: "idle",
149 activeRunId: null,
150 });
151 expect(shell.pendingBackgroundTasks).toEqual([{ taskId: "bg-1", description: "sleep 20" }]);
152 });
153​
154 it("stacks earlier provider owners behind the current one, newest history first to go", () => {
155 const codex = ProviderInstanceId.make("codex");
156 const claude = ProviderInstanceId.make("claude");
157 const cursor = ProviderInstanceId.make("cursor");
158 const grok = ProviderInstanceId.make("grok");
159 const shell = presentThreadShell(environmentId, {
160 ...v2ThreadShell,
161 providerInstanceId: grok,
162 modelSelection: { instanceId: grok, model: "grok-4" },
163 providerInstanceHistory: [codex, claude, cursor, grok],
164 });
165​
166 // Three slots: the two most recent earlier owners, then the current one.
167 expect(resolveThreadProviderStack(shell)).toEqual([claude, cursor, grok]);
168 expect(
169 resolveThreadProviderStack({ ...shell, providerInstanceHistory: [codex, grok] }),
170 ).toEqual([codex, grok]);
171 expect(resolveThreadProviderStack({ ...shell, providerInstanceHistory: [] })).toEqual([grok]);
172 // Servers that predate the field decode to an empty history.
173 expect(
174 presentThreadShell(environmentId, { ...v2ThreadShell, providerInstanceHistory: undefined })
175 .providerInstanceHistory,
176 ).toEqual([]);
177 });
178​
179 it("keeps terminal runtime completed when there are no pending background tasks", () => {
180 const runId = RunId.make("run-completed");
181 const shell = presentThreadShell(environmentId, {
182 ...v2ThreadShell,
183 latestRunId: runId,
184 activeRunId: null,
185 status: "completed",
186 pendingBackgroundTasks: [],
187 });
188​
189 expect(shell.latestRun).toMatchObject({ runId, status: "completed" });
190 expect(shell.runtime).toMatchObject({
191 status: "completed",
192 activeRunId: null,
193 });
194 });
195​
196 it("keeps runtime running when there is no background roster", () => {
197 const runId = RunId.make("run-running");
198 const shell = presentThreadShell(environmentId, {
199 ...v2ThreadShell,
200 latestRunId: runId,
201 activeRunId: runId,
202 status: "running",
203 pendingBackgroundTasks: [],
204 });
205​
206 expect(shell.latestRun).toMatchObject({ runId, status: "running" });
207 expect(shell.runtime).toMatchObject({
208 status: "running",
209 activeRunId: runId,
210 });
211 });
212​
213 it("keeps an older active run visible over a newer cancelled run", () => {
214 const activeRunId = RunId.make("run-active");
215 const cancelledRunId = RunId.make("run-cancelled");
216 const shell = presentThreadShell(environmentId, {
217 ...v2ThreadShell,
218 latestRunId: cancelledRunId,
219 latestRunStartedAt: null,
220 latestRunCompletedAt: DateTime.makeUnsafe("2026-06-20T01:05:00.000Z"),
221 activeRunId,
222 activityRunStatus: "running",
223 status: "cancelled",
224 pendingBackgroundTasks: [],
225 });
226​
227 expect(shell.latestRun).toMatchObject({ runId: cancelledRunId, status: "cancelled" });
228 expect(shell.runtime).toMatchObject({
229 status: "running",
230 activeRunId,
231 });
232 });
233​
234 it("keeps an older waiting run visible over a newer cancelled run", () => {
235 const shell = presentThreadShell(environmentId, {
236 ...v2ThreadShell,
237 latestRunId: RunId.make("run-cancelled"),
238 activeRunId: null,
239 activityRunStatus: "waiting",
240 status: "cancelled",
241 pendingBackgroundTasks: [],
242 });
243​
244 expect(shell.runtime).toMatchObject({ status: "waiting", activeRunId: null });
245 });
246​
247 it("keeps a post-settlement background roster ahead of activity status", () => {
248 const activeRunId = RunId.make("run-active");
249 const shell = presentThreadShell(environmentId, {
250 ...v2ThreadShell,
251 latestRunId: RunId.make("run-cancelled"),
252 activeRunId,
253 activityRunStatus: "running",
254 status: "cancelled",
255 pendingBackgroundTasks: [{ taskId: "bg-activity", description: "background work" }],
256 });
257​
258 expect(shell.runtime).toMatchObject({ status: "idle", activeRunId });
259 });
260​
261 it("parks runtime idle over stale shell running when the roster is nonempty", () => {
262 const runId = RunId.make("run-stale-running");
263 const shell = presentThreadShell(environmentId, {
264 ...v2ThreadShell,
265 latestRunId: runId,
266 activeRunId: runId,
267 // Stale: server already projected a post-settlement roster, but shell
268 // status still says running (packaged orchestrator-v2 bug).
269 status: "running",
270 pendingBackgroundTasks: [{ taskId: "bg-1", description: "sleep 20" }],
271 });
272​
273 expect(shell.latestRun).toMatchObject({ runId, status: "running" });
274 expect(shell.runtime).toMatchObject({
275 status: "idle",
276 activeRunId: runId,
277 });
278 expect(shell.pendingBackgroundTasks).toEqual([{ taskId: "bg-1", description: "sleep 20" }]);
279 });
280​
281 it("parks runtime idle over stale checkpoint waiting when the roster is nonempty", () => {
282 const runId = RunId.make("run-stale-waiting");
283 const shell = presentThreadShell(environmentId, {
284 ...v2ThreadShell,
285 latestRunId: runId,
286 activeRunId: runId,
287 // Stale: checkpoint-oriented waiting masks post-settlement background work.
288 status: "waiting",
289 pendingBackgroundTasks: [{ taskId: "bg-2", description: "background bash" }],
290 });
291​
292 expect(shell.latestRun).toMatchObject({ runId, status: "waiting" });
293 expect(shell.runtime).toMatchObject({
294 status: "idle",
295 activeRunId: runId,
296 });
297 expect(shell.pendingBackgroundTasks).toEqual([
298 { taskId: "bg-2", description: "background bash" },
299 ]);
300 });
301​
302 it("derives execution summaries without wrapping or copying the projection", () => {
303 const runId = RunId.make("run-1");
304 const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
305 const projection = {
306 ...v2Projection,
307 runs: [
308 {
309 id: runId,
310 threadId: v2Projection.thread.id,
311 ordinal: 1,
312 providerInstanceId: v2Projection.thread.providerInstanceId,
313 modelSelection: v2Projection.thread.modelSelection,
314 providerThreadId: null,
315 userMessageId: MessageId.make("message-user"),
316 rootNodeId: null,
317 activeAttemptId: null,
318 status: "running" as const,
319 requestedAt: now,
320 startedAt: now,
321 completedAt: null,
322 checkpointId: null,
323 contextHandoffId: null,
324 },
325 ],
326 messages: [
327 {
328 id: MessageId.make("message-user"),
329 threadId: v2Projection.thread.id,
330 runId,
331 nodeId: null,
332 role: "user" as const,
333 text: "Hello",
334 attachments: [],
335 streaming: false,
336 createdBy: "user" as const,
337 creationSource: "web" as const,
338 createdAt: now,
339 updatedAt: now,
340 },
341 ],
342 updatedAt: now,
343 };
344​
345 expect(deriveLatestThreadRun(projection)).toMatchObject({
346 runId,
347 status: "running",
348 requestedAt: "2026-06-20T01:00:00.000Z",
349 assistantMessageId: null,
350 });
351 expect(deriveThreadRuntime(projection)).toMatchObject({
352 status: "running",
353 activeRunId: runId,
354 providerInstanceId: projection.thread.providerInstanceId,
355 });
356 for (const status of ["queued", "cancelled"] as const) {
357 const later = DateTime.add(now, { hours: 1 });
358 const latest = {
359 ...projection.runs[0]!,
360 id: RunId.make("newer-run"),
361 ordinal: 2,
362 status,
363 requestedAt: later,
364 startedAt: null,
365 completedAt: status === "cancelled" ? later : null,
366 };
367 const detail = { ...projection, runs: [...projection.runs, latest], updatedAt: later };
368 const shell = presentThreadShell(environmentId, {
369 ...v2ThreadShell,
370 latestRunId: latest.id,
371 latestRunStartedAt: null,
372 latestRunRequestedAt: later,
373 latestRunCompletedAt: latest.completedAt,
374 status,
375 activeRunId: runId,
376 activityRunStatus: "running",
377 activityRunStartedAt: now,
378 updatedAt: later,
379 });
380 expect(resolveThreadWorkingStartedAt(shell)).toBe(DateTime.formatIso(now));
381 expect(
382 resolveThreadWorkingStartedAt({
383 latestRun: deriveLatestThreadRun(detail),
384 runtime: deriveThreadRuntime(detail),
385 }),
386 ).toBe(resolveThreadWorkingStartedAt(shell));
387 const stopped = {
388 ...detail,
389 runs: detail.runs.map((run) => ({
390 ...run,
391 status: "completed" as const,
392 completedAt: later,
393 })),
394 };
395 expect(
396 resolveThreadWorkingStartedAt({
397 latestRun: deriveLatestThreadRun(stopped),
398 runtime: deriveThreadRuntime(stopped),
399 }),
400 ).toBeNull();
401 }
402 });
403​
404 it("parks waiting runtime for a post-settlement roster without hiding active running work", () => {
405 const runId = RunId.make("run-background-presentation");
406 const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
407 const run = {
408 id: runId,
409 threadId: v2Projection.thread.id,
410 ordinal: 1,
411 providerInstanceId: v2Projection.thread.providerInstanceId,
412 modelSelection: v2Projection.thread.modelSelection,
413 providerThreadId: null,
414 userMessageId: MessageId.make("message-background-presentation"),
415 rootNodeId: null,
416 activeAttemptId: null,
417 status: "waiting" as const,
418 requestedAt: now,
419 startedAt: now,
420 completedAt: null,
421 checkpointId: null,
422 contextHandoffId: null,
423 };
424 const backgroundItem = {
425 id: TurnItemId.make("item-background-command"),
426 threadId: v2Projection.thread.id,
427 runId,
428 nodeId: null,
429 providerThreadId: null,
430 providerTurnId: null,
431 nativeItemRef: null,
432 parentItemId: null,
433 ordinal: 0,
434 status: "running" as const,
435 title: "Background command",
436 startedAt: now,
437 completedAt: null,
438 updatedAt: now,
439 type: "command_execution" as const,
440 input: "sleep 20",
441 };
442​
443 expect(
444 deriveThreadRuntime({
445 ...v2Projection,
446 runs: [run],
447 turnItems: [backgroundItem],
448 }),
449 ).toMatchObject({
450 status: "idle",
451 activeRunId: null,
452 });
453 expect(
454 deriveThreadRuntime({
455 ...v2Projection,
456 runs: [{ ...run, status: "running" as const }],
457 turnItems: [backgroundItem],
458 }),
459 ).toMatchObject({
460 status: "running",
461 activeRunId: runId,
462 });
463 });
464​
465 it("joins pending request entities to their native turn-item display data", () => {
466 const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
467 const requestId = RuntimeRequestId.make("request-approval");
468 const item = {
469 id: TurnItemId.make("item-approval"),
470 threadId: v2Projection.thread.id,
471 runId: null,
472 nodeId: NodeId.make("node-root"),
473 providerThreadId: null,
474 providerTurnId: null,
475 nativeItemRef: null,
476 parentItemId: null,
477 ordinal: 0,
478 status: "completed" as const,
479 title: null,
480 startedAt: now,
481 completedAt: now,
482 updatedAt: now,
483 type: "approval_request" as const,
484 requestId,
485 requestKind: "command" as const,
486 prompt: "Allow command?",
487 };
488 const projection = {
489 ...v2Projection,
490 runtimeRequests: [
491 {
492 id: requestId,
493 nodeId: NodeId.make("node-root"),
494 providerTurnId: null,
495 nativeRequestRef: null,
496 kind: "command" as const,
497 status: "pending" as const,
498 responseCapability: {
499 type: "not_resumable" as const,
500 reason: "provider disconnected",
501 },
502 createdAt: now,
503 resolvedAt: null,
504 },
505 ],
506 turnItems: [item],
507 updatedAt: now,
508 };
509​
510 expect(derivePendingThreadRequests(projection).approvals).toEqual([
511 {
512 requestId,
513 requestKind: "command",
514 createdAt: "2026-06-20T01:00:00.000Z",
515 detail: "Allow command?",
516 responseCapability: "not_resumable",
517 },
518 ]);
519 expect(derivePendingThreadRequests(projection).userInputs).toEqual([]);
520 });
521​
522 it("preserves structured-question selection mode and defaults legacy payloads", () => {
523 const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
524 const multiRequestId = RuntimeRequestId.make("request-multi-select");
525 const legacyRequestId = RuntimeRequestId.make("request-legacy-single-select");
526 const runtimeRequests = [multiRequestId, legacyRequestId].map((id) => ({
527 id,
528 nodeId: NodeId.make(`node-${id}`),
529 providerTurnId: null,
530 nativeRequestRef: null,
531 kind: "user_input" as const,
532 status: "pending" as const,
533 responseCapability: {
534 type: "live" as const,
535 providerSessionId: ProviderSessionId.make("provider-session-questions"),
536 },
537 createdAt: now,
538 resolvedAt: null,
539 }));
540 const common = {
541 threadId: v2Projection.thread.id,
542 runId: null,
543 providerThreadId: null,
544 providerTurnId: null,
545 nativeItemRef: null,
546 parentItemId: null,
547 ordinal: 0,
548 status: "completed" as const,
549 title: null,
550 startedAt: now,
551 completedAt: now,
552 updatedAt: now,
553 type: "user_input_request" as const,
554 };
555 const projection = {
556 ...v2Projection,
557 runtimeRequests,
558 turnItems: [
559 {
560 ...common,
561 id: TurnItemId.make("item-multi-select"),
562 nodeId: NodeId.make("node-request-multi-select"),
563 requestId: multiRequestId,
564 questions: [
565 {
566 id: "regions",
567 header: "Regions",
568 question: "Which regions?",
569 options: [
570 { label: "US", description: "United States" },
571 { label: "EU", description: "European Union" },
572 ],
573 multiSelect: true,
574 },
575 ],
576 },
577 {
578 ...common,
579 id: TurnItemId.make("item-legacy-single-select"),
580 nodeId: NodeId.make("node-request-legacy-single-select"),
581 requestId: legacyRequestId,
582 questions: [
583 {
584 id: "target",
585 header: "Target",
586 question: "Which target?",
587 options: [{ label: "Staging", description: "Staging environment" }],
588 },
589 ],
590 },
591 ],
592 updatedAt: now,
593 };
594​
595 expect(
596 derivePendingThreadRequests(projection).userInputs.map((input) => ({
597 requestId: input.requestId,
598 multiSelect: input.questions[0]?.multiSelect,
599 })),
600 ).toEqual([
601 { requestId: multiRequestId, multiSelect: true },
602 { requestId: legacyRequestId, multiSelect: false },
603 ]);
604 });
605});