diff --git a/__tests__/desktop/console-transcript.test.ts b/__tests__/desktop/console-transcript.test.ts index 0562a1d..c7eaff7 100644 --- a/__tests__/desktop/console-transcript.test.ts +++ b/__tests__/desktop/console-transcript.test.ts @@ -1129,3 +1129,127 @@ describe('console startup block state variants', () => { expect(findLine('briefs today')).toBeUndefined() }) }) + +describe('console optimize stream decode & template error handling', () => { + let invoke: ReturnType + let onStream: ReturnType + + beforeEach(async () => { + vi.useFakeTimers() + vi.resetModules() + document.open() + document.write(rendererHtml) + document.close() + + invoke = vi.fn().mockResolvedValue({}) + onStream = vi.fn() + vi.stubGlobal('sentraDesktop', { + getShellState: vi.fn().mockResolvedValue({ + providerReadiness: { + status: 'ready', + availableProviders: ['CLAUDE'], + activeProvider: 'CLAUDE', + }, + preferredProvider: 'CLAUDE', + }), + invoke, + auth: { getSession: vi.fn().mockResolvedValue(null) }, + workspace: { + listDrafts: vi.fn().mockResolvedValue([]), + saveDraft: vi.fn().mockResolvedValue({}), + listRecentRuns: vi.fn().mockResolvedValue([]), + listBenchmarks: vi.fn().mockResolvedValue([]), + }, + onStream, + offStream: vi.fn(), + close: vi.fn(), + minimize: vi.fn(), + getWindowPos: vi.fn().mockResolvedValue([0, 0]), + setWindowPos: vi.fn(), + }) + + await import('../../desktop/renderer/renderer') + await vi.waitFor(() => + expect((document.getElementById('cmdInput') as HTMLInputElement).disabled).toBe(false) + ) + }) + + afterEach(() => { + vi.useRealTimers() + vi.unstubAllGlobals() + vi.restoreAllMocks() + document.body.replaceChildren() + }) + + function getHandler(channelName: string) { + return onStream.mock.calls.find(([channel]) => channel === channelName)?.[1] as + | ((payload: unknown) => void) + | undefined + } + + function getLatestOptimizeRequestId() { + const call = invoke.mock.calls.find( + ([channel, payload]) => + channel === 'desktop:command' && (payload as { command?: string }).command === 'optimize:run' + ) + return (call?.[1] as { payload: { requestId: string } }).payload.requestId + } + + it('flushes buffered scramble chunks to the stream line instead of dropping the prefix', async () => { + type('build receptionist prompt') + await vi.waitFor(() => expect(getLatestOptimizeRequestId()).toBeTruthy()) + + const requestId = getLatestOptimizeRequestId() + const handleStatus = getHandler('optimize:status') + const handleChunk = getHandler('optimize:chunk') + + handleStatus?.({ requestId, stage: 'waiting', message: 'Waiting for claude...' }) + // Send >36 chars so decode starts immediately, plus an extra chunk during decode. + handleChunk?.({ requestId, delta: '\n{$MELINDA_INFO}\n\n\n1. Role\n' }) + handleChunk?.({ requestId, delta: '2. State the goal.' }) + + // Advance timers long enough for 36-char decode (36 * 30ms = 1080ms) to finish. + await vi.advanceTimersByTimeAsync(1500) + + const streamLine = document.querySelector( + `#display .line.type-agent[data-request-id="${requestId}"]` + ) + expect(streamLine?.textContent).toContain('\n{$MELINDA_INFO}\n') + expect(streamLine?.textContent).toContain('2. State the goal.') + }) + + it('removes raw partial XML from the stream line when TEMPLATE_INCOMPLETE fails', async () => { + type('build receptionist prompt') + await vi.waitFor(() => expect(getLatestOptimizeRequestId()).toBeTruthy()) + + const requestId = getLatestOptimizeRequestId() + const handleStatus = getHandler('optimize:status') + const handleChunk = getHandler('optimize:chunk') + const handleError = getHandler('optimize:error') + + handleStatus?.({ requestId, stage: 'waiting', message: 'Waiting for claude...' }) + handleChunk?.({ + requestId, + delta: '\n{$MELINDA_INFO}\n\n\n1. Role\n2. Cut off...', + }) + await vi.advanceTimersByTimeAsync(1500) + + handleError?.({ + requestId, + message: 'The prompt template was cut off before closed (token limit reached).', + failure: { + code: 'TEMPLATE_INCOMPLETE', + stage: 'stream', + retryable: true, + publicMessage: + 'The prompt template was cut off before closed (token limit reached).', + }, + }) + + await vi.waitFor(() => expect(findLine('[TEMPLATE_INCOMPLETE]')).toBeTruthy()) + expect( + document.querySelector(`#display .line.type-agent[data-request-id="${requestId}"]`) + ).toBeNull() + expect(findLine('')).toBeUndefined() + }) +}) diff --git a/__tests__/optimizer/prompt-template-format.test.ts b/__tests__/optimizer/prompt-template-format.test.ts index 6f74a00..639d2ef 100644 --- a/__tests__/optimizer/prompt-template-format.test.ts +++ b/__tests__/optimizer/prompt-template-format.test.ts @@ -42,9 +42,15 @@ describe('parsePromptTemplate', () => { expect(variables).toEqual(['$COMPANY_NAME', '$CUSTOMER_EMAIL']) }) - it('throws when the response has no closed Instructions block (e.g. cut off)', () => { + it('throws a cut-off message when opened without a closing tag', () => { expect(() => parsePromptTemplate('\n{$X}\n\n\nHalf a')).toThrow( - 'No block' + 'cut off before closed' + ) + }) + + it('throws when the response has no block at all', () => { + expect(() => parsePromptTemplate('\n{$X}\n\nJust plain prose')).toThrow( + 'No block found in the response.' ) }) }) diff --git a/__tests__/optimizer/prompt-template-generation.test.ts b/__tests__/optimizer/prompt-template-generation.test.ts index 363b5c5..f317e5b 100644 --- a/__tests__/optimizer/prompt-template-generation.test.ts +++ b/__tests__/optimizer/prompt-template-generation.test.ts @@ -82,7 +82,7 @@ describe('prompt template generation', () => { const [request] = provider.requests expect(request.userPrompt).toContain(`\n${templateRequest.rawIdea}\n`) expect(request.userPrompt).toMatch(/Start your response directly with the block\.[^]*$/) - expect(request.maxTokens).toBe(4096) + expect(request.maxTokens).toBe(8192) expect(getScopedProviderOverrides).toHaveBeenCalledWith('CLAUDE', 'OPTIMIZER', 'DEEP') }) @@ -109,17 +109,26 @@ describe('prompt template generation', () => { } }) - it('streams, then fails fast on a response without a closed Instructions block', async () => { + it('streams, then fails fast with cut-off guidance when never closes', async () => { const provider = makeFakeProvider('\n{$X}\n\n\nCut off') vi.mocked(getProvider).mockReturnValue(provider as never) const chunks: string[] = [] await expect( optimizePromptStreaming(templateRequest, (delta) => chunks.push(delta)) - ).rejects.toThrow('No block found in the response.') + ).rejects.toThrow('cut off before closed') expect(chunks.join('')).toContain('Cut off') }) + it('streams, then fails fast when the response has no block at all', async () => { + const provider = makeFakeProvider('\n{$X}\n\nNo instructions block here') + vi.mocked(getProvider).mockReturnValue(provider as never) + + await expect( + optimizePromptStreaming(templateRequest, () => undefined) + ).rejects.toThrow('No block found in the response.') + }) + it('lets the desktop recent-run store keep a Prompt Template run', () => { const record = { id: 'run-1', diff --git a/desktop/renderer/renderer.ts b/desktop/renderer/renderer.ts index 4c2bcb2..1d46cd0 100644 --- a/desktop/renderer/renderer.ts +++ b/desktop/renderer/renderer.ts @@ -1982,11 +1982,11 @@ function removeOptimizeStreamArtifacts( } } -function clearOptimizeTransientFailureArtifacts(requestId: string) { +function clearOptimizeTransientFailureArtifacts(requestId: string, forceRemoveStreamLine = false) { const streamLine = activeOptimizeLines.get(requestId) removeOptimizeStreamArtifacts(requestId, { - removeStreamLine: streamLine?.textContent?.trim().length === 0, + removeStreamLine: forceRemoveStreamLine || streamLine?.textContent?.trim().length === 0, removeStatusLine: true, }) } @@ -2055,9 +2055,11 @@ async function executeOptimizeStream( }, SCRAMBLE_INTERVAL_MS) } - function startDecode(target: string, onComplete: () => void): void { + function startDecode(target: string, onComplete: (flushed: string) => void): void { if (!activeScrambleLine) { - onComplete() + const flushed = pendingChunks + pendingChunks = '' + onComplete(flushed) return } if (scrambleIntervalId !== null) { @@ -2070,7 +2072,9 @@ async function executeOptimizeStream( function step(): void { if (!activeScrambleLine) { - onComplete() + const flushed = pendingChunks + pendingChunks = '' + onComplete(flushed) return } revealed++ @@ -2079,8 +2083,9 @@ async function executeOptimizeStream( if (revealed < len) { decodeTimeoutId = setTimeout(step, DECODE_CHAR_MS) } else { + const flushed = pendingChunks clearScramble() - onComplete() + onComplete(flushed) } } @@ -2130,9 +2135,8 @@ async function executeOptimizeStream( const readyByTimeout = Date.now() - decodeAccumStartMs >= DECODE_BUFFER_TIMEOUT_MS if (readyByLength || readyByTimeout) { - startDecode(decodeTarget.slice(0, DECODE_TARGET_LENGTH), () => { - streamLine.textContent += pendingChunks - pendingChunks = '' + startDecode(decodeTarget.slice(0, DECODE_TARGET_LENGTH), (flushed) => { + streamLine.textContent += flushed container.scrollTop = container.scrollHeight }) } @@ -2234,10 +2238,13 @@ async function executeOptimizeStream( return } + const failure = payload.failure + const failureCode = + isObjectRecord(failure) && typeof failure.code === 'string' ? failure.code : null + clearScramble() - clearOptimizeTransientFailureArtifacts(requestId) + clearOptimizeTransientFailureArtifacts(requestId, failureCode === 'TEMPLATE_INCOMPLETE') cleanup() - const failure = payload.failure const safeFailureMessage = isObjectRecord(failure) && typeof failure.code === 'string' && diff --git a/lib/optimizer/engine.ts b/lib/optimizer/engine.ts index 2edc2b9..5d200a0 100644 --- a/lib/optimizer/engine.ts +++ b/lib/optimizer/engine.ts @@ -227,7 +227,7 @@ async function runCodingBriefRoute( // ── Prompt Template route (Anthropic Metaprompt) ───────────────────────── -const PROMPT_TEMPLATE_MAX_TOKENS = 4096 +const PROMPT_TEMPLATE_MAX_TOKENS = 8192 const PROMPT_TEMPLATE_TEMPERATURE = 0 // Anthropic reports 'max_tokens', OpenAI-compatible providers 'length'. const TOKEN_LIMIT_FINISH_REASONS = new Set(['max_tokens', 'length']) @@ -235,7 +235,7 @@ const TOKEN_LIMIT_FINISH_REASONS = new Set(['max_tokens', 'length']) /** * Generate a reusable prompt template with the Metaprompt, called like the notebook: the * Metaprompt as the only (user) message, no system prompt, temperature 0. Always uses the DEEP - * provider scope: the few-shot prompt plus up to 4K output tokens exceeds the INTERACTIVE + * provider scope: the few-shot prompt plus up to 8K output tokens exceeds the INTERACTIVE * latency budget. Like the notebook it fails fast, with a PromptTemplateError, when the * response hit the token limit or holds no closed block. */ diff --git a/lib/optimizer/prompt-template-format.ts b/lib/optimizer/prompt-template-format.ts index 2cb51f0..dd1f884 100644 --- a/lib/optimizer/prompt-template-format.ts +++ b/lib/optimizer/prompt-template-format.ts @@ -41,6 +41,11 @@ function removeTrailingEmptyTag(text: string): string { export function parsePromptTemplate(raw: string): ParsedPromptTemplate { const match = raw.match(INSTRUCTIONS_PATTERN) if (!match) { + if (raw.includes('')) { + throw new PromptTemplateError( + 'The prompt template was cut off before closed (token limit reached). Try shortening the request or run again.' + ) + } throw new PromptTemplateError( 'No block found in the response. Run the same request again.' )