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

TurnStartReads.test.ts

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