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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions __tests__/desktop/console-transcript.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof vi.fn>
let onStream: ReturnType<typeof vi.fn>

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: '<Inputs>\n{$MELINDA_INFO}\n</Inputs>\n<Instructions Structure>\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<HTMLElement>(
`#display .line.type-agent[data-request-id="${requestId}"]`
)
expect(streamLine?.textContent).toContain('<Inputs>\n{$MELINDA_INFO}\n</Inputs>')
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: '<Inputs>\n{$MELINDA_INFO}\n</Inputs>\n<Instructions Structure>\n1. Role\n2. Cut off...',
})
await vi.advanceTimersByTimeAsync(1500)

handleError?.({
requestId,
message: 'The prompt template was cut off before </Instructions> closed (token limit reached).',
failure: {
code: 'TEMPLATE_INCOMPLETE',
stage: 'stream',
retryable: true,
publicMessage:
'The prompt template was cut off before </Instructions> 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('<Instructions Structure>')).toBeUndefined()
})
})
10 changes: 8 additions & 2 deletions __tests__/optimizer/prompt-template-format.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <Instructions> opened without a closing tag', () => {
expect(() => parsePromptTemplate('<Inputs>\n{$X}\n</Inputs>\n<Instructions>\nHalf a')).toThrow(
'No <Instructions> block'
'cut off before </Instructions> closed'
)
})

it('throws when the response has no <Instructions> block at all', () => {
expect(() => parsePromptTemplate('<Inputs>\n{$X}\n</Inputs>\nJust plain prose')).toThrow(
'No <Instructions> block found in the response.'
)
})
})
Expand Down
15 changes: 12 additions & 3 deletions __tests__/optimizer/prompt-template-generation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ describe('prompt template generation', () => {
const [request] = provider.requests
expect(request.userPrompt).toContain(`<Task>\n${templateRequest.rawIdea}\n</Task>`)
expect(request.userPrompt).toMatch(/Start your response directly with the <Inputs> block\.[^]*$/)
expect(request.maxTokens).toBe(4096)
expect(request.maxTokens).toBe(8192)
expect(getScopedProviderOverrides).toHaveBeenCalledWith('CLAUDE', 'OPTIMIZER', 'DEEP')
})

Expand All @@ -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 <Instructions> never closes', async () => {
const provider = makeFakeProvider('<Inputs>\n{$X}\n</Inputs>\n<Instructions>\nCut off')
vi.mocked(getProvider).mockReturnValue(provider as never)
const chunks: string[] = []

await expect(
optimizePromptStreaming(templateRequest, (delta) => chunks.push(delta))
).rejects.toThrow('No <Instructions> block found in the response.')
).rejects.toThrow('cut off before </Instructions> closed')
expect(chunks.join('')).toContain('Cut off')
})

it('streams, then fails fast when the response has no <Instructions> block at all', async () => {
const provider = makeFakeProvider('<Inputs>\n{$X}\n</Inputs>\nNo instructions block here')
vi.mocked(getProvider).mockReturnValue(provider as never)

await expect(
optimizePromptStreaming(templateRequest, () => undefined)
).rejects.toThrow('No <Instructions> block found in the response.')
})

it('lets the desktop recent-run store keep a Prompt Template run', () => {
const record = {
id: 'run-1',
Expand Down
29 changes: 18 additions & 11 deletions desktop/renderer/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
})
}
Expand Down Expand Up @@ -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) {
Expand All @@ -2070,7 +2072,9 @@ async function executeOptimizeStream(

function step(): void {
if (!activeScrambleLine) {
onComplete()
const flushed = pendingChunks
pendingChunks = ''
onComplete(flushed)
return
}
revealed++
Expand All @@ -2079,8 +2083,9 @@ async function executeOptimizeStream(
if (revealed < len) {
decodeTimeoutId = setTimeout(step, DECODE_CHAR_MS)
} else {
const flushed = pendingChunks
clearScramble()
onComplete()
onComplete(flushed)
}
}

Expand Down Expand Up @@ -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
})
}
Expand Down Expand Up @@ -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' &&
Expand Down
4 changes: 2 additions & 2 deletions lib/optimizer/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,15 +227,15 @@ 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'])

/**
* 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 <Instructions> block.
*/
Expand Down
5 changes: 5 additions & 0 deletions lib/optimizer/prompt-template-format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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('<Instructions>')) {
throw new PromptTemplateError(
'The prompt template was cut off before </Instructions> closed (token limit reached). Try shortening the request or run again.'
)
}
throw new PromptTemplateError(
'No <Instructions> block found in the response. Run the same request again.'
)
Expand Down
Loading