Add TypeScript contracts for custom statusline providers (#62034)

## What changed

Bundle a generated `statusline.d.ts` reference with the `create-statusline` skill, covering status snapshots, UI trees, colors, and canonical statusline item IDs. Add test-only `ts-rs` derives and an `UPDATE_STATUSLINE_TYPES` regeneration path.

Clarify that rate-limit usage percentages can exceed 100.

## Testing

Add a Rust test that checks key type exports in the installed skill and a strict TypeScript fixture covering provider rendering and invalid item IDs, row props, and colors.

GitOrigin-RevId: f615e0b3c2cd3d0d95a75de36ce0a84467ecd5b6
This commit is contained in:
Joe Savona
2026-11-17 11:58:26 +00:00
committed by copyberry
parent 59ac39addb
commit 7df454ceb5
17 changed files with 414 additions and 2 deletions
+1
View File
@@ -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
+2
View File
@@ -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
+2
View File
@@ -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",
+1 -1
View File
@@ -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")]
@@ -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<RateLimitSnapshot>, 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<Element | null>, } | { "type": "link", props: LinkProps, children: Array<Element | null>, } | { "type": "row", props: RowProps, children: Array<Element | null>, } | { "type": "bold", children: Array<Element | null>, } | { "type": "italic", children: Array<Element | null>, } | { "type": "underline", children: Array<Element | null>, } | 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<Element, { type: "text" }>;
export type BoldElement = Extract<Element, { type: "bold" }>;
export type ItalicElement = Extract<Element, { type: "italic" }>;
export type UnderlineElement = Extract<Element, { type: "underline" }>;
export type LinkElement = Extract<Element, { type: "link" }>;
export type RowElement = Extract<Element, { type: "row" }>;
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<Color, "primary" | "surface" | "accent">;
export type AnsiColor = Exclude<Color, ThemeColor | StatusColor | HexRgb>;
+2
View File
@@ -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 }
@@ -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,
@@ -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<String> {
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::<Result<Vec<_>, _>>()?;
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<Element, {{ type: \"{tag}\" }}>;"
)?;
}
writeln!(generated, "export {}", RateLimitWindow::decl())?;
generated.push_str(
"export type ThemeColor = Extract<Color, \"primary\" | \"surface\" | \"accent\">;\n\
export type AnsiColor = Exclude<Color, ThemeColor | StatusColor | HexRgb>;\n",
);
let mut generated = generated
.lines()
.map(str::trim_end)
.collect::<Vec<_>>()
.join("\n");
generated.push('\n');
Ok(generated)
}
@@ -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<StatusLineItem>,
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(test, ts(optional))]
profile: Option<String>,
}
#[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<String>,
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<StatuslineStateApproval>,
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(test, ts(optional))]
permissions: Option<StatuslineStatePermissions>,
}
#[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<CyberAccessProgram>,
display_name: String,
#[serde(skip_serializing_if = "Option::is_none")]
id: Option<String>,
provider: String,
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(test, ts(inline))]
reasoning_level: Option<ReasoningEffort>,
#[serde(skip_serializing_if = "Option::is_none")]
service_tier: Option<String>,
@@ -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<String>,
#[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;
@@ -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<RateLimit>,
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(test, ts(optional))]
workspace: Option<Workspace>,
}
#[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<String>,
#[cfg_attr(test, ts(type = "RateLimitWindow | null"))]
primary_limit: Option<RateLimitWindow>,
#[cfg_attr(test, ts(type = "RateLimitWindow | null"))]
secondary_limit: Option<RateLimitWindow>,
}
@@ -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<f64>,
@@ -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<f64>"))]
context_window_size: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(test, ts(as = "Option<f64>"))]
used_tokens: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(test, ts(as = "Option<f64>"))]
used_percentage: Option<i64>,
}
#[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,
}
+5
View File
@@ -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,
+20 -1
View File
@@ -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<UiNode>);
#[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<TextProps>", optional))]
props: TextProps,
children: Vec<Option<UiNode>>,
},
@@ -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<String> 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<RowWrap>", 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,
+8
View File
@@ -63,6 +63,7 @@ fn terminal_color(color: Option<TerminalColor>, 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<String> for HexRgb {
@@ -148,6 +155,7 @@ impl From<HexRgb> 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,
@@ -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";
+12
View File
@@ -0,0 +1,12 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"exactOptionalPropertyTypes": true,
"noEmit": true,
"types": []
},
"files": ["contract.check.ts"]
}