Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions apps/desktop/src/legacyLocalStorageMerge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,15 @@ describe("mergeLegacyLocalStorage", () => {
assert.equal(storage.getItem("t3code:composer-drafts:v1"), current);
});

it("caps the merged stash at the store's entry limit, dropping the oldest V1 entries", () => {
it("keeps every merged stash entry, V2 entries first", () => {
const v2Ids = Array.from({ length: 15 }, (_, index) => `v2-${index}`);
const v1Ids = Array.from({ length: 10 }, (_, index) => `v1-${index}`);
const storage = memoryStorage({ "t3code:prompt-stash:v2": stash(...v2Ids) });
mergeLegacyLocalStorage(storage, { "t3code:prompt-stash:v2": stash(...v1Ids) });
const ids = JSON.parse(storage.getItem("t3code:prompt-stash:v2")!).state.entries.map(
(entry: { id: string }) => entry.id,
);
assert.deepStrictEqual(ids, [...v2Ids, ...v1Ids.slice(0, 5)]);
assert.deepStrictEqual(ids, [...v2Ids, ...v1Ids]);
});

it("keeps importing other keys after one write fails, and reports the failure", () => {
Expand Down
4 changes: 1 addition & 3 deletions apps/desktop/src/legacyLocalStorageMerge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ const NOT_IMPORTED_KEYS = new Set([
"t3.backgroundActivity.clientId",
"t3code:snap-shot-setup-resume:v1",
]);
/** Matches MAX_STASH_ENTRIES in apps/web/src/promptStashStore.ts. */
const MAX_STASH_ENTRIES = 20;
const DRAFT_RECORD_FIELDS = [
"draftsByThreadKey",
"draftThreadsByThreadKey",
Expand Down Expand Up @@ -42,7 +40,7 @@ function mergePromptStash(current: JsonObject, legacy: JsonObject): JsonObject |
const state = isObject(current.state) ? current.state : {};
return {
...current,
state: { ...state, entries: [...currentEntries, ...added].slice(0, MAX_STASH_ENTRIES) },
state: { ...state, entries: [...currentEntries, ...added] },
};
}

Expand Down
33 changes: 32 additions & 1 deletion apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,14 @@ import * as Schema from "effect/Schema";
import {
contextUsageForHandoff,
handoffBudget,
MAX_HANDOFF_TOKEN_CAP,
historyCost,
historyResponseItems,
selectHistory,
historicalMessage,
} from "@t3tools/provider-core/server/handoffBudget";
import { projectContextHandoffForWire } from "./WireProjection.ts";
import { deliverContextHandoffs } from "./ContextHandoffDelivery.ts";
import { deliverContextHandoffs, textBesideHistory } from "./ContextHandoffDelivery.ts";

const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
const decodeHandoff = Schema.decodeUnknownSync(OrchestrationV2ContextHandoff);
Expand Down Expand Up @@ -260,6 +261,34 @@ describe("handoff budget", () => {
);
}
assert.equal(handoffBudget({ ...base, tokenCap: 2_000 }), 2_000);

// A side chat's parent digest is sent beside history, so it shares the room.
const sideChat = { ...base, tokenCap: undefined, modelContextWindow: 128_000 };
const withoutSideChat = handoffBudget(sideChat);
const withSideChat = handoffBudget({
...sideChat,
userText: textBesideHistory({
userText: base.userText,
restartNote: "",
sideChatContext: "s".repeat(64_000),
}),
});
assert.isBelow(withSideChat, withoutSideChat);
assert.isAtMost(withSideChat, 128_000 - 32_000 - 64_000);

const uncapped = { ...base, tokenCap: undefined };
assert.equal(
handoffBudget({ ...uncapped, modelContextWindow: 1_000_000 }),
500_000,
"half of a known window",
);
assert.equal(
handoffBudget({ ...uncapped, modelContextWindow: 4_000_000 }),
MAX_HANDOFF_TOKEN_CAP,
);
const unknownWindow = handoffBudget({ ...uncapped, modelContextWindow: undefined });
assert.isAbove(unknownWindow, 64_000, "the assumed 128k window bounds an unknown model");
assert.isBelow(unknownWindow, 128_000 - 32_000);
});

it("keeps measured occupancy across a model change", () => {
Expand Down Expand Up @@ -454,6 +483,7 @@ describe("handoff delivery", () => {
messages.map((item) => item.itemId),
);
assert.deepEqual(durable.delivery?.omittedItemIds, [omittedBeforeDelivery, oversized.itemId]);
assert.equal(result.omittedItems, 2);
assert.deepEqual(decodeHandoff(durable).delivery, durable.delivery);
}),
);
Expand All @@ -480,6 +510,7 @@ describe("handoff delivery", () => {
};
const first = yield* deliverContextHandoffs({ ...input, handoffs: [durable] });
assert.equal(first.context, "");
assert.equal(first.omittedItems, 0);
assert.deepEqual(statuses, ["pending", "injected"]);
assert.lengthOf(history, 3);
const second = yield* deliverContextHandoffs({ ...input, handoffs: [durable] });
Expand Down
29 changes: 25 additions & 4 deletions apps/server/src/orchestration-v2/ContextHandoffDelivery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,20 @@ import {
export const withInlineContext = (context: string, userText: string): string =>
context === "" ? userText : `${context}\n\nUser message:\n${userText}`;

/** Everything a turn sends beside handoff history; the history budget must leave room for it. */
export const textBesideHistory = (input: {
readonly userText: string;
readonly sideChatContext: string;
readonly restartNote: string;
}): string =>
[input.sideChatContext, input.restartNote, input.userText]
.filter((part) => part !== "")
.join("\n\n");

/** The user-visible counterpart of the coverage note that tells the agent how to recover history. */
export const omittedHistoryNotice = (omittedItems: number): string =>
`${omittedItems} earlier ${omittedItems === 1 ? "item" : "items"} of this thread did not fit in the model's context and ${omittedItems === 1 ? "was" : "were"} not passed along. The agent can read ${omittedItems === 1 ? "it" : "them"} from the thread when needed.`;

/** Persist around injection; ambiguous delivery requires a fresh native thread. Call unsent if refused before prompt consumption. */
export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextHandoffs")(
function* <InjectError = never, PersistError = never, BudgetError = never>(input: {
Expand All @@ -37,7 +51,7 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH
handoff.delivery.status === "pending",
);
if (pending.length === 0 || (input.deferInline && input.inject === undefined))
return { context: "", delivered: Effect.void, unsent: Effect.void };
return { context: "", delivered: Effect.void, unsent: Effect.void, omittedItems: 0 };
const budget = typeof input.budget === "number" ? input.budget : yield* input.budget;
let coverage = pending
.map(
Expand Down Expand Up @@ -75,7 +89,8 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH
budget,
});
if (historyCost(selected.messages, selected.context) > budget) {
if (input.deferInline) return { context: "", delivered: Effect.void, unsent: Effect.void };
if (input.deferInline)
return { context: "", delivered: Effect.void, unsent: Effect.void, omittedItems: 0 };
return yield* new ContextHandoffBudgetError();
}
const omittedItemIds = new Set(selected.omittedItemIds);
Expand Down Expand Up @@ -126,20 +141,26 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH
});
if (injected) {
yield* persist("injected");
return { context: "", delivered: Effect.void, unsent: Effect.void };
return {
context: "",
delivered: Effect.void,
unsent: Effect.void,
omittedItems: selected.omittedItems,
};
}
} else {
yield* persist("pending");
}
if (input.deferInline) {
// Compaction cannot carry inline transcripts; retain for the next turn if native injection is unsupported.
yield* Effect.forEach(pending, input.persist, { discard: true });
return { context: "", delivered: Effect.void, unsent: Effect.void };
return { context: "", delivered: Effect.void, unsent: Effect.void, omittedItems: 0 };
}
return {
context: renderHistory(selected.messages, selected.context),
delivered: persist("inline"),
unsent: Effect.forEach(pending, input.persist, { discard: true }),
omittedItems: selected.omittedItems,
};
},
);
Expand Down
80 changes: 75 additions & 5 deletions apps/server/src/orchestration-v2/ContextHandoffService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,9 @@ it.layer(layerTest)("ContextHandoffService legacy import", (it) => {
createdAt: DateTime.makeUnsafe("2026-01-02T00:00:00.000Z"),
});

// Delivery narrows history to the target window; preparation keeps the whole message.
assert.include(
handoff.history?.omittedItemIds ?? [],
handoff.history?.messages.map((message) => message.itemId) ?? [],
TurnItemId.make("turn-item:long-single-token"),
);
assert.isAtMost(handoff.summaryText.length, 32_000);
Expand All @@ -169,12 +170,12 @@ it.effect("caps the side chat context block without summarizing discarded parent
...importedItem({
role: index % 2 === 0 ? "user" : "assistant",
id: `parent-${index}`,
text: `item-${index} ${"x".repeat(228)}😀${"x".repeat(70)}`,
text: `item-${index} ${"x".repeat(1_228)}😀\n${"x".repeat(70)}`,
ordinal: index,
}),
get text() {
summarizedItems++;
return `item-${index} ${"x".repeat(228)}😀${"x".repeat(70)}`;
return `item-${index} ${"x".repeat(1_228)}😀\n${"x".repeat(70)}`;
},
}));
const service = yield* ContextHandoffService.ContextHandoffServiceV2;
Expand All @@ -195,8 +196,8 @@ it.effect("caps the side chat context block without summarizing discarded parent

assert.include(context, "- Earlier items truncated.");
assert.notInclude(context, "item-0 ");
assert.include(context, "- Assistant: item-59 ");
assert.isAtMost(context.length, 8_000);
assert.include(context, `- Assistant: item-59 ${"x".repeat(1_228)}😀\n${"x".repeat(70)}`);
assert.isAtMost(context.length, 64_000);
assert.isTrue(context.isWellFormed());
assert.isTrue(
context.endsWith(
Expand Down Expand Up @@ -243,6 +244,36 @@ it.effect("caps the side chat context block without summarizing discarded parent
}).pipe(Effect.provide(layerTest)),
);

it("keeps whole merge-back messages and drops the oldest past the budget", () => {
const deltaItems = Array.from({ length: 6 }, (_, index) =>
importedItem({
role: index % 2 === 0 ? "user" : "assistant",
id: `fork-${index}`,
text: `fork-${index}\n${"y".repeat(1_000)}`,
ordinal: index,
}),
);
const summarize = (budget: number) =>
ContextHandoffService.makeForkDeltaSummary({
sourceThreadId: ThreadId.make("thread:fork"),
targetThreadId: ThreadId.make("thread:main"),
coveredRunOrdinals: { from: 1, to: 2 },
deltaItems,
budget,
});

const full = summarize(1_000_000);
assert.include(full, `- User: fork-0\n${"y".repeat(1_000)}`);
assert.notInclude(full, "omitted");

const cut = summarize(3_000);
assert.isAtMost(Buffer.byteLength(cut), 3_000);
assert.include(cut, "- 4 earlier items omitted to fit the context budget");
assert.notInclude(cut, "fork-3");
assert.include(cut, `- User: fork-4\n${"y".repeat(1_000)}`);
assert.include(cut, `- Assistant: fork-5\n${"y".repeat(1_000)}`);
});

it("covers the run range of a very long delta", () => {
const runs = [
{ id: RunId.make("run:long-delta-early"), ordinal: 2 },
Expand Down Expand Up @@ -301,3 +332,42 @@ it.effect("inherited history stops at a missing fork ancestor", () =>
assert.deepEqual(items, []);
}),
);

it.effect("stores provider handoff history once, bounded by a known target window", () =>
Effect.gen(function* () {
const service = yield* ContextHandoffService.ContextHandoffServiceV2;
const items = Array.from({ length: 40 }, (_, index) =>
importedItem({
role: index % 2 === 0 ? "user" : "assistant",
id: `switch-${index}`,
text: `switch-${index} ${"z".repeat(4_000)}`,
ordinal: index,
}),
);
const prepare = (modelContextWindow: number | undefined) =>
service.prepareProviderHandoff({
threadId: ThreadId.make("thread:switch"),
targetRunId: RunId.make("run:switch"),
transferId: null,
fromProviderThreadIds: [ProviderThreadId.make("provider-thread:from")],
toProviderThreadId: ProviderThreadId.make("provider-thread:to"),
fromProviderInstanceId: ProviderInstanceId.make("codex"),
toProviderInstanceId: ProviderInstanceId.make("claudeAgent"),
coveredRunOrdinals: { from: 1, to: 2 },
strategy: "full_thread_summary",
items,
createdAt: DateTime.makeUnsafe(0),
modelContextWindow,
});

const unknown = yield* prepare(undefined);
assert.lengthOf(unknown.history?.messages ?? [], items.length);
assert.notInclude(unknown.summaryText, "z".repeat(100));
assert.isBelow(unknown.summaryText.length, 2_000);

const small = yield* prepare(40_000);
assert.isBelow(small.history?.messages.length ?? 0, items.length);
assert.isAbove(small.history?.omittedItems ?? 0, 0);
assert.include(small.history?.messages.at(-1)?.text ?? "", "switch-39");
}).pipe(Effect.provide(layerTest)),
);
Loading
Loading