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

ContextHandoffBudget.test.ts

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