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

ContextHandoffBudget.test.ts

689 lines22.2 KB

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