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

ContextHandoffBudget.test.ts

643 lines20.6 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("omits oversized multilingual items whole, preserves original constraints and recent work", () => {
152 const candidates = [
153 messages[0]!,
154 message("huge", "assistant", "界🧪".repeat(20_000)),
155 message("old", "assistant", "a".repeat(4_000)),
156 messages[1]!,
157 ];
158 const selected = selectHistory({
159 messages: candidates,
160 coverage: "thread:handoff runs 1-4",
161 budget: 3_000,
162 });
163 assert.deepEqual(selected.messages, messages);
164 assert.equal(selected.omittedItems, 2);
165 assert.isAtMost(historyCost(selected.messages, selected.context), 3_000);
166 });
167​
168 it("counts JSON escaping and UTF-8 bytes across many messages", () => {
169 const candidates = Array.from({ length: 500 }, (_, i) =>
170 message(`item:${i}`, i % 2 ? "assistant" : "user", '\u0000\\"🧪界'.repeat(15)),
171 );
172 for (const budget of [1_024, 4_000, 16_000]) {
173 const selected = selectHistory({
174 messages: candidates,
175 coverage: "Retrieve omitted history",
176 budget,
177 });
178 assert.isAtMost(historyCost(selected.messages, selected.context), budget);
179 assert.isAbove(selected.omittedItems, 0);
180 }
181 });
182​
183 it("fits the final envelope at intermediate selected/omitted digit boundaries", () => {
184 const candidates = Array.from({ length: 20 }, (_, index) =>
185 message(`boundary:${index}`, "user", "Short request"),
186 );
187 for (let budget = 4_000; budget <= 9_000; budget++) {
188 const selected = selectHistory({
189 messages: candidates,
190 coverage: "Recover history",
191 omittedItems: 90,
192 budget,
193 });
194 assert.isAtMost(historyCost(selected.messages, selected.context), budget);
195 }
196 });
197​
198 it("subtracts native usage, input, attachments, instructions and space for work", () => {
199 const base = {
200 tokenCap: 16_000,
201 userText: "Continue",
202 attachments: [],
203 providerThread,
204 nativeContextEstimate: 0,
205 modelContextWindow: 32_000,
206 };
207 assert.isBelow(handoffBudget(base), 16_000);
208 assert.isBelow(handoffBudget({ ...base, nativeContextEstimate: 8_000 }), handoffBudget(base));
209 assert.equal(handoffBudget({ ...base, userText: "界".repeat(30_000) }), 0);
210 assert.equal(
211 handoffBudget({
212 ...base,
213 providerThread: {
214 ...providerThread,
215 contextUsage: { usedTokens: 23_000, maxTokens: 24_000 },
216 },
217 }),
218 0,
219 );
220 for (const sizeBytes of [100_000, 10 * 1024 * 1024]) {
221 const attachments = [
222 {
223 type: "image",
224 id: "attachment",
225 name: "image.png",
226 mimeType: "image/png",
227 sizeBytes,
228 },
229 ];
230 const withImage = handoffBudget({ ...base, attachments });
231 assert.isAbove(withImage, 4_000);
232 assert.isBelow(withImage, handoffBudget(base));
233 assert.equal(handoffBudget({ ...base, attachments: [...attachments, ...attachments] }), 0);
234 assert.equal(
235 handoffBudget({
236 ...base,
237 tokenCap: 64_000,
238 modelContextWindow: 1_000_000,
239 userText: "x".repeat(70_000),
240 attachments,
241 providerThread: {
242 ...providerThread,
243 contextUsage: { usedTokens: 0, maxTokens: 1_000_000 },
244 },
245 }),
246 64_000,
247 );
248 }
249 assert.equal(handoffBudget({ ...base, tokenCap: 2_000 }), 2_000);
250 });
251​
252 it("keeps measured occupancy across a model change", () => {
253 const previous = {
254 usedTokens: 37_321,
255 maxTokens: 258_400,
256 autoCompactThreshold: 32_000,
257 };
258 assert.isNull(
259 contextUsageForHandoff({
260 sameNativeThread: false,
261 sameSelection: false,
262 reuseTelemetry: false,
263 previousUsage: previous,
264 }),
265 );
266 assert.equal(
267 contextUsageForHandoff({
268 sameNativeThread: true,
269 sameSelection: true,
270 reuseTelemetry: true,
271 previousUsage: previous,
272 }),
273 previous,
274 );
275 assert.deepEqual(
276 contextUsageForHandoff({
277 sameNativeThread: true,
278 sameSelection: false,
279 reuseTelemetry: true,
280 previousUsage: previous,
281 }),
282 { usedTokens: 37_321, maxTokens: 258_400 },
283 );
284 assert.deepEqual(
285 contextUsageForHandoff({
286 sameNativeThread: true,
287 sameSelection: false,
288 reuseTelemetry: false,
289 previousUsage: previous,
290 }),
291 { usedTokens: 37_321, maxTokens: 258_400 },
292 );
293 assert.deepEqual(
294 contextUsageForHandoff({
295 sameNativeThread: true,
296 sameSelection: false,
297 reuseTelemetry: false,
298 previousUsage: { usedTokens: 30_000, maxTokens: 32_000, autoCompactThreshold: 31_000 },
299 knownModelWindow: 1_000_000,
300 }),
301 { usedTokens: 30_000, maxTokens: 1_000_000 },
302 );
303​
304 const preserved = contextUsageForHandoff({
305 sameNativeThread: true,
306 sameSelection: false,
307 reuseTelemetry: false,
308 previousUsage: previous,
309 });
310 assert.equal(
311 handoffBudget({
312 tokenCap: 16_000,
313 userText: "Continue work",
314 attachments: [
315 {
316 type: "image",
317 id: "screenshot-a",
318 name: "a.png",
319 mimeType: "image/png",
320 sizeBytes: 100_000,
321 },
322 {
323 type: "image",
324 id: "screenshot-b",
325 name: "b.png",
326 mimeType: "image/png",
327 sizeBytes: 100_000,
328 },
329 ],
330 providerThread: { ...providerThread, contextUsage: preserved },
331 nativeContextEstimate: 0,
332 modelContextWindow: preserved?.maxTokens,
333 }),
334 16_000,
335 );
336 assert.equal(
337 handoffBudget({
338 tokenCap: 16_000,
339 userText: "Continue work",
340 attachments: [],
341 providerThread,
342 nativeContextEstimate: 120_000,
343 }),
344 0,
345 );
346 });
347 it("reserves context for image batches up to the attachment limit, honoring smaller known windows", () => {
348 let previousBudget = 16_000;
349 for (let count = 1; count <= PROVIDER_SEND_TURN_MAX_ATTACHMENTS; count++) {
350 const input = {
351 tokenCap: 16_000,
352 userText: "Compare these screenshots",
353 providerThread,
354 nativeContextEstimate: 0,
355 attachments: Array.from({ length: count }, (_, index) => ({
356 type: "image",
357 id: `image-${index}`,
358 name: "image.png",
359 mimeType: "image/png",
360 sizeBytes: 100_000,
361 })),
362 };
363 const budget = handoffBudget(input);
364 assert.isAtLeast(budget, 0);
365 assert.isAtMost(budget, previousBudget);
366 previousBudget = budget;
367 if (count <= 8) assert.equal(budget, 16_000);
368 if (count === 10) {
369 assert.isAbove(budget, 0);
370 assert.isBelow(budget, 16_000);
371 }
372 if (count === PROVIDER_SEND_TURN_MAX_ATTACHMENTS) assert.equal(budget, 0);
373 if (budget > 0) {
374 const selected = selectHistory({ messages, coverage: "Recover omitted history", budget });
375 assert.isAtMost(historyCost(selected.messages, selected.context), budget);
376 }
377 assert.equal(handoffBudget({ ...input, modelContextWindow: 2_000_000 }), 16_000);
378 assert.equal(handoffBudget({ ...input, modelContextWindow: 20_000 }), 0);
379 assert.equal(
380 handoffBudget({
381 ...input,
382 providerThread: { ...providerThread, contextUsage: { usedTokens: 0, maxTokens: 20_000 } },
383 }),
384 0,
385 );
386 assert.equal(
387 handoffBudget({
388 ...input,
389 modelContextWindow: 1_000_000,
390 providerThread: {
391 ...providerThread,
392 contextUsage: { usedTokens: 0, maxTokens: 1_000_000, autoCompactThreshold: 20_000 },
393 },
394 }),
395 0,
396 );
397 }
398 });
399});
400​
401describe("handoff delivery", () => {
402 it.effect.each([
403 { native: true, label: "injected" },
404 { native: false, label: "inline" },
405 ])("records omitted recovery coverage separately from $label text", ({ native }) =>
406 Effect.gen(function* () {
407 const omittedBeforeDelivery = TurnItemId.make("item:omitted-during-preparation");
408 const oversized = message("item:oversized", "user", "x".repeat(20_000));
409 let durable: OrchestrationV2ContextHandoff = {
410 ...handoff,
411 history: {
412 ...handoff.history!,
413 messages: [...messages, oversized],
414 omittedItems: 1,
415 omittedItemIds: [omittedBeforeDelivery],
416 },
417 };
418 const result = yield* deliverContextHandoffs({
419 handoffs: [durable],
420 providerThread,
421 budget: 16_000,
422 alreadyDeliveredItemIds: new Set(),
423 inject: (value) => {
424 assert.include(value.context, "omitted 2 items");
425 assert.notInclude(
426 value.messages.map((item) => item.itemId),
427 oversized.itemId,
428 );
429 return Effect.succeed(native);
430 },
431 persist: (value) =>
432 Effect.sync(() => {
433 durable = value;
434 }),
435 });
436 assert.equal(durable.delivery?.status, native ? "injected" : "pending");
437 yield* result.delivered;
438 assert.equal(durable.delivery?.status, native ? "injected" : "inline");
439 assert.deepEqual(
440 durable.delivery?.itemIds,
441 messages.map((item) => item.itemId),
442 );
443 assert.deepEqual(durable.delivery?.omittedItemIds, [omittedBeforeDelivery, oversized.itemId]);
444 assert.deepEqual(decodeHandoff(durable).delivery, durable.delivery);
445 }),
446 );
447​
448 it.effect("persists successful injection before turn start and skips it on retry", () =>
449 Effect.gen(function* () {
450 let durable = handoff;
451 const history: unknown[] = [];
452 const statuses: string[] = [];
453 const input = {
454 providerThread,
455 budget: 16_000,
456 alreadyDeliveredItemIds: new Set<string>(),
457 inject: (value: ProviderAdapter.ProviderAdapterV2HistoricalContext) =>
458 Effect.sync(() => {
459 history.push(...historyResponseItems(value.messages, value.context));
460 return true;
461 }),
462 persist: (value: OrchestrationV2ContextHandoff) =>
463 Effect.sync(() => {
464 durable = value;
465 statuses.push(value.delivery!.status);
466 }),
467 };
468 const first = yield* deliverContextHandoffs({ ...input, handoffs: [durable] });
469 assert.equal(first.context, "");
470 assert.deepEqual(statuses, ["pending", "injected"]);
471 assert.lengthOf(history, 3);
472 const second = yield* deliverContextHandoffs({ ...input, handoffs: [durable] });
473 assert.equal(second.context, "");
474 assert.lengthOf(history, 3);
475 }),
476 );
477​
478 it.effect(
479 "uses the same selection on explicit native fallback, marking only accepted input",
480 () =>
481 Effect.gen(function* () {
482 let durable = handoff;
483 const result = yield* deliverContextHandoffs({
484 handoffs: [handoff],
485 providerThread,
486 budget: 16_000,
487 alreadyDeliveredItemIds: new Set(),
488 inject: () => Effect.succeed(false),
489 persist: (value) =>
490 Effect.sync(() => {
491 durable = value;
492 }),
493 });
494 assert.include(result.context, messages[0]!.text);
495 assert.include(result.context, messages[1]!.text);
496 assert.equal(durable.delivery?.status, "pending");
497 yield* result.delivered;
498 assert.equal(durable.delivery?.status, "inline");
499 }),
500 );
501​
502 it.effect(
503 "defers unsupported compaction history until a normal turn without marking delivery uncertain",
504 () =>
505 Effect.gen(function* () {
506 let durable = handoff;
507 const persist = (value: OrchestrationV2ContextHandoff) =>
508 Effect.sync(() => {
509 durable = value;
510 });
511 const compact = yield* deliverContextHandoffs({
512 handoffs: [durable],
513 providerThread,
514 budget: 16_000,
515 alreadyDeliveredItemIds: new Set(),
516 deferInline: true,
517 inject: () => Effect.succeed(false),
518 persist,
519 });
520 yield* compact.delivered;
521 assert.equal(compact.context, "");
522 assert.isUndefined((() => durable.delivery)());
523 const next = yield* deliverContextHandoffs({
524 handoffs: [durable],
525 providerThread,
526 budget: 16_000,
527 alreadyDeliveredItemIds: new Set(),
528 inject: () => Effect.succeed(false),
529 persist,
530 });
531 assert.include(next.context, messages[0]!.text);
532 yield* next.delivered;
533 assert.equal(durable.delivery?.status, "inline");
534 }),
535 );
536​
537 it.effect("bounds accumulated recovery markers while keeping omitted history discoverable", () =>
538 Effect.gen(function* () {
539 const many = Array.from({ length: 100 }, (_, index) => ({
540 ...handoff,
541 id: ContextHandoffId.make(`handoff:retry:${index}`),
542 }));
543 let captured: ProviderAdapter.ProviderAdapterV2HistoricalContext | undefined;
544 const result = yield* deliverContextHandoffs({
545 handoffs: many,
546 providerThread,
547 budget: 2_500,
548 alreadyDeliveredItemIds: new Set(),
549 inject: (history) =>
550 Effect.sync(() => {
551 captured = history;
552 return true;
553 }),
554 persist: () => Effect.void,
555 });
556 assert.equal(result.context, "");
557 assert.isDefined(captured);
558 assert.include(captured.context, "detailed coverage references omitted");
559 assert.include(captured.context, "t3_thread_read");
560 assert.include(captured.context, threadId);
561 assert.isAtMost(historyCost(captured.messages, captured.context), 2_500);
562 assert.isAbove(captured.messages.length, 0);
563 }),
564 );
565​
566 it.effect("does not redeliver after ambiguous injection failure", () =>
567 Effect.gen(function* () {
568 let durable = handoff;
569 let calls = 0;
570 const input = {
571 providerThread,
572 budget: 16_000,
573 alreadyDeliveredItemIds: new Set<string>(),
574 inject: () =>
575 Effect.sync(() => {
576 calls++;
577 }).pipe(Effect.andThen(Effect.fail("connection lost"))),
578 persist: (value: OrchestrationV2ContextHandoff) =>
579 Effect.sync(() => {
580 durable = value;
581 }),
582 };
583 yield* deliverContextHandoffs({ ...input, handoffs: [durable] }).pipe(Effect.result);
584 assert.equal(durable.delivery?.status, "pending");
585 const retry = yield* deliverContextHandoffs({ ...input, handoffs: [durable] }).pipe(
586 Effect.result,
587 );
588 assert.equal(retry._tag, "Failure");
589 assert.equal(calls, 1);
590 }),
591 );
592​
593 it.effect("budgets multiple handoffs together and skips previously delivered items", () =>
594 Effect.gen(function* () {
595 const extra = {
596 ...handoff,
597 id: ContextHandoffId.make("handoff:two"),
598 history: {
599 ...handoff.history!,
600 messages: [...messages, message("item:three", "assistant", "Latest result")],
601 },
602 };
603 let delivered: ReadonlyArray<unknown> = [];
604 yield* deliverContextHandoffs({
605 handoffs: [handoff, extra],
606 providerThread,
607 budget: 2_500,
608 alreadyDeliveredItemIds: new Set(["item:one"]),
609 inject: (value) =>
610 Effect.sync(() => {
611 delivered = historyResponseItems(value.messages, value.context);
612 return true;
613 }),
614 persist: () => Effect.void,
615 });
616 const serialized = yield* encodeJson(delivered);
617 assert.isAtMost(Buffer.byteLength(serialized), 2_500);
618 assert.notInclude(serialized, "Preserve every line");
619 assert.equal(serialized.split("Partial work").length - 1, 1);
620 assert.include(serialized, "Latest result");
621 }),
622 );
623​
624 it.effect("fails before delivery when even the coverage marker cannot fit", () =>
625 Effect.gen(function* () {
626 let calls = 0;
627 const result = yield* deliverContextHandoffs({
628 handoffs: [handoff],
629 providerThread,
630 budget: 0,
631 alreadyDeliveredItemIds: new Set(),
632 inject: () =>
633 Effect.sync(() => {
634 calls++;
635 return true;
636 }),
637 persist: () => Effect.void,
638 }).pipe(Effect.result);
639 assert.equal(result._tag, "Failure");
640 assert.equal(calls, 0);
641 }),
642 );
643});