From eabe18714f721e6e94df966068abd190774010b7 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Wed, 1 Oct 2025 12:10:20 -0700 Subject: [PATCH 01/20] fix: use `number` instead of `bigint` for the generated TS for RequestId (#4575) Before this PR: ```typescript export type RequestId = string | bigint; ``` After: ```typescript export type RequestId = string | number; ``` `bigint` introduces headaches in TypeScript without providing any real value. --- codex-rs/app-server-protocol/src/jsonrpc_lite.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/codex-rs/app-server-protocol/src/jsonrpc_lite.rs b/codex-rs/app-server-protocol/src/jsonrpc_lite.rs index e458125dd2..9d6d6da06f 100644 --- a/codex-rs/app-server-protocol/src/jsonrpc_lite.rs +++ b/codex-rs/app-server-protocol/src/jsonrpc_lite.rs @@ -11,6 +11,7 @@ pub const JSONRPC_VERSION: &str = "2.0"; #[serde(untagged)] pub enum RequestId { String(String), + #[ts(type = "number")] Integer(i64), } From 609f75acecfe047035f2f19f4f8b74455a416efe Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Wed, 1 Oct 2025 12:26:28 -0700 Subject: [PATCH 02/20] Fix hang on second oauth login attempt (#4568) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This PR fixes a bug that results in a hang in the oauth login flow if a user logs in, then logs out, then logs in again without first closing the browser window. Root cause of problem: We use a local web server for the oauth flow, and it's implemented using the `tiny_http` rust crate. During the first login, a socket is created between the browser and the server. The `tiny_http` library creates worker threads that persist for as long as this socket remains open. Currently, there's no way to close the connection on the server side — the library provides no API to do this. The library also filters all "Connect: close" headers, which makes it difficult to tell the client browser to close the connection. On the second login attempt, the browser uses the existing connection rather than creating a new one. Since that connection is associated with a server instance that no longer exists, it is effectively ignored. I considered switching from `tiny_http` to a different web server library, but that would have been a big change with significant regression risk. This PR includes a more surgical fix that works around the limitation of `tiny_http` and sends a "Connect: close" header on the last "success" page of the oauth flow. --- codex-rs/login/src/server.rs | 78 ++++++++++++++++++++++++++++++------ 1 file changed, 66 insertions(+), 12 deletions(-) diff --git a/codex-rs/login/src/server.rs b/codex-rs/login/src/server.rs index 275e98901f..7808246a58 100644 --- a/codex-rs/login/src/server.rs +++ b/codex-rs/login/src/server.rs @@ -25,6 +25,7 @@ use tiny_http::Header; use tiny_http::Request; use tiny_http::Response; use tiny_http::Server; +use tiny_http::StatusCode; const DEFAULT_ISSUER: &str = "https://auth.openai.com"; const DEFAULT_PORT: u16 = 1455; @@ -148,8 +149,15 @@ pub fn run_login_server(opts: ServerOptions) -> io::Result { let _ = tokio::task::spawn_blocking(move || req.respond(response)).await; None } - HandledRequest::ResponseAndExit { response, result } => { - let _ = tokio::task::spawn_blocking(move || req.respond(response)).await; + HandledRequest::ResponseAndExit { + headers, + body, + result, + } => { + let _ = tokio::task::spawn_blocking(move || { + send_response_with_disconnect(req, headers, body) + }) + .await; Some(result) } HandledRequest::RedirectWithHeader(header) => { @@ -185,7 +193,8 @@ enum HandledRequest { Response(Response>>), RedirectWithHeader(Header), ResponseAndExit { - response: Response>>, + headers: Vec
, + body: Vec, result: io::Result<()>, }, } @@ -275,20 +284,21 @@ async fn process_request( } "/success" => { let body = include_str!("assets/success.html"); - let mut resp = Response::from_data(body.as_bytes()); - if let Ok(h) = tiny_http::Header::from_bytes( - &b"Content-Type"[..], - &b"text/html; charset=utf-8"[..], - ) { - resp.add_header(h); - } HandledRequest::ResponseAndExit { - response: resp, + headers: match Header::from_bytes( + &b"Content-Type"[..], + &b"text/html; charset=utf-8"[..], + ) { + Ok(header) => vec![header], + Err(_) => Vec::new(), + }, + body: body.as_bytes().to_vec(), result: Ok(()), } } "/cancel" => HandledRequest::ResponseAndExit { - response: Response::from_string("Login cancelled"), + headers: Vec::new(), + body: b"Login cancelled".to_vec(), result: Err(io::Error::new( io::ErrorKind::Interrupted, "Login cancelled", @@ -298,6 +308,50 @@ async fn process_request( } } +/// tiny_http filters `Connection` headers out of `Response` objects, so using +/// `req.respond` never informs the client (or the library) that a keep-alive +/// socket should be closed. That leaves the per-connection worker parked in a +/// loop waiting for more requests, which in turn causes the next login attempt +/// to hang on the old connection. This helper bypasses tiny_http’s response +/// machinery: it extracts the raw writer, prints the HTTP response manually, +/// and always appends `Connection: close`, ensuring the socket is closed from +/// the server side. Ideally, tiny_http would provide an API to control +/// server-side connection persistence, but it does not. +fn send_response_with_disconnect( + req: Request, + mut headers: Vec
, + body: Vec, +) -> io::Result<()> { + let status = StatusCode(200); + let mut writer = req.into_writer(); + let reason = status.default_reason_phrase(); + write!(writer, "HTTP/1.1 {} {}\r\n", status.0, reason)?; + headers.retain(|h| !h.field.equiv("Connection")); + if let Ok(close_header) = Header::from_bytes(&b"Connection"[..], &b"close"[..]) { + headers.push(close_header); + } + + let content_length_value = format!("{}", body.len()); + if let Ok(content_length_header) = + Header::from_bytes(&b"Content-Length"[..], content_length_value.as_bytes()) + { + headers.push(content_length_header); + } + + for header in headers { + write!( + writer, + "{}: {}\r\n", + header.field.as_str(), + header.value.as_str() + )?; + } + + writer.write_all(b"\r\n")?; + writer.write_all(&body)?; + writer.flush() +} + fn build_authorize_url( issuer: &str, client_id: &str, From 170c685882bf1ea0b67363dda531e85359ccae67 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Wed, 1 Oct 2025 12:39:04 -0700 Subject: [PATCH 03/20] Explicit node imports (#4567) To help with compatibility --- pnpm-lock.yaml | 13 +++++++++++++ sdk/typescript/eslint.config.js | 11 ++++++++++- sdk/typescript/package.json | 5 +++-- sdk/typescript/samples/basic_streaming.ts | 4 ++-- sdk/typescript/src/exec.ts | 10 ++++++---- sdk/typescript/tests/codexExecSpy.ts | 8 ++++---- sdk/typescript/tests/run.test.ts | 6 +++--- sdk/typescript/tests/runStreamed.test.ts | 2 +- sdk/typescript/tsconfig.json | 2 +- 9 files changed, 43 insertions(+), 18 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0f4465a220..75db5f5971 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -34,6 +34,9 @@ importers: eslint-plugin-jest: specifier: ^29.0.1 version: 29.0.1(@typescript-eslint/eslint-plugin@8.45.0(@typescript-eslint/parser@8.45.0(eslint@9.36.0)(typescript@5.9.2))(eslint@9.36.0)(typescript@5.9.2))(eslint@9.36.0)(jest@29.7.0(@types/node@20.19.18)(ts-node@10.9.2(@types/node@20.19.18)(typescript@5.9.2)))(typescript@5.9.2) + eslint-plugin-node-import: + specifier: ^1.0.5 + version: 1.0.5(eslint@9.36.0) jest: specifier: ^29.7.0 version: 29.7.0(@types/node@20.19.18)(ts-node@10.9.2(@types/node@20.19.18)(typescript@5.9.2)) @@ -1084,6 +1087,12 @@ packages: jest: optional: true + eslint-plugin-node-import@1.0.5: + resolution: {integrity: sha512-razzgbr3EcB5+bm8/gqTqzTJ7Bpiu8PIChiAMRfZCNigr9GZBtnVSI+wPw+RGbWYCCIzWAsK/A7ihoAeSz5j7A==} + engines: {node: ^14.18.0 || ^16.0.0 || >= 18.0.0} + peerDependencies: + eslint: '>=7' + eslint-scope@8.4.0: resolution: {integrity: sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -3244,6 +3253,10 @@ snapshots: - supports-color - typescript + eslint-plugin-node-import@1.0.5(eslint@9.36.0): + dependencies: + eslint: 9.36.0 + eslint-scope@8.4.0: dependencies: esrecurse: 4.3.0 diff --git a/sdk/typescript/eslint.config.js b/sdk/typescript/eslint.config.js index accb022be1..742f6fc8fd 100644 --- a/sdk/typescript/eslint.config.js +++ b/sdk/typescript/eslint.config.js @@ -1,5 +1,14 @@ import eslint from "@eslint/js"; import { defineConfig } from "eslint/config"; import tseslint from "typescript-eslint"; +import nodeImport from "eslint-plugin-node-import"; -export default defineConfig(eslint.configs.recommended, tseslint.configs.recommended); +export default defineConfig(eslint.configs.recommended, tseslint.configs.recommended, { + plugins: { + "node-import": nodeImport, + }, + + rules: { + "node-import/prefer-node-protocol": 2, + }, +}); diff --git a/sdk/typescript/package.json b/sdk/typescript/package.json index d248ba07f3..835da304b0 100644 --- a/sdk/typescript/package.json +++ b/sdk/typescript/package.json @@ -50,13 +50,14 @@ "eslint": "^9.36.0", "eslint-config-prettier": "^9.1.2", "eslint-plugin-jest": "^29.0.1", + "eslint-plugin-node-import": "^1.0.5", "jest": "^29.7.0", "prettier": "^3.6.2", "ts-jest": "^29.3.4", + "ts-jest-mock-import-meta": "^1.3.1", "ts-node": "^10.9.2", "tsup": "^8.5.0", "typescript": "^5.9.2", - "typescript-eslint": "^8.45.0", - "ts-jest-mock-import-meta": "^1.3.1" + "typescript-eslint": "^8.45.0" } } diff --git a/sdk/typescript/samples/basic_streaming.ts b/sdk/typescript/samples/basic_streaming.ts index 801b52e76f..97098d8a69 100755 --- a/sdk/typescript/samples/basic_streaming.ts +++ b/sdk/typescript/samples/basic_streaming.ts @@ -7,11 +7,11 @@ import { Codex } from "@openai/codex-sdk"; import type { ThreadEvent, ThreadItem } from "@openai/codex-sdk"; import path from "node:path"; -const executablePath = +const codexPathOverride = process.env.CODEX_EXECUTABLE ?? path.join(process.cwd(), "..", "..", "codex-rs", "target", "debug", "codex"); -const codex = new Codex({ executablePath }); +const codex = new Codex({ codexPathOverride }); const thread = codex.startThread(); const rl = createInterface({ input, output }); diff --git a/sdk/typescript/src/exec.ts b/sdk/typescript/src/exec.ts index d11c2a1646..cdb1982f0d 100644 --- a/sdk/typescript/src/exec.ts +++ b/sdk/typescript/src/exec.ts @@ -1,4 +1,4 @@ -import { spawn } from "child_process"; +import { spawn } from "node:child_process"; import readline from "node:readline"; @@ -49,7 +49,7 @@ export class CodexExec { if (args.threadId) { commandArgs.push("resume", args.threadId); - } + } const env = { ...process.env, @@ -67,7 +67,7 @@ export class CodexExec { let spawnError: unknown | null = null; child.once("error", (err) => (spawnError = err)); - + if (!child.stdin) { child.kill(); throw new Error("Child process has no stdin"); @@ -104,7 +104,9 @@ export class CodexExec { resolve(code); } else { const stderrBuffer = Buffer.concat(stderrChunks); - reject(new Error(`Codex Exec exited with code ${code}: ${stderrBuffer.toString('utf8')}`)); + reject( + new Error(`Codex Exec exited with code ${code}: ${stderrBuffer.toString("utf8")}`), + ); } }); }); diff --git a/sdk/typescript/tests/codexExecSpy.ts b/sdk/typescript/tests/codexExecSpy.ts index daf8123cb7..3715f71e0b 100644 --- a/sdk/typescript/tests/codexExecSpy.ts +++ b/sdk/typescript/tests/codexExecSpy.ts @@ -1,11 +1,11 @@ -import * as child_process from "child_process"; +import * as child_process from "node:child_process"; -jest.mock("child_process", () => { - const actual = jest.requireActual("child_process"); +jest.mock("node:child_process", () => { + const actual = jest.requireActual("node:child_process"); return { ...actual, spawn: jest.fn(actual.spawn) }; }); -const actualChildProcess = jest.requireActual("child_process"); +const actualChildProcess = jest.requireActual("node:child_process"); const spawnMock = child_process.spawn as jest.MockedFunction; export function codexExecSpy(): { args: string[][]; restore: () => void } { diff --git a/sdk/typescript/tests/run.test.ts b/sdk/typescript/tests/run.test.ts index 7c243b8e79..5b8de3c8d4 100644 --- a/sdk/typescript/tests/run.test.ts +++ b/sdk/typescript/tests/run.test.ts @@ -1,6 +1,6 @@ -import fs from "fs"; -import os from "os"; -import path from "path"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; import { codexExecSpy } from "./codexExecSpy"; import { describe, expect, it } from "@jest/globals"; diff --git a/sdk/typescript/tests/runStreamed.test.ts b/sdk/typescript/tests/runStreamed.test.ts index 9f60cef02e..1db273b98a 100644 --- a/sdk/typescript/tests/runStreamed.test.ts +++ b/sdk/typescript/tests/runStreamed.test.ts @@ -1,4 +1,4 @@ -import path from "path"; +import path from "node:path"; import { describe, expect, it } from "@jest/globals"; diff --git a/sdk/typescript/tsconfig.json b/sdk/typescript/tsconfig.json index cdbc4f30c2..8d62e06941 100644 --- a/sdk/typescript/tsconfig.json +++ b/sdk/typescript/tsconfig.json @@ -19,6 +19,6 @@ "outDir": "dist", "stripInternal": true }, - "include": ["src", "tests", "tsup.config.ts"], + "include": ["src", "tests", "tsup.config.ts", "samples"], "exclude": ["dist", "node_modules"] } From 5d78c1edd337c038a1207c30fe8a6fa329e3d502 Mon Sep 17 00:00:00 2001 From: Thibault Sottiaux Date: Wed, 1 Oct 2025 13:11:36 -0700 Subject: [PATCH 04/20] Revert "chore: prompt update to enforce good usage of apply_patch" (#4576) Reverts openai/codex#3846 --- codex-rs/core/gpt_5_codex_prompt.md | 1 - 1 file changed, 1 deletion(-) diff --git a/codex-rs/core/gpt_5_codex_prompt.md b/codex-rs/core/gpt_5_codex_prompt.md index acff4b2f9e..9a298f460f 100644 --- a/codex-rs/core/gpt_5_codex_prompt.md +++ b/codex-rs/core/gpt_5_codex_prompt.md @@ -5,7 +5,6 @@ You are Codex, based on GPT-5. You are running as a coding agent in the Codex CL - The arguments to `shell` will be passed to execvp(). Most terminal commands should be prefixed with ["bash", "-lc"]. - Always set the `workdir` param when using the shell function. Do not use `cd` unless absolutely necessary. - When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much faster than alternatives like `grep`. (If the `rg` command is not found, then use alternatives.) -- When editing or creating files, you MUST use apply_patch as a standalone tool without going through ["bash", "-lc"], `Python`, `cat`, `sed`, ... Example: functions.shell({"command":["apply_patch","*** Begin Patch\nAdd File: hello.txt\n+Hello, world!\n*** End Patch"]}). ## Editing constraints From 31102af54b79e5a56883b9108a6fc9d5d0af8937 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Wed, 1 Oct 2025 13:12:59 -0700 Subject: [PATCH 05/20] Add initial set of doc comments to the SDK (#4513) Also perform minor code cleanup. --- codex-rs/exec/src/exec_events.rs | 58 ++++++++++++++++++++++++-------- sdk/typescript/README.md | 52 ++++++++++++++++++++++++++++ sdk/typescript/src/codex.ts | 16 +++++++++ sdk/typescript/src/events.ts | 18 ++++++++++ sdk/typescript/src/index.ts | 3 +- sdk/typescript/src/items.ts | 31 +++++++++++++++++ sdk/typescript/src/thread.ts | 56 ++++++++++++++++++++---------- sdk/typescript/tests/run.test.ts | 2 -- 8 files changed, 202 insertions(+), 34 deletions(-) diff --git a/codex-rs/exec/src/exec_events.rs b/codex-rs/exec/src/exec_events.rs index f52071d4d3..4ea57e19b5 100644 --- a/codex-rs/exec/src/exec_events.rs +++ b/codex-rs/exec/src/exec_events.rs @@ -2,34 +2,45 @@ use serde::Deserialize; use serde::Serialize; use ts_rs::TS; -/// Top-level events emitted on the Codex Exec thread stream. +/// Top-level JSONL events emitted by codex exec #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)] #[serde(tag = "type")] pub enum ThreadEvent { + /// Emitted when a new thread is started as the first event. #[serde(rename = "thread.started")] ThreadStarted(ThreadStartedEvent), + /// Emitted when a turn is started by sending a new prompt to the model. + /// A turn encompasses all events that happen while agent is processing the prompt. #[serde(rename = "turn.started")] TurnStarted(TurnStartedEvent), + /// Emitted when a turn is completed. Typically right after the assistant's response. #[serde(rename = "turn.completed")] TurnCompleted(TurnCompletedEvent), + /// Indicates that a turn failed with an error. #[serde(rename = "turn.failed")] TurnFailed(TurnFailedEvent), + /// Emitted when a new item is added to the thread. Typically the item will be in an "in progress" state. #[serde(rename = "item.started")] ItemStarted(ItemStartedEvent), + /// Emitted when an item is updated. #[serde(rename = "item.updated")] ItemUpdated(ItemUpdatedEvent), + /// Signals that an item has reached a terminal state—either success or failure. #[serde(rename = "item.completed")] ItemCompleted(ItemCompletedEvent), + /// Represents an unrecoverable error emitted directly by the event stream. #[serde(rename = "error")] Error(ThreadErrorEvent), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)] pub struct ThreadStartedEvent { + /// The identified of the new thread. Can be used to resume the thread later. pub thread_id: String, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS, Default)] + pub struct TurnStartedEvent {} #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)] @@ -42,11 +53,14 @@ pub struct TurnFailedEvent { pub error: ThreadErrorEvent, } -/// Minimal usage summary for a turn. +/// Describes the usage of tokens during a turn. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS, Default)] pub struct Usage { + /// The number of input tokens used during the turn. pub input_tokens: u64, + /// The number of cached input tokens used during the turn. pub cached_input_tokens: u64, + /// The number of output tokens used during the turn. pub output_tokens: u64, } @@ -83,34 +97,44 @@ pub struct ThreadItem { #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)] #[serde(tag = "item_type", rename_all = "snake_case")] pub enum ThreadItemDetails { + /// Response from the agent. + /// Either a natural-language response or a JSON string when structured output is requested. AssistantMessage(AssistantMessageItem), + /// Agent's reasoning summary. Reasoning(ReasoningItem), + /// Tracks a command executed by the agent. The item starts when the command is + /// spawned, and completes when the process exits with an exit code. CommandExecution(CommandExecutionItem), + /// Represents a set of file changes by the agent. The item is emitted only as a + /// completed event once the patch succeeds or fails. FileChange(FileChangeItem), + /// Represents a call to an MCP tool. The item starts when the invocation is + /// dispatched and completes when the MCP server reports success or failure. McpToolCall(McpToolCallItem), + /// Captures a web search request. It starts when the search is kicked off + /// and completes when results are returned to the agent. WebSearch(WebSearchItem), + /// Tracks the agent's running to-do list. It starts when the plan is first + /// issued, updates as steps change state, and completes when the turn ends. TodoList(TodoListItem), + /// Describes a non-fatal error surfaced as an item. Error(ErrorItem), } -/// Session metadata. -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)] -pub struct SessionItem { - pub session_id: String, -} - -/// Assistant message payload. +/// Response from the agent. +/// Either a natural-language response or a JSON string when structured output is requested. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)] pub struct AssistantMessageItem { pub text: String, } -/// Model reasoning summary payload. +/// Agent's reasoning summary. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)] pub struct ReasoningItem { pub text: String, } +/// The status of a command execution. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, TS)] #[serde(rename_all = "snake_case")] pub enum CommandExecutionStatus { @@ -120,7 +144,7 @@ pub enum CommandExecutionStatus { Failed, } -/// Local shell command execution payload. +/// A command executed by the agent. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)] pub struct CommandExecutionItem { pub command: String, @@ -130,13 +154,14 @@ pub struct CommandExecutionItem { pub status: CommandExecutionStatus, } -/// Single file change summary for a patch. +/// A set of file changes by the agent. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)] pub struct FileUpdateChange { pub path: String, pub kind: PatchChangeKind, } +/// The status of a file change. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)] #[serde(rename_all = "snake_case")] pub enum PatchApplyStatus { @@ -144,14 +169,14 @@ pub enum PatchApplyStatus { Failed, } -/// Patch application payload. +/// A set of file changes by the agent. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)] pub struct FileChangeItem { pub changes: Vec, pub status: PatchApplyStatus, } -/// Known change kinds for a patch. +/// Indicates the type of the file change. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)] #[serde(rename_all = "snake_case")] pub enum PatchChangeKind { @@ -160,6 +185,7 @@ pub enum PatchChangeKind { Update, } +/// The status of an MCP tool call. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, TS)] #[serde(rename_all = "snake_case")] pub enum McpToolCallStatus { @@ -169,6 +195,7 @@ pub enum McpToolCallStatus { Failed, } +/// A call to an MCP tool. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)] pub struct McpToolCallItem { pub server: String, @@ -176,16 +203,19 @@ pub struct McpToolCallItem { pub status: McpToolCallStatus, } +/// A web search request. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)] pub struct WebSearchItem { pub query: String, } +/// An error notification. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)] pub struct ErrorItem { pub message: String, } +/// An item in agent's to-do list. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)] pub struct TodoItem { pub text: String, diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md index b70c4f4aff..19accb0b30 100644 --- a/sdk/typescript/README.md +++ b/sdk/typescript/README.md @@ -1 +1,53 @@ # Codex SDK + +Bring the power of the best coding agent to your application. + +## Installation + +```bash +npm install @openai/codex-sdk +``` + +## Usage + +Call `startThread()` and `run()` to start a thead with Codex. + +```typescript +import { Codex } from "@openai/codex-sdk"; + +const codex = new Codex(); +const thread = codex.startThread(); +const result = await thread.run("Diagnose the test failure and propose a fix"); + +console.log(result); +``` + +You can call `run()` again to continue the same thread. + +```typescript +const result = await thread.run("Implement the fix"); + +console.log(result); +``` + +### Streaming + +The `await run()` method completes when a thread turn is complete and agent is prepared the final response. + +You can thread items while they are being produced by calling `await runStreamed()`. + +```typescript +const result = thread.runStreamed("Diagnose the test failure and propose a fix"); +``` + +### Resuming a thread + +If you don't have the original `Thread` instance to continue the thread, you can resume a thread by calling `resumeThread()` and providing the thread. + +```typescript +const threadId = "..."; +const thread = codex.resumeThread(threadId); +const result = await thread.run("Implement the fix"); + +console.log(result); +``` diff --git a/sdk/typescript/src/codex.ts b/sdk/typescript/src/codex.ts index 331b7e6e3f..8f87122839 100644 --- a/sdk/typescript/src/codex.ts +++ b/sdk/typescript/src/codex.ts @@ -2,6 +2,11 @@ import { CodexOptions } from "./codexOptions"; import { CodexExec } from "./exec"; import { Thread } from "./thread"; +/** + * Codex is the main class for interacting with the Codex agent. + * + * Use the `startThread()` method to start a new thread or `resumeThread()` to resume a previously started thread. + */ export class Codex { private exec: CodexExec; private options: CodexOptions; @@ -11,10 +16,21 @@ export class Codex { this.options = options; } + /** + * Starts a new conversation with an agent. + * @returns A new thread instance. + */ startThread(): Thread { return new Thread(this.exec, this.options); } + /** + * Resumes a conversation with an agent based on the thread id. + * Threads are persisted in ~/.codex/sessions. + * + * @param id The id of the thread to resume. + * @returns A new thread instance. + */ resumeThread(id: string): Thread { return new Thread(this.exec, this.options, id); } diff --git a/sdk/typescript/src/events.ts b/sdk/typescript/src/events.ts index 344e348a0f..b8adcfb4b0 100644 --- a/sdk/typescript/src/events.ts +++ b/sdk/typescript/src/events.ts @@ -2,55 +2,73 @@ import type { ThreadItem } from "./items"; +/** Emitted when a new thread is started as the first event. */ export type ThreadStartedEvent = { type: "thread.started"; + /** The identifier of the new thread. Can be used to resume the thread later. */ thread_id: string; }; +/** + * Emitted when a turn is started by sending a new prompt to the model. + * A turn encompasses all events that happen while the agent is processing the prompt. + */ export type TurnStartedEvent = { type: "turn.started"; }; +/** Describes the usage of tokens during a turn. */ export type Usage = { + /** The number of input tokens used during the turn. */ input_tokens: number; + /** The number of cached input tokens used during the turn. */ cached_input_tokens: number; + /** The number of output tokens used during the turn. */ output_tokens: number; }; +/** Emitted when a turn is completed. Typically right after the assistant's response. */ export type TurnCompletedEvent = { type: "turn.completed"; usage: Usage; }; +/** Indicates that a turn failed with an error. */ export type TurnFailedEvent = { type: "turn.failed"; error: ThreadError; }; +/** Emitted when a new item is added to the thread. Typically the item is initially "in progress". */ export type ItemStartedEvent = { type: "item.started"; item: ThreadItem; }; +/** Emitted when an item is updated. */ export type ItemUpdatedEvent = { type: "item.updated"; item: ThreadItem; }; +/** Signals that an item has reached a terminal state—either success or failure. */ export type ItemCompletedEvent = { type: "item.completed"; item: ThreadItem; }; +/** Fatal error emitted by the stream. */ export type ThreadError = { message: string; }; +/** Represents an unrecoverable error emitted directly by the event stream. */ export type ThreadErrorEvent = { type: "error"; message: string; }; +/** Top-level JSONL events emitted by codex exec. */ export type ThreadEvent = | ThreadStartedEvent | TurnStartedEvent diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts index 5fa6d5bc4e..f2f84d153c 100644 --- a/sdk/typescript/src/index.ts +++ b/sdk/typescript/src/index.ts @@ -22,7 +22,8 @@ export type { ErrorItem, } from "./items"; -export { Thread, RunResult, RunStreamedResult, Input } from "./thread"; +export { Thread } from "./thread"; +export type { RunResult, RunStreamedResult, Input } from "./thread"; export { Codex } from "./codex"; diff --git a/sdk/typescript/src/items.ts b/sdk/typescript/src/items.ts index 546dd66ffd..85f54d78ca 100644 --- a/sdk/typescript/src/items.ts +++ b/sdk/typescript/src/items.ts @@ -1,71 +1,101 @@ // based on item types from codex-rs/exec/src/exec_events.rs +/** The status of a command execution. */ export type CommandExecutionStatus = "in_progress" | "completed" | "failed"; +/** A command executed by the agent. */ export type CommandExecutionItem = { id: string; item_type: "command_execution"; + /** The command line executed by the agent. */ command: string; + /** Aggregated stdout and stderr captured while the command was running. */ aggregated_output: string; + /** Set when the command exits; omitted while still running. */ exit_code?: number; + /** Current status of the command execution. */ status: CommandExecutionStatus; }; +/** Indicates the type of the file change. */ export type PatchChangeKind = "add" | "delete" | "update"; +/** A set of file changes by the agent. */ export type FileUpdateChange = { path: string; kind: PatchChangeKind; }; +/** The status of a file change. */ export type PatchApplyStatus = "completed" | "failed"; +/** A set of file changes by the agent. Emitted once the patch succeeds or fails. */ export type FileChangeItem = { id: string; item_type: "file_change"; + /** Individual file changes that comprise the patch. */ changes: FileUpdateChange[]; + /** Whether the patch ultimately succeeded or failed. */ status: PatchApplyStatus; }; +/** The status of an MCP tool call. */ export type McpToolCallStatus = "in_progress" | "completed" | "failed"; +/** + * Represents a call to an MCP tool. The item starts when the invocation is dispatched + * and completes when the MCP server reports success or failure. + */ export type McpToolCallItem = { id: string; item_type: "mcp_tool_call"; + /** Name of the MCP server handling the request. */ server: string; + /** The tool invoked on the MCP server. */ tool: string; + /** Current status of the tool invocation. */ status: McpToolCallStatus; }; +/** Response from the agent. Either natural-language text or JSON when structured output is requested. */ export type AssistantMessageItem = { id: string; item_type: "assistant_message"; + /** Either natural-language text or JSON when structured output is requested. */ text: string; }; +/** Agent's reasoning summary. */ export type ReasoningItem = { id: string; item_type: "reasoning"; text: string; }; +/** Captures a web search request. Completes when results are returned to the agent. */ export type WebSearchItem = { id: string; item_type: "web_search"; query: string; }; +/** Describes a non-fatal error surfaced as an item. */ export type ErrorItem = { id: string; item_type: "error"; message: string; }; +/** An item in the agent's to-do list. */ export type TodoItem = { text: string; completed: boolean; }; +/** + * Tracks the agent's running to-do list. Starts when the plan is issued, updates as steps change, + * and completes when the turn ends. + */ export type TodoListItem = { id: string; item_type: "todo_list"; @@ -78,6 +108,7 @@ export type SessionItem = { session_id: string; }; +/** Canonical union of thread items and their type-specific payloads. */ export type ThreadItem = | AssistantMessageItem | ReasoningItem diff --git a/sdk/typescript/src/thread.ts b/sdk/typescript/src/thread.ts index de2c2c94dc..7ec710217c 100644 --- a/sdk/typescript/src/thread.ts +++ b/sdk/typescript/src/thread.ts @@ -4,29 +4,45 @@ import { CodexExec } from "./exec"; import { ThreadItem } from "./items"; import { TurnOptions } from "./turnOptions"; -export type RunResult = { +/** Completed turn. */ +export type Turn = { items: ThreadItem[]; finalResponse: string; }; -export type RunStreamedResult = { +/** Alias for `Turn` to describe the result of `run()`. */ +export type RunResult = Turn; + +/** The result of the `runStreamed` method. */ +export type StreamedTurn = { events: AsyncGenerator; }; +/** Alias for `StreamedTurn` to describe the result of `runStreamed()`. */ +export type RunStreamedResult = StreamedTurn; + +/** An input to send to the agent. */ export type Input = string; +/** Respesent a thread of conversation with the agent. One thread can have multiple consecutive turns. */ export class Thread { - private exec: CodexExec; - private options: CodexOptions; - public id: string | null; + private _exec: CodexExec; + private _options: CodexOptions; + private _id: string | null; - constructor(exec: CodexExec, options: CodexOptions, id: string | null = null) { - this.exec = exec; - this.options = options; - this.id = id; + /** Returns the ID of the thread. Populated after the first turn starts. */ + public get id(): string | null { + return this._id; } - async runStreamed(input: string, options?: TurnOptions): Promise { + constructor(exec: CodexExec, options: CodexOptions, id: string | null = null) { + this._exec = exec; + this._options = options; + this._id = id; + } + + /** Provides the input to the agent and streams events as they are produced during the turn. */ + async runStreamed(input: string, options?: TurnOptions): Promise { return { events: this.runStreamedInternal(input, options) }; } @@ -34,26 +50,32 @@ export class Thread { input: string, options?: TurnOptions, ): AsyncGenerator { - const generator = this.exec.run({ + const generator = this._exec.run({ input, - baseUrl: this.options.baseUrl, - apiKey: this.options.apiKey, - threadId: this.id, + baseUrl: this._options.baseUrl, + apiKey: this._options.apiKey, + threadId: this._id, model: options?.model, sandboxMode: options?.sandboxMode, workingDirectory: options?.workingDirectory, skipGitRepoCheck: options?.skipGitRepoCheck, }); for await (const item of generator) { - const parsed = JSON.parse(item) as ThreadEvent; + let parsed: ThreadEvent; + try { + parsed = JSON.parse(item) as ThreadEvent; + } catch (error) { + throw new Error(`Failed to parse item: ${item}`, { cause: error }); + } if (parsed.type === "thread.started") { - this.id = parsed.thread_id; + this._id = parsed.thread_id; } yield parsed; } } - async run(input: string, options?: TurnOptions): Promise { + /** Provides the input to the agent and returns the completed turn. */ + async run(input: string, options?: TurnOptions): Promise { const generator = this.runStreamedInternal(input, options); const items: ThreadItem[] = []; let finalResponse: string = ""; diff --git a/sdk/typescript/tests/run.test.ts b/sdk/typescript/tests/run.test.ts index 5b8de3c8d4..2f15237f4f 100644 --- a/sdk/typescript/tests/run.test.ts +++ b/sdk/typescript/tests/run.test.ts @@ -218,7 +218,6 @@ describe("Codex", () => { await close(); } }); - it("runs in provided working directory", async () => { const { url, close } = await startResponsesTestProxy({ statusCode: 200, @@ -286,7 +285,6 @@ describe("Codex", () => { } }); }); - function expectPair(args: string[] | undefined, pair: [string, string]) { if (!args) { throw new Error("Args is undefined"); From 07c1db351a27d3f3c07935f50d57f08576c5d26a Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Wed, 1 Oct 2025 14:29:05 -0700 Subject: [PATCH 06/20] rework patch/exec approval UI (#4573) | Scenario | Screenshot | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | short patch | short patch | | short command | short command | | long patch | long patch | | long command | long command | | viewing complete patch | viewing
complete patch | --- codex-rs/tui/src/app.rs | 37 +- codex-rs/tui/src/app_event.rs | 4 + .../tui/src/bottom_pane/approval_overlay.rs | 218 ++++---- .../tui/src/bottom_pane/bottom_pane_view.rs | 10 +- codex-rs/tui/src/bottom_pane/command_popup.rs | 5 +- .../tui/src/bottom_pane/custom_prompt_view.rs | 60 +-- .../tui/src/bottom_pane/file_search_popup.rs | 6 +- .../src/bottom_pane/list_selection_view.rs | 296 +++++------ .../src/bottom_pane/selection_popup_common.rs | 97 +--- ..._list_selection_spacing_with_subtitle.snap | 13 +- ...st_selection_spacing_without_subtitle.snap | 11 +- codex-rs/tui/src/chatwidget.rs | 26 +- ...ly_patch_manual_flow_history_approved.snap | 3 +- ...ly_patch_manual_flow_history_proposed.snap | 6 - ...hatwidget__tests__approval_modal_exec.snap | 28 +- ..._tests__approval_modal_exec_no_reason.snap | 19 +- ...atwidget__tests__approval_modal_patch.snap | 21 +- ...c_approval_history_proposed_multiline.snap | 7 - ..._exec_approval_history_proposed_short.snap | 6 - ...dget__tests__exec_approval_modal_exec.snap | 42 ++ ...sts__status_widget_and_approval_modal.snap | 23 +- codex-rs/tui/src/chatwidget/tests.rs | 232 ++++----- codex-rs/tui/src/diff_render.rs | 471 ++++++------------ codex-rs/tui/src/history_cell.rs | 38 +- codex-rs/tui/src/pager_overlay.rs | 420 +++++++++------- codex-rs/tui/src/render/mod.rs | 45 ++ codex-rs/tui/src/render/renderable.rs | 102 ++++ ...der__tests__apply_update_block_manual.snap | 10 +- ...ript_overlay_apply_patch_scroll_vt100.snap | 9 +- codex-rs/tui/src/status_indicator_widget.rs | 3 +- 30 files changed, 1127 insertions(+), 1141 deletions(-) delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__apply_patch_manual_flow_history_proposed.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_proposed_multiline.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_proposed_short.snap create mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_modal_exec.snap create mode 100644 codex-rs/tui/src/render/renderable.rs diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 2d840a8c2c..383e5cae54 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -1,10 +1,14 @@ use crate::app_backtrack::BacktrackState; use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; +use crate::bottom_pane::ApprovalRequest; use crate::chatwidget::ChatWidget; +use crate::diff_render::DiffSummary; +use crate::exec_command::strip_bash_lc_and_escape; use crate::file_search::FileSearchManager; use crate::history_cell::HistoryCell; use crate::pager_overlay::Overlay; +use crate::render::highlight::highlight_bash_to_lines; use crate::resume_picker::ResumeSelection; use crate::tui; use crate::tui::TuiEvent; @@ -292,7 +296,7 @@ impl App { } else { text.lines().map(ansi_escape_line).collect() }; - self.overlay = Some(Overlay::new_static_with_title( + self.overlay = Some(Overlay::new_static_with_lines( pager_lines, "D I F F".to_string(), )); @@ -324,12 +328,18 @@ impl App { Ok(()) => { if let Some(profile) = profile { self.chat_widget.add_info_message( - format!("Model changed to {model} for {profile} profile"), + format!("Model changed to {model}{reasoning_effort} for {profile} profile", reasoning_effort = effort.map(|e| format!(" {e}")).unwrap_or_default()), None, ); } else { - self.chat_widget - .add_info_message(format!("Model changed to {model}"), None); + self.chat_widget.add_info_message( + format!( + "Model changed to {model}{reasoning_effort}", + reasoning_effort = + effort.map(|e| format!(" {e}")).unwrap_or_default() + ), + None, + ); } } Err(err) => { @@ -363,6 +373,25 @@ impl App { AppEvent::OpenReviewCustomPrompt => { self.chat_widget.show_review_custom_prompt(); } + AppEvent::FullScreenApprovalRequest(request) => match request { + ApprovalRequest::ApplyPatch { cwd, changes, .. } => { + let _ = tui.enter_alt_screen(); + let diff_summary = DiffSummary::new(changes, cwd); + self.overlay = Some(Overlay::new_static_with_renderables( + vec![diff_summary.into()], + "P A T C H".to_string(), + )); + } + ApprovalRequest::Exec { command, .. } => { + let _ = tui.enter_alt_screen(); + let full_cmd = strip_bash_lc_and_escape(&command); + let full_cmd_lines = highlight_bash_to_lines(&full_cmd); + self.overlay = Some(Overlay::new_static_with_lines( + full_cmd_lines, + "E X E C".to_string(), + )); + } + }, } Ok(true) } diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 56c66379a6..9c8a71de2e 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -4,6 +4,7 @@ use codex_core::protocol::ConversationPathResponseEvent; use codex_core::protocol::Event; use codex_file_search::FileMatch; +use crate::bottom_pane::ApprovalRequest; use crate::history_cell::HistoryCell; use codex_core::protocol::AskForApproval; @@ -76,4 +77,7 @@ pub(crate) enum AppEvent { /// Open the custom prompt option from the review popup. OpenReviewCustomPrompt, + + /// Open the approval popup. + FullScreenApprovalRequest(ApprovalRequest), } diff --git a/codex-rs/tui/src/bottom_pane/approval_overlay.rs b/codex-rs/tui/src/bottom_pane/approval_overlay.rs index 7ab2b79a57..511039df4a 100644 --- a/codex-rs/tui/src/bottom_pane/approval_overlay.rs +++ b/codex-rs/tui/src/bottom_pane/approval_overlay.rs @@ -1,16 +1,21 @@ +use std::collections::HashMap; use std::path::PathBuf; use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; use crate::bottom_pane::BottomPaneView; use crate::bottom_pane::CancellationEvent; -use crate::bottom_pane::list_selection_view::HeaderLine; use crate::bottom_pane::list_selection_view::ListSelectionView; use crate::bottom_pane::list_selection_view::SelectionItem; use crate::bottom_pane::list_selection_view::SelectionViewParams; +use crate::diff_render::DiffSummary; use crate::exec_command::strip_bash_lc_and_escape; use crate::history_cell; +use crate::render::highlight::highlight_bash_to_lines; +use crate::render::renderable::ColumnRenderable; +use crate::render::renderable::Renderable; use crate::text_formatting::truncate_text; +use codex_core::protocol::FileChange; use codex_core::protocol::Op; use codex_core::protocol::ReviewDecision; use crossterm::event::KeyCode; @@ -22,8 +27,11 @@ use ratatui::layout::Rect; use ratatui::style::Stylize; use ratatui::text::Line; use ratatui::text::Span; +use ratatui::widgets::Paragraph; +use ratatui::widgets::Wrap; /// Request coming from the agent that needs user approval. +#[derive(Clone, Debug)] pub(crate) enum ApprovalRequest { Exec { id: String, @@ -33,13 +41,15 @@ pub(crate) enum ApprovalRequest { ApplyPatch { id: String, reason: Option, - grant_root: Option, + cwd: PathBuf, + changes: HashMap, }, } /// Modal overlay asking the user to approve or deny one or more requests. pub(crate) struct ApprovalOverlay { - current: Option, + current_request: Option, + current_variant: Option, queue: Vec, app_event_tx: AppEventSender, list: ListSelectionView, @@ -51,23 +61,16 @@ pub(crate) struct ApprovalOverlay { impl ApprovalOverlay { pub fn new(request: ApprovalRequest, app_event_tx: AppEventSender) -> Self { let mut view = Self { - current: Some(ApprovalRequestState::from(request)), + current_request: None, + current_variant: None, queue: Vec::new(), app_event_tx: app_event_tx.clone(), - list: ListSelectionView::new( - SelectionViewParams { - title: String::new(), - ..Default::default() - }, - app_event_tx, - ), + list: ListSelectionView::new(Default::default(), app_event_tx), options: Vec::new(), current_complete: false, done: false, }; - let (options, params) = view.build_options(); - view.options = options; - view.list = ListSelectionView::new(params, view.app_event_tx.clone()); + view.set_current(request); view } @@ -76,28 +79,30 @@ impl ApprovalOverlay { } fn set_current(&mut self, request: ApprovalRequest) { - self.current = Some(ApprovalRequestState::from(request)); + self.current_request = Some(request.clone()); + let ApprovalRequestState { variant, header } = ApprovalRequestState::from(request); + self.current_variant = Some(variant.clone()); self.current_complete = false; - let (options, params) = self.build_options(); + let (options, params) = Self::build_options(variant, header); self.options = options; self.list = ListSelectionView::new(params, self.app_event_tx.clone()); } - fn build_options(&self) -> (Vec, SelectionViewParams) { - let Some(state) = self.current.as_ref() else { - return ( - Vec::new(), - SelectionViewParams { - title: String::new(), - ..Default::default() - }, - ); - }; - let (options, title) = match &state.variant { + fn build_options( + variant: ApprovalVariant, + header: Box, + ) -> (Vec, SelectionViewParams) { + let (options, title) = match &variant { ApprovalVariant::Exec { .. } => (exec_options(), "Allow command?".to_string()), ApprovalVariant::ApplyPatch { .. } => (patch_options(), "Apply changes?".to_string()), }; + let header = Box::new(ColumnRenderable::new([ + Box::new(Line::from(title.bold())), + Box::new(Line::from("")), + header, + ])); + let items = options .iter() .map(|opt| SelectionItem { @@ -111,10 +116,9 @@ impl ApprovalOverlay { .collect(); let params = SelectionViewParams { - title, footer_hint: Some("Press Enter to confirm or Esc to cancel".to_string()), items, - header: state.header.clone(), + header, ..Default::default() }; @@ -128,8 +132,8 @@ impl ApprovalOverlay { let Some(option) = self.options.get(actual_idx) else { return; }; - if let Some(state) = self.current.as_ref() { - match (&state.variant, option.decision) { + if let Some(variant) = self.current_variant.as_ref() { + match (&variant, option.decision) { (ApprovalVariant::Exec { id, command }, decision) => { self.handle_exec_decision(id, command, decision); } @@ -171,30 +175,43 @@ impl ApprovalOverlay { } fn try_handle_shortcut(&mut self, key_event: &KeyEvent) -> bool { - if key_event.kind != KeyEventKind::Press { - return false; - } - let KeyEvent { - code: KeyCode::Char(c), - modifiers, - .. - } = key_event - else { - return false; - }; - if modifiers.contains(KeyModifiers::CONTROL) || modifiers.contains(KeyModifiers::ALT) { - return false; - } - let lower = c.to_ascii_lowercase(); - if let Some(idx) = self - .options - .iter() - .position(|opt| opt.shortcut.map(|s| s == lower).unwrap_or(false)) - { - self.apply_selection(idx); - true - } else { - false + match key_event { + KeyEvent { + kind: KeyEventKind::Press, + code: KeyCode::Char('a'), + modifiers, + .. + } if modifiers.contains(KeyModifiers::CONTROL) => { + if let Some(request) = self.current_request.as_ref() { + self.app_event_tx + .send(AppEvent::FullScreenApprovalRequest(request.clone())); + true + } else { + false + } + } + KeyEvent { + kind: KeyEventKind::Press, + code: KeyCode::Char(c), + modifiers, + .. + } if !modifiers.contains(KeyModifiers::CONTROL) + && !modifiers.contains(KeyModifiers::ALT) => + { + let lower = c.to_ascii_lowercase(); + match self + .options + .iter() + .position(|opt| opt.shortcut.map(|s| s == lower).unwrap_or(false)) + { + Some(idx) => { + self.apply_selection(idx); + true + } + None => false, + } + } + _ => false, } } } @@ -215,9 +232,9 @@ impl BottomPaneView for ApprovalOverlay { return CancellationEvent::Handled; } if !self.current_complete - && let Some(state) = self.current.as_ref() + && let Some(variant) = self.current_variant.as_ref() { - match &state.variant { + match &variant { ApprovalVariant::Exec { id, command } => { self.handle_exec_decision(id, command, ReviewDecision::Abort); } @@ -235,14 +252,6 @@ impl BottomPaneView for ApprovalOverlay { self.done } - fn desired_height(&self, width: u16) -> u16 { - self.list.desired_height(width) - } - - fn render(&self, area: Rect, buf: &mut Buffer) { - self.list.render(area, buf); - } - fn try_consume_approval_request( &mut self, request: ApprovalRequest, @@ -256,9 +265,19 @@ impl BottomPaneView for ApprovalOverlay { } } +impl Renderable for ApprovalOverlay { + fn desired_height(&self, width: u16) -> u16 { + self.list.desired_height(width) + } + + fn render(&self, area: Rect, buf: &mut Buffer) { + self.list.render(area, buf); + } +} + struct ApprovalRequestState { variant: ApprovalVariant, - header: Vec, + header: Box, } impl From for ApprovalRequestState { @@ -269,63 +288,50 @@ impl From for ApprovalRequestState { command, reason, } => { - let mut header = Vec::new(); + let mut header: Vec> = Vec::new(); if let Some(reason) = reason && !reason.is_empty() { - header.push(HeaderLine::Text { - text: reason, - italic: true, - }); - header.push(HeaderLine::Spacer); + header.push(reason.italic().into()); + header.push(Line::from("")); } - let command_snippet = exec_snippet(&command); - if !command_snippet.is_empty() { - header.push(HeaderLine::Text { - text: format!("Command: {command_snippet}"), - italic: false, - }); - header.push(HeaderLine::Spacer); + let full_cmd = strip_bash_lc_and_escape(&command); + let mut full_cmd_lines = highlight_bash_to_lines(&full_cmd); + if let Some(first) = full_cmd_lines.first_mut() { + first.spans.insert(0, Span::from("$ ")); } + header.extend(full_cmd_lines); Self { variant: ApprovalVariant::Exec { id, command }, - header, + header: Box::new(Paragraph::new(header).wrap(Wrap { trim: false })), } } ApprovalRequest::ApplyPatch { id, reason, - grant_root, + cwd, + changes, } => { - let mut header = Vec::new(); + let mut header: Vec> = Vec::new(); + header.push(DiffSummary::new(changes, cwd).into()); if let Some(reason) = reason && !reason.is_empty() { - header.push(HeaderLine::Text { - text: reason, - italic: true, - }); - header.push(HeaderLine::Spacer); - } - if let Some(root) = grant_root { - header.push(HeaderLine::Text { - text: format!( - "Grant write access to {} for the remainder of this session.", - root.display() - ), - italic: false, - }); - header.push(HeaderLine::Spacer); + header.push(Box::new(Line::from(""))); + header.push(Box::new( + Paragraph::new(reason.italic()).wrap(Wrap { trim: false }), + )); } Self { variant: ApprovalVariant::ApplyPatch { id }, - header, + header: Box::new(ColumnRenderable::new(header)), } } } } } +#[derive(Clone)] enum ApprovalVariant { Exec { id: String, command: Vec }, ApplyPatch { id: String }, @@ -343,20 +349,20 @@ fn exec_options() -> Vec { vec![ ApprovalOption { label: "Approve and run now".to_string(), - description: "(Y) Run this command one time".to_string(), + description: "Run this command one time".to_string(), decision: ReviewDecision::Approved, shortcut: Some('y'), }, ApprovalOption { label: "Always approve this session".to_string(), - description: "(A) Automatically approve this command for the rest of the session" + description: "Automatically approve this command for the rest of the session" .to_string(), decision: ReviewDecision::ApprovedForSession, shortcut: Some('a'), }, ApprovalOption { label: "Cancel".to_string(), - description: "(N) Do not run the command".to_string(), + description: "Do not run the command".to_string(), decision: ReviewDecision::Abort, shortcut: Some('n'), }, @@ -367,13 +373,13 @@ fn patch_options() -> Vec { vec![ ApprovalOption { label: "Approve".to_string(), - description: "(Y) Apply the proposed changes".to_string(), + description: "Apply the proposed changes".to_string(), decision: ReviewDecision::Approved, shortcut: Some('y'), }, ApprovalOption { label: "Cancel".to_string(), - description: "(N) Do not apply the changes".to_string(), + description: "Do not apply the changes".to_string(), decision: ReviewDecision::Abort, shortcut: Some('n'), }, @@ -516,8 +522,8 @@ mod tests { }; let view = ApprovalOverlay::new(exec_request, tx); - let mut buf = Buffer::empty(Rect::new(0, 0, 80, 6)); - view.render(Rect::new(0, 0, 80, 6), &mut buf); + let mut buf = Buffer::empty(Rect::new(0, 0, 80, view.desired_height(80))); + view.render(Rect::new(0, 0, 80, view.desired_height(80)), &mut buf); let rendered: Vec = (0..buf.area.height) .map(|row| { @@ -529,7 +535,7 @@ mod tests { assert!( rendered .iter() - .any(|line| line.contains("Command: echo hello world")), + .any(|line| line.contains("echo hello world")), "expected header to include command snippet, got {rendered:?}" ); } diff --git a/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs b/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs index 8f569ec863..0271a7e19b 100644 --- a/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs +++ b/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs @@ -1,12 +1,12 @@ use crate::bottom_pane::ApprovalRequest; +use crate::render::renderable::Renderable; use crossterm::event::KeyEvent; -use ratatui::buffer::Buffer; use ratatui::layout::Rect; use super::CancellationEvent; /// Trait implemented by every view that can be shown in the bottom pane. -pub(crate) trait BottomPaneView { +pub(crate) trait BottomPaneView: Renderable { /// Handle a key event while the view is active. A redraw is always /// scheduled after this call. fn handle_key_event(&mut self, _key_event: KeyEvent) {} @@ -21,12 +21,6 @@ pub(crate) trait BottomPaneView { CancellationEvent::NotHandled } - /// Return the desired height of the view. - fn desired_height(&self, width: u16) -> u16; - - /// Render the view: this will be displayed in place of the composer. - fn render(&self, area: Rect, buf: &mut Buffer); - /// Optional paste handler. Return true if the view modified its state and /// needs a redraw. fn handle_paste(&mut self, _pasted: String) -> bool { diff --git a/codex-rs/tui/src/bottom_pane/command_popup.rs b/codex-rs/tui/src/bottom_pane/command_popup.rs index c493958272..b597f9ec08 100644 --- a/codex-rs/tui/src/bottom_pane/command_popup.rs +++ b/codex-rs/tui/src/bottom_pane/command_popup.rs @@ -6,6 +6,8 @@ use super::popup_consts::MAX_POPUP_ROWS; use super::scroll_state::ScrollState; use super::selection_popup_common::GenericDisplayRow; use super::selection_popup_common::render_rows; +use crate::render::Insets; +use crate::render::RectExt; use crate::slash_command::SlashCommand; use crate::slash_command::built_in_slash_commands; use codex_common::fuzzy_match::fuzzy_match; @@ -205,13 +207,12 @@ impl WidgetRef for CommandPopup { fn render_ref(&self, area: Rect, buf: &mut Buffer) { let rows = self.rows_from_matches(self.filtered()); render_rows( - area, + area.inset(Insets::tlbr(0, 2, 0, 0)), buf, &rows, &self.state, MAX_POPUP_ROWS, "no matches", - false, ); } } diff --git a/codex-rs/tui/src/bottom_pane/custom_prompt_view.rs b/codex-rs/tui/src/bottom_pane/custom_prompt_view.rs index a8084d0d04..07bd920384 100644 --- a/codex-rs/tui/src/bottom_pane/custom_prompt_view.rs +++ b/codex-rs/tui/src/bottom_pane/custom_prompt_view.rs @@ -12,6 +12,8 @@ use ratatui::widgets::StatefulWidgetRef; use ratatui::widgets::Widget; use std::cell::RefCell; +use crate::render::renderable::Renderable; + use super::popup_consts::STANDARD_POPUP_HINT_LINE; use super::CancellationEvent; @@ -94,6 +96,36 @@ impl BottomPaneView for CustomPromptView { self.complete } + fn handle_paste(&mut self, pasted: String) -> bool { + if pasted.is_empty() { + return false; + } + self.textarea.insert_str(&pasted); + true + } + + fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> { + if area.height < 2 || area.width <= 2 { + return None; + } + let text_area_height = self.input_height(area.width).saturating_sub(1); + if text_area_height == 0 { + return None; + } + let extra_offset: u16 = if self.context_label.is_some() { 1 } else { 0 }; + let top_line_count = 1u16 + extra_offset; + let textarea_rect = Rect { + x: area.x.saturating_add(2), + y: area.y.saturating_add(top_line_count).saturating_add(1), + width: area.width.saturating_sub(2), + height: text_area_height, + }; + let state = *self.textarea_state.borrow(); + self.textarea.cursor_pos_with_state(textarea_rect, state) + } +} + +impl Renderable for CustomPromptView { fn desired_height(&self, width: u16) -> u16 { let extra_top: u16 = if self.context_label.is_some() { 1 } else { 0 }; 1u16 + extra_top + self.input_height(width) + 3u16 @@ -200,34 +232,6 @@ impl BottomPaneView for CustomPromptView { ); } } - - fn handle_paste(&mut self, pasted: String) -> bool { - if pasted.is_empty() { - return false; - } - self.textarea.insert_str(&pasted); - true - } - - fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> { - if area.height < 2 || area.width <= 2 { - return None; - } - let text_area_height = self.input_height(area.width).saturating_sub(1); - if text_area_height == 0 { - return None; - } - let extra_offset: u16 = if self.context_label.is_some() { 1 } else { 0 }; - let top_line_count = 1u16 + extra_offset; - let textarea_rect = Rect { - x: area.x.saturating_add(2), - y: area.y.saturating_add(top_line_count).saturating_add(1), - width: area.width.saturating_sub(2), - height: text_area_height, - }; - let state = *self.textarea_state.borrow(); - self.textarea.cursor_pos_with_state(textarea_rect, state) - } } impl CustomPromptView { diff --git a/codex-rs/tui/src/bottom_pane/file_search_popup.rs b/codex-rs/tui/src/bottom_pane/file_search_popup.rs index e017b50410..6ba8599dd1 100644 --- a/codex-rs/tui/src/bottom_pane/file_search_popup.rs +++ b/codex-rs/tui/src/bottom_pane/file_search_popup.rs @@ -3,6 +3,9 @@ use ratatui::buffer::Buffer; use ratatui::layout::Rect; use ratatui::widgets::WidgetRef; +use crate::render::Insets; +use crate::render::RectExt; + use super::popup_consts::MAX_POPUP_ROWS; use super::scroll_state::ScrollState; use super::selection_popup_common::GenericDisplayRow; @@ -139,13 +142,12 @@ impl WidgetRef for &FileSearchPopup { }; render_rows( - area, + area.inset(Insets::tlbr(0, 2, 0, 0)), buf, &rows_all, &self.state, MAX_POPUP_ROWS, empty_message, - false, ); } } diff --git a/codex-rs/tui/src/bottom_pane/list_selection_view.rs b/codex-rs/tui/src/bottom_pane/list_selection_view.rs index b20d7476a7..e2614885a0 100644 --- a/codex-rs/tui/src/bottom_pane/list_selection_view.rs +++ b/codex-rs/tui/src/bottom_pane/list_selection_view.rs @@ -2,15 +2,23 @@ use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use crossterm::event::KeyModifiers; use ratatui::buffer::Buffer; +use ratatui::layout::Constraint; +use ratatui::layout::Layout; use ratatui::layout::Rect; use ratatui::style::Stylize; use ratatui::text::Line; use ratatui::text::Span; +use ratatui::widgets::Block; use ratatui::widgets::Paragraph; use ratatui::widgets::Widget; -use textwrap::wrap; use crate::app_event_sender::AppEventSender; +use crate::render::Insets; +use crate::render::RectExt as _; +use crate::render::renderable::ColumnRenderable; +use crate::render::renderable::Renderable; +use crate::style::user_message_style; +use crate::terminal_palette; use super::CancellationEvent; use super::bottom_pane_view::BottomPaneView; @@ -23,12 +31,6 @@ use super::selection_popup_common::render_rows; /// One selectable item in the generic selection list. pub(crate) type SelectionAction = Box; -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) enum HeaderLine { - Text { text: String, italic: bool }, - Spacer, -} - pub(crate) struct SelectionItem { pub name: String, pub description: Option, @@ -38,20 +40,31 @@ pub(crate) struct SelectionItem { pub search_value: Option, } -#[derive(Default)] pub(crate) struct SelectionViewParams { - pub title: String, + pub title: Option, pub subtitle: Option, pub footer_hint: Option, pub items: Vec, pub is_searchable: bool, pub search_placeholder: Option, - pub header: Vec, + pub header: Box, +} + +impl Default for SelectionViewParams { + fn default() -> Self { + Self { + title: None, + subtitle: None, + footer_hint: None, + items: Vec::new(), + is_searchable: false, + search_placeholder: None, + header: Box::new(()), + } + } } pub(crate) struct ListSelectionView { - title: String, - subtitle: Option, footer_hint: Option, items: Vec, state: ScrollState, @@ -62,23 +75,22 @@ pub(crate) struct ListSelectionView { search_placeholder: Option, filtered_indices: Vec, last_selected_actual_idx: Option, - header: Vec, + header: Box, } impl ListSelectionView { - fn dim_prefix_span() -> Span<'static> { - "▌ ".dim() - } - - fn render_dim_prefix_line(area: Rect, buf: &mut Buffer) { - let para = Paragraph::new(Line::from(Self::dim_prefix_span())); - para.render(area, buf); - } - pub fn new(params: SelectionViewParams, app_event_tx: AppEventSender) -> Self { + let mut header = params.header; + if params.title.is_some() || params.subtitle.is_some() { + let title = params.title.map(|title| Line::from(title.bold())); + let subtitle = params.subtitle.map(|subtitle| Line::from(subtitle.dim())); + header = Box::new(ColumnRenderable::new([ + header, + Box::new(title), + Box::new(subtitle), + ])); + } let mut s = Self { - title: params.title, - subtitle: params.subtitle, footer_hint: params.footer_hint, items: params.items, state: ScrollState::new(), @@ -93,7 +105,7 @@ impl ListSelectionView { }, filtered_indices: Vec::new(), last_selected_actual_idx: None, - header: params.header, + header, }; s.apply_filter(); s @@ -171,7 +183,7 @@ impl ListSelectionView { .filter_map(|(visible_idx, actual_idx)| { self.items.get(*actual_idx).map(|item| { let is_selected = self.state.selected_idx == Some(visible_idx); - let prefix = if is_selected { '>' } else { ' ' }; + let prefix = if is_selected { '›' } else { ' ' }; let name = item.name.as_str(); let name_with_marker = if item.is_current { format!("{name} (current)") @@ -179,7 +191,13 @@ impl ListSelectionView { item.name.clone() }; let n = visible_idx + 1; - let display_name = format!("{prefix} {n}. {name_with_marker}"); + let display_name = if self.is_searchable { + // The number keys don't work when search is enabled (since we let the + // numbers be used for the search query). + format!("{prefix} {name_with_marker}") + } else { + format!("{prefix} {n}. {name_with_marker}") + }; GenericDisplayRow { name: display_name, match_indices: None, @@ -231,39 +249,6 @@ impl ListSelectionView { pub(crate) fn take_last_selected_index(&mut self) -> Option { self.last_selected_actual_idx.take() } - - fn header_spans_for_width(&self, width: u16) -> Vec>> { - if self.header.is_empty() || width == 0 { - return Vec::new(); - } - let prefix_width = Self::dim_prefix_span().width() as u16; - let available = width.saturating_sub(prefix_width).max(1) as usize; - let mut lines = Vec::new(); - for entry in &self.header { - match entry { - HeaderLine::Spacer => lines.push(Vec::new()), - HeaderLine::Text { text, italic } => { - if text.is_empty() { - lines.push(Vec::new()); - continue; - } - for part in wrap(text, available) { - let span = if *italic { - Span::from(part.into_owned()).italic() - } else { - Span::from(part.into_owned()) - }; - lines.push(vec![span]); - } - } - } - } - lines - } - - fn header_height(&self, width: u16) -> u16 { - self.header_spans_for_width(width).len() as u16 - } } impl BottomPaneView for ListSelectionView { @@ -299,6 +284,24 @@ impl BottomPaneView for ListSelectionView { self.search_query.push(c); self.apply_filter(); } + KeyEvent { + code: KeyCode::Char(c), + modifiers, + .. + } if !self.is_searchable + && !modifiers.contains(KeyModifiers::CONTROL) + && !modifiers.contains(KeyModifiers::ALT) => + { + if let Some(idx) = c + .to_digit(10) + .map(|d| d as usize) + .and_then(|d| d.checked_sub(1)) + && idx < self.items.len() + { + self.state.selected_idx = Some(idx); + self.accept(); + } + } KeyEvent { code: KeyCode::Enter, modifiers: KeyModifiers::NONE, @@ -316,7 +319,9 @@ impl BottomPaneView for ListSelectionView { self.complete = true; CancellationEvent::Handled } +} +impl Renderable for ListSelectionView { fn desired_height(&self, width: u16) -> u16 { // Measure wrapped height for up to MAX_POPUP_ROWS items at the given width. // Build the same display rows used by the renderer so wrapping math matches. @@ -324,19 +329,13 @@ impl BottomPaneView for ListSelectionView { let rows_height = measure_rows_height(&rows, &self.state, MAX_POPUP_ROWS, width); - // +1 for the title row, +1 for a spacer line beneath the header, - // +1 for optional subtitle, +1 for optional footer (2 lines incl. spacing) - let mut height = self.header_height(width); - height = height.saturating_add(rows_height + 2); + let mut height = self.header.desired_height(width); + height = height.saturating_add(rows_height + 3); if self.is_searchable { height = height.saturating_add(1); } - if self.subtitle.is_some() { - // +1 for subtitle (the spacer is accounted for above) - height = height.saturating_add(1); - } if self.footer_hint.is_some() { - height = height.saturating_add(2); + height = height.saturating_add(1); } height } @@ -346,52 +345,42 @@ impl BottomPaneView for ListSelectionView { return; } - let mut next_y = area.y; - let header_spans = self.header_spans_for_width(area.width); - for spans in header_spans.into_iter() { - if next_y >= area.y + area.height { - return; - } - let row = Rect { - x: area.x, - y: next_y, - width: area.width, - height: 1, - }; - let mut prefixed: Vec> = vec![Self::dim_prefix_span()]; - if spans.is_empty() { - prefixed.push(String::new().into()); - } else { - prefixed.extend(spans); - } - Paragraph::new(Line::from(prefixed)).render(row, buf); - next_y = next_y.saturating_add(1); + let [content_area, footer_area] = Layout::vertical([ + Constraint::Fill(1), + Constraint::Length(if self.footer_hint.is_some() { 1 } else { 0 }), + ]) + .areas(area); + + Block::default() + .style(user_message_style(terminal_palette::default_bg())) + .render(content_area, buf); + + let header_height = self.header.desired_height(content_area.width); + let rows = self.build_rows(); + let rows_height = + measure_rows_height(&rows, &self.state, MAX_POPUP_ROWS, content_area.width); + let [header_area, _, search_area, list_area] = Layout::vertical([ + Constraint::Max(header_height), + Constraint::Max(1), + Constraint::Length(if self.is_searchable { 1 } else { 0 }), + Constraint::Length(rows_height), + ]) + .areas(content_area.inset(Insets::vh(1, 2))); + + if header_area.height < header_height { + let [header_area, elision_area] = + Layout::vertical([Constraint::Fill(1), Constraint::Length(1)]).areas(header_area); + self.header.render(header_area, buf); + Paragraph::new(vec![ + Line::from(format!("[… {header_height} lines] ctrl + a view all")).dim(), + ]) + .render(elision_area, buf); + } else { + self.header.render(header_area, buf); } - if next_y >= area.y + area.height { - return; - } - - let title_area = Rect { - x: area.x, - y: next_y, - width: area.width, - height: 1, - }; - Paragraph::new(Line::from(vec![ - Self::dim_prefix_span(), - self.title.clone().bold(), - ])) - .render(title_area, buf); - next_y = next_y.saturating_add(1); - - if self.is_searchable && next_y < area.y + area.height { - let search_area = Rect { - x: area.x, - y: next_y, - width: area.width, - height: 1, - }; + if self.is_searchable { + Line::from(self.search_query.clone()).render(search_area, buf); let query_span: Span<'static> = if self.search_query.is_empty() { self.search_placeholder .as_ref() @@ -400,80 +389,40 @@ impl BottomPaneView for ListSelectionView { } else { self.search_query.clone().into() }; - Paragraph::new(Line::from(vec![Self::dim_prefix_span(), query_span])) - .render(search_area, buf); - next_y = next_y.saturating_add(1); + Line::from(query_span).render(search_area, buf); } - if let Some(sub) = &self.subtitle { - if next_y >= area.y + area.height { - return; - } - let subtitle_area = Rect { - x: area.x, - y: next_y, - width: area.width, - height: 1, + if list_area.height > 0 { + let list_area = Rect { + x: list_area.x - 2, + y: list_area.y, + width: list_area.width + 2, + height: list_area.height, }; - Paragraph::new(Line::from(vec![Self::dim_prefix_span(), sub.clone().dim()])) - .render(subtitle_area, buf); - next_y = next_y.saturating_add(1); - } - - if next_y >= area.y + area.height { - return; - } - let spacer_area = Rect { - x: area.x, - y: next_y, - width: area.width, - height: 1, - }; - Self::render_dim_prefix_line(spacer_area, buf); - next_y = next_y.saturating_add(1); - - let footer_reserved = if self.footer_hint.is_some() { 2 } else { 0 }; - if next_y >= area.y + area.height { - return; - } - let rows_area = Rect { - x: area.x, - y: next_y, - width: area.width, - height: area - .height - .saturating_sub(next_y.saturating_sub(area.y)) - .saturating_sub(footer_reserved), - }; - - let rows = self.build_rows(); - if rows_area.height > 0 { render_rows( - rows_area, + list_area, buf, &rows, &self.state, - MAX_POPUP_ROWS, + list_area.height as usize, "no matches", - true, ); } if let Some(hint) = &self.footer_hint { - let footer_area = Rect { - x: area.x, - y: area.y + area.height - 1, - width: area.width, - height: 1, + let hint_area = Rect { + x: footer_area.x + 2, + y: footer_area.y, + width: footer_area.width.saturating_sub(2), + height: footer_area.height, }; - Paragraph::new(hint.clone().dim()).render(footer_area, buf); + Line::from(hint.clone().dim()).render(hint_area, buf); } } } #[cfg(test)] mod tests { - use super::BottomPaneView; use super::*; use crate::app_event::AppEvent; use crate::bottom_pane::popup_consts::STANDARD_POPUP_HINT_LINE; @@ -504,7 +453,7 @@ mod tests { ]; ListSelectionView::new( SelectionViewParams { - title: "Select Approval Mode".to_string(), + title: Some("Select Approval Mode".to_string()), subtitle: subtitle.map(str::to_string), footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), items, @@ -516,7 +465,7 @@ mod tests { fn render_lines(view: &ListSelectionView) -> String { let width = 48; - let height = BottomPaneView::desired_height(view, width); + let height = view.desired_height(width); let area = Rect::new(0, 0, width, height); let mut buf = Buffer::empty(area); view.render(area, &mut buf); @@ -567,7 +516,7 @@ mod tests { }]; let mut view = ListSelectionView::new( SelectionViewParams { - title: "Select Approval Mode".to_string(), + title: Some("Select Approval Mode".to_string()), footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), items, is_searchable: true, @@ -579,6 +528,9 @@ mod tests { view.set_search_query("filters".to_string()); let lines = render_lines(&view); - assert!(lines.contains("▌ filters")); + assert!( + lines.contains("filters"), + "expected search query line to include rendered query, got {lines:?}" + ); } } diff --git a/codex-rs/tui/src/bottom_pane/selection_popup_common.rs b/codex-rs/tui/src/bottom_pane/selection_popup_common.rs index f3b238016a..fd523532a2 100644 --- a/codex-rs/tui/src/bottom_pane/selection_popup_common.rs +++ b/codex-rs/tui/src/bottom_pane/selection_popup_common.rs @@ -3,17 +3,13 @@ use ratatui::layout::Rect; // Note: Table-based layout previously used Constraint; the manual renderer // below no longer requires it. use ratatui::style::Color; -use ratatui::style::Modifier; -use ratatui::style::Style; use ratatui::style::Stylize; use ratatui::text::Line; use ratatui::text::Span; -use ratatui::widgets::Paragraph; use ratatui::widgets::Widget; use unicode_width::UnicodeWidthChar; use super::scroll_state::ScrollState; -use crate::ui_consts::LIVE_PREFIX_COLS; /// A generic representation of a display row for selection popups. pub(crate) struct GenericDisplayRow { @@ -23,8 +19,6 @@ pub(crate) struct GenericDisplayRow { pub description: Option, // optional grey text after the name } -impl GenericDisplayRow {} - /// Compute a shared description-column start based on the widest visible name /// plus two spaces of padding. Ensures at least one column is left for the /// description. @@ -117,71 +111,19 @@ pub(crate) fn render_rows( state: &ScrollState, max_results: usize, empty_message: &str, - include_border: bool, ) { - if include_border { - use ratatui::widgets::Block; - use ratatui::widgets::BorderType; - use ratatui::widgets::Borders; - - // Always draw a dim left border to match other popups. - let block = Block::default() - .borders(Borders::LEFT) - .border_type(BorderType::QuadrantOutside) - .border_style(Style::default().add_modifier(Modifier::DIM)); - block.render(area, buf); - } - - // Content renders to the right of the border with the same live prefix - // padding used by the composer so the popup aligns with the input text. - let prefix_cols = LIVE_PREFIX_COLS; - let content_area = Rect { - x: area.x.saturating_add(prefix_cols), - y: area.y, - width: area.width.saturating_sub(prefix_cols), - height: area.height, - }; - - // Clear the padding column(s) so stale characters never peek between the - // border and the popup contents. - let padding_cols = prefix_cols.saturating_sub(1); - if padding_cols > 0 { - let pad_start = area.x.saturating_add(1); - let pad_end = pad_start - .saturating_add(padding_cols) - .min(area.x.saturating_add(area.width)); - let pad_bottom = area.y.saturating_add(area.height); - for x in pad_start..pad_end { - for y in area.y..pad_bottom { - if let Some(cell) = buf.cell_mut((x, y)) { - cell.set_symbol(" "); - } - } - } - } - if rows_all.is_empty() { - if content_area.height > 0 { - let para = Paragraph::new(Line::from(empty_message.dim().italic())); - para.render( - Rect { - x: content_area.x, - y: content_area.y, - width: content_area.width, - height: 1, - }, - buf, - ); + if area.height > 0 { + Line::from(empty_message.dim().italic()).render(area, buf); } return; } // Determine which logical rows (items) are visible given the selection and // the max_results clamp. Scrolling is still item-based for simplicity. - let max_rows_from_area = content_area.height as usize; let visible_items = max_results .min(rows_all.len()) - .min(max_rows_from_area.max(1)); + .min(area.height.max(1) as usize); let mut start_idx = state.scroll_top.min(rows_all.len().saturating_sub(1)); if let Some(sel) = state.selected_idx { @@ -195,18 +137,18 @@ pub(crate) fn render_rows( } } - let desc_col = compute_desc_col(rows_all, start_idx, visible_items, content_area.width); + let desc_col = compute_desc_col(rows_all, start_idx, visible_items, area.width); // Render items, wrapping descriptions and aligning wrapped lines under the // shared description column. Stop when we run out of vertical space. - let mut cur_y = content_area.y; + let mut cur_y = area.y; for (i, row) in rows_all .iter() .enumerate() .skip(start_idx) .take(visible_items) { - if cur_y >= content_area.y + content_area.height { + if cur_y >= area.y + area.height { break; } @@ -217,7 +159,7 @@ pub(crate) fn render_rows( description, } = row; - let full_line = build_full_line( + let mut full_line = build_full_line( &GenericDisplayRow { name: name.clone(), match_indices: match_indices.clone(), @@ -226,32 +168,31 @@ pub(crate) fn render_rows( }, desc_col, ); + if Some(i) == state.selected_idx { + // Match previous behavior: cyan + bold for the selected row. + full_line.spans.iter_mut().for_each(|span| { + span.style = span.style.fg(Color::Cyan).bold(); + }); + } // Wrap with subsequent indent aligned to the description column. use crate::wrapping::RtOptions; use crate::wrapping::word_wrap_line; - let options = RtOptions::new(content_area.width as usize) + let options = RtOptions::new(area.width as usize) .initial_indent(Line::from("")) .subsequent_indent(Line::from(" ".repeat(desc_col))); let wrapped = word_wrap_line(&full_line, options); // Render the wrapped lines. - for mut line in wrapped { - if cur_y >= content_area.y + content_area.height { + for line in wrapped { + if cur_y >= area.y + area.height { break; } - if Some(i) == state.selected_idx { - // Match previous behavior: cyan + bold for the selected row. - line.style = Style::default() - .fg(Color::Cyan) - .add_modifier(Modifier::BOLD); - } - let para = Paragraph::new(line); - para.render( + line.render( Rect { - x: content_area.x, + x: area.x, y: cur_y, - width: content_area.width, + width: area.width, height: 1, }, buf, diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_with_subtitle.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_with_subtitle.snap index ced53b7ce6..9cbfe88f78 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_with_subtitle.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_with_subtitle.snap @@ -2,10 +2,11 @@ source: tui/src/bottom_pane/list_selection_view.rs expression: render_lines(&view) --- -▌ Select Approval Mode -▌ Switch between Codex approval presets -▌ -▌ > 1. Read Only (current) Codex can read files -▌ 2. Full Access Codex can edit files -Press Enter to confirm or Esc to go back + Select Approval Mode + Switch between Codex approval presets + +› 1. Read Only (current) Codex can read files + 2. Full Access Codex can edit files + + Press Enter to confirm or Esc to go back diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_without_subtitle.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_without_subtitle.snap index b9858a4307..5e3cf2c6e6 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_without_subtitle.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_without_subtitle.snap @@ -2,9 +2,10 @@ source: tui/src/bottom_pane/list_selection_view.rs expression: render_lines(&view) --- -▌ Select Approval Mode -▌ -▌ > 1. Read Only (current) Codex can read files -▌ 2. Full Access Codex can edit files -Press Enter to confirm or Esc to go back + Select Approval Mode + +› 1. Read Only (current) Codex can read files + 2. Full Access Codex can edit files + + Press Enter to confirm or Esc to go back diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 5973f619a6..9940c8f7d7 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -79,7 +79,6 @@ use crate::history_cell; use crate::history_cell::AgentMessageCell; use crate::history_cell::HistoryCell; use crate::history_cell::McpToolCallCell; -use crate::history_cell::PatchEventType; use crate::markdown::append_markdown; use crate::slash_command::SlashCommand; use crate::status::RateLimitSnapshotDisplay; @@ -534,9 +533,6 @@ impl ChatWidget { fn on_patch_apply_begin(&mut self, event: PatchApplyBeginEvent) { self.add_to_history(history_cell::new_patch_event( - PatchEventType::ApplyBegin { - auto_approved: event.auto_approved, - }, event.changes, &self.config.cwd, )); @@ -736,8 +732,6 @@ impl ChatWidget { pub(crate) fn handle_exec_approval_now(&mut self, id: String, ev: ExecApprovalRequestEvent) { self.flush_answer_stream_with_separator(); - // Emit the proposed command into history (like proposed patches) - self.add_to_history(history_cell::new_proposed_command(&ev.command)); let command = shlex::try_join(ev.command.iter().map(String::as_str)) .unwrap_or_else(|_| ev.command.join(" ")); self.notify(Notification::ExecApprovalRequested { command }); @@ -757,16 +751,12 @@ impl ChatWidget { ev: ApplyPatchApprovalRequestEvent, ) { self.flush_answer_stream_with_separator(); - self.add_to_history(history_cell::new_patch_event( - PatchEventType::ApprovalRequest, - ev.changes.clone(), - &self.config.cwd, - )); let request = ApprovalRequest::ApplyPatch { id, reason: ev.reason, - grant_root: ev.grant_root, + changes: ev.changes.clone(), + cwd: self.config.cwd.clone(), }; self.bottom_pane.push_approval_request(request); self.request_redraw(); @@ -1631,7 +1621,7 @@ impl ChatWidget { } self.bottom_pane.show_selection_view(SelectionViewParams { - title: "Select model and reasoning level".to_string(), + title: Some("Select model and reasoning level".to_string()), subtitle: Some( "Switch between OpenAI models for this and future Codex CLI session".to_string(), ), @@ -1677,7 +1667,7 @@ impl ChatWidget { } self.bottom_pane.show_selection_view(SelectionViewParams { - title: "Select Approval Mode".to_string(), + title: Some("Select Approval Mode".to_string()), footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), items, ..Default::default() @@ -1852,7 +1842,7 @@ impl ChatWidget { }); self.bottom_pane.show_selection_view(SelectionViewParams { - title: "Select a review preset".into(), + title: Some("Select a review preset".into()), footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), items, ..Default::default() @@ -1888,7 +1878,7 @@ impl ChatWidget { } self.bottom_pane.show_selection_view(SelectionViewParams { - title: "Select a base branch".to_string(), + title: Some("Select a base branch".to_string()), footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), items, is_searchable: true, @@ -1929,7 +1919,7 @@ impl ChatWidget { } self.bottom_pane.show_selection_view(SelectionViewParams { - title: "Select a commit to review".to_string(), + title: Some("Select a commit to review".to_string()), footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), items, is_searchable: true, @@ -2154,7 +2144,7 @@ pub(crate) fn show_review_commit_picker_with_entries( } chat.bottom_pane.show_selection_view(SelectionViewParams { - title: "Select a commit to review".to_string(), + title: Some("Select a commit to review".to_string()), footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), items, is_searchable: true, diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__apply_patch_manual_flow_history_approved.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__apply_patch_manual_flow_history_approved.snap index 3ed1e07507..6e22bcebaa 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__apply_patch_manual_flow_history_approved.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__apply_patch_manual_flow_history_approved.snap @@ -2,4 +2,5 @@ source: tui/src/chatwidget/tests.rs expression: lines_to_single_string(&approved_lines) --- -• Change Approved foo.txt (+1 -0) +• Added foo.txt (+1 -0) + 1 +hello diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__apply_patch_manual_flow_history_proposed.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__apply_patch_manual_flow_history_proposed.snap deleted file mode 100644 index 2d0c73ca0f..0000000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__apply_patch_manual_flow_history_proposed.snap +++ /dev/null @@ -1,6 +0,0 @@ ---- -source: tui/src/chatwidget/tests.rs -expression: lines_to_single_string(&proposed_lines) ---- -• Proposed Change foo.txt (+1 -0) - 1 +hello diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec.snap index 304adf547e..10ded3d33f 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec.snap @@ -1,18 +1,16 @@ --- source: tui/src/chatwidget/tests.rs -expression: terminal.backend() +expression: terminal.backend().vt100().screen().contents() --- -" " -"▌ this is a test reason such as one that would be produced by the model " -"▌ " -"▌ Command: echo hello world " -"▌ " -"▌ Allow command? " -"▌ " -"▌ > 1. Approve and run now (Y) Run this command one time " -"▌ 2. Always approve this session (A) Automatically approve this command for " -"▌ the rest of the session " -"▌ 3. Cancel (N) Do not run the command " -" " -"Press Enter to confirm or Esc to cancel " -" " + Allow command? + + this is a test reason such as one that would be produced by the model + + $ echo hello world + +› 1. Approve and run now Run this command one time + 2. Always approve this session Automatically approve this command for the + rest of the session + 3. Cancel Do not run the command + + Press Enter to confirm or Esc to cancel diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec_no_reason.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec_no_reason.snap index 239681acb0..c3e04bd158 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec_no_reason.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec_no_reason.snap @@ -3,14 +3,15 @@ source: tui/src/chatwidget/tests.rs expression: terminal.backend() --- " " -"▌ Command: echo hello world " -"▌ " -"▌ Allow command? " -"▌ " -"▌ > 1. Approve and run now (Y) Run this command one time " -"▌ 2. Always approve this session (A) Automatically approve this command for " -"▌ the rest of the session " -"▌ 3. Cancel (N) Do not run the command " " " -"Press Enter to confirm or Esc to cancel " +" Allow command? " +" " +" $ echo hello world " +" " +"› 1. Approve and run now Run this command one time " +" 2. Always approve this session Automatically approve this command for the " +" rest of the session " +" 3. Cancel Do not run the command " +" " +" Press Enter to confirm or Esc to cancel " " " diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_patch.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_patch.snap index 2ee14a57f2..fd1860caf5 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_patch.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_patch.snap @@ -3,14 +3,17 @@ source: tui/src/chatwidget/tests.rs expression: terminal.backend() --- " " -"▌ The model wants to apply changes " -"▌ " -"▌ Grant write access to /tmp for the remainder of this session. " -"▌ " -"▌ Apply changes? " -"▌ " -"▌ > 1. Approve (Y) Apply the proposed changes " -"▌ 2. Cancel (N) Do not apply the changes " " " -"Press Enter to confirm or Esc to cancel " +" Apply changes? " +" " +" README.md (+2 -0) " +" 1 +hello " +" 2 +world " +" " +" The model wants to apply changes " +" " +"› 1. Approve Apply the proposed changes " +" 2. Cancel Do not apply the changes " +" " +" Press Enter to confirm or Esc to cancel " " " diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_proposed_multiline.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_proposed_multiline.snap deleted file mode 100644 index 119965df12..0000000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_proposed_multiline.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: tui/src/chatwidget/tests.rs -expression: lines_to_single_string(&proposed_multi) ---- -• Proposed Command - └ echo line1 - echo line2 diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_proposed_short.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_proposed_short.snap deleted file mode 100644 index dfc52c0162..0000000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_proposed_short.snap +++ /dev/null @@ -1,6 +0,0 @@ ---- -source: tui/src/chatwidget/tests.rs -expression: lines_to_single_string(&proposed) ---- -• Proposed Command - └ echo hello world diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_modal_exec.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_modal_exec.snap new file mode 100644 index 0000000000..5beb5323a2 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_modal_exec.snap @@ -0,0 +1,42 @@ +--- +source: tui/src/chatwidget/tests.rs +expression: "format!(\"{buf:?}\")" +--- +Buffer { + area: Rect { x: 0, y: 0, width: 80, height: 15 }, + content: [ + " ", + " ", + " Allow command? ", + " ", + " this is a test reason such as one that would be produced by the model ", + " ", + " $ echo hello world ", + " ", + "› 1. Approve and run now Run this command one time ", + " 2. Always approve this session Automatically approve this command for the ", + " rest of the session ", + " 3. Cancel Do not run the command ", + " ", + " Press Enter to confirm or Esc to cancel ", + " ", + ], + styles: [ + x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, + x: 2, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD, + x: 16, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, + x: 2, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: ITALIC, + x: 71, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, + x: 0, y: 8, fg: Cyan, bg: Reset, underline: Reset, modifier: BOLD, + x: 34, y: 8, fg: Cyan, bg: Reset, underline: Reset, modifier: BOLD | DIM, + x: 59, y: 8, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, + x: 34, y: 9, fg: Reset, bg: Reset, underline: Reset, modifier: DIM, + x: 76, y: 9, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, + x: 34, y: 10, fg: Reset, bg: Reset, underline: Reset, modifier: DIM, + x: 53, y: 10, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, + x: 34, y: 11, fg: Reset, bg: Reset, underline: Reset, modifier: DIM, + x: 56, y: 11, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, + x: 2, y: 13, fg: Reset, bg: Reset, underline: Reset, modifier: DIM, + x: 41, y: 13, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, + ] +} diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_and_approval_modal.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_and_approval_modal.snap index e762896fd7..86d89b80f5 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_and_approval_modal.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_and_approval_modal.snap @@ -3,16 +3,17 @@ source: tui/src/chatwidget/tests.rs expression: terminal.backend() --- " " -"▌ this is a test reason such as one that would be produced by the model " -"▌ " -"▌ Command: echo 'hello world' " -"▌ " -"▌ Allow command? " -"▌ " -"▌ > 1. Approve and run now (Y) Run this command one time " -"▌ 2. Always approve this session (A) Automatically approve this command for " -"▌ the rest of the session " -"▌ 3. Cancel (N) Do not run the command " " " -"Press Enter to confirm or Esc to cancel " +" Allow command? " +" " +" this is a test reason such as one that would be produced by the model " +" " +" $ echo 'hello world' " +" " +"› 1. Approve and run now Run this command one time " +" 2. Always approve this session Automatically approve this command for the " +" rest of the session " +" 3. Cancel Do not run the command " +" " +" Press Enter to confirm or Esc to cancel " " " diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index ed43172d1e..77cde195c5 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -83,66 +83,6 @@ fn upgrade_event_payload_for_tests(mut payload: serde_json::Value) -> serde_json payload } -/* -#[test] -fn final_answer_without_newline_is_flushed_immediately() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(); - - // Set up a VT100 test terminal to capture ANSI visual output - let width: u16 = 80; - // Increased height to keep the initial banner/help lines in view even if - // the session renders an extra header line or minor layout changes occur. - let height: u16 = 2500; - let viewport = Rect::new(0, height - 1, width, 1); - let backend = ratatui::backend::TestBackend::new(width, height); - let mut terminal = crate::custom_terminal::Terminal::with_options(backend) - .expect("failed to construct terminal"); - terminal.set_viewport_area(viewport); - - // Simulate a streaming answer without any newline characters. - chat.handle_codex_event(Event { - id: "sub-a".into(), - msg: EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { - delta: "Hi! How can I help with codex-rs or anything else today?".into(), - }), - }); - - // Now simulate the final AgentMessage which should flush the pending line immediately. - chat.handle_codex_event(Event { - id: "sub-a".into(), - msg: EventMsg::AgentMessage(AgentMessageEvent { - message: "Hi! How can I help with codex-rs or anything else today?".into(), - }), - }); - - // Drain history insertions and verify the final line is present. - let cells = drain_insert_history(&mut rx); - assert!( - cells.iter().any(|lines| { - let s = lines - .iter() - .flat_map(|l| l.spans.iter()) - .map(|sp| sp.content.clone()) - .collect::(); - s.contains("codex") - }), - "expected 'codex' header to be emitted", - ); - let found_final = cells.iter().any(|lines| { - let s = lines - .iter() - .flat_map(|l| l.spans.iter()) - .map(|sp| sp.content.clone()) - .collect::(); - s.contains("Hi! How can I help with codex-rs or anything else today?") - }); - assert!( - found_final, - "expected final answer text to be flushed to history" - ); -} -*/ - #[test] fn resumed_initial_messages_render_history() { let (mut chat, mut rx, _ops) = make_chatwidget_manual(); @@ -452,15 +392,18 @@ fn exec_approval_emits_proposed_command_and_decision_history() { msg: EventMsg::ExecApprovalRequest(ev), }); - // Snapshot the Proposed Command cell emitted into history - let proposed = drain_insert_history(&mut rx) - .pop() - .expect("expected proposed command cell"); - assert_snapshot!( - "exec_approval_history_proposed_short", - lines_to_single_string(&proposed) + let proposed_cells = drain_insert_history(&mut rx); + assert!( + proposed_cells.is_empty(), + "expected approval request to render via modal without emitting history cells" ); + // The approval modal should display the command snippet for user confirmation. + let area = Rect::new(0, 0, 80, chat.desired_height(80)); + let mut buf = ratatui::buffer::Buffer::empty(area); + (&chat).render_ref(area, &mut buf); + assert_snapshot!("exec_approval_modal_exec", format!("{buf:?}")); + // Approve via keyboard and verify a concise decision history line is added chat.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); let decision = drain_insert_history(&mut rx) @@ -476,7 +419,7 @@ fn exec_approval_emits_proposed_command_and_decision_history() { fn exec_approval_decision_truncates_multiline_and_long_commands() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(); - // Multiline command: should render proposed command fully in history with prefixes + // Multiline command: modal should show full command, history records decision only let ev_multi = ExecApprovalRequestEvent { call_id: "call-multi".into(), command: vec!["bash".into(), "-lc".into(), "echo line1\necho line2".into()], @@ -489,12 +432,29 @@ fn exec_approval_decision_truncates_multiline_and_long_commands() { id: "sub-multi".into(), msg: EventMsg::ExecApprovalRequest(ev_multi), }); - let proposed_multi = drain_insert_history(&mut rx) - .pop() - .expect("expected proposed multiline command cell"); - assert_snapshot!( - "exec_approval_history_proposed_multiline", - lines_to_single_string(&proposed_multi) + let proposed_multi = drain_insert_history(&mut rx); + assert!( + proposed_multi.is_empty(), + "expected multiline approval request to render via modal without emitting history cells" + ); + + let area = Rect::new(0, 0, 80, chat.desired_height(80)); + let mut buf = ratatui::buffer::Buffer::empty(area); + (&chat).render_ref(area, &mut buf); + let mut saw_first_line = false; + for y in 0..area.height { + let mut row = String::new(); + for x in 0..area.width { + row.push(buf[(x, y)].symbol().chars().next().unwrap_or(' ')); + } + if row.contains("echo line1") { + saw_first_line = true; + break; + } + } + assert!( + saw_first_line, + "expected modal to show first line of multiline snippet" ); // Deny via keyboard; decision snippet should be single-line and elided with " ..." @@ -519,7 +479,11 @@ fn exec_approval_decision_truncates_multiline_and_long_commands() { id: "sub-long".into(), msg: EventMsg::ExecApprovalRequest(ev_long), }); - drain_insert_history(&mut rx); // proposed cell not needed for this assertion + let proposed_long = drain_insert_history(&mut rx); + assert!( + proposed_long.is_empty(), + "expected long approval request to avoid emitting history cells before decision" + ); chat.handle_key_event(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE)); let aborted_long = drain_insert_history(&mut rx) .pop() @@ -935,18 +899,21 @@ fn render_bottom_first_row(chat: &ChatWidget, width: u16) -> String { let area = Rect::new(0, 0, width, height); let mut buf = Buffer::empty(area); (chat).render_ref(area, &mut buf); - let mut row = String::new(); - // Row 0 is the top spacer for the bottom pane; row 1 contains the header line - let y = 1u16.min(height.saturating_sub(1)); - for x in 0..area.width { - let s = buf[(x, y)].symbol(); - if s.is_empty() { - row.push(' '); - } else { - row.push_str(s); + for y in 0..area.height { + let mut row = String::new(); + for x in 0..area.width { + let s = buf[(x, y)].symbol(); + if s.is_empty() { + row.push(' '); + } else { + row.push_str(s); + } + } + if !row.trim().is_empty() { + return row; } } - row + String::new() } #[test] @@ -1181,12 +1148,19 @@ fn approval_modal_exec_snapshot() { // Render to a fixed-size test terminal and snapshot. // Call desired_height first and use that exact height for rendering. let height = chat.desired_height(80); - let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(80, height)) - .expect("create terminal"); + let mut terminal = + crate::custom_terminal::Terminal::with_options(VT100Backend::new(80, height)) + .expect("create terminal"); + let viewport = Rect::new(0, 0, 80, height); + terminal.set_viewport_area(viewport); + terminal .draw(|f| f.render_widget_ref(&chat, f.area())) .expect("draw approval modal"); - assert_snapshot!("approval_modal_exec", terminal.backend()); + assert_snapshot!( + "approval_modal_exec", + terminal.backend().vt100().screen().contents() + ); } // Snapshot test: command approval modal without a reason @@ -1470,13 +1444,27 @@ fn apply_patch_events_emit_history_cells() { msg: EventMsg::ApplyPatchApprovalRequest(ev), }); let cells = drain_insert_history(&mut rx); - assert!(!cells.is_empty(), "expected pending patch cell to be sent"); - let blob = lines_to_single_string(cells.last().unwrap()); assert!( - blob.contains("Proposed Change"), - "missing proposed change header: {blob:?}" + cells.is_empty(), + "expected approval request to surface via modal without emitting history cells" ); + let area = Rect::new(0, 0, 80, chat.desired_height(80)); + let mut buf = ratatui::buffer::Buffer::empty(area); + (&chat).render_ref(area, &mut buf); + let mut saw_summary = false; + for y in 0..area.height { + let mut row = String::new(); + for x in 0..area.width { + row.push(buf[(x, y)].symbol().chars().next().unwrap_or(' ')); + } + if row.contains("foo.txt (+1 -0)") { + saw_summary = true; + break; + } + } + assert!(saw_summary, "expected approval modal to show diff summary"); + // 2) Begin apply -> per-file apply block cell (no global header) let mut changes2 = HashMap::new(); changes2.insert( @@ -1562,8 +1550,8 @@ fn apply_patch_manual_approval_adjusts_header() { assert!(!cells.is_empty(), "expected apply block cell to be sent"); let blob = lines_to_single_string(cells.last().unwrap()); assert!( - blob.contains("Change Approved foo.txt"), - "expected change approved summary: {blob:?}" + blob.contains("Added foo.txt") || blob.contains("Edited foo.txt"), + "expected apply summary header for foo.txt: {blob:?}" ); } @@ -1587,9 +1575,11 @@ fn apply_patch_manual_flow_snapshot() { grant_root: None, }), }); - let proposed_lines = drain_insert_history(&mut rx) - .pop() - .expect("proposed patch cell"); + let history_before_apply = drain_insert_history(&mut rx); + assert!( + history_before_apply.is_empty(), + "expected approval modal to defer history emission" + ); let mut apply_changes = HashMap::new(); apply_changes.insert( @@ -1610,10 +1600,6 @@ fn apply_patch_manual_flow_snapshot() { .pop() .expect("approved patch cell"); - assert_snapshot!( - "apply_patch_manual_flow_history_proposed", - lines_to_single_string(&proposed_lines) - ); assert_snapshot!( "apply_patch_manual_flow_history_approved", lines_to_single_string(&approved_lines) @@ -1803,24 +1789,42 @@ fn apply_patch_request_shows_diff_summary() { }), }); - // Drain history insertions and verify the diff summary is present + // No history entries yet; the modal should contain the diff summary let cells = drain_insert_history(&mut rx); assert!( - !cells.is_empty(), - "expected a history cell with the proposed patch summary" - ); - let blob = lines_to_single_string(cells.last().unwrap()); - - // Header should summarize totals - assert!( - blob.contains("Proposed Change README.md (+2 -0)"), - "missing or incorrect diff header: {blob:?}" + cells.is_empty(), + "expected approval request to render via modal instead of history" ); - // Per-file summary line should include the file path and counts + let area = Rect::new(0, 0, 80, chat.desired_height(80)); + let mut buf = ratatui::buffer::Buffer::empty(area); + (&chat).render_ref(area, &mut buf); + + let mut saw_header = false; + let mut saw_line1 = false; + let mut saw_line2 = false; + for y in 0..area.height { + let mut row = String::new(); + for x in 0..area.width { + row.push(buf[(x, y)].symbol().chars().next().unwrap_or(' ')); + } + if row.contains("README.md (+2 -0)") { + saw_header = true; + } + if row.contains("+line one") { + saw_line1 = true; + } + if row.contains("+line two") { + saw_line2 = true; + } + if saw_header && saw_line1 && saw_line2 { + break; + } + } + assert!(saw_header, "expected modal to show diff header with totals"); assert!( - blob.contains("README.md"), - "missing per-file diff summary: {blob:?}" + saw_line1 && saw_line2, + "expected modal to show per-line diff summary" ); } diff --git a/codex-rs/tui/src/diff_render.rs b/codex-rs/tui/src/diff_render.rs index 1e0c222bbd..033fd09240 100644 --- a/codex-rs/tui/src/diff_render.rs +++ b/codex-rs/tui/src/diff_render.rs @@ -1,16 +1,20 @@ use diffy::Hunk; +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; use ratatui::style::Color; use ratatui::style::Modifier; use ratatui::style::Style; use ratatui::style::Stylize; use ratatui::text::Line as RtLine; use ratatui::text::Span as RtSpan; +use ratatui::widgets::Paragraph; use std::collections::HashMap; use std::path::Path; use std::path::PathBuf; use crate::exec_command::relativize_to_home; -use crate::history_cell::PatchEventType; +use crate::render::renderable::ColumnRenderable; +use crate::render::renderable::Renderable; use codex_core::git_info::get_git_repo_root; use codex_core::protocol::FileChange; @@ -23,24 +27,57 @@ enum DiffLineType { Context, } +pub struct DiffSummary { + changes: HashMap, + cwd: PathBuf, +} + +impl DiffSummary { + pub fn new(changes: HashMap, cwd: PathBuf) -> Self { + Self { changes, cwd } + } +} + +impl Renderable for FileChange { + fn render(&self, area: Rect, buf: &mut Buffer) { + let mut lines = vec![]; + render_change(self, &mut lines, area.width as usize); + Paragraph::new(lines).render(area, buf); + } + + fn desired_height(&self, width: u16) -> u16 { + let mut lines = vec![]; + render_change(self, &mut lines, width as usize); + lines.len() as u16 + } +} + +impl From for Box { + fn from(val: DiffSummary) -> Self { + let mut rows: Vec> = vec![]; + + for (i, row) in collect_rows(&val.changes).into_iter().enumerate() { + if i > 0 { + rows.push(Box::new(RtLine::from(""))); + } + let mut path = RtLine::from(display_path_for(&row.path, &val.cwd)); + path.push_span(" "); + path.extend(render_line_count_summary(row.added, row.removed)); + rows.push(Box::new(path)); + rows.push(Box::new(row.change)); + } + + Box::new(ColumnRenderable::new(rows)) + } +} + pub(crate) fn create_diff_summary( changes: &HashMap, - event_type: PatchEventType, cwd: &Path, wrap_cols: usize, ) -> Vec> { let rows = collect_rows(changes); - let header_kind = match event_type { - PatchEventType::ApplyBegin { auto_approved } => { - if auto_approved { - HeaderKind::Edited - } else { - HeaderKind::ChangeApproved - } - } - PatchEventType::ApprovalRequest => HeaderKind::ProposedChange, - }; - render_changes_block(rows, wrap_cols, header_kind, cwd) + render_changes_block(rows, wrap_cols, cwd) } // Shared row for per-file presentation @@ -81,30 +118,18 @@ fn collect_rows(changes: &HashMap) -> Vec { rows } -enum HeaderKind { - ProposedChange, - Edited, - ChangeApproved, +fn render_line_count_summary(added: usize, removed: usize) -> Vec> { + let mut spans = Vec::new(); + spans.push("(".into()); + spans.push(format!("+{added}").green()); + spans.push(" ".into()); + spans.push(format!("-{removed}").red()); + spans.push(")".into()); + spans } -fn render_changes_block( - rows: Vec, - wrap_cols: usize, - header_kind: HeaderKind, - cwd: &Path, -) -> Vec> { +fn render_changes_block(rows: Vec, wrap_cols: usize, cwd: &Path) -> Vec> { let mut out: Vec> = Vec::new(); - let term_cols = wrap_cols; - - fn render_line_count_summary(added: usize, removed: usize) -> Vec> { - let mut spans = Vec::new(); - spans.push("(".into()); - spans.push(format!("+{added}").green()); - spans.push(" ".into()); - spans.push(format!("-{removed}").red()); - spans.push(")".into()); - spans - } let render_path = |row: &Row| -> Vec> { let mut spans = Vec::new(); @@ -121,66 +146,31 @@ fn render_changes_block( let file_count = rows.len(); let noun = if file_count == 1 { "file" } else { "files" }; let mut header_spans: Vec> = vec!["• ".into()]; - match header_kind { - HeaderKind::ProposedChange => { - header_spans.push("Proposed Change".bold()); - if let [row] = &rows[..] { - header_spans.push(" ".into()); - header_spans.extend(render_path(row)); - header_spans.push(" ".into()); - header_spans.extend(render_line_count_summary(row.added, row.removed)); - } else { - header_spans.push(format!(" to {file_count} {noun} ").into()); - header_spans.extend(render_line_count_summary(total_added, total_removed)); - } - } - HeaderKind::Edited => { - if let [row] = &rows[..] { - let verb = match &row.change { - FileChange::Add { .. } => "Added", - FileChange::Delete { .. } => "Deleted", - _ => "Edited", - }; - header_spans.push(verb.bold()); - header_spans.push(" ".into()); - header_spans.extend(render_path(row)); - header_spans.push(" ".into()); - header_spans.extend(render_line_count_summary(row.added, row.removed)); - } else { - header_spans.push("Edited".bold()); - header_spans.push(format!(" {file_count} {noun} ").into()); - header_spans.extend(render_line_count_summary(total_added, total_removed)); - } - } - HeaderKind::ChangeApproved => { - header_spans.push("Change Approved".bold()); - if let [row] = &rows[..] { - header_spans.push(" ".into()); - header_spans.extend(render_path(row)); - header_spans.push(" ".into()); - header_spans.extend(render_line_count_summary(row.added, row.removed)); - } else { - header_spans.push(format!(" {file_count} {noun} ").into()); - header_spans.extend(render_line_count_summary(total_added, total_removed)); - } - } + if let [row] = &rows[..] { + let verb = match &row.change { + FileChange::Add { .. } => "Added", + FileChange::Delete { .. } => "Deleted", + _ => "Edited", + }; + header_spans.push(verb.bold()); + header_spans.push(" ".into()); + header_spans.extend(render_path(row)); + header_spans.push(" ".into()); + header_spans.extend(render_line_count_summary(row.added, row.removed)); + } else { + header_spans.push("Edited".bold()); + header_spans.push(format!(" {file_count} {noun} ").into()); + header_spans.extend(render_line_count_summary(total_added, total_removed)); } out.push(RtLine::from(header_spans)); - // For Change Approved, we only show the header summary and no per-file/diff details. - if matches!(header_kind, HeaderKind::ChangeApproved) { - return out; - } - for (idx, r) in rows.into_iter().enumerate() { // Insert a blank separator between file chunks (except before the first) if idx > 0 { out.push("".into()); } // File header line (skip when single-file header already shows the name) - let skip_file_header = - matches!(header_kind, HeaderKind::ProposedChange | HeaderKind::Edited) - && file_count == 1; + let skip_file_header = file_count == 1; if !skip_file_header { let mut header: Vec> = Vec::new(); header.push(" └ ".dim()); @@ -190,71 +180,77 @@ fn render_changes_block( out.push(RtLine::from(header)); } - match r.change { - FileChange::Add { content } => { - for (i, raw) in content.lines().enumerate() { - out.extend(push_wrapped_diff_line( - i + 1, - DiffLineType::Insert, - raw, - term_cols, - )); - } - } - FileChange::Delete { content } => { - for (i, raw) in content.lines().enumerate() { - out.extend(push_wrapped_diff_line( - i + 1, - DiffLineType::Delete, - raw, - term_cols, - )); - } - } - FileChange::Update { unified_diff, .. } => { - if let Ok(patch) = diffy::Patch::from_str(&unified_diff) { - let mut is_first_hunk = true; - for h in patch.hunks() { - if !is_first_hunk { - out.push(RtLine::from(vec![" ".into(), "⋮".dim()])); - } - is_first_hunk = false; + render_change(&r.change, &mut out, wrap_cols); + } - let mut old_ln = h.old_range().start(); - let mut new_ln = h.new_range().start(); - for l in h.lines() { - match l { - diffy::Line::Insert(text) => { - let s = text.trim_end_matches('\n'); - out.extend(push_wrapped_diff_line( - new_ln, - DiffLineType::Insert, - s, - term_cols, - )); - new_ln += 1; - } - diffy::Line::Delete(text) => { - let s = text.trim_end_matches('\n'); - out.extend(push_wrapped_diff_line( - old_ln, - DiffLineType::Delete, - s, - term_cols, - )); - old_ln += 1; - } - diffy::Line::Context(text) => { - let s = text.trim_end_matches('\n'); - out.extend(push_wrapped_diff_line( - new_ln, - DiffLineType::Context, - s, - term_cols, - )); - old_ln += 1; - new_ln += 1; - } + out +} + +fn render_change(change: &FileChange, out: &mut Vec>, width: usize) { + match change { + FileChange::Add { content } => { + for (i, raw) in content.lines().enumerate() { + out.extend(push_wrapped_diff_line( + i + 1, + DiffLineType::Insert, + raw, + width, + )); + } + } + FileChange::Delete { content } => { + for (i, raw) in content.lines().enumerate() { + out.extend(push_wrapped_diff_line( + i + 1, + DiffLineType::Delete, + raw, + width, + )); + } + } + FileChange::Update { unified_diff, .. } => { + if let Ok(patch) = diffy::Patch::from_str(unified_diff) { + let mut is_first_hunk = true; + for h in patch.hunks() { + if !is_first_hunk { + out.push(RtLine::from(vec![" ".into(), "⋮".dim()])); + } + is_first_hunk = false; + + let mut old_ln = h.old_range().start(); + let mut new_ln = h.new_range().start(); + for l in h.lines() { + match l { + diffy::Line::Insert(text) => { + let s = text.trim_end_matches('\n'); + out.extend(push_wrapped_diff_line( + new_ln, + DiffLineType::Insert, + s, + width, + )); + new_ln += 1; + } + diffy::Line::Delete(text) => { + let s = text.trim_end_matches('\n'); + out.extend(push_wrapped_diff_line( + old_ln, + DiffLineType::Delete, + s, + width, + )); + old_ln += 1; + } + diffy::Line::Context(text) => { + let s = text.trim_end_matches('\n'); + out.extend(push_wrapped_diff_line( + new_ln, + DiffLineType::Context, + s, + width, + )); + old_ln += 1; + new_ln += 1; } } } @@ -262,8 +258,6 @@ fn render_changes_block( } } } - - out } pub(crate) fn display_path_for(path: &Path, cwd: &Path) -> String { @@ -300,7 +294,7 @@ fn push_wrapped_diff_line( line_number: usize, kind: DiffLineType, text: &str, - term_cols: usize, + width: usize, ) -> Vec> { let indent = " "; let ln_str = line_number.to_string(); @@ -325,7 +319,7 @@ fn push_wrapped_diff_line( // Fit the content for the current terminal row: // compute how many columns are available after the prefix, then split // at a UTF-8 character boundary so this row's chunk fits exactly. - let available_content_cols = term_cols.saturating_sub(prefix_cols + 1).max(1); + let available_content_cols = width.saturating_sub(prefix_cols + 1).max(1); let split_at_byte_index = remaining_text .char_indices() .nth(available_content_cols) @@ -385,11 +379,8 @@ mod tests { use ratatui::widgets::Paragraph; use ratatui::widgets::WidgetRef; use ratatui::widgets::Wrap; - fn diff_summary_for_tests( - changes: &HashMap, - event_type: PatchEventType, - ) -> Vec> { - create_diff_summary(changes, event_type, &PathBuf::from("/"), 80) + fn diff_summary_for_tests(changes: &HashMap) -> Vec> { + create_diff_summary(changes, &PathBuf::from("/"), 80) } fn snapshot_lines(name: &str, lines: Vec>, width: u16, height: u16) { @@ -421,42 +412,6 @@ mod tests { assert_snapshot!(name, text); } - #[test] - fn ui_snapshot_add_details() { - let mut changes: HashMap = HashMap::new(); - changes.insert( - PathBuf::from("README.md"), - FileChange::Add { - content: "first line\nsecond line\n".to_string(), - }, - ); - - let lines = diff_summary_for_tests(&changes, PatchEventType::ApprovalRequest); - - snapshot_lines("add_details", lines, 80, 10); - } - - #[test] - fn ui_snapshot_update_details_with_rename() { - let mut changes: HashMap = HashMap::new(); - - let original = "line one\nline two\nline three\n"; - let modified = "line one\nline two changed\nline three\n"; - let patch = diffy::create_patch(original, modified).to_string(); - - changes.insert( - PathBuf::from("src/lib.rs"), - FileChange::Update { - unified_diff: patch, - move_path: Some(PathBuf::from("src/lib_new.rs")), - }, - ); - - let lines = diff_summary_for_tests(&changes, PatchEventType::ApprovalRequest); - - snapshot_lines("update_details_with_rename", lines, 80, 12); - } - #[test] fn ui_snapshot_wrap_behavior_insert() { // Narrow width to force wrapping within our diff line rendering @@ -469,71 +424,6 @@ mod tests { snapshot_lines("wrap_behavior_insert", lines, 90, 8); } - #[test] - fn ui_snapshot_single_line_replacement_counts() { - // Reproduce: one deleted line replaced by one inserted line, no extra context - let original = "# Codex CLI (Rust Implementation)\n"; - let modified = "# Codex CLI (Rust Implementation) banana\n"; - let patch = diffy::create_patch(original, modified).to_string(); - - let mut changes: HashMap = HashMap::new(); - changes.insert( - PathBuf::from("README.md"), - FileChange::Update { - unified_diff: patch, - move_path: None, - }, - ); - - let lines = diff_summary_for_tests(&changes, PatchEventType::ApprovalRequest); - - snapshot_lines("single_line_replacement_counts", lines, 80, 8); - } - - #[test] - fn ui_snapshot_blank_context_line() { - // Ensure a hunk that includes a blank context line at the beginning is rendered visibly - let original = "\nY\n"; - let modified = "\nY changed\n"; - let patch = diffy::create_patch(original, modified).to_string(); - - let mut changes: HashMap = HashMap::new(); - changes.insert( - PathBuf::from("example.txt"), - FileChange::Update { - unified_diff: patch, - move_path: None, - }, - ); - - let lines = diff_summary_for_tests(&changes, PatchEventType::ApprovalRequest); - - snapshot_lines("blank_context_line", lines, 80, 10); - } - - #[test] - fn ui_snapshot_vertical_ellipsis_between_hunks() { - // Create a patch with two separate hunks to ensure we render the vertical ellipsis (⋮) - let original = - "line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10\n"; - let modified = "line 1\nline two changed\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline nine changed\nline 10\n"; - let patch = diffy::create_patch(original, modified).to_string(); - - let mut changes: HashMap = HashMap::new(); - changes.insert( - PathBuf::from("example.txt"), - FileChange::Update { - unified_diff: patch, - move_path: None, - }, - ); - - let lines = diff_summary_for_tests(&changes, PatchEventType::ApprovalRequest); - - // Height is large enough to show both hunks and the separator - snapshot_lines("vertical_ellipsis_between_hunks", lines, 80, 16); - } - #[test] fn ui_snapshot_apply_update_block() { let mut changes: HashMap = HashMap::new(); @@ -549,12 +439,8 @@ mod tests { }, ); - for (name, auto_approved) in [ - ("apply_update_block", true), - ("apply_update_block_manual", false), - ] { - let lines = - diff_summary_for_tests(&changes, PatchEventType::ApplyBegin { auto_approved }); + for name in ["apply_update_block", "apply_update_block_manual"] { + let lines = diff_summary_for_tests(&changes); snapshot_lines(name, lines, 80, 12); } @@ -575,12 +461,7 @@ mod tests { }, ); - let lines = diff_summary_for_tests( - &changes, - PatchEventType::ApplyBegin { - auto_approved: true, - }, - ); + let lines = diff_summary_for_tests(&changes); snapshot_lines("apply_update_with_rename_block", lines, 80, 12); } @@ -608,12 +489,7 @@ mod tests { }, ); - let lines = diff_summary_for_tests( - &changes, - PatchEventType::ApplyBegin { - auto_approved: true, - }, - ); + let lines = diff_summary_for_tests(&changes); snapshot_lines("apply_multiple_files_block", lines, 80, 14); } @@ -628,12 +504,7 @@ mod tests { }, ); - let lines = diff_summary_for_tests( - &changes, - PatchEventType::ApplyBegin { - auto_approved: true, - }, - ); + let lines = diff_summary_for_tests(&changes); snapshot_lines("apply_add_block", lines, 80, 10); } @@ -652,12 +523,7 @@ mod tests { }, ); - let lines = diff_summary_for_tests( - &changes, - PatchEventType::ApplyBegin { - auto_approved: true, - }, - ); + let lines = diff_summary_for_tests(&changes); // Cleanup best-effort; rendering has already read the file let _ = std::fs::remove_file(&tmp_path); @@ -681,14 +547,7 @@ mod tests { }, ); - let lines = create_diff_summary( - &changes, - PatchEventType::ApplyBegin { - auto_approved: true, - }, - &PathBuf::from("/"), - 72, - ); + let lines = create_diff_summary(&changes, &PathBuf::from("/"), 72); // Render with backend width wider than wrap width to avoid Paragraph auto-wrap. snapshot_lines("apply_update_block_wraps_long_lines", lines, 80, 12); @@ -711,14 +570,7 @@ mod tests { }, ); - let mut lines = create_diff_summary( - &changes, - PatchEventType::ApplyBegin { - auto_approved: true, - }, - &PathBuf::from("/"), - 28, - ); + let mut lines = create_diff_summary(&changes, &PathBuf::from("/"), 28); // Drop the combined header for this text-only snapshot if !lines.is_empty() { lines.remove(0); @@ -745,14 +597,7 @@ mod tests { }, ); - let lines = create_diff_summary( - &changes, - PatchEventType::ApplyBegin { - auto_approved: true, - }, - &cwd, - 80, - ); + let lines = create_diff_summary(&changes, &cwd, 80); snapshot_lines("apply_update_block_relativizes_path", lines, 80, 10); } diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 6a1ac37a36..4121a98397 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -5,7 +5,6 @@ use crate::exec_cell::TOOL_CALL_MAX_LINES; use crate::exec_cell::output_lines; use crate::exec_cell::spinner; use crate::exec_command::relativize_to_home; -use crate::exec_command::strip_bash_lc_and_escape; use crate::markdown::MarkdownCitationContext; use crate::markdown::append_markdown; use crate::render::line_utils::line_to_static; @@ -50,12 +49,6 @@ use std::time::Instant; use tracing::error; use unicode_width::UnicodeWidthStr; -#[derive(Clone, Debug)] -pub(crate) enum PatchEventType { - ApprovalRequest, - ApplyBegin { auto_approved: bool }, -} - /// Represents an event to display in the conversation history. Returns its /// `Vec>` representation to make it easier to display in a /// scrollable list. @@ -277,19 +270,13 @@ pub(crate) fn new_review_status_line(message: String) -> PlainHistoryCell { #[derive(Debug)] pub(crate) struct PatchHistoryCell { - event_type: PatchEventType, changes: HashMap, cwd: PathBuf, } impl HistoryCell for PatchHistoryCell { fn display_lines(&self, width: u16) -> Vec> { - create_diff_summary( - &self.changes, - self.event_type.clone(), - &self.cwd, - width as usize, - ) + create_diff_summary(&self.changes, &self.cwd, width as usize) } } @@ -1016,12 +1003,10 @@ impl HistoryCell for PlanUpdateCell { /// a proposed patch. The summary lines should already be formatted (e.g. /// "A path/to/file.rs"). pub(crate) fn new_patch_event( - event_type: PatchEventType, changes: HashMap, cwd: &Path, ) -> PatchHistoryCell { PatchHistoryCell { - event_type, changes, cwd: cwd.to_path_buf(), } @@ -1052,27 +1037,6 @@ pub(crate) fn new_patch_apply_failure(stderr: String) -> PlainHistoryCell { PlainHistoryCell { lines } } -/// Create a new history cell for a proposed command approval. -/// Renders a header and the command preview similar to how proposed patches -/// show a header and summary. -pub(crate) fn new_proposed_command(command: &[String]) -> PlainHistoryCell { - let cmd = strip_bash_lc_and_escape(command); - - let mut lines: Vec> = Vec::new(); - lines.push(Line::from(vec!["• ".dim(), "Proposed Command".bold()])); - - let highlighted_lines = crate::render::highlight::highlight_bash_to_lines(&cmd); - let initial_prefix: Span<'static> = " └ ".dim(); - let subsequent_prefix: Span<'static> = " ".into(); - lines.extend(prefix_lines( - highlighted_lines, - initial_prefix, - subsequent_prefix, - )); - - PlainHistoryCell { lines } -} - pub(crate) fn new_reasoning_block( full_reasoning_buffer: String, config: &Config, diff --git a/codex-rs/tui/src/pager_overlay.rs b/codex-rs/tui/src/pager_overlay.rs index ec9652ce55..6a0562fe82 100644 --- a/codex-rs/tui/src/pager_overlay.rs +++ b/codex-rs/tui/src/pager_overlay.rs @@ -3,13 +3,14 @@ use std::sync::Arc; use std::time::Duration; use crate::history_cell::HistoryCell; -use crate::render::line_utils::push_owned_lines; +use crate::render::renderable::Renderable; use crate::tui; use crate::tui::TuiEvent; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use crossterm::event::KeyEventKind; use ratatui::buffer::Buffer; +use ratatui::buffer::Cell; use ratatui::layout::Rect; use ratatui::style::Color; use ratatui::style::Style; @@ -22,6 +23,7 @@ use ratatui::widgets::Clear; use ratatui::widgets::Paragraph; use ratatui::widgets::Widget; use ratatui::widgets::WidgetRef; +use ratatui::widgets::Wrap; pub(crate) enum Overlay { Transcript(TranscriptOverlay), @@ -33,10 +35,17 @@ impl Overlay { Self::Transcript(TranscriptOverlay::new(cells)) } - pub(crate) fn new_static_with_title(lines: Vec>, title: String) -> Self { + pub(crate) fn new_static_with_lines(lines: Vec>, title: String) -> Self { Self::Static(StaticOverlay::with_title(lines, title)) } + pub(crate) fn new_static_with_renderables( + renderables: Vec>, + title: String, + ) -> Self { + Self::Static(StaticOverlay::with_renderables(renderables, title)) + } + pub(crate) fn handle_event(&mut self, tui: &mut tui::Tui, event: TuiEvent) -> Result<()> { match self { Overlay::Transcript(o) => o.handle_event(tui, event), @@ -78,57 +87,53 @@ fn render_key_hints(area: Rect, buf: &mut Buffer, pairs: &[(&str, &str)]) { /// Generic widget for rendering a pager view. struct PagerView { - texts: Vec>, + renderables: Vec>, scroll_offset: usize, title: String, - wrap_cache: Option, last_content_height: Option, + last_rendered_height: Option, /// If set, on next render ensure this chunk is visible. pending_scroll_chunk: Option, } impl PagerView { - fn new(texts: Vec>, title: String, scroll_offset: usize) -> Self { + fn new(renderables: Vec>, title: String, scroll_offset: usize) -> Self { Self { - texts, + renderables, scroll_offset, title, - wrap_cache: None, last_content_height: None, + last_rendered_height: None, pending_scroll_chunk: None, } } + fn content_height(&self, width: u16) -> usize { + self.renderables + .iter() + .map(|c| c.desired_height(width) as usize) + .sum() + } + fn render(&mut self, area: Rect, buf: &mut Buffer) { Clear.render(area, buf); self.render_header(area, buf); - let content_area = self.scroll_area(area); + let content_area = self.content_area(area); self.update_last_content_height(content_area.height); - self.ensure_wrapped(content_area.width); + let content_height = self.content_height(content_area.width); + self.last_rendered_height = Some(content_height); // If there is a pending request to scroll a specific chunk into view, // satisfy it now that wrapping is up to date for this width. - if let (Some(idx), Some(cache)) = - (self.pending_scroll_chunk.take(), self.wrap_cache.as_ref()) - && let Some(range) = cache.chunk_ranges.get(idx).cloned() - { - self.ensure_range_visible(range, content_area.height as usize, cache.wrapped.len()); + if let Some(idx) = self.pending_scroll_chunk.take() { + self.ensure_chunk_visible(idx, content_area); } - // Compute page bounds without holding an immutable borrow on cache while mutating self - let wrapped_len = self - .wrap_cache - .as_ref() - .map(|c| c.wrapped.len()) - .unwrap_or(0); self.scroll_offset = self .scroll_offset - .min(wrapped_len.saturating_sub(content_area.height as usize)); - let start = self.scroll_offset; - let end = (start + content_area.height as usize).min(wrapped_len); + .min(content_height.saturating_sub(content_area.height as usize)); - let wrapped = self.cached(); - let page = &wrapped[start..end]; - self.render_content_page_prepared(content_area, buf, page); - self.render_bottom_bar(area, content_area, buf, wrapped); + self.render_content(content_area, buf); + + self.render_bottom_bar(area, content_area, buf, content_height); } fn render_header(&self, area: Rect, buf: &mut Buffer) { @@ -139,20 +144,38 @@ impl PagerView { header.dim().render_ref(area, buf); } - // Removed unused render_content_page (replaced by render_content_page_prepared) + fn render_content(&self, area: Rect, buf: &mut Buffer) { + let mut y = -(self.scroll_offset as isize); + let mut drawn_bottom = area.y; + for renderable in &self.renderables { + let top = y; + let height = renderable.desired_height(area.width) as isize; + y += height; + let bottom = y; + if bottom < area.y as isize { + continue; + } + if top > area.y as isize + area.height as isize { + break; + } + if top < 0 { + let drawn = render_offset_content(area, buf, &**renderable, (-top) as u16); + drawn_bottom = drawn_bottom.max(area.y + drawn); + } else { + let draw_height = (height as u16).min(area.height.saturating_sub(top as u16)); + let draw_area = Rect::new(area.x, area.y + top as u16, area.width, draw_height); + renderable.render(draw_area, buf); + drawn_bottom = drawn_bottom.max(draw_area.y.saturating_add(draw_area.height)); + } + } - fn render_content_page_prepared(&self, area: Rect, buf: &mut Buffer, page: &[Line<'static>]) { - Clear.render(area, buf); - Paragraph::new(page.to_vec()).render_ref(area, buf); - - let visible = page.len(); - if visible < area.height as usize { - for i in 0..(area.height as usize - visible) { - let add = ((visible + i).min(u16::MAX as usize)) as u16; - let y = area.y.saturating_add(add); - Span::from("~") - .dim() - .render_ref(Rect::new(area.x, y, 1, 1), buf); + for y in drawn_bottom..area.bottom() { + if area.width == 0 { + break; + } + buf[(area.x, y)] = Cell::from('~'); + for x in area.x + 1..area.right() { + buf[(x, y)] = Cell::from(' '); } } } @@ -162,7 +185,7 @@ impl PagerView { full_area: Rect, content_area: Rect, buf: &mut Buffer, - wrapped: &[Line<'static>], + total_len: usize, ) { let sep_y = content_area.bottom(); let sep_rect = Rect::new(full_area.x, sep_y, full_area.width, 1); @@ -170,10 +193,10 @@ impl PagerView { Span::from("─".repeat(sep_rect.width as usize)) .dim() .render_ref(sep_rect, buf); - let percent = if wrapped.is_empty() { + let percent = if total_len == 0 { 100 } else { - let max_scroll = wrapped.len().saturating_sub(content_area.height as usize); + let max_scroll = total_len.saturating_sub(content_area.height as usize); if max_scroll == 0 { 100 } else { @@ -210,7 +233,7 @@ impl PagerView { kind: KeyEventKind::Press | KeyEventKind::Repeat, .. } => { - let area = self.scroll_area(tui.terminal.viewport_area); + let area = self.content_area(tui.terminal.viewport_area); self.scroll_offset = self.scroll_offset.saturating_sub(area.height as usize); } KeyEvent { @@ -218,7 +241,7 @@ impl PagerView { kind: KeyEventKind::Press | KeyEventKind::Repeat, .. } => { - let area = self.scroll_area(tui.terminal.viewport_area); + let area = self.content_area(tui.terminal.viewport_area); self.scroll_offset = self.scroll_offset.saturating_add(area.height as usize); } KeyEvent { @@ -248,7 +271,7 @@ impl PagerView { self.last_content_height = Some(height as usize); } - fn scroll_area(&self, area: Rect) -> Rect { + fn content_area(&self, area: Rect) -> Rect { let mut area = area; area.y = area.y.saturating_add(1); area.height = area.height.saturating_sub(2); @@ -256,67 +279,24 @@ impl PagerView { } } -#[derive(Debug, Clone)] -struct WrapCache { - width: u16, - wrapped: Vec>, - /// For each input Text chunk, the inclusive-excluded range of wrapped lines produced. - chunk_ranges: Vec>, - base_len: usize, -} - impl PagerView { - fn ensure_wrapped(&mut self, width: u16) { - let width = width.max(1); - let needs = match self.wrap_cache { - Some(ref c) => c.width != width || c.base_len != self.texts.len(), - None => true, - }; - if !needs { - return; - } - let mut wrapped: Vec> = Vec::new(); - let mut chunk_ranges: Vec> = Vec::with_capacity(self.texts.len()); - for text in &self.texts { - let start = wrapped.len(); - for line in &text.lines { - let ws = crate::wrapping::word_wrap_line(line, width as usize); - push_owned_lines(&ws, &mut wrapped); - } - let end = wrapped.len(); - chunk_ranges.push(start..end); - } - self.wrap_cache = Some(WrapCache { - width, - wrapped, - chunk_ranges, - base_len: self.texts.len(), - }); - } - - fn cached(&self) -> &[Line<'static>] { - if let Some(cache) = self.wrap_cache.as_ref() { - &cache.wrapped - } else { - &[] - } - } - fn is_scrolled_to_bottom(&self) -> bool { if self.scroll_offset == usize::MAX { return true; } - let Some(cache) = &self.wrap_cache else { - return false; - }; let Some(height) = self.last_content_height else { return false; }; - if cache.wrapped.is_empty() { + if self.renderables.is_empty() { return true; } - let visible = height.min(cache.wrapped.len()); - let max_scroll = cache.wrapped.len().saturating_sub(visible); + let Some(total_height) = self.last_rendered_height else { + return false; + }; + if total_height <= height { + return true; + } + let max_scroll = total_height.saturating_sub(height); self.scroll_offset >= max_scroll } @@ -325,32 +305,57 @@ impl PagerView { self.pending_scroll_chunk = Some(chunk_index); } - fn ensure_range_visible( - &mut self, - range: std::ops::Range, - viewport_height: usize, - total_wrapped: usize, - ) { - if viewport_height == 0 || total_wrapped == 0 { + fn ensure_chunk_visible(&mut self, idx: usize, area: Rect) { + if area.height == 0 || idx >= self.renderables.len() { return; } - let first = range.start.min(total_wrapped.saturating_sub(1)); - let last = range - .end - .saturating_sub(1) - .min(total_wrapped.saturating_sub(1)); - let current_top = self.scroll_offset.min(total_wrapped.saturating_sub(1)); - let current_bottom = current_top.saturating_add(viewport_height.saturating_sub(1)); - + let first = self + .renderables + .iter() + .take(idx) + .map(|r| r.desired_height(area.width) as usize) + .sum(); + let last = first + self.renderables[idx].desired_height(area.width) as usize; + let current_top = self.scroll_offset; + let current_bottom = current_top.saturating_add(area.height.saturating_sub(1) as usize); if first < current_top { self.scroll_offset = first; } else if last > current_bottom { - // Scroll just enough so that 'last' is visible at the bottom - self.scroll_offset = last.saturating_sub(viewport_height.saturating_sub(1)); + self.scroll_offset = last.saturating_sub(area.height.saturating_sub(1) as usize); } } } +struct CachedParagraph { + paragraph: Paragraph<'static>, + height: std::cell::Cell>, + last_width: std::cell::Cell>, +} + +impl CachedParagraph { + fn new(paragraph: Paragraph<'static>) -> Self { + Self { + paragraph, + height: std::cell::Cell::new(None), + last_width: std::cell::Cell::new(None), + } + } +} + +impl Renderable for CachedParagraph { + fn render(&self, area: Rect, buf: &mut Buffer) { + self.paragraph.render_ref(area, buf); + } + fn desired_height(&self, width: u16) -> u16 { + if self.last_width.get() != Some(width) { + let height = self.paragraph.line_count(width) as u16; + self.height.set(Some(height)); + self.last_width.set(Some(width)); + } + self.height.get().unwrap_or(0) + } +} + pub(crate) struct TranscriptOverlay { view: PagerView, cells: Vec>, @@ -375,8 +380,8 @@ impl TranscriptOverlay { fn render_cells_to_texts( cells: &[Arc], highlight_cell: Option, - ) -> Vec> { - let mut texts: Vec> = Vec::new(); + ) -> Vec> { + let mut texts: Vec> = Vec::new(); let mut first = true; for (idx, cell) in cells.iter().enumerate() { let mut lines: Vec> = Vec::new(); @@ -392,7 +397,9 @@ impl TranscriptOverlay { cell.transcript_lines() }; lines.extend(cell_lines); - texts.push(Text::from(lines)); + texts.push(Box::new(CachedParagraph::new( + Paragraph::new(Text::from(lines)).wrap(Wrap { trim: false }), + ))); first = false; } texts @@ -406,9 +413,10 @@ impl TranscriptOverlay { lines.push(Line::from("")); } lines.extend(cell.transcript_lines()); - self.view.texts.push(Text::from(lines)); + self.view.renderables.push(Box::new(CachedParagraph::new( + Paragraph::new(Text::from(lines)).wrap(Wrap { trim: false }), + ))); self.cells.push(cell); - self.view.wrap_cache = None; if follow_bottom { self.view.scroll_offset = usize::MAX; } @@ -416,8 +424,7 @@ impl TranscriptOverlay { pub(crate) fn set_highlight_cell(&mut self, cell: Option) { self.highlight_cell = cell; - self.view.wrap_cache = None; - self.view.texts = Self::render_cells_to_texts(&self.cells, self.highlight_cell); + self.view.renderables = Self::render_cells_to_texts(&self.cells, self.highlight_cell); if let Some(idx) = self.highlight_cell { self.view.scroll_chunk_into_view(idx); } @@ -490,8 +497,17 @@ pub(crate) struct StaticOverlay { impl StaticOverlay { pub(crate) fn with_title(lines: Vec>, title: String) -> Self { + Self::with_renderables( + vec![Box::new(CachedParagraph::new(Paragraph::new(Text::from( + lines, + ))))], + title, + ) + } + + pub(crate) fn with_renderables(renderables: Vec>, title: String) -> Self { Self { - view: PagerView::new(vec![Text::from(lines)], title, 0), + view: PagerView::new(renderables, title, 0), is_done: false, } } @@ -547,6 +563,33 @@ impl StaticOverlay { } } +fn render_offset_content( + area: Rect, + buf: &mut Buffer, + renderable: &dyn Renderable, + scroll_offset: u16, +) -> u16 { + let height = renderable.desired_height(area.width); + let mut tall_buf = Buffer::empty(Rect::new( + 0, + 0, + area.width, + height.min(area.height + scroll_offset), + )); + renderable.render(*tall_buf.area(), &mut tall_buf); + let copy_height = area + .height + .min(tall_buf.area().height.saturating_sub(scroll_offset)); + for y in 0..copy_height { + let src_y = y + scroll_offset; + for x in 0..area.width { + buf[(area.x + x, area.y + y)] = tall_buf[(x, src_y)].clone(); + } + } + + copy_height +} + #[cfg(test)] mod tests { use super::*; @@ -558,12 +601,12 @@ mod tests { use crate::exec_cell::CommandOutput; use crate::history_cell::HistoryCell; - use crate::history_cell::PatchEventType; use crate::history_cell::new_patch_event; use codex_core::protocol::FileChange; use codex_protocol::parse_command::ParsedCommand; use ratatui::Terminal; use ratatui::backend::TestBackend; + use ratatui::text::Text; #[derive(Debug)] struct TestCell { @@ -580,6 +623,15 @@ mod tests { } } + fn paragraph_block(label: &str, lines: usize) -> Box { + let text = Text::from( + (0..lines) + .map(|i| Line::from(format!("{label}{i}"))) + .collect::>(), + ); + Box::new(Paragraph::new(text)) as Box + } + #[test] fn edit_prev_hint_is_visible() { let mut overlay = TranscriptOverlay::new(vec![Arc::new(TestCell { @@ -657,11 +709,7 @@ mod tests { content: "hello\nworld\n".to_string(), }, ); - let approval_cell: Arc = Arc::new(new_patch_event( - PatchEventType::ApprovalRequest, - approval_changes, - &cwd, - )); + let approval_cell: Arc = Arc::new(new_patch_event(approval_changes, &cwd)); cells.push(approval_cell); let mut apply_changes = HashMap::new(); @@ -671,13 +719,7 @@ mod tests { content: "hello\nworld\n".to_string(), }, ); - let apply_begin_cell: Arc = Arc::new(new_patch_event( - PatchEventType::ApplyBegin { - auto_approved: false, - }, - apply_changes, - &cwd, - )); + let apply_begin_cell: Arc = Arc::new(new_patch_event(apply_changes, &cwd)); cells.push(apply_begin_cell); let apply_end_cell: Arc = @@ -711,7 +753,6 @@ mod tests { overlay.render(area, &mut buf); overlay.view.scroll_offset = 0; - overlay.view.wrap_cache = None; overlay.render(area, &mut buf); let snapshot = buffer_to_text(&buf, area); @@ -783,54 +824,89 @@ mod tests { } #[test] - fn pager_wrap_cache_reuses_for_same_width_and_rebuilds_on_change() { - let long = "This is a long line that should wrap multiple times to ensure non-empty wrapped output."; - let mut pv = PagerView::new( - vec![Text::from(vec![long.into()]), Text::from(vec![long.into()])], + fn pager_view_content_height_counts_renderables() { + let pv = PagerView::new( + vec![paragraph_block("a", 2), paragraph_block("b", 3)], "T".to_string(), 0, ); - // Build cache at width 24 - pv.ensure_wrapped(24); - let w1 = pv.cached(); - assert!(!w1.is_empty(), "expected wrapped output to be non-empty"); - let ptr1 = w1.as_ptr(); + assert_eq!(pv.content_height(80), 5); + } - // Re-run with same width: cache should be reused (pointer stability heuristic) - pv.ensure_wrapped(24); - let w2 = pv.cached(); - let ptr2 = w2.as_ptr(); - assert_eq!(ptr1, ptr2, "cache should not rebuild for unchanged width"); + #[test] + fn pager_view_ensure_chunk_visible_scrolls_down_when_needed() { + let mut pv = PagerView::new( + vec![ + paragraph_block("a", 1), + paragraph_block("b", 3), + paragraph_block("c", 3), + ], + "T".to_string(), + 0, + ); + let area = Rect::new(0, 0, 20, 8); - // Change width: cache should rebuild and likely produce different length - // Drop immutable borrow before mutating - let prev_len = w2.len(); - pv.ensure_wrapped(36); - let w3 = pv.cached(); - assert_ne!( - prev_len, - w3.len(), - "wrapped length should change on width change" + pv.scroll_offset = 0; + let content_area = pv.content_area(area); + pv.ensure_chunk_visible(2, content_area); + + let mut buf = Buffer::empty(area); + pv.render(area, &mut buf); + let rendered = buffer_to_text(&buf, area); + + assert!( + rendered.contains("c0"), + "expected chunk top in view: {rendered:?}" + ); + assert!( + rendered.contains("c1"), + "expected chunk middle in view: {rendered:?}" + ); + assert!( + rendered.contains("c2"), + "expected chunk bottom in view: {rendered:?}" ); } #[test] - fn pager_wrap_cache_invalidates_on_append() { - let long = "Another long line for wrapping behavior verification."; - let mut pv = PagerView::new(vec![Text::from(vec![long.into()])], "T".to_string(), 0); - pv.ensure_wrapped(28); - let w1 = pv.cached(); - let len1 = w1.len(); + fn pager_view_ensure_chunk_visible_scrolls_up_when_needed() { + let mut pv = PagerView::new( + vec![ + paragraph_block("a", 2), + paragraph_block("b", 3), + paragraph_block("c", 3), + ], + "T".to_string(), + 0, + ); + let area = Rect::new(0, 0, 20, 3); + + pv.scroll_offset = 6; + pv.ensure_chunk_visible(0, area); + + assert_eq!(pv.scroll_offset, 0); + } + + #[test] + fn pager_view_is_scrolled_to_bottom_accounts_for_wrapped_height() { + let mut pv = PagerView::new(vec![paragraph_block("a", 10)], "T".to_string(), 0); + let area = Rect::new(0, 0, 20, 8); + let mut buf = Buffer::empty(area); + + pv.render(area, &mut buf); - // Append new lines should cause ensure_wrapped to rebuild due to len change - pv.texts.push(Text::from(vec![long.into()])); - pv.texts.push(Text::from(vec![long.into()])); - pv.ensure_wrapped(28); - let w2 = pv.cached(); assert!( - w2.len() >= len1, - "wrapped length should grow or stay same after append" + !pv.is_scrolled_to_bottom(), + "expected view to report not at bottom when offset < max" + ); + + pv.scroll_offset = usize::MAX; + pv.render(area, &mut buf); + + assert!( + pv.is_scrolled_to_bottom(), + "expected view to report at bottom after scrolling to end" ); } } diff --git a/codex-rs/tui/src/render/mod.rs b/codex-rs/tui/src/render/mod.rs index e457423f4e..441c1d6b21 100644 --- a/codex-rs/tui/src/render/mod.rs +++ b/codex-rs/tui/src/render/mod.rs @@ -1,2 +1,47 @@ +use ratatui::layout::Rect; + pub mod highlight; pub mod line_utils; +pub mod renderable; + +pub struct Insets { + pub left: u16, + pub top: u16, + pub right: u16, + pub bottom: u16, +} + +impl Insets { + pub fn tlbr(top: u16, left: u16, bottom: u16, right: u16) -> Self { + Self { + top, + left, + bottom, + right, + } + } + + pub fn vh(v: u16, h: u16) -> Self { + Self { + top: v, + left: h, + bottom: v, + right: h, + } + } +} + +pub trait RectExt { + fn inset(&self, insets: Insets) -> Rect; +} + +impl RectExt for Rect { + fn inset(&self, insets: Insets) -> Rect { + Rect { + x: self.x + insets.left, + y: self.y + insets.top, + width: self.width - insets.left - insets.right, + height: self.height - insets.top - insets.bottom, + } + } +} diff --git a/codex-rs/tui/src/render/renderable.rs b/codex-rs/tui/src/render/renderable.rs new file mode 100644 index 0000000000..868d07264b --- /dev/null +++ b/codex-rs/tui/src/render/renderable.rs @@ -0,0 +1,102 @@ +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; +use ratatui::text::Line; +use ratatui::widgets::Paragraph; +use ratatui::widgets::WidgetRef; + +pub trait Renderable { + fn render(&self, area: Rect, buf: &mut Buffer); + fn desired_height(&self, width: u16) -> u16; +} + +impl Renderable for () { + fn render(&self, _area: Rect, _buf: &mut Buffer) {} + fn desired_height(&self, _width: u16) -> u16 { + 0 + } +} + +impl Renderable for &str { + fn render(&self, area: Rect, buf: &mut Buffer) { + self.render_ref(area, buf); + } + fn desired_height(&self, _width: u16) -> u16 { + 1 + } +} + +impl Renderable for String { + fn render(&self, area: Rect, buf: &mut Buffer) { + self.render_ref(area, buf); + } + fn desired_height(&self, _width: u16) -> u16 { + 1 + } +} + +impl<'a> Renderable for Line<'a> { + fn render(&self, area: Rect, buf: &mut Buffer) { + WidgetRef::render_ref(self, area, buf); + } + fn desired_height(&self, _width: u16) -> u16 { + 1 + } +} + +impl<'a> Renderable for Paragraph<'a> { + fn render(&self, area: Rect, buf: &mut Buffer) { + self.render_ref(area, buf); + } + fn desired_height(&self, width: u16) -> u16 { + self.line_count(width) as u16 + } +} + +impl Renderable for Option { + fn render(&self, area: Rect, buf: &mut Buffer) { + if let Some(renderable) = self { + renderable.render(area, buf); + } + } + + fn desired_height(&self, width: u16) -> u16 { + if let Some(renderable) = self { + renderable.desired_height(width) + } else { + 0 + } + } +} + +pub struct ColumnRenderable { + children: Vec>, +} + +impl Renderable for ColumnRenderable { + fn render(&self, area: Rect, buf: &mut Buffer) { + let mut y = area.y; + for child in &self.children { + let child_area = Rect::new(area.x, y, area.width, child.desired_height(area.width)) + .intersection(area); + if !child_area.is_empty() { + child.render(child_area, buf); + } + y += child_area.height; + } + } + + fn desired_height(&self, width: u16) -> u16 { + self.children + .iter() + .map(|child| child.desired_height(width)) + .sum() + } +} + +impl ColumnRenderable { + pub fn new(children: impl IntoIterator>) -> Self { + Self { + children: children.into_iter().collect(), + } + } +} diff --git a/codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__apply_update_block_manual.snap b/codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__apply_update_block_manual.snap index 12c10ca460..d188b2fd6f 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__apply_update_block_manual.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__apply_update_block_manual.snap @@ -2,11 +2,11 @@ source: tui/src/diff_render.rs expression: terminal.backend() --- -"• Change Approved example.txt (+1 -1) " -" " -" " -" " -" " +"• Edited example.txt (+1 -1) " +" 1 line one " +" 2 -line two " +" 2 +line two changed " +" 3 line three " " " " " " " diff --git a/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_apply_patch_scroll_vt100.snap b/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_apply_patch_scroll_vt100.snap index 725f210c8d..df5f17adc7 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_apply_patch_scroll_vt100.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_apply_patch_scroll_vt100.snap @@ -1,16 +1,15 @@ --- source: tui/src/pager_overlay.rs -assertion_line: 721 expression: snapshot --- / T R A N S C R I P T / / / / / / / / / / / / / / / / / / / / / / / / / / / / / -• Proposed Change foo.txt (+2 -0) +• Added foo.txt (+2 -0) 1 +hello 2 +world -• Change Approved foo.txt (+2 -0) - -✓ Patch applied +• Added foo.txt (+2 -0) + 1 +hello + 2 +world ─────────────────────────────────────────────────────────────────────────── 0% ─ ↑/↓ scroll PgUp/PgDn page Home/End jump q quit Esc edit prev diff --git a/codex-rs/tui/src/status_indicator_widget.rs b/codex-rs/tui/src/status_indicator_widget.rs index b6fa2fd530..afb7952069 100644 --- a/codex-rs/tui/src/status_indicator_widget.rs +++ b/codex-rs/tui/src/status_indicator_widget.rs @@ -17,7 +17,6 @@ use crate::app_event_sender::AppEventSender; use crate::key_hint; use crate::shimmer::shimmer_spans; use crate::tui::FrameRequester; -use crate::ui_consts::LIVE_PREFIX_COLS; pub(crate) struct StatusIndicatorWidget { /// Animated header text (defaults to "Working"). @@ -160,7 +159,7 @@ impl WidgetRef for StatusIndicatorWidget { let pretty_elapsed = fmt_elapsed_compact(elapsed); // Plain rendering: no borders or padding so the live cell is visually indistinguishable from terminal scrollback. - let mut spans = vec![" ".repeat(LIVE_PREFIX_COLS as usize).into()]; + let mut spans = vec![" ".into()]; spans.extend(shimmer_spans(&self.header)); spans.extend(vec![ " ".into(), From 6f97ec4990610fc6a281b25374911c57ab053c92 Mon Sep 17 00:00:00 2001 From: iceweasel-oai Date: Wed, 1 Oct 2025 14:33:19 -0700 Subject: [PATCH 07/20] canonicalize display of Agents.md paths on Windows. (#4577) Canonicalize path on Windows to - remove unattractive path prefixes such as `\\?\` - simplify it (`../AGENTS.md` vs `C:\Users\iceweasel\code\coded\Agents.md`) before: Screenshot 2025-10-01 123520 after: Screenshot 2025-10-01 123612 --- codex-rs/Cargo.lock | 10 +++++++++- codex-rs/Cargo.toml | 1 + codex-rs/core/Cargo.toml | 1 + codex-rs/core/src/project_doc.rs | 3 ++- codex-rs/tui/Cargo.toml | 1 + codex-rs/tui/src/status/helpers.rs | 10 +++++++--- 6 files changed, 21 insertions(+), 5 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 198c986d87..53451bb2b1 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -863,6 +863,7 @@ dependencies = [ "codex-rmcp-client", "core_test_support", "dirs", + "dunce", "env-flags", "escargot", "eventsource-stream", @@ -1200,6 +1201,7 @@ dependencies = [ "crossterm", "diffy", "dirs", + "dunce", "image", "insta", "itertools 0.14.0", @@ -1798,6 +1800,12 @@ version = "0.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f678cf4a922c215c63e0de95eb1ff08a958a81d47e485cf9da1e27bf6305cfa5" +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "dupe" version = "0.9.1" @@ -4064,7 +4072,7 @@ dependencies = [ "once_cell", "socket2 0.5.10", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 01dc47a70d..06c83c819e 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -97,6 +97,7 @@ derive_more = "2" diffy = "0.4.2" dirs = "6" dotenvy = "0.15.7" +dunce = "1.0.4" env-flags = "0.1.1" env_logger = "0.11.5" escargot = "0.5" diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index 22ba1ee626..8c56e7d132 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -27,6 +27,7 @@ codex-protocol = { workspace = true } codex-app-server-protocol = { workspace = true } codex-otel = { workspace = true, features = ["otel"] } dirs = { workspace = true } +dunce = { workspace = true } env-flags = { workspace = true } eventsource-stream = { workspace = true } futures = { workspace = true } diff --git a/codex-rs/core/src/project_doc.rs b/codex-rs/core/src/project_doc.rs index 476f0e1f00..c33b1a5dac 100644 --- a/codex-rs/core/src/project_doc.rs +++ b/codex-rs/core/src/project_doc.rs @@ -14,6 +14,7 @@ //! 3. We do **not** walk past the Git root. use crate::config::Config; +use dunce::canonicalize as normalize_path; use std::path::PathBuf; use tokio::io::AsyncReadExt; use tracing::error; @@ -109,7 +110,7 @@ pub async fn read_project_docs(config: &Config) -> std::io::Result std::io::Result> { let mut dir = config.cwd.clone(); - if let Ok(canon) = dir.canonicalize() { + if let Ok(canon) = normalize_path(&dir) { dir = canon; } diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 21472d8fe9..7356ae334b 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -44,6 +44,7 @@ color-eyre = { workspace = true } crossterm = { workspace = true, features = ["bracketed-paste", "event-stream"] } diffy = { workspace = true } dirs = { workspace = true } +dunce = { workspace = true } image = { workspace = true, features = ["jpeg", "png"] } itertools = { workspace = true } lazy_static = { workspace = true } diff --git a/codex-rs/tui/src/status/helpers.rs b/codex-rs/tui/src/status/helpers.rs index 47faae27dc..1889d7f4f4 100644 --- a/codex-rs/tui/src/status/helpers.rs +++ b/codex-rs/tui/src/status/helpers.rs @@ -11,6 +11,10 @@ use unicode_width::UnicodeWidthStr; use super::account::StatusAccountDisplay; +fn normalize_agents_display_path(path: &Path) -> String { + dunce::simplified(path).display().to_string() +} + pub(crate) fn compose_model_display( config: &Config, entries: &[(&str, String)], @@ -59,13 +63,13 @@ pub(crate) fn compose_agents_summary(config: &Config) -> String { let up = format!("..{}", std::path::MAIN_SEPARATOR); format!("{}{}", up.repeat(ups), file_name) } else if let Ok(stripped) = p.strip_prefix(&config.cwd) { - stripped.display().to_string() + normalize_agents_display_path(stripped) } else { - p.display().to_string() + normalize_agents_display_path(&p) } } } else { - p.display().to_string() + normalize_agents_display_path(&p) }; rels.push(display); } From e899ae7d8a0c637d7a5d296481f3f48611acfdb0 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Wed, 1 Oct 2025 15:36:04 -0700 Subject: [PATCH 08/20] Include request ID in the error message (#4572) To help with issue debugging image --- codex-rs/core/src/chat_completions.rs | 13 +++++-- codex-rs/core/src/client.rs | 29 ++++++++++----- codex-rs/core/src/error.rs | 51 ++++++++++++++++++++++++--- 3 files changed, 79 insertions(+), 14 deletions(-) diff --git a/codex-rs/core/src/chat_completions.rs b/codex-rs/core/src/chat_completions.rs index f7194a0853..feedf3c4e5 100644 --- a/codex-rs/core/src/chat_completions.rs +++ b/codex-rs/core/src/chat_completions.rs @@ -6,6 +6,8 @@ use crate::client_common::ResponseEvent; use crate::client_common::ResponseStream; use crate::error::CodexErr; use crate::error::Result; +use crate::error::RetryLimitReachedError; +use crate::error::UnexpectedResponseError; use crate::model_family::ModelFamily; use crate::openai_tools::create_tools_json_for_chat_completions_api; use crate::util::backoff; @@ -320,11 +322,18 @@ pub(crate) async fn stream_chat_completions( let status = res.status(); if !(status == StatusCode::TOO_MANY_REQUESTS || status.is_server_error()) { let body = (res.text().await).unwrap_or_default(); - return Err(CodexErr::UnexpectedStatus(status, body)); + return Err(CodexErr::UnexpectedStatus(UnexpectedResponseError { + status, + body, + request_id: None, + })); } if attempt > max_retries { - return Err(CodexErr::RetryLimit(status)); + return Err(CodexErr::RetryLimit(RetryLimitReachedError { + status, + request_id: None, + })); } let retry_after_secs = res diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 9e0c1c0430..7cf60f56b9 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -5,6 +5,8 @@ use std::time::Duration; use crate::AuthManager; use crate::auth::CodexAuth; +use crate::error::RetryLimitReachedError; +use crate::error::UnexpectedResponseError; use bytes::Bytes; use codex_app_server_protocol::AuthMode; use codex_protocol::ConversationId; @@ -307,14 +309,17 @@ impl ModelClient { .log_request(attempt, || req_builder.send()) .await; + let mut request_id = None; if let Ok(resp) = &res { + request_id = resp + .headers() + .get("cf-ray") + .map(|v| v.to_str().unwrap_or_default().to_string()); + trace!( - "Response status: {}, cf-ray: {}", + "Response status: {}, cf-ray: {:?}", resp.status(), - resp.headers() - .get("cf-ray") - .map(|v| v.to_str().unwrap_or_default()) - .unwrap_or_default() + request_id ); } @@ -374,7 +379,11 @@ impl ModelClient { // Surface the error body to callers. Use `unwrap_or_default` per Clippy. let body = res.text().await.unwrap_or_default(); return Err(StreamAttemptError::Fatal(CodexErr::UnexpectedStatus( - status, body, + UnexpectedResponseError { + status, + body, + request_id: None, + }, ))); } @@ -405,6 +414,7 @@ impl ModelClient { Err(StreamAttemptError::RetryableHttpError { status, retry_after, + request_id, }) } Err(e) => Err(StreamAttemptError::RetryableTransportError(e.into())), @@ -448,6 +458,7 @@ enum StreamAttemptError { RetryableHttpError { status: StatusCode, retry_after: Option, + request_id: Option, }, RetryableTransportError(CodexErr), Fatal(CodexErr), @@ -472,11 +483,13 @@ impl StreamAttemptError { fn into_error(self) -> CodexErr { match self { - Self::RetryableHttpError { status, .. } => { + Self::RetryableHttpError { + status, request_id, .. + } => { if status == StatusCode::INTERNAL_SERVER_ERROR { CodexErr::InternalServerError } else { - CodexErr::RetryLimit(status) + CodexErr::RetryLimit(RetryLimitReachedError { status, request_id }) } } Self::RetryableTransportError(error) => error, diff --git a/codex-rs/core/src/error.rs b/codex-rs/core/src/error.rs index c6cc8940fa..7482c512fb 100644 --- a/codex-rs/core/src/error.rs +++ b/codex-rs/core/src/error.rs @@ -76,8 +76,8 @@ pub enum CodexErr { Interrupted, /// Unexpected HTTP status code. - #[error("unexpected status {0}: {1}")] - UnexpectedStatus(StatusCode, String), + #[error("{0}")] + UnexpectedStatus(UnexpectedResponseError), #[error("{0}")] UsageLimitReached(UsageLimitReachedError), @@ -91,8 +91,8 @@ pub enum CodexErr { InternalServerError, /// Retry limit exceeded. - #[error("exceeded retry limit, last status: {0}")] - RetryLimit(StatusCode), + #[error("{0}")] + RetryLimit(RetryLimitReachedError), /// Agent loop died unexpectedly #[error("internal error; agent loop died unexpectedly")] @@ -135,6 +135,49 @@ pub enum CodexErr { EnvVar(EnvVarError), } +#[derive(Debug)] +pub struct UnexpectedResponseError { + pub status: StatusCode, + pub body: String, + pub request_id: Option, +} + +impl std::fmt::Display for UnexpectedResponseError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "unexpected status {}: {}{}", + self.status, + self.body, + self.request_id + .as_ref() + .map(|id| format!(", request id: {id}")) + .unwrap_or_default() + ) + } +} + +impl std::error::Error for UnexpectedResponseError {} +#[derive(Debug)] +pub struct RetryLimitReachedError { + pub status: StatusCode, + pub request_id: Option, +} + +impl std::fmt::Display for RetryLimitReachedError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "exceeded retry limit, last status: {}{}", + self.status, + self.request_id + .as_ref() + .map(|id| format!(", request id: {id}")) + .unwrap_or_default() + ) + } +} + #[derive(Debug)] pub struct UsageLimitReachedError { pub(crate) plan_type: Option, From c07fb7118674ccb99abfb28fc5e3f51671d61acd Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Wed, 1 Oct 2025 17:31:13 -0700 Subject: [PATCH 09/20] Store settings on the thread instead of turn (#4579) It's much more common to keep the same settings for the entire conversation, we can add per-turn overrides later. --- sdk/typescript/README.md | 18 +++++++++++++ sdk/typescript/src/codex.ts | 9 ++++--- sdk/typescript/src/exec.ts | 2 +- sdk/typescript/src/index.ts | 2 +- sdk/typescript/src/thread.ts | 26 ++++++++++++------- .../src/{turnOptions.ts => threadOptions.ts} | 2 +- sdk/typescript/tests/codexExecSpy.ts | 3 ++- sdk/typescript/tests/run.test.ts | 26 +++++++++---------- 8 files changed, 56 insertions(+), 32 deletions(-) rename sdk/typescript/src/{turnOptions.ts => threadOptions.ts} (90%) diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md index 19accb0b30..b74fd44ba3 100644 --- a/sdk/typescript/README.md +++ b/sdk/typescript/README.md @@ -51,3 +51,21 @@ const result = await thread.run("Implement the fix"); console.log(result); ``` + +### Working directory + +By default, Codex will run in the current working directory. You can change the working directory by passing the `workingDirectory` option to the when creating a thread. + +```typescript +const thread = codex.startThread({ + workingDirectory: "/path/to/working/directory", +}); +``` + +To avoid unrecoverable errors, Codex requires the working directory to be a git repository. You can skip the git repository check by passing the `skipGitRepoCheck` option to the when creating a thread. + +```typescript +const thread = codex.startThread({ + skipGitRepoCheck: true, +}); +``` diff --git a/sdk/typescript/src/codex.ts b/sdk/typescript/src/codex.ts index 8f87122839..84376e677e 100644 --- a/sdk/typescript/src/codex.ts +++ b/sdk/typescript/src/codex.ts @@ -1,6 +1,7 @@ import { CodexOptions } from "./codexOptions"; import { CodexExec } from "./exec"; import { Thread } from "./thread"; +import { ThreadOptions } from "./threadOptions"; /** * Codex is the main class for interacting with the Codex agent. @@ -20,8 +21,8 @@ export class Codex { * Starts a new conversation with an agent. * @returns A new thread instance. */ - startThread(): Thread { - return new Thread(this.exec, this.options); + startThread(options: ThreadOptions = {}): Thread { + return new Thread(this.exec, this.options, options); } /** @@ -31,7 +32,7 @@ export class Codex { * @param id The id of the thread to resume. * @returns A new thread instance. */ - resumeThread(id: string): Thread { - return new Thread(this.exec, this.options, id); + resumeThread(id: string, options: ThreadOptions = {}): Thread { + return new Thread(this.exec, this.options, options, id); } } diff --git a/sdk/typescript/src/exec.ts b/sdk/typescript/src/exec.ts index cdb1982f0d..91ce763909 100644 --- a/sdk/typescript/src/exec.ts +++ b/sdk/typescript/src/exec.ts @@ -2,7 +2,7 @@ import { spawn } from "node:child_process"; import readline from "node:readline"; -import { SandboxMode } from "./turnOptions"; +import { SandboxMode } from "./threadOptions"; import path from "node:path"; import { fileURLToPath } from "node:url"; diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts index f2f84d153c..b759b3c68f 100644 --- a/sdk/typescript/src/index.ts +++ b/sdk/typescript/src/index.ts @@ -29,4 +29,4 @@ export { Codex } from "./codex"; export type { CodexOptions } from "./codexOptions"; -export type { TurnOptions, ApprovalMode, SandboxMode } from "./turnOptions"; +export type { ThreadOptions as TheadOptions, ApprovalMode, SandboxMode } from "./threadOptions"; diff --git a/sdk/typescript/src/thread.ts b/sdk/typescript/src/thread.ts index 7ec710217c..fe32a27136 100644 --- a/sdk/typescript/src/thread.ts +++ b/sdk/typescript/src/thread.ts @@ -2,7 +2,7 @@ import { CodexOptions } from "./codexOptions"; import { ThreadEvent } from "./events"; import { CodexExec } from "./exec"; import { ThreadItem } from "./items"; -import { TurnOptions } from "./turnOptions"; +import { ThreadOptions } from "./threadOptions"; /** Completed turn. */ export type Turn = { @@ -29,27 +29,33 @@ export class Thread { private _exec: CodexExec; private _options: CodexOptions; private _id: string | null; + private _threadOptions: ThreadOptions; /** Returns the ID of the thread. Populated after the first turn starts. */ public get id(): string | null { return this._id; } - constructor(exec: CodexExec, options: CodexOptions, id: string | null = null) { + /* @internal */ + constructor( + exec: CodexExec, + options: CodexOptions, + threadOptions: ThreadOptions, + id: string | null = null, + ) { this._exec = exec; this._options = options; this._id = id; + this._threadOptions = threadOptions; } /** Provides the input to the agent and streams events as they are produced during the turn. */ - async runStreamed(input: string, options?: TurnOptions): Promise { - return { events: this.runStreamedInternal(input, options) }; + async runStreamed(input: string): Promise { + return { events: this.runStreamedInternal(input) }; } - private async *runStreamedInternal( - input: string, - options?: TurnOptions, - ): AsyncGenerator { + private async *runStreamedInternal(input: string): AsyncGenerator { + const options = this._threadOptions; const generator = this._exec.run({ input, baseUrl: this._options.baseUrl, @@ -75,8 +81,8 @@ export class Thread { } /** Provides the input to the agent and returns the completed turn. */ - async run(input: string, options?: TurnOptions): Promise { - const generator = this.runStreamedInternal(input, options); + async run(input: string): Promise { + const generator = this.runStreamedInternal(input); const items: ThreadItem[] = []; let finalResponse: string = ""; for await (const event of generator) { diff --git a/sdk/typescript/src/turnOptions.ts b/sdk/typescript/src/threadOptions.ts similarity index 90% rename from sdk/typescript/src/turnOptions.ts rename to sdk/typescript/src/threadOptions.ts index ce56d7b2c6..7f01488d23 100644 --- a/sdk/typescript/src/turnOptions.ts +++ b/sdk/typescript/src/threadOptions.ts @@ -2,7 +2,7 @@ export type ApprovalMode = "never" | "on-request" | "on-failure" | "untrusted"; export type SandboxMode = "read-only" | "workspace-write" | "danger-full-access"; -export type TurnOptions = { +export type ThreadOptions = { model?: string; sandboxMode?: SandboxMode; workingDirectory?: string; diff --git a/sdk/typescript/tests/codexExecSpy.ts b/sdk/typescript/tests/codexExecSpy.ts index 3715f71e0b..bf7cbd6cc8 100644 --- a/sdk/typescript/tests/codexExecSpy.ts +++ b/sdk/typescript/tests/codexExecSpy.ts @@ -5,7 +5,8 @@ jest.mock("node:child_process", () => { return { ...actual, spawn: jest.fn(actual.spawn) }; }); -const actualChildProcess = jest.requireActual("node:child_process"); +const actualChildProcess = + jest.requireActual("node:child_process"); const spawnMock = child_process.spawn as jest.MockedFunction; export function codexExecSpy(): { args: string[][]; restore: () => void } { diff --git a/sdk/typescript/tests/run.test.ts b/sdk/typescript/tests/run.test.ts index 2f15237f4f..357d8cd0db 100644 --- a/sdk/typescript/tests/run.test.ts +++ b/sdk/typescript/tests/run.test.ts @@ -109,9 +109,7 @@ describe("Codex", () => { const thread = client.startThread(); await thread.run("first input"); - await thread.run("second input", { - model: "gpt-test-1", - }); + await thread.run("second input"); // Check second request continues the same thread expect(requests.length).toBeGreaterThanOrEqual(2); @@ -119,7 +117,7 @@ describe("Codex", () => { expect(secondRequest).toBeDefined(); const payload = secondRequest!.json; - expect(payload.model).toBe("gpt-test-1"); + expect(payload.input.at(-1)!.content![0]!.text).toBe("second input"); const assistantEntry = payload.input.find( (entry: { role: string }) => entry.role === "assistant", ); @@ -197,11 +195,11 @@ describe("Codex", () => { try { const client = new Codex({ codexPathOverride: codexExecPath, baseUrl: url, apiKey: "test" }); - const thread = client.startThread(); - await thread.run("apply options", { + const thread = client.startThread({ model: "gpt-test-1", sandboxMode: "workspace-write", }); + await thread.run("apply options"); const payload = requests[0]; expect(payload).toBeDefined(); @@ -240,11 +238,11 @@ describe("Codex", () => { apiKey: "test", }); - const thread = client.startThread(); - await thread.run("use custom working directory", { + const thread = client.startThread({ workingDirectory, skipGitRepoCheck: true, }); + await thread.run("use custom working directory"); const commandArgs = spawnArgs[0]; expectPair(commandArgs, ["--cd", workingDirectory]); @@ -274,12 +272,12 @@ describe("Codex", () => { apiKey: "test", }); - const thread = client.startThread(); - await expect( - thread.run("use custom working directory", { - workingDirectory, - }), - ).rejects.toThrow(/Not inside a trusted directory/); + const thread = client.startThread({ + workingDirectory, + }); + await expect(thread.run("use custom working directory")).rejects.toThrow( + /Not inside a trusted directory/, + ); } finally { await close(); } From 35c76ad47d0f6f134923026c9c80d1f2e9bbd83f Mon Sep 17 00:00:00 2001 From: Gabriel Peal Date: Wed, 1 Oct 2025 22:41:56 -0700 Subject: [PATCH 10/20] fix: update the gpt-5-codex prompt to be more explicit that it should always used fenced code blocks info tags (#4569) We get spurrious reports that the model writes fenced code blocks without an info tag which then causes auto-language detection in the extension to incorrectly highlight the code and show the wrong language. The model should really always include a tag when it can. --- codex-rs/core/gpt_5_codex_prompt.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codex-rs/core/gpt_5_codex_prompt.md b/codex-rs/core/gpt_5_codex_prompt.md index 9a298f460f..33ab98807d 100644 --- a/codex-rs/core/gpt_5_codex_prompt.md +++ b/codex-rs/core/gpt_5_codex_prompt.md @@ -89,7 +89,7 @@ You are producing plain text that will later be styled by the CLI. Follow these - Headers: optional; short Title Case (1-3 words) wrapped in **…**; no blank line before the first bullet; add only if they truly help. - Bullets: use - ; merge related points; keep to one line when possible; 4–6 per list ordered by importance; keep phrasing consistent. - Monospace: backticks for commands/paths/env vars/code ids and inline examples; use for literal keyword bullets; never combine with **. -- Code samples or multi-line snippets should be wrapped in fenced code blocks; add a language hint whenever obvious. +- Code samples or multi-line snippets should be wrapped in fenced code blocks; include an info string as often as possible. - Structure: group related bullets; order sections general → specific → supporting; for subsections, start with a bolded keyword bullet, then items; match complexity to the task. - Tone: collaborative, concise, factual; present tense, active voice; self‑contained; no "above/below"; parallel wording. - Don'ts: no nested bullets/hierarchies; no ANSI codes; don't cram unrelated keywords; keep keyword lists short—wrap/reformat if long; avoid naming formatting styles in answers. From 2f6fb37d72d552f2c7bed66be8be8502ace6d71b Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Thu, 2 Oct 2025 09:59:45 -0700 Subject: [PATCH 11/20] Support CODEX_API_KEY for codex exec (#4615) Allows to set API key per invocation of `codex exec` --- codex-rs/app-server/src/message_processor.rs | 2 +- codex-rs/cloud-tasks/src/lib.rs | 2 +- codex-rs/cloud-tasks/src/util.rs | 2 +- codex-rs/core/src/auth.rs | 44 +++++++++--- codex-rs/core/tests/common/test_codex_exec.rs | 3 +- codex-rs/exec/src/lib.rs | 10 +-- codex-rs/exec/tests/suite/auth_env.rs | 34 +++++++++ codex-rs/exec/tests/suite/mod.rs | 1 + codex-rs/exec/tests/suite/resume.rs | 72 +++++++------------ codex-rs/login/src/lib.rs | 1 + codex-rs/mcp-server/src/message_processor.rs | 2 +- codex-rs/tui/src/lib.rs | 2 +- sdk/typescript/src/exec.ts | 2 +- 13 files changed, 109 insertions(+), 68 deletions(-) create mode 100644 codex-rs/exec/tests/suite/auth_env.rs diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 1b9fcffb71..9d8db2f921 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -34,7 +34,7 @@ impl MessageProcessor { config: Arc, ) -> Self { let outgoing = Arc::new(outgoing); - let auth_manager = AuthManager::shared(config.codex_home.clone()); + let auth_manager = AuthManager::shared(config.codex_home.clone(), false); let conversation_manager = Arc::new(ConversationManager::new(auth_manager.clone())); let codex_message_processor = CodexMessageProcessor::new( auth_manager, diff --git a/codex-rs/cloud-tasks/src/lib.rs b/codex-rs/cloud-tasks/src/lib.rs index cea19b9741..da2d4eb908 100644 --- a/codex-rs/cloud-tasks/src/lib.rs +++ b/codex-rs/cloud-tasks/src/lib.rs @@ -190,7 +190,7 @@ pub async fn run_main(_cli: Cli, _codex_linux_sandbox_exe: Option) -> a // Require ChatGPT login (SWIC). Exit with a clear message if missing. let _token = match codex_core::config::find_codex_home() .ok() - .map(codex_login::AuthManager::new) + .map(|home| codex_login::AuthManager::new(home, false)) .and_then(|am| am.auth()) { Some(auth) => { diff --git a/codex-rs/cloud-tasks/src/util.rs b/codex-rs/cloud-tasks/src/util.rs index 9a610da244..8003a02f1e 100644 --- a/codex-rs/cloud-tasks/src/util.rs +++ b/codex-rs/cloud-tasks/src/util.rs @@ -70,7 +70,7 @@ pub async fn build_chatgpt_headers() -> HeaderMap { HeaderValue::from_str(&ua).unwrap_or(HeaderValue::from_static("codex-cli")), ); if let Ok(home) = codex_core::config::find_codex_home() { - let am = codex_login::AuthManager::new(home); + let am = codex_login::AuthManager::new(home, false); if let Some(auth) = am.auth() && let Ok(tok) = auth.get_token().await && !tok.is_empty() diff --git a/codex-rs/core/src/auth.rs b/codex-rs/core/src/auth.rs index b68540615a..4eea313e66 100644 --- a/codex-rs/core/src/auth.rs +++ b/codex-rs/core/src/auth.rs @@ -73,7 +73,7 @@ impl CodexAuth { /// Loads the available auth information from the auth.json. pub fn from_codex_home(codex_home: &Path) -> std::io::Result> { - load_auth(codex_home) + load_auth(codex_home, false) } pub async fn get_token_data(&self) -> Result { @@ -188,6 +188,7 @@ impl CodexAuth { } pub const OPENAI_API_KEY_ENV_VAR: &str = "OPENAI_API_KEY"; +pub const CODEX_API_KEY_ENV_VAR: &str = "CODEX_API_KEY"; pub fn read_openai_api_key_from_env() -> Option { env::var(OPENAI_API_KEY_ENV_VAR) @@ -196,6 +197,13 @@ pub fn read_openai_api_key_from_env() -> Option { .filter(|value| !value.is_empty()) } +pub fn read_codex_api_key_from_env() -> Option { + env::var(CODEX_API_KEY_ENV_VAR) + .ok() + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()) +} + pub fn get_auth_file(codex_home: &Path) -> PathBuf { codex_home.join("auth.json") } @@ -221,7 +229,18 @@ pub fn login_with_api_key(codex_home: &Path, api_key: &str) -> std::io::Result<( write_auth_json(&get_auth_file(codex_home), &auth_dot_json) } -fn load_auth(codex_home: &Path) -> std::io::Result> { +fn load_auth( + codex_home: &Path, + enable_codex_api_key_env: bool, +) -> std::io::Result> { + if enable_codex_api_key_env && let Some(api_key) = read_codex_api_key_from_env() { + let client = crate::default_client::create_client(); + return Ok(Some(CodexAuth::from_api_key_with_client( + api_key.as_str(), + client, + ))); + } + let auth_file = get_auth_file(codex_home); let client = crate::default_client::create_client(); let auth_dot_json = match try_read_auth_json(&auth_file) { @@ -455,7 +474,7 @@ mod tests { auth_dot_json, auth_file: _, .. - } = super::load_auth(codex_home.path()).unwrap().unwrap(); + } = super::load_auth(codex_home.path(), false).unwrap().unwrap(); assert_eq!(None, api_key); assert_eq!(AuthMode::ChatGPT, mode); @@ -494,7 +513,7 @@ mod tests { ) .unwrap(); - let auth = super::load_auth(dir.path()).unwrap().unwrap(); + let auth = super::load_auth(dir.path(), false).unwrap().unwrap(); assert_eq!(auth.mode, AuthMode::ApiKey); assert_eq!(auth.api_key, Some("sk-test-key".to_string())); @@ -577,6 +596,7 @@ mod tests { pub struct AuthManager { codex_home: PathBuf, inner: RwLock, + enable_codex_api_key_env: bool, } impl AuthManager { @@ -584,11 +604,14 @@ impl AuthManager { /// preferred auth method. Errors loading auth are swallowed; `auth()` will /// simply return `None` in that case so callers can treat it as an /// unauthenticated state. - pub fn new(codex_home: PathBuf) -> Self { - let auth = CodexAuth::from_codex_home(&codex_home).ok().flatten(); + pub fn new(codex_home: PathBuf, enable_codex_api_key_env: bool) -> Self { + let auth = load_auth(&codex_home, enable_codex_api_key_env) + .ok() + .flatten(); Self { codex_home, inner: RwLock::new(CachedAuth { auth }), + enable_codex_api_key_env, } } @@ -598,6 +621,7 @@ impl AuthManager { Arc::new(Self { codex_home: PathBuf::new(), inner: RwLock::new(cached), + enable_codex_api_key_env: false, }) } @@ -609,7 +633,9 @@ impl AuthManager { /// Force a reload of the auth information from auth.json. Returns /// whether the auth value changed. pub fn reload(&self) -> bool { - let new_auth = CodexAuth::from_codex_home(&self.codex_home).ok().flatten(); + let new_auth = load_auth(&self.codex_home, self.enable_codex_api_key_env) + .ok() + .flatten(); if let Ok(mut guard) = self.inner.write() { let changed = !AuthManager::auths_equal(&guard.auth, &new_auth); guard.auth = new_auth; @@ -628,8 +654,8 @@ impl AuthManager { } /// Convenience constructor returning an `Arc` wrapper. - pub fn shared(codex_home: PathBuf) -> Arc { - Arc::new(Self::new(codex_home)) + pub fn shared(codex_home: PathBuf, enable_codex_api_key_env: bool) -> Arc { + Arc::new(Self::new(codex_home, enable_codex_api_key_env)) } /// Attempt to refresh the current auth token (if any). On success, reload diff --git a/codex-rs/core/tests/common/test_codex_exec.rs b/codex-rs/core/tests/common/test_codex_exec.rs index 6a4ce32b0f..478d0c57f4 100644 --- a/codex-rs/core/tests/common/test_codex_exec.rs +++ b/codex-rs/core/tests/common/test_codex_exec.rs @@ -1,4 +1,5 @@ #![allow(clippy::expect_used)] +use codex_core::auth::CODEX_API_KEY_ENV_VAR; use std::path::Path; use tempfile::TempDir; use wiremock::MockServer; @@ -14,7 +15,7 @@ impl TestCodexExecBuilder { .expect("should find binary for codex-exec"); cmd.current_dir(self.cwd.path()) .env("CODEX_HOME", self.home.path()) - .env("OPENAI_API_KEY", "dummy"); + .env(CODEX_API_KEY_ENV_VAR, "dummy"); cmd } pub fn cmd_with_server(&self, server: &MockServer) -> assert_cmd::Command { diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index d77f968593..0ec905de15 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -236,8 +236,8 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any std::process::exit(1); } - let conversation_manager = - ConversationManager::new(AuthManager::shared(config.codex_home.clone())); + let auth_manager = AuthManager::shared(config.codex_home.clone(), true); + let conversation_manager = ConversationManager::new(auth_manager.clone()); // Handle resume subcommand by resolving a rollout path and using explicit resume API. let NewConversation { @@ -249,11 +249,7 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any if let Some(path) = resume_path { conversation_manager - .resume_conversation_from_rollout( - config.clone(), - path, - AuthManager::shared(config.codex_home.clone()), - ) + .resume_conversation_from_rollout(config.clone(), path, auth_manager.clone()) .await? } else { conversation_manager diff --git a/codex-rs/exec/tests/suite/auth_env.rs b/codex-rs/exec/tests/suite/auth_env.rs new file mode 100644 index 0000000000..d59f46cde8 --- /dev/null +++ b/codex-rs/exec/tests/suite/auth_env.rs @@ -0,0 +1,34 @@ +#![allow(clippy::unwrap_used, clippy::expect_used)] +use core_test_support::responses::ev_completed; +use core_test_support::responses::sse; +use core_test_support::responses::sse_response; +use core_test_support::responses::start_mock_server; +use core_test_support::test_codex_exec::test_codex_exec; +use wiremock::Mock; +use wiremock::matchers::header; +use wiremock::matchers::method; +use wiremock::matchers::path; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn exec_uses_codex_api_key_env_var() -> anyhow::Result<()> { + let test = test_codex_exec(); + let server = start_mock_server().await; + + Mock::given(method("POST")) + .and(path("/v1/responses")) + .and(header("Authorization", "Bearer dummy")) + .respond_with(sse_response(sse(vec![ev_completed("request_0")]))) + .expect(1) + .mount(&server) + .await; + + test.cmd_with_server(&server) + .arg("--skip-git-repo-check") + .arg("-C") + .arg(env!("CARGO_MANIFEST_DIR")) + .arg("echo testing codex api key") + .assert() + .success(); + + Ok(()) +} diff --git a/codex-rs/exec/tests/suite/mod.rs b/codex-rs/exec/tests/suite/mod.rs index 52f5bca34c..d04ecd2c93 100644 --- a/codex-rs/exec/tests/suite/mod.rs +++ b/codex-rs/exec/tests/suite/mod.rs @@ -1,5 +1,6 @@ // Aggregates all former standalone integration tests as modules. mod apply_patch; +mod auth_env; mod output_schema; mod resume; mod sandbox; diff --git a/codex-rs/exec/tests/suite/resume.rs b/codex-rs/exec/tests/suite/resume.rs index 4c4d343ee3..16be995e4d 100644 --- a/codex-rs/exec/tests/suite/resume.rs +++ b/codex-rs/exec/tests/suite/resume.rs @@ -1,10 +1,9 @@ #![allow(clippy::unwrap_used, clippy::expect_used)] use anyhow::Context; -use assert_cmd::prelude::*; +use core_test_support::test_codex_exec::test_codex_exec; use serde_json::Value; -use std::process::Command; +use std::path::Path; use std::string::ToString; -use tempfile::TempDir; use uuid::Uuid; use walkdir::WalkDir; @@ -72,18 +71,15 @@ fn extract_conversation_id(path: &std::path::Path) -> String { #[test] fn exec_resume_last_appends_to_existing_file() -> anyhow::Result<()> { - let home = TempDir::new()?; - let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("tests/fixtures/cli_responses_fixture.sse"); + let test = test_codex_exec(); + let fixture = + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/cli_responses_fixture.sse"); // 1) First run: create a session with a unique marker in the content. let marker = format!("resume-last-{}", Uuid::new_v4()); let prompt = format!("echo {marker}"); - Command::cargo_bin("codex-exec") - .context("should find binary for codex-exec")? - .env("CODEX_HOME", home.path()) - .env("OPENAI_API_KEY", "dummy") + test.cmd() .env("CODEX_RS_SSE_FIXTURE", &fixture) .env("OPENAI_BASE_URL", "http://unused.local") .arg("--skip-git-repo-check") @@ -94,7 +90,7 @@ fn exec_resume_last_appends_to_existing_file() -> anyhow::Result<()> { .success(); // Find the created session file containing the marker. - let sessions_dir = home.path().join("sessions"); + let sessions_dir = test.home_path().join("sessions"); let path = find_session_file_containing_marker(&sessions_dir, &marker) .expect("no session file found after first run"); @@ -102,11 +98,7 @@ fn exec_resume_last_appends_to_existing_file() -> anyhow::Result<()> { let marker2 = format!("resume-last-2-{}", Uuid::new_v4()); let prompt2 = format!("echo {marker2}"); - let mut binding = assert_cmd::Command::cargo_bin("codex-exec") - .context("should find binary for codex-exec")?; - let cmd = binding - .env("CODEX_HOME", home.path()) - .env("OPENAI_API_KEY", "dummy") + test.cmd() .env("CODEX_RS_SSE_FIXTURE", &fixture) .env("OPENAI_BASE_URL", "http://unused.local") .arg("--skip-git-repo-check") @@ -114,8 +106,9 @@ fn exec_resume_last_appends_to_existing_file() -> anyhow::Result<()> { .arg(env!("CARGO_MANIFEST_DIR")) .arg(&prompt2) .arg("resume") - .arg("--last"); - cmd.assert().success(); + .arg("--last") + .assert() + .success(); // Ensure the same file was updated and contains both markers. let resumed_path = find_session_file_containing_marker(&sessions_dir, &marker2) @@ -132,18 +125,15 @@ fn exec_resume_last_appends_to_existing_file() -> anyhow::Result<()> { #[test] fn exec_resume_by_id_appends_to_existing_file() -> anyhow::Result<()> { - let home = TempDir::new()?; - let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("tests/fixtures/cli_responses_fixture.sse"); + let test = test_codex_exec(); + let fixture = + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/cli_responses_fixture.sse"); // 1) First run: create a session let marker = format!("resume-by-id-{}", Uuid::new_v4()); let prompt = format!("echo {marker}"); - Command::cargo_bin("codex-exec") - .context("should find binary for codex-exec")? - .env("CODEX_HOME", home.path()) - .env("OPENAI_API_KEY", "dummy") + test.cmd() .env("CODEX_RS_SSE_FIXTURE", &fixture) .env("OPENAI_BASE_URL", "http://unused.local") .arg("--skip-git-repo-check") @@ -153,7 +143,7 @@ fn exec_resume_by_id_appends_to_existing_file() -> anyhow::Result<()> { .assert() .success(); - let sessions_dir = home.path().join("sessions"); + let sessions_dir = test.home_path().join("sessions"); let path = find_session_file_containing_marker(&sessions_dir, &marker) .expect("no session file found after first run"); let session_id = extract_conversation_id(&path); @@ -166,11 +156,7 @@ fn exec_resume_by_id_appends_to_existing_file() -> anyhow::Result<()> { let marker2 = format!("resume-by-id-2-{}", Uuid::new_v4()); let prompt2 = format!("echo {marker2}"); - let mut binding = assert_cmd::Command::cargo_bin("codex-exec") - .context("should find binary for codex-exec")?; - let cmd = binding - .env("CODEX_HOME", home.path()) - .env("OPENAI_API_KEY", "dummy") + test.cmd() .env("CODEX_RS_SSE_FIXTURE", &fixture) .env("OPENAI_BASE_URL", "http://unused.local") .arg("--skip-git-repo-check") @@ -178,8 +164,9 @@ fn exec_resume_by_id_appends_to_existing_file() -> anyhow::Result<()> { .arg(env!("CARGO_MANIFEST_DIR")) .arg(&prompt2) .arg("resume") - .arg(&session_id); - cmd.assert().success(); + .arg(&session_id) + .assert() + .success(); let resumed_path = find_session_file_containing_marker(&sessions_dir, &marker2) .expect("no resumed session file containing marker2"); @@ -195,17 +182,14 @@ fn exec_resume_by_id_appends_to_existing_file() -> anyhow::Result<()> { #[test] fn exec_resume_preserves_cli_configuration_overrides() -> anyhow::Result<()> { - let home = TempDir::new()?; - let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("tests/fixtures/cli_responses_fixture.sse"); + let test = test_codex_exec(); + let fixture = + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/cli_responses_fixture.sse"); let marker = format!("resume-config-{}", Uuid::new_v4()); let prompt = format!("echo {marker}"); - Command::cargo_bin("codex-exec") - .context("should find binary for codex-exec")? - .env("CODEX_HOME", home.path()) - .env("OPENAI_API_KEY", "dummy") + test.cmd() .env("CODEX_RS_SSE_FIXTURE", &fixture) .env("OPENAI_BASE_URL", "http://unused.local") .arg("--skip-git-repo-check") @@ -219,17 +203,15 @@ fn exec_resume_preserves_cli_configuration_overrides() -> anyhow::Result<()> { .assert() .success(); - let sessions_dir = home.path().join("sessions"); + let sessions_dir = test.home_path().join("sessions"); let path = find_session_file_containing_marker(&sessions_dir, &marker) .expect("no session file found after first run"); let marker2 = format!("resume-config-2-{}", Uuid::new_v4()); let prompt2 = format!("echo {marker2}"); - let output = Command::cargo_bin("codex-exec") - .context("should find binary for codex-exec")? - .env("CODEX_HOME", home.path()) - .env("OPENAI_API_KEY", "dummy") + let output = test + .cmd() .env("CODEX_RS_SSE_FIXTURE", &fixture) .env("OPENAI_BASE_URL", "http://unused.local") .arg("--skip-git-repo-check") diff --git a/codex-rs/login/src/lib.rs b/codex-rs/login/src/lib.rs index df4fc1e76a..0a64c61e4e 100644 --- a/codex-rs/login/src/lib.rs +++ b/codex-rs/login/src/lib.rs @@ -14,6 +14,7 @@ pub use codex_core::AuthManager; pub use codex_core::CodexAuth; pub use codex_core::auth::AuthDotJson; pub use codex_core::auth::CLIENT_ID; +pub use codex_core::auth::CODEX_API_KEY_ENV_VAR; pub use codex_core::auth::OPENAI_API_KEY_ENV_VAR; pub use codex_core::auth::get_auth_file; pub use codex_core::auth::login_with_api_key; diff --git a/codex-rs/mcp-server/src/message_processor.rs b/codex-rs/mcp-server/src/message_processor.rs index 039375b05d..418c2a5162 100644 --- a/codex-rs/mcp-server/src/message_processor.rs +++ b/codex-rs/mcp-server/src/message_processor.rs @@ -52,7 +52,7 @@ impl MessageProcessor { config: Arc, ) -> Self { let outgoing = Arc::new(outgoing); - let auth_manager = AuthManager::shared(config.codex_home.clone()); + let auth_manager = AuthManager::shared(config.codex_home.clone(), false); let conversation_manager = Arc::new(ConversationManager::new(auth_manager)); Self { outgoing, diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 8130d64796..d8dde74f06 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -361,7 +361,7 @@ async fn run_ratatui_app( // Initialize high-fidelity session event logging if enabled. session_log::maybe_init(&config); - let auth_manager = AuthManager::shared(config.codex_home.clone()); + let auth_manager = AuthManager::shared(config.codex_home.clone(), false); let login_status = get_login_status(&config); let should_show_onboarding = should_show_onboarding(login_status, &config, should_show_trust_screen); diff --git a/sdk/typescript/src/exec.ts b/sdk/typescript/src/exec.ts index 91ce763909..a20d1c4db1 100644 --- a/sdk/typescript/src/exec.ts +++ b/sdk/typescript/src/exec.ts @@ -58,7 +58,7 @@ export class CodexExec { env.OPENAI_BASE_URL = args.baseUrl; } if (args.apiKey) { - env.OPENAI_API_KEY = args.apiKey; + env.CODEX_API_KEY = args.apiKey; } const child = spawn(this.executablePath, commandArgs, { From b727d3f98aba0eecccfdd4af866bad83c2c4b9c0 Mon Sep 17 00:00:00 2001 From: Marcus Griep Date: Thu, 2 Oct 2025 11:05:51 -0600 Subject: [PATCH 12/20] fix: handle JSON Schema in additionalProperties for MCP tools (#4454) Fixes #4176 Some common tools provide a schema (even if just an empty object schema) as the value for `additionalProperties`. The parsing as it currently stands fails when it encounters this. This PR updates the schema to accept a schema object in addition to a boolean value, per the JSON Schema spec. --- .../core/src/exec_command/responses_api.rs | 4 +- codex-rs/core/src/openai_tools.rs | 153 +++++++++++++++++- codex-rs/core/src/plan_tool.rs | 4 +- codex-rs/core/src/tool_apply_patch.rs | 2 +- 4 files changed, 153 insertions(+), 10 deletions(-) diff --git a/codex-rs/core/src/exec_command/responses_api.rs b/codex-rs/core/src/exec_command/responses_api.rs index 70b90dd425..10629f4301 100644 --- a/codex-rs/core/src/exec_command/responses_api.rs +++ b/codex-rs/core/src/exec_command/responses_api.rs @@ -49,7 +49,7 @@ pub fn create_exec_command_tool_for_responses_api() -> ResponsesApiTool { parameters: JsonSchema::Object { properties, required: Some(vec!["cmd".to_string()]), - additional_properties: Some(false), + additional_properties: Some(false.into()), }, } } @@ -92,7 +92,7 @@ Can write control characters (\u0003 for Ctrl-C), or an empty string to just pol parameters: JsonSchema::Object { properties, required: Some(vec!["session_id".to_string(), "chars".to_string()]), - additional_properties: Some(false), + additional_properties: Some(false.into()), }, } } diff --git a/codex-rs/core/src/openai_tools.rs b/codex-rs/core/src/openai_tools.rs index 48dca79671..9e9b9388c7 100644 --- a/codex-rs/core/src/openai_tools.rs +++ b/codex-rs/core/src/openai_tools.rs @@ -122,6 +122,26 @@ impl ToolsConfig { } } +/// Whether additional properties are allowed, and if so, any required schema +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(untagged)] +pub(crate) enum AdditionalProperties { + Boolean(bool), + Schema(Box), +} + +impl From for AdditionalProperties { + fn from(b: bool) -> Self { + Self::Boolean(b) + } +} + +impl From for AdditionalProperties { + fn from(s: JsonSchema) -> Self { + Self::Schema(Box::new(s)) + } +} + /// Generic JSON‑Schema subset needed for our tool definitions #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type", rename_all = "lowercase")] @@ -154,7 +174,7 @@ pub(crate) enum JsonSchema { rename = "additionalProperties", skip_serializing_if = "Option::is_none" )] - additional_properties: Option, + additional_properties: Option, }, } @@ -200,7 +220,7 @@ fn create_unified_exec_tool() -> OpenAiTool { parameters: JsonSchema::Object { properties, required: Some(vec!["input".to_string()]), - additional_properties: Some(false), + additional_properties: Some(false.into()), }, }) } @@ -247,7 +267,7 @@ fn create_shell_tool() -> OpenAiTool { parameters: JsonSchema::Object { properties, required: Some(vec!["command".to_string()]), - additional_properties: Some(false), + additional_properties: Some(false.into()), }, }) } @@ -271,7 +291,7 @@ fn create_view_image_tool() -> OpenAiTool { parameters: JsonSchema::Object { properties, required: Some(vec!["path".to_string()]), - additional_properties: Some(false), + additional_properties: Some(false.into()), }, }) } @@ -708,7 +728,130 @@ mod tests { "string_property".to_string(), "number_property".to_string(), ]), - additional_properties: Some(false), + additional_properties: Some(false.into()), + }, + ), + ]), + required: None, + additional_properties: None, + }, + description: "Do something cool".to_string(), + strict: false, + }) + ); + } + + #[test] + fn test_get_openai_tools_mcp_tools_with_additional_properties_schema() { + let model_family = find_family_for_model("o3").expect("o3 should be a valid model family"); + let config = ToolsConfig::new(&ToolsConfigParams { + model_family: &model_family, + include_plan_tool: false, + include_apply_patch_tool: false, + include_web_search_request: true, + use_streamable_shell_tool: false, + include_view_image_tool: true, + experimental_unified_exec_tool: true, + }); + let tools = get_openai_tools( + &config, + Some(HashMap::from([( + "test_server/do_something_cool".to_string(), + mcp_types::Tool { + name: "do_something_cool".to_string(), + input_schema: ToolInputSchema { + properties: Some(serde_json::json!({ + "string_argument": { + "type": "string", + }, + "number_argument": { + "type": "number", + }, + "object_argument": { + "type": "object", + "properties": { + "string_property": { "type": "string" }, + "number_property": { "type": "number" }, + }, + "required": [ + "string_property", + "number_property", + ], + "additionalProperties": { + "type": "object", + "properties": { + "addtl_prop": { "type": "string" }, + }, + "required": [ + "addtl_prop", + ], + "additionalProperties": false, + }, + }, + })), + required: None, + r#type: "object".to_string(), + }, + output_schema: None, + title: None, + annotations: None, + description: Some("Do something cool".to_string()), + }, + )])), + ); + + assert_eq_tool_names( + &tools, + &[ + "unified_exec", + "web_search", + "view_image", + "test_server/do_something_cool", + ], + ); + + assert_eq!( + tools[3], + OpenAiTool::Function(ResponsesApiTool { + name: "test_server/do_something_cool".to_string(), + parameters: JsonSchema::Object { + properties: BTreeMap::from([ + ( + "string_argument".to_string(), + JsonSchema::String { description: None } + ), + ( + "number_argument".to_string(), + JsonSchema::Number { description: None } + ), + ( + "object_argument".to_string(), + JsonSchema::Object { + properties: BTreeMap::from([ + ( + "string_property".to_string(), + JsonSchema::String { description: None } + ), + ( + "number_property".to_string(), + JsonSchema::Number { description: None } + ), + ]), + required: Some(vec![ + "string_property".to_string(), + "number_property".to_string(), + ]), + additional_properties: Some( + JsonSchema::Object { + properties: BTreeMap::from([( + "addtl_prop".to_string(), + JsonSchema::String { description: None } + ),]), + required: Some(vec!["addtl_prop".to_string(),]), + additional_properties: Some(false.into()), + } + .into() + ), }, ), ]), diff --git a/codex-rs/core/src/plan_tool.rs b/codex-rs/core/src/plan_tool.rs index c81675698f..e0fdb56529 100644 --- a/codex-rs/core/src/plan_tool.rs +++ b/codex-rs/core/src/plan_tool.rs @@ -32,7 +32,7 @@ pub(crate) static PLAN_TOOL: LazyLock = LazyLock::new(|| { items: Box::new(JsonSchema::Object { properties: plan_item_props, required: Some(vec!["step".to_string(), "status".to_string()]), - additional_properties: Some(false), + additional_properties: Some(false.into()), }), }; @@ -54,7 +54,7 @@ At most one step can be in_progress at a time. parameters: JsonSchema::Object { properties, required: Some(vec!["plan".to_string()]), - additional_properties: Some(false), + additional_properties: Some(false.into()), }, }) }); diff --git a/codex-rs/core/src/tool_apply_patch.rs b/codex-rs/core/src/tool_apply_patch.rs index 164a1e127f..5f34b0d229 100644 --- a/codex-rs/core/src/tool_apply_patch.rs +++ b/codex-rs/core/src/tool_apply_patch.rs @@ -116,7 +116,7 @@ It is important to remember: parameters: JsonSchema::Object { properties, required: Some(vec!["input".to_string()]), - additional_properties: Some(false), + additional_properties: Some(false.into()), }, }) } From b07aafa5f55b74eadaaff404d871f4dc7694a389 Mon Sep 17 00:00:00 2001 From: dedrisian-oai Date: Thu, 2 Oct 2025 10:27:10 -0700 Subject: [PATCH 13/20] Fix status usage ratio (#4584) 1. Removes "Token usage" line for chatgpt sub users 2. Adds the word "used" to the context window line --- codex-rs/tui/src/status/card.rs | 7 +++++-- ...tus__tests__status_snapshot_includes_monthly_limit.snap | 2 +- ..._tests__status_snapshot_includes_reasoning_details.snap | 2 +- ..._tests__status_snapshot_shows_empty_limits_message.snap | 2 +- ...ests__status_snapshot_shows_missing_limits_message.snap | 2 +- ...ests__status_snapshot_truncates_in_narrow_terminal.snap | 2 +- codex-rs/tui/src/status/tests.rs | 2 +- 7 files changed, 11 insertions(+), 8 deletions(-) diff --git a/codex-rs/tui/src/status/card.rs b/codex-rs/tui/src/status/card.rs index 2674fc3e07..4832713bf9 100644 --- a/codex-rs/tui/src/status/card.rs +++ b/codex-rs/tui/src/status/card.rs @@ -152,7 +152,7 @@ impl StatusHistoryCell { Span::from(format!("{percent}% left")), Span::from(" (").dim(), Span::from(used_fmt).dim(), - Span::from(" / ").dim(), + Span::from(" used / ").dim(), Span::from(window_fmt).dim(), Span::from(")").dim(), ]) @@ -302,7 +302,10 @@ impl HistoryCell for StatusHistoryCell { } lines.push(Line::from(Vec::>::new())); - lines.push(formatter.line("Token usage", self.token_usage_spans())); + // Hide token usage only for ChatGPT subscribers + if !matches!(self.account, Some(StatusAccountDisplay::ChatGpt { .. })) { + lines.push(formatter.line("Token usage", self.token_usage_spans())); + } if let Some(spans) = self.context_window_spans() { lines.push(formatter.line("Context window", spans)); diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_monthly_limit.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_monthly_limit.snap index 73767d986b..cf3f492eef 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_monthly_limit.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_monthly_limit.snap @@ -14,6 +14,6 @@ expression: sanitized │ Agents.md: │ │ │ │ Token usage: 1.2K total (800 input + 400 output) │ -│ Context window: 100% left (1.2K / 272K) │ +│ Context window: 100% left (1.2K used / 272K) │ │ Monthly limit: [██░░░░░░░░░░░░░░░░░░] 12% used (resets 07:08 on 7 May) │ ╰────────────────────────────────────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_reasoning_details.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_reasoning_details.snap index 20904760cf..505375eae5 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_reasoning_details.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_reasoning_details.snap @@ -14,7 +14,7 @@ expression: sanitized │ Agents.md: │ │ │ │ Token usage: 1.9K total (1K input + 900 output) │ -│ Context window: 100% left (2.1K / 272K) │ +│ Context window: 100% left (2.1K used / 272K) │ │ 5h limit: [███████████████░░░░░] 72% used (resets 03:14) │ │ Weekly limit: [█████████░░░░░░░░░░░] 45% used (resets 03:24) │ ╰─────────────────────────────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_empty_limits_message.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_empty_limits_message.snap index 0ac26c5d54..472df543d6 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_empty_limits_message.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_empty_limits_message.snap @@ -14,6 +14,6 @@ expression: sanitized │ Agents.md: │ │ │ │ Token usage: 750 total (500 input + 250 output) │ -│ Context window: 100% left (750 / 272K) │ +│ Context window: 100% left (750 used / 272K) │ │ Limits: data not available yet │ ╰─────────────────────────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_missing_limits_message.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_missing_limits_message.snap index d59140a355..66bcfa3e21 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_missing_limits_message.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_missing_limits_message.snap @@ -14,6 +14,6 @@ expression: sanitized │ Agents.md: │ │ │ │ Token usage: 750 total (500 input + 250 output) │ -│ Context window: 100% left (750 / 272K) │ +│ Context window: 100% left (750 used / 272K) │ │ Limits: send a message to load usage data │ ╰─────────────────────────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_truncates_in_narrow_terminal.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_truncates_in_narrow_terminal.snap index fd429dd940..b7c595340d 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_truncates_in_narrow_terminal.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_truncates_in_narrow_terminal.snap @@ -14,7 +14,7 @@ expression: sanitized │ Agents.md: │ │ │ │ Token usage: 1.9K total (1K input + │ -│ Context window: 100% left (2.1K / 272K) │ +│ Context window: 100% left (2.1K used / │ │ 5h limit: [███████████████░░░░░] │ │ (resets 03:14) │ ╰────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/status/tests.rs b/codex-rs/tui/src/status/tests.rs index eff8d8f47f..395d952f41 100644 --- a/codex-rs/tui/src/status/tests.rs +++ b/codex-rs/tui/src/status/tests.rs @@ -314,7 +314,7 @@ fn status_context_window_uses_last_usage() { .expect("context line"); assert!( - context_line.contains("13.7K / 272K"), + context_line.contains("13.7K used / 272K"), "expected context line to reflect last usage tokens, got: {context_line}" ); assert!( From ec98445abf602e54c0399b7dd61da14de286b8a6 Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Thu, 2 Oct 2025 11:34:47 -0700 Subject: [PATCH 14/20] normalize key hints (#4586) render key hints the same everywhere. | Before | After | |--------|-------| | Screenshot 2025-10-01 at 5 15 42
PM | Screenshot 2025-10-01 at 5 13 56
PM | | Screenshot 2025-10-01 at 5 17 01
PM | Screenshot 2025-10-01 at 5 14 24
PM | | Screenshot 2025-10-01 at 5 17 29
PM | Screenshot 2025-10-01 at 5 14 37
PM | | Screenshot 2025-10-01 at 5 17 40
PM | Screenshot 2025-10-01 at 5 14 56
PM | --- .../tui/src/bottom_pane/approval_overlay.rs | 9 +- .../tui/src/bottom_pane/custom_prompt_view.rs | 4 +- codex-rs/tui/src/bottom_pane/footer.rs | 153 ++++++++---------- .../src/bottom_pane/list_selection_view.rs | 12 +- codex-rs/tui/src/bottom_pane/popup_consts.rs | 15 +- ...__tests__footer_mode_shortcut_overlay.snap | 1 - ...tests__footer_shortcuts_shift_and_esc.snap | 1 - ..._list_selection_spacing_with_subtitle.snap | 2 +- ...st_selection_spacing_without_subtitle.snap | 2 +- codex-rs/tui/src/chatwidget.rs | 14 +- ...hatwidget__tests__approval_modal_exec.snap | 2 +- ..._tests__approval_modal_exec_no_reason.snap | 2 +- ...atwidget__tests__approval_modal_patch.snap | 2 +- ...twidget__tests__chat_small_running_h2.snap | 2 +- ...exec_and_status_layout_vt100_snapshot.snap | 2 +- ...dget__tests__exec_approval_modal_exec.snap | 4 +- ...atwidget__tests__status_widget_active.snap | 2 +- ...sts__status_widget_and_approval_modal.snap | 2 +- codex-rs/tui/src/key_hint.rs | 95 +++++++++-- codex-rs/tui/src/pager_overlay.rs | 115 +++++-------- codex-rs/tui/src/resume_picker.rs | 23 +-- ..._tests__static_overlay_snapshot_basic.snap | 4 +- ...ript_overlay_apply_patch_scroll_vt100.snap | 4 +- ...ts__transcript_overlay_snapshot_basic.snap | 4 +- ...ator_widget__tests__renders_truncated.snap | 2 +- ...__tests__renders_with_queued_messages.snap | 4 +- ...t__tests__renders_with_working_header.snap | 2 +- codex-rs/tui/src/status_indicator_widget.rs | 13 +- 28 files changed, 270 insertions(+), 227 deletions(-) diff --git a/codex-rs/tui/src/bottom_pane/approval_overlay.rs b/codex-rs/tui/src/bottom_pane/approval_overlay.rs index 511039df4a..d85e5db57f 100644 --- a/codex-rs/tui/src/bottom_pane/approval_overlay.rs +++ b/codex-rs/tui/src/bottom_pane/approval_overlay.rs @@ -11,6 +11,7 @@ use crate::bottom_pane::list_selection_view::SelectionViewParams; use crate::diff_render::DiffSummary; use crate::exec_command::strip_bash_lc_and_escape; use crate::history_cell; +use crate::key_hint; use crate::render::highlight::highlight_bash_to_lines; use crate::render::renderable::ColumnRenderable; use crate::render::renderable::Renderable; @@ -116,7 +117,13 @@ impl ApprovalOverlay { .collect(); let params = SelectionViewParams { - footer_hint: Some("Press Enter to confirm or Esc to cancel".to_string()), + footer_hint: Some(Line::from(vec![ + "Press ".into(), + key_hint::plain(KeyCode::Enter).into(), + " to confirm or ".into(), + key_hint::plain(KeyCode::Esc).into(), + " to cancel".into(), + ])), items, header, ..Default::default() diff --git a/codex-rs/tui/src/bottom_pane/custom_prompt_view.rs b/codex-rs/tui/src/bottom_pane/custom_prompt_view.rs index 07bd920384..54f474fb1f 100644 --- a/codex-rs/tui/src/bottom_pane/custom_prompt_view.rs +++ b/codex-rs/tui/src/bottom_pane/custom_prompt_view.rs @@ -14,7 +14,7 @@ use std::cell::RefCell; use crate::render::renderable::Renderable; -use super::popup_consts::STANDARD_POPUP_HINT_LINE; +use super::popup_consts::standard_popup_hint_line; use super::CancellationEvent; use super::bottom_pane_view::BottomPaneView; @@ -221,7 +221,7 @@ impl Renderable for CustomPromptView { let hint_y = hint_blank_y.saturating_add(1); if hint_y < area.y.saturating_add(area.height) { - Paragraph::new(STANDARD_POPUP_HINT_LINE).render( + Paragraph::new(standard_popup_hint_line()).render( Rect { x: area.x, y: hint_y, diff --git a/codex-rs/tui/src/bottom_pane/footer.rs b/codex-rs/tui/src/bottom_pane/footer.rs index 133c0b34bf..3fc9b2e1f4 100644 --- a/codex-rs/tui/src/bottom_pane/footer.rs +++ b/codex-rs/tui/src/bottom_pane/footer.rs @@ -1,13 +1,15 @@ +use crate::key_hint; +use crate::key_hint::KeyBinding; +use crate::render::line_utils::prefix_lines; use crate::ui_consts::FOOTER_INDENT_COLS; use crossterm::event::KeyCode; -use crossterm::event::KeyModifiers; use ratatui::buffer::Buffer; use ratatui::layout::Rect; use ratatui::style::Stylize; use ratatui::text::Line; use ratatui::text::Span; -use ratatui::widgets::WidgetRef; -use std::iter; +use ratatui::widgets::Paragraph; +use ratatui::widgets::Widget; #[derive(Clone, Copy, Debug)] pub(crate) struct FooterProps { @@ -61,15 +63,12 @@ pub(crate) fn footer_height(props: FooterProps) -> u16 { } pub(crate) fn render_footer(area: Rect, buf: &mut Buffer, props: FooterProps) { - let lines = footer_lines(props); - for (idx, line) in lines.into_iter().enumerate() { - let y = area.y + idx as u16; - if y >= area.y + area.height { - break; - } - let row = Rect::new(area.x, y, area.width, 1); - line.render_ref(row, buf); - } + Paragraph::new(prefix_lines( + footer_lines(props), + " ".repeat(FOOTER_INDENT_COLS).into(), + " ".repeat(FOOTER_INDENT_COLS).into(), + )) + .render(area, buf); } fn footer_lines(props: FooterProps) -> Vec> { @@ -81,7 +80,10 @@ fn footer_lines(props: FooterProps) -> Vec> { if props.is_task_running { vec![context_window_line(props.context_window_percent)] } else { - vec![dim_line(indent_text("? for shortcuts"))] + vec![Line::from(vec![ + key_hint::plain(KeyCode::Char('?')).into(), + " for shortcuts".dim(), + ])] } } FooterMode::ShortcutOverlay => shortcut_overlay_lines(ShortcutsState { @@ -110,27 +112,36 @@ fn ctrl_c_reminder_line(state: CtrlCReminderState) -> Line<'static> { } else { "quit" }; - let text = format!("ctrl + c again to {action}"); - dim_line(indent_text(&text)) + Line::from(vec![ + key_hint::ctrl(KeyCode::Char('c')).into(), + format!(" again to {action}").into(), + ]) + .dim() } fn esc_hint_line(esc_backtrack_hint: bool) -> Line<'static> { - let text = if esc_backtrack_hint { - "esc again to edit previous message" + let esc = key_hint::plain(KeyCode::Esc); + if esc_backtrack_hint { + Line::from(vec![esc.into(), " again to edit previous message".into()]).dim() } else { - "esc esc to edit previous message" - }; - dim_line(indent_text(text)) + Line::from(vec![ + esc.into(), + " ".into(), + esc.into(), + " to edit previous message".into(), + ]) + .dim() + } } fn shortcut_overlay_lines(state: ShortcutsState) -> Vec> { - let mut commands = String::new(); - let mut newline = String::new(); - let mut file_paths = String::new(); - let mut paste_image = String::new(); - let mut edit_previous = String::new(); - let mut quit = String::new(); - let mut show_transcript = String::new(); + let mut commands = Line::from(""); + let mut newline = Line::from(""); + let mut file_paths = Line::from(""); + let mut paste_image = Line::from(""); + let mut edit_previous = Line::from(""); + let mut quit = Line::from(""); + let mut show_transcript = Line::from(""); for descriptor in SHORTCUTS { if let Some(text) = descriptor.overlay_entry(state) { @@ -153,14 +164,14 @@ fn shortcut_overlay_lines(state: ShortcutsState) -> Vec> { paste_image, edit_previous, quit, - String::new(), + Line::from(""), show_transcript, ]; build_columns(ordered) } -fn build_columns(entries: Vec) -> Vec> { +fn build_columns(entries: Vec>) -> Vec> { if entries.is_empty() { return Vec::new(); } @@ -174,7 +185,7 @@ fn build_columns(entries: Vec) -> Vec> { let mut entries = entries; if entries.len() < target_len { entries.extend(std::iter::repeat_n( - String::new(), + Line::from(""), target_len - entries.len(), )); } @@ -183,7 +194,7 @@ fn build_columns(entries: Vec) -> Vec> { for (idx, entry) in entries.iter().enumerate() { let column = idx % COLUMNS; - column_widths[column] = column_widths[column].max(entry.len()); + column_widths[column] = column_widths[column].max(entry.width()); } for (idx, width) in column_widths.iter_mut().enumerate() { @@ -193,42 +204,30 @@ fn build_columns(entries: Vec) -> Vec> { entries .chunks(COLUMNS) .map(|chunk| { - let mut line = String::new(); + let mut line = Line::from(""); for (col, entry) in chunk.iter().enumerate() { - line.push_str(entry); + line.extend(entry.spans.clone()); if col < COLUMNS - 1 { let target_width = column_widths[col]; - let padding = target_width.saturating_sub(entry.len()) + COLUMN_GAP; - line.push_str(&" ".repeat(padding)); + let padding = target_width.saturating_sub(entry.width()) + COLUMN_GAP; + line.push_span(Span::from(" ".repeat(padding))); } } - let indented = indent_text(&line); - dim_line(indented) + line.dim() }) .collect() } -fn indent_text(text: &str) -> String { - let mut indented = String::with_capacity(FOOTER_INDENT_COLS + text.len()); - indented.extend(iter::repeat_n(' ', FOOTER_INDENT_COLS)); - indented.push_str(text); - indented -} - -fn dim_line(text: String) -> Line<'static> { - Line::from(text).dim() -} - fn context_window_line(percent: Option) -> Line<'static> { let mut spans: Vec> = Vec::new(); - spans.push(indent_text("").into()); match percent { Some(percent) => { spans.push(format!("{percent}%").bold()); spans.push(" context left".dim()); } None => { - spans.push("? for shortcuts".dim()); + spans.push(key_hint::plain(KeyCode::Char('?')).into()); + spans.push(" for shortcuts".dim()); } } Line::from(spans) @@ -247,9 +246,7 @@ enum ShortcutId { #[derive(Clone, Copy, Debug, Eq, PartialEq)] struct ShortcutBinding { - code: KeyCode, - modifiers: KeyModifiers, - overlay_text: &'static str, + key: KeyBinding, condition: DisplayCondition, } @@ -288,20 +285,24 @@ impl ShortcutDescriptor { self.bindings.iter().find(|binding| binding.matches(state)) } - fn overlay_entry(&self, state: ShortcutsState) -> Option { + fn overlay_entry(&self, state: ShortcutsState) -> Option> { let binding = self.binding_for(state)?; - let label = match self.id { + let mut line = Line::from(vec![self.prefix.into(), binding.key.into()]); + match self.id { ShortcutId::EditPrevious => { if state.esc_backtrack_hint { - " again to edit previous message" + line.push_span(" again to edit previous message"); } else { - " esc to edit previous message" + line.extend(vec![ + " ".into(), + key_hint::plain(KeyCode::Esc).into(), + " to edit previous message".into(), + ]); } } - _ => self.label, + _ => line.push_span(self.label), }; - let text = format!("{}{}{}", self.prefix, binding.overlay_text, label); - Some(text) + Some(line) } } @@ -309,9 +310,7 @@ const SHORTCUTS: &[ShortcutDescriptor] = &[ ShortcutDescriptor { id: ShortcutId::Commands, bindings: &[ShortcutBinding { - code: KeyCode::Char('/'), - modifiers: KeyModifiers::NONE, - overlay_text: "/", + key: key_hint::plain(KeyCode::Char('/')), condition: DisplayCondition::Always, }], prefix: "", @@ -321,15 +320,11 @@ const SHORTCUTS: &[ShortcutDescriptor] = &[ id: ShortcutId::InsertNewline, bindings: &[ ShortcutBinding { - code: KeyCode::Enter, - modifiers: KeyModifiers::SHIFT, - overlay_text: "shift + enter", + key: key_hint::shift(KeyCode::Enter), condition: DisplayCondition::WhenShiftEnterHint, }, ShortcutBinding { - code: KeyCode::Char('j'), - modifiers: KeyModifiers::CONTROL, - overlay_text: "ctrl + j", + key: key_hint::ctrl(KeyCode::Char('j')), condition: DisplayCondition::WhenNotShiftEnterHint, }, ], @@ -339,9 +334,7 @@ const SHORTCUTS: &[ShortcutDescriptor] = &[ ShortcutDescriptor { id: ShortcutId::FilePaths, bindings: &[ShortcutBinding { - code: KeyCode::Char('@'), - modifiers: KeyModifiers::NONE, - overlay_text: "@", + key: key_hint::plain(KeyCode::Char('@')), condition: DisplayCondition::Always, }], prefix: "", @@ -350,9 +343,7 @@ const SHORTCUTS: &[ShortcutDescriptor] = &[ ShortcutDescriptor { id: ShortcutId::PasteImage, bindings: &[ShortcutBinding { - code: KeyCode::Char('v'), - modifiers: KeyModifiers::CONTROL, - overlay_text: "ctrl + v", + key: key_hint::ctrl(KeyCode::Char('v')), condition: DisplayCondition::Always, }], prefix: "", @@ -361,9 +352,7 @@ const SHORTCUTS: &[ShortcutDescriptor] = &[ ShortcutDescriptor { id: ShortcutId::EditPrevious, bindings: &[ShortcutBinding { - code: KeyCode::Esc, - modifiers: KeyModifiers::NONE, - overlay_text: "esc", + key: key_hint::plain(KeyCode::Esc), condition: DisplayCondition::Always, }], prefix: "", @@ -372,9 +361,7 @@ const SHORTCUTS: &[ShortcutDescriptor] = &[ ShortcutDescriptor { id: ShortcutId::Quit, bindings: &[ShortcutBinding { - code: KeyCode::Char('c'), - modifiers: KeyModifiers::CONTROL, - overlay_text: "ctrl + c", + key: key_hint::ctrl(KeyCode::Char('c')), condition: DisplayCondition::Always, }], prefix: "", @@ -383,9 +370,7 @@ const SHORTCUTS: &[ShortcutDescriptor] = &[ ShortcutDescriptor { id: ShortcutId::ShowTranscript, bindings: &[ShortcutBinding { - code: KeyCode::Char('t'), - modifiers: KeyModifiers::CONTROL, - overlay_text: "ctrl + t", + key: key_hint::ctrl(KeyCode::Char('t')), condition: DisplayCondition::Always, }], prefix: "", diff --git a/codex-rs/tui/src/bottom_pane/list_selection_view.rs b/codex-rs/tui/src/bottom_pane/list_selection_view.rs index e2614885a0..cb3de2122c 100644 --- a/codex-rs/tui/src/bottom_pane/list_selection_view.rs +++ b/codex-rs/tui/src/bottom_pane/list_selection_view.rs @@ -43,7 +43,7 @@ pub(crate) struct SelectionItem { pub(crate) struct SelectionViewParams { pub title: Option, pub subtitle: Option, - pub footer_hint: Option, + pub footer_hint: Option>, pub items: Vec, pub is_searchable: bool, pub search_placeholder: Option, @@ -65,7 +65,7 @@ impl Default for SelectionViewParams { } pub(crate) struct ListSelectionView { - footer_hint: Option, + footer_hint: Option>, items: Vec, state: ScrollState, complete: bool, @@ -416,7 +416,7 @@ impl Renderable for ListSelectionView { width: footer_area.width.saturating_sub(2), height: footer_area.height, }; - Line::from(hint.clone().dim()).render(hint_area, buf); + hint.clone().dim().render(hint_area, buf); } } } @@ -425,7 +425,7 @@ impl Renderable for ListSelectionView { mod tests { use super::*; use crate::app_event::AppEvent; - use crate::bottom_pane::popup_consts::STANDARD_POPUP_HINT_LINE; + use crate::bottom_pane::popup_consts::standard_popup_hint_line; use insta::assert_snapshot; use ratatui::layout::Rect; use tokio::sync::mpsc::unbounded_channel; @@ -455,7 +455,7 @@ mod tests { SelectionViewParams { title: Some("Select Approval Mode".to_string()), subtitle: subtitle.map(str::to_string), - footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), + footer_hint: Some(standard_popup_hint_line()), items, ..Default::default() }, @@ -517,7 +517,7 @@ mod tests { let mut view = ListSelectionView::new( SelectionViewParams { title: Some("Select Approval Mode".to_string()), - footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), + footer_hint: Some(standard_popup_hint_line()), items, is_searchable: true, search_placeholder: Some("Type to search branches".to_string()), diff --git a/codex-rs/tui/src/bottom_pane/popup_consts.rs b/codex-rs/tui/src/bottom_pane/popup_consts.rs index 5147b2ee5f..2cabe389b1 100644 --- a/codex-rs/tui/src/bottom_pane/popup_consts.rs +++ b/codex-rs/tui/src/bottom_pane/popup_consts.rs @@ -1,8 +1,21 @@ //! Shared popup-related constants for bottom pane widgets. +use crossterm::event::KeyCode; +use ratatui::text::Line; + +use crate::key_hint; + /// Maximum number of rows any popup should attempt to display. /// Keep this consistent across all popups for a uniform feel. pub(crate) const MAX_POPUP_ROWS: usize = 8; /// Standard footer hint text used by popups. -pub(crate) const STANDARD_POPUP_HINT_LINE: &str = "Press Enter to confirm or Esc to go back"; +pub(crate) fn standard_popup_hint_line() -> Line<'static> { + Line::from(vec![ + "Press ".into(), + key_hint::plain(KeyCode::Enter).into(), + " to confirm or ".into(), + key_hint::plain(KeyCode::Esc).into(), + " to go back".into(), + ]) +} diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_shortcut_overlay.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_shortcut_overlay.snap index 170dedc01e..3b6782d06d 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_shortcut_overlay.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_shortcut_overlay.snap @@ -1,6 +1,5 @@ --- source: tui/src/bottom_pane/chat_composer.rs -assertion_line: 1497 expression: terminal.backend() --- " " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_shift_and_esc.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_shift_and_esc.snap index ffa4c5b048..264515a6c2 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_shift_and_esc.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_shift_and_esc.snap @@ -1,6 +1,5 @@ --- source: tui/src/bottom_pane/footer.rs -assertion_line: 389 expression: terminal.backend() --- " / for commands shift + enter for newline " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_with_subtitle.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_with_subtitle.snap index 9cbfe88f78..512f6bbca6 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_with_subtitle.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_with_subtitle.snap @@ -9,4 +9,4 @@ expression: render_lines(&view) › 1. Read Only (current) Codex can read files 2. Full Access Codex can edit files - Press Enter to confirm or Esc to go back + Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_without_subtitle.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_without_subtitle.snap index 5e3cf2c6e6..ddd0f90cd8 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_without_subtitle.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_without_subtitle.snap @@ -8,4 +8,4 @@ expression: render_lines(&view) › 1. Read Only (current) Codex can read files 2. Full Access Codex can edit files - Press Enter to confirm or Esc to go back + Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 9940c8f7d7..32566b3ecd 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -68,7 +68,7 @@ use crate::bottom_pane::SelectionAction; use crate::bottom_pane::SelectionItem; use crate::bottom_pane::SelectionViewParams; use crate::bottom_pane::custom_prompt_view::CustomPromptView; -use crate::bottom_pane::popup_consts::STANDARD_POPUP_HINT_LINE; +use crate::bottom_pane::popup_consts::standard_popup_hint_line; use crate::clipboard_paste::paste_image_to_temp_png; use crate::diff_render::display_path_for; use crate::exec_cell::CommandOutput; @@ -1625,7 +1625,7 @@ impl ChatWidget { subtitle: Some( "Switch between OpenAI models for this and future Codex CLI session".to_string(), ), - footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), + footer_hint: Some(standard_popup_hint_line()), items, ..Default::default() }); @@ -1668,7 +1668,7 @@ impl ChatWidget { self.bottom_pane.show_selection_view(SelectionViewParams { title: Some("Select Approval Mode".to_string()), - footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), + footer_hint: Some(standard_popup_hint_line()), items, ..Default::default() }); @@ -1843,7 +1843,7 @@ impl ChatWidget { self.bottom_pane.show_selection_view(SelectionViewParams { title: Some("Select a review preset".into()), - footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), + footer_hint: Some(standard_popup_hint_line()), items, ..Default::default() }); @@ -1879,7 +1879,7 @@ impl ChatWidget { self.bottom_pane.show_selection_view(SelectionViewParams { title: Some("Select a base branch".to_string()), - footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), + footer_hint: Some(standard_popup_hint_line()), items, is_searchable: true, search_placeholder: Some("Type to search branches".to_string()), @@ -1920,7 +1920,7 @@ impl ChatWidget { self.bottom_pane.show_selection_view(SelectionViewParams { title: Some("Select a commit to review".to_string()), - footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), + footer_hint: Some(standard_popup_hint_line()), items, is_searchable: true, search_placeholder: Some("Type to search commits".to_string()), @@ -2145,7 +2145,7 @@ pub(crate) fn show_review_commit_picker_with_entries( chat.bottom_pane.show_selection_view(SelectionViewParams { title: Some("Select a commit to review".to_string()), - footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), + footer_hint: Some(standard_popup_hint_line()), items, is_searchable: true, search_placeholder: Some("Type to search commits".to_string()), diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec.snap index 10ded3d33f..558728bd31 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec.snap @@ -13,4 +13,4 @@ expression: terminal.backend().vt100().screen().contents() rest of the session 3. Cancel Do not run the command - Press Enter to confirm or Esc to cancel + Press enter to confirm or esc to cancel diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec_no_reason.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec_no_reason.snap index c3e04bd158..53348af155 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec_no_reason.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec_no_reason.snap @@ -13,5 +13,5 @@ expression: terminal.backend() " rest of the session " " 3. Cancel Do not run the command " " " -" Press Enter to confirm or Esc to cancel " +" Press enter to confirm or esc to cancel " " " diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_patch.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_patch.snap index fd1860caf5..64fbada3be 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_patch.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_patch.snap @@ -15,5 +15,5 @@ expression: terminal.backend() "› 1. Approve Apply the proposed changes " " 2. Cancel Do not apply the changes " " " -" Press Enter to confirm or Esc to cancel " +" Press enter to confirm or esc to cancel " " " diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_running_h2.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_running_h2.snap index 5164cd455d..3b236fff13 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_running_h2.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_running_h2.snap @@ -2,5 +2,5 @@ source: tui/src/chatwidget/tests.rs expression: terminal.backend() --- -" Thinking (0s • Esc to interrupt) " +" Thinking (0s • esc to interrupt) " "› Ask Codex to do anything " diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap index e3f7f532a7..a05ef27991 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap @@ -9,7 +9,7 @@ expression: term.backend().vt100().screen().contents() └ Search Change Approved Read diff_render.rs - Investigating rendering code (0s • Esc to interrupt) + Investigating rendering code (0s • esc to interrupt) › Summarize recent commits diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_modal_exec.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_modal_exec.snap index 5beb5323a2..8b7c5838cc 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_modal_exec.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_modal_exec.snap @@ -18,7 +18,7 @@ Buffer { " rest of the session ", " 3. Cancel Do not run the command ", " ", - " Press Enter to confirm or Esc to cancel ", + " Press enter to confirm or esc to cancel ", " ", ], styles: [ @@ -37,6 +37,6 @@ Buffer { x: 34, y: 11, fg: Reset, bg: Reset, underline: Reset, modifier: DIM, x: 56, y: 11, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, x: 2, y: 13, fg: Reset, bg: Reset, underline: Reset, modifier: DIM, - x: 41, y: 13, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, + x: 0, y: 14, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, ] } diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_active.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_active.snap index e4ae90ba90..465774602c 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_active.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_active.snap @@ -3,7 +3,7 @@ source: tui/src/chatwidget/tests.rs expression: terminal.backend() --- " " -" Analyzing (0s • Esc to interrupt) " +" Analyzing (0s • esc to interrupt) " " " " " "› Ask Codex to do anything " diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_and_approval_modal.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_and_approval_modal.snap index 86d89b80f5..96b51f7a36 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_and_approval_modal.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_and_approval_modal.snap @@ -15,5 +15,5 @@ expression: terminal.backend() " rest of the session " " 3. Cancel Do not run the command " " " -" Press Enter to confirm or Esc to cancel " +" Press enter to confirm or esc to cancel " " " diff --git a/codex-rs/tui/src/key_hint.rs b/codex-rs/tui/src/key_hint.rs index f68a493e9c..b79c2a2703 100644 --- a/codex-rs/tui/src/key_hint.rs +++ b/codex-rs/tui/src/key_hint.rs @@ -1,23 +1,86 @@ +use crossterm::event::KeyCode; +use crossterm::event::KeyEvent; +use crossterm::event::KeyEventKind; +use crossterm::event::KeyModifiers; use ratatui::style::Style; use ratatui::style::Stylize; use ratatui::text::Span; -use std::fmt::Display; -#[cfg(test)] -const ALT_PREFIX: &str = "⌥"; -#[cfg(all(not(test), target_os = "macos"))] -const ALT_PREFIX: &str = "⌥"; -#[cfg(all(not(test), not(target_os = "macos")))] -const ALT_PREFIX: &str = "Alt+"; +const ALT_PREFIX: &str = "alt + "; +const CTRL_PREFIX: &str = "ctrl + "; +const SHIFT_PREFIX: &str = "shift + "; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) struct KeyBinding { + key: KeyCode, + modifiers: KeyModifiers, +} + +impl KeyBinding { + pub(crate) const fn new(key: KeyCode, modifiers: KeyModifiers) -> Self { + Self { key, modifiers } + } + + pub fn is_press(&self, event: KeyEvent) -> bool { + self.key == event.code + && self.modifiers == event.modifiers + && (event.kind == KeyEventKind::Press || event.kind == KeyEventKind::Repeat) + } +} + +pub(crate) const fn plain(key: KeyCode) -> KeyBinding { + KeyBinding::new(key, KeyModifiers::NONE) +} + +pub(crate) const fn alt(key: KeyCode) -> KeyBinding { + KeyBinding::new(key, KeyModifiers::ALT) +} + +pub(crate) const fn shift(key: KeyCode) -> KeyBinding { + KeyBinding::new(key, KeyModifiers::SHIFT) +} + +pub(crate) const fn ctrl(key: KeyCode) -> KeyBinding { + KeyBinding::new(key, KeyModifiers::CONTROL) +} + +fn modifiers_to_string(modifiers: KeyModifiers) -> String { + let mut result = String::new(); + if modifiers.contains(KeyModifiers::CONTROL) { + result.push_str(CTRL_PREFIX); + } + if modifiers.contains(KeyModifiers::SHIFT) { + result.push_str(SHIFT_PREFIX); + } + if modifiers.contains(KeyModifiers::ALT) { + result.push_str(ALT_PREFIX); + } + result +} + +impl From for Span<'static> { + fn from(binding: KeyBinding) -> Self { + (&binding).into() + } +} +impl From<&KeyBinding> for Span<'static> { + fn from(binding: &KeyBinding) -> Self { + let KeyBinding { key, modifiers } = binding; + let modifiers = modifiers_to_string(*modifiers); + let key = match key { + KeyCode::Enter => "enter".to_string(), + KeyCode::Up => "↑".to_string(), + KeyCode::Down => "↓".to_string(), + KeyCode::Left => "←".to_string(), + KeyCode::Right => "→".to_string(), + KeyCode::PageUp => "pgup".to_string(), + KeyCode::PageDown => "pgdn".to_string(), + _ => format!("{key}").to_ascii_lowercase(), + }; + Span::styled(format!("{modifiers}{key}"), key_hint_style()) + } +} fn key_hint_style() -> Style { - Style::default().bold() -} - -fn modifier_span(prefix: &str, key: impl Display) -> Span<'static> { - Span::styled(format!("{prefix}{key}"), key_hint_style()) -} - -pub(crate) fn alt(key: impl Display) -> Span<'static> { - modifier_span(ALT_PREFIX, key) + Style::default().dim() } diff --git a/codex-rs/tui/src/pager_overlay.rs b/codex-rs/tui/src/pager_overlay.rs index 6a0562fe82..7997625aae 100644 --- a/codex-rs/tui/src/pager_overlay.rs +++ b/codex-rs/tui/src/pager_overlay.rs @@ -3,18 +3,16 @@ use std::sync::Arc; use std::time::Duration; use crate::history_cell::HistoryCell; +use crate::key_hint; +use crate::key_hint::KeyBinding; use crate::render::renderable::Renderable; use crate::tui; use crate::tui::TuiEvent; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; -use crossterm::event::KeyEventKind; use ratatui::buffer::Buffer; use ratatui::buffer::Cell; use ratatui::layout::Rect; -use ratatui::style::Color; -use ratatui::style::Style; -use ratatui::style::Styled; use ratatui::style::Stylize; use ratatui::text::Line; use ratatui::text::Span; @@ -61,23 +59,40 @@ impl Overlay { } } +const KEY_UP: KeyBinding = key_hint::plain(KeyCode::Up); +const KEY_DOWN: KeyBinding = key_hint::plain(KeyCode::Down); +const KEY_PAGE_UP: KeyBinding = key_hint::plain(KeyCode::PageUp); +const KEY_PAGE_DOWN: KeyBinding = key_hint::plain(KeyCode::PageDown); +const KEY_SPACE: KeyBinding = key_hint::plain(KeyCode::Char(' ')); +const KEY_HOME: KeyBinding = key_hint::plain(KeyCode::Home); +const KEY_END: KeyBinding = key_hint::plain(KeyCode::End); +const KEY_Q: KeyBinding = key_hint::plain(KeyCode::Char('q')); +const KEY_ESC: KeyBinding = key_hint::plain(KeyCode::Esc); +const KEY_ENTER: KeyBinding = key_hint::plain(KeyCode::Enter); +const KEY_CTRL_T: KeyBinding = key_hint::ctrl(KeyCode::Char('t')); +const KEY_CTRL_C: KeyBinding = key_hint::ctrl(KeyCode::Char('c')); + // Common pager navigation hints rendered on the first line -const PAGER_KEY_HINTS: &[(&str, &str)] = &[ - ("↑/↓", "scroll"), - ("PgUp/PgDn", "page"), - ("Home/End", "jump"), +const PAGER_KEY_HINTS: &[(&[KeyBinding], &str)] = &[ + (&[KEY_UP, KEY_DOWN], "to scroll"), + (&[KEY_PAGE_UP, KEY_PAGE_DOWN], "to page"), + (&[KEY_HOME, KEY_END], "to jump"), ]; -// Render a single line of key hints from (key, description) pairs. -fn render_key_hints(area: Rect, buf: &mut Buffer, pairs: &[(&str, &str)]) { - let key_hint_style = Style::default().fg(Color::Cyan); +// Render a single line of key hints from (key(s), description) pairs. +fn render_key_hints(area: Rect, buf: &mut Buffer, pairs: &[(&[KeyBinding], &str)]) { let mut spans: Vec> = vec![" ".into()]; let mut first = true; - for (key, desc) in pairs { + for (keys, desc) in pairs { if !first { spans.push(" ".into()); } - spans.push(Span::from(key.to_string()).set_style(key_hint_style)); + for (i, key) in keys.iter().enumerate() { + if i > 0 { + spans.push("/".into()); + } + spans.push(Span::from(key)); + } spans.push(" ".into()); spans.push(Span::from(desc.to_string())); first = false; @@ -214,48 +229,24 @@ impl PagerView { fn handle_key_event(&mut self, tui: &mut tui::Tui, key_event: KeyEvent) -> Result<()> { match key_event { - KeyEvent { - code: KeyCode::Up, - kind: KeyEventKind::Press | KeyEventKind::Repeat, - .. - } => { + e if KEY_UP.is_press(e) => { self.scroll_offset = self.scroll_offset.saturating_sub(1); } - KeyEvent { - code: KeyCode::Down, - kind: KeyEventKind::Press | KeyEventKind::Repeat, - .. - } => { + e if KEY_DOWN.is_press(e) => { self.scroll_offset = self.scroll_offset.saturating_add(1); } - KeyEvent { - code: KeyCode::PageUp, - kind: KeyEventKind::Press | KeyEventKind::Repeat, - .. - } => { + e if KEY_PAGE_UP.is_press(e) => { let area = self.content_area(tui.terminal.viewport_area); self.scroll_offset = self.scroll_offset.saturating_sub(area.height as usize); } - KeyEvent { - code: KeyCode::PageDown | KeyCode::Char(' '), - kind: KeyEventKind::Press | KeyEventKind::Repeat, - .. - } => { + e if KEY_PAGE_DOWN.is_press(e) || KEY_SPACE.is_press(e) => { let area = self.content_area(tui.terminal.viewport_area); self.scroll_offset = self.scroll_offset.saturating_add(area.height as usize); } - KeyEvent { - code: KeyCode::Home, - kind: KeyEventKind::Press | KeyEventKind::Repeat, - .. - } => { + e if KEY_HOME.is_press(e) => { self.scroll_offset = 0; } - KeyEvent { - code: KeyCode::End, - kind: KeyEventKind::Press | KeyEventKind::Repeat, - .. - } => { + e if KEY_END.is_press(e) => { self.scroll_offset = usize::MAX; } _ => { @@ -434,9 +425,11 @@ impl TranscriptOverlay { let line1 = Rect::new(area.x, area.y, area.width, 1); let line2 = Rect::new(area.x, area.y.saturating_add(1), area.width, 1); render_key_hints(line1, buf, PAGER_KEY_HINTS); - let mut pairs: Vec<(&str, &str)> = vec![("q", "quit"), ("Esc", "edit prev")]; + + let mut pairs: Vec<(&[KeyBinding], &str)> = + vec![(&[KEY_Q], "to quit"), (&[KEY_ESC], "to edit prev")]; if self.highlight_cell.is_some() { - pairs.push(("⏎", "edit message")); + pairs.push((&[KEY_ENTER], "to edit message")); } render_key_hints(line2, buf, &pairs); } @@ -454,23 +447,7 @@ impl TranscriptOverlay { pub(crate) fn handle_event(&mut self, tui: &mut tui::Tui, event: TuiEvent) -> Result<()> { match event { TuiEvent::Key(key_event) => match key_event { - KeyEvent { - code: KeyCode::Char('q'), - kind: KeyEventKind::Press, - .. - } - | KeyEvent { - code: KeyCode::Char('t'), - modifiers: crossterm::event::KeyModifiers::CONTROL, - kind: KeyEventKind::Press, - .. - } - | KeyEvent { - code: KeyCode::Char('c'), - modifiers: crossterm::event::KeyModifiers::CONTROL, - kind: KeyEventKind::Press, - .. - } => { + e if KEY_Q.is_press(e) || KEY_CTRL_C.is_press(e) || KEY_CTRL_T.is_press(e) => { self.is_done = true; Ok(()) } @@ -516,7 +493,7 @@ impl StaticOverlay { let line1 = Rect::new(area.x, area.y, area.width, 1); let line2 = Rect::new(area.x, area.y.saturating_add(1), area.width, 1); render_key_hints(line1, buf, PAGER_KEY_HINTS); - let pairs = [("q", "quit")]; + let pairs: Vec<(&[KeyBinding], &str)> = vec![(&[KEY_Q], "to quit")]; render_key_hints(line2, buf, &pairs); } @@ -533,17 +510,7 @@ impl StaticOverlay { pub(crate) fn handle_event(&mut self, tui: &mut tui::Tui, event: TuiEvent) -> Result<()> { match event { TuiEvent::Key(key_event) => match key_event { - KeyEvent { - code: KeyCode::Char('q'), - kind: KeyEventKind::Press, - .. - } - | KeyEvent { - code: KeyCode::Char('c'), - modifiers: crossterm::event::KeyModifiers::CONTROL, - kind: KeyEventKind::Press, - .. - } => { + e if KEY_Q.is_press(e) || KEY_CTRL_C.is_press(e) => { self.is_done = true; Ok(()) } diff --git a/codex-rs/tui/src/resume_picker.rs b/codex-rs/tui/src/resume_picker.rs index 9a8e8f408a..ded7d41afc 100644 --- a/codex-rs/tui/src/resume_picker.rs +++ b/codex-rs/tui/src/resume_picker.rs @@ -24,6 +24,7 @@ use tokio_stream::StreamExt; use tokio_stream::wrappers::UnboundedReceiverStream; use unicode_width::UnicodeWidthStr; +use crate::key_hint; use crate::text_formatting::truncate_text; use crate::tui::FrameRequester; use crate::tui::Tui; @@ -678,16 +679,18 @@ fn draw_picker(tui: &mut Tui, state: &PickerState) -> std::io::Result<()> { // Hint line let hint_line: Line = vec![ - "Enter".bold(), - " to resume ".into(), - "• ".dim(), - "Esc".bold(), - " to start new ".into(), - "• ".dim(), - "Ctrl+C".into(), - " to quit ".into(), - "• ".dim(), - "↑/↓".into(), + key_hint::plain(KeyCode::Enter).into(), + " to resume ".dim(), + " ".dim(), + key_hint::plain(KeyCode::Esc).into(), + " to start new ".dim(), + " ".dim(), + key_hint::ctrl(KeyCode::Char('c')).into(), + " to quit ".dim(), + " ".dim(), + key_hint::plain(KeyCode::Up).into(), + "/".dim(), + key_hint::plain(KeyCode::Down).into(), " to browse".dim(), ] .into(); diff --git a/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__static_overlay_snapshot_basic.snap b/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__static_overlay_snapshot_basic.snap index ee65b04d73..bc7818aff9 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__static_overlay_snapshot_basic.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__static_overlay_snapshot_basic.snap @@ -9,6 +9,6 @@ expression: term.backend() "~ " "~ " "───────────────────────────────── 100% ─" -" ↑/↓ scroll PgUp/PgDn page Home/End " -" q quit " +" ↑/↓ to scroll pgup/pgdn to page hom" +" q to quit " " " diff --git a/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_apply_patch_scroll_vt100.snap b/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_apply_patch_scroll_vt100.snap index df5f17adc7..7beca4a4c2 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_apply_patch_scroll_vt100.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_apply_patch_scroll_vt100.snap @@ -11,5 +11,5 @@ expression: snapshot 1 +hello 2 +world ─────────────────────────────────────────────────────────────────────────── 0% ─ - ↑/↓ scroll PgUp/PgDn page Home/End jump - q quit Esc edit prev + ↑/↓ to scroll pgup/pgdn to page home/end to jump + q to quit esc to edit prev diff --git a/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_snapshot_basic.snap b/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_snapshot_basic.snap index 0c03edef47..61fcf7d2ea 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_snapshot_basic.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_snapshot_basic.snap @@ -9,6 +9,6 @@ expression: term.backend() " " "gamma " "───────────────────────────────── 100% ─" -" ↑/↓ scroll PgUp/PgDn page Home/End " -" q quit Esc edit prev " +" ↑/↓ to scroll pgup/pgdn to page hom" +" q to quit esc to edit prev " " " diff --git a/codex-rs/tui/src/snapshots/codex_tui__status_indicator_widget__tests__renders_truncated.snap b/codex-rs/tui/src/snapshots/codex_tui__status_indicator_widget__tests__renders_truncated.snap index 6aa3401770..95dbc33bb2 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__status_indicator_widget__tests__renders_truncated.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__status_indicator_widget__tests__renders_truncated.snap @@ -2,5 +2,5 @@ source: tui/src/status_indicator_widget.rs expression: terminal.backend() --- -" Working (0s • Esc " +" Working (0s • esc " " " diff --git a/codex-rs/tui/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_queued_messages.snap b/codex-rs/tui/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_queued_messages.snap index 061f3a1393..7df7e5de75 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_queued_messages.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_queued_messages.snap @@ -2,11 +2,11 @@ source: tui/src/status_indicator_widget.rs expression: terminal.backend() --- -" Working (0s • Esc to interrupt) " +" Working (0s • esc to interrupt) " " " " ↳ first " " ↳ second " -" ⌥↑ edit " +" alt + ↑ edit " " " " " " " diff --git a/codex-rs/tui/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_working_header.snap b/codex-rs/tui/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_working_header.snap index debf282118..c02e83263d 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_working_header.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_working_header.snap @@ -2,5 +2,5 @@ source: tui/src/status_indicator_widget.rs expression: terminal.backend() --- -" Working (0s • Esc to interrupt) " +" Working (0s • esc to interrupt) " " " diff --git a/codex-rs/tui/src/status_indicator_widget.rs b/codex-rs/tui/src/status_indicator_widget.rs index afb7952069..caf15b2882 100644 --- a/codex-rs/tui/src/status_indicator_widget.rs +++ b/codex-rs/tui/src/status_indicator_widget.rs @@ -5,6 +5,7 @@ use std::time::Duration; use std::time::Instant; use codex_core::protocol::Op; +use crossterm::event::KeyCode; use ratatui::buffer::Buffer; use ratatui::layout::Rect; use ratatui::style::Stylize; @@ -164,7 +165,7 @@ impl WidgetRef for StatusIndicatorWidget { spans.extend(vec![ " ".into(), format!("({pretty_elapsed} • ").dim(), - "Esc".dim().bold(), + key_hint::plain(KeyCode::Esc).into(), " to interrupt)".dim(), ]); @@ -188,8 +189,14 @@ impl WidgetRef for StatusIndicatorWidget { } } if !self.queued_messages.is_empty() { - let shortcut = key_hint::alt("↑"); - lines.push(Line::from(vec![" ".into(), shortcut, " edit".into()]).dim()); + lines.push( + Line::from(vec![ + " ".into(), + key_hint::alt(KeyCode::Up).into(), + " edit".into(), + ]) + .dim(), + ); } let paragraph = Paragraph::new(lines); From 45936f8fbd761dbeaf75c8357d29dc89d53b9dc6 Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Thu, 2 Oct 2025 11:36:03 -0700 Subject: [PATCH 15/20] show "Viewed Image" when the model views an image (#4475) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Screenshot 2025-09-29 at 4 22 00 PM --- codex-rs/core/src/codex.rs | 11 +++++++++- codex-rs/core/src/rollout/policy.rs | 1 + .../src/event_processor_with_human_output.rs | 8 ++++++++ codex-rs/mcp-server/src/codex_tool_runner.rs | 1 + codex-rs/protocol/src/protocol.rs | 11 ++++++++++ codex-rs/tui/src/chatwidget.rs | 11 ++++++++++ ...cal_image_attachment_history_snapshot.snap | 6 ++++++ codex-rs/tui/src/chatwidget/tests.rs | 20 +++++++++++++++++++ codex-rs/tui/src/diff_render.rs | 4 +++- codex-rs/tui/src/history_cell.rs | 12 +++++++++++ 10 files changed, 83 insertions(+), 2 deletions(-) create mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__local_image_attachment_history_snapshot.snap diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 9f6b02a556..3114fc30f8 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -109,6 +109,7 @@ use crate::protocol::Submission; use crate::protocol::TokenCountEvent; use crate::protocol::TokenUsage; use crate::protocol::TurnDiffEvent; +use crate::protocol::ViewImageToolCallEvent; use crate::protocol::WebSearchBeginEvent; use crate::rollout::RolloutRecorder; use crate::rollout::RolloutRecorderParams; @@ -2469,13 +2470,21 @@ async fn handle_function_call( )) })?; let abs = turn_context.resolve_path(Some(args.path)); - sess.inject_input(vec![InputItem::LocalImage { path: abs }]) + sess.inject_input(vec![InputItem::LocalImage { path: abs.clone() }]) .await .map_err(|_| { FunctionCallError::RespondToModel( "unable to attach image (no active task)".to_string(), ) })?; + sess.send_event(Event { + id: sub_id.clone(), + msg: EventMsg::ViewImageToolCall(ViewImageToolCallEvent { + call_id: call_id.clone(), + path: abs, + }), + }) + .await; Ok("attached local image path".to_string()) } diff --git a/codex-rs/core/src/rollout/policy.rs b/codex-rs/core/src/rollout/policy.rs index 2fd0efb0dc..8fc39e79f5 100644 --- a/codex-rs/core/src/rollout/policy.rs +++ b/codex-rs/core/src/rollout/policy.rs @@ -70,6 +70,7 @@ pub(crate) fn should_persist_event_msg(ev: &EventMsg) -> bool { | EventMsg::ListCustomPromptsResponse(_) | EventMsg::PlanUpdate(_) | EventMsg::ShutdownComplete + | EventMsg::ViewImageToolCall(_) | EventMsg::ConversationPath(_) => false, } } diff --git a/codex-rs/exec/src/event_processor_with_human_output.rs b/codex-rs/exec/src/event_processor_with_human_output.rs index 4f231bab84..72c31c2979 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -580,6 +580,14 @@ impl EventProcessor for EventProcessorWithHumanOutput { EventMsg::ListCustomPromptsResponse(_) => { // Currently ignored in exec output. } + EventMsg::ViewImageToolCall(view) => { + ts_println!( + self, + "{} {}", + "viewed image".style(self.magenta), + view.path.display() + ); + } EventMsg::TurnAborted(abort_reason) => match abort_reason.reason { TurnAbortReason::Interrupted => { ts_println!(self, "task interrupted"); diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index bcbfdf4471..f09dc98cbc 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -280,6 +280,7 @@ async fn run_codex_tool_session_inner( | EventMsg::ConversationPath(_) | EventMsg::UserMessage(_) | EventMsg::ShutdownComplete + | EventMsg::ViewImageToolCall(_) | EventMsg::EnteredReviewMode(_) | EventMsg::ExitedReviewMode(_) => { // For now, we do not do anything extra for these diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 98e218b962..17a4a844b8 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -477,6 +477,9 @@ pub enum EventMsg { ExecCommandEnd(ExecCommandEndEvent), + /// Notification that the agent attached a local image via the view_image tool. + ViewImageToolCall(ViewImageToolCallEvent), + ExecApprovalRequest(ExecApprovalRequestEvent), ApplyPatchApprovalRequest(ApplyPatchApprovalRequestEvent), @@ -1074,6 +1077,14 @@ pub struct ExecCommandEndEvent { pub formatted_output: String, } +#[derive(Debug, Clone, Deserialize, Serialize, TS)] +pub struct ViewImageToolCallEvent { + /// Identifier for the originating tool call. + pub call_id: String, + /// Local filesystem path provided to the tool. + pub path: PathBuf, +} + #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, TS)] #[serde(rename_all = "snake_case")] pub enum ExecOutputStream { diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 32566b3ecd..48382354f6 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -39,6 +39,7 @@ use codex_core::protocol::TokenUsageInfo; use codex_core::protocol::TurnAbortReason; use codex_core::protocol::TurnDiffEvent; use codex_core::protocol::UserMessageEvent; +use codex_core::protocol::ViewImageToolCallEvent; use codex_core::protocol::WebSearchBeginEvent; use codex_core::protocol::WebSearchEndEvent; use codex_protocol::ConversationId; @@ -538,6 +539,15 @@ impl ChatWidget { )); } + fn on_view_image_tool_call(&mut self, event: ViewImageToolCallEvent) { + self.flush_answer_stream_with_separator(); + self.add_to_history(history_cell::new_view_image_tool_call( + event.path, + &self.config.cwd, + )); + self.request_redraw(); + } + fn on_patch_apply_end(&mut self, event: codex_core::protocol::PatchApplyEndEvent) { let ev2 = event.clone(); self.defer_or_handle( @@ -1398,6 +1408,7 @@ impl ChatWidget { EventMsg::PatchApplyBegin(ev) => self.on_patch_apply_begin(ev), EventMsg::PatchApplyEnd(ev) => self.on_patch_apply_end(ev), EventMsg::ExecCommandEnd(ev) => self.on_exec_command_end(ev), + EventMsg::ViewImageToolCall(ev) => self.on_view_image_tool_call(ev), EventMsg::McpToolCallBegin(ev) => self.on_mcp_tool_call_begin(ev), EventMsg::McpToolCallEnd(ev) => self.on_mcp_tool_call_end(ev), EventMsg::WebSearchBegin(ev) => self.on_web_search_begin(ev), diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__local_image_attachment_history_snapshot.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__local_image_attachment_history_snapshot.snap new file mode 100644 index 0000000000..cf4c6943fd --- /dev/null +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__local_image_attachment_history_snapshot.snap @@ -0,0 +1,6 @@ +--- +source: tui/src/chatwidget/tests.rs +expression: combined +--- +• Viewed Image + └ example.png diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 77cde195c5..e175e180b9 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -35,6 +35,7 @@ use codex_core::protocol::ReviewRequest; use codex_core::protocol::StreamErrorEvent; use codex_core::protocol::TaskCompleteEvent; use codex_core::protocol::TaskStartedEvent; +use codex_core::protocol::ViewImageToolCallEvent; use codex_protocol::ConversationId; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; @@ -794,6 +795,25 @@ fn custom_prompt_enter_empty_does_not_send() { assert!(rx.try_recv().is_err(), "no app event should be sent"); } +#[test] +fn view_image_tool_call_adds_history_cell() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(); + let image_path = chat.config.cwd.join("example.png"); + + chat.handle_codex_event(Event { + id: "sub-image".into(), + msg: EventMsg::ViewImageToolCall(ViewImageToolCallEvent { + call_id: "call-image".into(), + path: image_path, + }), + }); + + let cells = drain_insert_history(&mut rx); + assert_eq!(cells.len(), 1, "expected a single history cell"); + let combined = lines_to_single_string(&cells[0]); + assert_snapshot!("local_image_attachment_history_snapshot", combined); +} + // Snapshot test: interrupting a running exec finalizes the active cell with a red ✗ // marker (replacing the spinner) and flushes it into history. #[test] diff --git a/codex-rs/tui/src/diff_render.rs b/codex-rs/tui/src/diff_render.rs index 033fd09240..6f133feeb5 100644 --- a/codex-rs/tui/src/diff_render.rs +++ b/codex-rs/tui/src/diff_render.rs @@ -268,7 +268,9 @@ pub(crate) fn display_path_for(path: &Path, cwd: &Path) -> String { let chosen = if path_in_same_repo { pathdiff::diff_paths(path, cwd).unwrap_or_else(|| path.to_path_buf()) } else { - relativize_to_home(path).unwrap_or_else(|| path.to_path_buf()) + relativize_to_home(path) + .map(|p| PathBuf::from_iter([Path::new("~"), p.as_path()])) + .unwrap_or_else(|| path.to_path_buf()) }; chosen.display().to_string() } diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 4121a98397..4bab8afb70 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -1,4 +1,5 @@ use crate::diff_render::create_diff_summary; +use crate::diff_render::display_path_for; use crate::exec_cell::CommandOutput; use crate::exec_cell::OutputLinesParams; use crate::exec_cell::TOOL_CALL_MAX_LINES; @@ -1037,6 +1038,17 @@ pub(crate) fn new_patch_apply_failure(stderr: String) -> PlainHistoryCell { PlainHistoryCell { lines } } +pub(crate) fn new_view_image_tool_call(path: PathBuf, cwd: &Path) -> PlainHistoryCell { + let display_path = display_path_for(&path, cwd); + + let lines: Vec> = vec![ + vec!["• ".dim(), "Viewed Image".bold()].into(), + vec![" └ ".dim(), display_path.dim()].into(), + ]; + + PlainHistoryCell { lines } +} + pub(crate) fn new_reasoning_block( full_reasoning_buffer: String, config: &Config, From 06e34d4607ce4b2c03b21539f1e9577bdc5cc13a Mon Sep 17 00:00:00 2001 From: easong-openai Date: Thu, 2 Oct 2025 12:38:24 -0700 Subject: [PATCH 16/20] Make model switcher two-stage (#4178) https://github.com/user-attachments/assets/16d5c67c-e580-4a29-983c-a315f95424ee --- codex-rs/common/src/model_presets.rs | 14 +- codex-rs/tui/src/app.rs | 16 +- codex-rs/tui/src/app_event.rs | 7 + codex-rs/tui/src/chatwidget.rs | 194 ++++++++++++++---- ...ests__model_reasoning_selection_popup.snap | 13 ++ ...twidget__tests__model_selection_popup.snap | 12 ++ codex-rs/tui/src/chatwidget/tests.rs | 59 ++++++ 7 files changed, 265 insertions(+), 50 deletions(-) create mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup.snap create mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_selection_popup.snap diff --git a/codex-rs/common/src/model_presets.rs b/codex-rs/common/src/model_presets.rs index 68acb5ce90..9954ad1890 100644 --- a/codex-rs/common/src/model_presets.rs +++ b/codex-rs/common/src/model_presets.rs @@ -20,49 +20,49 @@ const PRESETS: &[ModelPreset] = &[ ModelPreset { id: "gpt-5-codex-low", label: "gpt-5-codex low", - description: "", + description: "Fastest responses with limited reasoning", model: "gpt-5-codex", effort: Some(ReasoningEffort::Low), }, ModelPreset { id: "gpt-5-codex-medium", label: "gpt-5-codex medium", - description: "", + description: "Dynamically adjusts reasoning based on the task", model: "gpt-5-codex", effort: Some(ReasoningEffort::Medium), }, ModelPreset { id: "gpt-5-codex-high", label: "gpt-5-codex high", - description: "", + description: "Maximizes reasoning depth for complex or ambiguous problems", model: "gpt-5-codex", effort: Some(ReasoningEffort::High), }, ModelPreset { id: "gpt-5-minimal", label: "gpt-5 minimal", - description: "— fastest responses with limited reasoning; ideal for coding, instructions, or lightweight tasks", + description: "Fastest responses with little reasoning", model: "gpt-5", effort: Some(ReasoningEffort::Minimal), }, ModelPreset { id: "gpt-5-low", label: "gpt-5 low", - description: "— balances speed with some reasoning; useful for straightforward queries and short explanations", + description: "Balances speed with some reasoning; useful for straightforward queries and short explanations", model: "gpt-5", effort: Some(ReasoningEffort::Low), }, ModelPreset { id: "gpt-5-medium", label: "gpt-5 medium", - description: "— default setting; provides a solid balance of reasoning depth and latency for general-purpose tasks", + description: "Provides a solid balance of reasoning depth and latency for general-purpose tasks", model: "gpt-5", effort: Some(ReasoningEffort::Medium), }, ModelPreset { id: "gpt-5-high", label: "gpt-5 high", - description: "— maximizes reasoning depth for complex or ambiguous problems", + description: "Maximizes reasoning depth for complex or ambiguous problems", model: "gpt-5", effort: Some(ReasoningEffort::High), }, diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 383e5cae54..ab43ceb0a3 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -320,24 +320,28 @@ impl App { self.config.model_family = family; } } + AppEvent::OpenReasoningPopup { model, presets } => { + self.chat_widget.open_reasoning_popup(model, presets); + } AppEvent::PersistModelSelection { model, effort } => { let profile = self.active_profile.as_deref(); match persist_model_selection(&self.config.codex_home, profile, &model, effort) .await { Ok(()) => { + let effort_label = effort + .map(|eff| format!(" with {eff} reasoning")) + .unwrap_or_else(|| " with default reasoning".to_string()); if let Some(profile) = profile { self.chat_widget.add_info_message( - format!("Model changed to {model}{reasoning_effort} for {profile} profile", reasoning_effort = effort.map(|e| format!(" {e}")).unwrap_or_default()), + format!( + "Model changed to {model}{effort_label} for {profile} profile" + ), None, ); } else { self.chat_widget.add_info_message( - format!( - "Model changed to {model}{reasoning_effort}", - reasoning_effort = - effort.map(|e| format!(" {e}")).unwrap_or_default() - ), + format!("Model changed to {model}{effort_label}"), None, ); } diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 9c8a71de2e..9d79c8ae13 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -1,5 +1,6 @@ use std::path::PathBuf; +use codex_common::model_presets::ModelPreset; use codex_core::protocol::ConversationPathResponseEvent; use codex_core::protocol::Event; use codex_file_search::FileMatch; @@ -60,6 +61,12 @@ pub(crate) enum AppEvent { effort: Option, }, + /// Open the reasoning selection popup after picking a model. + OpenReasoningPopup { + model: String, + presets: Vec, + }, + /// Update the current approval policy in the running app and widget. UpdateAskForApprovalPolicy(AskForApproval), diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 48382354f6..c03caca85c 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -1,3 +1,4 @@ +use std::collections::BTreeMap; use std::collections::HashMap; use std::collections::VecDeque; use std::path::PathBuf; @@ -111,6 +112,7 @@ use codex_git_tooling::GhostCommit; use codex_git_tooling::GitToolingError; use codex_git_tooling::create_ghost_commit; use codex_git_tooling::restore_ghost_commit; +use strum::IntoEnumIterator; const MAX_TRACKED_GHOST_COMMITS: usize = 20; @@ -283,6 +285,16 @@ fn create_initial_user_message(text: String, image_paths: Vec) -> Optio } impl ChatWidget { + fn model_description_for(slug: &str) -> Option<&'static str> { + if slug.starts_with("gpt-5-codex") { + Some("Optimized for coding tasks with many tools.") + } else if slug.starts_with("gpt-5") { + Some("Broad world knowledge with strong general reasoning.") + } else { + None + } + } + fn flush_answer_stream_with_separator(&mut self) { if let Some(mut controller) = self.stream_controller.take() && let Some(cell) = controller.finalize() @@ -1579,47 +1591,38 @@ impl ChatWidget { )); } - /// Open a popup to choose the model preset (model + reasoning effort). + /// Open a popup to choose the model (stage 1). After selecting a model, + /// a second popup is shown to choose the reasoning effort. pub(crate) fn open_model_popup(&mut self) { let current_model = self.config.model.clone(); - let current_effort = self.config.model_reasoning_effort; let auth_mode = self.auth_manager.auth().map(|auth| auth.mode); let presets: Vec = builtin_model_presets(auth_mode); + let mut grouped: BTreeMap<&str, Vec> = BTreeMap::new(); + for preset in presets.into_iter() { + grouped.entry(preset.model).or_default().push(preset); + } + let mut items: Vec = Vec::new(); - for preset in presets.iter() { - let name = preset.label.to_string(); - let description = Some(preset.description.to_string()); - let is_current = preset.model == current_model && preset.effort == current_effort; - let model_slug = preset.model.to_string(); - let effort = preset.effort; - let current_model = current_model.clone(); + for (model_slug, entries) in grouped.into_iter() { + let name = model_slug.to_string(); + let description = Self::model_description_for(model_slug) + .map(std::string::ToString::to_string) + .or_else(|| { + entries + .iter() + .find(|preset| !preset.description.is_empty()) + .map(|preset| preset.description.to_string()) + }) + .or_else(|| entries.first().map(|preset| preset.description.to_string())); + let is_current = model_slug == current_model; + let model_slug_string = model_slug.to_string(); + let presets_for_model = entries.clone(); let actions: Vec = vec![Box::new(move |tx| { - tx.send(AppEvent::CodexOp(Op::OverrideTurnContext { - cwd: None, - approval_policy: None, - sandbox_policy: None, - model: Some(model_slug.clone()), - effort: Some(effort), - summary: None, - })); - tx.send(AppEvent::UpdateModel(model_slug.clone())); - tx.send(AppEvent::UpdateReasoningEffort(effort)); - tx.send(AppEvent::PersistModelSelection { - model: model_slug.clone(), - effort, + tx.send(AppEvent::OpenReasoningPopup { + model: model_slug_string.clone(), + presets: presets_for_model.clone(), }); - tracing::info!( - "New model: {}, New effort: {}, Current model: {}, Current effort: {}", - model_slug.clone(), - effort - .map(|effort| effort.to_string()) - .unwrap_or_else(|| "none".to_string()), - current_model, - current_effort - .map(|effort| effort.to_string()) - .unwrap_or_else(|| "none".to_string()) - ); })]; items.push(SelectionItem { name, @@ -1632,10 +1635,127 @@ impl ChatWidget { } self.bottom_pane.show_selection_view(SelectionViewParams { - title: Some("Select model and reasoning level".to_string()), - subtitle: Some( - "Switch between OpenAI models for this and future Codex CLI session".to_string(), - ), + title: Some("Select Model".to_string()), + subtitle: Some("Switch the model for this and future Codex CLI sessions".to_string()), + footer_hint: Some(standard_popup_hint_line()), + items, + ..Default::default() + }); + } + + /// Open a popup to choose the reasoning effort (stage 2) for the given model. + pub(crate) fn open_reasoning_popup(&mut self, model_slug: String, presets: Vec) { + let default_effort = ReasoningEffortConfig::default(); + + let has_none_choice = presets.iter().any(|preset| preset.effort.is_none()); + struct EffortChoice { + stored: Option, + display: ReasoningEffortConfig, + } + let mut choices: Vec = Vec::new(); + for effort in ReasoningEffortConfig::iter() { + if presets.iter().any(|preset| preset.effort == Some(effort)) { + choices.push(EffortChoice { + stored: Some(effort), + display: effort, + }); + } + if has_none_choice && default_effort == effort { + choices.push(EffortChoice { + stored: None, + display: effort, + }); + } + } + if choices.is_empty() { + choices.push(EffortChoice { + stored: Some(default_effort), + display: default_effort, + }); + } + + let default_choice: Option = if has_none_choice { + None + } else if choices + .iter() + .any(|choice| choice.stored == Some(default_effort)) + { + Some(default_effort) + } else { + choices + .iter() + .find_map(|choice| choice.stored) + .or(Some(default_effort)) + }; + + let is_current_model = self.config.model == model_slug; + let highlight_choice = if is_current_model { + self.config.model_reasoning_effort + } else { + default_choice + }; + + let mut items: Vec = Vec::new(); + for choice in choices.iter() { + let effort = choice.display; + let mut effort_label = effort.to_string(); + if let Some(first) = effort_label.get_mut(0..1) { + first.make_ascii_uppercase(); + } + if choice.stored == default_choice { + effort_label.push_str(" (default)"); + } + + let description = presets + .iter() + .find(|preset| preset.effort == choice.stored && !preset.description.is_empty()) + .map(|preset| preset.description.to_string()) + .or_else(|| { + presets + .iter() + .find(|preset| preset.effort == choice.stored) + .map(|preset| preset.description.to_string()) + }); + + let model_for_action = model_slug.clone(); + let effort_for_action = choice.stored; + let actions: Vec = vec![Box::new(move |tx| { + tx.send(AppEvent::CodexOp(Op::OverrideTurnContext { + cwd: None, + approval_policy: None, + sandbox_policy: None, + model: Some(model_for_action.clone()), + effort: Some(effort_for_action), + summary: None, + })); + tx.send(AppEvent::UpdateModel(model_for_action.clone())); + tx.send(AppEvent::UpdateReasoningEffort(effort_for_action)); + tx.send(AppEvent::PersistModelSelection { + model: model_for_action.clone(), + effort: effort_for_action, + }); + tracing::info!( + "Selected model: {}, Selected effort: {}", + model_for_action, + effort_for_action + .map(|e| e.to_string()) + .unwrap_or_else(|| "default".to_string()) + ); + })]; + + items.push(SelectionItem { + name: effort_label, + description, + is_current: is_current_model && choice.stored == highlight_choice, + actions, + dismiss_on_select: true, + search_value: None, + }); + } + + self.bottom_pane.show_selection_view(SelectionViewParams { + title: Some("Select Reasoning Level".to_string()), + subtitle: Some(format!("Reasoning for model {model_slug}")), footer_hint: Some(standard_popup_hint_line()), items, ..Default::default() diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup.snap new file mode 100644 index 0000000000..664ec0f50f --- /dev/null +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/chatwidget/tests.rs +expression: popup +--- + Select Reasoning Level + Reasoning for model gpt-5-codex + + 1. Low Fastest responses with limited reasoning + 2. Medium (default) Dynamically adjusts reasoning based on the task +› 3. High (current) Maximizes reasoning depth for complex or ambiguous + problems + + Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_selection_popup.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_selection_popup.snap new file mode 100644 index 0000000000..cfe99bd0a6 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_selection_popup.snap @@ -0,0 +1,12 @@ +--- +source: tui/src/chatwidget/tests.rs +expression: popup +--- + Select Model + Switch the model for this and future Codex CLI sessions + + 1. gpt-5 Broad world knowledge with strong general + reasoning. +› 2. gpt-5-codex (current) Optimized for coding tasks with many tools. + + Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index e175e180b9..64b4c72b34 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -936,6 +936,65 @@ fn render_bottom_first_row(chat: &ChatWidget, width: u16) -> String { String::new() } +fn render_bottom_popup(chat: &ChatWidget, width: u16) -> String { + let height = chat.desired_height(width); + let area = Rect::new(0, 0, width, height); + let mut buf = Buffer::empty(area); + (chat).render_ref(area, &mut buf); + + let mut lines: Vec = (0..area.height) + .map(|row| { + let mut line = String::new(); + for col in 0..area.width { + let symbol = buf[(area.x + col, area.y + row)].symbol(); + if symbol.is_empty() { + line.push(' '); + } else { + line.push_str(symbol); + } + } + line.trim_end().to_string() + }) + .collect(); + + while lines.first().is_some_and(|line| line.trim().is_empty()) { + lines.remove(0); + } + while lines.last().is_some_and(|line| line.trim().is_empty()) { + lines.pop(); + } + + lines.join("\n") +} + +#[test] +fn model_selection_popup_snapshot() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(); + + chat.config.model = "gpt-5-codex".to_string(); + chat.open_model_popup(); + + let popup = render_bottom_popup(&chat, 80); + assert_snapshot!("model_selection_popup", popup); +} + +#[test] +fn model_reasoning_selection_popup_snapshot() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(); + + chat.config.model = "gpt-5-codex".to_string(); + chat.config.model_reasoning_effort = Some(ReasoningEffortConfig::High); + + let presets = builtin_model_presets(None) + .into_iter() + .filter(|preset| preset.model == "gpt-5-codex") + .collect::>(); + chat.open_reasoning_popup("gpt-5-codex".to_string(), presets); + + let popup = render_bottom_popup(&chat, 80); + assert_snapshot!("model_reasoning_selection_popup", popup); +} + #[test] fn exec_history_extends_previous_when_consecutive() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(); From 4c566d484afc60bb9e33895810dafaa6acfe790b Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Thu, 2 Oct 2025 13:06:21 -0700 Subject: [PATCH 17/20] Separate interactive and non-interactive sessions (#4612) Do not show exec session in VSCode/TUI selector. --- .../app-server/src/codex_message_processor.rs | 2 + codex-rs/app-server/src/message_processor.rs | 6 +- codex-rs/core/src/codex.rs | 10 +- codex-rs/core/src/conversation_manager.rs | 22 +- codex-rs/core/src/lib.rs | 1 + codex-rs/core/src/rollout/list.rs | 15 +- codex-rs/core/src/rollout/mod.rs | 4 + codex-rs/core/src/rollout/recorder.rs | 14 +- codex-rs/core/src/rollout/tests.rs | 265 ++++++++++++++---- codex-rs/core/tests/suite/cli_stream.rs | 2 +- codex-rs/core/tests/suite/client.rs | 3 +- codex-rs/exec/src/lib.rs | 7 +- codex-rs/mcp-server/src/message_processor.rs | 4 +- codex-rs/protocol/src/protocol.rs | 31 +- codex-rs/tui/src/app.rs | 6 +- codex-rs/tui/src/lib.rs | 10 +- codex-rs/tui/src/resume_picker.rs | 10 +- 17 files changed, 346 insertions(+), 66 deletions(-) diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 1e5eb82ef0..c158621d2e 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -53,6 +53,7 @@ use codex_core::AuthManager; use codex_core::CodexConversation; use codex_core::ConversationManager; use codex_core::Cursor as RolloutCursor; +use codex_core::INTERACTIVE_SESSION_SOURCES; use codex_core::NewConversation; use codex_core::RolloutRecorder; use codex_core::SessionMeta; @@ -708,6 +709,7 @@ impl CodexMessageProcessor { &self.config.codex_home, page_size, cursor_ref, + INTERACTIVE_SESSION_SOURCES, ) .await { diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 9d8db2f921..15086c19e1 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -17,6 +17,7 @@ use codex_core::ConversationManager; use codex_core::config::Config; use codex_core::default_client::USER_AGENT_SUFFIX; use codex_core::default_client::get_codex_user_agent; +use codex_protocol::protocol::SessionSource; use std::sync::Arc; pub(crate) struct MessageProcessor { @@ -35,7 +36,10 @@ impl MessageProcessor { ) -> Self { let outgoing = Arc::new(outgoing); let auth_manager = AuthManager::shared(config.codex_home.clone(), false); - let conversation_manager = Arc::new(ConversationManager::new(auth_manager.clone())); + let conversation_manager = Arc::new(ConversationManager::new( + auth_manager.clone(), + SessionSource::VSCode, + )); let codex_message_processor = CodexMessageProcessor::new( auth_manager, conversation_manager, diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 3114fc30f8..2bba2b42b7 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -22,6 +22,7 @@ use codex_protocol::protocol::ConversationPathResponseEvent; use codex_protocol::protocol::ExitedReviewModeEvent; use codex_protocol::protocol::ReviewRequest; use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::TaskStartedEvent; use codex_protocol::protocol::TurnAbortReason; use codex_protocol::protocol::TurnContextItem; @@ -172,6 +173,7 @@ impl Codex { config: Config, auth_manager: Arc, conversation_history: InitialHistory, + session_source: SessionSource, ) -> CodexResult { let (tx_sub, rx_sub) = async_channel::bounded(SUBMISSION_CHANNEL_CAPACITY); let (tx_event, rx_event) = async_channel::unbounded(); @@ -200,6 +202,7 @@ impl Codex { auth_manager.clone(), tx_event.clone(), conversation_history, + session_source, ) .await .map_err(|e| { @@ -334,6 +337,7 @@ impl Session { auth_manager: Arc, tx_event: Sender, initial_history: InitialHistory, + session_source: SessionSource, ) -> anyhow::Result<(Arc, TurnContext)> { let ConfigureSession { provider, @@ -357,7 +361,11 @@ impl Session { let conversation_id = ConversationId::default(); ( conversation_id, - RolloutRecorderParams::new(conversation_id, user_instructions.clone()), + RolloutRecorderParams::new( + conversation_id, + user_instructions.clone(), + session_source, + ), ) } InitialHistory::Resumed(resumed_history) => ( diff --git a/codex-rs/core/src/conversation_manager.rs b/codex-rs/core/src/conversation_manager.rs index 73d9b658ce..150794fc8d 100644 --- a/codex-rs/core/src/conversation_manager.rs +++ b/codex-rs/core/src/conversation_manager.rs @@ -17,6 +17,7 @@ use codex_protocol::ConversationId; use codex_protocol::models::ResponseItem; use codex_protocol::protocol::InitialHistory; use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::SessionSource; use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; @@ -35,20 +36,25 @@ pub struct NewConversation { pub struct ConversationManager { conversations: Arc>>>, auth_manager: Arc, + session_source: SessionSource, } impl ConversationManager { - pub fn new(auth_manager: Arc) -> Self { + pub fn new(auth_manager: Arc, session_source: SessionSource) -> Self { Self { conversations: Arc::new(RwLock::new(HashMap::new())), auth_manager, + session_source, } } /// Construct with a dummy AuthManager containing the provided CodexAuth. /// Used for integration tests: should not be used by ordinary business logic. pub fn with_auth(auth: CodexAuth) -> Self { - Self::new(crate::AuthManager::from_auth_for_testing(auth)) + Self::new( + crate::AuthManager::from_auth_for_testing(auth), + SessionSource::Exec, + ) } pub async fn new_conversation(&self, config: Config) -> CodexResult { @@ -64,7 +70,13 @@ impl ConversationManager { let CodexSpawnOk { codex, conversation_id, - } = Codex::spawn(config, auth_manager, InitialHistory::New).await?; + } = Codex::spawn( + config, + auth_manager, + InitialHistory::New, + self.session_source, + ) + .await?; self.finalize_spawn(codex, conversation_id).await } @@ -121,7 +133,7 @@ impl ConversationManager { let CodexSpawnOk { codex, conversation_id, - } = Codex::spawn(config, auth_manager, initial_history).await?; + } = Codex::spawn(config, auth_manager, initial_history, self.session_source).await?; self.finalize_spawn(codex, conversation_id).await } @@ -155,7 +167,7 @@ impl ConversationManager { let CodexSpawnOk { codex, conversation_id, - } = Codex::spawn(config, auth_manager, history).await?; + } = Codex::spawn(config, auth_manager, history, self.session_source).await?; self.finalize_spawn(codex, conversation_id).await } diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index 4c7dfdcb3c..94350a447e 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -68,6 +68,7 @@ pub mod terminal; mod tool_apply_patch; pub mod turn_diff_tracker; pub use rollout::ARCHIVED_SESSIONS_SUBDIR; +pub use rollout::INTERACTIVE_SESSION_SOURCES; pub use rollout::RolloutRecorder; pub use rollout::SESSIONS_SUBDIR; pub use rollout::SessionMeta; diff --git a/codex-rs/core/src/rollout/list.rs b/codex-rs/core/src/rollout/list.rs index 755e63df86..b27b3382e3 100644 --- a/codex-rs/core/src/rollout/list.rs +++ b/codex-rs/core/src/rollout/list.rs @@ -17,6 +17,7 @@ use super::SESSIONS_SUBDIR; use crate::protocol::EventMsg; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::RolloutLine; +use codex_protocol::protocol::SessionSource; /// Returned page of conversation summaries. #[derive(Debug, Default, PartialEq)] @@ -52,6 +53,7 @@ struct HeadTailSummary { tail: Vec, saw_session_meta: bool, saw_user_event: bool, + source: Option, created_at: Option, updated_at: Option, } @@ -106,6 +108,7 @@ pub(crate) async fn get_conversations( codex_home: &Path, page_size: usize, cursor: Option<&Cursor>, + allowed_sources: &[SessionSource], ) -> io::Result { let mut root = codex_home.to_path_buf(); root.push(SESSIONS_SUBDIR); @@ -121,7 +124,8 @@ pub(crate) async fn get_conversations( let anchor = cursor.cloned(); - let result = traverse_directories_for_paths(root.clone(), page_size, anchor).await?; + let result = + traverse_directories_for_paths(root.clone(), page_size, anchor, allowed_sources).await?; Ok(result) } @@ -140,6 +144,7 @@ async fn traverse_directories_for_paths( root: PathBuf, page_size: usize, anchor: Option, + allowed_sources: &[SessionSource], ) -> io::Result { let mut items: Vec = Vec::with_capacity(page_size); let mut scanned_files = 0usize; @@ -196,6 +201,13 @@ async fn traverse_directories_for_paths( let summary = read_head_and_tail(&path, HEAD_RECORD_LIMIT, TAIL_RECORD_LIMIT) .await .unwrap_or_default(); + if !allowed_sources.is_empty() + && !summary + .source + .is_some_and(|source| allowed_sources.iter().any(|s| s == &source)) + { + continue; + } // Apply filters: must have session meta and at least one user message event if summary.saw_session_meta && summary.saw_user_event { let HeadTailSummary { @@ -341,6 +353,7 @@ async fn read_head_and_tail( match rollout_line.item { RolloutItem::SessionMeta(session_meta_line) => { + summary.source = Some(session_meta_line.meta.source); summary.created_at = summary .created_at .clone() diff --git a/codex-rs/core/src/rollout/mod.rs b/codex-rs/core/src/rollout/mod.rs index 3c4cb10535..23410bd4d0 100644 --- a/codex-rs/core/src/rollout/mod.rs +++ b/codex-rs/core/src/rollout/mod.rs @@ -1,7 +1,11 @@ //! Rollout module: persistence and discovery of session rollout files. +use codex_protocol::protocol::SessionSource; + pub const SESSIONS_SUBDIR: &str = "sessions"; pub const ARCHIVED_SESSIONS_SUBDIR: &str = "archived_sessions"; +pub const INTERACTIVE_SESSION_SOURCES: &[SessionSource] = + &[SessionSource::Cli, SessionSource::VSCode]; pub mod list; pub(crate) mod policy; diff --git a/codex-rs/core/src/rollout/recorder.rs b/codex-rs/core/src/rollout/recorder.rs index f67c076c04..95f5d479b8 100644 --- a/codex-rs/core/src/rollout/recorder.rs +++ b/codex-rs/core/src/rollout/recorder.rs @@ -32,6 +32,7 @@ use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::RolloutLine; use codex_protocol::protocol::SessionMeta; use codex_protocol::protocol::SessionMetaLine; +use codex_protocol::protocol::SessionSource; /// Records all [`ResponseItem`]s for a session and flushes them to disk after /// every update. @@ -53,6 +54,7 @@ pub enum RolloutRecorderParams { Create { conversation_id: ConversationId, instructions: Option, + source: SessionSource, }, Resume { path: PathBuf, @@ -71,10 +73,15 @@ enum RolloutCmd { } impl RolloutRecorderParams { - pub fn new(conversation_id: ConversationId, instructions: Option) -> Self { + pub fn new( + conversation_id: ConversationId, + instructions: Option, + source: SessionSource, + ) -> Self { Self::Create { conversation_id, instructions, + source, } } @@ -89,8 +96,9 @@ impl RolloutRecorder { codex_home: &Path, page_size: usize, cursor: Option<&Cursor>, + allowed_sources: &[SessionSource], ) -> std::io::Result { - get_conversations(codex_home, page_size, cursor).await + get_conversations(codex_home, page_size, cursor, allowed_sources).await } /// Attempt to create a new [`RolloutRecorder`]. If the sessions directory @@ -101,6 +109,7 @@ impl RolloutRecorder { RolloutRecorderParams::Create { conversation_id, instructions, + source, } => { let LogFileInfo { file, @@ -127,6 +136,7 @@ impl RolloutRecorder { originator: originator().value.clone(), cli_version: env!("CARGO_PKG_VERSION").to_string(), instructions, + source, }), ) } diff --git a/codex-rs/core/src/rollout/tests.rs b/codex-rs/core/src/rollout/tests.rs index 7664ced0d7..b1f34e3a9c 100644 --- a/codex-rs/core/src/rollout/tests.rs +++ b/codex-rs/core/src/rollout/tests.rs @@ -12,6 +12,7 @@ use time::format_description::FormatItem; use time::macros::format_description; use uuid::Uuid; +use crate::rollout::INTERACTIVE_SESSION_SOURCES; use crate::rollout::list::ConversationItem; use crate::rollout::list::ConversationsPage; use crate::rollout::list::Cursor; @@ -28,13 +29,17 @@ use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::RolloutLine; use codex_protocol::protocol::SessionMeta; use codex_protocol::protocol::SessionMetaLine; +use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::UserMessageEvent; +const NO_SOURCE_FILTER: &[SessionSource] = &[]; + fn write_session_file( root: &Path, ts_str: &str, uuid: Uuid, num_records: usize, + source: Option, ) -> std::io::Result<(OffsetDateTime, Uuid)> { let format: &[FormatItem] = format_description!("[year]-[month]-[day]T[hour]-[minute]-[second]"); @@ -52,17 +57,23 @@ fn write_session_file( let file_path = dir.join(filename); let mut file = File::create(file_path)?; + let mut payload = serde_json::json!({ + "id": uuid, + "timestamp": ts_str, + "instructions": null, + "cwd": ".", + "originator": "test_originator", + "cli_version": "test_version", + }); + + if let Some(source) = source { + payload["source"] = serde_json::to_value(source).unwrap(); + } + let meta = serde_json::json!({ "timestamp": ts_str, "type": "session_meta", - "payload": { - "id": uuid, - "timestamp": ts_str, - "instructions": null, - "cwd": ".", - "originator": "test_originator", - "cli_version": "test_version" - } + "payload": payload, }); writeln!(file, "{meta}")?; @@ -99,11 +110,34 @@ async fn test_list_conversations_latest_first() { let u3 = Uuid::from_u128(3); // Create three sessions across three days - write_session_file(home, "2025-01-01T12-00-00", u1, 3).unwrap(); - write_session_file(home, "2025-01-02T12-00-00", u2, 3).unwrap(); - write_session_file(home, "2025-01-03T12-00-00", u3, 3).unwrap(); + write_session_file( + home, + "2025-01-01T12-00-00", + u1, + 3, + Some(SessionSource::VSCode), + ) + .unwrap(); + write_session_file( + home, + "2025-01-02T12-00-00", + u2, + 3, + Some(SessionSource::VSCode), + ) + .unwrap(); + write_session_file( + home, + "2025-01-03T12-00-00", + u3, + 3, + Some(SessionSource::VSCode), + ) + .unwrap(); - let page = get_conversations(home, 10, None).await.unwrap(); + let page = get_conversations(home, 10, None, INTERACTIVE_SESSION_SOURCES) + .await + .unwrap(); // Build expected objects let p1 = home @@ -131,7 +165,8 @@ async fn test_list_conversations_latest_first() { "instructions": null, "cwd": ".", "originator": "test_originator", - "cli_version": "test_version" + "cli_version": "test_version", + "source": "vscode", })]; let head_2 = vec![serde_json::json!({ "id": u2, @@ -139,7 +174,8 @@ async fn test_list_conversations_latest_first() { "instructions": null, "cwd": ".", "originator": "test_originator", - "cli_version": "test_version" + "cli_version": "test_version", + "source": "vscode", })]; let head_1 = vec![serde_json::json!({ "id": u1, @@ -147,7 +183,8 @@ async fn test_list_conversations_latest_first() { "instructions": null, "cwd": ".", "originator": "test_originator", - "cli_version": "test_version" + "cli_version": "test_version", + "source": "vscode", })]; let expected_cursor: Cursor = @@ -198,13 +235,50 @@ async fn test_pagination_cursor() { let u5 = Uuid::from_u128(55); // Oldest to newest - write_session_file(home, "2025-03-01T09-00-00", u1, 1).unwrap(); - write_session_file(home, "2025-03-02T09-00-00", u2, 1).unwrap(); - write_session_file(home, "2025-03-03T09-00-00", u3, 1).unwrap(); - write_session_file(home, "2025-03-04T09-00-00", u4, 1).unwrap(); - write_session_file(home, "2025-03-05T09-00-00", u5, 1).unwrap(); + write_session_file( + home, + "2025-03-01T09-00-00", + u1, + 1, + Some(SessionSource::VSCode), + ) + .unwrap(); + write_session_file( + home, + "2025-03-02T09-00-00", + u2, + 1, + Some(SessionSource::VSCode), + ) + .unwrap(); + write_session_file( + home, + "2025-03-03T09-00-00", + u3, + 1, + Some(SessionSource::VSCode), + ) + .unwrap(); + write_session_file( + home, + "2025-03-04T09-00-00", + u4, + 1, + Some(SessionSource::VSCode), + ) + .unwrap(); + write_session_file( + home, + "2025-03-05T09-00-00", + u5, + 1, + Some(SessionSource::VSCode), + ) + .unwrap(); - let page1 = get_conversations(home, 2, None).await.unwrap(); + let page1 = get_conversations(home, 2, None, INTERACTIVE_SESSION_SOURCES) + .await + .unwrap(); let p5 = home .join("sessions") .join("2025") @@ -223,7 +297,8 @@ async fn test_pagination_cursor() { "instructions": null, "cwd": ".", "originator": "test_originator", - "cli_version": "test_version" + "cli_version": "test_version", + "source": "vscode", })]; let head_4 = vec![serde_json::json!({ "id": u4, @@ -231,7 +306,8 @@ async fn test_pagination_cursor() { "instructions": null, "cwd": ".", "originator": "test_originator", - "cli_version": "test_version" + "cli_version": "test_version", + "source": "vscode", })]; let expected_cursor1: Cursor = serde_json::from_str(&format!("\"2025-03-04T09-00-00|{u4}\"")).unwrap(); @@ -258,9 +334,14 @@ async fn test_pagination_cursor() { }; assert_eq!(page1, expected_page1); - let page2 = get_conversations(home, 2, page1.next_cursor.as_ref()) - .await - .unwrap(); + let page2 = get_conversations( + home, + 2, + page1.next_cursor.as_ref(), + INTERACTIVE_SESSION_SOURCES, + ) + .await + .unwrap(); let p3 = home .join("sessions") .join("2025") @@ -279,7 +360,8 @@ async fn test_pagination_cursor() { "instructions": null, "cwd": ".", "originator": "test_originator", - "cli_version": "test_version" + "cli_version": "test_version", + "source": "vscode", })]; let head_2 = vec![serde_json::json!({ "id": u2, @@ -287,7 +369,8 @@ async fn test_pagination_cursor() { "instructions": null, "cwd": ".", "originator": "test_originator", - "cli_version": "test_version" + "cli_version": "test_version", + "source": "vscode", })]; let expected_cursor2: Cursor = serde_json::from_str(&format!("\"2025-03-02T09-00-00|{u2}\"")).unwrap(); @@ -314,9 +397,14 @@ async fn test_pagination_cursor() { }; assert_eq!(page2, expected_page2); - let page3 = get_conversations(home, 2, page2.next_cursor.as_ref()) - .await - .unwrap(); + let page3 = get_conversations( + home, + 2, + page2.next_cursor.as_ref(), + INTERACTIVE_SESSION_SOURCES, + ) + .await + .unwrap(); let p1 = home .join("sessions") .join("2025") @@ -329,7 +417,8 @@ async fn test_pagination_cursor() { "instructions": null, "cwd": ".", "originator": "test_originator", - "cli_version": "test_version" + "cli_version": "test_version", + "source": "vscode", })]; let expected_cursor3: Cursor = serde_json::from_str(&format!("\"2025-03-01T09-00-00|{u1}\"")).unwrap(); @@ -355,9 +444,11 @@ async fn test_get_conversation_contents() { let uuid = Uuid::new_v4(); let ts = "2025-04-01T10-30-00"; - write_session_file(home, ts, uuid, 2).unwrap(); + write_session_file(home, ts, uuid, 2, Some(SessionSource::VSCode)).unwrap(); - let page = get_conversations(home, 1, None).await.unwrap(); + let page = get_conversations(home, 1, None, INTERACTIVE_SESSION_SOURCES) + .await + .unwrap(); let path = &page.items[0].path; let content = get_conversation(path).await.unwrap(); @@ -375,7 +466,8 @@ async fn test_get_conversation_contents() { "instructions": null, "cwd": ".", "originator": "test_originator", - "cli_version": "test_version" + "cli_version": "test_version", + "source": "vscode", })]; let expected_cursor: Cursor = serde_json::from_str(&format!("\"{ts}|{uuid}\"")).unwrap(); let expected_page = ConversationsPage { @@ -393,7 +485,19 @@ async fn test_get_conversation_contents() { assert_eq!(page, expected_page); // Entire file contents equality - let meta = serde_json::json!({"timestamp": ts, "type": "session_meta", "payload": {"id": uuid, "timestamp": ts, "instructions": null, "cwd": ".", "originator": "test_originator", "cli_version": "test_version"}}); + let meta = serde_json::json!({ + "timestamp": ts, + "type": "session_meta", + "payload": { + "id": uuid, + "timestamp": ts, + "instructions": null, + "cwd": ".", + "originator": "test_originator", + "cli_version": "test_version", + "source": "vscode", + } + }); let user_event = serde_json::json!({ "timestamp": ts, "type": "event_msg", @@ -428,6 +532,7 @@ async fn test_tail_includes_last_response_items() -> Result<()> { cwd: ".".into(), originator: "test_originator".into(), cli_version: "test_version".into(), + source: SessionSource::VSCode, }, git: None, }), @@ -460,7 +565,7 @@ async fn test_tail_includes_last_response_items() -> Result<()> { } drop(file); - let page = get_conversations(home, 1, None).await?; + let page = get_conversations(home, 1, None, INTERACTIVE_SESSION_SOURCES).await?; let item = page.items.first().expect("conversation item"); let tail_len = item.tail.len(); assert_eq!(tail_len, 10usize.min(total_messages)); @@ -511,6 +616,7 @@ async fn test_tail_handles_short_sessions() -> Result<()> { cwd: ".".into(), originator: "test_originator".into(), cli_version: "test_version".into(), + source: SessionSource::VSCode, }, git: None, }), @@ -542,7 +648,7 @@ async fn test_tail_handles_short_sessions() -> Result<()> { } drop(file); - let page = get_conversations(home, 1, None).await?; + let page = get_conversations(home, 1, None, INTERACTIVE_SESSION_SOURCES).await?; let tail = &page.items.first().expect("conversation item").tail; assert_eq!(tail.len(), 3); @@ -595,6 +701,7 @@ async fn test_tail_skips_trailing_non_responses() -> Result<()> { cwd: ".".into(), originator: "test_originator".into(), cli_version: "test_version".into(), + source: SessionSource::VSCode, }, git: None, }), @@ -640,7 +747,7 @@ async fn test_tail_skips_trailing_non_responses() -> Result<()> { writeln!(file, "{}", serde_json::to_string(&shutdown_event)?)?; drop(file); - let page = get_conversations(home, 1, None).await?; + let page = get_conversations(home, 1, None, INTERACTIVE_SESSION_SOURCES).await?; let tail = &page.items.first().expect("conversation item").tail; let expected: Vec = (0..4) @@ -678,11 +785,13 @@ async fn test_stable_ordering_same_second_pagination() { let u2 = Uuid::from_u128(2); let u3 = Uuid::from_u128(3); - write_session_file(home, ts, u1, 0).unwrap(); - write_session_file(home, ts, u2, 0).unwrap(); - write_session_file(home, ts, u3, 0).unwrap(); + write_session_file(home, ts, u1, 0, Some(SessionSource::VSCode)).unwrap(); + write_session_file(home, ts, u2, 0, Some(SessionSource::VSCode)).unwrap(); + write_session_file(home, ts, u3, 0, Some(SessionSource::VSCode)).unwrap(); - let page1 = get_conversations(home, 2, None).await.unwrap(); + let page1 = get_conversations(home, 2, None, INTERACTIVE_SESSION_SOURCES) + .await + .unwrap(); let p3 = home .join("sessions") @@ -703,7 +812,8 @@ async fn test_stable_ordering_same_second_pagination() { "instructions": null, "cwd": ".", "originator": "test_originator", - "cli_version": "test_version" + "cli_version": "test_version", + "source": "vscode", })] }; let expected_cursor1: Cursor = serde_json::from_str(&format!("\"{ts}|{u2}\"")).unwrap(); @@ -730,9 +840,14 @@ async fn test_stable_ordering_same_second_pagination() { }; assert_eq!(page1, expected_page1); - let page2 = get_conversations(home, 2, page1.next_cursor.as_ref()) - .await - .unwrap(); + let page2 = get_conversations( + home, + 2, + page1.next_cursor.as_ref(), + INTERACTIVE_SESSION_SOURCES, + ) + .await + .unwrap(); let p1 = home .join("sessions") .join("2025") @@ -754,3 +869,59 @@ async fn test_stable_ordering_same_second_pagination() { }; assert_eq!(page2, expected_page2); } + +#[tokio::test] +async fn test_source_filter_excludes_non_matching_sessions() { + let temp = TempDir::new().unwrap(); + let home = temp.path(); + + let interactive_id = Uuid::from_u128(42); + let non_interactive_id = Uuid::from_u128(77); + + write_session_file( + home, + "2025-08-02T10-00-00", + interactive_id, + 2, + Some(SessionSource::Cli), + ) + .unwrap(); + write_session_file( + home, + "2025-08-01T10-00-00", + non_interactive_id, + 2, + Some(SessionSource::Exec), + ) + .unwrap(); + + let interactive_only = get_conversations(home, 10, None, INTERACTIVE_SESSION_SOURCES) + .await + .unwrap(); + let paths: Vec<_> = interactive_only + .items + .iter() + .map(|item| item.path.as_path()) + .collect(); + + assert_eq!(paths.len(), 1); + assert!(paths.iter().all(|path| { + path.ends_with("rollout-2025-08-02T10-00-00-00000000-0000-0000-0000-00000000002a.jsonl") + })); + + let all_sessions = get_conversations(home, 10, None, NO_SOURCE_FILTER) + .await + .unwrap(); + let all_paths: Vec<_> = all_sessions + .items + .into_iter() + .map(|item| item.path) + .collect(); + assert_eq!(all_paths.len(), 2); + assert!(all_paths.iter().any(|path| { + path.ends_with("rollout-2025-08-02T10-00-00-00000000-0000-0000-0000-00000000002a.jsonl") + })); + assert!(all_paths.iter().any(|path| { + path.ends_with("rollout-2025-08-01T10-00-00-00000000-0000-0000-0000-00000000004d.jsonl") + })); +} diff --git a/codex-rs/core/tests/suite/cli_stream.rs b/codex-rs/core/tests/suite/cli_stream.rs index 5b698934c0..8fc36772ad 100644 --- a/codex-rs/core/tests/suite/cli_stream.rs +++ b/codex-rs/core/tests/suite/cli_stream.rs @@ -76,7 +76,7 @@ async fn chat_mode_stream_cli() { server.verify().await; // Verify a new session rollout was created and is discoverable via list_conversations - let page = RolloutRecorder::list_conversations(home.path(), 10, None) + let page = RolloutRecorder::list_conversations(home.path(), 10, None, &[]) .await .expect("list conversations"); assert!( diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index d4ff9da2d6..7157a105fd 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -17,6 +17,7 @@ use codex_core::built_in_model_providers; use codex_core::protocol::EventMsg; use codex_core::protocol::InputItem; use codex_core::protocol::Op; +use codex_core::protocol::SessionSource; use codex_otel::otel_event_manager::OtelEventManager; use codex_protocol::ConversationId; use codex_protocol::models::ReasoningItemReasoningSummary; @@ -538,7 +539,7 @@ async fn prefers_apikey_when_config_prefers_apikey_even_with_chatgpt_tokens() { Ok(None) => panic!("No CodexAuth found in codex_home"), Err(e) => panic!("Failed to load CodexAuth: {e}"), }; - let conversation_manager = ConversationManager::new(auth_manager); + let conversation_manager = ConversationManager::new(auth_manager, SessionSource::Exec); let NewConversation { conversation: codex, .. diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index 0ec905de15..98f3d22fdc 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -17,6 +17,7 @@ use codex_core::protocol::Event; use codex_core::protocol::EventMsg; use codex_core::protocol::InputItem; use codex_core::protocol::Op; +use codex_core::protocol::SessionSource; use codex_core::protocol::TaskCompleteEvent; use codex_ollama::DEFAULT_OSS_MODEL; use codex_protocol::config_types::SandboxMode; @@ -237,7 +238,7 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any } let auth_manager = AuthManager::shared(config.codex_home.clone(), true); - let conversation_manager = ConversationManager::new(auth_manager.clone()); + let conversation_manager = ConversationManager::new(auth_manager.clone(), SessionSource::Exec); // Handle resume subcommand by resolving a rollout path and using explicit resume API. let NewConversation { @@ -375,7 +376,9 @@ async fn resolve_resume_path( args: &crate::cli::ResumeArgs, ) -> anyhow::Result> { if args.last { - match codex_core::RolloutRecorder::list_conversations(&config.codex_home, 1, None).await { + match codex_core::RolloutRecorder::list_conversations(&config.codex_home, 1, None, &[]) + .await + { Ok(page) => Ok(page.items.first().map(|it| it.path.clone())), Err(e) => { error!("Error listing conversations: {e}"); diff --git a/codex-rs/mcp-server/src/message_processor.rs b/codex-rs/mcp-server/src/message_processor.rs index 418c2a5162..bb24f5f0dc 100644 --- a/codex-rs/mcp-server/src/message_processor.rs +++ b/codex-rs/mcp-server/src/message_processor.rs @@ -8,6 +8,7 @@ use crate::codex_tool_config::create_tool_for_codex_tool_call_reply_param; use crate::error_code::INVALID_REQUEST_ERROR_CODE; use crate::outgoing_message::OutgoingMessageSender; use codex_protocol::ConversationId; +use codex_protocol::protocol::SessionSource; use codex_core::AuthManager; use codex_core::ConversationManager; @@ -53,7 +54,8 @@ impl MessageProcessor { ) -> Self { let outgoing = Arc::new(outgoing); let auth_manager = AuthManager::shared(config.codex_home.clone(), false); - let conversation_manager = Arc::new(ConversationManager::new(auth_manager)); + let conversation_manager = + Arc::new(ConversationManager::new(auth_manager, SessionSource::Mcp)); Self { outgoing, initialized: false, diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 17a4a844b8..2c6d3b33f0 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -919,7 +919,20 @@ impl InitialHistory { } } -#[derive(Serialize, Deserialize, Clone, Default, Debug, TS)] +#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq, Eq, TS, Default)] +#[serde(rename_all = "lowercase")] +#[ts(rename_all = "lowercase")] +pub enum SessionSource { + Cli, + #[default] + VSCode, + Exec, + Mcp, + #[serde(other)] + Unknown, +} + +#[derive(Serialize, Deserialize, Clone, Debug, TS)] pub struct SessionMeta { pub id: ConversationId, pub timestamp: String, @@ -927,6 +940,22 @@ pub struct SessionMeta { pub originator: String, pub cli_version: String, pub instructions: Option, + #[serde(default)] + pub source: SessionSource, +} + +impl Default for SessionMeta { + fn default() -> Self { + SessionMeta { + id: ConversationId::default(), + timestamp: String::new(), + cwd: PathBuf::new(), + originator: String::new(), + cli_version: String::new(), + instructions: None, + source: SessionSource::default(), + } + } } #[derive(Serialize, Deserialize, Debug, Clone, TS)] diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index ab43ceb0a3..cb3dea5e60 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -18,6 +18,7 @@ use codex_core::ConversationManager; use codex_core::config::Config; use codex_core::config::persist_model_selection; use codex_core::model_family::find_family_for_model; +use codex_core::protocol::SessionSource; use codex_core::protocol::TokenUsage; use codex_core::protocol_config_types::ReasoningEffort as ReasoningEffortConfig; use codex_protocol::ConversationId; @@ -86,7 +87,10 @@ impl App { let (app_event_tx, mut app_event_rx) = unbounded_channel(); let app_event_tx = AppEventSender::new(app_event_tx); - let conversation_manager = Arc::new(ConversationManager::new(auth_manager.clone())); + let conversation_manager = Arc::new(ConversationManager::new( + auth_manager.clone(), + SessionSource::Cli, + )); let enhanced_keys_supported = tui.enhanced_keys_supported(); diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index d8dde74f06..7807bf0a18 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -9,6 +9,7 @@ use codex_app_server_protocol::AuthMode; use codex_core::AuthManager; use codex_core::BUILT_IN_OSS_MODEL_PROVIDER_ID; use codex_core::CodexAuth; +use codex_core::INTERACTIVE_SESSION_SOURCES; use codex_core::RolloutRecorder; use codex_core::config::Config; use codex_core::config::ConfigOverrides; @@ -393,7 +394,14 @@ async fn run_ratatui_app( } } } else if cli.resume_last { - match RolloutRecorder::list_conversations(&config.codex_home, 1, None).await { + match RolloutRecorder::list_conversations( + &config.codex_home, + 1, + None, + INTERACTIVE_SESSION_SOURCES, + ) + .await + { Ok(page) => page .items .first() diff --git a/codex-rs/tui/src/resume_picker.rs b/codex-rs/tui/src/resume_picker.rs index ded7d41afc..eb2a9cd4ea 100644 --- a/codex-rs/tui/src/resume_picker.rs +++ b/codex-rs/tui/src/resume_picker.rs @@ -8,6 +8,7 @@ use chrono::Utc; use codex_core::ConversationItem; use codex_core::ConversationsPage; use codex_core::Cursor; +use codex_core::INTERACTIVE_SESSION_SOURCES; use codex_core::RolloutRecorder; use color_eyre::eyre::Result; use crossterm::event::KeyCode; @@ -77,6 +78,7 @@ pub async fn run_resume_picker(tui: &mut Tui, codex_home: &Path) -> Result Result<()> { - let page = RolloutRecorder::list_conversations(&self.codex_home, PAGE_SIZE, None).await?; + let page = RolloutRecorder::list_conversations( + &self.codex_home, + PAGE_SIZE, + None, + INTERACTIVE_SESSION_SOURCES, + ) + .await?; self.reset_pagination(); self.all_rows.clear(); self.filtered_rows.clear(); From b93cc0f4312586ea49682bacfea14a979f14e09f Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Thu, 2 Oct 2025 13:33:08 -0700 Subject: [PATCH 18/20] Add a separate exec doc (#4583) More/better docs. --- README.md | 1 + docs/advanced.md | 46 --------------------- docs/exec.md | 105 +++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 106 insertions(+), 46 deletions(-) create mode 100644 docs/exec.md diff --git a/README.md b/README.md index ae04239ae6..0a57a608eb 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,7 @@ Codex CLI supports a rich set of configuration options, with preferences stored - [**Authentication**](./docs/authentication.md) - [Auth methods](./docs/authentication.md#forcing-a-specific-auth-method-advanced) - [Login on a "Headless" machine](./docs/authentication.md#connecting-on-a-headless-machine) +- [**Non-interactive mode**](./docs/exec.md) - [**Advanced**](./docs/advanced.md) - [Non-interactive / CI mode](./docs/advanced.md#non-interactive--ci-mode) - [Tracing / verbose logging](./docs/advanced.md#tracing--verbose-logging) diff --git a/docs/advanced.md b/docs/advanced.md index 869a5fb533..d6a1e2ba8e 100644 --- a/docs/advanced.md +++ b/docs/advanced.md @@ -1,51 +1,5 @@ ## Advanced -## Non-interactive / CI mode - -Run Codex head-less in pipelines. Example GitHub Action step: - -```yaml -- name: Update changelog via Codex - run: | - npm install -g @openai/codex - codex login --api-key "${{ secrets.OPENAI_KEY }}" - codex exec --full-auto "update CHANGELOG for next release" -``` - -### Resuming non-interactive sessions - -You can resume a previous headless run to continue the same conversation context and append to the same rollout file. - -Interactive TUI equivalent: - -```shell -codex resume # picker -codex resume --last # most recent -codex resume -``` - -Compatibility: - -- Latest source builds include `codex exec resume` (examples below). -- Current released CLI may not include this yet. If `codex exec --help` shows no `resume`, use the workaround in the next subsection. - -```shell -# Resume the most recent recorded session and run with a new prompt (source builds) -codex exec "ship a release draft changelog" resume --last - -# Alternatively, pass the prompt via stdin (source builds) -# Note: omit the trailing '-' to avoid it being parsed as a SESSION_ID -echo "ship a release draft changelog" | codex exec resume --last - -# Or resume a specific session by id (UUID) (source builds) -codex exec resume 7f9f9a2e-1b3c-4c7a-9b0e-123456789abc "continue the task" -``` - -Notes: - -- When using `--last`, Codex picks the newest recorded session; if none exist, it behaves like starting fresh. -- Resuming appends new events to the existing session file and maintains the same conversation id. - ## Tracing / verbose logging Because Codex is written in Rust, it honors the `RUST_LOG` environment variable to configure its logging behavior. diff --git a/docs/exec.md b/docs/exec.md new file mode 100644 index 0000000000..5c3588eb5a --- /dev/null +++ b/docs/exec.md @@ -0,0 +1,105 @@ +## Non-interactive mode + +Use Codex in non-interactive mode to automate common workflows. + +```shell +codex exec "count the total number of lines of code in this project" +``` + +In non-interactive mode, Codex does not ask for command or edit approvals. By default it runs in `read-only` mode, so it cannot edit files or run commands that require network access. + +Use `codex exec --full-auto` to allow file edits. Use `codex exec --sandbox danger-full-access` to allow edits and networked commands. + + +### JSON output mode + +`codex exec` supports a `--json` mode that streams events to stdout as JSON Lines (JSONL) while the agent runs. + +Supported event types: +- `thread.started` - when a thread is started or resumed. +- `turn.started` - when a turn starts. A turn encompasses all events between the user message and the assistant response. +- `turn.completed` - when a turn completes; includes token usage. +- `turn.failed` - when a turn fails; includes error details. +- `item.started`/`item.updated`/`item.completed` - when a thread item is added/updated/completed. + +Supported item types: +- `assistant_message` - assistant message. +- `reasoning` - a summary of the assistant's thinking. +- `command_execution` - assistant executing a command. +- `file_change` - assistant making file changes. +- `mcp_tool_call` - assistant calling an MCP tool. +- `web_search` - assistant performing a web search. + +Typically, an `assistant_message` is added at the end of the turn. + +Sample output: +```jsonl +{"type":"thread.started","thread_id":"0199a213-81c0-7800-8aa1-bbab2a035a53"} +{"type":"turn.started"} +{"type":"item.completed","item":{"id":"item_0","item_type":"reasoning","text":"**Searching for README files**"}} +{"type":"item.started","item":{"id":"item_1","item_type":"command_execution","command":"bash -lc ls","aggregated_output":"","status":"in_progress"}} +{"type":"item.completed","item":{"id":"item_1","item_type":"command_execution","command":"bash -lc ls","aggregated_output":"2025-09-11\nAGENTS.md\nCHANGELOG.md\ncliff.toml\ncodex-cli\ncodex-rs\ndocs\nexamples\nflake.lock\nflake.nix\nLICENSE\nnode_modules\nNOTICE\npackage.json\npnpm-lock.yaml\npnpm-workspace.yaml\nPNPM.md\nREADME.md\nscripts\nsdk\ntmp\n","exit_code":0,"status":"completed"}} +{"type":"item.completed","item":{"id":"item_2","item_type":"reasoning","text":"**Checking repository root for README**"}} +{"type":"item.completed","item":{"id":"item_3","item_type":"assistant_message","text":"Yep — there’s a `README.md` in the repository root."}} +{"type":"turn.completed","usage":{"input_tokens":24763,"cached_input_tokens":24448,"output_tokens":122}} +``` + +### Structured output + +By default, the agent responds with natural language. Use `--output-schema` to provide a JSON Schema that defines the expected JSON output. + +The JSON Schema must follow the [strict schema rules](https://platform.openai.com/docs/guides/structured-outputs). + +Sample schema: + +```json +{ + "type": "object", + "properties": { + "project_name": { "type": "string" }, + "programming_languages": { "type": "array", "items": { "type": "string" } } + }, + "required": ["project_name", "programming_languages"], + "additionalProperties": false +} +``` + +```shell +codex exec "Extract details of the project" --output-schema ~/schema.json +... + +{"project_name":"Codex CLI","programming_languages":["Rust","TypeScript","Shell"]} +``` + +Combine `--output-schema` with `-o` to only print the final JSON output. You can also pass a file path to `-o` to save the JSON output to a file. + +### Git repository requirement + +Codex requires a Git repository to avoid destructive changes. To disable this check, use `codex exec --skip-git-repo-check`. + + +### Resuming non-interactive sessions + +Resume a previous non-interactive session with `codex exec resume ` or `codex exec resume --last`. This preserves conversation context so you can ask follow-up questions or give new tasks to the agent. + +```shell +codex exec "Review the change, look for use-after-free issues" +codex exec resume --last "Fix use-after-free issues" +``` + +Only the conversation context is preserved; you must still provide flags to customize Codex behavior. + +```shell +codex exec --model gpt-5-codex --json "Review the change, look for use-after-free issues" +codex exec --model gpt-5 --json resume --last "Fix use-after-free issues" +``` + +## Authentication + +By default, `codex exec` will use the same authentication method as Codex CLI and VSCode extension. You can override the api key by setting the `CODEX_API_KEY` environment variable. + +```shell +CODEX_API_KEY=your-api-key-here codex exec "Fix merge conflict" +``` + +NOTE: `CODEX_API_KEY` is only supported in `codex exec`. From c43a5619165c5df41ba5a4f951ebf92d48486db7 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Thu, 2 Oct 2025 13:39:45 -0700 Subject: [PATCH 19/20] Add issue labeler workflow (#4621) Auto label issues using codex cli --- .github/prompts/issue-labeler.txt | 26 ++++++++++ .github/workflows/issue-labeler.yml | 76 +++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+) create mode 100644 .github/prompts/issue-labeler.txt create mode 100644 .github/workflows/issue-labeler.yml diff --git a/.github/prompts/issue-labeler.txt b/.github/prompts/issue-labeler.txt new file mode 100644 index 0000000000..7e880d307f --- /dev/null +++ b/.github/prompts/issue-labeler.txt @@ -0,0 +1,26 @@ +You are an assistant that reviews GitHub issues for the repository. + +Your job is to choose the most appropriate existing labels for the issue described later in this prompt. +Follow these rules: +- Only pick labels out of the list below. +- Prefer a small set of precise labels over many broad ones. +- If none of the labels fit, respond with an empty JSON array: [] +- Output must be a JSON array of label names (strings) with no additional commentary. + +Labels to apply: +1. bug — Reproducible defects in Codex products (CLI, VS Code extension, web, auth). +2. enhancement — Feature requests or usability improvements that ask for new capabilities, better ergonomics, or quality-of-life tweaks. +3. extension — VS Code (or other IDE) extension-specific issues. +4. windows-os — Bugs or friction specific to Windows environments (PowerShell behavior, path handling, copy/paste, OS-specific auth or tooling failures). +5. mcp — Topics involving Model Context Protocol servers/clients. +6. codex-web — Issues targeting the Codex web UI/Cloud experience. +8. azure — Problems or requests tied to Azure OpenAI deployments. +9. documentation — Updates or corrections needed in docs/README/config references (broken links, missing examples, outdated keys, clarification requests). +10. model-behavior — Undesirable LLM behavior: forgetting goals, refusing work, hallucinating environment details, quota misreports, or other reasoning/performance anomalies. + +Issue information is available in environment variables: + +ISSUE_NUMBER +ISSUE_TITLE +ISSUE_BODY +REPO_FULL_NAME diff --git a/.github/workflows/issue-labeler.yml b/.github/workflows/issue-labeler.yml new file mode 100644 index 0000000000..dfbd17c27f --- /dev/null +++ b/.github/workflows/issue-labeler.yml @@ -0,0 +1,76 @@ +name: Issue Labeler + +on: + issues: + types: +# - opened - disabled while testing + - labeled + +jobs: + gather-labels: + name: Generate label suggestions + if: ${{ github.event.action == 'opened' || (github.event.action == 'labeled' && github.event.label.name == 'codex-label') }} + runs-on: ubuntu-latest + permissions: + contents: read + env: + ISSUE_NUMBER: ${{ github.event.issue.number }} + ISSUE_TITLE: ${{ github.event.issue.title }} + ISSUE_BODY: ${{ github.event.issue.body }} + REPO_FULL_NAME: ${{ github.repository }} + outputs: + codex_output: ${{ steps.codex.outputs.final_message }} + steps: + - uses: actions/checkout@v4 + + - id: codex + uses: openai/codex-action@main + with: + openai_api_key: ${{ secrets.CODEX_OPENAI_API_KEY }} + prompt_file: .github/prompts/issue-labeler.txt + + apply-labels: + name: Apply labels from Codex output + needs: gather-labels + if: ${{ needs.gather-labels.result != 'skipped' }} + runs-on: ubuntu-latest + permissions: + contents: read + issues: write + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + ISSUE_NUMBER: ${{ github.event.issue.number }} + CODEX_OUTPUT: ${{ needs.gather-labels.outputs.codex_output }} + steps: + - name: Apply labels + run: | + json=${CODEX_OUTPUT//$'\r'/} + if [ -z "$json" ]; then + echo "Codex produced no output. Skipping label application." + exit 0 + fi + + if ! printf '%s' "$json" | jq -e 'type == "array"' >/dev/null 2>&1; then + echo "Codex output was not a JSON array. Raw output: $json" + exit 0 + fi + + labels=$(printf '%s' "$json" | jq -r '.[] | tostring') + if [ -z "$labels" ]; then + echo "Codex returned an empty array. Nothing to do." + exit 0 + fi + + cmd=(gh issue edit "$ISSUE_NUMBER") + while IFS= read -r label; do + cmd+=(--add-label "$label") + done <<< "$labels" + + "${cmd[@]}" || true + + - name: Remove codex-label trigger + if: ${{ always() && github.event.action == 'labeled' && github.event.label.name == 'codex-label' }} + run: | + gh issue edit "$ISSUE_NUMBER" --remove-label codex-label || true + echo "Attempted to remove label: codex-label" From 5ee657888c6773ef2f197a62063a05cf3a9f6f90 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 2 Oct 2025 14:43:12 -0700 Subject: [PATCH 20/20] fix: leverage always() to simplify logic in .github/workflows/rust-ci.yml --- .github/workflows/rust-ci.yml | 17 +++-------------- 1 file changed, 3 insertions(+), 14 deletions(-) diff --git a/.github/workflows/rust-ci.yml b/.github/workflows/rust-ci.yml index 846408f3a8..e61e590157 100644 --- a/.github/workflows/rust-ci.yml +++ b/.github/workflows/rust-ci.yml @@ -164,7 +164,6 @@ jobs: sudo apt install -y musl-tools pkg-config && sudo rm -rf /var/lib/apt/lists/* - name: cargo clippy - id: clippy run: cargo clippy --target ${{ matrix.target }} --all-features --tests --profile ${{ matrix.profile }} -- -D warnings # Running `cargo build` from the workspace root builds the workspace using @@ -173,7 +172,6 @@ jobs: # run `cargo check` for each crate individually, though because this is # slower, we only do this for the x86_64-unknown-linux-gnu target. - name: cargo check individual crates - id: cargo_check_all_crates if: ${{ matrix.target == 'x86_64-unknown-linux-gnu' && matrix.profile != 'release' }} continue-on-error: true run: | @@ -186,24 +184,15 @@ jobs: version: 0.9.103 - name: tests - id: test # Tests take too long for release builds to run them on every PR. - if: ${{ matrix.profile != 'release' }} + # Though run the tests even if `cargo clippy` failed to get more + # complete information. + if: ${{ always() && matrix.profile != 'release' }} continue-on-error: true run: cargo nextest run --all-features --no-fail-fast --target ${{ matrix.target }} env: RUST_BACKTRACE: 1 - # Fail the job if any of the previous steps failed. - - name: verify all steps passed - if: | - steps.clippy.outcome == 'failure' || - steps.cargo_check_all_crates.outcome == 'failure' || - steps.test.outcome == 'failure' - run: | - echo "One or more checks failed (clippy, cargo_check_all_crates, or test). See logs for details." - exit 1 - # --- Gatherer job that you mark as the ONLY required status ----------------- results: name: CI results (required)