The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.
Desktop: a failed turn says why, not "Internal error" (#89)
riverisbuilding7a64d1feacdb
diff --git a/.changeset/agent-error-cause.md b/.changeset/agent-error-cause.mdnew file mode 100644index 0000000..522975d--- /dev/null+++ b/.changeset/agent-error-cause.md@@ -0,0 +1,5 @@+---+'@openfilm/desktop': patch+---++Desktop: a chat turn that fails says why (the model service didn't answer, the context is too long, and others) instead of "Internal error".diff --git a/apps/desktop/src/agents.mjs b/apps/desktop/src/agents.mjsindex ea35949..eb0ff49 100644--- a/apps/desktop/src/agents.mjs+++ b/apps/desktop/src/agents.mjs@@ -657,15 +657,27 @@ export function codexTooOld(agent, path, e, versionOf = codexVersion) {return Object.assign(new Error(`Codex ${version} is older than OpenFilm needs (${CODEX_TESTED} or later): update Codex, then try again. ${why}`.trim()), { code: 'outdated' });}+/** ACP's internal error: what an agent's own failures come as. */+const INTERNAL_ERROR = -32603;+/**- * A session refused for the agent's sign-in, said so (`code: 'sign-in'`); any other error with its reason: an error- * the agent sends as "Internal error" carries the reason in its `data` (Codex's settings it cannot read, for one).+ * A session refused for the agent's sign-in, said so (`code: 'sign-in'`); any other error with its reason (errorCause).*/export function signInError(label, e) {if (e?.code === AUTH_REQUIRED) return Object.assign(new Error(`${label} is not signed in. Sign in under Settings → Agents.`), { code: 'sign-in' });- const data = e?.data;+ return errorCause(e);+}++/**+ * An error the agent sends as just "Internal error" with its reason: the reason is in its `data`, as a string or its+ * `message` or `details` (the ACP SDK puts a thrown Error's text there; Codex its settings it cannot read). The error+ * it came as stays its `cause`.+ */+export function errorCause(e) {+ if (e?.code !== INTERNAL_ERROR || String(e.message ?? '').trim() !== 'Internal error') return e;+ const data = e.data;const why = typeof data === 'string' ? data : [data?.message, data?.details].find((v) => typeof v === 'string') ?? '';- return why.trim() ? Object.assign(new Error(why.trim()), { code: e.code }) : e;+ return why.trim() ? Object.assign(new Error(why.trim(), { cause: e }), { code: e.code }) : e;}/** The answer that lets it go ahead (for good, where it offers that), or null when none does. */@@ -888,7 +900,7 @@ export class AgentSession {const own = this.opts.harness?.models?.find((m) => m.id === this.modelNow) ?? this.opts.harness?.models?.[0];const broke = own ? outOfBalance({ id: own.name, baseUrl: own.baseUrl }, e) : null;if (broke) throw broke;- if (!isAgentId(this.opts.agent)) throw e;+ if (!isAgentId(this.opts.agent)) throw errorCause(e);const said = signInError(this.spec.label, e);if (said.code === 'sign-in') noteSignedOut(this.opts.agent);throw said;diff --git a/apps/desktop/src/agents.test.mjs b/apps/desktop/src/agents.test.mjsindex 6ad0172..18d906e 100644--- a/apps/desktop/src/agents.test.mjs+++ b/apps/desktop/src/agents.test.mjs@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { CLIENT_CAPABILITIES, CODEX_UTF8_CMD, agentShell, allowOption, codexDeveloperInstructions, codexLaunchEnv, legacyOptions, powerShellScript, readAgentStatus, signInError, codexTooOld } from './agents.mjs';+import { CLIENT_CAPABILITIES, CODEX_UTF8_CMD, agentShell, allowOption, codexDeveloperInstructions, codexLaunchEnv, errorCause, legacyOptions, powerShellScript, readAgentStatus, signInError, codexTooOld } from './agents.mjs';test('an agent that asks: yes for good where it offers that, else yes this once; nothing to say yes with is null', () => {const options = [@@ -57,6 +57,22 @@ test('an error the agent sends as "Internal error" carries its reason; a sign-inassert.equal(signInError('Codex', Object.assign(new Error('Authentication required'), { code: -32000 })).code, 'sign-in');});+test('a turn the agent ends with just "Internal error" says the reason in its data; the error as sent stays its cause', () => {+ /* the ACP SDK's own shape for a thrown Error: its text as data.details */+ const sent = Object.assign(new Error('Internal error'), { code: -32603, data: { details: 'Request timed out.' } });+ const e = errorCause(sent);+ assert.equal(e.message, 'Request timed out.');+ assert.equal(e.cause, sent);+ assert.equal(errorCause(Object.assign(new Error('Internal error'), { code: -32603, data: 'model not found' })).message, 'model not found');+ /* an error that says its reason itself, or has none in data, as it came */+ const said = Object.assign(new Error('The model service did not answer.'), { code: -32603, data: { details: 'Request timed out.' } });+ assert.equal(errorCause(said), said);+ const bare = Object.assign(new Error('Internal error'), { code: -32603, data: { errorKind: 'transport_lost' } });+ assert.equal(errorCause(bare), bare);+ const other = Object.assign(new Error('Invalid params'), { code: -32602, data: { message: 'x' } });+ assert.equal(errorCause(other), other);+});+test("the person's own developer_instructions in Codex's config, read as TOML writes them; a profile's is not theirs at the top", () => {assert.equal(codexDeveloperInstructions('model = "gpt"\ndeveloper_instructions = "Be brief.\\nSay \\"why\\"."\n'), 'Be brief.\nSay "why".');assert.equal(codexDeveloperInstructions("developer_instructions = 'C:\\no\\escapes'"), 'C:\\no\\escapes');diff --git a/apps/desktop/src/local-agents-ipc.mjs b/apps/desktop/src/local-agents-ipc.mjsindex c2f4797..14e23e5 100644--- a/apps/desktop/src/local-agents-ipc.mjs+++ b/apps/desktop/src/local-agents-ipc.mjs@@ -270,11 +270,15 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbacentry.running = (entry.running ?? 0) + 1;onWorking(working());let result;+ /* the error as the agent sent it (ACP's code, message and data), for the turn log */+ let raw = null;try {result = { ok: true, stopReason: await entry.session.prompt([{ type: 'text', text }, ...images], { turnId: meta?.turnId }) };} catch (e) {/* `balance`: the service the app's own agent runs on has no balance left (agents.mjs), and where to top it up */result = { ok: false, error: e instanceof Error ? e.message : String(e), ...(e?.balance ? { balance: e.balance } : {}) };+ const asSent = e?.cause ?? e;+ if (typeof asSent?.code === 'number') raw = { code: asSent.code, message: asSent.message, data: asSent.data ?? null };} finally {activePrompts--;entry.running -= 1;@@ -283,7 +287,7 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbacentry.lastUsed = Date.now();if (turn) {/* a turn that failed: what the agent's process last wrote to stderr says why */- turn.file.write('done', result.ok ? result : { ...result, stderr: String(entry.session?.stderr ?? '').slice(-8000) });+ turn.file.write('done', result.ok ? result : { ...result, ...(raw ? { raw } : {}), stderr: String(entry.session?.stderr ?? '').slice(-8000) });turn.file.end();turn.done = result;entry.turnEnded = Date.now();diff --git a/apps/desktop/src/pi-agent.mjs b/apps/desktop/src/pi-agent.mjsindex 866bece..82f0481 100644--- a/apps/desktop/src/pi-agent.mjs+++ b/apps/desktop/src/pi-agent.mjs@@ -137,7 +137,7 @@ async function open(client, cwd, resumeId) {const now = ownOf(session.model);const onModel = now.id ?? startModel;const levels = byId.get(onModel)?.levels ?? ['auto'];- const entry = { session, log: null, model: onModel,+ const entry = { session, log: null, answer: null, overflow: null, model: onModel,effort: now.thinking && levels.includes(session.thinkingLevel) ? session.thinkingLevel : !now.thinking && levels.includes('auto') ? 'auto' : byId.get(onModel)?.effort ?? 'auto' };/* a conversation taken up again on a model no longer set up: on the one a session starts on */if (!now.id) await use(entry, onModel, entry.effort);@@ -155,6 +155,8 @@ async function open(client, cwd, resumeId) {case 'message_end': {const message = event.message;if (message?.role !== 'assistant') break;+ /* the turn's last answer: Pi drops one too long for the model from the conversation as it tries to recover */+ entry.answer = message;if (pending && entry.log) {const toolsNow = (session.agent?.state?.tools ?? []).map((t) => ({ name: t.name, description: t.description, parameters: t.parameters }));entry.log.write({ startedAt: pending.startedAt, messages: pending.messages, toolsNow, answer: { message, systemPrompt: session.systemPrompt } });@@ -176,6 +178,10 @@ async function open(client, cwd, resumeId) {send({ sessionUpdate: 'tool_call_update', toolCallId: event.toolCallId, status: event.isError ? 'failed' : 'completed',content: toolContent(event.result), rawOutput: event.result?.content?.filter?.((b) => b?.type === 'text').map((b) => b.text).join('\n') ?? '' });break;+ case 'compaction_end':+ /* Pi could not make room for the conversation: the turn ends on that (its last answer may not say it) */+ if (event.reason === 'overflow' && event.errorMessage) entry.overflow = event.errorMessage;+ break;default: break;}});@@ -254,6 +260,21 @@ function promptOf(blocks) {return { text: text.join('\n'), images };}+/**+ * A failure with its own text: the SDK sends a plain Error as "Internal error", its text only in `data`. Pi's own words,+ * when the text is plainer (pi-config.mjs failureText), go as `details`.+ */+function failed(e) {+ if (e instanceof acp.RequestError) return e;+ const text = e instanceof Error ? e.message : String(e);+ return new acp.RequestError(-32603, text, typeof e?.details === 'string' && e.details !== text ? { details: e.details } : undefined);+}++/** A request whose failure the chat shows as it is said. */+const said = (handler) => async (params) => {+ try { return await handler(params); } catch (e) { throw failed(e); }+};+const connection = new acp.AgentSideConnection((client) => ({async initialize() {return {@@ -264,25 +285,27 @@ const connection = new acp.AgentSideConnection((client) => ({};},async authenticate() { return {}; },- async newSession(params) { return open(client, params.cwd, null); },- async resumeSession(params) { return open(client, params.cwd, params.sessionId); },- async prompt(params) {+ newSession: said((params) => open(client, params.cwd, null)),+ resumeSession: said((params) => open(client, params.cwd, params.sessionId)),+ prompt: said(async (params) => {const entry = sessions.get(params.sessionId);if (!entry) throw new Error('This conversation has ended.');const { session } = entry;const meta = params._meta?.openfilm ?? {};entry.log = typeof meta.turnId === 'string' && typeof meta.cwd === 'string' ? modelLog(meta.cwd, meta.turnId) : null;+ entry.answer = null;+ entry.overflow = null;try {const { text, images } = promptOf(params.prompt);await session.prompt(text, images.length ? { images } : undefined);- const last = [...session.messages].reverse().find((m) => m.role === 'assistant');- return { stopReason: stopReason(last) };+ const last = entry.answer ?? [...session.messages].reverse().find((m) => m.role === 'assistant');+ return { stopReason: stopReason(entry.overflow && last?.stopReason !== 'aborted' ? { stopReason: 'error', errorMessage: entry.overflow } : last) };} finally {entry.log?.end();entry.log = null;}- },- async setSessionConfigOption(params) {+ }),+ setSessionConfigOption: said(async (params) => {const entry = sessions.get(params.sessionId);if (!entry) throw new Error('This conversation has ended.');if (params.configId === 'model') {@@ -297,7 +320,7 @@ const connection = new acp.AgentSideConnection((client) => ({await use(entry, entry.model, effort);} else throw new Error(`No option ${params.configId}.`);return { configOptions: optionsOf(entry) };- },+ }),async cancel(params) { await sessions.get(params.sessionId)?.session.abort(); },async closeSession(params) {sessions.get(params.sessionId)?.session.dispose();diff --git a/apps/desktop/src/pi-agent.test.mjs b/apps/desktop/src/pi-agent.test.mjsindex 0c03416..ff904f8 100644--- a/apps/desktop/src/pi-agent.test.mjs+++ b/apps/desktop/src/pi-agent.test.mjs@@ -7,7 +7,7 @@ import { join } from 'node:path';import { AgentSession } from './agents.mjs';/** A service on the Chat Completions API that answers "ok" and notes the model each request named (and each request, and its key). */-async function service({ broke = false } = {}) {+async function service({ broke = false, fails = null } = {}) {const asked = [];const bodies = [];const keys = [];@@ -20,6 +20,7 @@ async function service({ broke = false } = {}) {bodies.push(JSON.parse(body || '{}'));keys.push(String(req.headers.authorization ?? ''));if (broke) { res.writeHead(402, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: { message: 'Insufficient Balance' } })); return; }+ if (fails) { res.writeHead(400, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: { message: fails } })); return; }res.writeHead(200, { 'content-type': 'text/event-stream' });const chunk = (choice, extra = {}) => `data: ${JSON.stringify({ id: 'c', object: 'chat.completion.chunk', created: 0, model, choices: [choice], ...extra })}\n\n`;res.end(chunk({ index: 0, delta: { role: 'assistant', content: 'ok' }, finish_reason: null })@@ -135,3 +136,39 @@ test('a service with no balance left is named for the model the turn was on, notsecond.close();}});++test('a turn that fails says why, as the service said it, not "Internal error"', { timeout: 60_000 }, async () => {+ const svc = await service({ fails: 'The model `big` does not exist.' });+ const session = new AgentSession({+ agent: 'byok',+ cwd: mkdtempSync(join(tmpdir(), 'of-pi-')),+ harness: { home: mkdtempSync(join(tmpdir(), 'of-pi-home-')), models: [own('a', svc.url)], model: 'a', env: { OPENFILM_BYOK_KEY_a: 'sk' } },+ });+ try {+ await session.start();+ const error = await session.prompt([{ type: 'text', text: 'hi' }]).then(() => null, (e) => e);+ assert.match(error?.message ?? '', /The model `big` does not exist\./);+ assert.equal(error.code, -32603);+ } finally {+ session.close();+ svc.close();+ }+});++test('a conversation too long for the model says so, and where its context is set', { timeout: 60_000 }, async () => {+ const svc = await service({ fails: "This model's maximum context length is 1000 tokens. However, you requested about 2000 tokens." });+ const session = new AgentSession({+ agent: 'byok',+ cwd: mkdtempSync(join(tmpdir(), 'of-pi-')),+ harness: { home: mkdtempSync(join(tmpdir(), 'of-pi-home-')), models: [own('a', svc.url)], model: 'a', env: { OPENFILM_BYOK_KEY_a: 'sk' } },+ });+ try {+ await session.start();+ const error = await session.prompt([{ type: 'text', text: 'hi' }]).then(() => null, (e) => e);+ assert.equal(error?.message, "The conversation is too long for the model. The model's context may be smaller than set in Settings: lower it there.");+ assert.match(error.data?.details ?? '', /maximum context length is 1000 tokens/, 'what the service said goes too');+ } finally {+ session.close();+ svc.close();+ }+});diff --git a/apps/desktop/src/pi-config.mjs b/apps/desktop/src/pi-config.mjsindex ccfeef2..77518f1 100644--- a/apps/desktop/src/pi-config.mjs+++ b/apps/desktop/src/pi-config.mjs@@ -133,16 +133,38 @@ export function toolContent(result) {: []));}-/** How a run ended, as ACP says it, from Pi's last answer; an error is thrown (the chat shows it). */+/**+ * How a run ended, as ACP says it, from Pi's last answer; an error is thrown (the chat shows it), in plain words+ * (`failureText`), with Pi's own words as its `details`.+ */export function stopReason(message) {switch (message?.stopReason) {case 'length': return 'max_tokens';case 'aborted': return 'cancelled';- case 'error': throw new Error(String(message.errorMessage || 'The model did not answer.'));+ case 'error': {+ const said = String(message.errorMessage || 'The model did not answer.');+ throw Object.assign(new Error(failureText(said)), { details: said });+ }default: return 'end_turn';}}+/* what the model service's client says when no answer came in time (Pi waits 5 minutes, then tries again twice) */+const TIMED_OUT = /request timed out|headers timeout|body timeout/i;+/* a conversation longer than the model takes: as Pi says it, then as services commonly do */+const PI_OVERFLOW = /^context overflow recovery failed/i;+const OVERFLOW = /context (?:length|window|size)|prompt (?:is )?too long/i;+const CONTEXT_HINT = "The model's context may be smaller than set in Settings: lower it there.";++/** Why a turn failed, in plain words where Pi's own are technical; anything else as Pi said it. */+export function failureText(said) {+ const text = String(said ?? '').trim();+ if (TIMED_OUT.test(text)) return "The model service didn't answer for 5 minutes, even after retries. Check that the service is running and reachable, then try again.";+ if (PI_OVERFLOW.test(text)) return `${text} ${CONTEXT_HINT}`;+ if (OVERFLOW.test(text)) return `The conversation is too long for the model. ${CONTEXT_HINT}`;+ return text;+}+/** How full the context is after an answer (ACP usage_update): what the conversation takes, of the model's window. */export function contextUsed(message, model) {const u = message?.usage;diff --git a/apps/desktop/src/pi-config.test.mjs b/apps/desktop/src/pi-config.test.mjsindex bf410bb..c0e5fd2 100644--- a/apps/desktop/src/pi-config.test.mjs+++ b/apps/desktop/src/pi-config.test.mjs@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { THINKING, contextLength, contextUsed, effortOption, modelEffort, modelOption, modelsJson, outOfBalance, providerOf, stopReason, toolCall, toolContent } from './pi-config.mjs';+import { THINKING, contextLength, contextUsed, effortOption, failureText, modelEffort, modelOption, modelsJson, outOfBalance, providerOf, stopReason, toolCall, toolContent } from './pi-config.mjs';/** One of the person's own models, as the roster's harness gives it. */const own = (id, over = {}) => ({ id, name: id.toUpperCase(), api: 'openai-completions', baseUrl: `https://${id}.test/v1`, keyEnv: `K_${id}`, model: `${id}-model`, levels: ['auto'], effort: 'auto', ...over });@@ -52,6 +52,8 @@ test('what Pi does reads in the chat as Codex\'s did: a command\'s kind and titlassert.equal(stopReason({ stopReason: 'toolUse' }), 'end_turn');assert.equal(stopReason({ stopReason: 'aborted' }), 'cancelled');assert.throws(() => stopReason({ stopReason: 'error', errorMessage: '400 bad' }), /400 bad/);+ assert.throws(() => stopReason({ stopReason: 'error', errorMessage: 'Request timed out.' }),+ (e) => e.message.startsWith("The model service didn't answer for 5 minutes") && e.details === 'Request timed out.');assert.deepEqual(contextUsed({ usage: { input: 100, cacheRead: 900, cacheWrite: 0, output: 50 } }, { contextWindow: 10_000 }), { used: 1050, size: 10_000 });});@@ -93,3 +95,18 @@ test('the effort option: for a model offering more than one, its levels named',assert.deepEqual(effortOption(['auto', 'xhigh'], 'xhigh'), { id: 'effort', name: 'Effort', category: 'thought_level', type: 'select', currentValue: 'xhigh',options: [{ value: 'auto', name: 'Auto' }, { value: 'xhigh', name: 'Extra high' }] });});++test('why a turn failed, in plain words: a service that sent nothing in time, a conversation too long for the model; else as Pi said it', () => {+ const timedOut = "The model service didn't answer for 5 minutes, even after retries. Check that the service is running and reachable, then try again.";+ assert.equal(failureText('Request timed out.'), timedOut, "the OpenAI and Anthropic clients' own timeout");+ assert.equal(failureText('Headers Timeout Error'), timedOut);+ assert.equal(failureText('Body Timeout Error'), timedOut);+ const hint = "The model's context may be smaller than set in Settings: lower it there.";+ const pi = 'Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.';+ assert.equal(failureText(pi), `${pi} ${hint}`);+ assert.equal(failureText('Context overflow recovery failed: 400 prompt is too long'), `Context overflow recovery failed: 400 prompt is too long ${hint}`);+ assert.equal(failureText("400: This model's maximum context length is 65536 tokens. However, you requested 70000 tokens."), `The conversation is too long for the model. ${hint}`);+ assert.equal(failureText('prompt is too long: 213462 tokens > 200000 maximum'), `The conversation is too long for the model. ${hint}`);+ assert.equal(failureText('401 Incorrect API key provided'), '401 Incorrect API key provided');+ assert.equal(failureText('terminated'), 'terminated', 'a connection cut off is not said to be a timeout');+});