diff --git a/apps/desktop/src/legacyLocalStorageMerge.test.ts b/apps/desktop/src/legacyLocalStorageMerge.test.ts index fd10c1d02019c..d3d337b8a38a9 100644 --- a/apps/desktop/src/legacyLocalStorageMerge.test.ts +++ b/apps/desktop/src/legacyLocalStorageMerge.test.ts @@ -74,7 +74,7 @@ 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) }); @@ -82,7 +82,7 @@ describe("mergeLegacyLocalStorage", () => { 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", () => { diff --git a/apps/desktop/src/legacyLocalStorageMerge.ts b/apps/desktop/src/legacyLocalStorageMerge.ts index c63bf7e4668c2..fbb07022750a8 100644 --- a/apps/desktop/src/legacyLocalStorageMerge.ts +++ b/apps/desktop/src/legacyLocalStorageMerge.ts @@ -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", @@ -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] }, }; } diff --git a/apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts b/apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts index 71d9cf3dadaf9..97c08f6ffd4d6 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts @@ -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); @@ -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", () => { @@ -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); }), ); @@ -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] }); diff --git a/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts b/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts index adff6f65d8e75..60a749156b69e 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts @@ -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* (input: { @@ -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( @@ -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); @@ -126,7 +141,12 @@ 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"); @@ -134,12 +154,13 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH 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, }; }, ); diff --git a/apps/server/src/orchestration-v2/ContextHandoffService.test.ts b/apps/server/src/orchestration-v2/ContextHandoffService.test.ts index 78958c2e317d5..488ec986e91ec 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffService.test.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffService.test.ts @@ -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); @@ -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; @@ -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( @@ -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 }, @@ -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)), +); diff --git a/apps/server/src/orchestration-v2/ContextHandoffService.ts b/apps/server/src/orchestration-v2/ContextHandoffService.ts index 10f2701446268..7720ae637ca13 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffService.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffService.ts @@ -16,11 +16,10 @@ import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import { - DEFAULT_HANDOFF_TOKEN_CAP, handoffTokenCapConfig, + preparationTokenCap, handoffCoverage, historicalMessage, - renderHistory, selectHistory, } from "@t3tools/provider-core/server/handoffBudget"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; @@ -53,6 +52,8 @@ export interface ContextHandoffServiceV2Shape { readonly toProviderInstanceId: ProviderInstanceId; readonly items: ReadonlyArray; readonly createdAt: DateTime.Utc; + /** The target model's window when known; preparation keeps no more history than it can use. */ + readonly modelContextWindow?: number | undefined; }) => Effect.Effect; readonly prepareForkDelta: (input: { readonly sourceThreadId: ThreadId; @@ -66,6 +67,8 @@ export interface ContextHandoffServiceV2Shape { readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"]; readonly deltaItems: ReadonlyArray; readonly createdAt: DateTime.Utc; + /** The target model's window when known; preparation keeps no more history than it can use. */ + readonly modelContextWindow?: number | undefined; }) => Effect.Effect; readonly prepareProviderHandoff: (input: { readonly threadId: ThreadId; @@ -83,6 +86,8 @@ export interface ContextHandoffServiceV2Shape { >; readonly items: ReadonlyArray; readonly createdAt: DateTime.Utc; + /** The target model's window when known; preparation keeps no more history than it can use. */ + readonly modelContextWindow?: number | undefined; }) => Effect.Effect; /** Parent activity after the fork point, prepended to a side chat's first provider turn. */ readonly prepareSideChatContext: (input: { @@ -204,12 +209,21 @@ export const readForkHistoryItems = Effect.fn( ]; }); +const DELTA_ITEM_TYPES = new Set([ + "user_message", + "assistant_message", + "command_execution", + "file_change", + "checkpoint", + "handoff", +]); + function summarizeDeltaItem(item: OrchestrationV2TurnItem): string | null { switch (item.type) { case "user_message": - return `- User: ${compactText(item.text)}`; + return `- User: ${item.text.trim()}`; case "assistant_message": - return `- Assistant: ${compactText(item.text)}`; + return `- Assistant: ${item.text.trim()}`; case "command_execution": return `- Command: ${compactText(item.input)}`; case "file_change": @@ -223,28 +237,63 @@ function summarizeDeltaItem(item: OrchestrationV2TurnItem): string | null { } } -function makeForkDeltaSummary(input: { +/** Keeps whole lines, newest first, until `budget` runs out; older lines are dropped, never cut. */ +function newestLinesWithin( + digest: ReadonlyArray, + budget: number, + cost: (line: string) => number, +) { + const kept: Array = []; + let remaining = budget; + let index = digest.length - 1; + for (; index >= 0; index--) { + const item = digest[index]!; + const line = typeof item === "string" ? item : summarizeDeltaItem(item); + if (line === null) continue; + if (cost(line) + 1 > remaining) break; + kept.unshift(line); + remaining -= cost(line) + 1; + } + const omitted = digest + .slice(0, index + 1) + .filter((item) => typeof item === "string" || DELTA_ITEM_TYPES.has(item.type)).length; + return { kept, omitted }; +} + +const utf8Bytes = (line: string) => Buffer.byteLength(line); + +export function makeForkDeltaSummary(input: { readonly sourceThreadId: ThreadId; readonly targetThreadId: ThreadId; readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"]; readonly deltaItems: ReadonlyArray; + readonly budget: number; }): string { - const itemLines = input.deltaItems.flatMap((item) => { - const line = summarizeDeltaItem(item); - return line === null ? [] : [line]; - }); - return [ + const header = [ "Merge-back context from forked conversation.", `Source thread: ${input.sourceThreadId}`, `Target thread: ${input.targetThreadId}`, `Covered fork runs: ${input.coveredRunOrdinals.from}-${input.coveredRunOrdinals.to}`, "", "Fork delta:", - ...(itemLines.length === 0 ? ["- No user-visible delta items."] : itemLines), + ]; + const omittedLine = (count: number) => + `- ${count} earlier ${count === 1 ? "item" : "items"} omitted to fit the context budget; read them with t3_thread_read on thread ${input.sourceThreadId}.`; + const { kept, omitted } = newestLinesWithin( + input.deltaItems, + input.budget - utf8Bytes(header.join("\n")) - utf8Bytes(omittedLine(input.deltaItems.length)), + utf8Bytes, + ); + return [ + ...header, + ...(omitted > 0 ? [omittedLine(omitted)] : []), + ...(kept.length === 0 && omitted === 0 ? ["- No user-visible delta items."] : kept), ].join("\n"); } -const SIDE_CHAT_CONTEXT_MAX_CHARS = 8_000; +/** The full delta travels in history; this summary only labels the handoff. */ +const FORK_DELTA_SUMMARY_BUDGET = 16_000; +const SIDE_CHAT_CONTEXT_MAX_CHARS = 64_000; /** Oldest first; raw parent items are summarized only until the context cap is reached. */ export function makeSideChatContext(input: { @@ -256,25 +305,15 @@ export function makeSideChatContext(input: { const header = "Main thread activity since this side chat's starting point:"; const truncated = "- Earlier items truncated."; const footer = `Use t3_thread_read on thread ${input.parentThreadId} to see the main thread's live state.`; - const kept: Array = []; - let omitted = false; // The cap covers the whole block, so the fixed lines are reserved before any digest line. - let remaining = - SIDE_CHAT_CONTEXT_MAX_CHARS - [framing, "", header, truncated, "", footer].join("\n").length; - for (let index = input.digest.length - 1; index >= 0; index--) { - const item = input.digest[index]!; - const line = typeof item === "string" ? item : summarizeDeltaItem(item); - if (line === null) continue; - if (line.length + 1 > remaining) { - omitted = true; - break; - } - kept.unshift(line); - remaining -= line.length + 1; - } + const { kept, omitted } = newestLinesWithin( + input.digest, + SIDE_CHAT_CONTEXT_MAX_CHARS - [framing, "", header, truncated, "", footer].join("\n").length, + (line) => line.length, + ); return [ framing, - ...(kept.length === 0 ? [] : ["", header, ...(omitted ? [truncated] : []), ...kept]), + ...(kept.length === 0 ? [] : ["", header, ...(omitted > 0 ? [truncated] : []), ...kept]), "", footer, ].join("\n"); @@ -348,8 +387,8 @@ function makeLegacyImportSummary(items: ReadonlyArray): const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffService.layer")( function* () { const idAllocator = yield* IdAllocator.IdAllocatorV2; - const tokenCap = yield* handoffTokenCapConfig.pipe( - Effect.orElseSucceed(() => DEFAULT_HANDOFF_TOKEN_CAP), + const tokenCapOverride = yield* handoffTokenCapConfig.pipe( + Effect.orElseSucceed(() => undefined), ); const prepareLegacyImport = Effect.fn("orchestrationV2.contextHandoff.prepareLegacyImport")( @@ -360,6 +399,7 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi readonly toProviderInstanceId: ProviderInstanceId; readonly items: ReadonlyArray; readonly createdAt: DateTime.Utc; + readonly modelContextWindow?: number | undefined; }) { const handoffId = yield* idAllocator.allocate .contextHandoff({ @@ -386,7 +426,7 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi return message === null ? [] : [message]; }), coverage, - budget: tokenCap, + budget: preparationTokenCap(tokenCapOverride, input.modelContextWindow), }); return { id: handoffId, @@ -426,6 +466,7 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"]; readonly deltaItems: ReadonlyArray; readonly createdAt: DateTime.Utc; + readonly modelContextWindow?: number | undefined; }) { const handoffId = yield* idAllocator.allocate .contextHandoff({ @@ -456,7 +497,7 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi return message === null ? [] : [message]; }), coverage, - budget: tokenCap, + budget: preparationTokenCap(tokenCapOverride, input.modelContextWindow), }); return { id: handoffId, @@ -469,7 +510,7 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi strategy: "fork_delta_summary", status: "ready", summaryMessageId: null, - summaryText: makeForkDeltaSummary(input), + summaryText: makeForkDeltaSummary({ ...input, budget: FORK_DELTA_SUMMARY_BUDGET }), history: { messages: selected.messages, coverage, @@ -501,6 +542,7 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi >; readonly items: ReadonlyArray; readonly createdAt: DateTime.Utc; + readonly modelContextWindow?: number | undefined; }) { const handoffId = yield* idAllocator.allocate .contextHandoff({ @@ -535,7 +577,7 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi ]; }), coverage, - budget: tokenCap, + budget: preparationTokenCap(tokenCapOverride, input.modelContextWindow), }); return { id: handoffId, @@ -548,7 +590,8 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi strategy: input.strategy, status: "ready", summaryMessageId: null, - summaryText: renderHistory(selected.messages, selected.context), + // history carries the messages; a second full copy here would also land in the turn item. + summaryText: selected.context, history: { messages: selected.messages, coverage, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index a9e0b3f29b3aa..115bb3235a841 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -37,7 +37,6 @@ import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts" import * as ContextHandoffService from "./ContextHandoffService.ts"; import { isActiveRun } from "./CommandPolicy.ts"; import { - DEFAULT_HANDOFF_TOKEN_CAP, handoffTokenCapConfig, handoffBudget, attachmentTokenAllowance, @@ -45,7 +44,12 @@ import { historicalMessage, latestNativeContextUsage, } from "@t3tools/provider-core/server/handoffBudget"; -import { deliverContextHandoffs, withInlineContext } from "./ContextHandoffDelivery.ts"; +import { + deliverContextHandoffs, + omittedHistoryNotice, + textBesideHistory, + withInlineContext, +} from "./ContextHandoffDelivery.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProjectionStore from "./ProjectionStore.ts"; @@ -816,6 +820,10 @@ export const layer: Layer.Layer< } const session = sessionResult.success; if (!(yield* isCurrentAttemptInStatus("starting"))) return; + const targetModelWindow = session.getModelContextWindow?.( + run.modelSelection, + resolvedRuntimePolicy.cwd, + ); const loadFromProvider = Effect.fn("ProviderTurnStartService.loadFromProvider")(function* ( load: Effect.Effect, ) { @@ -868,9 +876,7 @@ export const layer: Layer.Layer< restartCancelledWork.length === 0 ? "" : restartCancelledBackgroundWorkNote(restartCancelledWork); - const tokenCap = yield* handoffTokenCapConfig.pipe( - Effect.orElseSucceed(() => DEFAULT_HANDOFF_TOKEN_CAP), - ); + const tokenCap = yield* handoffTokenCapConfig.pipe(Effect.orElseSucceed(() => undefined)); const handoffContextForThread = (loadedProviderThread: OrchestrationV2ProviderThread) => { const measuredContext = latestNativeContextUsage(projection, providerThread); const previousSelection = @@ -1013,7 +1019,12 @@ export const layer: Layer.Layer< return handoffBudget({ tokenCap, modelContextWindow, - userText: restartNote === "" ? userText : `${restartNote}\n\n${userText}`, + userText: textBesideHistory({ + userText, + restartNote, + // Counted even on turns that defer it; over-reserving only shrinks history. + sideChatContext: sideChatHandoff?.summaryText ?? "", + }), attachments: message.attachments, providerThread: budgetProviderThread, nativeContextEstimate: @@ -1044,6 +1055,7 @@ export const layer: Layer.Layer< ? [] : [ yield* contextHandoffService.prepareProviderHandoff({ + modelContextWindow: targetModelWindow, threadId: projection.thread.id, targetRunId: run.id, transferId: null, @@ -1073,6 +1085,7 @@ export const layer: Layer.Layer< }); const createdAt = yield* DateTime.now; const handoff = yield* contextHandoffService.prepareProviderHandoff({ + modelContextWindow: targetModelWindow, threadId: projection.thread.id, targetRunId: run.id, transferId, @@ -1175,6 +1188,7 @@ export const layer: Layer.Layer< ); const createdAt = yield* DateTime.now; const handoff = yield* contextHandoffService.prepareProviderHandoff({ + modelContextWindow: targetModelWindow, threadId: projection.thread.id, targetRunId: run.id, transferId: nativeForkTransfer.id, @@ -1572,6 +1586,44 @@ export const layer: Layer.Layer< ], }); }); + const recordOmittedHistoryNotice = Effect.fn("ProviderTurnStartService.recordOmittedHistory")( + function* (omittedItems: number) { + const now = yield* DateTime.now; + yield* eventSink.write({ + events: [ + { + id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }), + type: "turn-item.updated", + threadId: projection.thread.id, + runId: run.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { + id: idAllocator.derive.runSignalTurnItem({ + runId: run.id, + signal: "context-handoff-omitted", + }), + threadId: projection.thread.id, + runId: run.id, + nodeId: runningRootNode.id, + providerThreadId: runningProviderThread.id, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: run.ordinal * 100 - 1, + status: "completed", + title: null, + startedAt: now, + completedAt: now, + updatedAt: now, + type: "system_notice", + message: omittedHistoryNotice(omittedItems), + }, + }, + ], + }); + }, + ); const startWithHandoffs = Effect.fn("ProviderTurnStartService.startWithHandoffs")( function* (turnInput: Parameters[0], compact = false) { const delivery = yield* deliverContextHandoffs({ @@ -1627,6 +1679,9 @@ export const layer: Layer.Layer< yield* Effect.forEach( [ delivery.delivered, + ...(delivery.omittedItems === 0 + ? [] + : [recordOmittedHistoryNotice(delivery.omittedItems)]), ...(sideChatContext === "" || sideChatHandoff === undefined || nativeThreadId == null ? [] : [ diff --git a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts index 41a1120620f86..7cc180a8ee3d8 100644 --- a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts +++ b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts @@ -30,6 +30,7 @@ import * as Orchestrator from "./Orchestrator.ts"; import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import { MAX_HANDOFF_TOKEN_CAP } from "@t3tools/provider-core/server/handoffBudget"; const forkCases = ( [ @@ -558,7 +559,7 @@ it.effect.each([ contextHandoffId: null, }, }, - // Each message alone exceeds the default 16k handoff budget, so a + // Each message alone exceeds the largest handoff budget, so a // portable handoff omits both whole items. { id: EventId.make("fork-compact-user-item"), @@ -575,7 +576,7 @@ it.effect.each([ creationSource: "web", inputIntent: "turn_start", messageId: userMessageId, - text: "u".repeat(17_000), + text: "u".repeat(MAX_HANDOFF_TOKEN_CAP), attachments: [], }, }, @@ -591,7 +592,7 @@ it.effect.each([ ordinal: 2, type: "assistant_message", messageId: MessageId.make("fork-compact-assistant-message"), - text: "a".repeat(17_000), + text: "a".repeat(MAX_HANDOFF_TOKEN_CAP), streaming: false, }, }, diff --git a/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts b/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts index bec9c60c7a014..61d4818dad509 100644 --- a/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts +++ b/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts @@ -7,6 +7,8 @@ import { expect, it } from "@effect/vitest"; import { ChatAttachmentId, CommandId, + ComposerContextId, + PROVIDER_SEND_TURN_MAX_INPUT_CHARS, EventId, GuestMessageId, MessageId, @@ -426,3 +428,43 @@ it.effect("sends a guest message with the guest's files, never ones the client n expect(command.attachments).toEqual([guestFile]); }).pipe(Effect.provide(layerIntakeTest)), ); + +it.effect("refuses a message whose attached context pushes it over the prompt limit", () => + Effect.gen(function* () { + const captured: OrchestrationV2ServerCommand[] = []; + const record = { + version: 1 as const, + kind: "terminal" as const, + contextId: ComposerContextId.make("terminal_big"), + label: "Terminal 1 lines 1-2", + terminalId: "default", + terminalLabel: "Terminal 1", + lineStart: 1, + lineEnd: 2, + text: "t".repeat(PROVIDER_SEND_TURN_MAX_INPUT_CHARS - 1_000), + }; + const message = (records: ReadonlyArray) => + dispatchCommand({ + type: "message.dispatch", + commandId: CommandId.make("send-large-context"), + threadId: ThreadId.make("thread-large-context"), + messageId: MessageId.make("message-large-context"), + text: `${"p".repeat(2_000)} ${records + .map((entry) => `[${entry.label}](t3-context://v1/terminal/${entry.contextId})`) + .join(" ")}`, + context: { version: 1, records }, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }).pipe(Effect.provide(layerFailingDispatch(captured)), Effect.flip); + + const refused = yield* message([record]); + expect(refused._tag).toBe("ProviderInputTooLongError"); + expect(refused.message).toMatch(/over the 120,000-character limit/); + expect(captured).toEqual([]); + + yield* message([{ ...record, text: "short" }]); + expect(captured).toHaveLength(1); + }).pipe(Effect.provide(layerIntakeTest)), +); diff --git a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts index a48cc3ca7cd90..1a768175c9cba 100644 --- a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts +++ b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts @@ -1,6 +1,13 @@ -import { remapComposerContextAttachments } from "@t3tools/shared/composerContextReferences"; +import { + providerInputLengthErrorMessage, + remapComposerContextAttachments, +} from "@t3tools/shared/composerContextReferences"; import { appendUserInputAttachmentPaths } from "../provider/userInputAttachments.ts"; -import type { ChatAttachment, OrchestrationV2Command } from "@t3tools/contracts"; +import type { + ChatAttachment, + OrchestrationMessageContext, + OrchestrationV2Command, +} from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { resolveAttachmentPath } from "../attachmentStore.ts"; @@ -32,6 +39,25 @@ function dispatchWasNotAccepted( return false; } } +export class ProviderInputTooLongError extends Schema.TaggedError()( + "ProviderInputTooLongError", + { message: Schema.String }, +) {} + +/** The provider receives the prompt with its context records rendered in, so measure that. */ +const validateProviderInputLength = Effect.fn("ThreadMessageIntake.validateProviderInputLength")( + function* (input: { + readonly text: string; + readonly context?: OrchestrationMessageContext | undefined; + }) { + const message = providerInputLengthErrorMessage({ + text: input.text, + records: input.context?.records ?? [], + }); + if (message !== null) return yield* new ProviderInputTooLongError({ message }); + }, +); + const isOrchestratorError = Schema.is(Orchestrator.OrchestratorV2Error); const isThreadManagementError = Schema.is(ThreadManagement.ThreadManagementError); @@ -88,6 +114,9 @@ export const dispatchCommand = Effect.fn("ThreadMessageIntake.dispatchCommand")( ) { const command = incoming.type === "message.dispatch" ? yield* withGuestAttachments(incoming) : incoming; + if (command.type === "message.dispatch" || command.type === "queued-run.edit") { + yield* validateProviderInputLength(command); + } const threads = yield* ThreadManagement.ThreadManagementService; if (command.type === "runtime-request.respond" && command.attachmentsByQuestionId) { const config = yield* ServerConfig.ServerConfig; @@ -213,6 +242,7 @@ export const launchThread = Effect.fn("ThreadMessageIntake.launchThread")(functi ) { const launches = yield* ThreadLaunch.ThreadLaunchService; yield* AttachmentClaims.validateAttachmentLimits(input.initialMessage?.attachments ?? []); + if (input.initialMessage) yield* validateProviderInputLength(input.initialMessage); if (!input.initialMessage?.attachments.some(AttachmentClaims.attachmentIsPendingUpload)) { return yield* launches.launch(input); } diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index 83eee8f66a5dc..04ba3a4c2614f 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -1,5 +1,5 @@ import { vi } from "vite-plus/test"; -import { historyResponseItems } from "@t3tools/provider-core/server/handoffBudget"; +import { historyResponseItems, renderHistory } from "@t3tools/provider-core/server/handoffBudget"; import { assert, describe, it } from "@effect/vitest"; import { CommandId, @@ -46,6 +46,7 @@ import { canReuseCodexContextUsage, } from "../Adapters/CodexAdapterV2.ts"; import { AcpProviderCapabilitiesV2 } from "@t3tools/provider-acp/server/adapter"; +import { omittedHistoryNotice } from "../ContextHandoffDelivery.ts"; import * as EventSink from "../EventSink.ts"; import * as EventStore from "../EventStore.ts"; import * as LegacyV1ThreadImporter from "../legacy/LegacyV1ThreadImporter.ts"; @@ -822,7 +823,12 @@ describe("orchestration v2 provider switching", () => { if (scenario.includes("legacy-replacement")) { const recovered = yield* orchestrator.getThreadProjection(threadId); const handoff = recovered.contextHandoffs.at(-1)!; - const { history: _history, ...legacyHandoff } = handoff; + // Records from before history existed carried the rendered transcript as summaryText. + const { history, ...withoutHistory } = handoff; + const legacyHandoff = { + ...withoutHistory, + summaryText: renderHistory(history!.messages, handoff.summaryText), + }; yield* eventSink.write({ events: [ { @@ -982,7 +988,12 @@ describe("orchestration v2 provider switching", () => { assert.deepEqual((yield* Ref.get(capturedTurns)).at(-1)!.attachments, screenshots); } if (scenario === "compact-legacy") { - const { history: _history, ...legacyHandoff } = handoff; + // Records from before history existed carried the rendered transcript as summaryText. + const { history, ...withoutHistory } = handoff; + const legacyHandoff = { + ...withoutHistory, + summaryText: renderHistory(history!.messages, handoff.summaryText), + }; yield* eventSink.write({ events: [ { @@ -1183,6 +1194,14 @@ describe("orchestration v2 provider switching", () => { const delivery = retried.contextHandoffs.at(-1)!.delivery!; assert.include(delivery.omittedItemIds ?? [], missedRequest.id); assert.notInclude(delivery.itemIds, missedRequest.id); + assert.deepEqual( + retried.turnItems.flatMap((item) => + item.type === "system_notice" && item.runId === retried.runs.at(-1)!.id + ? [item.message] + : [], + ), + [omittedHistoryNotice(1)], + ); } else assert.include(delta, "First target request"); assert.notInclude(delta, "Original request with constraints"); assert.notInclude(delta, "Original partial work"); @@ -2523,7 +2542,7 @@ describe("orchestration v2 provider switching", () => { ); assert.isBelow(handoffItem?.ordinal ?? Infinity, queuedUserItem?.ordinal ?? -Infinity); assert.include( - handoffItem?.type === "handoff" ? handoffItem.summary : "", + projection.contextHandoffs[0]?.history?.messages.map((message) => message.text) ?? [], "Codex second queued turn complete", ); assert.include(turns[3]?.text ?? "", "Codex current turn complete"); @@ -3771,7 +3790,10 @@ describe("orchestration v2 provider switching", () => { (handoff) => handoff.id === projection.runs[1]?.contextHandoffId, ); assert.equal(recoveryHandoff?.strategy, "full_thread_summary"); - assert.include(recoveryHandoff?.summaryText ?? "", failedPrompt); + assert.include( + recoveryHandoff?.history?.messages.map((message) => message.text) ?? [], + failedPrompt, + ); if (queueBeforeFailure) { const handoffItem = projection.turnItems.find( (item) => item.type === "handoff" && item.runId === projection.runs[1]?.id, diff --git a/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts index 836e06e74fbde..9f5e95fe07c2a 100644 --- a/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts @@ -128,11 +128,6 @@ function readTranscript(scenario: string, driver: ProviderDriverKind) { }); } -function compactExpectedText(text: string, maxLength = 240): string { - const compacted = text.replace(/\s+/gu, " ").trim(); - return compacted.length <= maxLength ? compacted : `${compacted.slice(0, maxLength - 3)}...`; -} - function forkDeltaSummary(input: { readonly sourceThreadId: ThreadId; readonly targetThreadId: ThreadId; @@ -146,8 +141,8 @@ function forkDeltaSummary(input: { "Covered fork runs: 1-1", "", "Fork delta:", - `- User: ${compactExpectedText(input.forkUserText)}`, - `- Assistant: ${compactExpectedText(input.forkAssistantText)}`, + `- User: ${input.forkUserText.trim()}`, + `- Assistant: ${input.forkAssistantText.trim()}`, "- Checkpoint: 0 files", ].join("\n"); } diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts index c659622a2f1e8..d2c79f85dec6c 100644 --- a/apps/server/src/project/AgentSessionImporter.test.ts +++ b/apps/server/src/project/AgentSessionImporter.test.ts @@ -86,7 +86,6 @@ function candidate( model: modelSelection.model, createdAt: timestamp, updatedAt: timestamp, - omittedMessageCount: 0, messages: [ { role: "user" as const, text: "Fix it", createdAt: timestamp }, { role: "assistant" as const, text: "Fixed", createdAt: timestamp }, @@ -179,7 +178,7 @@ const seedOwner = Effect.fn(function* ( }); const makeImporter = Effect.fn(function* ( - candidates: ReadonlyArray>, + candidates: ReadonlyArray, beforeTransaction: Effect.Effect = Effect.void, getAdapter?: ProviderAdapterRegistry.ProviderAdapterRegistryV2Shape["get"], threadCommands?: KeyedLock.KeyedLock, @@ -303,8 +302,13 @@ it.effect( "claudeAgent", ); const unowned = candidate(CODEX_MODEL_SELECTION, "unowned"); - unowned.thread.omittedMessageCount = 1; const unownedPi = candidate(PI_MODEL_SELECTION, "unowned-pi", "pi"); + const tooLarge = { + provider: "codex", + filePath: "/tmp/codex/too-large.jsonl", + reason: "too_large", + } as const; + const unresumable = candidate(CLAUDE_MODEL_SELECTION, "not-a-session-uuid", "claudeAgent"); const importer = yield* makeImporter([ active, archived, @@ -313,9 +317,26 @@ it.effect( otherInstance, unowned, unownedPi, + { _tag: "Skipped", skipped: tooLarge }, + unresumable, ]); - expect(yield* importer.run).toEqual({ importedCount: 3, skippedCount: 0 }); + expect(yield* importer.run).toEqual({ + importedCount: 3, + skippedCount: 2, + skipped: [ + { + reason: "too_large", + count: 1, + examples: [{ provider: "codex", filePath: tooLarge.filePath }], + }, + { + reason: "unresumable", + count: 1, + examples: [{ provider: "claudeAgent", filePath: unresumable.source.filePath }], + }, + ], + }); for (const source of [active, archived, deleted, ownedPi]) { const threadId = importId(source); expect(yield* Effect.option(projections.getThread(threadId))).toEqual(Option.none()); @@ -342,19 +363,6 @@ it.effect( "providerThreads", ]); expect(records.messages.map((message) => message.text)).toEqual(["Fix it", "Fixed"]); - const notices = records.turnItems.filter((item) => item.type === "system_notice"); - if (source === unowned) { - expect(records.turnItems[0]).toBe(notices[0]); - expect(notices).toMatchObject([ - { - ordinal: 1, - runId: null, - message: expect.stringContaining("1 earlier message was not imported"), - }, - ]); - } else { - expect(notices).toEqual([]); - } expect(records.thread.historyOrigin).toBe("v1_import"); expect(records.thread.activeProviderThreadId).toBe(records.providerThreads[0]?.id); expect(records.providerThreads[0]?.nativeThreadRef?.nativeId).toBe(nativeId(source)); @@ -386,8 +394,8 @@ it.effect("rechecks ownership after the import reaches the commit transaction", // Commit ownership after all pre-transaction reads, before the import acquires SQLite. const ownerId = yield* seedOwner(source); yield* Deferred.succeed(continueTransaction, undefined); - expect(yield* Fiber.join(pending)).toEqual({ importedCount: 0, skippedCount: 0 }); - expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 0 }); + expect(yield* Fiber.join(pending)).toEqual({ importedCount: 0, skippedCount: 0, skipped: [] }); + expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 0, skipped: [] }); const projections = yield* ProjectionStore.ProjectionStoreV2; const events = yield* EventStore.EventStoreV2; const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; @@ -414,7 +422,17 @@ it.effect( const threadId = importId(source); const importer = yield* makeImporter([source]); yield* sql`CREATE TEMP TRIGGER fail_import BEFORE INSERT ON orchestration_events WHEN NEW.event_type = 'message.updated' BEGIN SELECT RAISE(ABORT, 'test publication failure'); END`; - expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 1 }); + expect(yield* importer.run).toEqual({ + importedCount: 0, + skippedCount: 1, + skipped: [ + { + reason: "import_failed", + count: 1, + examples: [{ provider: "codex", filePath: source.source.filePath }], + }, + ], + }); expect(yield* events.read({ threadId }).pipe(Stream.runCollect)).toEqual([]); expect(yield* Effect.option(projections.getThread(threadId))).toEqual(Option.none()); expect(yield* runtimes.list()).toEqual([]); @@ -422,15 +440,25 @@ it.effect( yield* sql`DROP TRIGGER fail_import`; yield* sql`CREATE TEMP TRIGGER fail_runtime BEFORE INSERT ON provider_session_runtime BEGIN SELECT RAISE(ABORT, 'test runtime failure'); END`; - expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 1 }); + expect(yield* importer.run).toEqual({ + importedCount: 0, + skippedCount: 1, + skipped: [ + { + reason: "import_failed", + count: 1, + examples: [{ provider: "codex", filePath: source.source.filePath }], + }, + ], + }); const committed = yield* events.read({ threadId }).pipe(Stream.runCollect); expect(committed).toHaveLength(6); expect(importer.published).toHaveLength(6); expect(yield* runtimes.list()).toEqual([]); yield* sql`DROP TRIGGER fail_runtime`; - expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 }); - expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 }); + expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0, skipped: [] }); + expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0, skipped: [] }); expect(yield* events.read({ threadId }).pipe(Stream.runCollect)).toEqual(committed); expect(importer.published).toHaveLength(6); expect( @@ -781,7 +809,7 @@ it.effect("imports under a policy ceiling in the project's default, kept under t }, ), ); - expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 }); + expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0, skipped: [] }); expect((yield* projections.getThread(threadId)).runtimeMode).toBe("auto-accept-edits"); expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId })).runtimeMode).toBe( "auto-accept-edits", diff --git a/apps/server/src/project/AgentSessionImporter.ts b/apps/server/src/project/AgentSessionImporter.ts index ec3e9e3bbe21a..6c5dacb87af2b 100644 --- a/apps/server/src/project/AgentSessionImporter.ts +++ b/apps/server/src/project/AgentSessionImporter.ts @@ -17,6 +17,9 @@ import { TurnItemId, type AgentSessionImportInput, type AgentSessionImportResult, + type AgentSessionImportSkipReason, + type AgentSessionImportSkippedGroup, + mergeSkippedImportGroups, type OrchestrationV2AppThread, type OrchestrationV2ConversationMessage, type OrchestrationV2DomainEvent, @@ -265,11 +268,23 @@ const make = Effect.gen(function* () { const importedThreadIds = new Set(); let importedCount = 0; let skippedCount = 0; + let skipped: Array = []; + const skip = (entry: AgentSessionScanner.AgentSessionSkippedTranscript) => { + skippedCount += 1; + skipped = mergeSkippedImportGroups([ + ...skipped, + { + reason: entry.reason, + count: 1, + examples: [{ provider: entry.provider, filePath: entry.filePath }], + }, + ]); + }; yield* Stream.runForEach(outcomes, (outcome) => Effect.gen(function* () { if (outcome._tag === "Skipped") { - skippedCount += 1; + skip(outcome.skipped); return; } const source = outcome.source; @@ -415,34 +430,6 @@ const make = Effect.gen(function* () { occurredAt: createdAt, payload: appThread, }, - ...(thread.omittedMessageCount > 0 - ? [ - { - id: EventId.make(`${IMPORT_EVENT_PREFIX}:history-truncated:${threadId}`), - type: "turn-item.updated" as const, - threadId, - occurredAt: createdAt, - payload: { - id: TurnItemId.make(`${IMPORT_EVENT_PREFIX}:history-truncated:${threadId}`), - threadId, - runId: null, - nodeId: null, - providerThreadId: null, - providerTurnId: null, - nativeItemRef: null, - parentItemId: null, - ordinal: 0, - status: "completed" as const, - title: null, - startedAt: createdAt, - completedAt: createdAt, - updatedAt: createdAt, - type: "system_notice" as const, - message: `${thread.omittedMessageCount} earlier ${thread.omittedMessageCount === 1 ? "message was" : "messages were"} not imported. This thread keeps the first user message and the most recent history. The original session transcript is unchanged.`, - }, - }, - ] - : []), ...thread.messages.flatMap((message, index) => messageEvents({ threadId, index, message }), ), @@ -467,19 +454,29 @@ const make = Effect.gen(function* () { provider: outcome.thread.source, sessionId: outcome.thread.providerSessionId, cause, - }).pipe(Effect.as(false)), + }).pipe( + Effect.as( + cause._tag === "AgentSessionUnresumableSessionError" + ? "unresumable" + : "import_failed", + ), + ), ), ); if (imported === true) { importedThreadIds.add(threadId); importedCount += 1; - } else if (imported === false) { - skippedCount += 1; + } else if (typeof imported === "string") { + skip({ provider: source.provider, filePath: source.filePath, reason: imported }); } }), ); - return { importedCount, skippedCount } satisfies AgentSessionImportResult; + return { + importedCount, + skippedCount, + skipped, + } satisfies AgentSessionImportResult; }); /** diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 6ab04f7e302a4..6d824efefc050 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -62,6 +62,9 @@ interface ScannerTestInput { readonly processRunner?: Layer.Layer; } +// The real limit is 10M records; the same boundaries hold at a fixture-sized one. +const TEST_RECORD_LIMIT = 100_000; + const layerScannerTest = (input: ScannerTestInput) => (input.processRunner === undefined ? AgentSessionScanner.layer @@ -103,6 +106,7 @@ const layerScannerTest = (input: ScannerTestInput) => input.configBaseDir ?? { prefix: "t3code-scanner-config-" }, ), layerProjectStore(input.importedWorkspaceRoots ?? []), + Layer.succeed(AgentSessionScanner.ImportRecordLimit, TEST_RECORD_LIMIT), ), ), ); @@ -170,7 +174,7 @@ function makeRecordLimitTranscript(cwd: string, overflow: boolean): string { }), ].join("\n") + "\n" + - "{}\n".repeat(99_998); + "{}\n".repeat(TEST_RECORD_LIMIT - 2); return overflow ? records + "\n" + @@ -1123,168 +1127,172 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }); describe("recentThreads", () => { - it.effect("imports recent Claude, Codex, and Pi sessions for the selected project only", () => - Effect.gen(function* () { - const path = yield* Path.Path; - const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); - yield* TestClock.setTime(nowMs); - const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); - const codexHomePath = yield* makeTempDir("t3code-codex-home-"); - const piAgentDir = yield* makeTempDir("t3code-pi-agent-"); - const workspace = yield* makeTempDir("t3code-workspace-"); - const otherWorkspace = yield* makeTempDir("t3code-workspace-other-"); - - const claudeTranscript = (cwd: string, sessionId: string) => - `${JSON.stringify({ - type: "user", - cwd, - sessionId, - timestamp: "2026-08-23T12:00:00.000Z", - message: { role: "user", content: "Fix the project" }, - })}\n${JSON.stringify({ - type: "assistant", - sessionId, - timestamp: "2026-08-23T12:01:00.000Z", - message: { role: "assistant", content: [{ type: "text", text: "Done" }] }, - })}\n`; + it.effect( + "imports Claude, Codex, and Pi sessions of any age for the selected project only", + () => + Effect.gen(function* () { + const path = yield* Path.Path; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const piAgentDir = yield* makeTempDir("t3code-pi-agent-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + const otherWorkspace = yield* makeTempDir("t3code-workspace-other-"); + + const claudeTranscript = (cwd: string, sessionId: string) => + `${JSON.stringify({ + type: "user", + cwd, + sessionId, + timestamp: "2026-08-23T12:00:00.000Z", + message: { role: "user", content: "Fix the project" }, + })}\n${JSON.stringify({ + type: "assistant", + sessionId, + timestamp: "2026-08-23T12:01:00.000Z", + message: { role: "assistant", content: [{ type: "text", text: "Done" }] }, + })}\n`; - yield* writeTranscript({ - filePath: path.join(claudeHomePath, "projects", "-selected", "claude-recent.jsonl"), - contents: claudeTranscript(workspace, "claude-recent"), - mtimeMs: nowMs - 24 * 60 * 60 * 1000, - }); - yield* writeTranscript({ - filePath: path.join(claudeHomePath, "projects", "-selected", "claude-old.jsonl"), - contents: claudeTranscript(workspace, "claude-old"), - mtimeMs: nowMs - 31 * 24 * 60 * 60 * 1000, - }); - yield* writeTranscript({ - filePath: path.join(claudeHomePath, "projects", "-other", "claude-other.jsonl"), - contents: claudeTranscript(otherWorkspace, "claude-other"), - mtimeMs: nowMs - 24 * 60 * 60 * 1000, - }); - yield* writeTranscript({ - filePath: path.join( - codexHomePath, - "sessions", - "2026", - "08", - "24", - "rollout-codex-recent.jsonl", - ), - contents: [ - encodeTranscriptRecord({ - type: "session_meta", - payload: { id: "codex-recent", cwd: workspace }, - }), - encodeTranscriptRecord({ - type: "event_msg", - timestamp: "2026-08-24T10:00:00.000Z", - payload: { type: "user_message", message: "Review this code" }, - }), - encodeTranscriptRecord({ - type: "response_item", - timestamp: "2026-08-24T10:01:00.000Z", - payload: { - type: "message", - role: "assistant", - content: [{ type: "output_text", text: "Looks good" }], - }, - }), - ].join("\n"), - mtimeMs: nowMs - 60 * 60 * 1000, - }); - const piMessage = ( - id: string, - parentId: string | null, - message: { readonly role: string; readonly content: unknown }, - ) => - encodeTranscriptRecord({ - type: "message", - id, - parentId, - timestamp: "2026-08-24T11:00:00.000Z", - message, + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-selected", "claude-recent.jsonl"), + contents: claudeTranscript(workspace, "claude-recent"), + mtimeMs: nowMs - 24 * 60 * 60 * 1000, }); - // The user rewound to the first prompt; the abandoned branch stays in the file. - yield* writeTranscript({ - filePath: path.join(piAgentDir, "sessions", "--selected--", "2026-08-24_pi.jsonl"), - contents: [ - encodeTranscriptRecord({ - type: "session", - version: 3, - id: "pi-recent", - cwd: workspace, - }), - piMessage("a1", null, { role: "user", content: "Plan the change" }), - piMessage("a2", "a1", { - role: "assistant", - content: [{ type: "text", text: "Abandoned answer" }], - }), - piMessage("a3", "a2", { role: "user", content: "Abandoned follow-up" }), - piMessage("b1", "a1", { - role: "assistant", - content: [ - { type: "thinking", thinking: "Hidden reasoning" }, - { type: "toolCall", id: "call-1", name: "bash", arguments: {} }, - ], - }), - piMessage("bn", "b1", { role: "toolResult", content: null }), - piMessage("b2", "bn", { - role: "toolResult", - content: [{ type: "text", text: "Tool output" }], - }), - piMessage("b3", "b2", { - role: "assistant", - content: [{ type: "text", text: "Active answer" }], - }), - encodeTranscriptRecord({ - type: "session_info", - id: "b4", - parentId: "b3", - name: "Pi refactor", - }), - ].join("\n"), - mtimeMs: nowMs - 30 * 60 * 1000, - }); - // Version 1 sessions predate the entry tree. - yield* writeTranscript({ - filePath: path.join(piAgentDir, "sessions", "--selected--", "2025-01-01_pi-v1.jsonl"), - contents: [ - encodeTranscriptRecord({ type: "session", id: "pi-v1", cwd: workspace }), - encodeTranscriptRecord({ - type: "message", - message: { role: "user", content: "Legacy prompt" }, - }), + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-selected", "claude-old.jsonl"), + contents: claudeTranscript(workspace, "claude-old"), + mtimeMs: nowMs - 31 * 24 * 60 * 60 * 1000, + }); + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-other", "claude-other.jsonl"), + contents: claudeTranscript(otherWorkspace, "claude-other"), + mtimeMs: nowMs - 24 * 60 * 60 * 1000, + }); + yield* writeTranscript({ + filePath: path.join( + codexHomePath, + "sessions", + "2026", + "08", + "24", + "rollout-codex-recent.jsonl", + ), + contents: [ + encodeTranscriptRecord({ + type: "session_meta", + payload: { id: "codex-recent", cwd: workspace }, + }), + encodeTranscriptRecord({ + type: "event_msg", + timestamp: "2026-08-24T10:00:00.000Z", + payload: { type: "user_message", message: "Review this code" }, + }), + encodeTranscriptRecord({ + type: "response_item", + timestamp: "2026-08-24T10:01:00.000Z", + payload: { + type: "message", + role: "assistant", + content: [{ type: "output_text", text: "Looks good" }], + }, + }), + ].join("\n"), + mtimeMs: nowMs - 60 * 60 * 1000, + }); + const piMessage = ( + id: string, + parentId: string | null, + message: { readonly role: string; readonly content: unknown }, + ) => encodeTranscriptRecord({ type: "message", - message: { role: "assistant", content: [{ type: "text", text: "Legacy answer" }] }, - }), - ].join("\n"), - mtimeMs: nowMs - 2 * 24 * 60 * 60 * 1000, - }); + id, + parentId, + timestamp: "2026-08-24T11:00:00.000Z", + message, + }); + // The user rewound to the first prompt; the abandoned branch stays in the file. + yield* writeTranscript({ + filePath: path.join(piAgentDir, "sessions", "--selected--", "2026-08-24_pi.jsonl"), + contents: [ + encodeTranscriptRecord({ + type: "session", + version: 3, + id: "pi-recent", + cwd: workspace, + }), + piMessage("a1", null, { role: "user", content: "Plan the change" }), + piMessage("a2", "a1", { + role: "assistant", + content: [{ type: "text", text: "Abandoned answer" }], + }), + piMessage("a3", "a2", { role: "user", content: "Abandoned follow-up" }), + piMessage("b1", "a1", { + role: "assistant", + content: [ + { type: "thinking", thinking: "Hidden reasoning" }, + { type: "toolCall", id: "call-1", name: "bash", arguments: {} }, + ], + }), + piMessage("bn", "b1", { role: "toolResult", content: null }), + piMessage("b2", "bn", { + role: "toolResult", + content: [{ type: "text", text: "Tool output" }], + }), + piMessage("b3", "b2", { + role: "assistant", + content: [{ type: "text", text: "Active answer" }], + }), + encodeTranscriptRecord({ + type: "session_info", + id: "b4", + parentId: "b3", + name: "Pi refactor", + }), + ].join("\n"), + mtimeMs: nowMs - 30 * 60 * 1000, + }); + // Version 1 sessions predate the entry tree. + yield* writeTranscript({ + filePath: path.join(piAgentDir, "sessions", "--selected--", "2025-01-01_pi-v1.jsonl"), + contents: [ + encodeTranscriptRecord({ type: "session", id: "pi-v1", cwd: workspace }), + encodeTranscriptRecord({ + type: "message", + message: { role: "user", content: "Legacy prompt" }, + }), + encodeTranscriptRecord({ + type: "message", + message: { role: "assistant", content: [{ type: "text", text: "Legacy answer" }] }, + }), + ].join("\n"), + mtimeMs: nowMs - 2 * 24 * 60 * 60 * 1000, + }); - const threads = yield* runRecentThreads({ - claudeHomePath, - codexHomePath, - piAgentDir, - workspaceRoot: workspace, - }); + const threads = yield* runRecentThreads({ + claudeHomePath, + codexHomePath, + piAgentDir, + workspaceRoot: workspace, + }); - expect(threads.map((thread) => thread.providerSessionId)).toEqual([ - "pi-recent", - "codex-recent", - "claude-recent", - "pi-v1", - ]); - expect(threads.map((thread) => thread.messages.map((message) => message.text))).toEqual([ - ["Plan the change", "Active answer"], - ["Review this code", "Looks good"], - ["Fix the project", "Done"], - ["Legacy prompt", "Legacy answer"], - ]); - expect(threads[0]).toMatchObject({ source: "pi", title: "Pi refactor" }); - }), + expect(threads.map((thread) => thread.providerSessionId)).toEqual([ + "pi-recent", + "codex-recent", + "claude-recent", + "pi-v1", + "claude-old", + ]); + expect(threads.map((thread) => thread.messages.map((message) => message.text))).toEqual([ + ["Plan the change", "Active answer"], + ["Review this code", "Looks good"], + ["Fix the project", "Done"], + ["Legacy prompt", "Legacy answer"], + ["Fix the project", "Done"], + ]); + expect(threads[0]).toMatchObject({ source: "pi", title: "Pi refactor" }); + }), ); it.effect("keeps the provider instance that owns a custom session home", () => @@ -1611,7 +1619,7 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { { subagent: { other: "guardian" } }, { subAgent: "compact" }, ]; - // Newer subagents would exhaust the 100-transcript import budget before any parent. + // Subagent rollouts are excluded, however many come before their parents. const sources = [ ...Array.from({ length: 100 }, (_, index) => subagentSources[index % 4]), "vscode", @@ -1735,6 +1743,7 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { workspaceRoot: workspace, }); expect(outcomes.map((outcome) => outcome._tag)).toEqual(["Skipped", "Importable"]); + expect(outcomes[0]).toMatchObject({ skipped: { reason: "too_large" } }); expect(outcomes[1]).toMatchObject({ thread: { providerSessionId: "record-limit-session" }, }); @@ -1878,7 +1887,12 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { thread: { messages: [{ text: "Replacement prompt" }] }, }); } else { - expect(outcomes).toEqual([{ _tag: "Skipped" }]); + expect(outcomes).toEqual([ + { + _tag: "Skipped", + skipped: { provider: source, filePath, reason: "outside_project" }, + }, + ]); } }).pipe(Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath }))); }), @@ -1995,7 +2009,7 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { type: "assistant", message: { role: "assistant", model: "claude-opus-5-5", content: "First reply" }, }), - // Small tool records exceed the real 32 MiB selected-history budget in aggregate. + // Tool records do not count toward the selected-history budget. ...Array.from({ length: 20_000 }, () => toolResult), record({ type: "user", message: { role: "user", content: "Latest prompt" } }), record({ @@ -2101,7 +2115,16 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { expect(transcriptOpenCount).toBe(2); expect(fullReadBytes).toBe(new TextEncoder().encode(contents).byteLength); - expect(outcomes).toEqual([{ _tag: "Skipped" }]); + expect(outcomes).toEqual([ + { + _tag: "Skipped", + skipped: { + provider: "codex", + filePath: transcriptPath, + reason: "changed_while_reading", + }, + }, + ]); }), ); @@ -2434,6 +2457,7 @@ describe("parseAgentSessionTranscript", () => { (overflow) => { const thread = AgentSessionScanner.parseAgentSessionTranscript({ contents: makeRecordLimitTranscript("/project", overflow), + maxRecords: TEST_RECORD_LIMIT, source: "codex", providerInstanceId: ProviderInstanceId.make("codex"), fallbackSessionId: "unused", @@ -2445,7 +2469,7 @@ describe("parseAgentSessionTranscript", () => { ); it.each([199, 200, 201, 205])( - "counts only omitted conversation messages for a %s-message Claude transcript", + "keeps every conversation message of a %s-message Claude transcript", (count) => { const thread = AgentSessionScanner.parseAgentSessionTranscript({ contents: [ @@ -2479,8 +2503,7 @@ describe("parseAgentSessionTranscript", () => { lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"), }); - expect(thread?.omittedMessageCount).toBe(Math.max(0, count - 200)); - expect(thread?.messages).toHaveLength(Math.min(200, count)); + expect(thread?.messages).toHaveLength(count); expect(thread?.messages[0]?.text).toBe("Message 0"); expect(thread?.messages.at(-1)?.text).toBe(`Message ${count - 1}`); }, @@ -2676,8 +2699,7 @@ describe("parseAgentSessionTranscript", () => { lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"), }); - expect(thread?.omittedMessageCount).toBe(count - 199); - expect(thread?.messages).toHaveLength(200); + expect(thread?.messages).toHaveLength(count + 1); expect(thread?.messages[0]).toMatchObject({ role: "user", text: canonicalPrompt, @@ -2739,8 +2761,7 @@ describe("parseAgentSessionTranscript", () => { lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"), }); - expect(thread?.omittedMessageCount).toBe(1); - expect(thread?.messages).toHaveLength(200); + expect(thread?.messages).toHaveLength(201); expect(thread?.messages[0]).toMatchObject({ role: "user", text: canonicalPrompt, diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index 1b32de22a8878..3b9e1f16012b1 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -9,6 +9,7 @@ import { ProviderInstanceId, resolveProviderInstanceEnabled, type AgentSessionImportSource, + type AgentSessionImportSkipReason, type AgentSessionProjectCandidate, type AgentSessionProjectGit, type AgentSessionScanResult, @@ -48,6 +49,8 @@ import { const TRANSCRIPT_PREFIX_BYTES = 32 * 1024; +const isTranscriptJsonLimitError = Schema.is(TranscriptJsonLimitError); + class TranscriptParseError extends Schema.TaggedError()( "TranscriptParseError", { filePath: Schema.String, cause: Schema.Defect() }, @@ -70,21 +73,25 @@ const MAX_TRANSCRIPT_SCAN_BYTES = 1024 * 1024; const MAX_CODEX_SESSION_INDEX_BYTES = 1024 * 1024; const MAX_CODEX_PROJECT_ROOT_ROWS = 100_000; -const MAX_TRANSCRIPTS_PER_SOURCE = 5000; +const MAX_TRANSCRIPTS_PER_SOURCE = 100_000; +// Metadata budgets scale with the transcript cap, keeping the per-transcript average. const MAX_DISCOVERY_OPERATIONS_PER_SOURCE = MAX_TRANSCRIPTS_PER_SOURCE * 4; -const MAX_METADATA_BYTES_PER_SOURCE = 64 * 1024 * 1024; +const MAX_METADATA_BYTES_PER_SOURCE = MAX_TRANSCRIPTS_PER_SOURCE * 13 * 1024; const MAX_METADATA_OPERATIONS_PER_SOURCE = MAX_TRANSCRIPTS_PER_SOURCE * 4; -const MAX_METADATA_RECORDS_PER_SOURCE = 100_000; +const MAX_METADATA_RECORDS_PER_SOURCE = MAX_TRANSCRIPTS_PER_SOURCE * 20; const MAX_METADATA_RECORDS_PER_TRANSCRIPT = 1_000; -const RECENT_THREAD_WINDOW_MS = 30 * 24 * 60 * 60 * 1000; // Screenshot-heavy transcripts can reach GiB; select fields while streaming to avoid allocating payloads. const MAX_IMPORTED_TRANSCRIPT_BYTES = 4 * 1024 * 1024 * 1024; -const MAX_IMPORTED_MESSAGES = 200; -const MAX_IMPORT_HISTORY_BYTES = 32 * 1024 * 1024; +// A thread is parsed and committed whole; peak heap runs at a few times the kept text. +const MAX_IMPORT_HISTORY_BYTES = 128 * 1024 * 1024; const MAX_IMPORT_BYTES = 4 * 1024 * 1024 * 1024; -const MAX_IMPORT_TRANSCRIPTS = 100; -const MAX_IMPORT_RECORDS = 100_000; +const MAX_IMPORT_RECORDS = 10_000_000; +/** Records read per transcript; tests lower it to keep fixtures small. */ +export const ImportRecordLimit = Context.Reference( + "t3/project/AgentSessionScanner/ImportRecordLimit", + { defaultValue: () => MAX_IMPORT_RECORDS }, +); /** * open() of a file under macOS privacy protection waits on a consent prompt @@ -201,7 +208,12 @@ export interface AgentSessionThread { readonly createdAt: string; readonly updatedAt: string; readonly messages: ReadonlyArray; - readonly omittedMessageCount: number; +} + +export interface AgentSessionSkippedTranscript { + readonly provider: AgentSessionSource; + readonly filePath: string; + readonly reason: AgentSessionImportSkipReason; } export type AgentSessionRecentThread = @@ -212,7 +224,10 @@ export type AgentSessionRecentThread = } | { readonly _tag: "AlreadyImported"; readonly source: AgentSessionImportSource } | { readonly _tag: "Duplicate"; readonly source: AgentSessionImportSource } - | { readonly _tag: "Skipped" }; + | { + readonly _tag: "Skipped"; + readonly skipped: AgentSessionSkippedTranscript; + }; export class AgentSessionScanner extends Context.Service< AgentSessionScanner, @@ -422,10 +437,12 @@ function isPiConversationRecord( export function parseAgentSessionTranscript( input: AgentSessionTranscriptMetadata & { readonly contents: string; + readonly maxRecords?: number; }, - lines = splitTranscriptRecords(input.contents, MAX_IMPORT_RECORDS + 1), ): AgentSessionThread | null { - if (lines.length > MAX_IMPORT_RECORDS) return null; + const maxRecords = input.maxRecords ?? MAX_IMPORT_RECORDS; + const lines = splitTranscriptRecords(input.contents, maxRecords + 1); + if (lines.length > maxRecords) return null; const records = lines.flatMap((line) => Option.toArray(decodeTranscriptRecord(line))); const claudeFields = input.source === "claudeAgent" @@ -457,9 +474,6 @@ function parseAgentSessionRecords( let derivedTitle: string | undefined; let hasCodexSessionId = false; const messages: Array = []; - let firstUserMessage: - | (AgentSessionThreadMessage & { readonly codexResponseUser: boolean }) - | undefined; const canonicalCodexResponseUserIndices = new Set(); let canonicalUserTextsInTurn = new Set(); let responseUsersInTurn: Array<{ @@ -513,19 +527,13 @@ function parseAgentSessionRecords( finishCodexTurn(); } - let conversationMessageCount = 0; const retainMessage = ( message: AgentSessionThreadMessage & { readonly codexResponseUser: boolean }, ) => { - if (firstUserMessage === undefined && message.role === "user") { - firstUserMessage = message; - } if (derivedTitle === undefined && message.role === "user") { derivedTitle = deriveTitle(input.source, message.text); } - conversationMessageCount += 1; messages.push(message); - if (messages.length > MAX_IMPORTED_MESSAGES) messages.shift(); }; const hasMatchingCodexEventInTurn = (text: string) => { @@ -593,9 +601,7 @@ function parseAgentSessionRecords( const message = messages[index]; if (message?.role === "assistant") break; if (message?.codexResponseUser === true && message.text.trim() === text.trim()) { - if (firstUserMessage === message) firstUserMessage = undefined; messages.splice(index, 1); - conversationMessageCount -= 1; break; } } @@ -631,15 +637,15 @@ function parseAgentSessionRecords( }); } - const visibleMessages = messages.map( + if ( + providerSessionId.trim().length === 0 || + !messages.some((message) => message.role === "user") + ) { + return null; + } + const retainedMessages = messages.map( ({ codexResponseUser: _codexResponseUser, ...message }) => message, ); - if (providerSessionId.trim().length === 0 || firstUserMessage === undefined) return null; - const firstUserMessageRetained = messages.includes(firstUserMessage); - const { codexResponseUser: _codexResponseUser, ...visibleFirstUserMessage } = firstUserMessage; - const retainedMessages = firstUserMessageRetained - ? visibleMessages - : [visibleFirstUserMessage, ...visibleMessages.slice(-(MAX_IMPORTED_MESSAGES - 1))]; return { source: input.source, @@ -650,7 +656,6 @@ function parseAgentSessionRecords( createdAt: retainedMessages[0]?.createdAt ?? fallbackTimestamp, updatedAt: fallbackTimestamp, messages: retainedMessages, - omittedMessageCount: conversationMessageCount - retainedMessages.length, }; } @@ -780,6 +785,7 @@ function sameTranscriptIdentity(left: TranscriptIdentity, right: TranscriptIdent /** @public */ export const make = Effect.gen(function* () { + const maxImportRecords = yield* ImportRecordLimit; const fileSystem = yield* FileSystem.FileSystem; const processRunner = yield* ProcessRunner.ProcessRunner; // Concurrent client imports must not hold multiple selected-history budgets. @@ -1046,14 +1052,15 @@ export const make = Effect.gen(function* () { prefix?: { readonly endByteOffset: number; readonly historyBytes: number }, ) { const readBytes = prefix?.endByteOffset ?? expected.size; - if (readBytes > expected.size || readBytes > MAX_IMPORTED_TRANSCRIPT_BYTES) return null; + if (readBytes > expected.size) return "changed_while_reading" as const; + if (readBytes > MAX_IMPORTED_TRANSCRIPT_BYTES) return "too_large" as const; return yield* Effect.scoped( fileSystem.open(filePath, { flag: "r" }).pipe( Effect.flatMap((file) => Effect.gen(function* () { if (!sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat))) { - return null; + return "changed_while_reading" as const; } const records: Array = []; let cwd = Option.none(); @@ -1066,7 +1073,7 @@ export const make = Effect.gen(function* () { recordBytes += bytes; if (historyBytes + recordBytes > MAX_IMPORT_HISTORY_BYTES) { throw new TranscriptJsonLimitError({ - message: "Transcript selected history exceeds the 32 MiB memory budget", + message: "Transcript selected history exceeds the 128 MiB memory budget", }); } }; @@ -1077,7 +1084,7 @@ export const make = Effect.gen(function* () { const finishRecord = () => { reader.write(decoder.decode()); recordCount += 1; - if (recordCount > MAX_IMPORT_RECORDS) return false; + if (recordCount > maxImportRecords) return false; const value = reader.finish(); const decoded = decodeTranscriptValue(value); if (Option.isNone(decoded) && source === "pi") { @@ -1115,7 +1122,7 @@ export const make = Effect.gen(function* () { Math.min(TRANSCRIPT_PREFIX_BYTES, readBytes - bytesRead), ); if (Option.isNone(next)) { - return null; + return "changed_while_reading" as const; } bytesRead += next.value.byteLength; @@ -1135,7 +1142,7 @@ export const make = Effect.gen(function* () { }, catch: (cause) => new TranscriptParseError({ filePath, cause }), }); - if (!withinBudget) return null; + if (!withinBudget) return "too_large" as const; } if ( @@ -1145,17 +1152,21 @@ export const make = Effect.gen(function* () { catch: (cause) => new TranscriptParseError({ filePath, cause }), })) ) - return null; + return "too_large" as const; return sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat)) ? { records, cwd, claudeFields, historyBytes } - : null; + : ("changed_while_reading" as const); }), ), ), ).pipe( Effect.catch((cause) => Effect.logWarning("Could not read imported transcript", { filePath, cause }).pipe( - Effect.as(null), + Effect.as( + cause._tag === "TranscriptParseError" && isTranscriptJsonLimitError(cause.cause) + ? "too_large" + : "unreadable", + ), ), ), ); @@ -1729,8 +1740,6 @@ export const make = Effect.gen(function* () { const realRoot = yield* fileSystem.realPath(root).pipe(Effect.orElseSucceed(() => root)); if (isExcludedProjectPath(root) || isExcludedProjectPath(realRoot)) return Stream.empty; const rootIdentity = yield* directoryIdentity(root); - const nowMs = DateTime.toEpochMillis(yield* DateTime.now); - const cutoffMs = nowMs - RECENT_THREAD_WINDOW_MS; const candidates = cachedCandidates ?? (yield* collectCandidates()).candidates; cachedCandidates = candidates; @@ -1746,13 +1755,7 @@ export const make = Effect.gen(function* () { if ((yield* directoryIdentity(resolved)) !== rootIdentity) continue; for (const transcript of candidate.transcripts) { - if ( - transcript.mtimeMs === null || - transcript.mtimeMs < cutoffMs || - transcript.mtimeMs > nowMs - ) { - continue; - } + if (transcript.mtimeMs === null) continue; eligibleTranscripts.push({ candidate, transcript: { ...transcript, mtimeMs: transcript.mtimeMs }, @@ -1774,7 +1777,6 @@ export const make = Effect.gen(function* () { const importedSessions = new Set(); const codexThreadNamesByHome = new Map>(); let bytesRemaining = MAX_IMPORT_BYTES; - let transcriptsRemaining = MAX_IMPORT_TRANSCRIPTS; const codexRolloutPaths = new Map>(); const codexRolloutPath = (providerInstanceId: ProviderInstanceId, rolloutId: string) => { let paths = codexRolloutPaths.get(providerInstanceId); @@ -1818,7 +1820,7 @@ export const make = Effect.gen(function* () { "codex", { endByteOffset: base.end_byte_offset, historyBytes }, ); - if (inherited === null) return null; + if (typeof inherited === "string") return null; historyBytes = inherited.historyBytes; // The rollout's own session_meta names the thread; inherited ones may name a fork parent. prefixes.unshift(inherited.records.filter((record) => record.type !== "session_meta")); @@ -1829,16 +1831,17 @@ export const make = Effect.gen(function* () { return Stream.fromIteratorSucceed(eligibleTranscripts.values(), 1).pipe( Stream.mapEffect(({ candidate, transcript }) => Effect.gen(function* () { + const skip = (reason: AgentSessionImportSkipReason) => + Option.some({ + _tag: "Skipped", + skipped: { provider: candidate.source, filePath: transcript.filePath, reason }, + }); const completed = completedByFile.get( `${candidate.providerInstanceId}\0${transcript.filePath}`, ); - if (completed === undefined && (transcriptsRemaining === 0 || bytesRemaining === 0)) { - return Option.some({ _tag: "Skipped" }); - } + if (completed === undefined && bytesRemaining === 0) return skip("import_limit"); const stats = yield* statOption(transcript.filePath); - if (Option.isNone(stats) || stats.value.type !== "File") { - return Option.some({ _tag: "Skipped" }); - } + if (Option.isNone(stats) || stats.value.type !== "File") return skip("unreadable"); const identity = transcriptIdentity(transcript.filePath, stats.value); const completedSource = completed?.find( (source) => @@ -1853,23 +1856,12 @@ export const make = Effect.gen(function* () { source: completedSource, }); } - if ( - transcriptsRemaining === 0 || - identity.size > MAX_IMPORTED_TRANSCRIPT_BYTES || - identity.size > bytesRemaining - ) { - return Option.some({ _tag: "Skipped" }); - } - transcriptsRemaining -= 1; + if (identity.size > MAX_IMPORTED_TRANSCRIPT_BYTES) return skip("too_large"); + if (identity.size > bytesRemaining) return skip("import_limit"); bytesRemaining -= identity.size; const snapshot = yield* readTranscript(transcript.filePath, identity, candidate.source); - if (snapshot === null) { - return Option.some({ _tag: "Skipped" }); - } - - if (Option.isNone(snapshot.cwd)) { - return Option.some({ _tag: "Skipped" }); - } + if (typeof snapshot === "string") return skip(snapshot); + if (Option.isNone(snapshot.cwd)) return skip("outside_project"); const expandedCwd = expandHomePath( projectCwd(snapshot.cwd.value, transcript.projectRoots).trim(), homeDir, @@ -1878,7 +1870,7 @@ export const make = Effect.gen(function* () { !path.isAbsolute(expandedCwd) || (yield* directoryIdentity(path.resolve(expandedCwd))) !== rootIdentity ) { - return Option.some({ _tag: "Skipped" }); + return skip("outside_project"); } const inheritedRecords = @@ -1901,9 +1893,7 @@ export const make = Effect.gen(function* () { : [...inheritedRecords, ...snapshot.records], snapshot.claudeFields, ); - if (parsedThread === null) { - return Option.some({ _tag: "Skipped" }); - } + if (parsedThread === null) return skip("no_conversation"); let savedTitle: string | undefined; if (candidate.source === "codex") { const names = diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 08a2756bfbe6c..c403e9550df57 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2169,6 +2169,13 @@ export const layerWsRpc = ( message: cause.message, cause, }), + ProviderInputTooLongError: (cause) => + new OrchestrationV2ThreadLaunchError({ + commandId: input.commandId, + projectId: input.projectId, + message: cause.message, + cause, + }), ThreadLaunchError: (cause) => new OrchestrationV2ThreadLaunchError({ commandId: input.commandId, diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index c66f05ff7903a..4d68f3a5ad264 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -43,6 +43,7 @@ import { ProviderDriverKind, ProviderInstanceId, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, + PROVIDER_SEND_TURN_MAX_INPUT_CHARS, } from "@t3tools/contracts"; import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection"; import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; @@ -181,6 +182,7 @@ import { threadContextReference, environmentContextRecord, environmentContextReference, + oversizedComposerContextLabels, } from "~/lib/composerContextRecords"; import { rememberCopiedComposerAttachments } from "~/lib/copiedComposerAttachments"; import { useThreadContextDrop, threadContextDropTargetProps } from "./threadContextDrag"; @@ -233,7 +235,7 @@ import { observeResize } from "~/lib/observeResize"; const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError); import { toastManager } from "../ui/toast"; -import { BuildingIcon, PlayIcon } from "lucide-react"; +import { BuildingIcon, PlayIcon, ScissorsIcon } from "lucide-react"; import { Button } from "../ui/button"; import { useManagedPolicy } from "../../state/managedPolicy"; import { hasProviderSetup } from "./ProviderStatusBanner"; @@ -2475,12 +2477,29 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }), }, ]; + const oversizedContextLabels = oversizedComposerContextLabels({ + terminalContexts: composerTerminalContexts, + reviewComments: composerReviewComments, + }); + const bannerItemsWithContextWarning: readonly ComposerBannerStackItem[] = + oversizedContextLabels.length === 0 + ? bannerItems + : [ + ...bannerItems, + { + id: "oversized-context", + variant: "warning", + icon: , + title: "Attached context will be cut when sent", + description: `${oversizedContextLabels.join(", ")} ${oversizedContextLabels.length === 1 ? "is" : "are"} longer than ${PROVIDER_SEND_TURN_MAX_INPUT_CHARS.toLocaleString("en-US")} characters, so only the start will be sent. Select less to send all of it.`, + }, + ]; const shelfItems = hasBlockingComposerTopDrawer - ? bannerItems.filter( + ? bannerItemsWithContextWarning.filter( (item) => item.group === "environment" && (item.variant === "error" || item.variant === "warning"), ) - : bannerItems; + : bannerItemsWithContextWarning; const insertComposerText = ( text: string, diff --git a/apps/web/src/components/chat/composerSubmission.test.ts b/apps/web/src/components/chat/composerSubmission.test.ts index 23e85c9c644b6..7b816b24ff1a7 100644 --- a/apps/web/src/components/chat/composerSubmission.test.ts +++ b/apps/web/src/components/chat/composerSubmission.test.ts @@ -49,7 +49,7 @@ describe("submitComposerDraft", () => { expect(dispatchedDrafts).toEqual([]); expect(draft).toHaveLength(PROVIDER_SEND_TURN_MAX_INPUT_CHARS + 1); expect(validationMessage).toBe( - "Prompt is 1 character over the 120,000-character limit. Shorten or split it before sending.", + "Prompt is 1 character over the 120,000-character limit, including attached context. Shorten or split it before sending.", ); expect(preventDefault).toHaveBeenCalledOnce(); @@ -74,7 +74,7 @@ describe("submitComposerDraft", () => { expect(result).toEqual({ validationMessage: - "Prompt is 18 characters over the 120,000-character limit. Shorten or split it before sending.", + "Prompt is 18 characters over the 120,000-character limit, including attached context. Shorten or split it before sending.", didDispatch: false, }); expect(draft).toHaveLength(PROVIDER_SEND_TURN_MAX_INPUT_CHARS); @@ -130,7 +130,7 @@ describe("submitComposerDraft", () => { expect(result).toEqual({ validationMessage: - "Prompt is 1 character over the 120,000-character limit. Shorten or split it before sending.", + "Prompt is 1 character over the 120,000-character limit, including attached context. Shorten or split it before sending.", didDispatch: false, }); expect(onSend).not.toHaveBeenCalled(); @@ -161,7 +161,7 @@ describe("submitComposerDraft", () => { expect(result).toEqual({ validationMessage: - "Prompt is 1 character over the 120,000-character limit. Shorten or split it before sending.", + "Prompt is 1 character over the 120,000-character limit, including attached context. Shorten or split it before sending.", didDispatch: false, }); expect(onSend).not.toHaveBeenCalled(); diff --git a/apps/web/src/components/chat/composerSubmission.ts b/apps/web/src/components/chat/composerSubmission.ts index 2f9ffe0ddbd26..ccae9e9e45c1c 100644 --- a/apps/web/src/components/chat/composerSubmission.ts +++ b/apps/web/src/components/chat/composerSubmission.ts @@ -1,5 +1,5 @@ -import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts"; import { expandAssistantCitationsForProvider } from "@t3tools/shared/assistantCitations"; +import { promptLengthErrorMessage } from "@t3tools/shared/composerContextReferences"; type ComposerSubmitEvent = { preventDefault: () => void }; @@ -11,15 +11,9 @@ type ComposerSubmissionInput = { export function getComposerPromptLengthValidationMessage(prompt: string): string | null { const normalizedPrompt = prompt.trim(); - const inputLength = Math.max( - normalizedPrompt.length, - expandAssistantCitationsForProvider(normalizedPrompt).length, + return promptLengthErrorMessage( + Math.max(normalizedPrompt.length, expandAssistantCitationsForProvider(normalizedPrompt).length), ); - const excessCharacters = inputLength - PROVIDER_SEND_TURN_MAX_INPUT_CHARS; - if (excessCharacters <= 0) return null; - - const characterLabel = excessCharacters === 1 ? "character" : "characters"; - return `Prompt is ${excessCharacters.toLocaleString("en-US")} ${characterLabel} over the ${PROVIDER_SEND_TURN_MAX_INPUT_CHARS.toLocaleString("en-US")}-character limit. Shorten or split it before sending.`; } export function getComposerSubmissionValidationMessage( diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index cc68f956aea5f..0638e87994faa 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -112,6 +112,7 @@ import { readEnvironmentScope } from "../../state/session"; import { useOrchestrationCommand } from "../../state/use-orchestration-command"; import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, + projectComposerContextForProvider, threadContextsOutsideEnvironment, } from "@t3tools/shared/composerContextReferences"; import { @@ -801,7 +802,12 @@ export function useComposerSend(input: ComposerSendInput) { effort: ctxSelectedPromptEffort, text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, }); - if (composerRef.current?.validateProviderInput(outgoingMessageText) === false) { + // The provider receives attached context rendered into the prompt, so measure that. + const projectedProviderInput = projectComposerContextForProvider({ + text: outgoingMessageText, + records: outgoingMessageContext?.records ?? [], + }); + if (composerRef.current?.validateProviderInput(projectedProviderInput) === false) { return; } diff --git a/apps/web/src/components/chat/useComposerStash.ts b/apps/web/src/components/chat/useComposerStash.ts index 1d480dcf150e1..b390858d684f8 100644 --- a/apps/web/src/components/chat/useComposerStash.ts +++ b/apps/web/src/components/chat/useComposerStash.ts @@ -19,12 +19,7 @@ import { useComposerDraftStore, } from "../../composerDraftStore"; import { type ComposerPromptEditorHandle } from "../ComposerPromptEditorTiptap"; -import { - MAX_STASH_ENTRIES, - type PromptStashEntry, - partitionStashAttachments, - usePromptStashStore, -} from "../../promptStashStore"; +import { type PromptStashEntry, usePromptStashStore } from "../../promptStashStore"; import { type PendingUserInput } from "../../session-logic"; import { type ReviewCommentContext } from "../../reviewCommentContext"; import { collapseExpandedComposerCursor } from "../../composer-logic"; @@ -379,7 +374,7 @@ export function useComposerStash(input: { const missingImageReasons: string[] = []; if (entry.droppedImageNames.length > 0) { missingImageReasons.push( - `${entry.droppedImageNames.join(", ")} exceeded the stash size limit when this prompt was saved.`, + `${entry.droppedImageNames.join(", ")} did not fit in browser storage when this prompt was saved.`, ); } if (entry.unreadableImageNames && entry.unreadableImageNames.length > 0) { @@ -525,7 +520,7 @@ export function useComposerStash(input: { // crash or closed tab mid-encode still leaves the prompt recoverable, // while clearing before the async image work means edits typed during // encoding are not wiped. - const { evicted, written, durable } = stashEntryToQueue({ + const { written, durable, storageFull } = stashEntryToQueue({ id: entryId, createdAt: new Date().toISOString(), prompt, @@ -544,8 +539,9 @@ export function useComposerStash(input: { toastManager.add({ type: "error", title: "Could not stash this prompt", - description: - "Browser storage rejected the write, so the composer was left as-is. Free up site data and try again.", + description: storageFull + ? "Browser storage is full. Your earlier stashed prompts are unchanged and this one stays in the composer. Delete stashed prompts you no longer need, then try again." + : "Browser storage rejected the write. Your earlier stashed prompts are unchanged and this one stays in the composer.", data: { hideCopyButton: true }, }); return; @@ -579,22 +575,6 @@ export function useComposerStash(input: { setComposerTrigger(null); pulseStashBadge(); - if (evicted) { - for (const file of evicted.files ?? []) { - releasePersistedAttachmentUpload({ - id: file.id, - environmentId: file.environmentId, - attachmentId: file.attachmentId, - }); - } - toastManager.add({ - type: "warning", - title: "Oldest stashed prompt discarded", - description: `The stash holds ${MAX_STASH_ENTRIES} prompts; the oldest was removed to make room.`, - data: { hideCopyButton: true }, - }); - } - // Images are re-encoded for the stash rather than stored verbatim: the // composer allows up to 10MB per image, but localStorage gives the whole // origin ~5MB. @@ -620,15 +600,24 @@ export function useComposerStash(input: { : {}), }); } - const { kept, droppedNames } = partitionStashAttachments(candidateAttachments); - - const { attached, durable: imagesDurable } = finalizeStashEntryImages(entryId, { - attachments: kept, - droppedImageNames: [...oversizedImageNames, ...droppedNames], + const { + attached, + durable: imagesDurable, + storageDroppedImageNames, + } = finalizeStashEntryImages(entryId, { + attachments: candidateAttachments, + droppedImageNames: oversizedImageNames, unreadableImageNames, }); if (attached) { - if (!imagesDurable && durable && images.length > 0) { + if (storageDroppedImageNames.length > 0 && imagesDurable) { + toastManager.add({ + type: "warning", + title: "Some stashed images were not saved", + description: `The stash is at its share of browser storage, which it leaves partly free for drafts, so the prompt was stashed without ${storageDroppedImageNames.join(", ")}. Delete stashed prompts you no longer need to make room.`, + data: { hideCopyButton: true }, + }); + } else if (!imagesDurable && durable && images.length > 0) { toastManager.add({ type: "warning", title: "Stashed images were not saved", @@ -637,11 +626,11 @@ export function useComposerStash(input: { data: { hideCopyButton: true }, }); } - } else if (kept.length > 0) { + } else if (candidateAttachments.length > 0) { toastManager.add({ type: "warning", title: "Stashed images did not attach", - description: `That prompt was restored or deleted before ${kept.length} image${kept.length === 1 ? "" : "s"} finished saving. Re-attach ${kept.length === 1 ? "it" : "them"} if you still need ${kept.length === 1 ? "it" : "them"}.`, + description: `That prompt was restored or deleted before ${candidateAttachments.length} image${candidateAttachments.length === 1 ? "" : "s"} finished saving. Re-attach ${candidateAttachments.length === 1 ? "it" : "them"} if you still need ${candidateAttachments.length === 1 ? "it" : "them"}.`, data: { hideCopyButton: true }, }); } diff --git a/apps/web/src/components/onboarding/WelcomePage.tsx b/apps/web/src/components/onboarding/WelcomePage.tsx index 48171ccf94457..4d86075392e8c 100644 --- a/apps/web/src/components/onboarding/WelcomePage.tsx +++ b/apps/web/src/components/onboarding/WelcomePage.tsx @@ -1,6 +1,7 @@ import { useAuth } from "@clerk/react"; import { useAtomValue } from "@effect/atom-react"; import type { + AgentSessionImportSkippedGroup, AgentSessionProjectCandidate, EnvironmentId, ProjectId, @@ -16,6 +17,7 @@ import { squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { + mergeSkippedImportGroups, AgentSessionSource, AuthProvidersManageScope, AuthRelayReadScope, @@ -52,6 +54,8 @@ import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt"; import { completeOnboarding } from "../../onboarding/firstRun"; import { groupOnboardingProjects, + hasRetryableImportSkips, + skippedImportLabel, partitionOnboardingProjects, onboardingProjectKey, resolveOnboardingLandingProject, @@ -179,7 +183,7 @@ export function WelcomePage({ const completionErrorToastIdRef = useRef | null>(null); const finish = ( projectRef?: ScopedProjectRef, - importWarning?: string, + importWarning?: ImportWarning, importedThreadCount = 0, ) => { if (finishingPromiseRef.current !== null) return finishingPromiseRef.current; @@ -203,8 +207,17 @@ export function WelcomePage({ toastManager.add({ type: "warning", title: "Some history was not imported", - description: importWarning, + description: importWarning.description, timeout: 0, + ...(importWarning.skipped.length === 0 + ? {} + : { + data: { + expandableContent: , + expandableDescriptionTrigger: true, + expandableLabels: { expand: "Show skipped", collapse: "Hide skipped" }, + }, + }), }); } else if (importedThreadCount > 0) { toastManager.add({ @@ -1374,14 +1387,14 @@ function useProjectImport({ readonly holdPageRef: { current: boolean }; readonly onDone: ( projectRef?: ScopedProjectRef, - importWarning?: string, + importWarning?: ImportWarning, importedThreadCount?: number, ) => Promise; }) { const writableEnvironments = useEnvironmentsWithScope(scans, AuthOrchestrationOperateScope); const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); const importThreads = useAtomCommand(agentSessionImport, { reportFailure: false }); - const importWarningRef = useRef(""); + const importWarningRef = useRef(undefined); // Per project, so a retry that skips finished projects still counts their threads. const importedThreadsRef = useRef(new Map()); const importedProjectsRef = useRef(new Map()); @@ -1491,7 +1504,7 @@ function useProjectImport({ return; } setIsImporting(true); - importWarningRef.current = ""; + importWarningRef.current = undefined; lastImportSelectionRef.current = selection.map((candidate) => candidate.key); const importGeneration = importGenerationRef.current; const importedThreads = importedThreadsRef.current; @@ -1502,6 +1515,7 @@ function useProjectImport({ ? selection.filter((candidate) => importedProjects.has(candidate.key)).length : 0; let skippedThreadCount = 0; + let skippedThreads: Array = []; const refreshEnvironments = new Set(); // Resolves false when the run stopped early: a newer run, an unmount, or lost access. const importEach = async () => { @@ -1561,13 +1575,17 @@ function useProjectImport({ (importedThreads.get(candidate.key) ?? 0) + threadImportResult.value.importedCount, ); skippedThreadCount += threadImportResult.value.skippedCount; + skippedThreads = mergeSkippedImportGroups([ + ...skippedThreads, + ...(threadImportResult.value.skipped ?? []), + ]); if (threadImportResult.value.importedCount > 0) { projectsWithImportedHistoryRef.current.set( candidate.key, scopeProjectRef(environmentId, projectId), ); } - if (threadImportResult.value.skippedCount === 0) { + if (!hasRetryableImportSkips(threadImportResult.value)) { importedProjectsCount += 1; importedProjects.set(candidate.key, scopeProjectRef(environmentId, projectId)); } @@ -1589,14 +1607,22 @@ function useProjectImport({ setIsImporting(false); const importedThreadCount = importedThreadTotal(); if (importedProjectsCount < selection.length) { + const warn = (description: string) => { + importWarningRef.current = { description, skipped: skippedThreads }; + }; + const skippedText = `${skippedThreadCount} ${skippedThreadCount === 1 ? "conversation was" : "conversations were"} skipped.`; if (importedThreadCount > 0 && skippedThreadCount > 0) { - importWarningRef.current = `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}. ${skippedThreadCount} ${skippedThreadCount === 1 ? "thread" : "threads"} could not be imported.`; + warn( + `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}. ${skippedText}`, + ); } else if (skippedThreadCount > 0) { - importWarningRef.current = `${skippedThreadCount} ${skippedThreadCount === 1 ? "thread could" : "threads could"} not be imported.`; + warn(skippedText); } else if (importedThreadCount > 0) { - importWarningRef.current = `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}. Some thread history could not be imported.`; + warn( + `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}. Some thread history could not be imported.`, + ); } else { - importWarningRef.current = "Could not import thread history."; + warn("Could not import thread history."); } } finishAfterImport(); @@ -1616,6 +1642,39 @@ function useProjectImport({ }; } +interface ImportWarning { + readonly description: string; + readonly skipped: ReadonlyArray; +} + +function SkippedImportList({ + skipped, +}: { + readonly skipped: ReadonlyArray; +}) { + return ( +
+ {skipped.map((group) => ( +
+
+ {skippedImportLabel(group.reason)} ({group.count}) +
+
    + {group.examples.map((example) => ( +
  • + {example.filePath} +
  • + ))} + {group.count > group.examples.length ? ( +
  • and {(group.count - group.examples.length).toLocaleString("en-US")} more
  • + ) : null} +
+
+ ))} +
+ ); +} + type ImportCandidate = AgentSessionProjectCandidate & { readonly environmentId: EnvironmentId; readonly key: string; diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index dde304da3d03e..b9761b2caf3f2 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -91,7 +91,13 @@ import { import { create } from "zustand"; import { persist, type PersistStorage, type StorageValue } from "zustand/middleware"; import { useShallow } from "zustand/react/shallow"; -import { createDeferredStorage, createMemoryStorage } from "./lib/storage"; +import { + createDeferredStorage, + createMemoryStorage, + isStorageQuotaError, + type DeferredStorageWriteObserver, +} from "./lib/storage"; +import { toastManager } from "./components/ui/toast"; import { getDefaultServerModel } from "./providerModels"; import { replaceComposerContextReferences, @@ -124,6 +130,30 @@ type ComposerPersistState = | { capturedState: ComposerDraftStoreState } | PersistedComposerDraftStoreState; +// One visible warning per failure streak; drafts keep working in memory meanwhile. +function draftWriteObserver(): DeferredStorageWriteObserver { + let warned = false; + return { + onWriteError: (error) => { + console.error("[COMPOSER-DRAFTS] Could not save drafts.", error); + if (warned) return; + warned = true; + toastManager.add({ + type: "error", + title: "Drafts are not being saved", + description: isStorageQuotaError(error) + ? "Browser storage is full, so unsent drafts will be lost on reload. Delete stashed prompts you no longer need to make room." + : "Browser storage rejected the write, so unsent drafts will be lost on reload.", + timeout: 0, + data: { hideCopyButton: true }, + }); + }, + onWriteSuccess: () => { + warned = false; + }, + }; +} + const composerDebouncedStorage = createDeferredStorage>( typeof localStorage !== "undefined" ? localStorage : createMemoryStorage(), (value) => @@ -135,6 +165,7 @@ const composerDebouncedStorage = createDeferredStorage = { diff --git a/apps/web/src/lib/composerContextRecords.test.ts b/apps/web/src/lib/composerContextRecords.test.ts index 4f119f1b45573..4b84d0f870831 100644 --- a/apps/web/src/lib/composerContextRecords.test.ts +++ b/apps/web/src/lib/composerContextRecords.test.ts @@ -1,4 +1,6 @@ import { + COMPOSER_CONTEXT_REVIEW_DIFF_MAX_CHARS, + COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS, type ComposerContextId, EnvironmentId, MessageId, @@ -20,6 +22,7 @@ import { buildMessageContext, composerContextImportLookupIds, isSameComposerContextPayload, + oversizedComposerContextLabels, previewAnnotationContextRecord, previewAnnotationFromRecord, pullRequestContextKindLabel, @@ -32,6 +35,7 @@ import { terminalContextDraftFromRecord, uploadedAttachmentContextRecord, } from "./composerContextRecords"; +import { formatTerminalContextLabel } from "./terminalContext"; const decodeMessageContext = Schema.decodeUnknownSync(OrchestrationMessageContext); @@ -265,28 +269,29 @@ describe("composerContextRecords", () => { }); it("clamps oversized review and terminal selections so the records still encode", () => { - const build = (diffLength: number) => - reviewCommentContextRecord({ - id: "rc-big", - sectionId: "file:a/b.ts", - sectionTitle: "File comment", - filePath: "a/b.ts", - startIndex: 0, - endIndex: 1, - rangeLabel: "L1", - text: "Why?", - diff: "d".repeat(diffLength), - }); + const limit = COMPOSER_CONTEXT_REVIEW_DIFF_MAX_CHARS; + const comment = (diffLength: number) => ({ + id: "rc-big", + sectionId: "file:a/b.ts", + sectionTitle: "File comment", + filePath: "a/b.ts", + startIndex: 0, + endIndex: 1, + rangeLabel: "L1", + text: "Why?", + diff: "d".repeat(diffLength), + }); - const atLimit = build(32_000); - expect(atLimit.diff).toHaveLength(32_000); - const overLimit = build(32_001); - expect(overLimit.diff.length).toBeLessThanOrEqual(32_000); + const atLimit = reviewCommentContextRecord(comment(limit)); + expect(atLimit.diff).toHaveLength(limit); + const overLimit = reviewCommentContextRecord(comment(limit + 1)); + expect(overLimit.diff.length).toBeLessThanOrEqual(limit); expect(overLimit.diff.endsWith("… truncated …")).toBe(true); expect(() => decodeMessageContext({ version: 1, records: [atLimit] })).not.toThrow(); expect(() => decodeMessageContext({ version: 1, records: [overLimit] })).not.toThrow(); - const terminal = terminalContextRecord({ + const kept = COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS - 15; + const terminalDraft = { id: "term-big", threadId: ThreadId.make("t"), createdAt: "2026-01-01T00:00:00.000Z", @@ -294,12 +299,20 @@ describe("composerContextRecords", () => { terminalLabel: "Terminal 1", lineStart: 1, lineEnd: 2_000, - text: `${"t".repeat(63_985)}${"šŸ˜€".repeat(8)}`, - }); - expect(terminal.text).toBe(`${"t".repeat(63_985)}\n… truncated …`); + text: `${"t".repeat(kept)}${"šŸ˜€".repeat(8)}`, + }; + const terminal = terminalContextRecord(terminalDraft); + expect(terminal.text).toBe(`${"t".repeat(kept)}\n… truncated …`); expect(decodeMessageContext({ version: 1, records: [terminal] }).records).toMatchObject([ { kind: "terminal", text: terminal.text }, ]); + + expect( + oversizedComposerContextLabels({ + terminalContexts: [terminalDraft, { ...terminalDraft, id: "small", text: "ok" }], + reviewComments: [comment(limit), comment(limit + 1)], + }), + ).toEqual([formatTerminalContextLabel(terminalDraft), "b.ts L1"]); }); it("finds the destination collision for different legacy terminal messages", () => { diff --git a/apps/web/src/lib/composerContextRecords.ts b/apps/web/src/lib/composerContextRecords.ts index 5f8eda0008cd9..4723daa4e08a3 100644 --- a/apps/web/src/lib/composerContextRecords.ts +++ b/apps/web/src/lib/composerContextRecords.ts @@ -204,6 +204,29 @@ export function terminalContextRecord(context: TerminalContextDraft): TerminalCo }; } +/** Labels of draft context that sending would cut, so the composer can say so first. */ +export function oversizedComposerContextLabels(input: { + readonly terminalContexts: ReadonlyArray; + readonly reviewComments: ReadonlyArray; +}): string[] { + return [ + ...input.terminalContexts + .filter( + (context) => + normalizeTerminalContextText(context.text).length > + COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS, + ) + .map(formatTerminalContextLabel), + ...input.reviewComments + .filter( + (comment) => + comment.text.length > COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS || + comment.diff.length > COMPOSER_CONTEXT_REVIEW_DIFF_MAX_CHARS, + ) + .map(reviewCommentContextLabel), + ]; +} + export function reviewCommentContextRecord( comment: ReviewCommentContext, ): ReviewCommentContextRecord { diff --git a/apps/web/src/lib/storage.test.ts b/apps/web/src/lib/storage.test.ts new file mode 100644 index 0000000000000..1f8e1bdb7d8d7 --- /dev/null +++ b/apps/web/src/lib/storage.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +import { createDeferredStorage, createMemoryStorage, isStorageQuotaError } from "./storage"; + +describe("createDeferredStorage", () => { + it("reports a failed write and keeps the last saved value", () => { + const base = createMemoryStorage(); + const onWriteError = vi.fn(); + const onWriteSuccess = vi.fn(); + const storage = createDeferredStorage(base, (value) => value, 0, { + onWriteError, + onWriteSuccess, + }); + storage.setItem("drafts", "first"); + storage.flush(); + expect(onWriteSuccess).toHaveBeenCalledOnce(); + + const quota = new DOMException("full", "QuotaExceededError"); + { + using _full = vi.spyOn(base, "setItem").mockImplementation(() => { + throw quota; + }); + storage.setItem("drafts", "second"); + expect(() => storage.flush()).not.toThrow(); + } + expect(onWriteError).toHaveBeenCalledWith(quota); + expect(isStorageQuotaError(onWriteError.mock.calls[0]?.[0])).toBe(true); + expect(base.getItem("drafts")).toBe("first"); + }); +}); diff --git a/apps/web/src/lib/storage.ts b/apps/web/src/lib/storage.ts index 948b8f427f971..c58704dcb79be 100644 --- a/apps/web/src/lib/storage.ts +++ b/apps/web/src/lib/storage.ts @@ -42,15 +42,37 @@ export function resolveStorage(storage: Partial | null | undefined return isStateStorage(storage) ? storage : createMemoryStorage(); } +/** Browsers name a full quota differently; Firefox used NS_ERROR_DOM_QUOTA_REACHED. */ +export function isStorageQuotaError(error: unknown): boolean { + return ( + error instanceof DOMException && + (error.name === "QuotaExceededError" || error.name === "NS_ERROR_DOM_QUOTA_REACHED") + ); +} + +export interface DeferredStorageWriteObserver { + /** A debounced write threw; the previous saved value is still in storage. */ + readonly onWriteError: (error: unknown) => void; + readonly onWriteSuccess: () => void; +} + export function createDeferredStorage( baseStorage: Partial | null | undefined, serialize: (value: TValue) => string, debounceMs: number = 300, + observer?: DeferredStorageWriteObserver, ): DeferredStorage { const resolvedStorage = resolveStorage(baseStorage); const debouncedSetItem = new Debouncer( (name: string, value: TValue) => { - resolvedStorage.setItem(name, serialize(value)); + try { + resolvedStorage.setItem(name, serialize(value)); + } catch (error) { + if (observer === undefined) throw error; + observer.onWriteError(error); + return; + } + observer?.onWriteSuccess(); }, { wait: debounceMs }, ); diff --git a/apps/web/src/onboarding/projectImport.logic.test.ts b/apps/web/src/onboarding/projectImport.logic.test.ts index 10cb0d731ee75..c7e7d10ad0970 100644 --- a/apps/web/src/onboarding/projectImport.logic.test.ts +++ b/apps/web/src/onboarding/projectImport.logic.test.ts @@ -2,6 +2,7 @@ import { EnvironmentId, ProjectId, type AgentSessionProjectCandidate } from "@t3 import { describe, expect, it } from "vite-plus/test"; import { + hasRetryableImportSkips, groupOnboardingProjects, isNewOnboardingProject, partitionOnboardingProjects, @@ -252,3 +253,25 @@ describe("projects on multiple computers", () => { expect(partitionOnboardingProjects([first, second], now).recent).toEqual([first, second]); }); }); + +describe("hasRetryableImportSkips", () => { + it("keeps a project unfinished only for skips another import could change", () => { + const group = (reason: "no_conversation" | "import_limit", count: number) => ({ + reason, + count, + examples: [], + }); + expect( + hasRetryableImportSkips({ skippedCount: 4, skipped: [group("no_conversation", 4)] }), + ).toBe(false); + expect( + hasRetryableImportSkips({ + skippedCount: 5, + skipped: [group("no_conversation", 4), group("import_limit", 1)], + }), + ).toBe(true); + // Older servers report only a count. + expect(hasRetryableImportSkips({ skippedCount: 1 })).toBe(true); + expect(hasRetryableImportSkips({ skippedCount: 0 })).toBe(false); + }); +}); diff --git a/apps/web/src/onboarding/projectImport.logic.ts b/apps/web/src/onboarding/projectImport.logic.ts index 1be9c7b824b2a..0b3a13433118d 100644 --- a/apps/web/src/onboarding/projectImport.logic.ts +++ b/apps/web/src/onboarding/projectImport.logic.ts @@ -2,7 +2,14 @@ import { findProjectByPath, normalizeProjectPathForComparison, } from "@t3tools/client-runtime/state/projects"; -import type { AgentSessionProjectCandidate, EnvironmentId, ProjectId } from "@t3tools/contracts"; +import type { + AgentSessionImportResult, + AgentSessionImportSkipReason, + AgentSessionImportSkippedGroup, + AgentSessionProjectCandidate, + EnvironmentId, + ProjectId, +} from "@t3tools/contracts"; const RECENT_PROJECT_WINDOW_MS = 30 * 24 * 60 * 60 * 1000; const DEFAULT_SELECTION_MIN_THREADS = 3; @@ -163,3 +170,33 @@ export function splitOnboardingProjectPath(path: string): { export function onboardingProjectKey(environmentId: EnvironmentId, path: string): string { return JSON.stringify([environmentId, path]); } + +const SKIP_REASON_LABELS: Record = { + too_large: "Too large to import", + import_limit: "Over this import's 4 GiB read limit. Import again to continue", + changed_while_reading: "Changed while being read. Import again to retry", + unreadable: "Could not be read", + outside_project: "Belongs to a different folder", + no_conversation: "Has no user messages", + unresumable: "Has a session ID the agent cannot resume", + import_failed: "Could not be saved", +}; + +export function skippedImportLabel(reason: AgentSessionImportSkipReason): string { + return SKIP_REASON_LABELS[reason]; +} + +/** Skips that importing again cannot change do not keep a project marked unfinished. */ +const PERMANENT_SKIP_REASONS: ReadonlySet = new Set([ + "no_conversation", +]); + +export function hasRetryableImportSkips( + result: Pick, +): boolean { + if (result.skipped === undefined) return result.skippedCount > 0; + return result.skipped.some( + (group: AgentSessionImportSkippedGroup) => + group.count > 0 && !PERMANENT_SKIP_REASONS.has(group.reason), + ); +} diff --git a/apps/web/src/promptStashStore.test.ts b/apps/web/src/promptStashStore.test.ts index 0b6bcf79a4fa2..b0e0654897cbd 100644 --- a/apps/web/src/promptStashStore.test.ts +++ b/apps/web/src/promptStashStore.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; import { collectAssistantCitations, @@ -8,10 +8,10 @@ import { import { removeLocalStorageItem } from "./hooks/useLocalStorage"; import { - MAX_STASH_ENTRIES, PROMPT_STASH_STORAGE_KEY, - MAX_STASH_ENTRY_ATTACHMENT_CHARS, - partitionStashAttachments, + STASH_IMAGE_STORAGE_BUDGET_CHARS, + keepImagesThatFit, + promptStashStorageForTest, usePromptStashStore, writePromptStashStorageForTest, type PromptStashEntry, @@ -48,32 +48,51 @@ function resetPromptStashStore() { removeLocalStorageItem(PROMPT_STASH_STORAGE_KEY); } -describe("partitionStashAttachments", () => { - it("keeps attachments within the budget and reports dropped names in order", () => { - const small = { - id: "a", - name: "small.png", - mimeType: "image/png", - sizeBytes: 10, - dataUrl: "x".repeat(10), - }; - const huge = { - id: "b", - name: "huge.png", - mimeType: "image/png", - sizeBytes: MAX_STASH_ENTRY_ATTACHMENT_CHARS, - dataUrl: "x".repeat(MAX_STASH_ENTRY_ATTACHMENT_CHARS), - }; - const alsoSmall = { - id: "c", - name: "also-small.png", - mimeType: "image/png", - sizeBytes: 10, - dataUrl: "x".repeat(10), - }; - const { kept, droppedNames } = partitionStashAttachments([small, huge, alsoSmall]); - expect(kept.map((attachment) => attachment.id)).toEqual(["a", "c"]); - expect(droppedNames).toEqual(["huge.png"]); +describe("keepImagesThatFit", () => { + const image = (id: string, chars: number) => ({ + id, + name: `${id}.png`, + mimeType: "image/png", + sizeBytes: chars, + dataUrl: "x".repeat(chars), + }); + + it("keeps every image that storage accepts, dropping the largest first when it is full", () => { + const images = [image("small", 10), image("huge", 1_000), image("medium", 100)]; + const writes: Array> = []; + const fits = keepImagesThatFit(images, (kept) => { + writes.push(kept.map((attachment) => attachment.id)); + return { written: true, storageFull: false }; + }); + expect(fits.kept).toEqual(images); + expect(fits.droppedNames).toEqual([]); + + writes.length = 0; + const full = keepImagesThatFit(images, (kept, dropped) => { + writes.push([...kept.map((attachment) => attachment.id), ...dropped]); + const written = kept.reduce((sum, attachment) => sum + attachment.dataUrl.length, 0) < 50; + return { written, storageFull: !written }; + }); + expect(full.kept.map((attachment) => attachment.id)).toEqual(["small"]); + expect(full.droppedNames).toEqual(["huge.png", "medium.png"]); + expect(writes).toEqual([ + ["small", "huge", "medium"], + ["small", "medium", "huge.png"], + ["small", "huge.png", "medium.png"], + ]); + + const nothingFits = keepImagesThatFit(images, () => ({ written: false, storageFull: true })); + expect(nothingFits.kept).toEqual([]); + expect(nothingFits.result.written).toBe(false); + + // A failure other than a full quota is not fixed by dropping images. + let attempts = 0; + const broken = keepImagesThatFit(images, () => { + attempts += 1; + return { written: false, storageFull: false }; + }); + expect(attempts).toBe(1); + expect(broken.kept).toEqual(images); }); }); @@ -114,16 +133,66 @@ describe("promptStashStore", () => { expect(usePromptStashStore.getState().takeEntry("citation-stash").entry).toBeNull(); }); - it("evicts the oldest entry past the cap and returns it", () => { + it("keeps every stashed entry, newest first", () => { const store = usePromptStashStore.getState(); - for (let index = 0; index < MAX_STASH_ENTRIES; index += 1) { - expect(store.stashEntry(makeEntry({ id: `entry-${index}` })).evicted).toBeNull(); + for (let index = 0; index < 50; index += 1) { + expect(store.stashEntry(makeEntry({ id: `entry-${index}` })).written).toBe(true); } - const { evicted } = store.stashEntry(makeEntry({ id: "overflow" })); - expect(evicted?.id).toBe("entry-0"); const entries = usePromptStashStore.getState().entries; - expect(entries).toHaveLength(MAX_STASH_ENTRIES); - expect(entries[0]?.id).toBe("overflow"); + expect(entries).toHaveLength(50); + expect(entries[0]?.id).toBe("entry-49"); + expect(entries.at(-1)?.id).toBe("entry-0"); + }); + + it("keeps existing entries intact when a write hits the storage quota", () => { + const store = usePromptStashStore.getState(); + store.stashEntry(makeEntry({ id: "kept-1" })); + store.stashEntry(makeEntry({ id: "kept-2" })); + const storage = promptStashStorageForTest(); + const saved = storage.getItem(PROMPT_STASH_STORAGE_KEY); + { + using _full = vi.spyOn(storage, "setItem").mockImplementation(() => { + throw new DOMException("full", "QuotaExceededError"); + }); + expect(store.stashEntry(makeEntry({ id: "rejected" }))).toEqual({ + written: false, + durable: false, + storageFull: true, + }); + } + { + using _denied = vi.spyOn(storage, "setItem").mockImplementation(() => { + throw new DOMException("denied", "SecurityError"); + }); + expect(store.stashEntry(makeEntry({ id: "denied" })).storageFull).toBe(false); + } + expect(usePromptStashStore.getState().entries.map((entry) => entry.id)).toEqual([ + "kept-2", + "kept-1", + ]); + expect(storage.getItem(PROMPT_STASH_STORAGE_KEY)).toBe(saved); + }); + + it("leaves images out once the stash would pass its share of storage", () => { + const store = usePromptStashStore.getState(); + store.stashEntry({ ...makeEntry({ id: "big-images" }), pendingImageCount: 2 }); + const image = (id: string, chars: number) => ({ + id, + name: `${id}.png`, + mimeType: "image/png", + sizeBytes: chars, + dataUrl: "x".repeat(chars), + }); + const result = store.finalizeEntryImages("big-images", { + attachments: [image("small", 1_000), image("huge", STASH_IMAGE_STORAGE_BUDGET_CHARS)], + droppedImageNames: [], + unreadableImageNames: [], + }); + expect(result.storageDroppedImageNames).toEqual(["huge.png"]); + expect(usePromptStashStore.getState().entries[0]).toMatchObject({ + attachments: [{ id: "small" }], + droppedImageNames: ["huge.png"], + }); }); // regression: #4787 stashed prompts were lost when switching providers diff --git a/apps/web/src/promptStashStore.ts b/apps/web/src/promptStashStore.ts index 099353cad284e..522bf7c1fdbeb 100644 --- a/apps/web/src/promptStashStore.ts +++ b/apps/web/src/promptStashStore.ts @@ -6,16 +6,12 @@ import { PersistedComposerFileAttachment, PersistedComposerImageAttachment, } from "./composerDraftStore"; -import { createMemoryStorage, type StateStorage } from "./lib/storage"; +import { createMemoryStorage, isStorageQuotaError, type StateStorage } from "./lib/storage"; export const PROMPT_STASH_STORAGE_KEY = "t3code:prompt-stash:v2"; const LEGACY_PROMPT_STASH_STORAGE_KEY = "t3code:prompt-stash:v1"; const PROMPT_STASH_STORAGE_VERSION = 2; -export const MAX_STASH_ENTRIES = 20; -// Share localStorage's ~5MB quota with drafts; record oversized attachments in droppedImageNames. -export const MAX_STASH_ENTRY_ATTACHMENT_CHARS = 2_700_000; - const StashEntrySchema = Schema.Struct({ id: Schema.String, createdAt: Schema.String, @@ -57,24 +53,36 @@ function clearOrphanedPendingImages( }); } -export function partitionStashAttachments( +/** + * Write every image when it fits; when storage is full, drop the largest until the + * write succeeds, and report what was dropped. + */ +export function keepImagesThatFit< + Result extends { readonly written: boolean; readonly storageFull: boolean }, +>( attachments: ReadonlyArray, + write: ( + kept: ReadonlyArray, + droppedNames: ReadonlyArray, + ) => Result, ): { - kept: PersistedComposerImageAttachment[]; + kept: ReadonlyArray; droppedNames: string[]; + result: Result; } { - const kept: PersistedComposerImageAttachment[] = []; + let kept = [...attachments]; const droppedNames: string[] = []; - let usedChars = 0; - for (const attachment of attachments) { - if (usedChars + attachment.dataUrl.length > MAX_STASH_ENTRY_ATTACHMENT_CHARS) { - droppedNames.push(attachment.name); - continue; + for (;;) { + const result = write(kept, droppedNames); + if (result.written || !result.storageFull || kept.length === 0) { + return { kept, droppedNames, result }; } - usedChars += attachment.dataUrl.length; - kept.push(attachment); + const largest = kept.reduce((max, attachment) => + attachment.dataUrl.length > max.dataUrl.length ? attachment : max, + ); + kept = kept.filter((attachment) => attachment !== largest); + droppedNames.push(largest.name); } - return { kept, droppedNames }; } // Accessing localStorage itself can throw SecurityError before get/set. @@ -89,26 +97,38 @@ function resolveBaseStorage(): { storage: StateStorage; durable: boolean } { const { storage: baseStashStorage, durable: storageIsDurable } = resolveBaseStorage(); +/** + * localStorage holds ~5M characters per origin, shared with drafts. Images stop being + * stashed past ~60% of that so drafts keep room to save. + */ +export const STASH_IMAGE_STORAGE_BUDGET_CHARS = 3_000_000; + +function serializeEntries(entries: ReadonlyArray): string { + return JSON.stringify({ version: PROMPT_STASH_STORAGE_VERSION, state: { entries } }); +} + +interface PersistResult { + readonly written: boolean; + readonly durable: boolean; + /** Only a quota error means storage is full; other failures say nothing about space. */ + readonly storageFull: boolean; +} + // Clear the composer only after a durable write; debounce cannot confirm durability. -function persistEntries(entries: ReadonlyArray): { - written: boolean; - durable: boolean; -} { +function persistSerialized(serialized: string): PersistResult { try { - baseStashStorage.setItem( - PROMPT_STASH_STORAGE_KEY, - JSON.stringify({ - version: PROMPT_STASH_STORAGE_VERSION, - state: { entries }, - }), - ); - return { written: true, durable: storageIsDurable }; + baseStashStorage.setItem(PROMPT_STASH_STORAGE_KEY, serialized); + return { written: true, durable: storageIsDurable, storageFull: false }; } catch (error) { - console.error("[PROMPT-STASH] Could not persist stash (storage quota?).", error); - return { written: false, durable: false }; + console.error("[PROMPT-STASH] Could not persist stash.", error); + return { written: false, durable: false, storageFull: isStorageQuotaError(error) }; } } +function persistEntries(entries: ReadonlyArray): PersistResult { + return persistSerialized(serializeEntries(entries)); +} + function readPersistedEntries(): ReadonlyArray | null { try { const raw = baseStashStorage.getItem(PROMPT_STASH_STORAGE_KEY); @@ -125,15 +145,18 @@ function readPersistedEntries(): ReadonlyArray | null { interface PromptStashStoreState { entries: ReadonlyArray; stashEntry: (entry: PromptStashEntry) => { - evicted: PromptStashEntry | null; /** False when the write failed outright (e.g. quota); nothing was kept. */ written: boolean; + storageFull: boolean; /** False for failed writes or in-memory fallback; the entry will not survive reload. */ durable: boolean; }; /** durable=false means removal was not persisted and reload would restore the entry. */ takeEntry: (entryId: string) => { entry: PromptStashEntry | null; durable: boolean }; - /** attached=false means the entry disappeared while encoding, so images could not be saved. */ + /** + * attached=false means the entry disappeared while encoding, so images could not be saved. + * storageDroppedImageNames lists images left out because browser storage was full. + */ finalizeEntryImages: ( entryId: string, images: { @@ -141,21 +164,20 @@ interface PromptStashStoreState { droppedImageNames: ReadonlyArray; unreadableImageNames: ReadonlyArray; }, - ) => { attached: boolean; durable: boolean }; + ) => { attached: boolean; durable: boolean; storageDroppedImageNames: ReadonlyArray }; } export const usePromptStashStore = create()((set, get) => ({ entries: [], stashEntry: (entry) => { const nextEntries = [entry, ...get().entries]; - const evicted = nextEntries.length > MAX_STASH_ENTRIES ? (nextEntries.pop() ?? null) : null; - const { written, durable } = persistEntries(nextEntries); - // Failed writes must not duplicate the intact composer; eviction also commits only on success. + const { written, durable, storageFull } = persistEntries(nextEntries); + // A failed write keeps the existing stash and the intact composer; nothing is evicted. if (!written) { - return { evicted: null, written: false, durable: false }; + return { written: false, durable: false, storageFull }; } set(() => ({ entries: nextEntries })); - return { evicted, written: true, durable }; + return { written: true, durable, storageFull: false }; }, takeEntry: (entryId) => { const entries = get().entries; @@ -170,18 +192,33 @@ export const usePromptStashStore = create()((set, get) => const entries = get().entries; const index = entries.findIndex((candidate) => candidate.id === entryId); const existing = index === -1 ? undefined : entries[index]; - if (!existing) return { attached: false, durable: true }; - const nextEntries = [...entries]; - nextEntries[index] = { - ...existing, - attachments: images.attachments, - droppedImageNames: images.droppedImageNames, - unreadableImageNames: images.unreadableImageNames, - pendingImageCount: 0, + if (!existing) return { attached: false, durable: true, storageDroppedImageNames: [] }; + const withImages = ( + attachments: ReadonlyArray, + storageDroppedImageNames: ReadonlyArray, + ) => { + const nextEntries = [...entries]; + nextEntries[index] = { + ...existing, + attachments, + droppedImageNames: [...images.droppedImageNames, ...storageDroppedImageNames], + unreadableImageNames: images.unreadableImageNames, + pendingImageCount: 0, + }; + return nextEntries; }; - const { durable } = persistEntries(nextEntries); - set(() => ({ entries: nextEntries })); - return { attached: true, durable }; + const { kept, droppedNames, result } = keepImagesThatFit( + images.attachments, + (attachments, dropped) => { + const serialized = serializeEntries(withImages(attachments, dropped)); + // Over the image budget counts as full, so drafts keep their share of the quota. + return attachments.length > 0 && serialized.length > STASH_IMAGE_STORAGE_BUDGET_CHARS + ? { written: false, durable: false, storageFull: true } + : persistSerialized(serialized); + }, + ); + set(() => ({ entries: withImages(kept, droppedNames) })); + return { attached: true, durable: result.durable, storageDroppedImageNames: droppedNames }; }, })); @@ -199,3 +236,7 @@ export function writePromptStashStorageForTest(raw: string): void { baseStashStorage.setItem(PROMPT_STASH_STORAGE_KEY, raw); usePromptStashStore.setState({ entries: readPersistedEntries() ?? [] }); } + +export function promptStashStorageForTest(): StateStorage { + return baseStashStorage; +} diff --git a/apps/web/src/rpc/requestLatencyState.ts b/apps/web/src/rpc/requestLatencyState.ts index c95ddae2afcde..6705b448448cb 100644 --- a/apps/web/src/rpc/requestLatencyState.ts +++ b/apps/web/src/rpc/requestLatencyState.ts @@ -35,6 +35,8 @@ const untrackedRpcAckMethods = new Set([ WS_METHODS.sourceControlSignInWait, ]); const longRunningRpcAckMethods = new Set([ + // One request imports a whole project's history; the Welcome page shows it is busy. + WS_METHODS.agentSessionsImport, WS_METHODS.serverUpdateProvider, WS_METHODS.serverRefreshProviders, WS_METHODS.serverUpdateServer, diff --git a/docs/user/composer.md b/docs/user/composer.md index df880e49c6ca5..67fc0c9a3ebc8 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -3,8 +3,10 @@ Give the agent a task in the composer. Add files, quote a previous response, or include a skill when the task needs more context. -Messages can contain up to 120,000 characters. Longer drafts stay in the composer -so you can shorten them or split them into several messages. +Messages can contain up to 120,000 characters, including attached terminal output +and review comments. Longer drafts stay in the composer so you can shorten them or +split them into several messages. A single terminal selection or review comment +longer than that is cut to fit, and the composer warns you before you send it. Pasting 32 KiB or more of text adds that fragment as a text-file attachment so the agent can inspect it without filling the model context. A smaller paste also @@ -192,6 +194,13 @@ the current prompt and its attachments for later. Wait for uploads to finish fir With an empty composer, the same shortcut restores a single stash or opens the stash menu when there are several. +Stashes are kept in browser storage, which holds a few megabytes for the whole +site. There is no limit on the number of stashes; when storage is full, T3 Code +keeps your existing stashes, leaves the new prompt in the composer, and tells you +to delete stashes you no longer need. Images are left out, with a warning, once +the stash would use more than about 60% of that space, so drafts keep room to save. +If drafts cannot be saved, T3 Code tells you. + Stashes containing uploaded files must be restored in their original environment. Those files are retained for 24 hours. After an upload expires, restore the prompt and use **Attach again** or remove the missing file before sending. diff --git a/docs/user/portable-handoffs.md b/docs/user/portable-handoffs.md index 04b2a8ce14987..efb0b43ed7641 100644 --- a/docs/user/portable-handoffs.md +++ b/docs/user/portable-handoffs.md @@ -12,9 +12,10 @@ Codex receives historical messages directly when its installed version supports Other providers receive the same selection as attributed conversation context. A handoff does not copy the outgoing provider's reasoning, tool-call state, or attachments. -The handoff includes references to omitted history. The agent can use T3 Code's thread-reading tool -to retrieve saved messages and activity, including the remainder of a long item. For an important -constraint, you can still repeat it in your next message. A handoff is a budgeted selection, not an +When history is left out, the thread shows a notice saying how many items did not fit, and the +handoff includes references to them. The agent can use T3 Code's thread-reading tool to retrieve +saved messages and activity, including the remainder of a long item. For an important constraint, +you can still repeat it in your next message. A handoff is a budgeted selection, not an agent-written summary. ## Context limits @@ -28,11 +29,14 @@ never shortens your request to make it fit. Recovery leaves running background work intact. Let it finish or stop it before retrying the handoff. -Server operators can set `T3CODE_CONTEXT_HANDOFF_TOKEN_CAP` to change the initial history allowance -(default 16,000; clamped to 1,024–64,000). This is an upper bound, not a provider context-window -guarantee. Text accounting conservatively charges one token per UTF-8 byte, including attribution -and JSON escaping. Imported history has a separate 64,000-byte ceiling; your current input and -attachment payloads do not consume that ceiling. +By default, history may use up to half of the target model's context window, or 200,000 tokens +when the window is unknown. Switching a long thread to a large-window model can therefore send a +lot of history on the first turn, which costs tokens with providers that bill by usage; start a +new thread instead when you do not need the earlier conversation. Server operators can set `T3CODE_CONTEXT_HANDOFF_TOKEN_CAP` to use a +fixed allowance instead (clamped to 1,024–1,000,000). Either way it is an upper bound, not a +provider context-window guarantee. Text accounting conservatively charges one token per UTF-8 byte, +including attribution and JSON escaping. Your current input and attachments do not count against +the allowance. T3 Code uses available capacity information for your selected model and options, together with provider context telemetry. Starting a fresh provider conversation clears prior usage, while keeping diff --git a/docs/user/welcome-page.md b/docs/user/welcome-page.md index f280ace079147..2327c8b1a327a 100644 --- a/docs/user/welcome-page.md +++ b/docs/user/welcome-page.md @@ -81,30 +81,29 @@ offered. A large or malformed history can reach the scan limit. T3 Code keeps the projects it found and warns when projects or conversations may be missing. -Imported projects include Claude, Codex and Pi conversations active within the last -30 days. You can continue those conversations in T3 Code. Pi is off by default: +Imported projects include all of their Claude, Codex and Pi conversations. You can +continue those conversations in T3 Code. Pi is off by default: open **Add more agents** and select **Turn on** next to Pi, and the page looks for its sessions too. Pi sessions are read from each enabled Pi provider's session directory, which follows `PI_CODING_AGENT_SESSION_DIR` and `PI_CODING_AGENT_DIR` in its environment. A Pi conversation imports its active branch, the one Pi reopens. -Conversation import is best effort. T3 Code keeps the first user prompt and the -newest remaining visible user and assistant messages, with 200 messages total. -It omits tool activity and attachments. For Codex, it omits generated setup -context only when a canonical user event and a valid shared turn ID identify the -same user turn. Ambiguous legacy or response-only context stays in the imported -conversation so T3 Code does not remove user text. It reads one conversation at -a time and skips files larger than 4 GiB. It also skips a conversation when the -message text and metadata it keeps need more than 32 MiB of memory. Tool output -does not count toward that limit. It skips a conversation with more than 100,000 -records every time, so opening the page again does not import it. It ignores -malformed records and skips unreadable or unparseable conversations. - -Each import attempt reads up to 100 conversation files and 4 GiB per project. To -continue a large batch, open the Welcome page again and pick the project in -**Review all**. Completed conversations are not imported again. You can continue -without the remaining history. +Conversation import is best effort. T3 Code imports every visible user and +assistant message. It omits tool activity and attachments. For Codex, it omits +generated setup context only when a canonical user event and a valid shared turn +ID identify the same user turn. Ambiguous legacy or response-only context stays +in the imported conversation so T3 Code does not remove user text. It reads one +conversation at a time and ignores malformed records. + +Some conversations are skipped: files larger than 4 GiB, conversations whose +message text and metadata need more than 128 MiB of memory (tool output does not +count), conversations with more than 10 million records, unreadable files, and +sessions with no user messages. Each import attempt reads up to 4 GiB per +project; open the Welcome page again and pick the project in **Review all** to +continue past that. Completed conversations are not imported again. When anything +is skipped, the warning after setup groups the files by reason, with up to 50 +paths per reason. Sessions with no user messages never count against a project. You can start without importing. While an import runs, T3 Code stays on the Welcome page. If you quit, open the Welcome page again from **Settings → About**; the diff --git a/packages/contracts/src/agentSessions.test.ts b/packages/contracts/src/agentSessions.test.ts new file mode 100644 index 0000000000000..07b5a4c9299ee --- /dev/null +++ b/packages/contracts/src/agentSessions.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + AGENT_SESSION_IMPORT_SKIPPED_EXAMPLES, + mergeSkippedImportGroups, +} from "./agentSessions.ts"; + +describe("mergeSkippedImportGroups", () => { + it("sums counts per reason and keeps a bounded list of example paths", () => { + const example = (index: number) => ({ provider: "codex" as const, filePath: `/t/${index}` }); + const many = Array.from({ length: 70 }, (_, index) => ({ + reason: "too_large" as const, + count: 1, + examples: [example(index)], + })); + const merged = mergeSkippedImportGroups([ + ...many, + { reason: "no_conversation", count: 3, examples: [example(100)] }, + { reason: "too_large", count: 5, examples: [] }, + ]); + expect(merged.map((group) => [group.reason, group.count])).toEqual([ + ["too_large", 75], + ["no_conversation", 3], + ]); + expect(merged[0]?.examples).toHaveLength(AGENT_SESSION_IMPORT_SKIPPED_EXAMPLES); + expect(merged[0]?.examples[0]).toEqual(example(0)); + }); +}); diff --git a/packages/contracts/src/agentSessions.ts b/packages/contracts/src/agentSessions.ts index 93e0e36e4fbd4..fd1ac30b27c13 100644 --- a/packages/contracts/src/agentSessions.ts +++ b/packages/contracts/src/agentSessions.ts @@ -72,9 +72,56 @@ export class AgentSessionImportProjectChangedError extends Schema.TaggedError, +): Array { + const merged = new Map(); + for (const group of groups) { + const previous = merged.get(group.reason); + merged.set(group.reason, { + reason: group.reason, + count: (previous?.count ?? 0) + group.count, + examples: [...(previous?.examples ?? []), ...group.examples].slice( + 0, + AGENT_SESSION_IMPORT_SKIPPED_EXAMPLES, + ), + }); + } + return Array.from(merged.values()); +} + export const AgentSessionImportResult = Schema.Struct({ importedCount: NonNegativeInt, skippedCount: NonNegativeInt, + /** Older servers omit it. */ + skipped: Schema.optional(Schema.Array(AgentSessionImportSkippedGroup)), }); export type AgentSessionImportResult = typeof AgentSessionImportResult.Type; diff --git a/packages/contracts/src/composerContext.ts b/packages/contracts/src/composerContext.ts index 834dbd6821323..06e26205799a0 100644 --- a/packages/contracts/src/composerContext.ts +++ b/packages/contracts/src/composerContext.ts @@ -10,6 +10,7 @@ import { ThreadId, TrimmedNonEmptyString, } from "./baseSchemas.ts"; +import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "./chatAttachment.ts"; import { GUEST_MESSAGE_MAX_LENGTH, GUEST_NAME_MAX_LENGTH } from "./guestShare.ts"; /** Image and file records reference `ChatAttachment` ids, never bytes. */ @@ -34,11 +35,12 @@ const CONTEXT_KIND_PATTERN = /^[a-z][a-z0-9-]{0,39}$/; const KNOWN_KIND_PATTERN = new RegExp(`^(?!(?:${COMPOSER_CONTEXT_KINDS.join("|")})$)`); export const COMPOSER_CONTEXT_LABEL_MAX_CHARS = 200; -export const COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS = 64_000; +// Pasted text may use the whole prompt; a combined prompt over it is refused before sending. +export const COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS = PROVIDER_SEND_TURN_MAX_INPUT_CHARS; const COMPOSER_CONTEXT_ELEMENT_HTML_MAX_CHARS = 8_000; const COMPOSER_CONTEXT_ELEMENT_STYLES_MAX_CHARS = 8_000; -export const COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS = 16_000; -export const COMPOSER_CONTEXT_REVIEW_DIFF_MAX_CHARS = 32_000; +export const COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS = PROVIDER_SEND_TURN_MAX_INPUT_CHARS; +export const COMPOSER_CONTEXT_REVIEW_DIFF_MAX_CHARS = PROVIDER_SEND_TURN_MAX_INPUT_CHARS; const COMPOSER_CONTEXT_PREVIEW_COMMENT_MAX_CHARS = 8_000; export const ComposerContextId = TrimmedNonEmptyString.check( diff --git a/packages/provider-core/src/server/handoffBudget.ts b/packages/provider-core/src/server/handoffBudget.ts index 5f9f2f3ae33f6..f6e41ebbf443c 100644 --- a/packages/provider-core/src/server/handoffBudget.ts +++ b/packages/provider-core/src/server/handoffBudget.ts @@ -10,13 +10,36 @@ import type { } from "@t3tools/contracts"; import * as Config from "effect/Config"; +import * as Option from "effect/Option"; -export const DEFAULT_HANDOFF_TOKEN_CAP = 16_000; -const HANDOFF_BYTE_CAP = 64_000; -export const handoffTokenCapConfig = Config.Int("T3CODE_CONTEXT_HANDOFF_TOKEN_CAP").pipe( - Config.withDefault(DEFAULT_HANDOFF_TOKEN_CAP), - Config.map((value) => Math.max(1_024, Math.min(HANDOFF_BYTE_CAP, value))), -); +/** History allowance when the target model's window is unknown. */ +export const DEFAULT_HANDOFF_TOKEN_CAP = 200_000; +/** Clamp ceiling for overrides, and the selection bound before the target window is known. */ +export const MAX_HANDOFF_TOKEN_CAP = 1_000_000; +/** An operator override, or undefined to size each handoff from the target model's window. */ +export const handoffTokenCapConfig = Config.option( + Config.Int("T3CODE_CONTEXT_HANDOFF_TOKEN_CAP").pipe( + Config.map((value) => Math.max(1_024, Math.min(MAX_HANDOFF_TOKEN_CAP, value))), + ), +).pipe(Config.map(Option.getOrUndefined)); + +/** Preparation bound: the override, else half a known window, else the ceiling for delivery to narrow. */ +export function preparationTokenCap( + override: number | undefined, + knownWindow: number | undefined, +): number { + if (override !== undefined) return override; + return knownWindow === undefined || knownWindow <= 0 + ? MAX_HANDOFF_TOKEN_CAP + : defaultHandoffTokenCap(knownWindow); +} + +/** Half a known window leaves the other half for instructions, tools, and the work itself. */ +function defaultHandoffTokenCap(knownWindow: number | undefined): number { + return knownWindow === undefined || knownWindow <= 0 + ? DEFAULT_HANDOFF_TOKEN_CAP + : Math.min(MAX_HANDOFF_TOKEN_CAP, Math.floor(knownWindow / 2)); +} // Only accepted roots with matching native identity count; row reuse must not revive old usage. export function latestNativeContextUsage( @@ -97,7 +120,7 @@ export function attachmentTokenAllowance(attachments: ReadonlyArray; readonly providerThread: OrchestrationV2ProviderThread; @@ -105,8 +128,9 @@ export function handoffBudget(input: { readonly modelContextWindow?: number | undefined; }): number { const usage = input.providerThread.contextUsage; + const knownWindow = input.modelContextWindow ?? usage?.maxTokens; const window = Math.min( - input.modelContextWindow ?? usage?.maxTokens ?? 128_000, + knownWindow ?? 128_000, usage?.maxTokens ?? Infinity, usage?.autoCompactThreshold ?? Infinity, ); @@ -116,9 +140,7 @@ export function handoffBudget(input: { return Math.max( 0, Math.min( - input.tokenCap, - // Cap imported history only; adapters own attachment transport limits. - HANDOFF_BYTE_CAP, + input.tokenCap ?? defaultHandoffTokenCap(knownWindow), window - native - current - Math.max(16_000, Math.ceil(window / 4)), ), ); diff --git a/packages/shared/src/composerContextReferences.ts b/packages/shared/src/composerContextReferences.ts index a7aeb1373ae10..d437b9cc08cca 100644 --- a/packages/shared/src/composerContextReferences.ts +++ b/packages/shared/src/composerContextReferences.ts @@ -8,6 +8,7 @@ import { type KnownComposerContextRecord, type ScopedThreadRef, type ThreadContextRecord, + PROVIDER_SEND_TURN_MAX_INPUT_CHARS, } from "@t3tools/contracts"; import { replaceThreadLinks, threadLinkCandidates } from "./threadLinks.ts"; @@ -450,3 +451,18 @@ export function remapComposerContextAttachments( ), }; } + +/** The over-limit message for a prompt of `length` characters, or null when it fits. */ +export function promptLengthErrorMessage(length: number): string | null { + const excess = length - PROVIDER_SEND_TURN_MAX_INPUT_CHARS; + if (excess <= 0) return null; + return `Prompt is ${excess.toLocaleString("en-US")} ${excess === 1 ? "character" : "characters"} over the ${PROVIDER_SEND_TURN_MAX_INPUT_CHARS.toLocaleString("en-US")}-character limit, including attached context. Shorten or split it before sending.`; +} + +/** Measures the text the provider receives: the prompt with its context records rendered in. */ +export function providerInputLengthErrorMessage(input: { + text: string; + records: ReadonlyArray; +}): string | null { + return promptLengthErrorMessage(projectComposerContextForProvider(input).trim().length); +}