返回 CodeWhale
active_cell.rs
根目录 / crates / tui / src / tui / active_cell.rs
1 //! Active in-flight tool/exec cell — single mutable group that buffers parallel
2 //! tool work for the current turn.
3 //!
4 //! ## Why
5 //!
6 //! When the model issues parallel tool calls in a single assistant turn (e.g.
7 //! two `read_file` and one `grep_files` running concurrently), naively
8 //! appending each tool start as its own history cell makes the transcript
9 //! "bounce" as completions arrive out of order. Codex's pattern is to keep all
10 //! in-flight tool work in ONE active cell that mutates in place; once the turn
11 //! resolves the active cell finalizes into the transcript.
12 //!
13 //! ## Contract
14 //!
15 //! - At most one [`ActiveCell`] per turn. It holds zero or more
16 //! [`HistoryCell`]s that are still being mutated (status `Running`, output
17 //! pending, etc.).
18 //! - The owning [`crate::tui::app::App`] renders the active cell's contents
19 //! AFTER `App.history` so they appear at the live tail.
20 //! - Cell indices used by helpers like `tool_cells` / `tool_details_by_cell`
21 //! address the virtual sequence `App.history ++ active_cell.entries`. Each
22 //! entry's index is `App.history.len() + entry_offset`.
23 //! - When a tool completes whose `tool_id` does not match any active entry
24 //! (orphan), the caller pushes a finalized standalone cell into `App.history`
25 //! instead of mutating the active group. This keeps `active_cell` a stable
26 //! reflection of what was actually started, and avoids merging unrelated
27 //! tool work.
28 //! - On `TurnComplete` (or cancellation) the active cell is "flushed":
29 //! in-progress entries are marked with the supplied terminal status, then
30 //! every entry is appended to `App.history`. Companion maps
31 //! (`tool_cells`, `tool_details_by_cell`) are rewritten to point at the new
32 //! `App.history` indices.
33 //!
34 //! ## Revision counter
35 //!
36 //! Cells inside the active group mutate without changing pointer identity, so
37 //! the transcript cache cannot rely on enum-equality for invalidation. We
38 //! expose `revision()` and `bump_revision()`; the renderer combines this with
39 //! `App.history_version` when computing per-cell revisions for the cache.
40
41 use crate::tui::history::{HistoryCell, ToolCell, ToolStatus};
42
43 /// In-flight active cell: a sequence of mutable [`HistoryCell`] entries.
44 ///
45 /// Conceptually a single "live tail" cell in the Codex sense: it appears as
46 /// one logical block at the end of the transcript, but internally it is
47 /// composed of one or more entries (each rendered as its own
48 /// [`HistoryCell`]). The reason we keep them as separate entries — rather
49 /// than fusing into a single conceptual block — is that they may have
50 /// different shapes (an `ExecCell`, an `ExploringCell` aggregate, an MCP
51 /// tool result, …) and the existing renderers already know how to draw each
52 /// shape correctly. Coalescing into a single render path would duplicate
53 /// logic we already have.
54 #[derive(Debug, Clone, Default)]
55 pub struct ActiveCell {
56 entries: Vec<HistoryCell>,
57 /// Tool ids currently associated with this active cell. The map values are
58 /// indices into [`Self::entries`], with one entry per tool call.
59 tool_to_entry: std::collections::HashMap<String, usize>,
60 /// Bumped on every mutation. Used by the transcript cache to know that
61 /// the active cell needs re-rendering even though its position in the
62 /// virtual cell list is unchanged.
63 revision: u64,
64 }
65
66 impl ActiveCell {
67 /// Create an empty active cell.
68 #[must_use]
69 pub fn new() -> Self {
70 Self::default()
71 }
72
73 /// Number of entries (each rendered as its own [`HistoryCell`]).
74 #[must_use]
75 pub fn entry_count(&self) -> usize {
76 self.entries.len()
77 }
78
79 /// Whether the active cell has any entries.
80 #[must_use]
81 pub fn is_empty(&self) -> bool {
82 self.entries.is_empty()
83 }
84
85 /// Read-only access to the underlying entries (for rendering).
86 #[must_use]
87 pub fn entries(&self) -> &[HistoryCell] {
88 &self.entries
89 }
90
91 /// Mutable access to a specific entry. Bumps the revision counter so the
92 /// renderer knows the cached lines are stale.
93 pub fn entry_mut(&mut self, index: usize) -> Option<&mut HistoryCell> {
94 if index < self.entries.len() {
95 self.bump_revision();
96 self.entries.get_mut(index)
97 } else {
98 None
99 }
100 }
101
102 /// Current revision counter. Wraps on overflow which is fine for cache
103 /// invalidation; the chance of a wrap-around collision is astronomical
104 /// over a single session and any miss only causes one extra re-render.
105 #[must_use]
106 pub fn revision(&self) -> u64 {
107 self.revision
108 }
109
110 /// Increment the revision counter. Call any time an entry is mutated.
111 pub fn bump_revision(&mut self) {
112 self.revision = self.revision.wrapping_add(1);
113 }
114
115 /// Add a tool entry to the active cell.
116 ///
117 /// Returns the entry index (which the caller can record in
118 /// `tool_cells_in_active`).
119 ///
120 /// `tool_id` is registered for the new entry so future
121 /// completion lookups can find it.
122 pub fn push_tool(&mut self, tool_id: impl Into<String>, cell: HistoryCell) -> usize {
123 let tool_id = tool_id.into();
124 let entry_idx = self.entries.len();
125 self.entries.push(cell);
126 self.tool_to_entry.insert(tool_id, entry_idx);
127 self.bump_revision();
128 entry_idx
129 }
130
131 /// Push an entry with no tool id binding. Approval notices use this path
132 /// so they can remain in the transcript without shifting the virtual
133 /// indices of tools that are still running in `active_cell`.
134 pub fn push_untracked(&mut self, cell: HistoryCell) -> usize {
135 let entry_idx = self.entries.len();
136 self.entries.push(cell);
137 self.bump_revision();
138 entry_idx
139 }
140
141 /// Push a thinking entry as a new active-cell entry. Sibling to
142 /// [`Self::push_tool`] but for `HistoryCell::Thinking` content. Returns the
143 /// entry index. Thinking entries do not participate in `tool_to_entry`.
144 ///
145 /// P2.3: thinking lives in the active cell so a `Thinking → Tool → Tool`
146 /// sequence renders as one logical "Working…" block until the next
147 /// assistant prose chunk flushes the group into history.
148 pub fn push_thinking(&mut self, cell: HistoryCell) -> usize {
149 debug_assert!(
150 matches!(cell, HistoryCell::Thinking { .. }),
151 "push_thinking expects HistoryCell::Thinking",
152 );
153 let entry_idx = self.entries.len();
154 self.entries.push(cell);
155 self.bump_revision();
156 entry_idx
157 }
158
159 /// Look up the entry index that holds the given tool id.
160 #[must_use]
161 pub fn entry_index_for_tool(&self, tool_id: &str) -> Option<usize> {
162 self.tool_to_entry.get(tool_id).copied()
163 }
164
165 /// Drain every entry, returning them in insertion order. Resets internal
166 /// state (revision is bumped via `bump_revision`).
167 ///
168 /// Callers use this on `TurnComplete` (or cancellation) to flush the
169 /// active group into `App.history`.
170 pub fn drain(&mut self) -> Vec<HistoryCell> {
171 let entries = std::mem::take(&mut self.entries);
172 self.tool_to_entry.clear();
173 self.bump_revision();
174 entries
175 }
176
177 /// Mark every still-running tool entry as `Stopped` (used when the turn is
178 /// cancelled or the provider ends it mid-flight). Entries that already
179 /// completed are left alone.
180 pub fn mark_in_progress_as_interrupted(&mut self) {
181 for cell in &mut self.entries {
182 mark_running_as_interrupted(cell);
183 }
184 self.bump_revision();
185 }
186 }
187
188 fn mark_running_as_interrupted(cell: &mut HistoryCell) {
189 if let HistoryCell::Thinking {
190 streaming,
191 duration_secs,
192 ..
193 } = cell
194 {
195 // A thinking cell stuck mid-stream should stop spinning when the turn
196 // is cancelled. Leave `duration_secs` as-is if it's already populated;
197 // otherwise the renderer simply omits the duration badge.
198 *streaming = false;
199 let _ = duration_secs;
200 return;
201 }
202 let HistoryCell::Tool(tool_cell) = cell else {
203 return;
204 };
205 match tool_cell {
206 ToolCell::Exec(exec) if exec.status.is_active() => {
207 exec.status = ToolStatus::Stopped;
208 exec.waiting = None;
209 }
210 ToolCell::Exploring(explore) => {
211 for entry in &mut explore.entries {
212 if entry.status.is_active() {
213 entry.status = ToolStatus::Stopped;
214 }
215 }
216 }
217 ToolCell::PlanUpdate(plan) if plan.status.is_active() => {
218 plan.status = ToolStatus::Stopped;
219 }
220 ToolCell::PatchSummary(patch) if patch.status.is_active() => {
221 patch.status = ToolStatus::Stopped;
222 }
223 ToolCell::Review(review) if review.status.is_active() => {
224 review.status = ToolStatus::Stopped;
225 }
226 ToolCell::Mcp(mcp) if mcp.status.is_active() => {
227 mcp.status = ToolStatus::Stopped;
228 }
229 ToolCell::WebSearch(search) if search.status.is_active() => {
230 search.status = ToolStatus::Stopped;
231 }
232 ToolCell::DataDisplay(data) if data.status.is_active() => {
233 data.status = ToolStatus::Stopped;
234 }
235 ToolCell::Generic(generic) if generic.status.is_active() => {
236 generic.status = ToolStatus::Stopped;
237 }
238 _ => {}
239 }
240 }
241
242 #[cfg(test)]
243 mod tests {
244 use super::*;
245 use crate::tui::history::{
246 ExecCell, ExecSource, ExploringCell, ExploringEntry, GenericToolCell,
247 };
248 use std::time::Instant;
249
250 fn exec_cell(command: &str) -> HistoryCell {
251 HistoryCell::Tool(ToolCell::Exec(ExecCell {
252 command: command.to_string(),
253 status: ToolStatus::Running,
254 output: None,
255 live_output: None,
256 shell_task_id: None,
257 owner_agent_id: None,
258 owner_agent_name: None,
259 started_at: Some(Instant::now()),
260 duration_ms: None,
261 stale_elapsed_since_output_ms: None,
262 waiting: None,
263 source: ExecSource::Assistant,
264 description: None,
265 interaction: None,
266 output_summary: None,
267 }))
268 }
269
270 fn exploring_cell_with(label: &str) -> HistoryCell {
271 HistoryCell::Tool(ToolCell::Exploring(ExploringCell {
272 entries: vec![ExploringEntry {
273 label: label.to_string(),
274 search: false,
275 status: ToolStatus::Running,
276 error: None,
277 }],
278 }))
279 }
280
281 fn generic_cell(name: &str) -> HistoryCell {
282 HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
283 name: name.to_string(),
284 status: ToolStatus::Running,
285 input_summary: None,
286 output: None,
287 prompts: None,
288 spillover_path: None,
289 output_summary: None,
290 is_diff: false,
291 }))
292 }
293
294 #[test]
295 fn push_tool_records_entry_and_revision_advances() {
296 let mut cell = ActiveCell::new();
297 let r0 = cell.revision();
298 let idx = cell.push_tool("t1", exec_cell("ls"));
299 assert_eq!(idx, 0);
300 assert_eq!(cell.entry_count(), 1);
301 assert!(cell.revision() != r0);
302 assert_eq!(cell.entry_index_for_tool("t1"), Some(0));
303 }
304
305 #[test]
306 fn parallel_exploring_starts_keep_distinct_entries() {
307 let mut cell = ActiveCell::new();
308 let idx_a = cell.push_tool("a", exploring_cell_with("Read foo.rs"));
309 let idx_b = cell.push_tool("b", exploring_cell_with("Read bar.rs"));
310 assert_ne!(idx_a, idx_b);
311 assert_eq!(cell.entry_count(), 2);
312 assert_eq!(cell.entry_index_for_tool("a"), Some(idx_a));
313 assert_eq!(cell.entry_index_for_tool("b"), Some(idx_b));
314 for entry in cell.entries() {
315 let HistoryCell::Tool(ToolCell::Exploring(explore)) = entry else {
316 panic!("expected exploring cell")
317 };
318 assert_eq!(explore.entries.len(), 1);
319 }
320 }
321
322 #[test]
323 fn drain_resets_state_and_returns_in_order() {
324 let mut cell = ActiveCell::new();
325 cell.push_tool("a", exec_cell("ls"));
326 cell.push_tool("b", generic_cell("foo"));
327 let drained = cell.drain();
328 assert_eq!(drained.len(), 2);
329 assert!(cell.is_empty());
330 assert_eq!(cell.entry_index_for_tool("a"), None);
331 }
332
333 #[test]
334 fn interrupt_marks_running_entries_stopped() {
335 let mut cell = ActiveCell::new();
336 cell.push_tool("a", exec_cell("ls"));
337 cell.mark_in_progress_as_interrupted();
338 let HistoryCell::Tool(ToolCell::Exec(exec)) = &cell.entries()[0] else {
339 panic!("expected exec")
340 };
341 assert_eq!(exec.status, ToolStatus::Stopped);
342 }
343
344 fn thinking_cell(content: &str, streaming: bool) -> HistoryCell {
345 HistoryCell::Thinking {
346 content: content.to_string(),
347 streaming,
348 duration_secs: None,
349 }
350 }
351
352 #[test]
353 fn push_thinking_records_entry_at_tail() {
354 let mut cell = ActiveCell::new();
355 let r0 = cell.revision();
356 let idx = cell.push_thinking(thinking_cell("planning…", true));
357 assert_eq!(idx, 0);
358 assert_eq!(cell.entry_count(), 1);
359 assert!(cell.revision() != r0);
360 }
361
362 #[test]
363 fn thinking_then_tools_group_in_one_active_cell() {
364 // P2.3: a turn that emits Thinking → Tool → Tool keeps everything in
365 // one active cell until the next prose chunk flushes the group.
366 let mut cell = ActiveCell::new();
367 cell.push_thinking(thinking_cell("plan…", true));
368 cell.push_tool("t-1", exec_cell("ls"));
369 cell.push_tool("t-2", exploring_cell_with("Read foo.rs"));
370 assert_eq!(
371 cell.entry_count(),
372 3,
373 "thinking, exec, and exploring entries coexist in one active cell"
374 );
375 assert!(matches!(cell.entries()[0], HistoryCell::Thinking { .. }));
376 assert!(matches!(
377 cell.entries()[1],
378 HistoryCell::Tool(ToolCell::Exec(_))
379 ));
380 assert!(matches!(
381 cell.entries()[2],
382 HistoryCell::Tool(ToolCell::Exploring(_))
383 ));
384 }
385
386 #[test]
387 fn drain_flushes_thinking_alongside_tools_in_order() {
388 let mut cell = ActiveCell::new();
389 cell.push_thinking(thinking_cell("plan…", false));
390 cell.push_tool("t", exec_cell("ls"));
391 let drained = cell.drain();
392 assert_eq!(drained.len(), 2);
393 assert!(matches!(drained[0], HistoryCell::Thinking { .. }));
394 assert!(matches!(drained[1], HistoryCell::Tool(ToolCell::Exec(_))));
395 }
396
397 #[test]
398 fn interrupt_stops_streaming_thinking_spinner() {
399 let mut cell = ActiveCell::new();
400 cell.push_thinking(thinking_cell("plan…", true));
401 cell.mark_in_progress_as_interrupted();
402 let HistoryCell::Thinking { streaming, .. } = &cell.entries()[0] else {
403 panic!("expected thinking cell")
404 };
405 assert!(
406 !*streaming,
407 "interrupted thinking should stop streaming so the spinner exits"
408 );
409 }
410
411 #[test]
412 fn interrupt_stops_queued_tools_and_clears_approval_hold() {
413 let mut cell = ActiveCell::new();
414 let mut exec = exec_cell("sleep 10");
415 if let HistoryCell::Tool(ToolCell::Exec(ref mut inner)) = exec {
416 inner.status = ToolStatus::Queued;
417 inner.waiting = Some(crate::tui::history::ExecWait::Approval);
418 }
419 cell.push_tool("q-1", exec);
420 cell.mark_in_progress_as_interrupted();
421 let HistoryCell::Tool(ToolCell::Exec(inner)) = &cell.entries()[0] else {
422 panic!("expected exec cell");
423 };
424 assert_eq!(inner.status, ToolStatus::Stopped);
425 assert_eq!(inner.waiting, None);
426 }
427 }
428
428 lines RUST