diff --git a/.gitattributes b/.gitattributes index e1ba3d54e3..fa0d196b41 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,5 @@ codex-rs/app-server-protocol/schema/** linguist-generated codex-rs/hooks/schema/generated/** linguist-generated +codex-rs/skills/src/assets/samples/create-statusline/references/statusline.d.ts linguist-generated third_party/voice/sources.json text eol=lf patches/v8_array_sort_elements_kind.patch text eol=lf diff --git a/.prettierignore b/.prettierignore index f5b50f6ba2..542908c940 100644 --- a/.prettierignore +++ b/.prettierignore @@ -5,3 +5,5 @@ pnpm-lock.yaml prompt.md *_prompt.md *_instructions.md + +/codex-rs/skills/src/assets/samples/create-statusline/references/statusline.d.ts diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 4188b80dd2..db2b9b1dcf 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -5296,6 +5296,7 @@ dependencies = [ "codex-rollout", "codex-sandboxing", "codex-shell-command", + "codex-skills", "codex-state", "codex-terminal-detection", "codex-uds", @@ -5365,6 +5366,7 @@ dependencies = [ "tracing", "tracing-appender", "tracing-subscriber", + "ts-rs", "two-face", "unicode-bidi", "unicode-linebreak", diff --git a/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst b/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst index e8d10d7451..1c0ad89d3e 100644 Binary files a/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst and b/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst differ diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index e9215d052c..5644165e5c 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -2710,7 +2710,7 @@ impl FromStr for RateLimitReachedType { #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)] pub struct RateLimitWindow { - /// Percentage (0-100) of the window that has been consumed. + /// Percentage of the allowance consumed during the window. Can exceed 100. pub used_percent: f64, /// Rolling window duration, in minutes. #[ts(type = "number | null")] diff --git a/codex-rs/skills/src/assets/samples/create-statusline/references/statusline.d.ts b/codex-rs/skills/src/assets/samples/create-statusline/references/statusline.d.ts new file mode 100644 index 0000000000..d0581ca6f8 --- /dev/null +++ b/codex-rs/skills/src/assets/samples/create-statusline/references/statusline.d.ts @@ -0,0 +1,102 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type Account = { rate_limits: Array, workspace?: AccountWorkspace, }; + +export type AccountWorkspace = { headline: string, }; + +export type Agent = { state: RunState, }; + +export type App = { cli_version: string, display_mode: DisplayMode, }; + +export type Approval = { policy: ApprovalPolicy, reviewer: ApprovalReviewer, }; + +export type ApprovalPolicy = "untrusted" | "on-request" | "granular" | "never"; + +export type ApprovalReviewer = "user" | "auto-review"; + +export type Color = "primary" | "surface" | "accent" | "black" | "red" | "green" | "yellow" | "blue" | "magenta" | "cyan" | "white" | StatusColor | HexRgb; + +export type Config = { statusline_items: StatuslineItemId[], profile?: string, }; + +export type Context = { context_window_size?: number, used_tokens?: number, used_percentage?: number, }; + +export type Cost = { total_cost_usd?: number, total_credits?: number, }; + +export type DisplayMode = "standard" | "raw"; + +export type Element = { "type": "text", props?: TextProps, children: Array, } | { "type": "link", props: LinkProps, children: Array, } | { "type": "row", props: RowProps, children: Array, } | { "type": "bold", children: Array, } | { "type": "italic", children: Array, } | { "type": "underline", children: Array, } | string; + +export type FileSystem = { "type": "restricted" } | { "type": "unrestricted" }; + +/** + * A six-digit sRGB color in `#RRGGBB` form. + */ +export type HexRgb = `#${string}`; + +/** + * An absolute HTTP(S) URL without control characters, at most 8 KiB in UTF-8. + */ +export type LinkHref = string; + +export type LinkProps = { href: LinkHref, title?: string | null, }; + +export type Model = { access_program?: "standard" | "daybreak_blue" | "daybreak_red", display_name: string, id?: string, provider: string, reasoning_level?: string, service_tier?: string, service_tier_display_name?: string, }; + +export type Permissions = { display_name: string, profile_id?: string, } & ({ "type": "managed", file_system: FileSystem, network: "restricted" | "enabled", } | { "type": "disabled" } | { "type": "external", network: "restricted" | "enabled", }); + +export type RateLimitSnapshot = { limit_id: string, limit_name: string | null, primary_limit: RateLimitWindow | null, secondary_limit: RateLimitWindow | null, }; + +export type RowProps = { +/** + * Horizontal spacing in terminal columns, expressed as a non-negative JavaScript-safe integer. + */ +gap: number, background?: Color | null, wrap?: RowWrap, }; + +export type RowWrap = "nowrap" | "wrap"; + +export type RunState = "starting" | "ready" | "working" | "waiting" | "thinking"; + +export type StatusColor = "status-model" | "status-path" | "status-branch" | "status-state" | "status-usage" | "status-limit" | "status-metadata" | "status-mode" | "status-thread" | "status-progress"; + +export type StatuslineState = { account: Account, app: App, config: Config, thread: Thread, }; + +export type TextProps = { color?: Color | null, weight?: TextWeight | null, italic?: boolean | null, underline?: boolean | null, }; + +export type TextWeight = "normal" | "bold"; + +export type Thread = { id: string, name: string | null, agent: Agent, model: Model, workspace: Workspace, usage: Usage, approval?: Approval, permissions?: Permissions, }; + +export type TokenUsage = { total_input_tokens: number, cache_read_input_tokens: number, cache_write_input_tokens: number, other_input_tokens: number, output_tokens: number, }; + +/** + * A nullable root. JSON is limited to 64 KiB, 256 non-null nodes, depth 16 (root at 0), + * and 16 KiB of UTF-8 text across all string leaves. + */ +export type UiTree = Element | null; + +export type Usage = { context: Context, total?: TokenUsage, cost?: Cost, }; + +export type Workspace = { cwd: string, }; + +export type StatuslineItemId = "model" | "model-with-reasoning" | "reasoning" | "current-dir" | "project-name" | "hostname" | "git-branch" | "pull-request-number" | "branch-changes" | "run-state" | "permissions" | "approval-mode" | "context-remaining" | "context-used" | "five-hour-limit" | "weekly-limit" | "codex-version" | "context-window-size" | "used-tokens" | "total-input-tokens" | "total-output-tokens" | "thread-credits" | "estimated-thread-cost" | "thread-id" | "fast-mode" | "daybreak" | "raw-output" | "thread-name" | "thread-title" | "workspace-headline" | "task-progress" | "profile" | "provider"; +export type TextElement = Extract; +export type BoldElement = Extract; +export type ItalicElement = Extract; +export type UnderlineElement = Extract; +export type LinkElement = Extract; +export type RowElement = Extract; +export type RateLimitWindow = { +/** + * Percentage of the allowance consumed during the window. Can exceed 100. + */ +used_percent: number, +/** + * Rolling window duration, in minutes. + */ +window_minutes: number | null, +/** + * Unix timestamp (seconds since epoch) when the window resets. + */ +resets_at: number | null, }; +export type ThemeColor = Extract; +export type AnsiColor = Exclude; diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index d3e354f888..79ae4afa11 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -185,6 +185,7 @@ arboard = { workspace = true } app_test_support = { workspace = true } codex-mcp = { workspace = true } codex-protocol-test-support = { workspace = true } +codex-skills = { workspace = true } core_test_support = { workspace = true } codex-utils-cargo-bin = { workspace = true } assert_matches = { workspace = true } @@ -196,6 +197,7 @@ pretty_assertions = { workspace = true } rand = { workspace = true } serial_test = { workspace = true } tokio-tungstenite = { workspace = true } +ts-rs = { workspace = true } vt100 = { workspace = true } uuid = { workspace = true } wiremock = { workspace = true } diff --git a/codex-rs/tui/src/bottom_pane/status_line_style.rs b/codex-rs/tui/src/bottom_pane/status_line_style.rs index 2efa1a07db..59426adf57 100644 --- a/codex-rs/tui/src/bottom_pane/status_line_style.rs +++ b/codex-rs/tui/src/bottom_pane/status_line_style.rs @@ -20,6 +20,11 @@ const STATUS_LINE_COLOR_SATURATION_PERCENT: u16 = 85; const STATUS_LINE_COLOR_BRIGHTNESS_PERCENT: u16 = 100; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize)] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", rename = "StatusColor") +)] pub(crate) enum StatusLineAccent { #[serde(rename = "status-model")] Model, diff --git a/codex-rs/tui/src/chatwidget/statusline_contract_tests.rs b/codex-rs/tui/src/chatwidget/statusline_contract_tests.rs new file mode 100644 index 0000000000..3058e6ac46 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/statusline_contract_tests.rs @@ -0,0 +1,82 @@ +#![cfg(test)] +//! Generate the TypeScript reference and check the exports installed with the authoring skill. + +use super::StatuslineState; +use crate::bottom_pane::StatusLineItem; +use crate::ui_tree::UiTree; +use codex_protocol::protocol::RateLimitWindow; +use codex_utils_absolute_path::AbsolutePathBuf; +use std::fmt::Write as _; +use std::path::Path; +use strum::IntoEnumIterator; +use ts_rs::TS; + +#[test] +fn statusline_typescript_contract_matches_the_bundled_reference() -> color_eyre::Result<()> { + let output = tempfile::tempdir()?; + if let Some(destination) = std::env::var_os("UPDATE_STATUSLINE_TYPES") { + std::fs::write(destination, generate_reference(output.path())?)?; + return Ok(()); + } + + let home = AbsolutePathBuf::try_from(output.path().to_path_buf())?; + codex_skills::install_system_skills(&home)?; + let reference = codex_skills::system_cache_root_dir(&home) + .join("create-statusline/references/statusline.d.ts"); + let reference = std::fs::read_to_string(reference.as_path())?; + for name in [ + "StatuslineState", + "UiTree", + "RowElement", + "StatuslineItemId", + "Color", + ] { + assert!( + reference.lines().any(|line| { + line.strip_prefix("export type ") + .and_then(|declaration| declaration.split_once('=')) + .is_some_and(|(declared_name, _)| declared_name.trim_end() == name) + }), + "missing export {name} in statusline.d.ts" + ); + } + Ok(()) +} + +fn generate_reference(output: &Path) -> color_eyre::Result { + StatuslineState::export_all_to(output)?; + UiTree::export_all_to(output)?; + let mut generated = std::fs::read_to_string(output.join("statusline.d.ts"))?; + generated.push('\n'); + + // Item IDs use the same display serialization as the native field editor. + let items = StatusLineItem::iter() + .map(|item| serde_json::to_string(&item)) + .collect::, _>>()?; + writeln!( + generated, + "export type StatuslineItemId = {};", + items.join(" | ") + )?; + for name in ["Text", "Bold", "Italic", "Underline", "Link", "Row"] { + let tag = name.to_ascii_lowercase(); + writeln!( + generated, + "export type {name}Element = Extract;" + )?; + } + + writeln!(generated, "export {}", RateLimitWindow::decl())?; + generated.push_str( + "export type ThemeColor = Extract;\n\ + export type AnsiColor = Exclude;\n", + ); + + let mut generated = generated + .lines() + .map(str::trim_end) + .collect::>() + .join("\n"); + generated.push('\n'); + Ok(generated) +} diff --git a/codex-rs/tui/src/chatwidget/statusline_state.rs b/codex-rs/tui/src/chatwidget/statusline_state.rs index fb1a098fa5..553b65e807 100644 --- a/codex-rs/tui/src/chatwidget/statusline_state.rs +++ b/codex-rs/tui/src/chatwidget/statusline_state.rs @@ -21,6 +21,7 @@ use serde::Serialize; use strum_macros::Display; #[derive(Serialize)] +#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))] pub(crate) struct StatuslineState { account: account::Account, app: StatuslineStateApp, @@ -29,20 +30,38 @@ pub(crate) struct StatuslineState { } #[derive(Serialize)] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", rename = "App") +)] struct StatuslineStateApp { cli_version: &'static str, display_mode: crate::history_cell::HistoryRenderMode, } #[derive(Serialize)] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", rename = "Config") +)] struct StatuslineStateConfig { + #[cfg_attr(test, ts(type = "StatuslineItemId[]"))] statusline_items: Vec, #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] profile: Option, } #[derive(Serialize)] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", rename = "Thread") +)] struct StatuslineStateThread { + #[cfg_attr(test, ts(inline))] id: codex_protocol::ThreadId, name: Option, agent: StatuslineStateAgent, @@ -50,23 +69,41 @@ struct StatuslineStateThread { workspace: StatuslineStateWorkspace, usage: usage::Usage, #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] approval: Option, #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] permissions: Option, } #[derive(Serialize)] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", rename = "Workspace") +)] struct StatuslineStateWorkspace { + #[cfg_attr(test, ts(inline))] cwd: codex_utils_path_uri::LegacyAppPathString, } #[derive(Serialize)] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", rename = "Agent") +)] struct StatuslineStateAgent { state: StatuslineStateRunState, } #[derive(Serialize, Display)] #[serde(rename_all = "lowercase")] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", rename = "RunState") +)] pub(super) enum StatuslineStateRunState { Starting, Ready, @@ -76,14 +113,21 @@ pub(super) enum StatuslineStateRunState { } #[derive(Serialize)] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", rename = "Model", optional_fields) +)] struct StatuslineStateModel { #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(inline))] access_program: Option, display_name: String, #[serde(skip_serializing_if = "Option::is_none")] id: Option, provider: String, #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(inline))] reasoning_level: Option, #[serde(skip_serializing_if = "Option::is_none")] service_tier: Option, @@ -92,6 +136,11 @@ struct StatuslineStateModel { } #[derive(Serialize)] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", rename = "Approval") +)] struct StatuslineStateApproval { policy: StatuslineStateApprovalPolicy, reviewer: StatuslineStateApprovalReviewer, @@ -99,6 +148,11 @@ struct StatuslineStateApproval { #[derive(Serialize)] #[serde(rename_all = "kebab-case")] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", rename = "ApprovalPolicy") +)] enum StatuslineStateApprovalPolicy { Untrusted, OnRequest, @@ -108,15 +162,26 @@ enum StatuslineStateApprovalPolicy { #[derive(Serialize)] #[serde(rename_all = "kebab-case")] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", rename = "ApprovalReviewer") +)] enum StatuslineStateApprovalReviewer { User, AutoReview, } #[derive(Serialize)] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", rename = "Permissions") +)] struct StatuslineStatePermissions { display_name: String, #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] profile_id: Option, #[serde(flatten)] enforcement: StatuslineStateEnforcement, @@ -124,19 +189,31 @@ struct StatuslineStatePermissions { #[derive(Serialize)] #[serde(tag = "type", rename_all = "lowercase")] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", rename = "Enforcement") +)] enum StatuslineStateEnforcement { Managed { file_system: StatuslineStateFileSystem, + #[cfg_attr(test, ts(inline))] network: NetworkSandboxPolicy, }, Disabled, External { + #[cfg_attr(test, ts(inline))] network: NetworkSandboxPolicy, }, } #[derive(Serialize)] #[serde(tag = "type", rename_all = "lowercase")] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", rename = "FileSystem") +)] enum StatuslineStateFileSystem { Restricted, Unrestricted, @@ -265,3 +342,7 @@ impl ChatWidget { }) } } + +#[cfg(test)] +#[path = "statusline_contract_tests.rs"] +mod contract_tests; diff --git a/codex-rs/tui/src/chatwidget/statusline_state/account.rs b/codex-rs/tui/src/chatwidget/statusline_state/account.rs index d266874455..72a49fb046 100644 --- a/codex-rs/tui/src/chatwidget/statusline_state/account.rs +++ b/codex-rs/tui/src/chatwidget/statusline_state/account.rs @@ -6,22 +6,36 @@ use codex_protocol::protocol::RateLimitWindow; use serde::Serialize; #[derive(Serialize)] +#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))] pub(super) struct Account { rate_limits: Vec, #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] workspace: Option, } #[derive(Serialize)] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", rename = "AccountWorkspace") +)] struct Workspace { headline: String, } #[derive(Serialize)] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", rename = "RateLimitSnapshot") +)] struct RateLimit { limit_id: &'static str, limit_name: Option, + #[cfg_attr(test, ts(type = "RateLimitWindow | null"))] primary_limit: Option, + #[cfg_attr(test, ts(type = "RateLimitWindow | null"))] secondary_limit: Option, } diff --git a/codex-rs/tui/src/chatwidget/statusline_state/usage.rs b/codex-rs/tui/src/chatwidget/statusline_state/usage.rs index f6b006894f..ed4f2a0ee4 100644 --- a/codex-rs/tui/src/chatwidget/statusline_state/usage.rs +++ b/codex-rs/tui/src/chatwidget/statusline_state/usage.rs @@ -5,6 +5,11 @@ use crate::token_usage::TokenUsage; use serde::Serialize; #[derive(Serialize)] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", optional_fields) +)] pub(super) struct Usage { context: Context, #[serde(skip_serializing_if = "Option::is_none")] @@ -14,6 +19,11 @@ pub(super) struct Usage { } #[derive(Serialize)] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", optional_fields) +)] struct Cost { #[serde(skip_serializing_if = "Option::is_none")] total_cost_usd: Option, @@ -22,21 +32,39 @@ struct Cost { } #[derive(Serialize)] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", optional_fields) +)] struct Context { #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(as = "Option"))] context_window_size: Option, #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(as = "Option"))] used_tokens: Option, #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(as = "Option"))] used_percentage: Option, } #[derive(Serialize)] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", rename = "TokenUsage") +)] struct Counts { + #[cfg_attr(test, ts(type = "number"))] total_input_tokens: i64, + #[cfg_attr(test, ts(type = "number"))] cache_read_input_tokens: i64, + #[cfg_attr(test, ts(type = "number"))] cache_write_input_tokens: i64, + #[cfg_attr(test, ts(type = "number"))] other_input_tokens: i64, + #[cfg_attr(test, ts(type = "number"))] output_tokens: i64, } diff --git a/codex-rs/tui/src/history_cell/mod.rs b/codex-rs/tui/src/history_cell/mod.rs index ff152d5d4e..4940b27ecf 100644 --- a/codex-rs/tui/src/history_cell/mod.rs +++ b/codex-rs/tui/src/history_cell/mod.rs @@ -156,6 +156,11 @@ pub(crate) use warnings::warning_entries; mod tests; #[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize)] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", rename = "DisplayMode") +)] pub(crate) enum HistoryRenderMode { #[serde(rename = "standard")] Rich, diff --git a/codex-rs/tui/src/ui_tree.rs b/codex-rs/tui/src/ui_tree.rs index f7326697db..f3e5497fdb 100644 --- a/codex-rs/tui/src/ui_tree.rs +++ b/codex-rs/tui/src/ui_tree.rs @@ -19,15 +19,23 @@ use serde::Serialize; const MAX_GAP: u64 = (1 << 53) - 1; const MAX_TEXT_BYTES: usize = 16 * 1024; -/// A nullable root with bounded depth, node count, and total UTF-8 leaf bytes. +/// A nullable root. JSON is limited to 64 KiB, 256 non-null nodes, depth 16 (root at 0), +/// and 16 KiB of UTF-8 text across all string leaves. #[derive(Clone, Debug, PartialEq, Serialize)] +#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))] pub(crate) struct UiTree(pub(crate) Option); #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "kebab-case", deny_unknown_fields)] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", rename = "Element") +)] pub(crate) enum UiNode { Text { #[serde(default, skip_serializing_if = "is_default")] + #[cfg_attr(test, ts(as = "Option", optional))] props: TextProps, children: Vec>, }, @@ -54,6 +62,7 @@ pub(crate) enum UiNode { #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] +#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts", optional_fields = nullable))] pub(crate) struct TextProps { #[serde( deserialize_with = "decode::optional_token", @@ -73,6 +82,7 @@ pub(crate) struct TextProps { #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] +#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts", optional_fields = nullable))] pub(crate) struct LinkProps { pub(crate) href: LinkHref, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -82,6 +92,11 @@ pub(crate) struct LinkProps { /// An absolute HTTP(S) URL without control characters, at most 8 KiB in UTF-8. #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(try_from = "String")] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", type = "string") +)] pub(crate) struct LinkHref(String); impl TryFrom for LinkHref { @@ -105,9 +120,11 @@ impl TryFrom<&str> for LinkHref { #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] +#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts", optional_fields = nullable))] pub(crate) struct RowProps { /// Horizontal spacing in terminal columns, expressed as a non-negative JavaScript-safe integer. #[serde(deserialize_with = "decode::gap")] + #[cfg_attr(test, ts(type = "number"))] pub(crate) gap: u64, #[serde( default, @@ -120,11 +137,13 @@ pub(crate) struct RowProps { deserialize_with = "decode::token", skip_serializing_if = "is_default" )] + #[cfg_attr(test, ts(as = "Option", optional))] wrap: RowWrap, } #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] +#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))] enum RowWrap { #[default] Nowrap, diff --git a/codex-rs/tui/src/ui_tree/theme.rs b/codex-rs/tui/src/ui_tree/theme.rs index d98aab72ef..fdb4bd3269 100644 --- a/codex-rs/tui/src/ui_tree/theme.rs +++ b/codex-rs/tui/src/ui_tree/theme.rs @@ -63,6 +63,7 @@ fn terminal_color(color: Option, fallback: TerminalColor) -> Term #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] +#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))] pub(super) enum Color { Primary, Surface, @@ -121,8 +122,14 @@ impl Color { } } +/// A six-digit sRGB color in `#RRGGBB` form. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)] #[serde(try_from = "String", into = "String")] +#[cfg_attr( + test, + derive(ts_rs::TS), + ts(export_to = "statusline.d.ts", type = "`#${string}`") +)] pub(super) struct HexRgb((u8, u8, u8)); impl TryFrom for HexRgb { @@ -148,6 +155,7 @@ impl From for String { #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] +#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))] pub(super) enum TextWeight { Normal, Bold, diff --git a/codex-rs/tui/tests/fixtures/statusline/contract.check.ts b/codex-rs/tui/tests/fixtures/statusline/contract.check.ts new file mode 100644 index 0000000000..851ee02eb0 --- /dev/null +++ b/codex-rs/tui/tests/fixtures/statusline/contract.check.ts @@ -0,0 +1,49 @@ +import type { + Color, + RowElement, + StatuslineItemId, + StatuslineState, + UiTree, +} from "../../../../skills/src/assets/samples/create-statusline/references/statusline.js"; + +// Typecheck a provider as an author would: the snapshot arrives over JSON, and +// each returned element is sent as resource text. +export function render(state: StatuslineState): UiTree { + const children: UiTree[] = []; + const { account, config, thread } = state; + if (config.statusline_items.includes("model")) { + children.push({ + type: "text", + props: { color: "status-model", weight: "bold" }, + children: [thread.model.display_name], + }); + } + + const workspace = account.workspace?.headline; + if (workspace) { + children.push({ type: "italic", children: [workspace] }); + } + const window = account.rate_limits[0]?.primary_limit; + if (window && window.resets_at !== null) { + children.push( + `${window.used_percent}% until ${new Date(window.resets_at * 1_000).toISOString()}`, + ); + } + if (thread.usage.total) { + children.push(String(thread.usage.total.output_tokens)); + } + if (config.statusline_items.includes("current-dir")) { + children.push(thread.workspace.cwd); + } + if (children.length === 0) { + return null; + } + return { type: "row", props: { gap: 1, wrap: "wrap" }, children }; +} + +// @ts-expect-error The snapshot emits the canonical ID even when config used an alias. +const alias: StatuslineItemId = "project-root"; +// @ts-expect-error Row props require a gap in terminal columns. +const missingGap: RowElement = { type: "row", props: {}, children: [] }; +// @ts-expect-error Color literals begin with a hash or match one of the named tokens. +const invalidColor: Color = "ff00bb"; diff --git a/codex-rs/tui/tests/fixtures/statusline/tsconfig.json b/codex-rs/tui/tests/fixtures/statusline/tsconfig.json new file mode 100644 index 0000000000..f532674d55 --- /dev/null +++ b/codex-rs/tui/tests/fixtures/statusline/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "exactOptionalPropertyTypes": true, + "noEmit": true, + "types": [] + }, + "files": ["contract.check.ts"] +}