Skip to content

Commit c577e94

Browse files
authored
chore: introduce codex-common crate (#843)
I started this PR because I wanted to share the `format_duration()` utility function in `codex-rs/exec/src/event_processor.rs` with the TUI. The question was: where to put it? `core` should have as few dependencies as possible, so moving it there would introduce a dependency on `chrono`, which seemed undesirable. `core` already had this `cli` feature to deal with a similar situation around sharing common utility functions, so I decided to: * make `core` feature-free * introduce `common` * `common` can have as many "special interest" features as it needs, each of which can declare their own deps * the first two features of common are `cli` and `elapsed` In practice, this meant updating a number of `Cargo.toml` files, replacing this line: ```toml codex-core = { path = "../core", features = ["cli"] } ``` with these: ```toml codex-core = { path = "../core" } codex-common = { path = "../common", features = ["cli"] } ``` Moving `format_duration()` into its own file gave it some "breathing room" to add a unit test, so I had Codex generate some tests and new support for durations over 1 minute.
1 parent 7d8b38b commit c577e94

File tree

20 files changed

+143
-42
lines changed

20 files changed

+143
-42
lines changed

.github/workflows/rust-ci.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ jobs:
9393
run: find . -name Cargo.toml -mindepth 2 -maxdepth 2 -print0 | xargs -0 -n1 -I{} bash -c 'cd "$(dirname "{}")" && cargo build' || echo "FAILED=${FAILED:+$FAILED, }cargo build individual crates" >> $GITHUB_ENV
9494

9595
- name: cargo test
96-
run: cargo test --target ${{ matrix.target }} || echo "FAILED=${FAILED:+$FAILED, }cargo test" >> $GITHUB_ENV
96+
run: cargo test --all-features --target ${{ matrix.target }} || echo "FAILED=${FAILED:+$FAILED, }cargo test" >> $GITHUB_ENV
9797

9898
- name: Fail if any step failed
9999
if: env.FAILED != ''

codex-rs/Cargo.lock

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

codex-rs/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ members = [
44
"ansi-escape",
55
"apply-patch",
66
"cli",
7+
"common",
78
"core",
89
"exec",
910
"execpolicy",

codex-rs/cli/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ path = "src/lib.rs"
1919
anyhow = "1"
2020
clap = { version = "4", features = ["derive"] }
2121
codex-core = { path = "../core" }
22+
codex-common = { path = "../common", features = ["cli"] }
2223
codex-exec = { path = "../exec" }
2324
codex-tui = { path = "../tui" }
2425
serde_json = "1"

codex-rs/cli/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ pub mod proto;
44
pub mod seatbelt;
55

66
use clap::Parser;
7+
use codex_common::SandboxPermissionOption;
78
use codex_core::protocol::SandboxPolicy;
8-
use codex_core::SandboxPermissionOption;
99

1010
#[derive(Debug, Parser)]
1111
pub struct SeatbeltCommand {

codex-rs/common/Cargo.toml

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
[package]
2+
name = "codex-common"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
[dependencies]
7+
chrono = { version = "0.4.40", optional = true }
8+
clap = { version = "4", features = ["derive", "wrap_help"], optional = true }
9+
codex-core = { path = "../core" }
10+
11+
[features]
12+
# Separate feature so that `clap` is not a mandatory dependency.
13+
cli = ["clap"]
14+
elapsed = ["chrono"]

codex-rs/common/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# codex-common
2+
3+
This crate is designed for utilities that need to be shared across other crates in the workspace, but should not go in `core`.
4+
5+
For narrow utility features, the pattern is to add introduce a new feature under `[features]` in `Cargo.toml` and then gate it with `#[cfg]` in `lib.rs`, as appropriate.

codex-rs/core/src/approval_mode_cli_arg.rs renamed to codex-rs/common/src/approval_mode_cli_arg.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@ use clap::ArgAction;
55
use clap::Parser;
66
use clap::ValueEnum;
77

8-
use crate::config::parse_sandbox_permission_with_base_path;
9-
use crate::protocol::AskForApproval;
10-
use crate::protocol::SandboxPermission;
8+
use codex_core::config::parse_sandbox_permission_with_base_path;
9+
use codex_core::protocol::AskForApproval;
10+
use codex_core::protocol::SandboxPermission;
1111

1212
#[derive(Clone, Copy, Debug, ValueEnum)]
1313
#[value(rename_all = "kebab-case")]

codex-rs/common/src/elapsed.rs

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
use chrono::Utc;
2+
3+
/// Returns a string representing the elapsed time since `start_time` like
4+
/// "1m15s" or "1.50s".
5+
pub fn format_elapsed(start_time: chrono::DateTime<Utc>) -> String {
6+
let elapsed = Utc::now().signed_duration_since(start_time);
7+
format_time_delta(elapsed)
8+
}
9+
10+
fn format_time_delta(elapsed: chrono::TimeDelta) -> String {
11+
let millis = elapsed.num_milliseconds();
12+
format_elapsed_millis(millis)
13+
}
14+
15+
pub fn format_duration(duration: std::time::Duration) -> String {
16+
let millis = duration.as_millis() as i64;
17+
format_elapsed_millis(millis)
18+
}
19+
20+
fn format_elapsed_millis(millis: i64) -> String {
21+
if millis < 1000 {
22+
format!("{}ms", millis)
23+
} else if millis < 60_000 {
24+
format!("{:.2}s", millis as f64 / 1000.0)
25+
} else {
26+
let minutes = millis / 60_000;
27+
let seconds = (millis % 60_000) / 1000;
28+
format!("{minutes}m{seconds:02}s")
29+
}
30+
}
31+
32+
#[cfg(test)]
33+
mod tests {
34+
use super::*;
35+
use chrono::Duration;
36+
37+
#[test]
38+
fn test_format_time_delta_subsecond() {
39+
// Durations < 1s should be rendered in milliseconds with no decimals.
40+
let dur = Duration::milliseconds(250);
41+
assert_eq!(format_time_delta(dur), "250ms");
42+
43+
// Exactly zero should still work.
44+
let dur_zero = Duration::milliseconds(0);
45+
assert_eq!(format_time_delta(dur_zero), "0ms");
46+
}
47+
48+
#[test]
49+
fn test_format_time_delta_seconds() {
50+
// Durations between 1s (inclusive) and 60s (exclusive) should be
51+
// printed with 2-decimal-place seconds.
52+
let dur = Duration::milliseconds(1_500); // 1.5s
53+
assert_eq!(format_time_delta(dur), "1.50s");
54+
55+
// 59.999s rounds to 60.00s
56+
let dur2 = Duration::milliseconds(59_999);
57+
assert_eq!(format_time_delta(dur2), "60.00s");
58+
}
59+
60+
#[test]
61+
fn test_format_time_delta_minutes() {
62+
// Durations ≥ 1 minute should be printed mmss.
63+
let dur = Duration::milliseconds(75_000); // 1m15s
64+
assert_eq!(format_time_delta(dur), "1m15s");
65+
66+
let dur_exact = Duration::milliseconds(60_000); // 1m0s
67+
assert_eq!(format_time_delta(dur_exact), "1m00s");
68+
69+
let dur_long = Duration::milliseconds(3_601_000);
70+
assert_eq!(format_time_delta(dur_long), "60m01s");
71+
}
72+
}

codex-rs/common/src/lib.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#[cfg(feature = "cli")]
2+
mod approval_mode_cli_arg;
3+
4+
#[cfg(feature = "elapsed")]
5+
pub mod elapsed;
6+
7+
#[cfg(feature = "cli")]
8+
pub use approval_mode_cli_arg::ApprovalModeCliArg;
9+
#[cfg(feature = "cli")]
10+
pub use approval_mode_cli_arg::SandboxPermissionOption;

codex-rs/core/Cargo.toml

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -56,9 +56,3 @@ assert_cmd = "2"
5656
predicates = "3"
5757
tempfile = "3"
5858
wiremock = "0.6"
59-
60-
[features]
61-
default = []
62-
63-
# Separate feature so that `clap` is not a mandatory dependency.
64-
cli = ["clap"]

codex-rs/core/src/config.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@ pub fn log_dir() -> std::io::Result<PathBuf> {
266266
Ok(p)
267267
}
268268

269-
pub(crate) fn parse_sandbox_permission_with_base_path(
269+
pub fn parse_sandbox_permission_with_base_path(
270270
raw: &str,
271271
base_path: PathBuf,
272272
) -> std::io::Result<SandboxPermission> {

codex-rs/core/src/lib.rs

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,3 @@ pub mod util;
2626
mod zdr_transcript;
2727

2828
pub use codex::Codex;
29-
30-
#[cfg(feature = "cli")]
31-
mod approval_mode_cli_arg;
32-
#[cfg(feature = "cli")]
33-
pub use approval_mode_cli_arg::ApprovalModeCliArg;
34-
#[cfg(feature = "cli")]
35-
pub use approval_mode_cli_arg::SandboxPermissionOption;

codex-rs/exec/Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ path = "src/lib.rs"
1515
anyhow = "1"
1616
chrono = "0.4.40"
1717
clap = { version = "4", features = ["derive"] }
18-
codex-core = { path = "../core", features = ["cli"] }
18+
codex-core = { path = "../core" }
19+
codex-common = { path = "../common", features = ["cli", "elapsed"] }
1920
mcp-types = { path = "../mcp-types" }
2021
owo-colors = "4.2.0"
2122
serde_json = "1"

codex-rs/exec/src/cli.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use clap::Parser;
22
use clap::ValueEnum;
3-
use codex_core::SandboxPermissionOption;
3+
use codex_common::SandboxPermissionOption;
44
use std::path::PathBuf;
55

66
#[derive(Parser, Debug)]

codex-rs/exec/src/event_processor.rs

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use chrono::Utc;
2+
use codex_common::elapsed::format_elapsed;
23
use codex_core::protocol::Event;
34
use codex_core::protocol::EventMsg;
45
use codex_core::protocol::FileChange;
@@ -145,7 +146,7 @@ impl EventProcessor {
145146
}) = exec_command
146147
{
147148
(
148-
format_duration(start_time),
149+
format!(" in {}", format_elapsed(start_time)),
149150
format!("{}", escape_command(&command).style(self.bold)),
150151
)
151152
} else {
@@ -160,7 +161,7 @@ impl EventProcessor {
160161
.join("\n");
161162
match exit_code {
162163
0 => {
163-
let title = format!("{call} succeded{duration}:");
164+
let title = format!("{call} succeeded{duration}:");
164165
ts_println!("{}", title.style(self.green));
165166
}
166167
_ => {
@@ -221,7 +222,7 @@ impl EventProcessor {
221222
..
222223
}) = info
223224
{
224-
(format_duration(start_time), invocation)
225+
(format!(" in {}", format_elapsed(start_time)), invocation)
225226
} else {
226227
(String::new(), format!("tool('{call_id}')"))
227228
};
@@ -335,7 +336,7 @@ impl EventProcessor {
335336
}) = patch_begin
336337
{
337338
(
338-
format_duration(start_time),
339+
format!(" in {}", format_elapsed(start_time)),
339340
format!("apply_patch(auto_approved={})", auto_approved),
340341
)
341342
} else {
@@ -383,13 +384,3 @@ fn format_file_change(change: &FileChange) -> &'static str {
383384
} => "M",
384385
}
385386
}
386-
387-
fn format_duration(start_time: chrono::DateTime<Utc>) -> String {
388-
let elapsed = Utc::now().signed_duration_since(start_time);
389-
let millis = elapsed.num_milliseconds();
390-
if millis < 1000 {
391-
format!(" in {}ms", millis)
392-
} else {
393-
format!(" in {:.2}s", millis as f64 / 1000.0)
394-
}
395-
}

codex-rs/mcp-server/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ version = "0.1.0"
44
edition = "2021"
55

66
[dependencies]
7-
codex-core = { path = "../core", features = ["cli"] }
7+
codex-core = { path = "../core" }
88
mcp-types = { path = "../mcp-types" }
99
schemars = "0.8.22"
1010
serde = { version = "1", features = ["derive"] }

codex-rs/tui/Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ path = "src/lib.rs"
1515
anyhow = "1"
1616
clap = { version = "4", features = ["derive"] }
1717
codex-ansi-escape = { path = "../ansi-escape" }
18-
codex-core = { path = "../core", features = ["cli"] }
18+
codex-core = { path = "../core" }
19+
codex-common = { path = "../common", features = ["cli", "elapsed"] }
1920
color-eyre = "0.6.3"
2021
crossterm = "0.28.1"
2122
mcp-types = { path = "../mcp-types" }

codex-rs/tui/src/cli.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use clap::Parser;
2-
use codex_core::ApprovalModeCliArg;
3-
use codex_core::SandboxPermissionOption;
2+
use codex_common::ApprovalModeCliArg;
3+
use codex_common::SandboxPermissionOption;
44
use std::path::PathBuf;
55

66
#[derive(Parser, Debug)]

codex-rs/tui/src/history_cell.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use codex_ansi_escape::ansi_escape_line;
2+
use codex_common::elapsed::format_duration;
23
use codex_core::config::Config;
34
use codex_core::protocol::FileChange;
45
use ratatui::prelude::*;
@@ -132,7 +133,12 @@ impl HistoryCell {
132133
// Title depends on whether we have output yet.
133134
let title_line = Line::from(vec![
134135
"command".magenta(),
135-
format!(" (code: {}, duration: {:?})", exit_code, duration).dim(),
136+
format!(
137+
" (code: {}, duration: {})",
138+
exit_code,
139+
format_duration(duration)
140+
)
141+
.dim(),
136142
]);
137143
lines.push(title_line);
138144

@@ -201,11 +207,11 @@ impl HistoryCell {
201207
success: bool,
202208
result: Option<serde_json::Value>,
203209
) -> Self {
204-
let duration = start.elapsed();
210+
let duration = format_duration(start.elapsed());
205211
let status_str = if success { "success" } else { "failed" };
206212
let title_line = Line::from(vec![
207213
"tool".magenta(),
208-
format!(" {fq_tool_name} ({status_str}, duration: {:?})", duration).dim(),
214+
format!(" {fq_tool_name} ({status_str}, duration: {})", duration).dim(),
209215
]);
210216

211217
let mut lines: Vec<Line<'static>> = Vec::new();

0 commit comments

Comments
 (0)