返回 CodeWhale
status.rs
根目录 / crates / tui / src / commands / groups / config / status.rs
1 //! Runtime status command.
2
3 use super::policy_messages::{StatusMessages as Messages, StatusText as MessageId};
4 use codewhale_command_contract::config_policy::*;
5 use codewhale_command_contract::handler::{CommandCapabilities, CommandContexts, CommandHandler};
6 use codewhale_command_contract::metadata::{CommandInfo, RegisterCommand};
7 use codewhale_command_contract::outcome::ConfigStatusCommandResult as CommandResult;
8 use codewhale_command_contract::types::{CommandApprovalMode, CommandMode};
9 use std::borrow::Cow;
10 use std::fmt::Write as _;
11 use unicode_width::UnicodeWidthStr;
12
13 pub const CAPABILITIES: CommandCapabilities =
14 CommandCapabilities::CONFIG_STATUS.union(CommandCapabilities::PRESENTATION);
15 pub struct StatusCmd;
16 impl RegisterCommand<CommandResult> for StatusCmd {
17 fn info() -> &'static CommandInfo {
18 &CommandInfo {
19 name: "status",
20 aliases: &[],
21 usage: "/status",
22 description_key: "cmd_status_description",
23 }
24 }
25 fn handler() -> CommandHandler<CommandResult> {
26 CommandHandler::Contextual {
27 capabilities: CAPABILITIES,
28 handler: execute,
29 }
30 }
31 }
32 fn tr(messages: &Messages, id: MessageId) -> Cow<'static, str> {
33 messages.text(id)
34 }
35
36 /// Show a compact runtime status report for the current TUI session.
37 pub fn execute(contexts: CommandContexts<'_>, _arg: Option<&str>) -> CommandResult {
38 let parts = contexts.into_parts();
39 let Some(status) = parts.config_status else {
40 return CommandResult::error("Command capability unavailable: config_status");
41 };
42 let Some(presentation) = parts.presentation else {
43 return CommandResult::error("Command capability unavailable: presentation");
44 };
45 let messages = match Messages::load(presentation) {
46 Ok(messages) => messages,
47 Err(error) => return CommandResult::error(error),
48 };
49 CommandResult::message(format_status(&status.snapshot(), &messages))
50 }
51
52 /// Models.dev live-layer freshness: source, row count, and age (#4187).
53 fn catalog_summary(view: &ConfigStatusView, locale: &Messages) -> Option<String> {
54 let st = &view.catalog;
55 let mut out = tr(
56 locale,
57 match st.freshness {
58 StatusCatalogFreshness::Bundled => return None,
59 StatusCatalogFreshness::Live => MessageId::StatusCatalogLive,
60 StatusCatalogFreshness::Stale => MessageId::StatusCatalogStale,
61 StatusCatalogFreshness::Failed => MessageId::StatusCatalogRefreshFailed,
62 },
63 )
64 .into_owned();
65 if st.offering_count > 0 {
66 let _ = write!(
67 out,
68 " · {}",
69 localized(
70 locale,
71 MessageId::StatusCatalogOfferings,
72 &[("{count}", &st.offering_count.to_string())],
73 )
74 );
75 }
76 if let Some(fetched_at) = st.fetched_at {
77 let _ = write!(
78 out,
79 " · {}",
80 localized(
81 locale,
82 MessageId::StatusCatalogFetched,
83 &[("{age}", &age_label(fetched_at, view.observed_at, locale))],
84 )
85 );
86 }
87 if let Some(err) = st.last_error.as_deref().filter(|e| !e.is_empty())
88 && st.freshness == StatusCatalogFreshness::Failed
89 {
90 let _ = write!(out, " ({err})");
91 }
92 Some(out)
93 }
94
95 fn age_label(then: u64, now: u64, locale: &Messages) -> String {
96 let secs = now.saturating_sub(then);
97 let (id, count) = if secs < 60 {
98 return tr(locale, MessageId::SessionsTimeJustNow).into_owned();
99 } else if secs < 3600 {
100 (MessageId::SessionsTimeMinutesAgo, secs / 60)
101 } else if secs < 86_400 {
102 (MessageId::SessionsTimeHoursAgo, secs / 3600)
103 } else {
104 (MessageId::SessionsTimeDaysAgo, secs / 86_400)
105 };
106 localized(locale, id, &[("{count}", &count.to_string())])
107 }
108
109 /// Cloud facts provenance: channel, version, key, age, origin — or why the
110 /// bundled facts are in use. Off by default.
111 fn cloud_facts_summary(view: &ConfigStatusView, locale: &Messages) -> String {
112 if view.cloud_facts == codewhale_protocol::cloud_facts::CloudFactsState::Off {
113 tr(locale, MessageId::StatusCloudFactsOff).into_owned()
114 } else {
115 view.cloud_facts.label(view.observed_at)
116 }
117 }
118
119 /// Row label column, in columns. English's widest label is `Context window:`
120 /// (15); the tail space in [`push_row`] makes its value start at column 19.
121 /// Longer localized labels extend naturally rather than being truncated.
122 const LABEL_WIDTH: usize = 16;
123
124 fn format_status(view: &ConfigStatusView, locale: &Messages) -> String {
125 let mut out = String::new();
126 let (context_used, context_max, context_percent) = context_usage(view);
127
128 // A transcript cell has no ink and no rules, so the only grouping mark
129 // available is a blank row. It is spent on the two group boundaries and
130 // nowhere else: standing facts about the route and the machine first,
131 // then everything that accumulates as the session runs.
132 let _ = writeln!(out, "codewhale {}", view.version);
133 let _ = writeln!(out);
134
135 push_row(
136 &mut out,
137 locale,
138 MessageId::StatusLabelRoute,
139 &route_summary(view, locale),
140 );
141 push_row(
142 &mut out,
143 locale,
144 MessageId::StatusLabelDirectory,
145 &codewhale_protocol::display::display_path_with_home(&view.workspace, view.home.as_deref()),
146 );
147 push_row(
148 &mut out,
149 locale,
150 MessageId::StatusLabelProjectDocs,
151 &project_docs(&view.project_docs, locale),
152 );
153 push_row(
154 &mut out,
155 locale,
156 MessageId::StatusLabelMode,
157 &posture_summary(view, locale),
158 );
159 push_row(
160 &mut out,
161 locale,
162 MessageId::StatusLabelSafety,
163 safety_summary(view, locale).as_ref(),
164 );
165 push_row(
166 &mut out,
167 locale,
168 MessageId::StatusLabelMcp,
169 &localized(
170 locale,
171 MessageId::StatusMcpConfigured,
172 &[("{count}", &view.mcp_configured_count.to_string())],
173 ),
174 );
175 if let Some(model) = &view.model_pin_drift {
176 let notice = localized(
177 locale,
178 MessageId::StatusModelNotInRoster,
179 &[("{model}", model), ("{provider}", &view.provider)],
180 );
181 let _ = writeln!(out, " {notice}");
182 }
183 if let Some(drift) = &view.fleet_drift {
184 let value = localized(
185 locale,
186 MessageId::StatusFleetDrifted,
187 &[
188 ("{fleet}", &drift.name),
189 ("{count}", &drift.ids.len().to_string()),
190 ("{ids}", &drift.ids.join(", ")),
191 ],
192 );
193 push_row(&mut out, locale, MessageId::StatusLabelFleet, &value);
194 }
195 if let Some(notice) = &view.snapshot_notice {
196 let _ = writeln!(out, " {}", snapshot_notice(notice, locale));
197 }
198 let _ = writeln!(out);
199
200 push_row(
201 &mut out,
202 locale,
203 MessageId::StatusLabelContextWindow,
204 &localized(
205 locale,
206 MessageId::StatusContextUsage,
207 &[
208 ("{percent}", &format!("{context_percent:.1}")),
209 ("{used}", &context_used.to_string()),
210 ("{max}", &context_max.to_string()),
211 ],
212 ),
213 );
214 let mut source_summary =
215 context_window_source_label(context_window_source(view), locale).into_owned();
216 // The default bundled source needs no second catalog label. Keeping it
217 // compact preserves the 80-column budget as well as the report's row count.
218 if let Some(catalog) = catalog_summary(view, locale) {
219 let _ = write!(
220 source_summary,
221 " · {}: {}",
222 tr(locale, MessageId::StatusLabelCatalog),
223 catalog
224 );
225 }
226 let _ = write!(
227 source_summary,
228 " · {}: {}",
229 tr(locale, MessageId::StatusLabelCloudFacts),
230 cloud_facts_summary(view, locale)
231 );
232 push_row(
233 &mut out,
234 locale,
235 MessageId::StatusLabelWindowSource,
236 &source_summary,
237 );
238 if let Some(key) = context_window_override_key(view, locale) {
239 push_row(&mut out, locale, MessageId::StatusLabelWindowOverride, &key);
240 }
241 push_row(
242 &mut out,
243 locale,
244 MessageId::StatusLabelSession,
245 &session_summary(view, locale),
246 );
247 push_row(
248 &mut out,
249 locale,
250 MessageId::StatusLabelSessionTokens,
251 &session_tokens(view, locale),
252 );
253 let cost = view
254 .cost_label
255 .clone()
256 .unwrap_or_else(|| super::money::format_cost_amount_precise(view.cost, view.currency));
257 push_row(&mut out, locale, MessageId::StatusLabelSessionCost, &cost);
258 // The full, untrimmed session metrics strip (the footer sheds groups to
259 // fit; here every group that has evidence is printed). It keeps its own
260 // template because the label and metrics form one localized sentence.
261 let snapshot = view.metrics;
262 if !snapshot.is_empty() {
263 let metrics = codewhale_command_contract::metrics::RenderedStrip {
264 groups: codewhale_command_contract::metrics::build_groups(
265 snapshot,
266 &metric_labels(locale),
267 ),
268 separators: codewhale_command_contract::metrics::Separators::for_ascii(view.ascii_safe),
269 }
270 .text();
271 let _ = writeln!(
272 out,
273 " {}",
274 tr(locale, MessageId::SessionMetricsStatusLine).replace("{metrics}", &metrics)
275 );
276 }
277 let tool_output_status = &view.tool_outputs;
278 push_row(
279 &mut out,
280 locale,
281 MessageId::StatusLabelToolOutputs,
282 &codewhale_command_contract::tool_outputs::format_tool_output_status(
283 tool_output_status,
284 &tool_output_labels(locale),
285 ),
286 );
287 let _ = writeln!(out);
288 // Two whole fields left this report rather than being printed at the same
289 // weight as everything else: the per-turn token ledger, which `/tokens`
290 // already prints in full, and the list of enabled footer item keys, which
291 // is `/statusline`'s own subject. The pointer costs one row; they cost
292 // seven.
293 let _ = writeln!(out, " {}", tr(locale, MessageId::StatusPointers));
294
295 out
296 }
297
298 /// Provider, model, and effort as one lockup, matching the header rail.
299 ///
300 /// These were three rows (`Provider:`, `Model:` with the effort parenthesised)
301 /// for one fact — which route is this turn going to. The header already joins
302 /// them with a middle dot; `/status` now agrees with it.
303 fn route_summary(view: &ConfigStatusView, locale: &Messages) -> String {
304 let model = view.model.clone();
305 let reasoning = view.reasoning.clone();
306 localized(
307 locale,
308 MessageId::StatusRouteSummary,
309 &[
310 ("{provider}", &view.provider),
311 ("{model}", &model),
312 ("{reasoning}", &reasoning),
313 ],
314 )
315 }
316
317 /// Mode and the permissions that qualify it, as one statement of posture.
318 fn posture_summary(view: &ConfigStatusView, locale: &Messages) -> String {
319 let trust = if view.trusted {
320 tr(locale, MessageId::StatusTrustedWorkspace)
321 } else {
322 tr(locale, MessageId::StatusWorkspace)
323 };
324 let shell = if view.allow_shell {
325 tr(locale, MessageId::StatusShellOn)
326 } else {
327 tr(locale, MessageId::StatusShellOff)
328 };
329 let mode = tr(
330 locale,
331 match view.mode {
332 CommandMode::Agent => MessageId::AppModeAgent,
333 CommandMode::Plan => MessageId::AppModePlan,
334 },
335 );
336 let approval = approval_summary(view.approval_mode, locale);
337 localized(
338 locale,
339 MessageId::StatusPostureSummary,
340 &[
341 ("{mode}", mode.as_ref()),
342 ("{approval}", approval.as_ref()),
343 ("{shell}", shell.as_ref()),
344 ("{trust}", trust.as_ref()),
345 ],
346 )
347 }
348
349 fn approval_summary(mode: CommandApprovalMode, locale: &Messages) -> Cow<'static, str> {
350 tr(
351 locale,
352 match mode {
353 CommandApprovalMode::Suggest => MessageId::StatusApprovalAsk,
354 CommandApprovalMode::AcceptEdits => MessageId::StatusApprovalAcceptEdits,
355 CommandApprovalMode::Auto => MessageId::StatusApprovalAuto,
356 CommandApprovalMode::Bypass => MessageId::StatusApprovalFullAccess,
357 CommandApprovalMode::Never => MessageId::StatusApprovalNever,
358 },
359 )
360 }
361
362 /// Session identity and the size of the conversation it names.
363 fn session_summary(view: &ConfigStatusView, locale: &Messages) -> String {
364 let session = view
365 .session_id
366 .clone()
367 .unwrap_or_else(|| tr(locale, MessageId::StatusSessionNotSaved).into_owned());
368 localized(
369 locale,
370 MessageId::StatusSessionSummary,
371 &[
372 ("{session}", &session),
373 ("{cells}", &view.history_count.to_string()),
374 ("{messages}", &view.message_count.to_string()),
375 ],
376 )
377 }
378
379 /// Cumulative token ledger on one row.
380 ///
381 /// The session input/output split and the cumulative cache totals live only
382 /// here; the per-turn figures they used to sit beside are `/tokens`.
383 fn session_tokens(view: &ConfigStatusView, locale: &Messages) -> String {
384 let cache = if view.cache_hit_tokens == 0 && view.cache_miss_tokens == 0 {
385 tr(locale, MessageId::StatusCacheNotReported).into_owned()
386 } else {
387 localized(
388 locale,
389 MessageId::StatusCacheSummary,
390 &[
391 ("{hit}", &view.cache_hit_tokens.to_string()),
392 ("{miss}", &view.cache_miss_tokens.to_string()),
393 ],
394 )
395 };
396 localized(
397 locale,
398 MessageId::StatusSessionTokensSummary,
399 &[
400 ("{input}", &view.input_tokens.to_string()),
401 ("{output}", &view.output_tokens.to_string()),
402 ("{total}", &view.total_tokens.to_string()),
403 ("{cache}", &cache),
404 ],
405 )
406 }
407
408 fn push_row(out: &mut String, locale: &Messages, label: MessageId, value: &str) {
409 let label = format!("{}:", tr(locale, label));
410 let padding = LABEL_WIDTH.saturating_sub(UnicodeWidthStr::width(label.as_str()));
411 let _ = writeln!(out, " {label}{:padding$} {value}", "");
412 }
413
414 fn safety_summary(view: &ConfigStatusView, locale: &Messages) -> Cow<'static, str> {
415 let id = match view.safety {
416 StatusSafety::ReadOnly { enforced: false } => MessageId::StatusSafetyReadOnlyUnenforced,
417 StatusSafety::ReadOnly { enforced: true } => MessageId::StatusSafetyReadOnly,
418 StatusSafety::WorkspaceWrite {
419 enforced: false,
420 network_access: true,
421 } => MessageId::StatusSafetyWorkspaceWriteUnenforcedNetworkOn,
422 StatusSafety::WorkspaceWrite {
423 enforced: false,
424 network_access: false,
425 } => MessageId::StatusSafetyWorkspaceWriteUnenforcedNetworkOff,
426 StatusSafety::WorkspaceWrite {
427 enforced: true,
428 network_access: true,
429 } => MessageId::StatusSafetyWorkspaceWriteNetworkOn,
430 StatusSafety::WorkspaceWrite {
431 enforced: true,
432 network_access: false,
433 } => MessageId::StatusSafetyWorkspaceWriteNetworkOff,
434 StatusSafety::FullAccess { no_new_privs } => safety_disabled_message(no_new_privs),
435 StatusSafety::External => MessageId::StatusSafetyExternal,
436 };
437 tr(locale, id)
438 }
439
440 /// The full-access safety row must disclose the residual setuid block
441 /// truthfully (#5723): the no-new-privileges kernel flag is set at startup in
442 /// every narrower posture and is irreversible, so "sandbox disabled" alone
443 /// would promise `sudo`/setuid workflows the process tree cannot perform.
444 /// `None` is a platform without the flag, where the plain label is accurate.
445 pub fn safety_disabled_message(no_new_privs_active: Option<bool>) -> MessageId {
446 match no_new_privs_active {
447 Some(true) => MessageId::StatusSafetyDisabledSetuidBlocked,
448 Some(false) => MessageId::StatusSafetyDisabledSetuidAllowed,
449 None => MessageId::StatusSafetyDisabled,
450 }
451 }
452
453 fn project_docs(docs: &[String], locale: &Messages) -> String {
454 if docs.is_empty() {
455 tr(locale, MessageId::StatusProjectDocsNone).into_owned()
456 } else {
457 docs.join(", ")
458 }
459 }
460
461 fn context_usage(view: &ConfigStatusView) -> (usize, u32, f64) {
462 let used = view.context_used;
463 let max = view.context_window;
464 (
465 used,
466 max,
467 ((used as f64 / f64::from(max)) * 100.0).clamp(0.0, 100.0),
468 )
469 }
470
471 /// Where the effective context window came from.
472 ///
473 /// #5134: `/status` printed the window as a bare number, so a user watching
474 /// auto-compaction fire at 128K on a 1M-capable model had no way to learn that
475 /// `context_window` exists, let alone which table it belongs on. The
476 /// provenance label alone is not enough — the actionable half is the key path,
477 /// which now gets its own aligned row rather than a parenthesis that wrapped
478 /// the provenance off the end of the line.
479 fn context_window_source(view: &ConfigStatusView) -> StatusContextSource {
480 view.context_source
481 }
482
483 fn context_window_source_label(
484 source: StatusContextSource,
485 locale: &Messages,
486 ) -> Cow<'static, str> {
487 tr(
488 locale,
489 match source {
490 StatusContextSource::Configured | StatusContextSource::UserDeclared => {
491 MessageId::StatusContextSourceConfigured
492 }
493 StatusContextSource::ConfiguredModel => MessageId::StatusContextSourceConfiguredModel,
494 StatusContextSource::ProviderReported => MessageId::StatusContextSourceProviderReported,
495 StatusContextSource::StaticKimiCodeSafeFloor => {
496 MessageId::StatusContextSourceKimiSafeFloor
497 }
498 StatusContextSource::Catalog => MessageId::StatusContextSourceCatalog,
499 StatusContextSource::NameSuffixHint => MessageId::StatusContextSourceModelHint,
500 StatusContextSource::Fallback => MessageId::StatusContextSourceFallback,
501 },
502 )
503 }
504
505 /// The exact key that changes the window, or `None` when the user already set
506 /// it and the row would be naming a key they have already used.
507 fn context_window_override_key(view: &ConfigStatusView, locale: &Messages) -> Option<String> {
508 view.window_override.as_ref().map(|key| match key {
509 StatusWindowOverride::Provider(table) => localized(
510 locale,
511 MessageId::StatusWindowOverrideProvider,
512 &[("{table}", table)],
513 ),
514 StatusWindowOverride::ActiveProvider => {
515 tr(locale, MessageId::StatusWindowOverrideActiveProvider).into_owned()
516 }
517 })
518 }
519
520 fn localized(locale: &Messages, id: MessageId, replacements: &[(&str, &str)]) -> String {
521 super::interpolate(&tr(locale, id), replacements)
522 }
523
524 fn snapshot_notice(notice: &StatusSnapshotNotice, locale: &Messages) -> String {
525 let id = match notice.scope {
526 StatusSnapshotScope::WorkspaceTooLarge => MessageId::SnapshotsDisabledTooLarge,
527 StatusSnapshotScope::TooManyFiles => MessageId::SnapshotsDisabledTooManyFiles,
528 StatusSnapshotScope::UnsafeLocation => MessageId::SnapshotsDisabledUnsafeLocation,
529 StatusSnapshotScope::HistoryRepaired => MessageId::SnapshotsHistoryRepaired,
530 StatusSnapshotScope::Failing => MessageId::SnapshotsFailing,
531 };
532 notice.render(&tr(locale, id))
533 }
534
535 fn metric_labels(locale: &Messages) -> codewhale_command_contract::metrics::MetricLabels {
536 codewhale_command_contract::metrics::MetricLabels {
537 turn: tr(locale, MessageId::SessionMetricsTurn).into_owned(),
538 turns: tr(locale, MessageId::SessionMetricsTurns).into_owned(),
539 step: tr(locale, MessageId::SessionMetricsStep).into_owned(),
540 steps: tr(locale, MessageId::SessionMetricsSteps).into_owned(),
541 llm: tr(locale, MessageId::SessionMetricsLlm).into_owned(),
542 tools: tr(locale, MessageId::SessionMetricsTools).into_owned(),
543 ttft: tr(locale, MessageId::SessionMetricsTtft).into_owned(),
544 tokens_per_second: tr(locale, MessageId::SessionMetricsTokensPerSecond).into_owned(),
545 cache: tr(locale, MessageId::SessionMetricsCache).into_owned(),
546 input: tr(locale, MessageId::SessionMetricsInput).into_owned(),
547 }
548 }
549 fn tool_output_labels(
550 locale: &Messages,
551 ) -> codewhale_command_contract::tool_outputs::ToolOutputLabels {
552 codewhale_command_contract::tool_outputs::ToolOutputLabels {
553 raw_pressure: tr(locale, MessageId::StatusToolRawPressure).into_owned(),
554 compact_receipts: tr(locale, MessageId::StatusToolCompactReceipts).into_owned(),
555 artifacts: tr(locale, MessageId::StatusToolArtifacts).into_owned(),
556 none: tr(locale, MessageId::StatusToolNone).into_owned(),
557 }
558 }
559
559 lines RUST