diff --git a/src/components/LimitSwitchDialog.test.ts b/src/components/LimitSwitchDialog.test.ts new file mode 100644 index 0000000000..75545cb099 --- /dev/null +++ b/src/components/LimitSwitchDialog.test.ts @@ -0,0 +1,78 @@ +import { expect, test } from 'bun:test' + +import { describeFailedTurn, limitSwitchDoneMessage, limitSwitchModelOptions } from './LimitSwitchDialog.js' + +test('offers Verboo models, last used first, plus keeping the current one', () => { + const options = limitSwitchModelOptions( + [ + { id: 'ultra/a', displayName: 'A' }, + { id: 'ultra/b', displayName: 'B' }, + { id: 'ultra/c' }, + ], + 'ultra/b', + ) + expect(options.map(option => option.value)).toEqual([ + 'ultra/b', + 'ultra/a', + 'ultra/c', + '__keep_current_model__', + ]) + expect(options[2]?.label).toBe('ultra/c') +}) + +test('caps the list at five models', () => { + const models = Array.from({ length: 8 }, (_, i) => ({ id: `m${i}` })) + expect(limitSwitchModelOptions(models, undefined)).toHaveLength(6) +}) + +const limitError = { type: 'assistant', isApiErrorMessage: true, message: { content: [{ type: 'text', text: 'limit' }] } } +const reply = { type: 'assistant', message: { content: [{ type: 'text', text: 'ok' }] } } + +test('a turn where nothing ran can be sent again', () => { + const turn = describeFailedTurn([ + { type: 'user', uuid: 'old', message: { content: 'first request' } }, + reply, + { type: 'user', uuid: 'new', message: { content: 'refactor the parser' } }, + { type: 'user', isMeta: true, message: { content: 'system reminder' } }, + limitError, + ] as never) + expect(turn).toEqual({ prompt: 'refactor the parser', promptUuid: 'new', toolsRan: false }) + expect(describeFailedTurn([] as never)).toEqual({ prompt: null, toolsRan: false }) +}) + +test('a turn that already ran tools is reported, so it is not repeated', () => { + const turn = describeFailedTurn([ + { type: 'user', uuid: 'new', message: { content: 'append to the file' } }, + { type: 'assistant', message: { content: [{ type: 'tool_use', id: 't', name: 'Bash', input: {} }] } }, + { type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 't', content: 'out' }] } }, + limitError, + ] as never) + expect(turn.toolsRan).toBe(true) + expect(limitSwitchDoneMessage('m', turn)).toContain('nada foi reenviado') +}) + +test('the compaction summary is not mistaken for what the user typed', () => { + const turn = describeFailedTurn([ + { type: 'user', uuid: 'typed', message: { content: 'next step' } }, + { type: 'system', subtype: 'compact_boundary' }, + { type: 'user', isCompactSummary: true, isVisibleInTranscriptOnly: true, message: { content: 'This session is being continued' } }, + limitError, + ] as never) + expect(turn.prompt).toBe('next step') +}) + +test('a turn not started by typed text never falls back to an older prompt', () => { + for (const content of [ + [{ type: 'image', source: {} }, { type: 'text', text: 'see this' }], + 'done', + 'agent finished', + ]) { + const turn = describeFailedTurn([ + { type: 'user', uuid: 'old', message: { content: 'older prompt' } }, + reply, + { type: 'user', uuid: 'new', message: { content } }, + limitError, + ] as never) + expect(turn.prompt).toBeNull() + } +}) diff --git a/src/components/LimitSwitchDialog.tsx b/src/components/LimitSwitchDialog.tsx new file mode 100644 index 0000000000..729dc02d8a --- /dev/null +++ b/src/components/LimitSwitchDialog.tsx @@ -0,0 +1,128 @@ +import * as React from 'react' + +import { getUserMessageText, textForResubmit } from '../utils/messages.js' +import type { Message, UserMessage } from '../types/message.js' +import { Select } from './CustomSelect/select.js' +import { Dialog } from './design-system/Dialog.js' +import { Box, Text } from '../ink.js' + +const KEEP = '__keep_current_model__' +const MAX_MODELS = 5 +// Text the CLI itself placed in a user message; the user did not type it. +const NOT_TYPED = /^\s*<(local-command-|bash-|task-notification)/ + +/** Verboo models to offer, the last Verboo model used first. */ +export function limitSwitchModelOptions( + models: ReadonlyArray<{ id: string; displayName?: string }>, + lastRouterModel: string | undefined, +): Array<{ label: string; value: string }> { + const ordered = [...models].sort((a, b) => + a.id === lastRouterModel ? -1 : b.id === lastRouterModel ? 1 : 0, + ) + return [ + ...ordered.slice(0, MAX_MODELS).map(model => ({ + label: model.displayName ?? model.id, + value: model.id, + })), + { label: 'Manter o modelo atual', value: KEEP }, + ] +} + +export type FailedTurn = { + /** The prompt that started the failed turn, when it can be sent again as is. */ + prompt: string | null + promptUuid?: string + /** Tools already ran in this turn: sending the prompt again would repeat them. */ + toolsRan: boolean +} + +/** Looks back from the limit error to the message that started that turn. */ +export function describeFailedTurn(messages: readonly Message[]): FailedTurn { + let toolsRan = false + for (let i = messages.length - 1; i >= 0; i--) { + const message = messages[i]! + if (message.type === 'assistant') { + const content = message.message.content + if (Array.isArray(content) && content.some(block => block.type === 'tool_use')) { + toolsRan = true + } + continue + } + if ( + message.type !== 'user' || + message.isMeta || + message.isCompactSummary || + message.isVisibleInTranscriptOnly + ) { + continue + } + const content = message.message.content + if (Array.isArray(content) && content.some(block => block.type === 'tool_result')) { + continue + } + // Images and other attachments cannot be sent again from the text alone. + const hasOnlyText = !Array.isArray(content) || content.every(block => block.type === 'text') + const resubmit = hasOnlyText ? textForResubmit(message as UserMessage) : null + const text = resubmit?.mode === 'prompt' ? resubmit.text : '' + return { + prompt: text.trim() && !NOT_TYPED.test(getUserMessageText(message as UserMessage) ?? '') ? text : null, + promptUuid: message.uuid, + toolsRan, + } + } + return { prompt: null, toolsRan } +} + +export function limitSwitchDoneMessage(model: string, turn: FailedTurn): string { + if (turn.toolsRan) { + return `Modelo alterado para ${model}. A resposta anterior parou depois de executar ferramentas, então nada foi reenviado para não repetir ações. Diga como continuar.` + } + if (turn.prompt === null) { + return `Modelo alterado para ${model}. Envie sua mensagem novamente para continuar.` + } + return `Modelo alterado para ${model}.` +} + +type Props = { + reason: string + models: ReadonlyArray<{ id: string; displayName?: string }> + lastRouterModel: string | undefined + turn: FailedTurn + onSwitch: (model: string) => void + onKeep: () => void +} + +/** + * Opened by the REPL when the user's own account (ChatGPT plan, OpenAI or + * Anthropic key) runs out; offers to continue on a Verboo model. + */ +export function LimitSwitchDialog({ + reason, + models, + lastRouterModel, + turn, + onSwitch, + onKeep, +}: Props): React.ReactNode { + const options = limitSwitchModelOptions(models, lastRouterModel) + const consequence = turn.toolsRan + ? ' Sua última mensagem não será reenviada, porque ela já executou ferramentas.' + : turn.prompt !== null + ? ' Sua última mensagem será reenviada.' + : '' + return ( + + + {reason.charAt(0).toUpperCase() + reason.slice(1)} + Trocar para um modelo Verboo?{consequence} +