Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 MessageId,
4 ProjectId,
5 ProviderInstanceId,
6 ProviderThreadId,
7 RunId,
8 ThreadId,
9 TurnItemId,
10 type OrchestrationV2AppThread,
11 type OrchestrationV2TurnItem,
12} from "@t3tools/contracts";
13import * as DateTime from "effect/DateTime";
14import * as Effect from "effect/Effect";
15import * as Layer from "effect/Layer";
16
17import * as ContextHandoffService from "./ContextHandoffService.ts";
18import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
19import { ProjectionStoreThreadNotFoundError } from "./ProjectionStore.ts";
20
21const layerTest = ContextHandoffService.layer.pipe(Layer.provide(IdAllocator.layer));
22
23function importedItem(
24 input:
25 | {
26 readonly role: "user";
27 readonly id: string;
28 readonly text: string;
29 readonly ordinal: number;
30 }
31 | {
32 readonly role: "assistant";
33 readonly id: string;
34 readonly text: string;
35 readonly ordinal: number;
36 },
37): OrchestrationV2TurnItem {
38 const now = DateTime.makeUnsafe("2026-01-01T00:00:00.000Z");
39 const base = {
40 id: TurnItemId.make(`turn-item:${input.id}`),
41 threadId: ThreadId.make("thread:legacy-context"),
42 runId: null,
43 nodeId: null,
44 providerThreadId: null,
45 providerTurnId: null,
46 nativeItemRef: null,
47 parentItemId: null,
48 ordinal: input.ordinal,
49 status: "completed" as const,
50 title: null,
51 startedAt: now,
52 completedAt: now,
53 updatedAt: now,
54 messageId: MessageId.make(`message:${input.id}`),
55 text: input.text,
56 };
57 return input.role === "user"
58 ? {
59 ...base,
60 createdBy: "user",
61 creationSource: "server",
62 type: "user_message",
63 inputIntent: "turn_start",
64 attachments: [],
65 }
66 : {
67 ...base,
68 type: "assistant_message",
69 streaming: false,
70 };
71}
72
73it.layer(layerTest)("ContextHandoffService legacy import", (it) => {
74 it.effect("prepares imported history for the first native v2 turn", () =>
75 Effect.gen(function* () {
76 const service = yield* ContextHandoffService.ContextHandoffServiceV2;
77 const handoff = yield* service.prepareLegacyImport({
78 threadId: ThreadId.make("thread:legacy-context"),
79 targetRunId: RunId.make("run:first-v2"),
80 toProviderThreadId: ProviderThreadId.make("provider-thread:first-v2"),
81 toProviderInstanceId: ProviderInstanceId.make("codex"),
82 items: [
83 importedItem({ role: "user", id: "one", text: "What did we decide?", ordinal: 1 }),
84 importedItem({
85 role: "assistant",
86 id: "two",
87 text: "We decided to keep the migration lightweight.",
88 ordinal: 2,
89 }),
90 ],
91 createdAt: DateTime.makeUnsafe("2026-01-02T00:00:00.000Z"),
92 });
93
94 assert.equal(handoff.strategy, "manual_context");
95 assert.deepStrictEqual(handoff.fromProviderThreadIds, []);
96 assert.include(handoff.summaryText, "What did we decide?");
97 assert.include(handoff.summaryText, "keep the migration lightweight");
98 }),
99 );
100
101 it.effect("preserves role attribution when truncating imported history", () =>
102 Effect.gen(function* () {
103 const service = yield* ContextHandoffService.ContextHandoffServiceV2;
104 const handoff = yield* service.prepareLegacyImport({
105 threadId: ThreadId.make("thread:legacy-context"),
106 targetRunId: RunId.make("run:first-v2"),
107 toProviderThreadId: ProviderThreadId.make("provider-thread:first-v2"),
108 toProviderInstanceId: ProviderInstanceId.make("codex"),
109 items: [
110 importedItem({
111 role: "user",
112 id: "long",
113 text: `${"x".repeat(35_000)} retained final words`,
114 ordinal: 1,
115 }),
116 ],
117 createdAt: DateTime.makeUnsafe("2026-01-02T00:00:00.000Z"),
118 });
119
120 assert.isAtMost(handoff.summaryText.length, 32_000);
121 assert.include(handoff.summaryText, "User:\n... retained final words");
122 assert.notMatch(handoff.summaryText, /\n+x+ retained final words/);
123 }),
124 );
125
126 it.effect("retains the newest oversized import even when it has no whitespace", () =>
127 Effect.gen(function* () {
128 const service = yield* ContextHandoffService.ContextHandoffServiceV2;
129 const handoff = yield* service.prepareLegacyImport({
130 threadId: ThreadId.make("thread:legacy-context"),
131 targetRunId: RunId.make("run:first-v2"),
132 toProviderThreadId: ProviderThreadId.make("provider-thread:first-v2"),
133 toProviderInstanceId: ProviderInstanceId.make("codex"),
134 items: [
135 importedItem({
136 role: "assistant",
137 id: "older",
138 text: "older message",
139 ordinal: 1,
140 }),
141 importedItem({
142 role: "user",
143 id: "long-single-token",
144 text: `${"🧪".repeat(20_000)}LATEST_SINGLE_TOKEN`,
145 ordinal: 2,
146 }),
147 ],
148 createdAt: DateTime.makeUnsafe("2026-01-02T00:00:00.000Z"),
149 });
150
151 assert.include(
152 handoff.history?.omittedItemIds ?? [],
153 TurnItemId.make("turn-item:long-single-token"),
154 );
155 assert.isAtMost(handoff.summaryText.length, 32_000);
156 assert.include(handoff.summaryText, "User:\n... ");
157 assert.include(handoff.summaryText, "LATEST_SINGLE_TOKEN");
158 assert.notInclude(handoff.summaryText, "\ufffd");
159 }),
160 );
161});
162
163it("caps the side chat context block, keeping the newest parent items", () => {
164 const parentThreadId = ThreadId.make("thread:side-chat-parent");
165 const digest = Array.from({ length: 60 }, (_, index) =>
166 ContextHandoffService.summarizeDeltaItem(
167 importedItem({
168 role: index % 2 === 0 ? "user" : "assistant",
169 id: `parent-${index}`,
170 text: `item-${index} ${"x".repeat(300)}`,
171 ordinal: index,
172 }),
173 )!,
174 );
175 const context = ContextHandoffService.makeSideChatContext({ parentThreadId, digest });
176
177 assert.include(context, "- Earlier items truncated.");
178 assert.notInclude(context, "item-0 ");
179 assert.include(context, "- Assistant: item-59 ");
180 assert.isAtMost(context.length, 8_000);
181 assert.isTrue(
182 context.endsWith(
183 `Use t3_thread_read on thread ${parentThreadId} to see the main thread's live state.`,
184 ),
185 );
186
187 const framingOnly = ContextHandoffService.makeSideChatContext({ parentThreadId, digest: [] });
188 assert.isTrue(framingOnly.startsWith("You are in a side chat beside the main thread."));
189 assert.notInclude(framingOnly, "Main thread activity");
190});
191
192it("covers the run range of a very long delta", () => {
193 const runs = [
194 { id: RunId.make("run:long-delta-early"), ordinal: 2 },
195 { id: RunId.make("run:long-delta-late"), ordinal: 5 },
196 ];
197 const items = Array.from({ length: 150_000 }, (_, index) => ({
198 runId: runs[index % 2]!.id,
199 }));
200
201 assert.deepEqual(
202 ContextHandoffService.visibleDeltaRunOrdinals({ runs }, [...items, { runId: null }]),
203 { from: 2, to: 5 },
204 );
205});
206
207it.effect("inherited history stops at a missing fork ancestor", () =>
208 Effect.gen(function* () {
209 const now = DateTime.makeUnsafe("2026-01-01T00:00:00.000Z");
210 const threadId = ThreadId.make("thread:fork-of-missing");
211 const thread: OrchestrationV2AppThread = {
212 createdBy: "user",
213 creationSource: "web",
214 id: threadId,
215 projectId: ProjectId.make("project:fork-of-missing"),
216 title: "Fork of a missing thread",
217 providerInstanceId: ProviderInstanceId.make("codex"),
218 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
219 runtimeMode: "full-access",
220 interactionMode: "default",
221 branch: null,
222 worktreePath: null,
223 activeProviderThreadId: null,
224 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
225 forkedFrom: {
226 type: "run",
227 threadId: ThreadId.make("thread:missing-ancestor"),
228 runId: RunId.make("run:missing-ancestor"),
229 },
230 createdAt: now,
231 updatedAt: now,
232 archivedAt: null,
233 settledOverride: null,
234 settledAt: null,
235 lastVisitedAt: null,
236 snoozedUntil: null,
237 snoozedAt: null,
238 deletedAt: null,
239 };
240 const items = yield* ContextHandoffService.readInheritedHandoffItems(
241 {
242 getThreadRecords: (missing) =>
243 Effect.fail(new ProjectionStoreThreadNotFoundError({ threadId: missing })),
244 },
245 thread,
246 );
247 assert.deepEqual(items, []);
248 }),
249);