diff --git a/ui-packages/web/src/core/agent/compaction.test.ts b/ui-packages/web/src/core/agent/compaction.test.ts index 87d85ca..f6136a9 100644 --- a/ui-packages/web/src/core/agent/compaction.test.ts +++ b/ui-packages/web/src/core/agent/compaction.test.ts @@ -1,7 +1,15 @@ import type { AgentMessage } from '@earendil-works/pi-agent-core' import type { AssistantMessage, Message, ToolResultMessage } from '@earendil-works/pi-ai' import { describe, expect, it } from 'vitest' -import { type CompactionMessage, planCompaction, projectContext } from './compaction' +import { + autoCompactionEnabled, + type CompactionMessage, + compactionThreshold, + keepRecentFor, + needsCompaction, + planCompaction, + projectContext, +} from './compaction' const user = (text: string): Message => ({ role: 'user', content: text, timestamp: 1 }) @@ -144,3 +152,42 @@ describe('planCompaction', () => { expect(planCompaction([...messages, compaction('done', 1)], 0)).toBeNull() }) }) + +describe('when to compact', () => { + it('scales the threshold and what is kept with the window', () => { + const budget = (window: number) => [compactionThreshold(window), keepRecentFor(window)] + + expect(budget(1_000_000)).toEqual([512_000, 40_000]) + expect(budget(128_000)).toEqual([111_616, 40_000]) + expect(budget(32_000)).toEqual([16_000, 6_400]) + expect(budget(8_000)).toEqual([4_000, 1_600]) + // A window the catalog does not know. + expect(budget(0)).toEqual([512_000, 40_000]) + }) + + it('compacts once the context passes the threshold, and not again after', () => { + const window = 128_000 + const messages: AgentMessage[] = [ + user('x'.repeat(400_000)), + assistant('y'.repeat(400_000)), + user('z'.repeat(400)), + ] + + expect(needsCompaction(messages, window)).toBe(true) + expect(needsCompaction([...messages, compaction('short', 2)], window)).toBe(false) + }) + + it('automates only known windows of at least 128K', () => { + const messages = [user('x'.repeat(2_000_000))] + const smallWindows = [0, 32_000, 127_999] + smallWindows.forEach(window => { + expect(autoCompactionEnabled(window)).toBe(false) + expect(needsCompaction(messages, window)).toBe(false) + }) + const supportedWindows = [128_000, 1_000_000] + supportedWindows.forEach(window => { + expect(autoCompactionEnabled(window)).toBe(true) + expect(needsCompaction(messages, window)).toBe(true) + }) + }) +}) diff --git a/ui-packages/web/src/core/agent/compaction.ts b/ui-packages/web/src/core/agent/compaction.ts index 6755532..4f82b07 100644 --- a/ui-packages/web/src/core/agent/compaction.ts +++ b/ui-packages/web/src/core/agent/compaction.ts @@ -30,10 +30,28 @@ export const isCompactionMessage = (message: AgentMessage): message is Compactio export const compactionSettings = { /** Room left for the reply; it also bounds the summary's length. */ reserveTokens: 16_384, - /** Recent context kept as it is. */ - keepRecentTokens: 20_000, + /** Every request resends the whole context, mostly from the provider's cache, so compacting + * rarely costs less than it loses; very long contexts still answer worse. */ + maximumThreshold: 512_000, + /** Recent context kept as it is, enough to quote the last pages read. */ + maximumKeep: 40_000, } +// A window of 0 is one the catalog does not know. Half the window keeps a tiny one usable. +export const compactionThreshold = (contextWindow: number) => + contextWindow > 0 + ? Math.min( + compactionSettings.maximumThreshold, + Math.max(contextWindow - compactionSettings.reserveTokens, Math.floor(contextWindow / 2)), + ) + : compactionSettings.maximumThreshold + +export const autoCompactionEnabled = (contextWindow: number): boolean => contextWindow >= 128_000 + +// A retention budget, not a bound on the summary or an indivisible message kept with it. +export const keepRecentFor = (contextWindow: number) => + Math.min(compactionSettings.maximumKeep, Math.floor(0.4 * compactionThreshold(contextWindow))) + const summaryPrefix = 'The conversation history before this point was compacted into the following summary:\n\n\n' const summarySuffix = '\n' @@ -100,7 +118,7 @@ const isCutPoint = (message: AgentMessage) => // valid point at or after it. Returns null when there is nothing to fold away. export const planCompaction = ( conversation: readonly AgentMessage[], - keepRecentTokens = compactionSettings.keepRecentTokens, + keepRecentTokens: number, ): CompactionPlan | null => { const last = conversation.at(-1) if (!last || isCompactionMessage(last)) return null @@ -139,6 +157,11 @@ export const planCompaction = ( } } +// Whether the context the provider would be sent has passed the threshold. +export const needsCompaction = (messages: readonly AgentMessage[], contextWindow: number) => + autoCompactionEnabled(contextWindow) && + estimateContextTokens(projectContext(messages)).tokens > compactionThreshold(contextWindow) + const toolResultLimit = 2_000 const truncate = (text: string) => diff --git a/ui-packages/web/src/features/assistant/compaction.ts b/ui-packages/web/src/features/assistant/compaction.ts index f7d1d24..2d852a7 100644 --- a/ui-packages/web/src/features/assistant/compaction.ts +++ b/ui-packages/web/src/features/assistant/compaction.ts @@ -9,6 +9,7 @@ import { import { type CompactionMessage, compactionSettings, + keepRecentFor, planCompaction, serializeConversation, } from '../../core/agent/compaction' @@ -145,7 +146,7 @@ export const compactConversation = async ( conversation: readonly AgentMessage[], signal?: AbortSignal, ): Promise => { - const plan = planCompaction(conversation) + const plan = planCompaction(conversation, keepRecentFor(model.contextWindow)) if (!plan) return null const { firstKept, history, turnPrefix, previousSummary, tokensBefore } = plan const [summary, prefix] = await Promise.all([ diff --git a/ui-packages/web/src/features/assistant/create-reader-agent.test.ts b/ui-packages/web/src/features/assistant/create-reader-agent.test.ts index c61b644..965574e 100644 --- a/ui-packages/web/src/features/assistant/create-reader-agent.test.ts +++ b/ui-packages/web/src/features/assistant/create-reader-agent.test.ts @@ -59,10 +59,10 @@ const xlsx = vi.hoisted(() => ({ read: vi.fn() })) vi.mock('read-excel-file/browser', () => ({ default: xlsx.read })) const config = await createModelRuntime(modelConfig) -const event = (delta: unknown, finish: string | null = null) => - `data: ${JSON.stringify({ id: 'reply', choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n` -const reply = (text: string) => - new Response(`${event({ content: text }) + event({}, 'stop')}data: [DONE]\n\n`, { +const event = (delta: unknown, finish: string | null = null, tokens = 0) => + `data: ${JSON.stringify({ id: 'reply', choices: [{ index: 0, delta, finish_reason: finish }], ...(tokens ? { usage: { prompt_tokens: tokens, completion_tokens: 0, total_tokens: tokens } } : {}) })}\n\n` +const reply = (text: string, tokens = 0) => + new Response(`${event({ content: text }) + event({}, 'stop', tokens)}data: [DONE]\n\n`, { headers: { 'Content-Type': 'text/event-stream' }, }) const call = (name: string, args: unknown) => @@ -87,6 +87,67 @@ const localTools = () => createLocalTools(emptyState, writeStoredTextFile, moveS const session = { id: 'test-conversation', messages: [], ...resolveModelSelection(config) } describe('reader agent', () => { + it.each([0, 32_000, 127_999, 128_000])( + 'automates between tool turns only for a supported %i window', + async window => { + const notifications = vi.fn() + const fetchModel = vi + .spyOn(globalThis, 'fetch') + .mockResolvedValueOnce(reply('x'.repeat(150_000), 120_000)) + const agent = createReaderAgent(config, localTools(), { + ...session, + model: { ...session.model, contextWindow: window }, + onCompactionChange: notifications, + }) + await agent.prompt('Earlier question') + const requests: string[] = [] + fetchModel.mockImplementation(async (_url, init) => { + const summary = String(init?.body).includes('context summarization assistant') + requests.push(summary ? 'summary' : 'chat') + if (summary) return reply('Earlier question summarized') + return requests.length === 1 ? call('get_reader_state', {}) : reply('Finished') + }) + await agent.prompt('Read more') + expect(requests).toEqual(window >= 128_000 ? ['chat', 'summary', 'chat'] : ['chat', 'chat']) + expect(notifications.mock.calls).toEqual(window >= 128_000 ? [[true], [false]] : []) + expect(agent.state.messages.at(-1)).toMatchObject({ stopReason: 'stop' }) + }, + ) + + it.each(['failure', 'stop'])( + 'ends between-turn compaction notifications after a %s', + async outcome => { + const notifications: boolean[] = [] + const fetchModel = vi + .spyOn(globalThis, 'fetch') + .mockResolvedValueOnce(reply('x'.repeat(150_000), 120_000)) + vi.spyOn(console, 'error').mockImplementation(vi.fn()) + const agent = createReaderAgent(config, localTools(), { + ...session, + model: { ...session.model, contextWindow: 128_000 }, + onCompactionChange: compacting => { + notifications.push(compacting) + if (compacting && outcome === 'stop') agent.abort() + }, + }) + await agent.prompt('Earlier question') + let chats = 0 + fetchModel.mockImplementation(async (_url, init) => { + if (String(init?.body).includes('context summarization assistant')) + return Response.json({ error: { message: 'Unavailable' } }, { status: 503 }) + chats += 1 + return chats === 1 ? call('get_reader_state', {}) : reply('Finished') + }) + await agent.prompt('Read more') + expect(notifications).toEqual([true, false]) + expect(conversationMessages(agent).some(message => message.role === 'compaction')).toBe(false) + expect(chats).toBe(outcome === 'stop' ? 1 : 2) + expect(agent.state.messages.at(-1)).toMatchObject({ + stopReason: outcome === 'stop' ? 'aborted' : 'stop', + }) + }, + ) + it('restores the transcript under the selected conversation id', () => { const message = createReaderUserMessage('Earlier question', []) const agent = createReaderAgent(config, localTools(), { diff --git a/ui-packages/web/src/features/assistant/create-reader-agent.ts b/ui-packages/web/src/features/assistant/create-reader-agent.ts index a403b61..ff61fa9 100644 --- a/ui-packages/web/src/features/assistant/create-reader-agent.ts +++ b/ui-packages/web/src/features/assistant/create-reader-agent.ts @@ -1,5 +1,5 @@ import { Agent, type AgentMessage, type AgentState } from '@earendil-works/pi-agent-core' -import { projectContext } from '../../core/agent/compaction' +import { needsCompaction, projectContext } from '../../core/agent/compaction' import { type AgentDefinition, assemble, type Skill, streamFn } from '../../core/agent/definition' import { LocalToolError } from '../../core/agent/tool' import { @@ -11,6 +11,7 @@ import { type ModelRuntime, visionModelFor } from '../../core/models/model-runti import { getStoredFile, listStoredFiles } from '../../data/file-store' import { markdownText } from '../../formats/markdown-text' import { memoryAgentParts } from '../memory' +import { compactConversation } from './compaction' import { createDocumentTools, type DocumentAccess } from './document-tools' import { createDocxRuntime, type DocxRuntime } from './docx/runtime' import { createImageTools } from './image-tools' @@ -110,6 +111,27 @@ const readerAgent: AgentDefinition = { export const conversationMessages = (agent: Agent) => agent.state.messages.filter(message => message.role !== 'system') +// A reply that reads page after page can pass the threshold between two of its own requests. The +// summary joins the transcript before the next one; a failure leaves the reply to go on without it. +const compactBetweenTurns = async ( + agent: Agent, + signal?: AbortSignal, + onCompactionChange?: (compacting: boolean) => void, +) => { + const { model } = agent.state + if (!needsCompaction(agent.state.messages, model.contextWindow)) return undefined + onCompactionChange?.(true) + try { + const message = await compactConversation(model, conversationMessages(agent), signal) + return message && !signal?.aborted ? { messages: [message] } : undefined + } catch (cause) { + if (!signal?.aborted) console.error('Unable to compact the conversation between turns', cause) + return undefined + } finally { + onCompactionChange?.(false) + } +} + export const createReaderAgent = ( runtime: ModelRuntime, local: LocalTools, @@ -118,6 +140,7 @@ export const createReaderAgent = ( messages: readonly AgentMessage[] // Read at each call, so turning web search on or off needs no new agent. web?: () => WebState + onCompactionChange?: (compacting: boolean) => void } & Pick, ) => { const pdf = createPdfRuntime(getStoredFile) @@ -151,6 +174,8 @@ export const createReaderAgent = ( const projected = projectContext(messages) return memory ? memory.transformContext(projected) : projected }, + prepareNextTurnWithContext: (_turn, signal) => + compactBetweenTurns(agent, signal, session.onCompactionChange), streamFn, }) agent.subscribe(async event => { diff --git a/ui-packages/web/src/features/conversation/composer/index.tsx b/ui-packages/web/src/features/conversation/composer/index.tsx index bd56306..0c09ae4 100644 --- a/ui-packages/web/src/features/conversation/composer/index.tsx +++ b/ui-packages/web/src/features/conversation/composer/index.tsx @@ -96,12 +96,13 @@ export const ConversationComposer = ({ const value = draft || command const matches = command ? matchCommands(command, commands) : [] const menuOpen = !dismissed && matches.length > 0 - const running = phase === 'running' || phase === 'stopping' + // A summary can be stopped like a reply, but accepts no new messages. + const running = phase === 'running' || phase === 'stopping' || phase === 'compacting' const readyAttachments = attachments.filter(item => item.status === 'ready') const hasUnavailable = readyAttachments.some(item => !availableFileIds.has(item.metadata.id)) // While a reply runs, sending queues the message. const canSend = - (phase === 'ready' || running) && + (phase === 'ready' || phase === 'running') && !unsettled && !hasUnavailable && Boolean(value.trim() || readyAttachments.length) diff --git a/ui-packages/web/src/features/conversation/use-conversation/agent-session.ts b/ui-packages/web/src/features/conversation/use-conversation/agent-session.ts index 9e09f95..f500423 100644 --- a/ui-packages/web/src/features/conversation/use-conversation/agent-session.ts +++ b/ui-packages/web/src/features/conversation/use-conversation/agent-session.ts @@ -113,6 +113,12 @@ export const attachAgent = ( : getActive(ctx).webSearch ? 'on' : 'off', + onCompactionChange: compacting => { + if (runtime.agent !== agent || runtime.switching) return + const { phase } = store.getState() + if (compacting && phase === 'running') store.setState({ phase: 'compacting' }) + if (!compacting && phase === 'compacting') store.setState({ phase: 'running' }) + }, }) agent.state.tools = withWebSearch( agent.state.tools, diff --git a/ui-packages/web/src/features/conversation/use-conversation/compaction.ts b/ui-packages/web/src/features/conversation/use-conversation/compaction.ts new file mode 100644 index 0000000..0b070ba --- /dev/null +++ b/ui-packages/web/src/features/conversation/use-conversation/compaction.ts @@ -0,0 +1,99 @@ +import type { Agent, AgentMessage } from '@earendil-works/pi-agent-core' +import { isContextOverflow } from '@earendil-works/pi-ai' +import { autoCompactionEnabled, needsCompaction } from '../../../core/agent/compaction' +import { compactConversation } from '../../assistant/compaction' +import { conversationMessages } from '../../assistant/create-reader-agent' +import { persistAgentMessages, refresh } from './agent-session' +import type { Ctx } from './state' + +// The summary is appended like any message, so the conversation is saved whole and the provider +// is sent the summary and what it kept from the next request on. A failed call throws. +const summarize = async (ctx: Ctx, agent: Agent) => { + const { runtime, store } = ctx + const controller = new AbortController() + runtime.compaction = controller + store.setState({ phase: 'compacting' }) + try { + const message = await compactConversation( + agent.state.model, + conversationMessages(agent), + controller.signal, + ) + if (runtime.agent !== agent || controller.signal.aborted) return 'aborted' + if (!message) return 'nothing' + agent.state.messages = [...agent.state.messages, message] + refresh(ctx, agent) + await persistAgentMessages(ctx, agent) + if (runtime.agent !== agent || controller.signal.aborted) return 'aborted' + return 'compacted' + } catch (cause) { + if (runtime.agent !== agent || controller.signal.aborted) return 'aborted' + throw cause + } finally { + if (runtime.compaction === controller) runtime.compaction = null + } +} + +// The reader's /compact. +export const compact = async (ctx: Ctx) => { + const { runtime, store } = ctx + const agent = runtime.agent + if (!agent || runtime.busy || runtime.switching) return + runtime.busy = true + store.setState({ error: undefined }) + try { + if ((await summarize(ctx, agent)) === 'nothing') + store.setState({ + error: 'Nothing to compact yet: the conversation still fits in its recent context.', + }) + } catch (cause) { + if (runtime.agent !== agent) return + console.error('Unable to compact the conversation', cause) + store.setState({ + error: cause instanceof Error ? cause.message : 'Could not compact the conversation.', + }) + } finally { + if (runtime.agent === agent) { + runtime.busy = false + store.setState({ phase: 'ready' }) + } + } +} + +// Before a message is sent into a context past the threshold. False when the reader stopped it; +// a failure sends the message anyway and leaves an overflow to recoverFromOverflow. +export const compactBeforeSending = async ( + ctx: Ctx, + agent: Agent, + sending: readonly AgentMessage[], +) => { + const { model } = agent.state + if (!needsCompaction([...agent.state.messages, ...sending], model.contextWindow)) return true + try { + return (await summarize(ctx, agent)) !== 'aborted' + } catch (cause) { + console.error('Unable to compact the conversation before sending', cause) + return true + } +} + +// A reply refused for its context length is answered again, once, after compacting what came +// before it. The failed reply stays in the transcript; the provider is never sent it again. +export const recoverFromOverflow = async (ctx: Ctx, agent: Agent) => { + const last = agent.state.messages.at(-1) + if ( + !autoCompactionEnabled(agent.state.model.contextWindow) || + last?.role !== 'assistant' || + last.stopReason !== 'error' || + !isContextOverflow(last, agent.state.model.contextWindow) + ) + return + try { + if ((await summarize(ctx, agent)) !== 'compacted') return + } catch (cause) { + console.error('Unable to compact the conversation after it overflowed', cause) + return + } + ctx.store.setState({ phase: 'running' }) + await agent.continue() +} diff --git a/ui-packages/web/src/features/conversation/use-conversation/controller.test.ts b/ui-packages/web/src/features/conversation/use-conversation/controller.test.ts new file mode 100644 index 0000000..6d1737c --- /dev/null +++ b/ui-packages/web/src/features/conversation/use-conversation/controller.test.ts @@ -0,0 +1,262 @@ +import type { AssistantMessage } from '@earendil-works/pi-ai' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { emptyConversationDraft } from '../../../core/conversations' +import { models } from '../../../core/models/model-runtime' +import { createReaderUserMessage } from '../../../core/reader-message' +import * as conversationStore from '../../../data/conversation-store' +import { moveStoredFile, writeStoredTextFile } from '../../../data/file-store' +import { isTitleRequest, modelConfig } from '../../../test/model-config' +import { createLocalTools } from '../../assistant/local-tools' +import { createConversationController } from './controller' +import type { DraftAttachmentsPort } from './state' + +const event = (delta: unknown, finish: string | null = null, tokens = 0) => + `data: ${JSON.stringify({ choices: [{ index: 0, delta, finish_reason: finish }], usage: { prompt_tokens: tokens, completion_tokens: 0, total_tokens: tokens } })}\n\n` +const reply = (text: string) => + new Response(`${event({ content: text })}${event({}, 'stop')}data: [DONE]\n\n`, { + headers: { 'Content-Type': 'text/event-stream' }, + }) +const overflow = () => + Response.json({ error: { message: 'context length exceeded' } }, { status: 400 }) +const deferred = () => { + let resolve!: (value: T) => void + const promise = new Promise(done => { + resolve = done + }) + return { promise, resolve } +} +const assistant = (timestamp: number, tokens = 0): AssistantMessage => ({ + role: 'assistant', + content: [{ type: 'text', text: 'Earlier answer' }], + api: 'openai-completions', + provider: 'zai-coding-cn', + model: 'glm-5.3', + timestamp, + stopReason: 'stop', + usage: { + input: tokens, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: tokens, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, +}) +const history = (tokens: number) => [ + { ...createReaderUserMessage(`old-material-${'x'.repeat(70_000)}`, []), timestamp: 1 }, + assistant(2), + { ...createReaderUserMessage(`recent-material-${'y'.repeat(145_000)}`, []), timestamp: 3 }, + assistant(4, tokens), +] + +let cleanup = () => {} +afterEach(() => cleanup()) + +const start = async (tokens = 0) => { + await conversationStore.appendStoredConversationMessages({ + conversation: { + id: 'saved', + title: 'Reading', + titledBy: 'reader', + draft: emptyConversationDraft(), + createdAt: 1, + lastActiveAt: 1, + }, + startPosition: 0, + messages: history(tokens), + }) + const attachments = { + ready: vi.fn(() => []), + settle: async () => {}, + replaceReady: vi.fn(), + restore: vi.fn(), + takeReady: vi.fn(() => []), + } satisfies DraftAttachmentsPort + const controller = createConversationController( + createLocalTools( + () => ({ openFiles: [], activeFile: null, viewport: null }), + writeStoredTextFile, + moveStoredFile, + ), + attachments, + false, + ) + cleanup = controller.start() + await vi.waitFor(() => expect(controller.store.getState().phase).toBe('ready')) + return { controller, attachments } +} + +type RequestKind = 'chat' | 'summary' +const mockRequests = ( + respond: (kind: RequestKind, init?: RequestInit) => Response | Promise, +) => { + const requests: { kind: RequestKind; body: string }[] = [] + vi.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => { + if (url === '/api/agent/config') return Response.json(modelConfig) + if (isTitleRequest(init)) return reply('Reading') + const body = String(init?.body) + const kind = body.includes('context summarization assistant') ? 'summary' : 'chat' + requests.push({ kind, body }) + return respond(kind, init) + }) + return requests +} + +describe('conversation compaction', () => { + it.each([0, 32_000, 127_999])( + 'does not automatically compact or recover a %i window', + async window => { + const getModel = models.getModel.bind(models) + vi.spyOn(models, 'getModel').mockImplementation((provider, id) => { + const model = getModel(provider, id) + return model ? { ...model, contextWindow: window } : model + }) + const requests = mockRequests(() => overflow()) + const { controller } = await start(600_000) + controller.setDraft('Next question') + controller.send({ unsettled: false, hasAttachments: false }) + await vi.waitFor(() => expect(controller.store.getState().phase).toBe('ready')) + expect(requests.map(request => request.kind)).toEqual(['chat']) + expect(controller.store.getState().messages.at(-1)).toMatchObject({ failed: true }) + }, + ) + + it.each([false, true])( + 'shrinks overflow context and retries at most once (retry fails: %s)', + async fails => { + let chats = 0 + const requests = mockRequests(kind => { + if (kind === 'summary') return reply('Earlier material summarized.') + chats += 1 + return chats === 1 || fails ? overflow() : reply('Recovered answer') + }) + const { controller } = await start() + controller.setDraft('Keep this question exactly') + controller.send({ unsettled: false, hasAttachments: false }) + await vi.waitFor(() => expect(controller.store.getState().phase).toBe('ready')) + expect(requests.map(request => request.kind)).toEqual(['chat', 'summary', 'chat']) + const first = requests[0]?.body ?? '' + const retry = requests[2]?.body ?? '' + expect(retry.length).toBeLessThan(first.length) + expect(retry).not.toContain('old-material-') + expect(retry).toContain('recent-material-') + expect(retry).toContain('Keep this question exactly') + expect(controller.store.getState().messages.at(-1)).toMatchObject( + fails ? { failed: true } : { text: 'Recovered answer' }, + ) + }, + ) + + it('keeps drafts and attachments when sending during manual compaction or stopping', async () => { + const summary = deferred() + const requests = mockRequests(() => summary.promise) + const { controller, attachments } = await start() + const compacting = controller.compact() + await vi.waitFor(() => expect(requests).toHaveLength(1)) + controller.setDraft('Still editing') + controller.attachmentsChanged([ + { id: 'note', name: 'note.md', mediaType: 'text/markdown', previewKind: 'markdown', size: 5 }, + ]) + const before = controller.store.getState().active + controller.send({ unsettled: false, hasAttachments: true }) + expect(controller.store.getState().active).toBe(before) + controller.stop() + expect(controller.store.getState().phase).toBe('stopping') + controller.send({ unsettled: false, hasAttachments: true }) + expect(controller.store.getState().active).toBe(before) + expect(attachments.takeReady).not.toHaveBeenCalled() + summary.resolve(reply('A summary arriving after cancellation')) + await compacting + expect(controller.store.getState().draft).toBe('Still editing') + expect( + controller.store.getState().messages.some(message => message.role === 'compaction'), + ).toBe(false) + expect(requests.map(request => request.kind)).toEqual(['summary']) + expect(controller.store.getState().phase).toBe('ready') + }) + + it.each(['before sending', 'overflow recovery'])( + 'does not resume when stopped while saving a summary (%s)', + async trigger => { + const requests = mockRequests(kind => + kind === 'summary' ? reply('Summary saved') : overflow(), + ) + const { controller } = await start(trigger === 'before sending' ? 600_000 : 0) + const saved = deferred() + const release = deferred() + const append = conversationStore.appendStoredConversationMessages + vi.spyOn(conversationStore, 'appendStoredConversationMessages').mockImplementation( + async input => { + await append(input) + if (!input.messages.some(message => message.role === 'compaction')) return + saved.resolve() + await release.promise + }, + ) + controller.setDraft('Unsent question') + controller.send({ unsettled: false, hasAttachments: false }) + await saved.promise + controller.stop() + release.resolve() + await vi.waitFor(() => expect(controller.store.getState().phase).toBe('ready')) + expect(requests.map(request => request.kind)).toEqual( + trigger === 'before sending' ? ['summary'] : ['chat', 'summary'], + ) + expect(controller.store.getState().draft).toBe( + trigger === 'before sending' ? 'Unsent question' : '', + ) + const stored = await conversationStore.getStoredConversation('saved') + expect(stored?.messages.some(message => message.role === 'compaction')).toBe(true) + }, + ) + + it.each(['finish', 'stop', 'switch'])( + 'handles %s during between-turn compaction without accepting new messages', + async action => { + const first = deferred() + const summary = deferred() + let chats = 0 + const requests = mockRequests(kind => { + if (kind === 'summary') return summary.promise + chats += 1 + return chats === 1 ? first.promise : reply('Finished') + }) + const { controller } = await start() + controller.setDraft('Read more') + controller.send({ unsettled: false, hasAttachments: false }) + await vi.waitFor(() => expect(requests).toHaveLength(1)) + controller.setDraft('Queued before compaction') + controller.send({ unsettled: false, hasAttachments: false }) + first.resolve( + new Response( + `${event({ tool_calls: [{ index: 0, id: 'state', type: 'function', function: { name: 'get_reader_state', arguments: '{}' } }] }, 'tool_calls', 600_000)}data: [DONE]\n\n`, + { headers: { 'Content-Type': 'text/event-stream' } }, + ), + ) + await vi.waitFor(() => expect(controller.store.getState().phase).toBe('compacting')) + controller.setDraft('Draft during compaction') + controller.send({ unsettled: false, hasAttachments: false }) + const phases: string[] = [] + const unsubscribe = controller.store.subscribe(state => phases.push(state.phase)) + if (action === 'stop') controller.stop() + const switching = action === 'switch' ? controller.startNew() : undefined + summary.resolve(reply('Earlier material summarized')) + await switching + await vi.waitFor(() => expect(controller.store.getState().phase).toBe('ready')) + unsubscribe() + expect(requests.map(request => request.kind)).toEqual( + action === 'finish' ? ['chat', 'summary', 'chat'] : ['chat', 'summary'], + ) + if (action === 'finish') { + expect(requests[2]?.body).toContain('Queued before compaction') + expect(requests[2]?.body).not.toContain('Draft during compaction') + } else expect(phases).not.toContain('running') + if (action === 'switch') { + expect(controller.store.getState().active.id).not.toBe('saved') + expect( + (await conversationStore.getStoredConversation('saved'))?.conversation.draft.text, + ).toBe('Draft during compaction') + } else expect(controller.store.getState().draft).toBe('Draft during compaction') + }, + ) +}) diff --git a/ui-packages/web/src/features/conversation/use-conversation/controller.ts b/ui-packages/web/src/features/conversation/use-conversation/controller.ts index 2a0d5b1..f8ff689 100644 --- a/ui-packages/web/src/features/conversation/use-conversation/controller.ts +++ b/ui-packages/web/src/features/conversation/use-conversation/controller.ts @@ -1,11 +1,12 @@ import type { ConversationId } from '../../../core/conversations' import type { ConversationAttachment } from '../../../core/reader-message' import type { LocalTools } from '../../assistant/local-tools' +import { compact } from './compaction' import { createDraftQueue } from './draft-queue' import { attachmentsChanged, removeQueued, setDraft, writeDraft } from './drafts' import { loadMore, reload } from './history' import { deleteConversation, start, startNew, switchTo } from './navigation' -import { compact, send, stop } from './run' +import { send, stop } from './run' import { createConversation } from './session' import { configureModel, memoryChanged, refreshProviders, setWebSearch } from './settings' import { type Ctx, createRuntime, createState, type DraftAttachmentsPort } from './state' diff --git a/ui-packages/web/src/features/conversation/use-conversation/run.ts b/ui-packages/web/src/features/conversation/use-conversation/run.ts index 6fd48ff..69e1110 100644 --- a/ui-packages/web/src/features/conversation/use-conversation/run.ts +++ b/ui-packages/web/src/features/conversation/use-conversation/run.ts @@ -6,9 +6,8 @@ import { foldQueued, } from '../../../core/conversations' import { createReaderUserMessage, isReaderUserMessage } from '../../../core/reader-message' -import { compactConversation } from '../../assistant/compaction' -import { conversationMessages } from '../../assistant/create-reader-agent' -import { persistAgentMessages, refresh } from './agent-session' +import { refresh } from './agent-session' +import { compactBeforeSending, recoverFromOverflow } from './compaction' import { queueDraft, restoreToDraft, takeQueued } from './drafts' import { failedRun } from './messages' import { nextActivityTime } from './session' @@ -28,8 +27,16 @@ const run = async (ctx: Ctx, agent: Agent, batch: readonly ConversationDraft[]) item, message: createReaderUserMessage(item.text, item.attachments), })) + const messages = sending.map(entry => entry.message) + // Stopped while compacting: nothing was sent, so the messages go back to the draft. + if (!(await compactBeforeSending(ctx, agent, messages))) { + if (runtime.agent === agent) restoreToDraft(ctx, [...items, ...takeQueued(ctx)]) + return + } + store.setState({ phase: 'running' }) try { - await agent.prompt(sending.map(entry => entry.message)) + await agent.prompt(messages) + if (runtime.agent === agent) await recoverFromOverflow(ctx, agent) } catch (cause) { if (runtime.agent !== agent) return store.setState({ @@ -68,7 +75,9 @@ export const send = ( ) => { const { runtime, store } = ctx const agent = runtime.agent - const text = store.getState().draft.trim() + const { draft, phase } = store.getState() + if (phase !== 'ready' && phase !== 'running') return + const text = draft.trim() if (!agent || unsettled || (!text && !hasAttachments)) return const item = { text, attachments: ctx.attachments.takeReady().map(entry => entry.metadata) } const current = getActive(ctx) @@ -89,46 +98,6 @@ export const send = ( export const stop = (ctx: Ctx) => { if (!ctx.runtime.busy) return ctx.store.setState({ phase: 'stopping' }) + ctx.runtime.compaction?.abort() ctx.runtime.agent?.abort() } - -// The summary is appended like any message, so the conversation is saved whole and the provider -// is sent the summary and what it kept from the next request on. -export const compact = async (ctx: Ctx) => { - const { runtime, store } = ctx - const agent = runtime.agent - if (!agent || runtime.busy || runtime.switching) return - const controller = new AbortController() - runtime.compaction = controller - runtime.busy = true - store.setState({ error: undefined, phase: 'compacting' }) - try { - const message = await compactConversation( - agent.state.model, - conversationMessages(agent), - controller.signal, - ) - if (runtime.agent !== agent) return - if (!message) { - store.setState({ - error: 'Nothing to compact yet: the conversation still fits in its recent context.', - }) - return - } - agent.state.messages = [...agent.state.messages, message] - refresh(ctx, agent) - await persistAgentMessages(ctx, agent) - } catch (cause) { - if (runtime.agent !== agent || controller.signal.aborted) return - console.error('Unable to compact the conversation', cause) - store.setState({ - error: cause instanceof Error ? cause.message : 'Could not compact the conversation.', - }) - } finally { - if (runtime.compaction === controller) runtime.compaction = null - if (runtime.agent === agent) { - runtime.busy = false - store.setState({ phase: 'ready' }) - } - } -} diff --git a/ui-packages/web/src/shell/conversation-panel.integration.test.tsx b/ui-packages/web/src/shell/conversation-panel.integration.test.tsx index 015f9be..1d74388 100644 --- a/ui-packages/web/src/shell/conversation-panel.integration.test.tsx +++ b/ui-packages/web/src/shell/conversation-panel.integration.test.tsx @@ -10,6 +10,7 @@ import { getStoredConversation, saveStoredConversationDraft, } from '../data/conversation-store' +import * as compaction from '../features/assistant/compaction' import { DraftAttachmentTray, MessageAttachments, @@ -55,6 +56,56 @@ describe('conversation', () => { expect(await screen.findByText(limit)).toBeInTheDocument() }) + it('keeps editing available but blocks sending while compacting, and can stop', async () => { + const user = userEvent.setup({ delay: null }) + let finish: () => void = () => { + throw new Error('Compaction has not started') + } + let aborted = false + vi.spyOn(compaction, 'compactConversation').mockImplementation( + async (_model, _messages, signal) => + new Promise(resolve => { + signal?.addEventListener( + 'abort', + () => { + aborted = true + }, + { once: true }, + ) + finish = () => resolve(null) + }), + ) + let requests = 0 + vi.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => { + if (url === '/api/agent/config') return Response.json(config) + if (isTitleRequest(init)) return complete('Reading') + requests += 1 + return complete('A short answer') + }) + open() + await waitFor(() => expect(question()).toBeEnabled()) + await user.type(question(), 'Read the guide') + await user.click(send()) + await screen.findByText('A short answer') + await waitFor(() => expect(screen.getByRole('combobox', { name: 'Chat model' })).toBeEnabled()) + await user.type(question(), '/compact{Enter}') + expect(await screen.findByText('Summarizing earlier messages…')).toBeVisible() + await user.type(question(), 'Keep this draft{Enter}') + expect(question()).toHaveValue('Keep this draft') + expect(screen.queryByRole('button', { name: 'Queue message' })).not.toBeInTheDocument() + expect(screen.queryByRole('button', { name: 'Send question' })).not.toBeInTheDocument() + expect(requests).toBe(1) + await user.click(screen.getByRole('button', { name: 'Stop generation' })) + expect(aborted).toBe(true) + expect(screen.getByRole('button', { name: 'Stop generation' })).toBeDisabled() + await user.keyboard('{Enter}') + expect(question()).toHaveValue('Keep this draft') + await act(async () => finish()) + await waitFor(() => expect(send()).toBeEnabled()) + expect(question()).toHaveValue('Keep this draft') + expect(requests).toBe(1) + }) + it('offers web search only where the server searches, off until the reader turns it on', async () => { const user = userEvent.setup({ delay: null }) let served: PublicModelConfig = config diff --git a/web-packages/server/src/model-proxy/routes.test.ts b/web-packages/server/src/model-proxy/routes.test.ts index a89709f..52b82bf 100644 --- a/web-packages/server/src/model-proxy/routes.test.ts +++ b/web-packages/server/src/model-proxy/routes.test.ts @@ -408,6 +408,46 @@ describe('model proxy', () => { expect(log).toHaveBeenCalledWith('Model connection failed', { name: 'TypeError' }) }) + it('names a refusal for context length without passing on what the provider said', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce( + Response.json( + { + error: { + message: + "This model's maximum context length is 1048576 tokens. However, you requested 1200000 tokens. request id abc-private", + }, + }, + { status: 400 }, + ), + ) + const refused = await post() + const text = await refused.text() + expect(refused.status).toBe(400) + expect(text).toContain('context length exceeded') + expect(text).not.toContain('abc-private') + + // A rate limit that mentions tokens is still a rate limit. + vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce( + Response.json( + { error: { message: 'Rate limit reached: too many tokens per minute' } }, + { status: 429 }, + ), + ) + const limited = await post() + expect(limited.status).toBe(429) + expect(await limited.text()).toContain('HTTP 429') + + // A refusal whose body fails midway keeps its own status. + const broken = new ReadableStream({ + start: controller => controller.error(new TypeError('connection reset')), + }) + vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(new Response(broken, { status: 400 })) + const unread = await post() + expect(unread.status).toBe(400) + expect(await unread.text()).toContain('HTTP 400') + }) + it('times out upstream requests', async () => { vi.useFakeTimers() const timeout = new AbortController() diff --git a/web-packages/server/src/model-proxy/routes.ts b/web-packages/server/src/model-proxy/routes.ts index 61d345a..34d8532 100644 --- a/web-packages/server/src/model-proxy/routes.ts +++ b/web-packages/server/src/model-proxy/routes.ts @@ -1,3 +1,4 @@ +import { getOverflowPatterns } from '@earendil-works/pi-ai' import { Hono } from 'hono' import { bodyLimit } from 'hono/body-limit' import { setCookie } from 'hono/cookie' @@ -17,6 +18,46 @@ type Granted = Extract const fail = (status: number, message: string) => Response.json({ error: { message } }, { status, headers: { 'Cache-Control': 'no-store' } }) +const errorPreviewBytes = 4096 + +// The start of a refusal, enough to recognise it; the rest is never read. +const errorPreview = async (response: Response) => { + const reader = response.body?.getReader() + if (!reader) return '' + const chunks: Uint8Array[] = [] + let size = 0 + try { + while (size < errorPreviewBytes) { + const { done, value } = await reader.read() + if (done) break + chunks.push(value) + size += value.byteLength + } + } catch (cause) { + // A stream that failed is already closed; the status alone is reported. + console.warn('Model error body could not be read', { + name: cause instanceof Error ? cause.name : 'UnknownError', + }) + return '' + } + await reader.cancel() + return Buffer.concat(chunks).subarray(0, errorPreviewBytes).toString('utf8') +} + +// A request too large comes back as 400 or 413; a rate limit can still mention "too many +// tokens", so it is ruled out first, as pi-ai's own isContextOverflow does. +const overflowStatuses = new Set([400, 413]) +const notOverflow = [/rate limit/i, /too many requests/i] + +// Provider text is never passed on. A refusal for length is named in a fixed sentence the +// reader's client recognises, so it can compact the conversation and ask again. +const refusalMessage = (status: number, preview: string) => + overflowStatuses.has(status) && + !notOverflow.some(pattern => pattern.test(preview)) && + getOverflowPatterns().some(pattern => pattern.test(preview)) + ? 'The model provider rejected the request: context length exceeded.' + : `The model provider returned HTTP ${status}.` + const validBody = (body: unknown, modelIds: readonly string[]): body is Record => typeof body === 'object' && body !== null && @@ -60,10 +101,10 @@ const forward = async ( body: payload, }) if (!response.ok) { - await response.body?.cancel() + const preview = await errorPreview(response) granted.done(0) console.warn('Model request rejected', { status: response.status }) - return fail(response.status, `The model provider returned HTTP ${response.status}.`) + return fail(response.status, refusalMessage(response.status, preview)) } if (!response.body || !response.headers.get('content-type')?.includes('text/event-stream')) { await response.body?.cancel()