Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

fix(codex-cli): report spawn timeouts as timeouts, not exit code -1

annieyii6f9b7f5c2ec9
diff --git a/src-tauri/src/commands/codex_cli.rs b/src-tauri/src/commands/codex_cli.rs
index 41d647b1..117e031e 100644
--- a/src-tauri/src/commands/codex_cli.rs
+++ b/src-tauri/src/commands/codex_cli.rs
@@ -253,39 +253,55 @@ pub async fn codex_cli_spawn(
};
let mut stderr_text = stderr_task.await.unwrap_or_default();
- if timed_out.load(Ordering::SeqCst) {
- if !stderr_text.is_empty() {
- stderr_text.push('\n');
- }
- stderr_text.push_str(&format!(
- "Codex CLI timed out after {timeout_minutes} minutes."
- ));
- } else if stderr_text.len() >= STDERR_LIMIT_BYTES {
+ if stderr_text.len() >= STDERR_LIMIT_BYTES {
stderr_text.push_str("\n[stderr truncated]");
}
if stdout_text.len() >= STDOUT_LIMIT_BYTES {
stdout_text.push_str("\n[stdout truncated]");
}
- let code = if timed_out.load(Ordering::SeqCst) {
- Some(-1)
- } else {
- exit_code
- };
-
+ // A timeout is a separate fact from an exit code, and travels in its
+ // own field: reporting it as exit code -1 made a deliberate stop look
+ // like a CLI crash, and buried the real cause under whatever Codex
+ // happened to write to stderr. Note that `exit_code` is None on the
+ // timeout path because the timeout task took the child handle away in
+ // order to kill it, not because a final status was observed, so
+ // `timedOut` is the only dependable signal that the run was stopped.
let _ = app.emit(
&done_topic,
- serde_json::json!({
- "code": code,
- "stderr": stderr_text,
- "stdout": stdout_text,
- }),
+ done_payload(
+ exit_code,
+ timed_out.load(Ordering::SeqCst),
+ timeout_minutes,
+ &stderr_text,
+ &stdout_text,
+ ),
);
});
Ok(())
}
+/// Shape of the `codex-cli:{id}:done` event. Split out from the emit site so
+/// that the key names, which `codex-cli-transport.ts` reads by hand, are
+/// covered by a test instead of only by reading the two files side by side.
+/// This pins the Rust half only; the frontend can still drift independently.
+fn done_payload(
+ exit_code: Option<i32>,
+ timed_out: bool,
+ timeout_minutes: u64,
+ stderr: &str,
+ stdout: &str,
+) -> serde_json::Value {
+ serde_json::json!({
+ "code": exit_code,
+ "timedOut": timed_out,
+ "timeoutMinutes": timeout_minutes,
+ "stderr": stderr,
+ "stdout": stdout,
+ })
+}
+
fn codex_spawn_timeout_minutes(value: Option<u64>) -> u64 {
value.unwrap_or(DEFAULT_CODEX_SPAWN_TIMEOUT_MINUTES).clamp(
MIN_CODEX_SPAWN_TIMEOUT_MINUTES,
@@ -392,6 +408,31 @@ mod tests {
assert!(std::str::from_utf8(out.as_bytes()).is_ok());
}
+ #[test]
+ fn done_payload_uses_the_camel_case_keys_the_frontend_reads() {
+ let payload = done_payload(None, true, 10, "boom", "");
+
+ // These key names are one part of the contract with
+ // codex-cli-transport.ts, alongside the event topic and the value
+ // types. If `timedOut` drifts, the frontend stops recognising the
+ // timeout: a run that had already emitted an agent message is then
+ // reported as completed, and one that had not gets the generic
+ // no-agent-message error instead of the real cause.
+ assert_eq!(payload["code"], serde_json::Value::Null);
+ assert_eq!(payload["timedOut"], true);
+ assert_eq!(payload["timeoutMinutes"], 10);
+ assert_eq!(payload["stderr"], "boom");
+ assert_eq!(payload["stdout"], "");
+ }
+
+ #[test]
+ fn done_payload_passes_through_a_real_exit_code_when_not_timed_out() {
+ let payload = done_payload(Some(2), false, 10, "", "out");
+
+ assert_eq!(payload["code"], 2);
+ assert_eq!(payload["timedOut"], false);
+ }
+
#[test]
fn codex_spawn_timeout_minutes_defaults_and_clamps() {
assert_eq!(
diff --git a/src/lib/codex-cli-transport.test.ts b/src/lib/codex-cli-transport.test.ts
index acdadcb8..38324fdc 100644
--- a/src/lib/codex-cli-transport.test.ts
+++ b/src/lib/codex-cli-transport.test.ts
@@ -474,6 +474,152 @@ describe("streamCodexCli", () => {
)
})
+ it("reports the timeout cause when Codex CLI is stopped by the spawn timeout", async () => {
+ const callbacks = {
+ onToken: vi.fn(),
+ onDone: vi.fn(),
+ onError: vi.fn(),
+ }
+
+ const stream = streamCodexCli(
+ {
+ provider: "codex-cli",
+ apiKey: "",
+ model: "gpt-5.1-codex-mini",
+ ollamaUrl: "",
+ customEndpoint: "",
+ maxContextSize: 128000,
+ },
+ [{ role: "user", content: "Analyze this source." }],
+ callbacks,
+ )
+
+ await vi.waitFor(() => {
+ expect(tauriMocks.invoke).toHaveBeenCalledTimes(1)
+ })
+
+ const payload = tauriMocks.invoke.mock.calls[0]?.[1] as { streamId: string }
+ // `code` is null because the timeout task removes the child handle before
+ // killing it, so the run's status is never observed on any platform, and
+ // the timeout is visible only through `timedOut`. The stderr here is
+ // startup noise Codex prints on every run - it must not become the
+ // headline.
+ tauriMocks.emit(`codex-cli:${payload.streamId}:done`, {
+ code: null,
+ timedOut: true,
+ timeoutMinutes: 10,
+ stderr: "ERROR codex_core::session: failed to load skill /x/SKILL.md: missing YAML frontmatter",
+ stdout: "",
+ })
+
+ await stream
+
+ expect(callbacks.onDone).not.toHaveBeenCalled()
+ expect(callbacks.onError).toHaveBeenCalledTimes(1)
+ const message = (callbacks.onError.mock.calls[0]?.[0] as Error).message
+ expect(message).toContain("10 minute timeout")
+ expect(message).not.toContain("did not emit an agent_message")
+ // The diagnostic is kept, but below the cause that explains it. Both
+ // anchors are asserted present first: a substring that has drifted out of
+ // the message yields -1, which would satisfy any ordering check silently.
+ const causeAt = message.indexOf("10 minute timeout")
+ const diagnosticAt = message.indexOf("missing YAML frontmatter")
+ expect(causeAt).toBeGreaterThanOrEqual(0)
+ expect(diagnosticAt).toBeGreaterThanOrEqual(0)
+ expect(causeAt).toBeLessThan(diagnosticAt)
+ })
+
+ it("errors on timeout even when a partial agent message already arrived", async () => {
+ const callbacks = {
+ onToken: vi.fn(),
+ onDone: vi.fn(),
+ onError: vi.fn(),
+ }
+
+ const stream = streamCodexCli(
+ {
+ provider: "codex-cli",
+ apiKey: "",
+ model: "gpt-5.1-codex-mini",
+ ollamaUrl: "",
+ customEndpoint: "",
+ maxContextSize: 128000,
+ },
+ [{ role: "user", content: "Analyze this source." }],
+ callbacks,
+ )
+
+ await vi.waitFor(() => {
+ expect(tauriMocks.invoke).toHaveBeenCalledTimes(1)
+ })
+
+ const payload = tauriMocks.invoke.mock.calls[0]?.[1] as { streamId: string }
+ tauriMocks.emit(
+ `codex-cli:${payload.streamId}`,
+ JSON.stringify({
+ type: "item.completed",
+ item: { type: "agent_message", text: "partial answer" },
+ }),
+ )
+ tauriMocks.emit(`codex-cli:${payload.streamId}:done`, {
+ code: null,
+ timedOut: true,
+ timeoutMinutes: 10,
+ stderr: "",
+ stdout: "",
+ })
+
+ await stream
+
+ expect(callbacks.onToken).toHaveBeenCalledWith("partial answer")
+ expect(callbacks.onDone).not.toHaveBeenCalled()
+ expect(callbacks.onError).toHaveBeenCalledTimes(1)
+ expect((callbacks.onError.mock.calls[0]?.[0] as Error).message).toContain(
+ "10 minute timeout",
+ )
+ })
+
+ it("labels timeout fallback output as stdout when stderr is empty", async () => {
+ const callbacks = {
+ onToken: vi.fn(),
+ onDone: vi.fn(),
+ onError: vi.fn(),
+ }
+
+ const stream = streamCodexCli(
+ {
+ provider: "codex-cli",
+ apiKey: "",
+ model: "gpt-5.1-codex-mini",
+ ollamaUrl: "",
+ customEndpoint: "",
+ maxContextSize: 128000,
+ },
+ [{ role: "user", content: "Analyze this source." }],
+ callbacks,
+ )
+
+ await vi.waitFor(() => {
+ expect(tauriMocks.invoke).toHaveBeenCalledTimes(1)
+ })
+
+ const payload = tauriMocks.invoke.mock.calls[0]?.[1] as { streamId: string }
+ tauriMocks.emit(`codex-cli:${payload.streamId}:done`, {
+ code: null,
+ timedOut: true,
+ timeoutMinutes: 10,
+ stderr: "",
+ stdout: '{"type":"turn.started"}',
+ })
+
+ await stream
+
+ const message = (callbacks.onError.mock.calls[0]?.[0] as Error).message
+ expect(message).toContain("turn.started")
+ expect(message).toContain("— stdout —")
+ expect(message).not.toContain("— stderr —")
+ })
+
it("does not spawn when the signal is already aborted", async () => {
const controller = new AbortController()
controller.abort()
diff --git a/src/lib/codex-cli-transport.ts b/src/lib/codex-cli-transport.ts
index eef9b3ba..3810d593 100644
--- a/src/lib/codex-cli-transport.ts
+++ b/src/lib/codex-cli-transport.ts
@@ -157,12 +157,42 @@ export async function streamCodexCli(
return
}
- unlistenDone = await listen<{ code: number | null; stderr: string; stdout?: string }>(
+ unlistenDone = await listen<{
+ code: number | null
+ stderr: string
+ stdout?: string
+ timedOut?: boolean
+ timeoutMinutes?: number
+ }>(
`codex-cli:${streamId}:done`,
(event) => {
const code = event.payload?.code
const stderr = event.payload?.stderr?.trim() ?? ""
const stdout = event.payload?.stdout ?? ""
+ // Checked before `code`, and before the agent_message branch below.
+ // The timeout task takes the child handle away in order to kill it, so
+ // `code` is null here regardless of how the process ended. The
+ // exit-code branch skips null outright, and the branch after it calls
+ // onDone once any agent message has arrived, so a timeout that had
+ // already produced partial output would be reported as a success.
+ if (event.payload?.timedOut) {
+ const minutes = event.payload.timeoutMinutes
+ const limit = typeof minutes === "number" ? `${minutes} minute` : "configured"
+ const details = stderr || stdout.trim()
+ // Only stderr was consulted first; say which stream this actually is.
+ const label = stderr ? "stderr" : "stdout"
+ finishWith(() =>
+ onError(new Error(
+ [
+ `Codex CLI did not report completion within the ${limit} timeout, so LLM Wiki stopped waiting.`,
+ "Raise the Codex CLI timeout for this preset in Settings",
+ "(1-240 minutes), or shorten the prompt.",
+ details ? `\n\n— ${label} —\n${details}` : "",
+ ].join(" ").trim(),
+ )),
+ )
+ return
+ }
if (code !== null && code !== undefined && code !== 0) {
const details = stderr || stdout.trim() || unparsedLines.join("\n")
finishWith(() =>