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

entities.test.ts

633 lines20.1 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", kind: "command" }],
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([
152 { taskId: "bg-1", description: "sleep 20", kind: "command" },
153 ]);
154 });
155​
156 it("keeps a failed latest run failed while background tasks are still pending", () => {
157 const shell = presentThreadShell(environmentId, {
158 ...v2ThreadShell,
159 latestRunId: RunId.make("run-failed"),
160 activeRunId: null,
161 status: "failed",
162 lastError: "Provider turn failed",
163 pendingBackgroundTasks: [{ taskId: "bg-1", description: "sleep 20", kind: "command" }],
164 });
165​
166 // Sidebar and mobile list read runtime "idle" as Waiting before failure.
167 expect(shell.runtime).toMatchObject({ status: "failed", lastError: "Provider turn failed" });
168 expect(shell.pendingBackgroundTasks).toHaveLength(1);
169 });
170​
171 it("stacks earlier provider owners behind the current one, newest history first to go", () => {
172 const codex = ProviderInstanceId.make("codex");
173 const claude = ProviderInstanceId.make("claude");
174 const cursor = ProviderInstanceId.make("cursor");
175 const grok = ProviderInstanceId.make("grok");
176 const shell = presentThreadShell(environmentId, {
177 ...v2ThreadShell,
178 providerInstanceId: grok,
179 modelSelection: { instanceId: grok, model: "grok-4" },
180 providerInstanceHistory: [codex, claude, cursor, grok],
181 });
182​
183 // Three slots: the two most recent earlier owners, then the current one.
184 expect(resolveThreadProviderStack(shell)).toEqual([claude, cursor, grok]);
185 expect(
186 resolveThreadProviderStack({ ...shell, providerInstanceHistory: [codex, grok] }),
187 ).toEqual([codex, grok]);
188 expect(resolveThreadProviderStack({ ...shell, providerInstanceHistory: [] })).toEqual([grok]);
189 // Servers that predate the field decode to an empty history.
190 expect(
191 presentThreadShell(environmentId, { ...v2ThreadShell, providerInstanceHistory: undefined })
192 .providerInstanceHistory,
193 ).toEqual([]);
194 });
195​
196 it("keeps terminal runtime completed when there are no pending background tasks", () => {
197 const runId = RunId.make("run-completed");
198 const shell = presentThreadShell(environmentId, {
199 ...v2ThreadShell,
200 latestRunId: runId,
201 activeRunId: null,
202 status: "completed",
203 pendingBackgroundTasks: [],
204 });
205​
206 expect(shell.latestRun).toMatchObject({ runId, status: "completed" });
207 expect(shell.runtime).toMatchObject({
208 status: "completed",
209 activeRunId: null,
210 });
211 });
212​
213 it("keeps runtime running when there is no background roster", () => {
214 const runId = RunId.make("run-running");
215 const shell = presentThreadShell(environmentId, {
216 ...v2ThreadShell,
217 latestRunId: runId,
218 activeRunId: runId,
219 status: "running",
220 pendingBackgroundTasks: [],
221 });
222​
223 expect(shell.latestRun).toMatchObject({ runId, status: "running" });
224 expect(shell.runtime).toMatchObject({
225 status: "running",
226 activeRunId: runId,
227 });
228 });
229​
230 it("keeps an older active run visible over a newer cancelled run", () => {
231 const activeRunId = RunId.make("run-active");
232 const cancelledRunId = RunId.make("run-cancelled");
233 const shell = presentThreadShell(environmentId, {
234 ...v2ThreadShell,
235 latestRunId: cancelledRunId,
236 latestRunStartedAt: null,
237 latestRunCompletedAt: DateTime.makeUnsafe("2026-06-20T01:05:00.000Z"),
238 activeRunId,
239 activityRunStatus: "running",
240 status: "cancelled",
241 pendingBackgroundTasks: [],
242 });
243​
244 expect(shell.latestRun).toMatchObject({ runId: cancelledRunId, status: "cancelled" });
245 expect(shell.runtime).toMatchObject({
246 status: "running",
247 activeRunId,
248 });
249 });
250​
251 it("keeps an older waiting run visible over a newer cancelled run", () => {
252 const shell = presentThreadShell(environmentId, {
253 ...v2ThreadShell,
254 latestRunId: RunId.make("run-cancelled"),
255 activeRunId: null,
256 activityRunStatus: "waiting",
257 status: "cancelled",
258 pendingBackgroundTasks: [],
259 });
260​
261 expect(shell.runtime).toMatchObject({ status: "waiting", activeRunId: null });
262 });
263​
264 it("keeps a post-settlement background roster ahead of activity status", () => {
265 const activeRunId = RunId.make("run-active");
266 const shell = presentThreadShell(environmentId, {
267 ...v2ThreadShell,
268 latestRunId: RunId.make("run-cancelled"),
269 activeRunId,
270 activityRunStatus: "running",
271 status: "cancelled",
272 pendingBackgroundTasks: [
273 { taskId: "bg-activity", description: "background work", kind: "background_task" },
274 ],
275 });
276​
277 expect(shell.runtime).toMatchObject({ status: "idle", activeRunId });
278 });
279​
280 it("parks runtime idle over stale shell running when the roster is nonempty", () => {
281 const runId = RunId.make("run-stale-running");
282 const shell = presentThreadShell(environmentId, {
283 ...v2ThreadShell,
284 latestRunId: runId,
285 activeRunId: runId,
286 // Stale: server already projected a post-settlement roster, but shell
287 // status still says running (packaged orchestrator-v2 bug).
288 status: "running",
289 pendingBackgroundTasks: [{ taskId: "bg-1", description: "sleep 20", kind: "command" }],
290 });
291​
292 expect(shell.latestRun).toMatchObject({ runId, status: "running" });
293 expect(shell.runtime).toMatchObject({
294 status: "idle",
295 activeRunId: runId,
296 });
297 expect(shell.pendingBackgroundTasks).toEqual([
298 { taskId: "bg-1", description: "sleep 20", kind: "command" },
299 ]);
300 });
301​
302 it("parks runtime idle over stale checkpoint waiting when the roster is nonempty", () => {
303 const runId = RunId.make("run-stale-waiting");
304 const shell = presentThreadShell(environmentId, {
305 ...v2ThreadShell,
306 latestRunId: runId,
307 activeRunId: runId,
308 // Stale: checkpoint-oriented waiting masks post-settlement background work.
309 status: "waiting",
310 pendingBackgroundTasks: [{ taskId: "bg-2", description: "background bash", kind: "command" }],
311 });
312​
313 expect(shell.latestRun).toMatchObject({ runId, status: "waiting" });
314 expect(shell.runtime).toMatchObject({
315 status: "idle",
316 activeRunId: runId,
317 });
318 expect(shell.pendingBackgroundTasks).toEqual([
319 { taskId: "bg-2", description: "background bash", kind: "command" },
320 ]);
321 });
322​
323 it("derives execution summaries without wrapping or copying the projection", () => {
324 const runId = RunId.make("run-1");
325 const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
326 const projection = {
327 ...v2Projection,
328 runs: [
329 {
330 id: runId,
331 threadId: v2Projection.thread.id,
332 ordinal: 1,
333 providerInstanceId: v2Projection.thread.providerInstanceId,
334 modelSelection: v2Projection.thread.modelSelection,
335 providerThreadId: null,
336 userMessageId: MessageId.make("message-user"),
337 rootNodeId: null,
338 activeAttemptId: null,
339 status: "running" as const,
340 requestedAt: now,
341 startedAt: now,
342 completedAt: null,
343 checkpointId: null,
344 contextHandoffId: null,
345 },
346 ],
347 messages: [
348 {
349 id: MessageId.make("message-user"),
350 threadId: v2Projection.thread.id,
351 runId,
352 nodeId: null,
353 role: "user" as const,
354 text: "Hello",
355 attachments: [],
356 streaming: false,
357 createdBy: "user" as const,
358 creationSource: "web" as const,
359 createdAt: now,
360 updatedAt: now,
361 },
362 ],
363 updatedAt: now,
364 };
365​
366 expect(deriveLatestThreadRun(projection)).toMatchObject({
367 runId,
368 status: "running",
369 requestedAt: "2026-06-20T01:00:00.000Z",
370 assistantMessageId: null,
371 });
372 expect(deriveThreadRuntime(projection)).toMatchObject({
373 status: "running",
374 activeRunId: runId,
375 providerInstanceId: projection.thread.providerInstanceId,
376 });
377 for (const status of ["queued", "cancelled"] as const) {
378 const later = DateTime.add(now, { hours: 1 });
379 const latest = {
380 ...projection.runs[0]!,
381 id: RunId.make("newer-run"),
382 ordinal: 2,
383 status,
384 requestedAt: later,
385 startedAt: null,
386 completedAt: status === "cancelled" ? later : null,
387 };
388 const detail = { ...projection, runs: [...projection.runs, latest], updatedAt: later };
389 const shell = presentThreadShell(environmentId, {
390 ...v2ThreadShell,
391 latestRunId: latest.id,
392 latestRunStartedAt: null,
393 latestRunRequestedAt: later,
394 latestRunCompletedAt: latest.completedAt,
395 status,
396 activeRunId: runId,
397 activityRunStatus: "running",
398 activityRunStartedAt: now,
399 updatedAt: later,
400 });
401 expect(resolveThreadWorkingStartedAt(shell)).toBe(DateTime.formatIso(now));
402 expect(
403 resolveThreadWorkingStartedAt({
404 latestRun: deriveLatestThreadRun(detail),
405 runtime: deriveThreadRuntime(detail),
406 }),
407 ).toBe(resolveThreadWorkingStartedAt(shell));
408 const stopped = {
409 ...detail,
410 runs: detail.runs.map((run) => ({
411 ...run,
412 status: "completed" as const,
413 completedAt: later,
414 })),
415 };
416 expect(
417 resolveThreadWorkingStartedAt({
418 latestRun: deriveLatestThreadRun(stopped),
419 runtime: deriveThreadRuntime(stopped),
420 }),
421 ).toBeNull();
422 }
423 });
424​
425 it("parks waiting runtime for a post-settlement roster without hiding active running work", () => {
426 const runId = RunId.make("run-background-presentation");
427 const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
428 const run = {
429 id: runId,
430 threadId: v2Projection.thread.id,
431 ordinal: 1,
432 providerInstanceId: v2Projection.thread.providerInstanceId,
433 modelSelection: v2Projection.thread.modelSelection,
434 providerThreadId: null,
435 userMessageId: MessageId.make("message-background-presentation"),
436 rootNodeId: null,
437 activeAttemptId: null,
438 status: "waiting" as const,
439 requestedAt: now,
440 startedAt: now,
441 completedAt: null,
442 checkpointId: null,
443 contextHandoffId: null,
444 };
445 const backgroundItem = {
446 id: TurnItemId.make("item-background-command"),
447 threadId: v2Projection.thread.id,
448 runId,
449 nodeId: null,
450 providerThreadId: null,
451 providerTurnId: null,
452 nativeItemRef: null,
453 parentItemId: null,
454 ordinal: 0,
455 status: "running" as const,
456 title: "Background command",
457 startedAt: now,
458 completedAt: null,
459 updatedAt: now,
460 type: "command_execution" as const,
461 input: "sleep 20",
462 };
463​
464 expect(
465 deriveThreadRuntime({
466 ...v2Projection,
467 runs: [run],
468 turnItems: [backgroundItem],
469 }),
470 ).toMatchObject({
471 status: "idle",
472 activeRunId: null,
473 });
474 expect(
475 deriveThreadRuntime({
476 ...v2Projection,
477 runs: [{ ...run, status: "running" as const }],
478 turnItems: [backgroundItem],
479 }),
480 ).toMatchObject({
481 status: "running",
482 activeRunId: runId,
483 });
484 expect(
485 deriveThreadRuntime({
486 ...v2Projection,
487 runs: [{ ...run, status: "failed" as const, completedAt: now }],
488 turnItems: [backgroundItem],
489 }),
490 ).toMatchObject({ status: "failed", activeRunId: null });
491 });
492​
493 it("joins pending request entities to their native turn-item display data", () => {
494 const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
495 const requestId = RuntimeRequestId.make("request-approval");
496 const item = {
497 id: TurnItemId.make("item-approval"),
498 threadId: v2Projection.thread.id,
499 runId: null,
500 nodeId: NodeId.make("node-root"),
501 providerThreadId: null,
502 providerTurnId: null,
503 nativeItemRef: null,
504 parentItemId: null,
505 ordinal: 0,
506 status: "completed" as const,
507 title: null,
508 startedAt: now,
509 completedAt: now,
510 updatedAt: now,
511 type: "approval_request" as const,
512 requestId,
513 requestKind: "command" as const,
514 prompt: "Allow command?",
515 };
516 const projection = {
517 ...v2Projection,
518 runtimeRequests: [
519 {
520 id: requestId,
521 nodeId: NodeId.make("node-root"),
522 providerTurnId: null,
523 nativeRequestRef: null,
524 kind: "command" as const,
525 status: "pending" as const,
526 responseCapability: {
527 type: "not_resumable" as const,
528 reason: "provider disconnected",
529 },
530 createdAt: now,
531 resolvedAt: null,
532 },
533 ],
534 turnItems: [item],
535 updatedAt: now,
536 };
537​
538 expect(derivePendingThreadRequests(projection).approvals).toEqual([
539 {
540 requestId,
541 requestKind: "command",
542 createdAt: "2026-06-20T01:00:00.000Z",
543 detail: "Allow command?",
544 responseCapability: "not_resumable",
545 },
546 ]);
547 expect(derivePendingThreadRequests(projection).userInputs).toEqual([]);
548 });
549​
550 it("preserves structured-question selection mode and defaults legacy payloads", () => {
551 const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
552 const multiRequestId = RuntimeRequestId.make("request-multi-select");
553 const legacyRequestId = RuntimeRequestId.make("request-legacy-single-select");
554 const runtimeRequests = [multiRequestId, legacyRequestId].map((id) => ({
555 id,
556 nodeId: NodeId.make(`node-${id}`),
557 providerTurnId: null,
558 nativeRequestRef: null,
559 kind: "user_input" as const,
560 status: "pending" as const,
561 responseCapability: {
562 type: "live" as const,
563 providerSessionId: ProviderSessionId.make("provider-session-questions"),
564 },
565 createdAt: now,
566 resolvedAt: null,
567 }));
568 const common = {
569 threadId: v2Projection.thread.id,
570 runId: null,
571 providerThreadId: null,
572 providerTurnId: null,
573 nativeItemRef: null,
574 parentItemId: null,
575 ordinal: 0,
576 status: "completed" as const,
577 title: null,
578 startedAt: now,
579 completedAt: now,
580 updatedAt: now,
581 type: "user_input_request" as const,
582 };
583 const projection = {
584 ...v2Projection,
585 runtimeRequests,
586 turnItems: [
587 {
588 ...common,
589 id: TurnItemId.make("item-multi-select"),
590 nodeId: NodeId.make("node-request-multi-select"),
591 requestId: multiRequestId,
592 questions: [
593 {
594 id: "regions",
595 header: "Regions",
596 question: "Which regions?",
597 options: [
598 { label: "US", description: "United States" },
599 { label: "EU", description: "European Union" },
600 ],
601 multiSelect: true,
602 },
603 ],
604 },
605 {
606 ...common,
607 id: TurnItemId.make("item-legacy-single-select"),
608 nodeId: NodeId.make("node-request-legacy-single-select"),
609 requestId: legacyRequestId,
610 questions: [
611 {
612 id: "target",
613 header: "Target",
614 question: "Which target?",
615 options: [{ label: "Staging", description: "Staging environment" }],
616 },
617 ],
618 },
619 ],
620 updatedAt: now,
621 };
622​
623 expect(
624 derivePendingThreadRequests(projection).userInputs.map((input) => ({
625 requestId: input.requestId,
626 multiSelect: input.questions[0]?.multiSelect,
627 })),
628 ).toEqual([
629 { requestId: multiRequestId, multiSelect: true },
630 { requestId: legacyRequestId, multiSelect: false },
631 ]);
632 });
633});