Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 ContextTransferId,
4 MessageId,
5 ProjectId,
6 ProviderInstanceId,
7 ProviderThreadId,
8 RunId,
9 ThreadId,
10 TurnItemId,
11 type OrchestrationV2AppThread,
12 type OrchestrationV2TurnItem,
13} from "@t3tools/contracts";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17β
18import * as ContextHandoffService from "./ContextHandoffService.ts";
19import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
20import { ProjectionStoreThreadNotFoundError } from "./ProjectionStore.ts";
21β
22const layerTest = ContextHandoffService.layer.pipe(Layer.provide(IdAllocator.layer));
23β
24function importedItem(
25 input:
26 | {
27 readonly role: "user";
28 readonly id: string;
29 readonly text: string;
30 readonly ordinal: number;
31 }
32 | {
33 readonly role: "assistant";
34 readonly id: string;
35 readonly text: string;
36 readonly ordinal: number;
37 },
38): OrchestrationV2TurnItem {
39 const now = DateTime.makeUnsafe("2026-01-01T00:00:00.000Z");
40 const base = {
41 id: TurnItemId.make(`turn-item:${input.id}`),
42 threadId: ThreadId.make("thread:legacy-context"),
43 runId: null,
44 nodeId: null,
45 providerThreadId: null,
46 providerTurnId: null,
47 nativeItemRef: null,
48 parentItemId: null,
49 ordinal: input.ordinal,
50 status: "completed" as const,
51 title: null,
52 startedAt: now,
53 completedAt: now,
54 updatedAt: now,
55 messageId: MessageId.make(`message:${input.id}`),
56 text: input.text,
57 };
58 return input.role === "user"
59 ? {
60 ...base,
61 createdBy: "user",
62 creationSource: "server",
63 type: "user_message",
64 inputIntent: "turn_start",
65 attachments: [],
66 }
67 : {
68 ...base,
69 type: "assistant_message",
70 streaming: false,
71 };
72}
73β
74it.layer(layerTest)("ContextHandoffService legacy import", (it) => {
75 it.effect("prepares imported history for the first native v2 turn", () =>
76 Effect.gen(function* () {
77 const service = yield* ContextHandoffService.ContextHandoffServiceV2;
78 const handoff = yield* service.prepareLegacyImport({
79 threadId: ThreadId.make("thread:legacy-context"),
80 targetRunId: RunId.make("run:first-v2"),
81 toProviderThreadId: ProviderThreadId.make("provider-thread:first-v2"),
82 toProviderInstanceId: ProviderInstanceId.make("codex"),
83 items: [
84 importedItem({ role: "user", id: "one", text: "What did we decide?", ordinal: 1 }),
85 importedItem({
86 role: "assistant",
87 id: "two",
88 text: "We decided to keep the migration lightweight.",
89 ordinal: 2,
90 }),
91 ],
92 createdAt: DateTime.makeUnsafe("2026-01-02T00:00:00.000Z"),
93 });
94β
95 assert.equal(handoff.strategy, "manual_context");
96 assert.deepStrictEqual(handoff.fromProviderThreadIds, []);
97 assert.include(handoff.summaryText, "What did we decide?");
98 assert.include(handoff.summaryText, "keep the migration lightweight");
99 }),
100 );
101β
102 it.effect("preserves role attribution when truncating imported history", () =>
103 Effect.gen(function* () {
104 const service = yield* ContextHandoffService.ContextHandoffServiceV2;
105 const handoff = yield* service.prepareLegacyImport({
106 threadId: ThreadId.make("thread:legacy-context"),
107 targetRunId: RunId.make("run:first-v2"),
108 toProviderThreadId: ProviderThreadId.make("provider-thread:first-v2"),
109 toProviderInstanceId: ProviderInstanceId.make("codex"),
110 items: [
111 importedItem({
112 role: "user",
113 id: "long",
114 text: `${"x".repeat(35_000)} retained final words`,
115 ordinal: 1,
116 }),
117 ],
118 createdAt: DateTime.makeUnsafe("2026-01-02T00:00:00.000Z"),
119 });
120β
121 assert.isAtMost(handoff.summaryText.length, 32_000);
122 assert.include(handoff.summaryText, "User:\n... retained final words");
123 assert.notMatch(handoff.summaryText, /\n+x+ retained final words/);
124 }),
125 );
126β
127 it.effect("retains the newest oversized import even when it has no whitespace", () =>
128 Effect.gen(function* () {
129 const service = yield* ContextHandoffService.ContextHandoffServiceV2;
130 const handoff = yield* service.prepareLegacyImport({
131 threadId: ThreadId.make("thread:legacy-context"),
132 targetRunId: RunId.make("run:first-v2"),
133 toProviderThreadId: ProviderThreadId.make("provider-thread:first-v2"),
134 toProviderInstanceId: ProviderInstanceId.make("codex"),
135 items: [
136 importedItem({
137 role: "assistant",
138 id: "older",
139 text: "older message",
140 ordinal: 1,
141 }),
142 importedItem({
143 role: "user",
144 id: "long-single-token",
145 text: `${"π§ͺ".repeat(20_000)}LATEST_SINGLE_TOKEN`,
146 ordinal: 2,
147 }),
148 ],
149 createdAt: DateTime.makeUnsafe("2026-01-02T00:00:00.000Z"),
150 });
151β
152 assert.include(
153 handoff.history?.omittedItemIds ?? [],
154 TurnItemId.make("turn-item:long-single-token"),
155 );
156 assert.isAtMost(handoff.summaryText.length, 32_000);
157 assert.include(handoff.summaryText, "User:\n... ");
158 assert.include(handoff.summaryText, "LATEST_SINGLE_TOKEN");
159 assert.notInclude(handoff.summaryText, "\ufffd");
160 }),
161 );
162});
163β
164it.layer(layerTest)("ContextHandoffService token cap", (it) => {
165 it.effect("retains a long reply within the configured token cap", () =>
166 Effect.gen(function* () {
167 const service = yield* ContextHandoffService.ContextHandoffServiceV2;
168 const replyText = "Detailed plan.\n".repeat(1_400);
169 const handoff = yield* service.prepareProviderHandoff({
170 threadId: ThreadId.make("thread:legacy-context"),
171 targetRunId: RunId.make("run:handoff"),
172 transferId: null,
173 fromProviderThreadIds: [ProviderThreadId.make("provider-thread:source")],
174 toProviderThreadId: ProviderThreadId.make("provider-thread:target"),
175 fromProviderInstanceId: ProviderInstanceId.make("codex"),
176 toProviderInstanceId: ProviderInstanceId.make("claude"),
177 coveredRunOrdinals: { from: 1, to: 1 },
178 createdAt: DateTime.makeUnsafe("2026-01-02T00:00:00.000Z"),
179 strategy: "full_thread_summary",
180 items: [
181 importedItem({ role: "user", id: "request", text: "Write a plan", ordinal: 1 }),
182 importedItem({ role: "assistant", id: "long-reply", text: replyText, ordinal: 2 }),
183 ],
184 });
185 assert.deepEqual(
186 handoff.history?.messages.map((message) => message.text),
187 ["Write a plan", replyText],
188 );
189 assert.equal(handoff.history?.omittedItems, 0);
190 }),
191 );
192});
193β
194it.effect("caps the side chat context block without summarizing discarded parent history", () =>
195 Effect.gen(function* () {
196 const parentThreadId = ThreadId.make("thread:side-chat-parent");
197 let summarizedItems = 0;
198 const parentItems = Array.from({ length: 60 }, (_, index) => ({
199 ...importedItem({
200 role: index % 2 === 0 ? "user" : "assistant",
201 id: `parent-${index}`,
202 text: `item-${index} ${"x".repeat(228)}π${"x".repeat(70)}`,
203 ordinal: index,
204 }),
205 get text() {
206 summarizedItems++;
207 return `item-${index} ${"x".repeat(228)}π${"x".repeat(70)}`;
208 },
209 }));
210 const service = yield* ContextHandoffService.ContextHandoffServiceV2;
211 const handoff = yield* service.prepareSideChatContext({
212 parentThreadId,
213 threadId: ThreadId.make("thread:side-chat"),
214 targetRunId: RunId.make("run:side-chat"),
215 transferId: ContextTransferId.make("transfer:side-chat"),
216 toProviderThreadId: ProviderThreadId.make("provider-thread:side-chat"),
217 fromProviderInstanceId: ProviderInstanceId.make("codex"),
218 toProviderInstanceId: ProviderInstanceId.make("codex"),
219 coveredRunOrdinals: { from: 1, to: 1 },
220 parentItems,
221 createdAt: DateTime.makeUnsafe(0),
222 });
223 const context = handoff.summaryText;
224 assert.isBelow(summarizedItems, parentItems.length);
225β
226 assert.include(context, "- Earlier items truncated.");
227 assert.notInclude(context, "item-0 ");
228 assert.include(context, "- Assistant: item-59 ");
229 assert.isAtMost(context.length, 8_000);
230 assert.isTrue(context.isWellFormed());
231 assert.isTrue(
232 context.endsWith(
233 `Use t3_thread_read on thread ${parentThreadId} to see the main thread's live state.`,
234 ),
235 );
236β
237 const framingOnly = ContextHandoffService.makeSideChatContext({
238 parentThreadId,
239 digest: [],
240 });
241 assert.isTrue(framingOnly.startsWith("You are in a side chat beside the main thread."));
242 assert.notInclude(framingOnly, "Main thread activity");
243β
244 const multiFilePatch = ContextHandoffService.makeSideChatContext({
245 parentThreadId,
246 digest: [
247 {
248 id: TurnItemId.make("turn-item:patch"),
249 threadId: parentThreadId,
250 runId: null,
251 nodeId: null,
252 providerThreadId: null,
253 providerTurnId: null,
254 nativeItemRef: null,
255 parentItemId: null,
256 ordinal: 60,
257 status: "completed",
258 title: null,
259 startedAt: null,
260 completedAt: null,
261 updatedAt: DateTime.makeUnsafe(0),
262 type: "file_change",
263 fileName: "src/a.ts",
264 changes: [
265 { operation: "update", path: "src/a.ts" },
266 { operation: "add", path: "src/b.ts" },
267 { operation: "update", path: "src/new.ts", oldPath: "src/old.ts" },
268 ],
269 },
270 ],
271 });
272 assert.include(multiFilePatch, "- File change: src/a.ts, src/b.ts, src/new.ts");
273 }).pipe(Effect.provide(layerTest)),
274);
275β
276it("covers the run range of a very long delta", () => {
277 const runs = [
278 { id: RunId.make("run:long-delta-early"), ordinal: 2 },
279 { id: RunId.make("run:long-delta-late"), ordinal: 5 },
280 ];
281 const items = Array.from({ length: 150_000 }, (_, index) => ({
282 runId: runs[index % 2]!.id,
283 }));
284β
285 assert.deepEqual(
286 ContextHandoffService.visibleDeltaRunOrdinals({ runs }, [...items, { runId: null }]),
287 { from: 2, to: 5 },
288 );
289});
290β
291it.effect("inherited history stops at a missing fork ancestor", () =>
292 Effect.gen(function* () {
293 const now = DateTime.makeUnsafe("2026-01-01T00:00:00.000Z");
294 const threadId = ThreadId.make("thread:fork-of-missing");
295 const thread: OrchestrationV2AppThread = {
296 createdBy: "user",
297 creationSource: "web",
298 id: threadId,
299 projectId: ProjectId.make("project:fork-of-missing"),
300 title: "Fork of a missing thread",
301 providerInstanceId: ProviderInstanceId.make("codex"),
302 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
303 runtimeMode: "full-access",
304 interactionMode: "default",
305 branch: null,
306 worktreePath: null,
307 activeProviderThreadId: null,
308 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
309 forkedFrom: {
310 type: "run",
311 threadId: ThreadId.make("thread:missing-ancestor"),
312 runId: RunId.make("run:missing-ancestor"),
313 },
314 createdAt: now,
315 updatedAt: now,
316 archivedAt: null,
317 settledOverride: null,
318 settledAt: null,
319 lastVisitedAt: null,
320 snoozedUntil: null,
321 snoozedAt: null,
322 deletedAt: null,
323 };
324 const items = yield* ContextHandoffService.readInheritedHandoffItems(
325 {
326 getForkSourceRunIds: () => Effect.succeed([]),
327 getThreadRecords: (missing) =>
328 Effect.fail(new ProjectionStoreThreadNotFoundError({ threadId: missing })),
329 },
330 thread,
331 );
332 assert.deepEqual(items, []);
333 }),
334);
335β
336const clearNow = DateTime.makeUnsafe("2026-01-01T00:00:00.000Z");
337const clearAncestorId = ThreadId.make("thread:ancestor-before-clear");
338const clearSourceId = ThreadId.make("thread:source-with-clear");
339const clearAncestorRunId = RunId.make("run:ancestor-1");
340β
341function clearRun(id: RunId, threadId: ThreadId, ordinal: number, freshContext?: boolean) {
342 return {
343 id,
344 threadId,
345 ordinal,
346 providerInstanceId: ProviderInstanceId.make("codex"),
347 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
348 providerThreadId: ProviderThreadId.make(`pt:${id}`),
349 userMessageId: MessageId.make(`msg:${id}`),
350 rootNodeId: null as never,
351 activeAttemptId: null,
352 status: "completed" as const,
353 queuePosition: null,
354 requestedAt: clearNow,
355 startedAt: clearNow,
356 completedAt: clearNow,
357 checkpointId: null,
358 contextHandoffId: null,
359 ...(freshContext ? { freshContext: true } : {}),
360 };
361}
362β
363function clearUserItem(
364 id: string,
365 threadId: ThreadId,
366 runId: RunId,
367 text: string,
368 ordinal: number,
369 scheduledTaskId?: string,
370) {
371 return {
372 ...importedItem({ role: "user", id, text, ordinal }),
373 threadId,
374 runId,
375 ...(scheduledTaskId === undefined ? {} : { scheduledTaskId }),
376 } as OrchestrationV2TurnItem;
377}
378β
379function clearThread(
380 id: ThreadId,
381 forkedFrom: OrchestrationV2AppThread["forkedFrom"],
382): OrchestrationV2AppThread {
383 return {
384 createdBy: "user",
385 creationSource: "web",
386 id,
387 projectId: ProjectId.make("project:clear-fork"),
388 title: id,
389 providerInstanceId: ProviderInstanceId.make("codex"),
390 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
391 runtimeMode: "full-access",
392 interactionMode: "default",
393 branch: null,
394 worktreePath: null,
395 activeProviderThreadId: null,
396 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: clearAncestorId },
397 forkedFrom,
398 createdAt: clearNow,
399 updatedAt: clearNow,
400 archivedAt: null,
401 settledOverride: null,
402 settledAt: null,
403 lastVisitedAt: null,
404 snoozedUntil: null,
405 snoozedAt: null,
406 deletedAt: null,
407 };
408}
409β
410/** Portable fork history of a source forked from an ancestor, through its last run. */
411const readClearFork = Effect.fn(function* (
412 sourceRuns: ReadonlyArray<ReturnType<typeof clearRun>>,
413 sourceItems: ReadonlyArray<OrchestrationV2TurnItem>,
414) {
415 const sourceThread = clearThread(clearSourceId, {
416 type: "run",
417 threadId: clearAncestorId,
418 runId: clearAncestorRunId,
419 });
420 const fork = clearThread(ThreadId.make("thread:clear-fork"), {
421 type: "run",
422 threadId: clearSourceId,
423 runId: sourceRuns.at(-1)!.id,
424 });
425 const store = {
426 getForkSourceRunIds: (threadId: ThreadId) =>
427 Effect.succeed(
428 threadId === clearSourceId ? [clearAncestorRunId] : sourceRuns.map((run) => run.id),
429 ),
430 getThreadRecords: (threadId: ThreadId) =>
431 Effect.succeed(
432 (threadId === clearAncestorId
433 ? {
434 thread: clearThread(clearAncestorId, null),
435 runs: [clearRun(clearAncestorRunId, clearAncestorId, 1)],
436 attempts: [],
437 turnItems: [
438 clearUserItem("anc", clearAncestorId, clearAncestorRunId, "ancestor history", 1),
439 ],
440 }
441 : {
442 thread: sourceThread,
443 runs: sourceRuns,
444 attempts: [],
445 turnItems: sourceItems,
446 }) as never,
447 ),
448 };
449 const items = yield* ContextHandoffService.readForkHistoryItems(
450 store as never,
451 { thread: sourceThread, runs: sourceRuns, attempts: [] } as never,
452 sourceRuns.at(-1)!,
453 fork,
454 );
455 return items.map((item) => (item.type === "user_message" ? item.text : ""));
456});
457β
458it.effect("portable fork history stops at /clear (freshContext) and drops ancestor history", () =>
459 Effect.gen(function* () {
460 const before = RunId.make("run:source-1");
461 const clear = RunId.make("run:source-2-clear");
462 const texts = yield* readClearFork(
463 [clearRun(before, clearSourceId, 1), clearRun(clear, clearSourceId, 2, true)],
464 [
465 clearUserItem("old", clearSourceId, before, "before clear", 1),
466 clearUserItem("new", clearSourceId, clear, "after clear", 2),
467 ],
468 );
469 assert.deepEqual(texts, ["after clear"]);
470 }),
471);
472β
473it.effect("portable fork history keeps history past a restarted scheduled fresh run", () =>
474 Effect.gen(function* () {
475 const before = RunId.make("run:source-1");
476 const scheduled = RunId.make("run:source-2-scheduled");
477 const after = RunId.make("run:source-3");
478 // A steering restart points userMessageId at the steer, which carries no scheduledTaskId.
479 const scheduledRun = {
480 ...clearRun(scheduled, clearSourceId, 2, true),
481 userMessageId: MessageId.make("message:steer"),
482 };
483 const texts = yield* readClearFork(
484 [clearRun(before, clearSourceId, 1), scheduledRun, clearRun(after, clearSourceId, 3)],
485 [
486 clearUserItem("old", clearSourceId, before, "before schedule", 1),
487 clearUserItem("sched", clearSourceId, scheduled, "scheduled prompt", 2, "task-1"),
488 clearUserItem("steer", clearSourceId, scheduled, "steer", 3),
489 clearUserItem("new", clearSourceId, after, "after schedule", 4),
490 ],
491 );
492 assert.deepEqual(texts, [
493 "ancestor history",
494 "before schedule",
495 "scheduled prompt",
496 "steer",
497 "after schedule",
498 ]);
499 }),
500);