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

ContextHandoffBudget.test.ts

598 lines20.1 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("reserves context for image batches up to the attachment limit, honoring smaller known windows", () => {
265 let previousBudget = 16_000;
266 for (let count = 1; count <= PROVIDER_SEND_TURN_MAX_ATTACHMENTS; count++) {
267 const input = {
268 tokenCap: 16_000,
269 userText: "Compare these screenshots",
270 providerThread,
271 nativeContextEstimate: 0,
272 attachments: Array.from({ length: count }, (_, index) => ({
273 type: "image",
274 id: `image-${index}`,
275 name: "image.png",
276 mimeType: "image/png",
277 sizeBytes: 100_000,
278 })),
279 };
280 const budget = handoffBudget(input);
281 assert.isAtLeast(budget, 0);
282 assert.isAtMost(budget, previousBudget);
283 previousBudget = budget;
284 if (count <= 8) assert.equal(budget, 16_000);
285 if (count === 10) {
286 assert.isAbove(budget, 0);
287 assert.isBelow(budget, 16_000);
288 }
289 if (count === PROVIDER_SEND_TURN_MAX_ATTACHMENTS) assert.equal(budget, 0);
290 if (budget > 0) {
291 const selected = selectHistory({ messages, coverage: "Recover omitted history", budget });
292 assert.isAtMost(historyCost(selected.messages, selected.context), budget);
293 }
294 assert.equal(handoffBudget({ ...input, modelContextWindow: 2_000_000 }), 16_000);
295 assert.equal(handoffBudget({ ...input, modelContextWindow: 20_000 }), 0);
296 assert.equal(
297 handoffBudget({
298 ...input,
299 providerThread: { ...providerThread, contextUsage: { usedTokens: 0, maxTokens: 20_000 } },
300 }),
301 0,
302 );
303 assert.equal(
304 handoffBudget({
305 ...input,
306 modelContextWindow: 1_000_000,
307 providerThread: {
308 ...providerThread,
309 contextUsage: { usedTokens: 0, maxTokens: 1_000_000, autoCompactThreshold: 20_000 },
310 },
311 }),
312 0,
313 );
314 }
315 });
316});
317​
318describe("handoff delivery", () => {
319 for (const native of [true, false]) {
320 it.effect(
321 `records omitted recovery coverage separately from ${native ? "injected" : "inline"} text`,
322 () =>
323 Effect.gen(function* () {
324 const omittedBeforeDelivery = TurnItemId.make("item:omitted-during-preparation");
325 const oversized = message("item:oversized", "user", "x".repeat(20_000));
326 let durable: OrchestrationV2ContextHandoff = {
327 ...handoff,
328 history: {
329 ...handoff.history!,
330 messages: [...messages, oversized],
331 omittedItems: 1,
332 omittedItemIds: [omittedBeforeDelivery],
333 },
334 };
335 const result = yield* deliverContextHandoffs({
336 handoffs: [durable],
337 providerThread,
338 budget: 16_000,
339 alreadyDeliveredItemIds: new Set(),
340 inject: (value) => {
341 assert.include(value.context, "omitted 2 items");
342 assert.notInclude(
343 value.messages.map((item) => item.itemId),
344 oversized.itemId,
345 );
346 return Effect.succeed(native);
347 },
348 persist: (value) =>
349 Effect.sync(() => {
350 durable = value;
351 }),
352 });
353 assert.equal(durable.delivery?.status, native ? "injected" : "pending");
354 yield* result.delivered;
355 assert.equal(durable.delivery?.status, native ? "injected" : "inline");
356 assert.deepEqual(
357 durable.delivery?.itemIds,
358 messages.map((item) => item.itemId),
359 );
360 assert.deepEqual(durable.delivery?.omittedItemIds, [
361 omittedBeforeDelivery,
362 oversized.itemId,
363 ]);
364 assert.deepEqual(decodeHandoff(durable).delivery, durable.delivery);
365 }),
366 );
367 }
368 it.effect("loads the history budget only when a handoff needs delivery", () =>
369 Effect.gen(function* () {
370 let reads = 0;
371 const input = {
372 providerThread,
373 budget: Effect.sync(() => {
374 reads++;
375 return 16_000;
376 }),
377 alreadyDeliveredItemIds: new Set<string>(),
378 persist: () => Effect.void,
379 };
380 yield* deliverContextHandoffs({ ...input, handoffs: [] });
381 yield* deliverContextHandoffs({ ...input, handoffs: [handoff], deferInline: true });
382 yield* deliverContextHandoffs({
383 ...input,
384 handoffs: [
385 {
386 ...handoff,
387 delivery: {
388 nativeThreadId: providerThread.nativeThreadRef!.nativeId!,
389 status: "injected",
390 itemIds: [],
391 },
392 },
393 ],
394 });
395 assert.equal(reads, 0);
396 const result = yield* deliverContextHandoffs({ ...input, handoffs: [handoff] });
397 assert.equal(reads, 1);
398 assert.include(result.context, messages[0]!.text);
399 }),
400 );
401​
402 it.effect("persists successful injection before turn start and skips it on retry", () =>
403 Effect.gen(function* () {
404 let durable = handoff;
405 const history: unknown[] = [];
406 const statuses: string[] = [];
407 const input = {
408 providerThread,
409 budget: 16_000,
410 alreadyDeliveredItemIds: new Set<string>(),
411 inject: (value: ProviderAdapterV2HistoricalContext) =>
412 Effect.sync(() => {
413 history.push(...historyResponseItems(value.messages, value.context));
414 return true;
415 }),
416 persist: (value: OrchestrationV2ContextHandoff) =>
417 Effect.sync(() => {
418 durable = value;
419 statuses.push(value.delivery!.status);
420 }),
421 };
422 const first = yield* deliverContextHandoffs({ ...input, handoffs: [durable] });
423 assert.equal(first.context, "");
424 assert.deepEqual(statuses, ["pending", "injected"]);
425 assert.lengthOf(history, 3);
426 // No turn has started. Reconstruct from the durable projection as a retry would.
427 const second = yield* deliverContextHandoffs({ ...input, handoffs: [durable] });
428 assert.equal(second.context, "");
429 assert.lengthOf(history, 3);
430 }),
431 );
432​
433 it.effect(
434 "uses the same selection on explicit native fallback, marking only accepted input",
435 () =>
436 Effect.gen(function* () {
437 let durable = handoff;
438 const result = yield* deliverContextHandoffs({
439 handoffs: [handoff],
440 providerThread,
441 budget: 16_000,
442 alreadyDeliveredItemIds: new Set(),
443 inject: () => Effect.succeed(false),
444 persist: (value) =>
445 Effect.sync(() => {
446 durable = value;
447 }),
448 });
449 assert.include(result.context, messages[0]!.text);
450 assert.include(result.context, messages[1]!.text);
451 assert.equal(durable.delivery?.status, "pending");
452 yield* result.delivered;
453 assert.equal(durable.delivery?.status, "inline");
454 }),
455 );
456​
457 it.effect(
458 "defers unsupported compaction history until a normal turn without marking delivery uncertain",
459 () =>
460 Effect.gen(function* () {
461 let durable = handoff;
462 const persist = (value: OrchestrationV2ContextHandoff) =>
463 Effect.sync(() => {
464 durable = value;
465 });
466 const compact = yield* deliverContextHandoffs({
467 handoffs: [durable],
468 providerThread,
469 budget: 16_000,
470 alreadyDeliveredItemIds: new Set(),
471 deferInline: true,
472 inject: () => Effect.succeed(false),
473 persist,
474 });
475 yield* compact.delivered;
476 assert.equal(compact.context, "");
477 assert.isUndefined((() => durable.delivery)());
478 const next = yield* deliverContextHandoffs({
479 handoffs: [durable],
480 providerThread,
481 budget: 16_000,
482 alreadyDeliveredItemIds: new Set(),
483 inject: () => Effect.succeed(false),
484 persist,
485 });
486 assert.include(next.context, messages[0]!.text);
487 yield* next.delivered;
488 assert.equal(durable.delivery?.status, "inline");
489 }),
490 );
491​
492 it.effect("bounds accumulated recovery markers while keeping omitted history discoverable", () =>
493 Effect.gen(function* () {
494 const many = Array.from({ length: 100 }, (_, index) => ({
495 ...handoff,
496 id: ContextHandoffId.make(`handoff:retry:${index}`),
497 }));
498 let captured: ProviderAdapterV2HistoricalContext | undefined;
499 const result = yield* deliverContextHandoffs({
500 handoffs: many,
501 providerThread,
502 budget: 2_500,
503 alreadyDeliveredItemIds: new Set(),
504 inject: (history) =>
505 Effect.sync(() => {
506 captured = history;
507 return true;
508 }),
509 persist: () => Effect.void,
510 });
511 assert.equal(result.context, "");
512 assert.isDefined(captured);
513 assert.include(captured.context, "detailed coverage references omitted");
514 assert.include(captured.context, "t3_thread_read");
515 assert.include(captured.context, threadId);
516 assert.isAtMost(historyCost(captured.messages, captured.context), 2_500);
517 assert.isAbove(captured.messages.length, 0);
518 }),
519 );
520​
521 it.effect("does not redeliver after ambiguous injection failure", () =>
522 Effect.gen(function* () {
523 let durable = handoff;
524 let calls = 0;
525 const input = {
526 providerThread,
527 budget: 16_000,
528 alreadyDeliveredItemIds: new Set<string>(),
529 inject: () =>
530 Effect.sync(() => {
531 calls++;
532 }).pipe(Effect.andThen(Effect.fail("connection lost"))),
533 persist: (value: OrchestrationV2ContextHandoff) =>
534 Effect.sync(() => {
535 durable = value;
536 }),
537 };
538 yield* deliverContextHandoffs({ ...input, handoffs: [durable] }).pipe(Effect.result);
539 assert.equal(durable.delivery?.status, "pending");
540 const retry = yield* deliverContextHandoffs({ ...input, handoffs: [durable] }).pipe(
541 Effect.result,
542 );
543 assert.equal(retry._tag, "Failure");
544 assert.equal(calls, 1);
545 }),
546 );
547​
548 it.effect("budgets multiple handoffs together and skips previously delivered items", () =>
549 Effect.gen(function* () {
550 const extra = {
551 ...handoff,
552 id: ContextHandoffId.make("handoff:two"),
553 history: {
554 ...handoff.history!,
555 messages: [...messages, message("item:three", "assistant", "Latest result")],
556 },
557 };
558 let delivered: ReadonlyArray<unknown> = [];
559 yield* deliverContextHandoffs({
560 handoffs: [handoff, extra],
561 providerThread,
562 budget: 2_500,
563 alreadyDeliveredItemIds: new Set(["item:one"]),
564 inject: (value) =>
565 Effect.sync(() => {
566 delivered = historyResponseItems(value.messages, value.context);
567 return true;
568 }),
569 persist: () => Effect.void,
570 });
571 const serialized = yield* encodeJson(delivered);
572 assert.isAtMost(Buffer.byteLength(serialized), 2_500);
573 assert.notInclude(serialized, "Preserve every line");
574 assert.equal(serialized.split("Partial work").length - 1, 1);
575 assert.include(serialized, "Latest result");
576 }),
577 );
578​
579 it.effect("fails before delivery when even the coverage marker cannot fit", () =>
580 Effect.gen(function* () {
581 let calls = 0;
582 const result = yield* deliverContextHandoffs({
583 handoffs: [handoff],
584 providerThread,
585 budget: 0,
586 alreadyDeliveredItemIds: new Set(),
587 inject: () =>
588 Effect.sync(() => {
589 calls++;
590 return true;
591 }),
592 persist: () => Effect.void,
593 }).pipe(Effect.result);
594 assert.equal(result._tag, "Failure");
595 assert.equal(calls, 0);
596 }),
597 );
598});