Skip to content

The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.

Desktop: Codex connects once found, and an agent's failure says why (#86)

riverisbuilding278f79b17d59
diff --git a/.changeset/codex-connect-and-refusals.md b/.changeset/codex-connect-and-refusals.md
new file mode 100644
index 0000000..90a4e2d
--- /dev/null
+++ b/.changeset/codex-connect-and-refusals.md
@@ -0,0 +1,5 @@
+---
+'@openfilm/desktop': patch
+---
+
+Desktop: Codex connects once it is found, with no sign-in from OpenFilm; it is signed in in Codex itself. An agent's failure says why: what the agent said, or, when it says nothing, the step it stopped at, how its process ended and what it last wrote, and a start that fails is in the turn's log too. Codex's reconnects ("Reconnecting... 2/5", "waiting for network") show in the chat as it retries, and a message its model service refuses fails the turn with the reason instead of showing it as the reply; a model the Codex on the computer is too old for says to update Codex or choose another model.
diff --git a/apps/desktop/chat/src/components/TurnLog.tsx b/apps/desktop/chat/src/components/TurnLog.tsx
index 6727901..229ec38 100644
--- a/apps/desktop/chat/src/components/TurnLog.tsx
+++ b/apps/desktop/chat/src/components/TurnLog.tsx
@@ -487,6 +487,11 @@ function updateRow(event: LogEvent, titles: Map<string, string>): Omit<Row, 'at'
}
}
+/** A start or a turn that failed: why, the step it stopped at, and the last the agent wrote to stderr. */
+function failed(event: LogEvent): string {
+ return `${str(event.error, 500)}${event.step ? ` · ${str(event.step)}` : ''}${event.stderr ? ` · ${str(String(event.stderr).trim().split('\n').slice(-3).join(' | '), 300)}` : ''}`;
+}
+
function rowOf(event: LogEvent, titles: Map<string, string>): Omit<Row, 'at' | 'events'> {
switch (event.kind) {
case 'prompt': {
@@ -504,7 +509,8 @@ function rowOf(event: LogEvent, titles: Map<string, string>): Omit<Row, 'at' | '
case 'cancel': return { kind: 'end', label: 'cancel', summary: '' };
case 'set-option': return { kind: 'update', label: 'set option', summary: `${str(event.configId)} = ${str(event.value)}`, tone: 'quiet' };
case 'exit': return { kind: 'end', label: 'exit', summary: `code ${str(event.code)}${event.stderr ? ` ${str(event.stderr, 300)}` : ''}`, tone: event.code ? 'error' : undefined };
- case 'done': return { kind: 'end', label: 'done', summary: event.ok ? str(event.stopReason) : str(event.error, 500), tone: event.ok ? undefined : 'error' };
+ case 'start': return { kind: 'end', label: 'start', summary: failed(event), tone: 'error' };
+ case 'done': return { kind: 'end', label: 'done', summary: event.ok ? str(event.stopReason) : failed(event), tone: event.ok ? undefined : 'error' };
default: return { kind: 'update', label: event.kind, summary: str(event, 300), tone: 'quiet' };
}
}
diff --git a/apps/desktop/chat/src/lib/desktop-bridge.ts b/apps/desktop/chat/src/lib/desktop-bridge.ts
index 57afd76..4da7b14 100644
--- a/apps/desktop/chat/src/lib/desktop-bridge.ts
+++ b/apps/desktop/chat/src/lib/desktop-bridge.ts
@@ -195,8 +195,11 @@ export interface DesktopBridge {
signIn(agent: LocalAgentId): Promise<{ ok: true } | { ok: false; error: string }>;
/** Opens a session and closes it at once, only for its options. Sends no message, so costs nothing. */
probe(agent: LocalAgentId): Promise<{ ok: true; info: LocalAgentSessionInfo } | { ok: false; error: string; code?: string }>;
- /** `resume`: the agent's own id of a conversation it had (an earlier start's info.sessionId), to go on with */
- start(agent: LocalAgentId, cwd: string, resume?: string | null): Promise<
+ /**
+ * `resume`: the agent's own id of a conversation it had (an earlier start's info.sessionId), to go on with.
+ * `meta`: the turn it starts for, whose log says why when it does not start.
+ */
+ start(agent: LocalAgentId, cwd: string, resume?: string | null, meta?: LocalAgentTurnMeta): Promise<
| { ok: true; key: string; info: LocalAgentSessionInfo }
| { ok: false; error: string; code?: string; install?: string }
>;
diff --git a/apps/desktop/chat/src/lib/local-agent-run.ts b/apps/desktop/chat/src/lib/local-agent-run.ts
index b1303e9..f7cfb98 100644
--- a/apps/desktop/chat/src/lib/local-agent-run.ts
+++ b/apps/desktop/chat/src/lib/local-agent-run.ts
@@ -833,7 +833,7 @@ export async function runLocalAgentTurn({
const sessionKey = `${projectId}:${conversation}:${agent}`;
let session = sessions.get(sessionKey);
if (!session || session.cwd !== cwd) {
- const started = await bridge.start(agent, cwd, resume);
+ const started = await bridge.start(agent, cwd, resume, meta);
if (!started.ok) {
throw Object.assign(new Error(started.error), { code: started.code, install: started.install });
}
diff --git a/apps/desktop/src/agent-roster.mjs b/apps/desktop/src/agent-roster.mjs
index a5cf3e9..4f05b3a 100644
--- a/apps/desktop/src/agent-roster.mjs
+++ b/apps/desktop/src/agent-roster.mjs
@@ -4,10 +4,11 @@
* · codex, claude, copilot, cursor, opencode, codebuddy, qwen, kimi, minimax — the person's own agents (agents.mjs):
* Codex, Claude Code, GitHub Copilot, Cursor, OpenCode, CodeBuddy, Qwen Code, Kimi and MiniMax Code. Each uses
* the account signed in on the computer as it is: connecting opens Terminal for its own sign-in command only when
- * it is signed out, disconnecting only stops OpenFilm using it, and connecting again uses whichever account is
- * signed in then (one switched in the agent or its maker's app). `account` says whose it is. Codex and Claude Code
- * are shown in the chat's menu from the start; the others once the person connects one or switches it on. Codex is
- * connected from the start, Claude Code once the person connects it.
+ * it is signed out (never Codex's: it is signed in in Codex, so one found is connected), disconnecting only stops
+ * OpenFilm using it, and connecting again uses whichever account is signed in then (one switched in the agent or
+ * its maker's app). `account` says whose it is. Codex and Claude Code are shown in the chat's menu from the start;
+ * the others once the person connects one or switches it on. Codex is connected from the start, Claude Code once
+ * the person connects it.
* · byok — the app's own agent (Pi, pi-agent.mjs) on the person's own models, each set up on its own: the name the
* chat's menu shows, its service (an address on a standard API in one of three formats: the OpenAI Responses API
* (…/v1/responses), the OpenAI Chat Completions API (…/v1/chat/completions) or the Anthropic Messages API
diff --git a/apps/desktop/src/agents.mjs b/apps/desktop/src/agents.mjs
index 22e5536..c2d7371 100644
--- a/apps/desktop/src/agents.mjs
+++ b/apps/desktop/src/agents.mjs
@@ -13,8 +13,8 @@
* · size: each official program is 200–330 MB; the adapters are a few MB and take its path
* (`CLAUDE_CODE_EXECUTABLE`, `CODEX_PATH`);
* · terms: Anthropic lets people use their own subscription in the unmodified Claude Code, and does not let anyone
- * else hold or pass on their credentials. The app runs their own program, sign-in is its own (`claude auth login`,
- * `codex login`, in Terminal, or a command window on Windows), and the app never sees a token.
+ * else hold or pass on their credentials. The app runs their own program, sign-in is its own (`claude auth login`
+ * in Terminal, or a command window on Windows; Codex in Codex itself), and the app never sees a token.
*
* Each uses the account signed in on the computer, as it is: one switched in the agent (or its maker's app) is the
* one used once the agent is connected again here.
@@ -45,7 +45,8 @@ const require = createRequire(import.meta.url);
* Each agent: through an adapter the app carries (`adapter`, told where the person's program is by `env`), or the
* person's program itself with `args`. Signed in? `auth` asks the program (its words say); without it, a session is
* opened and closed (acpSignedIn). `login` is its own sign-in, run in Terminal (none: the program itself, which asks
- * for one on its first run). `authenticate`: the ACP auth method that takes up the program's own sign-in.
+ * for one on its first run; null: signed in in the program or its maker's app, never from here, so one found is
+ * connected). `authenticate`: the ACP auth method that takes up the program's own sign-in.
* `approve`: it asks permission for what the app lets every agent do (see the chat's AGENT_FORCED_PREFS), so the app
* answers yes itself. The others are told the app's INSTRUCTIONS in the first message of a session (`systemPrompt`:
* how Claude Code and Codex are told them instead).
@@ -68,8 +69,9 @@ export const AGENTS = Object.freeze({
label: 'Codex',
adapter: '@agentclientprotocol/codex-acp',
env: (path) => codexLaunchEnv(path),
+ /* asked only for whose account it is: Codex is signed in in Codex (its app, or `codex login`) */
auth: ['login', 'status'],
- login: ['login'],
+ login: null,
systemPrompt: true,
},
copilot: { label: 'GitHub Copilot', args: ['--acp', '--allow-all'], login: ['login'], approve: true },
@@ -505,6 +507,7 @@ export async function openAgentSignIn(id) {
const pathDirs = (await loginShellEnvironment()).PATH.split(PATH_SEP);
const cli = spec ? resolveAgentCli(id, { pathDirs }) : null;
if (!spec || !cli) return { ok: false, error: `${spec?.label ?? id} is not installed on this computer.` };
+ if (spec.login === null) return { ok: false, error: `Sign in in ${spec.label} itself.` };
asked.delete(id);
let how = null;
if (spec.acpSignIn) {
@@ -579,12 +582,17 @@ async function agentOnComputer(id, pathDirs) {
label: AGENTS[id].label,
cli: cli ? { path: cli.path, source: cli.source } : null,
chosen: chosenPaths[id] ?? null,
- ...(cli ? await agentStatus(id, cli.path) : { signedIn: null, account: null }),
+ ...(cli ? ownSignIn(AGENTS[id], await agentStatus(id, cli.path)) : { signedIn: null, account: null }),
install,
setupRequired: claudeApp ? 'code-tab' : null,
};
}
+/** An agent signed in in its own program (`login: null`) is never signed out here: its account, if it says one. */
+export function ownSignIn(spec, status) {
+ return spec.login === null && status.signedIn === false ? { ...status, signedIn: null } : status;
+}
+
/** The adapter's command line (its package's `bin`), run with Electron's own Node. */
function adapterScript(pkg) {
const manifest = require.resolve(`${pkg}/package.json`);
@@ -734,11 +742,11 @@ const INTERNAL_ERROR = -32603;
* Code…") is the agent's own words (`code: 'agent-error'`): signing in again would not help, and the agent is not taken
* for signed out. Any other error with its reason (errorCause).
*/
-export function signInError(label, e) {
+export function signInError(label, e, { own = false } = {}) {
if (e?.code === AUTH_REQUIRED) {
const plan = planProblem(e?.message);
if (plan) return Object.assign(new Error(`${label}: ${plan}`), { code: 'agent-error' });
- return Object.assign(new Error(`${label} is not signed in. Sign in under Settings → Agents.`), { code: 'sign-in' });
+ return Object.assign(new Error(`${label} is not signed in. ${own ? `Sign in in ${label}, then try again.` : 'Sign in under Settings → Agents.'}`), { code: 'sign-in' });
}
return errorCause(e);
}
@@ -755,6 +763,90 @@ export function errorCause(e) {
return why.trim() ? Object.assign(new Error(why.trim(), { cause: e }), { code: e.code }) : e;
}
+/**
+ * The model service's refusal, when that is what a reply's words are: Codex's adapter sends an error from OpenAI as
+ * the reply (`{"type":"error","status":400,"error":{"message":…}}`), and the turn ends as if answered. Its message
+ * and status, or null for anything else.
+ * @returns {{ message: string, status: number | null } | null}
+ */
+export function codexServiceError(update) {
+ if (update?.sessionUpdate !== 'agent_message_chunk' || update.content?.type !== 'text') return null;
+ const text = String(update.content.text ?? '').trim();
+ if (!text.startsWith('{"type":"error"')) return null;
+ try {
+ const said = JSON.parse(text);
+ const message = typeof said?.error?.message === 'string' ? said.error.message.trim() : '';
+ return said?.type === 'error' && message ? { message, status: Number.isInteger(said.status) ? said.status : null } : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The turn's error for a refusal. A model "not supported when using Codex" is one this Codex is too old for (Codex
+ * lists models it cannot use yet): updating it, or another model, is the fix.
+ * @param {{ message: string }} refused @param {string | undefined} path @param {(file: string) => string | null} [versionOf]
+ */
+export function codexRefusal(refused, path, versionOf = codexVersion) {
+ if (!/not supported when using Codex/i.test(refused.message)) return new Error(refused.message);
+ const version = path ? versionOf(path) : null;
+ return Object.assign(new Error(`${refused.message} Update Codex${version ? ` (this one is ${version})` : ''}, or choose another model.`), { code: 'outdated' });
+}
+
+/**
+ * Codex's reconnects and retries ("Reconnecting... 2/5", "waiting for network"), and an error of a turn not running
+ * now: its adapter puts them in a session_info_update's `_meta.codex.error`, which says nothing in the chat. As the
+ * notice the chat shows (its words, then what it adds), or null.
+ */
+export function codexNotice(update) {
+ const error = update?.sessionUpdate === 'session_info_update' ? update._meta?.codex?.error : null;
+ const title = typeof error?.message === 'string' ? error.message.trim() : '';
+ if (!title) return null;
+ const details = typeof error.additionalDetails === 'string' ? error.additionalDetails.trim() : '';
+ return { sessionUpdate: 'notice', severity: error.willRetry ? 'warning' : 'error', title, ...(details ? { description: details } : {}) };
+}
+
+/** where each step of a session is, in words */
+const STEP_WORDS = Object.freeze({
+ start: 'as it started', initialize: 'as it started', authenticate: 'while signing in',
+ 'session/new': 'while opening the session', 'session/prompt': 'while answering',
+});
+
+/** what an agent says when it says nothing: an error with no reason, or its process gone mid-request */
+const SAYS_NOTHING = /^(?:internal error|internal server error|unknown error|(?:acp )?connection closed|pending response rejected since connection got disposed)\.?$/i;
+
+/* stderr lines that never say why: a stack frame, a caret, a brace, a property of the error printed, Node's banner
+ and its "Emitted 'error' event" */
+const NOISE = /^(?:at\s|\^+$|[{}]$|[a-z]+: [-'\w]+,?$|Node\.js v|node:|throw\s|Emitted '\w+' event)/;
+const REASON = /error|fail|cannot|can't|refused|denied|not found|panic|timed? ?out|unable/i;
+
+/** What the last of an agent's stderr says: its last lines that name an error, else its last lines; at most 600 characters. */
+export function stderrReason(stderr = '') {
+ const lines = stderr.split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !NOISE.test(l));
+ const reasons = lines.filter((l) => REASON.test(l));
+ return [...new Set((reasons.length ? reasons : lines).slice(-3))].join(' | ').slice(-600);
+}
+
+/**
+ * An agent's failure as it is: what it said when it said why; else the step it stopped at, how its process ended and
+ * the last it wrote to stderr; with neither, that an agent which cannot reach its service stops like this.
+ * @param {any} e @param {{ label: string, step?: string | null, stderr?: string, exited?: { code: number | null } | null }} at
+ */
+export function explainFailure(e, { label, step = null, stderr = '', exited = null }) {
+ const said = (e instanceof Error ? e.message : String(e ?? '')).trim();
+ const bare = !said || SAYS_NOTHING.test(said);
+ if (!bare && !exited) return e;
+ const tail = stderrReason(stderr);
+ const where = step && STEP_WORDS[step] ? ` ${STEP_WORDS[step]}` : '';
+ const ended = exited ? ` Its process ended${exited.code == null ? '' : ` with code ${exited.code}`}.` : '';
+ const message = [
+ bare ? `${label} stopped${where} without saying why.` : said,
+ ended.trim(),
+ tail ? `It last wrote: ${tail}` : bare ? 'If it cannot reach its service, check the network or proxy, then try again.' : '',
+ ].filter(Boolean).join(' ');
+ return Object.assign(new Error(message, { cause: e }), { ...(e?.code !== undefined ? { code: e.code } : {}), ...(step ? { step } : {}) });
+}
+
/** What an agent's sign-in refusal says when it is about the person's plan, not their sign-in, or null. */
export function planProblem(message) {
const text = String(message ?? '').replace(/^\s*Authentication required[:.]?\s*/i, '').trim();
@@ -854,13 +946,42 @@ export class AgentSession {
*/
async start() {
try {
- return await this.open();
+ const info = await this.open();
+ this.step = null;
+ return info;
} catch (e) {
- throw codexTooOld(this.opts.agent, this.cli?.path, e);
+ throw await this.explain(codexTooOld(this.opts.agent, this.cli?.path, e));
}
}
+ /**
+ * An error with what the agent said, or, when it said nothing, where it stopped and what it last wrote. Its process
+ * may be ending as the request fails: how it ended is waited for, a second at most.
+ */
+ async explain(e) {
+ if (this.child && !this.exited && this.child.exitCode === null && this.child.signalCode === null) {
+ await new Promise((done) => { this.child.once('exit', done); setTimeout(done, 1000).unref?.(); });
+ }
+ return explainFailure(e, { label: this.spec.label, step: this.step, stderr: this.stderr, exited: this.exited ?? null });
+ }
+
+ /**
+ * What a failure needs said for the turn log: the step it stopped at, the program, its adapter, how its process
+ * ended, all it wrote to stderr, and where the agent keeps its own logs.
+ */
+ failure() {
+ return {
+ step: this.step ?? null,
+ program: this.cli?.path ?? null,
+ adapter: this.spec.adapter ?? null,
+ exit: this.exited ?? null,
+ stderr: this.stderr.slice(-8000),
+ ...(this.ownLogs ? { ownLogs: this.ownLogs } : {}),
+ };
+ }
+
async open() {
+ this.step = 'start';
const shell = agentShell(this.opts.agent, await loginShellVariables({ staleOk: true }));
const harness = this.opts.harness ?? null;
const cli = harness ? null : resolveAgentCli(this.opts.agent, { pathDirs: shell.PATH.split(PATH_SEP) });
@@ -898,6 +1019,7 @@ export class AgentSession {
const env = childEnvironment({ shell: { ...shell, PATH: path }, extra });
const claude = this.spec.adapter === AGENTS.claude.adapter;
if (this.spec.adapter === AGENTS.codex.adapter) {
+ this.ownLogs = shell.CODEX_HOME || join(homedir(), '.codex');
const theirs = codexDeveloperInstructions(codexConfigText(shell));
env.CODEX_CONFIG = JSON.stringify(mergeConfig({ developer_instructions: theirs ? `${theirs}\n\n${instructions}` : instructions }, skills?.codexConfig ?? {}));
}
@@ -910,7 +1032,7 @@ export class AgentSession {
: spawn(node.command, [...(node.env.ELECTRON_RUN_AS_NODE ? [AS_NODE] : []), script], { cwd: this.opts.cwd, env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
this.child.stderr.on('data', (d) => { this.stderr = (this.stderr + String(d)).slice(-16_000); });
LIVE.add(this);
- this.child.once('exit', (code) => { LIVE.delete(this); this.opts.onExit?.({ code, stderr: this.stderr }); });
+ this.child.once('exit', (code) => { LIVE.delete(this); this.exited = { code }; this.opts.onExit?.({ code, stderr: this.stderr }); });
this.child.once('error', () => {});
const stream = acp.ndJsonStream(Writable.toWeb(this.child.stdin), Readable.toWeb(this.child.stdout));
@@ -932,15 +1054,27 @@ export class AgentSession {
this.heard = Date.now();
const phase = agentPhase(update);
if (phase) this.phase = phase;
- if (!this.replaying) this.opts.onUpdate?.(update?.configOptions ? { ...update, configOptions: distinctOptions(update.configOptions) } : update);
+ if (this.replaying) return;
+ /* Codex's adapter sends the model service's refusal as the reply's words: kept to fail the turn with */
+ const codex = this.spec.adapter === AGENTS.codex.adapter;
+ const refused = codex ? codexServiceError(update) : null;
+ if (refused) { this.refused = refused; return; }
+ this.opts.onUpdate?.(update?.configOptions ? { ...update, configOptions: distinctOptions(update.configOptions) } : update);
+ /* and its reconnects and retries, which it says where the chat does not look, as notices (once each) */
+ const notice = codex ? codexNotice(update) : null;
+ if (notice && notice.title !== this.lastNotice) {
+ this.lastNotice = notice.title;
+ this.opts.onUpdate?.(notice);
+ }
})
.connect(stream);
+ this.step = 'initialize';
const init = await this.conn.agent.request(acp.methods.agent.initialize, {
protocolVersion: acp.PROTOCOL_VERSION,
clientCapabilities: CLIENT_CAPABILITIES,
clientInfo: CLIENT_INFO,
- }).catch((e) => { throw signInError(this.spec.label, e); });
+ }).catch((e) => { throw signInError(this.spec.label, e, { own: this.spec.login === null }); });
const params = {
cwd: this.opts.cwd,
@@ -950,9 +1084,11 @@ export class AgentSession {
};
/* the program's own sign-in, taken up (Cursor asks for this before any session) */
if (this.spec.authenticate && (init.authMethods ?? []).some((m) => m.id === this.spec.authenticate)) {
- await this.conn.agent.request(acp.methods.agent.authenticate, { methodId: this.spec.authenticate }).catch((e) => { throw signInError(this.spec.label, e); });
+ this.step = 'authenticate';
+ await this.conn.agent.request(acp.methods.agent.authenticate, { methodId: this.spec.authenticate }).catch((e) => { throw signInError(this.spec.label, e, { own: this.spec.login === null }); });
}
+ this.step = 'session/new';
let session = null;
const resume = this.opts.resume;
const caps = init.agentCapabilities ?? {};
@@ -964,7 +1100,7 @@ export class AgentSession {
this.replaying = false;
}
const resumed = Boolean(session);
- session ??= await this.conn.agent.request(acp.methods.agent.session.new, params).catch((e) => { throw signInError(this.spec.label, e); });
+ session ??= await this.conn.agent.request(acp.methods.agent.session.new, params).catch((e) => { throw signInError(this.spec.label, e, { own: this.spec.login === null }); });
this.sessionId = session.sessionId;
/* an agent on the protocol's older model and mode lists: the same choices, as config options */
this.legacy = !session.configOptions && Boolean(session.models || session.modes);
@@ -1014,6 +1150,9 @@ export class AgentSession {
this.instructions = null;
/* the message exactly as the agent gets it, for the turn log */
this.opts.onSend?.({ prompt: [...told, ...blocks], ...meta });
+ this.refused = null;
+ this.lastNotice = null;
+ this.step = 'session/prompt';
this.spoke = false;
this.heard = Date.now();
this.phase = null;
@@ -1032,18 +1171,19 @@ export class AgentSession {
}, Math.min(15_000, Math.max(50, stallMs / 4)));
watch.unref?.();
const asking = this.conn.agent.request(acp.methods.agent.session.prompt, { sessionId: this.sessionId, prompt: [...told, ...blocks], ...meta })
- .catch((e) => {
+ .catch(async (e) => {
/* the app's own agent: a service with no balance left is said the same for every service, with its page */
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 errorCause(e);
- const said = signInError(this.spec.label, e);
+ const said = signInError(this.spec.label, e, { own: this.spec.login === null });
if (said.code === 'sign-in') noteSignedOut(this.opts.agent);
- throw said;
+ throw await this.explain(said);
});
const r = await Promise.race([asking, gaveUp]).finally(() => clearInterval(watch));
if (stalled && r.stopReason === 'cancelled') throw stallError(this.spec.label, stallMs);
+ if (this.refused) throw codexRefusal(this.refused, this.cli?.path);
/* a turn the agent gave up on with its reason beside it, not in its reply (CodeBuddy: a network error): said as
the turn's error, or the chat would show an empty reply */
const why = r.stopReason === 'refusal' ? turnError(r) : null;
@@ -1052,6 +1192,7 @@ export class AgentSession {
if (r.stopReason === 'end_turn' && !this.spoke && isAgentId(this.opts.agent)) {
throw Object.assign(new Error(`${this.spec.label} ended its turn without replying. If it keeps doing so, try ${this.spec.label} in its own terminal: it may need an update, or a plan that covers it.`), { code: 'empty-turn' });
}
+ this.step = null;
return r.stopReason;
}
diff --git a/apps/desktop/src/agents.test.mjs b/apps/desktop/src/agents.test.mjs
index 319eb11..c15986d 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 { AgentSession, CLIENT_CAPABILITIES, agentDefaults, closeEverySession, planProblem, probeFolder, CODEX_UTF8_CMD, agentShell, allowOption, codexDeveloperInstructions, codexLaunchEnv, distinctOptions, errorCause, legacyOptions, powerShellScript, readAgentStatus, setChosenPaths, signInScript, turnError, signInError, codexTooOld } from './agents.mjs';
+import { AgentSession, CLIENT_CAPABILITIES, agentDefaults, closeEverySession, planProblem, probeFolder, CODEX_UTF8_CMD, agentShell, allowOption, codexDeveloperInstructions, codexLaunchEnv, distinctOptions, errorCause, legacyOptions, powerShellScript, readAgentStatus, setChosenPaths, signInScript, turnError, signInError, codexTooOld, AGENTS, ownSignIn, codexServiceError, codexRefusal, codexNotice, explainFailure, stderrReason } 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 = [
@@ -66,6 +66,36 @@ test('an error the agent sends as "Internal error" carries its reason; a sign-in
const plain = new Error('Codex process has exited with code 1');
assert.equal(signInError('Codex', plain), plain);
assert.equal(signInError('Codex', Object.assign(new Error('Authentication required'), { code: -32000 })).code, 'sign-in');
+ const own = signInError('Codex', Object.assign(new Error('Authentication required'), { code: -32000 }), { own: true });
+ assert.equal(own.code, 'sign-in');
+ assert.equal(own.message, 'Codex is not signed in. Sign in in Codex, then try again.');
+});
+
+test('Codex is signed in in Codex: one found is never signed out here, and keeps whose account it is', () => {
+ assert.equal(AGENTS.codex.login, null);
+ assert.deepEqual(ownSignIn(AGENTS.codex, { signedIn: false, account: null }), { signedIn: null, account: null });
+ const account = { method: 'chatgpt' };
+ assert.deepEqual(ownSignIn(AGENTS.codex, { signedIn: true, account }), { signedIn: true, account });
+ assert.deepEqual(ownSignIn(AGENTS.claude, { signedIn: false, account: null }), { signedIn: false, account: null });
+});
+
+test("the model service's refusal Codex sends as its reply fails the turn; a model this Codex is too old for says to update it", () => {
+ const chunk = (text) => ({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } });
+ const said = `{"type":"error","status":400,"error":{"type":"invalid_request_error","message":"The 'gpt-6.1-sol' model is not supported when using Codex with a ChatGPT account."}}\n\n`;
+ const refused = codexServiceError(chunk(said));
+ assert.deepEqual(refused, { message: "The 'gpt-6.1-sol' model is not supported when using Codex with a ChatGPT account.", status: 400 });
+ assert.equal(codexServiceError(chunk('Hi!')), null);
+ assert.equal(codexServiceError(chunk('{"type":"error"')), null, 'not JSON');
+ assert.equal(codexServiceError(chunk('{"type":"error","error":{}}')), null, 'no message');
+ assert.equal(codexServiceError({ sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: said } }), null);
+
+ const old = codexRefusal(refused, '/usr/local/bin/codex', () => '0.156.1');
+ assert.equal(old.code, 'outdated');
+ assert.equal(old.message, "The 'gpt-6.1-sol' model is not supported when using Codex with a ChatGPT account. Update Codex (this one is 0.156.1), or choose another model.");
+ assert.match(codexRefusal(refused, '/usr/local/bin/codex', () => null).message, / Update Codex, or choose another model\.$/);
+ const other = codexRefusal({ message: 'Rate limit reached.', status: 429 }, '/usr/local/bin/codex', () => '0.163.0');
+ assert.equal(other.message, 'Rate limit reached.');
+ assert.equal(other.code, undefined);
});
test('a turn the agent ends with just "Internal error" says the reason in its data; the error as sent stays its cause', () => {
@@ -201,6 +231,10 @@ test('a refusal about the plan is the agent\'s own words; one about the sign-in
'403 Your current subscription does not have access to Kimi Code right now. Upgrade your plan to keep coding with Kimi Code: https://www.kimi.com/code/#pricing');
assert.equal(planProblem('Authentication required: Use Qwen Code CLI to authenticate first.'), null);
assert.equal(planProblem('Authentication required'), null);
+ /* one signed in in its own program is told the same about its plan */
+ const plan = signInError('Codex', Object.assign(new Error('Authentication required: 403 Your plan does not include this model.'), { code: -32000 }), { own: true });
+ assert.equal(plan.code, 'agent-error');
+ assert.equal(plan.message, 'Codex: 403 Your plan does not include this model.');
});
test('a turn that ends with nothing said is said so; a refusal for the plan does not sign the agent out', async () => {
@@ -316,3 +350,51 @@ test('a Codex older than the ones tried, that did not start, is said to need an
assert.equal(codexTooOld('codex', '/usr/local/bin/codex', signIn, () => '0.104.0'), signIn);
assert.equal(codexTooOld('claude', '/usr/local/bin/claude', failed, () => '0.104.0'), failed);
});
+
+test("Codex's reconnects and retries, which it says where the chat does not look, are notices in its words", () => {
+ const info = (error) => ({ sessionUpdate: 'session_info_update', _meta: { codex: { error } } });
+ assert.deepEqual(codexNotice(info({ message: 'Reconnecting... 2/5', additionalDetails: 'stream disconnected before completion: Connection refused (os error 61)', willRetry: true })), {
+ sessionUpdate: 'notice', severity: 'warning', title: 'Reconnecting... 2/5', description: 'stream disconnected before completion: Connection refused (os error 61)',
+ });
+ assert.deepEqual(codexNotice(info({ message: 'Quota exceeded.', additionalDetails: null, willRetry: false })), { sessionUpdate: 'notice', severity: 'error', title: 'Quota exceeded.' });
+ assert.equal(codexNotice(info({ message: ' ' })), null);
+ assert.equal(codexNotice({ sessionUpdate: 'session_info_update', _meta: { codex: { threadStatus: { type: 'idle' } } } }), null);
+ assert.equal(codexNotice({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'Hi' } }), null);
+});
+
+test('a failure keeps what the agent said; one that says nothing says where it stopped, how its process ended and what it wrote', () => {
+ const said = Object.assign(new Error('Codex process has exited with code 3:\nerror: failed to connect'), { code: 1001 });
+ assert.equal(explainFailure(said, { label: 'Codex', step: 'session/new' }), said);
+
+ const bare = explainFailure(Object.assign(new Error('Internal error'), { code: -32603 }), { label: 'Codex', step: 'session/prompt' });
+ assert.equal(bare.message, 'Codex stopped while answering without saying why. If it cannot reach its service, check the network or proxy, then try again.');
+ assert.equal(bare.code, -32603);
+ assert.equal(bare.step, 'session/prompt');
+
+ const crashed = explainFailure(new Error('ACP connection closed'), {
+ label: 'Codex', step: 'initialize', exited: { code: 1 },
+ stderr: "node:events:487\n throw er; // Unhandled 'error' event\n ^\n\nError: write EPIPE\n at afterWriteDispatched (node:internal/stream_base_commons:159:15)\nEmitted 'error' event on Socket instance at:\n errno: -32,\n code: 'EPIPE',\n}\n\nNode.js v26.0.0\n",
+ });
+ assert.equal(crashed.message, 'Codex stopped as it started without saying why. Its process ended with code 1. It last wrote: Error: write EPIPE');
+
+ const ended = explainFailure(new Error('Rate limit reached.'), { label: 'Kimi', exited: { code: null } });
+ assert.equal(ended.message, 'Rate limit reached. Its process ended.');
+});
+
+test('"Internal error" with its reason in data: the reason is what the turn says, and the error as sent stays under it', () => {
+ const sent = Object.assign(new Error('Internal error'), { code: -32603, data: { details: 'Request timed out.' } });
+ const said = explainFailure(signInError('Codex', sent, { own: true }), { label: 'Codex', step: 'session/prompt' });
+ assert.equal(said.message, 'Request timed out.', 'a reason given is not "without saying why"');
+ let asSent = said;
+ while (asSent.cause) asSent = asSent.cause;
+ assert.equal(asSent, sent, 'the turn log reaches the error as the agent sent it');
+
+ const bare = explainFailure(signInError('Codex', Object.assign(new Error('Internal error'), { code: -32603 }), { own: true }), { label: 'Codex', step: 'session/prompt', exited: { code: 1 } });
+ assert.match(bare.message, /^Codex stopped while answering without saying why\. Its process ended with code 1\./);
+});
+
+test("what an agent's stderr says: the lines that name an error, else its last lines", () => {
+ assert.equal(stderrReason('starting\nwarning: slow disk\nlistening'), 'starting | warning: slow disk | listening');
+ assert.equal(stderrReason('ok\nError: cannot read config.toml\n at load (x.js:1:1)\ndone'), 'Error: cannot read config.toml');
+ assert.equal(stderrReason(''), '');
+});
diff --git a/apps/desktop/src/local-agents-ipc.mjs b/apps/desktop/src/local-agents-ipc.mjs
index d256cd7..a89db4a 100644
--- a/apps/desktop/src/local-agents-ipc.mjs
+++ b/apps/desktop/src/local-agents-ipc.mjs
@@ -97,6 +97,16 @@ function imageBlocks(images) {
.map((image) => ({ type: 'image', data: image.data, mimeType: image.mimeType }));
}
+/**
+ * The error as the agent sent it (ACP's code, message and data), under any rewording on the way (errorCause,
+ * explainFailure), for the turn log; null when it sent none.
+ */
+export function sentError(e) {
+ let asSent = e;
+ while (asSent?.cause) asSent = asSent.cause;
+ return typeof asSent?.code === 'number' ? { code: asSent.code, message: asSent.message, data: asSent.data ?? null } : null;
+}
+
/**
* An agent that did not start, did not answer, or whose process ended by itself, as Studio's problems keep it
* (openfilm's problems.mjs): why, the step it stopped at, its program, the last of its stderr, and where its turn's log
@@ -219,6 +229,8 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbac
const agent = opts?.agent;
const cwd = opts?.cwd;
const resume = typeof opts?.resume === 'string' && opts.resume ? opts.resume : null;
+ /* the turn it starts for: a start that fails is written in that turn's log, as a prompt that fails is */
+ const meta = opts?.meta && typeof opts.meta === 'object' ? opts.meta : null;
if (!isChatAgent(agent)) return { ok: false, error: `Unknown agent: ${String(agent)}` };
if (typeof cwd !== 'string' || !cwd) return { ok: false, error: 'Missing project folder.' };
/* the conversation still open here (the page was reloaded): taken up as it is, no second process */
@@ -272,10 +284,17 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbac
entry.info = info;
return { ok: true, key, info: { ...info, authMethods: [], mcp: false } };
} catch (e) {
+ const result = { ok: false, error: e instanceof Error ? e.message : String(e), ...(e?.code ? { code: String(e.code) } : {}) };
+ if (meta?.turnId) {
+ const raw = sentError(e);
+ const file = openLog(cwd, meta.turnId, (err) => log(`turn log ${meta.turnId}: ${err.message}\n`));
+ file?.write('start', { ...result, agent, cwd, resume, meta, ...(raw ? { raw } : {}), ...entry.session?.failure?.() });
+ file?.end();
+ }
/* one not installed, or not set up, is not a problem of the app's: the chat says what to do */
- if (e?.code !== 'not-installed' && e?.code !== 'not-ready') noteProblem(entry, 'start', e);
+ if (e?.code !== 'not-installed' && e?.code !== 'not-ready') noteProblem(entry, 'start', e, meta?.turnId ?? null);
close(key);
- return { ok: false, error: e instanceof Error ? e.message : String(e), ...(e?.code ? { code: String(e.code) } : {}) };
+ return result;
}
});
@@ -306,8 +325,7 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbac
} 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 };
+ raw = sentError(e);
if (!e?.balance) noteProblem(entry, 'prompt', e, meta?.turnId ?? null);
} finally {
activePrompts--;
@@ -316,8 +334,9 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbac
}
entry.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, ...(raw ? { raw } : {}), stderr: String(entry.session?.stderr ?? '').slice(-8000) });
+ /* a turn that failed: the error as the agent sent it, the step it stopped at, its program and what its process
+ last wrote to stderr say why */
+ turn.file.write('done', result.ok ? result : { ...result, ...(raw ? { raw } : {}), ...entry.session?.failure?.() });
turn.file.end();
turn.done = result;
entry.turnEnded = Date.now();
diff --git a/apps/desktop/src/local-agents-ipc.test.mjs b/apps/desktop/src/local-agents-ipc.test.mjs
index 92fc3d3..48aed28 100644
--- a/apps/desktop/src/local-agents-ipc.test.mjs
+++ b/apps/desktop/src/local-agents-ipc.test.mjs
@@ -1,7 +1,28 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { agentProblem } from './local-agents-ipc.mjs';
+import { readLog } from './chat-store.mjs';
+import { agentProblem, registerLocalAgentIpc, sentError } from './local-agents-ipc.mjs';
+
+test("a start that fails is written in the log of the turn it was for, with why", async () => {
+ const handlers = new Map();
+ registerLocalAgentIpc({ handle: (channel, fn) => handlers.set(channel, fn) }, { trusted: () => true });
+ const project = mkdtempSync(join(tmpdir(), 'openfilm-ipc-'));
+ const event = { sender: { once() {}, isDestroyed: () => false, send() {} } };
+ /* the own key with no models set up: refused before anything starts */
+ const r = await handlers.get('desktop:local-agents:start')(event, { agent: 'byok', cwd: project, meta: { turnId: 'local:startfail1' } });
+ assert.equal(r.ok, false);
+ assert.equal(r.code, 'not-ready');
+ await new Promise((done) => setTimeout(done, 50));
+ const start = readLog(project, 'local:startfail1')?.events.find((e) => e.kind === 'start');
+ assert.ok(start, 'the turn has a log');
+ assert.equal(start.ok, false);
+ assert.equal(start.error, r.error);
+ assert.equal(start.agent, 'byok');
+ assert.equal(start.meta.turnId, 'local:startfail1');
+});
test('an agent that failed, as its problem is kept: its name, why, the step, the last of its stderr and its turn\'s log', () => {
const session = { stderr: 'a\nb\nc\nd\ne\nError: write EPIPE\n' };
@@ -17,3 +38,10 @@ test('an agent that failed, as its problem is kept: its name, why, the step, the
});
assert.equal(agentProblem({ agent: 'byok', cwd: '/p' }, 'start', 'no models').agent, 'Own key');
});
+
+test('the error as the agent sent it, under any rewording on the way; none when it sent none', () => {
+ const sent = Object.assign(new Error('Internal error'), { code: -32603, data: { details: 'stream closed' } });
+ const reworded = new Error('Codex stopped while answering without saying why.', { cause: new Error('stream closed', { cause: sent }) });
+ assert.deepEqual(sentError(reworded), { code: -32603, message: 'Internal error', data: { details: 'stream closed' } });
+ assert.equal(sentError(new Error('not installed')), null);
+});
diff --git a/apps/desktop/src/preload.cjs b/apps/desktop/src/preload.cjs
index f82c79f..29bcf08 100644
--- a/apps/desktop/src/preload.cjs
+++ b/apps/desktop/src/preload.cjs
@@ -69,7 +69,7 @@ contextBridge.exposeInMainWorld('openfilmNative', {
signIn: (agent) => invoke('desktop:local-agents:sign-in')({ agent }),
disconnect: (agent) => invoke('desktop:local-agents:disconnect')({ agent }),
probe: (agent) => invoke('desktop:local-agents:probe')({ agent }),
- start: (agent, cwd, resume) => invoke('desktop:local-agents:start')({ agent, cwd, resume }),
+ start: (agent, cwd, resume, meta) => invoke('desktop:local-agents:start')({ agent, cwd, resume, meta }),
prompt: (key, text, meta, images) => invoke('desktop:local-agents:prompt')({ key, text, meta, images }),
running: () => ipcRenderer.invoke('desktop:local-agents:running'),
ack: (key, turnId) => invoke('desktop:local-agents:ack')({ key, turnId }),