返回 CodeWhale
tideline.rs
根目录 / crates / tui / src / tui / tideline.rs
1 //! Read-only projections for the Tideline terminal workbench contract.
2 //!
3 //! [`App`] remains the sole owner of runtime state. This module neither
4 //! replaces it nor introduces another settings store, event loop, or engine;
5 //! it gives render and input code typed snapshots of facts that existing
6 //! owners have already resolved.
7
8 use ratatui::layout::{Position, Rect};
9
10 use crate::tui::app::App;
11
12 /// A bounded view of the context window currently owned by the active route.
13 ///
14 /// Percent is stored in basis points (`10_000 == 100%`) so snapshots remain
15 /// equality-testable without making renderers compare floating-point values.
16 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
17 pub struct ContextBudgetSnapshot {
18 pub used_tokens: u32,
19 pub max_tokens: u32,
20 pub percent_basis_points: u16,
21 }
22
23 impl ContextBudgetSnapshot {
24 /// Project the existing context estimator without becoming a second
25 /// context-budget owner.
26 #[must_use]
27 pub(crate) fn from_app(app: &App) -> Option<Self> {
28 let (used, max_tokens, _) = crate::tui::ui::context_usage_snapshot(app)?;
29 let used_tokens = u32::try_from(used.max(0))
30 .unwrap_or(u32::MAX)
31 .min(max_tokens);
32 let percent_basis_points = if max_tokens == 0 {
33 0
34 } else {
35 let numerator = u64::from(used_tokens).saturating_mul(10_000);
36 let rounded = numerator
37 .saturating_add(u64::from(max_tokens) / 2)
38 .checked_div(u64::from(max_tokens))
39 .unwrap_or(0)
40 .min(10_000);
41 u16::try_from(rounded).unwrap_or(10_000)
42 };
43
44 Some(Self {
45 used_tokens,
46 max_tokens,
47 percent_basis_points,
48 })
49 }
50 }
51
52 /// The owner whose value currently wins for a setting fact.
53 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
54 pub enum SettingAuthority {
55 Session,
56 UserSettings,
57 WorkspaceConfiguration,
58 ManagedPolicy,
59 /// An environment variable or session (SSH) forces the effective value.
60 Environment,
61 /// The terminal program forces the effective value.
62 Terminal,
63 }
64
65 /// When an edit to a setting becomes observable.
66 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
67 pub enum SettingApplySemantics {
68 EffectiveNow,
69 Immediate,
70 NextSession,
71 #[cfg(test)]
72 RestartRequired,
73 ReadOnly,
74 /// Persisted and the live owner updated now, but a running consumer keeps
75 /// the old value until it is explicitly reloaded (MCP servers after an
76 /// `mcp_config_path` change: `/mcp reload`).
77 ReloadRequired,
78 /// The UI applies the edit now while engine tools only read it at startup
79 /// (`workspace_follow_symlinks`).
80 UiNowEngineRestart,
81 }
82
83 /// One setting without collapsing live, resolved, startup, and persisted
84 /// values into an ambiguous `Session`/`Saved` label.
85 #[derive(Debug, Clone, PartialEq, Eq)]
86 pub struct SettingFact<T> {
87 /// Value currently held by the live owner before further resolution.
88 pub current: Option<T>,
89 /// Value actually in force after route, policy, or session overrides.
90 pub effective: Option<T>,
91 /// Value a fresh session is expected to start with, when observed.
92 #[cfg(test)]
93 pub startup: Option<T>,
94 /// Exact persisted value last read from its owning store, when observed.
95 pub saved: Option<T>,
96 #[cfg(test)]
97 pub authority: SettingAuthority,
98 pub apply: SettingApplySemantics,
99 }
100
101 impl<T: Clone> SettingFact<T> {
102 /// A fact already owned by the active session.
103 #[must_use]
104 pub fn active_session(value: T) -> Self {
105 Self {
106 current: Some(value.clone()),
107 effective: Some(value),
108 #[cfg(test)]
109 startup: None,
110 saved: None,
111 #[cfg(test)]
112 authority: SettingAuthority::Session,
113 apply: SettingApplySemantics::EffectiveNow,
114 }
115 }
116 }
117
118 /// The narrow, read-only workbench projection available in this slice.
119 ///
120 /// `App` intentionally does not retain a resident [`codewhale_runtime::settings::Settings`]
121 /// value. Consequently this projection never reloads disk or guesses startup
122 /// defaults: those lanes remain `None` until the settings owner supplies them.
123 #[derive(Debug, Clone, PartialEq, Eq)]
124 pub struct UiSnapshot {
125 pub context_budget: Option<ContextBudgetSnapshot>,
126 pub provider: SettingFact<String>,
127 pub model: SettingFact<String>,
128 }
129
130 impl UiSnapshot {
131 #[must_use]
132 pub(crate) fn from_app(app: &App) -> Self {
133 let (provider, model) = app.effective_route_identity_display();
134 Self {
135 context_budget: ContextBudgetSnapshot::from_app(app),
136 provider: SettingFact::active_session(provider),
137 model: SettingFact::active_session(model),
138 }
139 }
140 }
141
142 /// Stable identifier from the Tideline wiring manifest.
143 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
144 pub struct InteractionTargetId(&'static str);
145
146 impl InteractionTargetId {
147 pub const HEADER_CONTEXT: Self = Self("header.context");
148 /// The rendered route/model segment. This is intentionally an affordance
149 /// id only: the provider picker remains the owner of route catalog and
150 /// readiness facts.
151 pub const HEADER_ROUTE: Self = Self("header.route");
152 /// The model name and effort tier inside the info line's route segment.
153 pub const HEADER_MODEL: Self = Self("header.model");
154 pub const HEADER_UPDATE: Self = Self("header.update");
155 /// A live count in the posture bar; opens the dock view it counts.
156 pub const FOOTER_COUNT: Self = Self("footer.count");
157 pub const DOCK_TAB_AGENTS: Self = Self("dock.tab.agents");
158 pub const DOCK_TAB_TASKS: Self = Self("dock.tab.tasks");
159 pub const DOCK_TAB_BACKGROUND: Self = Self("dock.tab.background");
160 pub const DOCK_TAB_TERMINAL: Self = Self("dock.tab.terminal");
161 pub const DOCK_TAB_FILES: Self = Self("dock.tab.files");
162 pub const DOCK_TAB_NOTEPAD: Self = Self("dock.tab.notepad");
163 pub const DOCK_TAB_CONTEXT: Self = Self("dock.tab.context");
164 pub const DOCK_TAB_GIT: Self = Self("dock.tab.git");
165 pub const DOCK_TAB_PRICE: Self = Self("dock.tab.price");
166 pub const DOCK_CLOSE: Self = Self("dock.close");
167 }
168
169 /// Typed destination shared by keyboard and mouse input routes.
170 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
171 pub enum InteractionAction {
172 InspectContext,
173 /// Open the existing provider/route picker without making this chrome
174 /// target another source of catalog or runtime authority.
175 OpenProviderPicker,
176 /// Open the existing `/model` picker. Same discipline as the provider
177 /// entry: an entry point, never a second catalog.
178 OpenModelPicker,
179 OpenUpdate,
180 /// Open the existing automations manager.
181 OpenAutomations,
182 ShowDockPanel(crate::tui::work_surface::RailPanel),
183 DismissDock,
184 }
185
186 /// Focus metadata for a selectable target.
187 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
188 pub enum InteractionFocus {
189 /// The target has a direct keyboard shortcut but is not in traversal yet.
190 Direct,
191 }
192
193 /// Typed, non-prose evidence made available to an inspector.
194 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
195 pub enum InspectDetail {
196 ContextBudget(ContextBudgetSnapshot),
197 /// The topbar exposes a route entry point, not a copied route snapshot.
198 /// `ProviderPickerView` remains the authoritative presentation owner.
199 Route,
200 Update,
201 }
202
203 /// A selectable region painted in the current frame.
204 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
205 pub struct InteractionTarget {
206 pub id: InteractionTargetId,
207 pub area: Rect,
208 pub focus: InteractionFocus,
209 pub keyboard_action: Option<InteractionAction>,
210 pub mouse_action: Option<InteractionAction>,
211 pub inspect_detail: InspectDetail,
212 }
213
214 /// Frame-scoped interaction geometry.
215 ///
216 /// Targets are cleared before every render. Hit testing runs newest-first so a
217 /// later modal or overlay can safely own cells also covered by a lower layer.
218 #[derive(Debug, Default)]
219 pub struct InteractionRegistry {
220 targets: Vec<InteractionTarget>,
221 }
222
223 impl InteractionRegistry {
224 pub fn clear(&mut self) {
225 self.targets.clear();
226 }
227
228 pub fn register(&mut self, target: InteractionTarget) {
229 if target.area.width > 0 && target.area.height > 0 {
230 self.targets.push(target);
231 }
232 }
233
234 #[must_use]
235 pub fn target_at(&self, column: u16, row: u16) -> Option<&InteractionTarget> {
236 let position = Position::new(column, row);
237 self.targets
238 .iter()
239 .rev()
240 .find(|target| target.area.contains(position))
241 }
242
243 pub fn iter(&self) -> impl DoubleEndedIterator<Item = &InteractionTarget> {
244 self.targets.iter()
245 }
246 }
247
248 #[cfg(test)]
249 mod tests {
250 use super::{
251 ContextBudgetSnapshot, InspectDetail, InteractionAction, InteractionFocus,
252 InteractionRegistry, InteractionTarget, InteractionTargetId, SettingApplySemantics,
253 SettingAuthority, SettingFact, UiSnapshot,
254 };
255 use codewhale_config::ProviderKind;
256 use ratatui::layout::Rect;
257
258 fn target(area: Rect, used_tokens: u32) -> InteractionTarget {
259 InteractionTarget {
260 id: InteractionTargetId::HEADER_CONTEXT,
261 area,
262 focus: InteractionFocus::Direct,
263 keyboard_action: Some(InteractionAction::InspectContext),
264 mouse_action: Some(InteractionAction::InspectContext),
265 inspect_detail: InspectDetail::ContextBudget(ContextBudgetSnapshot {
266 used_tokens,
267 max_tokens: 10_000,
268 percent_basis_points: 3_000,
269 }),
270 }
271 }
272
273 #[test]
274 fn topbar_route_target_is_typed_without_copying_route_facts() {
275 let target = InteractionTarget {
276 id: InteractionTargetId::HEADER_ROUTE,
277 area: Rect::new(20, 0, 24, 1),
278 focus: InteractionFocus::Direct,
279 keyboard_action: Some(InteractionAction::OpenProviderPicker),
280 mouse_action: Some(InteractionAction::OpenProviderPicker),
281 inspect_detail: InspectDetail::Route,
282 };
283
284 assert_eq!(target.id, InteractionTargetId::HEADER_ROUTE);
285 assert_eq!(
286 target.keyboard_action,
287 Some(InteractionAction::OpenProviderPicker)
288 );
289 assert_eq!(target.mouse_action, target.keyboard_action);
290 assert_eq!(target.inspect_detail, InspectDetail::Route);
291 }
292
293 #[test]
294 fn ui_snapshot_uses_active_route_without_claiming_saved_defaults() {
295 let mut app = crate::tui::test_support::test_app_with_options(
296 crate::tui::test_support::test_tui_options("."),
297 );
298 app.pending_turn_route = Some((ProviderKind::Zai, "GLM-5.3".to_string(), false));
299
300 let snapshot = UiSnapshot::from_app(&app);
301
302 assert_eq!(
303 snapshot.provider.current.as_deref(),
304 Some(ProviderKind::Zai.provider().display_name())
305 );
306 assert_eq!(snapshot.provider.current, snapshot.provider.effective);
307 assert_eq!(snapshot.model.current.as_deref(), Some("GLM-5.3"));
308 assert_eq!(snapshot.model.current, snapshot.model.effective);
309 assert!(snapshot.provider.startup.is_none());
310 assert!(snapshot.provider.saved.is_none());
311 assert_eq!(snapshot.provider.authority, SettingAuthority::Session);
312 assert_eq!(snapshot.provider.apply, SettingApplySemantics::EffectiveNow);
313 }
314
315 #[test]
316 fn context_budget_projection_reuses_and_bounds_the_existing_estimate() {
317 let app = crate::tui::test_support::test_app_with_options(
318 crate::tui::test_support::test_tui_options("."),
319 );
320 let (used, max_tokens, _) =
321 crate::tui::ui::context_usage_snapshot(&app).expect("existing context estimate");
322 let snapshot = ContextBudgetSnapshot::from_app(&app).expect("Tideline projection");
323
324 assert_eq!(snapshot.used_tokens, u32::try_from(used).unwrap());
325 assert_eq!(snapshot.max_tokens, max_tokens);
326 assert!(snapshot.used_tokens <= snapshot.max_tokens);
327 assert!(snapshot.percent_basis_points <= 10_000);
328 }
329
330 #[test]
331 fn setting_fact_keeps_live_startup_and_saved_lanes_distinct() {
332 let fact = SettingFact {
333 current: Some("session"),
334 effective: Some("managed"),
335 startup: Some("next"),
336 saved: Some("disk"),
337 authority: SettingAuthority::ManagedPolicy,
338 apply: SettingApplySemantics::NextSession,
339 };
340
341 assert_eq!(fact.current, Some("session"));
342 assert_eq!(fact.effective, Some("managed"));
343 assert_eq!(fact.startup, Some("next"));
344 assert_eq!(fact.saved, Some("disk"));
345 }
346
347 #[test]
348 fn apply_semantics_distinguish_reload_and_partial_restart_from_full_restart() {
349 let reload = SettingFact {
350 current: Some("live"),
351 effective: None,
352 startup: None,
353 saved: Some("disk"),
354 authority: SettingAuthority::UserSettings,
355 apply: SettingApplySemantics::ReloadRequired,
356 };
357 let partial = SettingFact {
358 apply: SettingApplySemantics::UiNowEngineRestart,
359 ..reload.clone()
360 };
361 assert_ne!(reload.apply, SettingApplySemantics::RestartRequired);
362 assert_ne!(partial.apply, SettingApplySemantics::RestartRequired);
363 assert_ne!(reload.apply, partial.apply);
364 assert_ne!(reload.apply, SettingApplySemantics::Immediate);
365 }
366
367 #[test]
368 fn registry_ignores_empty_geometry_and_prefers_the_topmost_target() {
369 let mut registry = InteractionRegistry::default();
370
371 registry.register(target(Rect::new(2, 2, 6, 3), 3_000));
372 registry.register(target(Rect::new(4, 3, 6, 3), 4_000));
373 registry.register(target(Rect::new(0, 0, 0, 1), 5_000));
374
375 assert_eq!(registry.iter().count(), 2);
376 assert_eq!(
377 registry.target_at(5, 3).map(|target| target.area),
378 Some(Rect::new(4, 3, 6, 3))
379 );
380 assert_eq!(
381 registry.target_at(2, 2).map(|target| target.area),
382 Some(Rect::new(2, 2, 6, 3))
383 );
384 assert!(registry.target_at(20, 20).is_none());
385
386 registry.clear();
387 assert_eq!(registry.iter().count(), 0);
388 }
389 }
390
390 lines RUST