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

ContextHandoffBudget.test.ts

552 lines18.6 KB

1import type { ProviderAdapterV2HistoricalContext } from "./ProviderAdapter.ts";
2import { assert, describe, it } from "@effect/vitest";
3import {
4 ContextHandoffId,
5 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
6 ProviderDriverKind,
7 ProviderInstanceId,
8 ProviderThreadId,
9 RunId,
10 ThreadId,
11 TurnItemId,
12 OrchestrationV2ContextHandoff,
13 type OrchestrationV2HistoricalMessage,
14 type OrchestrationV2ProviderThread,
15} from "@t3tools/contracts";
16import * as DateTime from "effect/DateTime";
17import * as Effect from "effect/Effect";
18import * as Schema from "effect/Schema";
19import {
20 handoffBudget,
21 historyCost,
22 historyResponseItems,
23 selectHistory,
24 historicalMessage,
25} from "./ContextHandoffBudget.ts";
26import { projectContextHandoffForWire } from "./WireProjection.ts";
27import { deliverContextHandoffs } from "./ContextHandoffDelivery.ts";
28​
29const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
30const decodeHandoff = Schema.decodeUnknownSync(OrchestrationV2ContextHandoff);
31​
32const now = DateTime.makeUnsafe("2026-09-17T00:00:00Z");
33const threadId = ThreadId.make("thread:handoff");
34const providerThread: OrchestrationV2ProviderThread = {
35 id: ProviderThreadId.make("provider-thread:target"),
36 driver: ProviderDriverKind.make("codex"),
37 providerInstanceId: ProviderInstanceId.make("codex"),
38 providerSessionId: null,
39 appThreadId: threadId,
40 ownerNodeId: null,
41 nativeThreadRef: {
42 driver: ProviderDriverKind.make("codex"),
43 strength: "strong",
44 nativeId: "native:target",
45 },
46 nativeConversationHeadRef: null,
47 status: "idle",
48 firstRunOrdinal: null,
49 lastRunOrdinal: null,
50 handoffIds: [],
51 forkedFrom: null,
52 createdAt: now,
53 updatedAt: now,
54};
55const message = (
56 id: string,
57 role: "user" | "assistant",
58 text: string,
59): OrchestrationV2HistoricalMessage => ({
60 itemId: TurnItemId.make(id),
61 role,
62 text,
63 threadId,
64 runId: RunId.make("run:source"),
65 providerThreadId: ProviderThreadId.make("provider-thread:source"),
66 status: "interrupted",
67 kind: role === "user" ? "user_message" : "assistant_message",
68});
69const messages = [
70 message("item:one", "user", "Preserve every line.\n\n And this indentation.\n"),
71 message("item:two", "assistant", "Partial work: 日本語 🧪 مرحبا\n" + "x".repeat(600)),
72];
73const handoff: OrchestrationV2ContextHandoff = {
74 id: ContextHandoffId.make("handoff:one"),
75 threadId,
76 targetRunId: RunId.make("run:target"),
77 fromProviderThreadIds: [],
78 toProviderThreadId: providerThread.id,
79 coveredRunOrdinals: { from: 1, to: 2 },
80 strategy: "full_thread_summary",
81 status: "ready",
82 summaryMessageId: null,
83 summaryText: "",
84 history: {
85 messages,
86 coverage: "Historical context; retrieve thread:handoff with t3_thread_read.",
87 omittedItems: 0,
88 },
89 createdByProviderInstanceId: null,
90 createdAt: now,
91 updatedAt: now,
92};
93​
94describe("handoff budget", () => {
95 it("keeps old preview handoffs readable and delivery history off the wire", () => {
96 const projected = projectContextHandoffForWire({
97 ...handoff,
98 summaryText: "private transcript and command output",
99 delivery: {
100 nativeThreadId: "native:target",
101 status: "injected",
102 itemIds: [messages[0]!.itemId],
103 },
104 });
105 assert.equal(projected.summaryText, "");
106 assert.isUndefined(projected.history);
107 assert.isUndefined(projected.delivery);
108 assert.equal(decodeHandoff(projected).id, handoff.id);
109 assert.deepEqual(handoff.history?.messages, messages);
110 });
111 it("carries command outcomes as attributed activity and excludes reasoning", () => {
112 const base = {
113 id: TurnItemId.make("item:command"),
114 threadId,
115 runId: RunId.make("run:source"),
116 nodeId: null,
117 providerThreadId: providerThread.id,
118 providerTurnId: null,
119 nativeItemRef: null,
120 parentItemId: null,
121 ordinal: 1,
122 status: "failed" as const,
123 title: null,
124 startedAt: now,
125 completedAt: now,
126 updatedAt: now,
127 };
128 const command = historicalMessage({
129 ...base,
130 type: "command_execution",
131 input: "vp test",
132 output: "Failure near the end: " + "界".repeat(300),
133 exitCode: 1,
134 });
135 assert.equal(command?.role, "assistant");
136 assert.equal(command?.kind, "command_execution");
137 assert.include(command!.text, "Exit code: 1");
138 assert.include(command!.text, "界".repeat(300));
139 assert.isNull(
140 historicalMessage({
141 ...base,
142 type: "reasoning",
143 text: "private reasoning",
144 streaming: false,
145 }),
146 );
147 assert.equal(historyResponseItems([command!], "Activity")[1]?.type, "message");
148 });
149​
150 it("retains short conversations verbatim in role and order", () => {
151 const selected = selectHistory({ messages, coverage: "History", budget: 16_000 });
152 assert.deepEqual(selected.messages, messages);
153 const items = historyResponseItems(selected.messages, selected.context);
154 assert.deepEqual(
155 items.map((item) => item.role),
156 ["user", "user", "assistant"],
157 );
158 assert.include(items[1]!.content[0]!.text, messages[0]!.text);
159 assert.include(items[2]!.content[0]!.text, messages[1]!.text);
160 assert.equal(selected.omittedItems, 0);
161 });
162​
163 it("omits oversized multilingual items whole, preserves original constraints and recent work", () => {
164 const candidates = [
165 messages[0]!,
166 message("huge", "assistant", "界🧪".repeat(20_000)),
167 message("old", "assistant", "a".repeat(4_000)),
168 messages[1]!,
169 ];
170 const selected = selectHistory({
171 messages: candidates,
172 coverage: "thread:handoff runs 1-4",
173 budget: 3_000,
174 });
175 assert.deepEqual(selected.messages, messages);
176 assert.equal(selected.omittedItems, 2);
177 assert.isAtMost(historyCost(selected.messages, selected.context), 3_000);
178 });
179​
180 it("counts JSON escaping and UTF-8 bytes across many messages", () => {
181 const candidates = Array.from({ length: 500 }, (_, i) =>
182 message(`item:${i}`, i % 2 ? "assistant" : "user", '\u0000\\"🧪界'.repeat(15)),
183 );
184 for (const budget of [1_024, 4_000, 16_000]) {
185 const selected = selectHistory({
186 messages: candidates,
187 coverage: "Retrieve omitted history",
188 budget,
189 });
190 assert.isAtMost(historyCost(selected.messages, selected.context), budget);
191 assert.isAbove(selected.omittedItems, 0);
192 }
193 });
194​
195 it("fits the final envelope at intermediate selected/omitted digit boundaries", () => {
196 const candidates = Array.from({ length: 20 }, (_, index) =>
197 message(`boundary:${index}`, "user", "Short request"),
198 );
199 for (let budget = 4_000; budget <= 9_000; budget++) {
200 const selected = selectHistory({
201 messages: candidates,
202 coverage: "Recover history",
203 omittedItems: 90,
204 budget,
205 });
206 assert.isAtMost(historyCost(selected.messages, selected.context), budget);
207 }
208 });
209​
210 it("subtracts native usage, input, attachments, instructions and space for work", () => {
211 const base = {
212 tokenCap: 16_000,
213 userText: "Continue",
214 attachments: [],
215 providerThread,
216 nativeContextEstimate: 0,
217 modelContextWindow: 32_000,
218 };
219 assert.isBelow(handoffBudget(base), 16_000);
220 assert.isBelow(handoffBudget({ ...base, nativeContextEstimate: 8_000 }), handoffBudget(base));
221 assert.equal(handoffBudget({ ...base, userText: "界".repeat(30_000) }), 0);
222 assert.equal(
223 handoffBudget({
224 ...base,
225 providerThread: {
226 ...providerThread,
227 contextUsage: { usedTokens: 23_000, maxTokens: 24_000 },
228 },
229 }),
230 0,
231 );
232 for (const sizeBytes of [100_000, 10 * 1024 * 1024]) {
233 const attachments = [
234 {
235 type: "image",
236 id: "attachment",
237 name: "image.png",
238 mimeType: "image/png",
239 sizeBytes,
240 },
241 ];
242 const withImage = handoffBudget({ ...base, attachments });
243 assert.isAbove(withImage, 4_000);
244 assert.isBelow(withImage, handoffBudget(base));
245 assert.equal(handoffBudget({ ...base, attachments: [...attachments, ...attachments] }), 0);
246 assert.equal(
247 handoffBudget({
248 ...base,
249 tokenCap: 64_000,
250 modelContextWindow: 1_000_000,
251 // The history byte cap is independent of both current text and image payloads.
252 userText: "x".repeat(70_000),
253 attachments,
254 providerThread: {
255 ...providerThread,
256 contextUsage: { usedTokens: 0, maxTokens: 1_000_000 },
257 },
258 }),
259 64_000,
260 );
261 }
262 assert.equal(handoffBudget({ ...base, tokenCap: 2_000 }), 2_000);
263 });
264 it("budgets all supported image counts with unknown capacity, honoring smaller known windows", () => {
265 for (let count = 1; count <= PROVIDER_SEND_TURN_MAX_ATTACHMENTS; count++) {
266 const input = {
267 tokenCap: 16_000,
268 userText: "Compare these screenshots",
269 providerThread,
270 nativeContextEstimate: 0,
271 attachments: Array.from({ length: count }, (_, index) => ({
272 type: "image",
273 id: `image-${index}`,
274 name: "image.png",
275 mimeType: "image/png",
276 sizeBytes: 10 * 1024 * 1024,
277 })),
278 };
279 const budget = handoffBudget(input);
280 assert.equal(budget, 16_000);
281 const selected = selectHistory({ messages, coverage: "Recover omitted history", budget });
282 assert.isAtMost(historyCost(selected.messages, selected.context), budget);
283 assert.equal(handoffBudget({ ...input, modelContextWindow: 20_000 }), 0);
284 assert.equal(
285 handoffBudget({
286 ...input,
287 providerThread: { ...providerThread, contextUsage: { usedTokens: 0, maxTokens: 20_000 } },
288 }),
289 0,
290 );
291 assert.equal(
292 handoffBudget({
293 ...input,
294 modelContextWindow: 1_000_000,
295 providerThread: {
296 ...providerThread,
297 contextUsage: { usedTokens: 0, maxTokens: 1_000_000, autoCompactThreshold: 20_000 },
298 },
299 }),
300 0,
301 );
302 }
303 });
304});
305​
306describe("handoff delivery", () => {
307 for (const native of [true, false]) {
308 it.effect(
309 `records omitted recovery coverage separately from ${native ? "injected" : "inline"} text`,
310 () =>
311 Effect.gen(function* () {
312 const omittedBeforeDelivery = TurnItemId.make("item:omitted-during-preparation");
313 const oversized = message("item:oversized", "user", "x".repeat(20_000));
314 let durable: OrchestrationV2ContextHandoff = {
315 ...handoff,
316 history: {
317 ...handoff.history!,
318 messages: [...messages, oversized],
319 omittedItems: 1,
320 omittedItemIds: [omittedBeforeDelivery],
321 },
322 };
323 const result = yield* deliverContextHandoffs({
324 handoffs: [durable],
325 providerThread,
326 budget: 16_000,
327 alreadyDeliveredItemIds: new Set(),
328 inject: (value) => {
329 assert.include(value.context, "omitted 2 items");
330 assert.notInclude(
331 value.messages.map((item) => item.itemId),
332 oversized.itemId,
333 );
334 return Effect.succeed(native);
335 },
336 persist: (value) =>
337 Effect.sync(() => {
338 durable = value;
339 }),
340 });
341 assert.equal(durable.delivery?.status, native ? "injected" : "pending");
342 yield* result.delivered;
343 assert.equal(durable.delivery?.status, native ? "injected" : "inline");
344 assert.deepEqual(
345 durable.delivery?.itemIds,
346 messages.map((item) => item.itemId),
347 );
348 assert.deepEqual(durable.delivery?.omittedItemIds, [
349 omittedBeforeDelivery,
350 oversized.itemId,
351 ]);
352 assert.deepEqual(decodeHandoff(durable).delivery, durable.delivery);
353 }),
354 );
355 }
356 it.effect("persists successful injection before turn start and skips it on retry", () =>
357 Effect.gen(function* () {
358 let durable = handoff;
359 const history: unknown[] = [];
360 const statuses: string[] = [];
361 const input = {
362 providerThread,
363 budget: 16_000,
364 alreadyDeliveredItemIds: new Set<string>(),
365 inject: (value: ProviderAdapterV2HistoricalContext) =>
366 Effect.sync(() => {
367 history.push(...historyResponseItems(value.messages, value.context));
368 return true;
369 }),
370 persist: (value: OrchestrationV2ContextHandoff) =>
371 Effect.sync(() => {
372 durable = value;
373 statuses.push(value.delivery!.status);
374 }),
375 };
376 const first = yield* deliverContextHandoffs({ ...input, handoffs: [durable] });
377 assert.equal(first.context, "");
378 assert.deepEqual(statuses, ["pending", "injected"]);
379 assert.lengthOf(history, 3);
380 // No turn has started. Reconstruct from the durable projection as a retry would.
381 const second = yield* deliverContextHandoffs({ ...input, handoffs: [durable] });
382 assert.equal(second.context, "");
383 assert.lengthOf(history, 3);
384 }),
385 );
386​
387 it.effect(
388 "uses the same selection on explicit native fallback, marking only accepted input",
389 () =>
390 Effect.gen(function* () {
391 let durable = handoff;
392 const result = yield* deliverContextHandoffs({
393 handoffs: [handoff],
394 providerThread,
395 budget: 16_000,
396 alreadyDeliveredItemIds: new Set(),
397 inject: () => Effect.succeed(false),
398 persist: (value) =>
399 Effect.sync(() => {
400 durable = value;
401 }),
402 });
403 assert.include(result.context, messages[0]!.text);
404 assert.include(result.context, messages[1]!.text);
405 assert.equal(durable.delivery?.status, "pending");
406 yield* result.delivered;
407 assert.equal(durable.delivery?.status, "inline");
408 }),
409 );
410​
411 it.effect(
412 "defers unsupported compaction history until a normal turn without marking delivery uncertain",
413 () =>
414 Effect.gen(function* () {
415 let durable = handoff;
416 const persist = (value: OrchestrationV2ContextHandoff) =>
417 Effect.sync(() => {
418 durable = value;
419 });
420 const compact = yield* deliverContextHandoffs({
421 handoffs: [durable],
422 providerThread,
423 budget: 16_000,
424 alreadyDeliveredItemIds: new Set(),
425 deferInline: true,
426 inject: () => Effect.succeed(false),
427 persist,
428 });
429 yield* compact.delivered;
430 assert.equal(compact.context, "");
431 assert.isUndefined((() => durable.delivery)());
432 const next = yield* deliverContextHandoffs({
433 handoffs: [durable],
434 providerThread,
435 budget: 16_000,
436 alreadyDeliveredItemIds: new Set(),
437 inject: () => Effect.succeed(false),
438 persist,
439 });
440 assert.include(next.context, messages[0]!.text);
441 yield* next.delivered;
442 assert.equal(durable.delivery?.status, "inline");
443 }),
444 );
445​
446 it.effect("bounds accumulated recovery markers while keeping omitted history discoverable", () =>
447 Effect.gen(function* () {
448 const many = Array.from({ length: 100 }, (_, index) => ({
449 ...handoff,
450 id: ContextHandoffId.make(`handoff:retry:${index}`),
451 }));
452 let captured: ProviderAdapterV2HistoricalContext | undefined;
453 const result = yield* deliverContextHandoffs({
454 handoffs: many,
455 providerThread,
456 budget: 2_500,
457 alreadyDeliveredItemIds: new Set(),
458 inject: (history) =>
459 Effect.sync(() => {
460 captured = history;
461 return true;
462 }),
463 persist: () => Effect.void,
464 });
465 assert.equal(result.context, "");
466 assert.isDefined(captured);
467 assert.include(captured.context, "detailed coverage references omitted");
468 assert.include(captured.context, "t3_thread_read");
469 assert.include(captured.context, threadId);
470 assert.isAtMost(historyCost(captured.messages, captured.context), 2_500);
471 assert.isAbove(captured.messages.length, 0);
472 }),
473 );
474​
475 it.effect("does not redeliver after ambiguous injection failure", () =>
476 Effect.gen(function* () {
477 let durable = handoff;
478 let calls = 0;
479 const input = {
480 providerThread,
481 budget: 16_000,
482 alreadyDeliveredItemIds: new Set<string>(),
483 inject: () =>
484 Effect.sync(() => {
485 calls++;
486 }).pipe(Effect.andThen(Effect.fail("connection lost"))),
487 persist: (value: OrchestrationV2ContextHandoff) =>
488 Effect.sync(() => {
489 durable = value;
490 }),
491 };
492 yield* deliverContextHandoffs({ ...input, handoffs: [durable] }).pipe(Effect.result);
493 assert.equal(durable.delivery?.status, "pending");
494 const retry = yield* deliverContextHandoffs({ ...input, handoffs: [durable] }).pipe(
495 Effect.result,
496 );
497 assert.equal(retry._tag, "Failure");
498 assert.equal(calls, 1);
499 }),
500 );
501​
502 it.effect("budgets multiple handoffs together and skips previously delivered items", () =>
503 Effect.gen(function* () {
504 const extra = {
505 ...handoff,
506 id: ContextHandoffId.make("handoff:two"),
507 history: {
508 ...handoff.history!,
509 messages: [...messages, message("item:three", "assistant", "Latest result")],
510 },
511 };
512 let delivered: ReadonlyArray<unknown> = [];
513 yield* deliverContextHandoffs({
514 handoffs: [handoff, extra],
515 providerThread,
516 budget: 2_500,
517 alreadyDeliveredItemIds: new Set(["item:one"]),
518 inject: (value) =>
519 Effect.sync(() => {
520 delivered = historyResponseItems(value.messages, value.context);
521 return true;
522 }),
523 persist: () => Effect.void,
524 });
525 const serialized = yield* encodeJson(delivered);
526 assert.isAtMost(Buffer.byteLength(serialized), 2_500);
527 assert.notInclude(serialized, "Preserve every line");
528 assert.equal(serialized.split("Partial work").length - 1, 1);
529 assert.include(serialized, "Latest result");
530 }),
531 );
532​
533 it.effect("fails before delivery when even the coverage marker cannot fit", () =>
534 Effect.gen(function* () {
535 let calls = 0;
536 const result = yield* deliverContextHandoffs({
537 handoffs: [handoff],
538 providerThread,
539 budget: 0,
540 alreadyDeliveredItemIds: new Set(),
541 inject: () =>
542 Effect.sync(() => {
543 calls++;
544 return true;
545 }),
546 persist: () => Effect.void,
547 }).pipe(Effect.result);
548 assert.equal(result._tag, "Failure");
549 assert.equal(calls, 0);
550 }),
551 );
552});