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

TurnStartReads.test.ts

629 lines21.8 KB

1import { assert, it } from "@effect/vitest";
2import {
3 CheckpointScopeId,
4 ContextTransferId,
5 NodeId,
6 EventId,
7 MessageId,
8 ProjectId,
9 ProviderDriverKind,
10 ProviderInstanceId,
11 RunId,
12 RuntimeRequestId,
13 ThreadId,
14 TurnItemId,
15 type OrchestrationV2AppThread,
16 type OrchestrationV2Run,
17} from "@t3tools/contracts";
18import * as DateTime from "effect/DateTime";
19import * as Effect from "effect/Effect";
20import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
21import * as Layer from "effect/Layer";
22import * as SqlClient from "effect/sql/SqlClient";
23import * as SqlitePersistence from "../persistence/Sqlite.ts";
24import * as ProjectionStore from "./ProjectionStore.ts";
25​
26const layerDatabase = Layer.mergeAll(
27 SqlitePersistence.layerMemory,
28 ProjectionStore.layer.pipe(
29 Layer.provide(NodeCrypto.layerDigest),
30 Layer.provide(SqlitePersistence.layerMemory),
31 ),
32);
33​
34it.effect.each(["sqlite"] as const)(
35 "loads startup state without obsolete transcript payloads in %s",
36 (storage) =>
37 Effect.gen(function* () {
38 const store = yield* ProjectionStore.ProjectionStoreV2;
39 const now = yield* DateTime.now;
40 const threadId = ThreadId.make("thread:completion-reads");
41 const runId = RunId.make("run:completion-reads");
42 const messageId = MessageId.make("message:completion-reads");
43 const instanceId = ProviderInstanceId.make("codex");
44 const thread: OrchestrationV2AppThread = {
45 id: threadId,
46 projectId: ProjectId.make("project:completion-reads"),
47 title: "Completion controls",
48 providerInstanceId: instanceId,
49 modelSelection: { instanceId, model: "test" },
50 runtimeMode: "full-access",
51 interactionMode: "default",
52 branch: null,
53 worktreePath: null,
54 activeProviderThreadId: null,
55 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
56 forkedFrom: null,
57 createdBy: "user",
58 creationSource: "web",
59 createdAt: now,
60 updatedAt: now,
61 archivedAt: null,
62 settledOverride: null,
63 settledAt: null,
64 lastVisitedAt: null,
65 deletedAt: null,
66 };
67 const run: OrchestrationV2Run = {
68 id: runId,
69 threadId,
70 ordinal: 2,
71 providerInstanceId: instanceId,
72 modelSelection: thread.modelSelection,
73 providerThreadId: null,
74 userMessageId: messageId,
75 rootNodeId: NodeId.make("startup:root"),
76 activeAttemptId: null,
77 status: "queued",
78 requestedAt: now,
79 startedAt: null,
80 completedAt: null,
81 checkpointId: null,
82 contextHandoffId: null,
83 };
84 const putThread = (value: OrchestrationV2AppThread) =>
85 store.apply({
86 id: EventId.make(`event:thread:${value.id}`),
87 type: "thread.created",
88 threadId: value.id,
89 occurredAt: now,
90 payload: value,
91 });
92 const putRun = (value: OrchestrationV2Run) =>
93 store.apply({
94 id: EventId.make(`event:run:${value.id}:${value.status}`),
95 type: "run.updated",
96 threadId,
97 runId: value.id,
98 occurredAt: now,
99 payload: value,
100 });
101 yield* putThread(thread);
102 yield* putRun(run);
103 const scopeId = CheckpointScopeId.make("startup:shared-scope");
104 yield* store.apply({
105 id: EventId.make("startup:root-event"),
106 type: "node.updated",
107 threadId,
108 occurredAt: now,
109 payload: {
110 id: run.rootNodeId!,
111 threadId,
112 runId,
113 parentNodeId: null,
114 rootNodeId: run.rootNodeId!,
115 kind: "root_turn",
116 status: "pending",
117 countsForRun: true,
118 providerThreadId: null,
119 providerTurnId: null,
120 nativeItemRef: null,
121 runtimeRequestId: null,
122 checkpointScopeId: scopeId,
123 startedAt: null,
124 completedAt: null,
125 },
126 });
127 yield* store.apply({
128 id: EventId.make("startup:scope-event"),
129 type: "checkpoint-scope.created",
130 threadId,
131 occurredAt: now,
132 payload: {
133 id: scopeId,
134 threadId,
135 runId: RunId.make("run:old"),
136 nodeId: NodeId.make("startup:earlier-root"),
137 parentScopeId: null,
138 providerThreadId: null,
139 kind: "root_run",
140 ordinalWithinParent: 0,
141 advancesAppRunCount: true,
142 cwd: "/repo/worktree",
143 createdAt: now,
144 },
145 });
146 const message = {
147 id: messageId,
148 threadId,
149 runId,
150 nodeId: null,
151 role: "user" as const,
152 text: "Continue",
153 attachments: [],
154 streaming: false,
155 createdBy: "agent" as const,
156 creationSource: "server" as const,
157 createdAt: now,
158 updatedAt: now,
159 delegatedCompletion: { parentRunId: RunId.make("parent-run"), generation: 1, taskIds: [] },
160 };
161 yield* store.apply({
162 id: EventId.make("event:input"),
163 type: "message.updated",
164 threadId,
165 runId,
166 occurredAt: now,
167 payload: message,
168 });
169 const oldRunId = RunId.make("run:old");
170 yield* putRun({ ...run, id: oldRunId, ordinal: 1, status: "completed" });
171 const item = {
172 id: TurnItemId.make("item:history"),
173 threadId,
174 runId: oldRunId,
175 nodeId: null,
176 providerThreadId: null,
177 providerTurnId: null,
178 nativeItemRef: null,
179 parentItemId: null,
180 ordinal: 1,
181 status: "completed" as const,
182 title: "old command",
183 startedAt: now,
184 completedAt: now,
185 updatedAt: now,
186 type: "command_execution" as const,
187 input: "echo history",
188 output: "historical result",
189 };
190 yield* store.apply({
191 id: EventId.make("item-event"),
192 type: "turn-item.updated",
193 threadId,
194 runId: oldRunId,
195 occurredAt: now,
196 payload: item,
197 });
198 if (storage === "sqlite") {
199 const sql = yield* SqlClient.SqlClient;
200 yield* sql`INSERT INTO orchestration_v2_projection_messages
201 (message_id, thread_id, run_id, node_id, role, streaming, created_at, updated_at, payload_json)
202 VALUES ('obsolete-history', ${threadId}, NULL, NULL, 'assistant', 0,
203 ${DateTime.formatIso(now)}, ${DateTime.formatIso(now)}, '{"obsolete":true}')`;
204 yield* sql`INSERT INTO orchestration_v2_projection_turn_items
205 (turn_item_id, thread_id, run_id, node_id, provider_thread_id, provider_turn_id,
206 type, status, ordinal, updated_at, payload_json)
207 VALUES ('obsolete-tool', ${threadId}, ${oldRunId}, NULL, NULL, NULL,
208 'tool_call', 'completed', 2, ${DateTime.formatIso(now)}, '{"obsolete":true}')`;
209 assert.equal((yield* Effect.exit(store.getThreadProjection(threadId)))._tag, "Failure");
210 }
211 const selected = yield* store.getThreadRecords(threadId, ["runs", "messages"], {
212 runIds: [runId],
213 messageIds: [messageId],
214 });
215 assert.deepEqual(Object.keys(selected).sort(), ["messages", "runs", "thread"]);
216 assert.deepEqual(
217 selected.runs.map((r) => r.id),
218 [runId],
219 );
220 assert.deepEqual(
221 selected.messages.map((m) => m.id),
222 [messageId],
223 );
224 assert.deepEqual(
225 (yield* store.getThreadRecords(threadId, ["messages"], { messageIds: [] })).messages,
226 [],
227 );
228 assert.deepEqual(
229 (yield* store.getThreadRecords(threadId, ["turnItems"], {
230 turnItemTypes: ["command_execution"],
231 turnItemRunId: oldRunId,
232 })).turnItems,
233 [item],
234 );
235 assert.deepEqual(
236 (yield* store.getThreadRecords(threadId, ["turnItems"], {
237 turnItemTypes: ["command_execution"],
238 turnItemRunId: runId,
239 })).turnItems,
240 [],
241 );
242 assert.equal(yield* store.getNextTurnItemOrdinal(threadId), storage === "sqlite" ? 3 : 2);
243 assert.equal(yield* store.getMessageCount(threadId), storage === "sqlite" ? 2 : 1);
244 assert.deepEqual(
245 (yield* store.getThreadRecords(threadId, ["messages"], {
246 messageRunIds: [runId],
247 })).messages.map((message) => message.id),
248 [messageId],
249 );
250 assert.deepEqual(
251 (yield* store.getThreadRecords(threadId, ["messages"], { messageRunIds: [] })).messages,
252 [],
253 );
254 assert.deepEqual(
255 (yield* store.getThreadRecords(threadId, ["turnItems"], {
256 turnItemTypes: ["command_execution"],
257 turnItemRunIds: [oldRunId],
258 })).turnItems,
259 [item],
260 );
261 assert.deepEqual(
262 (yield* store.getThreadRecords(threadId, ["turnItems"], { turnItemRunIds: [] })).turnItems,
263 [],
264 );
265 assert.deepEqual(yield* store.getThreadAttachmentIds(threadId), []);
266 if (storage === "sqlite") {
267 const sql = yield* SqlClient.SqlClient;
268 yield* sql`UPDATE orchestration_v2_projection_messages SET payload_json = json_object('text', ${"x".repeat(512_000)}, 'attachments', json_array(json_object('id', 'attachment:old'))) WHERE message_id = 'obsolete-history'`;
269 assert.deepEqual(yield* store.getThreadAttachmentIds(threadId), ["attachment:old"]);
270 }
271 const page = yield* store.getTimelinePage(threadId, { view: "activity", limit: 1 });
272 assert.deepEqual(
273 page.items.map((row) => row.item),
274 [item],
275 );
276 assert.equal(page.hasMore, storage === "sqlite");
277 assert.equal(page.totalItems, storage === "sqlite" ? 2 : 1);
278 assert.deepEqual(
279 (yield* store.getTimelinePage(threadId, { view: "messages", limit: 1 })).items,
280 [],
281 );
282 const context = yield* store.getTurnStartContext(threadId, runId);
283 assert.equal(context.thread.id, threadId);
284 assert.deepEqual(
285 context.checkpointScopes.map((scope) => scope.id),
286 [scopeId],
287 );
288 assert.equal(context.messages.find((m) => m.id === messageId)?.text, "Continue");
289 assert.isTrue(context.hasConversation);
290 assert.deepEqual(context.turnItems, []);
291 assert.deepEqual(yield* store.getTurnStartHistory(threadId), [item]);
292 assert.deepEqual(yield* store.getTurnStartHistory(threadId, [oldRunId]), [item]);
293 assert.deepEqual(yield* store.getTurnStartHistory(threadId, [runId]), []);
294 assert.deepEqual(yield* store.getTurnStartHistory(threadId, []), []);
295 const resultId = TurnItemId.make("interrupt-result");
296 assert.isTrue(yield* store.hasUnpairedRunInterruptRequest(threadId, item.id, resultId));
297 assert.isFalse(yield* store.hasUnpairedRunInterruptRequest(threadId, resultId, item.id));
298 assert.isFalse(
299 yield* store.hasUnpairedRunInterruptRequest(
300 ThreadId.make("other-thread"),
301 item.id,
302 resultId,
303 ),
304 );
305 yield* store.apply({
306 id: EventId.make("interrupt-result-event"),
307 type: "turn-item.updated",
308 threadId,
309 runId: oldRunId,
310 occurredAt: now,
311 payload: { ...item, id: resultId },
312 });
313 assert.isFalse(yield* store.hasUnpairedRunInterruptRequest(threadId, item.id, resultId));
314 if (storage === "sqlite") {
315 const sql = yield* SqlClient.SqlClient;
316 const original = yield* sql<{ payload_json: string }>`SELECT payload_json
317 FROM orchestration_v2_projection_turn_items WHERE turn_item_id = ${item.id}`;
318 yield* sql`UPDATE orchestration_v2_projection_turn_items
319 SET payload_json = 'invalid JSON' WHERE turn_item_id = ${item.id}`;
320 assert.isTrue(
321 yield* store.hasUnpairedRunInterruptRequest(
322 threadId,
323 item.id,
324 TurnItemId.make("absent-result"),
325 ),
326 );
327 yield* sql`UPDATE orchestration_v2_projection_turn_items
328 SET payload_json = ${original[0]!.payload_json} WHERE turn_item_id = ${item.id}`;
329 }
330 yield* store.apply({
331 id: EventId.make("cancel-interrupt-result"),
332 type: "turn-item.updated",
333 threadId,
334 runId: oldRunId,
335 occurredAt: now,
336 payload: { ...item, id: resultId, status: "cancelled" },
337 });
338 assert.isTrue(yield* store.hasUnpairedRunInterruptRequest(threadId, item.id, resultId));
339 yield* store.apply({
340 id: EventId.make("cancel-interrupt-request"),
341 type: "turn-item.updated",
342 threadId,
343 runId: oldRunId,
344 occurredAt: now,
345 payload: { ...item, status: "cancelled" },
346 });
347 assert.isFalse(yield* store.hasUnpairedRunInterruptRequest(threadId, item.id, resultId));
348 for (const text of ["/compact", " \t/COMPACT\n", "\u00a0/compact\u3000"]) {
349 yield* store.apply({
350 id: EventId.make("compact-input"),
351 type: "message.updated",
352 threadId,
353 runId,
354 occurredAt: now,
355 payload: { ...message, text },
356 });
357 assert.isFalse((yield* store.getTurnStartContext(threadId, runId)).hasConversation);
358 }
359 const marker = {
360 ...message,
361 id: MessageId.make("old-compact"),
362 runId: oldRunId,
363 text: "\t/COMPACT\n",
364 };
365 yield* store.apply({
366 id: EventId.make("old-compact-input"),
367 type: "message.updated",
368 threadId,
369 runId: oldRunId,
370 occurredAt: now,
371 payload: marker,
372 });
373 assert.include(
374 (yield* store.getTurnStartContext(threadId, runId)).messages.map((m) => m.id),
375 marker.id,
376 );
377 const originalId = MessageId.make("unsent-original");
378 yield* store.apply({
379 id: EventId.make("unsent-original-event"),
380 type: "message.updated",
381 threadId,
382 runId: oldRunId,
383 occurredAt: now,
384 payload: { ...message, id: originalId, runId: oldRunId, text: "Original request" },
385 });
386 yield* putRun({
387 ...run,
388 id: oldRunId,
389 ordinal: 1,
390 status: "interrupted",
391 userMessageId: originalId,
392 });
393 const retryId = RunId.make("unsent-retry");
394 yield* putRun({ ...run, ordinal: 3, manualContinuationOfRunId: retryId });
395 yield* putRun({
396 ...run,
397 id: retryId,
398 ordinal: 2,
399 status: "interrupted",
400 manualContinuationOfRunId: oldRunId,
401 });
402 assert.equal(
403 (yield* store.getTurnStartContext(threadId, runId)).messages.find(
404 (m) => m.id === originalId,
405 )?.text,
406 "Original request",
407 );
408 const other = ThreadId.make("other");
409 yield* putThread({ ...thread, id: other });
410 assert.deepEqual((yield* store.getTurnStartContext(other, runId)).messages, []);
411 assert.deepEqual(yield* store.getTurnStartHistory(other, [oldRunId]), []);
412 assert.isFalse((yield* store.getTurnStartContext(other, runId)).hasConversation);
413 assert.instanceOf(
414 yield* store.getTurnStartContext(ThreadId.make("missing"), runId).pipe(Effect.flip),
415 ProjectionStore.ProjectionStoreThreadNotFoundError,
416 );
417 const file = {
418 type: "file" as const,
419 id: "message-file",
420 name: "notes.pdf",
421 mimeType: "application/pdf",
422 sizeBytes: 12,
423 };
424 yield* store.apply({
425 id: EventId.make("attachment:message-event"),
426 type: "message.updated",
427 threadId,
428 runId,
429 occurredAt: now,
430 payload: { ...message, attachments: [file] },
431 });
432 yield* store.apply({
433 id: EventId.make("attachment:question-event"),
434 type: "turn-item.updated",
435 threadId,
436 runId: oldRunId,
437 occurredAt: now,
438 payload: {
439 ...item,
440 id: TurnItemId.make("attachment:question"),
441 type: "user_input_request",
442 requestId: RuntimeRequestId.make("attachment:request"),
443 questions: [],
444 questionAnswer: {
445 requestId: "attachment:request",
446 answers: { document: ["See document"], image: ["See image"] },
447 attachmentsByQuestionId: {
448 document: [{ ...file, id: "answer-document" }],
449 image: [
450 {
451 type: "image",
452 id: "answer-image",
453 name: "photo.png",
454 mimeType: "image/png",
455 sizeBytes: 8,
456 },
457 ],
458 },
459 },
460 },
461 });
462 const recordingId = "thread-completion-reads-0b9f6c1e-3c1d-4f7a-9d2e-5a6b7c8d9e0f-webm";
463 yield* store.apply({
464 id: EventId.make("attachment:recording-event"),
465 type: "turn-item.updated",
466 threadId,
467 runId: oldRunId,
468 occurredAt: now,
469 payload: {
470 ...item,
471 id: TurnItemId.make("attachment:recording"),
472 type: "dynamic_tool",
473 toolName: "mcp__t3-code__preview_recording_stop",
474 input: {},
475 output: [
476 { type: "text", text: JSON.stringify({ id: recordingId, mimeType: "video/webm" }) },
477 ],
478 },
479 });
480 assert.deepEqual((yield* store.getThreadAttachmentIds(threadId)).toSorted(), [
481 "answer-document",
482 "answer-image",
483 "attachment:old",
484 "message-file",
485 recordingId,
486 ]);
487 }).pipe(Effect.provide(layerDatabase)),
488);
489​
490it.effect(
491 "counts a native fork's inherited history as conversation for its first /compact in sqlite",
492 () =>
493 Effect.gen(function* () {
494 const store = yield* ProjectionStore.ProjectionStoreV2;
495 const now = yield* DateTime.now;
496 const instanceId = ProviderInstanceId.make("claudeAgent");
497 const sourceId = ThreadId.make("thread:fork-source");
498 const forkId = ThreadId.make("thread:fork-target");
499 const sourceRunId = RunId.make("run:fork-source-third");
500 const forkRunId = RunId.make("run:fork-compact");
501 const source: OrchestrationV2AppThread = {
502 id: sourceId,
503 projectId: ProjectId.make("project:fork-compact"),
504 title: "Source",
505 providerInstanceId: instanceId,
506 modelSelection: { instanceId, model: "claude-opus-5-5" },
507 runtimeMode: "full-access",
508 interactionMode: "default",
509 branch: null,
510 worktreePath: null,
511 activeProviderThreadId: null,
512 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: sourceId },
513 forkedFrom: null,
514 createdBy: "user",
515 creationSource: "web",
516 createdAt: now,
517 updatedAt: now,
518 archivedAt: null,
519 settledOverride: null,
520 settledAt: null,
521 lastVisitedAt: null,
522 deletedAt: null,
523 };
524 const fork: OrchestrationV2AppThread = {
525 ...source,
526 id: forkId,
527 title: "Fork",
528 lineage: { parentThreadId: sourceId, relationshipToParent: "fork", rootThreadId: sourceId },
529 forkedFrom: { type: "run", threadId: sourceId, runId: sourceRunId },
530 };
531 const run = (threadId: ThreadId, id: RunId, status: OrchestrationV2Run["status"]) =>
532 ({
533 id,
534 threadId,
535 ordinal: 1,
536 providerInstanceId: instanceId,
537 modelSelection: source.modelSelection,
538 providerThreadId: null,
539 userMessageId: MessageId.make(`message:${id}`),
540 rootNodeId: NodeId.make(`node:${id}`),
541 activeAttemptId: null,
542 status,
543 requestedAt: now,
544 startedAt: null,
545 completedAt: null,
546 checkpointId: null,
547 contextHandoffId: null,
548 }) satisfies OrchestrationV2Run;
549 const userMessage = (threadId: ThreadId, runId: RunId, text: string) =>
550 store.apply({
551 id: EventId.make(`event:message:${runId}`),
552 type: "message.updated",
553 threadId,
554 runId,
555 occurredAt: now,
556 payload: {
557 id: MessageId.make(`message:${runId}`),
558 threadId,
559 runId,
560 nodeId: null,
561 role: "user",
562 text,
563 attachments: [],
564 streaming: false,
565 createdBy: "user",
566 creationSource: "web",
567 createdAt: now,
568 updatedAt: now,
569 },
570 });
571 for (const thread of [source, fork]) {
572 yield* store.apply({
573 id: EventId.make(`event:thread:${thread.id}`),
574 type: "thread.created",
575 threadId: thread.id,
576 occurredAt: now,
577 payload: thread,
578 });
579 }
580 for (const [threadId, value] of [
581 [sourceId, run(sourceId, sourceRunId, "completed")],
582 [forkId, run(forkId, forkRunId, "queued")],
583 ] as const) {
584 yield* store.apply({
585 id: EventId.make(`event:run:${value.id}`),
586 type: "run.updated",
587 threadId,
588 runId: value.id,
589 occurredAt: now,
590 payload: value,
591 });
592 }
593 yield* userMessage(sourceId, sourceRunId, "THIRD");
594 yield* store.apply({
595 id: EventId.make("event:fork-transfer"),
596 type: "context-transfer.created",
597 threadId: forkId,
598 occurredAt: now,
599 payload: {
600 id: ContextTransferId.make("transfer:fork-compact"),
601 type: "fork",
602 sourceThreadId: sourceId,
603 targetThreadId: forkId,
604 sourcePoint: { threadId: sourceId, runId: sourceRunId },
605 basePoint: null,
606 sourceProviderInstanceId: instanceId,
607 targetProviderInstanceId: instanceId,
608 targetRunId: forkRunId,
609 status: "pending",
610 resolution: {
611 strategy: "native_fork",
612 providerThreadRef: {
613 driver: ProviderDriverKind.make("claudeAgent"),
614 nativeId: "native-fork-source",
615 strength: "strong",
616 },
617 },
618 createdBy: "user",
619 error: null,
620 createdAt: now,
621 updatedAt: now,
622 consumedAt: null,
623 },
624 });
625 yield* userMessage(forkId, forkRunId, "/compact");
626​
627 assert.isTrue((yield* store.getTurnStartContext(forkId, forkRunId)).hasConversation);
628 }).pipe(Effect.provide(layerDatabase)),
629);