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

entities.test.ts

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