ascii-agents 0.3.0

Terminal pixel-art office for AI coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! `Renderer` trait impl that drives the half-block terminal TUI.
//!
//! Closes the v1 gap where production code called the free function
//! `draw_scene` directly, leaving the core `Renderer` trait exercised only
//! by `TestRenderer` in tests. `TuiRenderer` is the production impl: it
//! owns the cross-frame mutable state (`RgbBuffer`, `FrameCache`,
//! `AStarRouter`, `OccupancyOverlay`, `PoseHistory`) per floor and forwards
//! to `draw_scene`, which recomputes its own layout per frame from
//! `terminal.size()` because the user can resize at any time.

use std::time::SystemTime;

use anyhow::Result;
use ascii_agents_core::sprite::format::Pack;
use ascii_agents_core::sprite::{Rgb, RgbBuffer};
use ascii_agents_core::state::SceneState;
use ascii_agents_core::Renderer;
use ratatui::backend::Backend;
use ratatui::Terminal;

use ratatui::layout::Rect;

use crate::tui::floor::{build_floor_scene, num_floors, FloorCtx, FloorMeta, FloorTransition};
use crate::tui::layout::{Layout, Point, MAX_VISIBLE_DESKS};
use crate::tui::pathfind::Router;
use crate::tui::pixel_painter::render_to_rgb_buffer;
use crate::tui::renderer::{draw_scene, flush_buffer_to_term_at_offset, CatPetState, DrawCtx};

pub struct TuiRenderer<B: Backend> {
    pub terminal: Terminal<B>,
    floor_bufs: Vec<RgbBuffer>,
    floor_ctxs: Vec<FloorCtx>,
    current_floor: usize,
    transition: Option<FloorTransition>,
    mouse_pos: Option<(u16, u16)>,
    pinned_agent: Option<ascii_agents_core::AgentId>,
    pub ticker: crate::tui::renderer::TickerQueue,
    theme: &'static crate::tui::theme::Theme,
    theme_picker: Option<usize>,
    cached_layout: Option<Layout>,
    cat_pet: Option<CatPetState>,
    last_cat_pos: Option<(Point, &'static str)>,
    chitchat_state: std::collections::HashMap<(usize, usize), crate::tui::chitchat::ActiveChitchat>,
    /// Persistent set of agents that have visited the pantry and carry a
    /// coffee cup back to their desk. Replaces the stateless
    /// `has_desk_coffee` cycle-scanning. Cleared on agent exit.
    coffee_holders: std::collections::HashSet<ascii_agents_core::AgentId>,
    /// Timestamp when each agent first returned with coffee (for steam).
    coffee_fetched_at: std::collections::HashMap<ascii_agents_core::AgentId, SystemTime>,
}

impl<B: Backend> TuiRenderer<B> {
    pub fn new(terminal: Terminal<B>, theme: &'static crate::tui::theme::Theme) -> Self {
        Self {
            terminal,
            floor_bufs: vec![RgbBuffer::filled(0, 0, Rgb(0, 0, 0))],
            floor_ctxs: vec![FloorCtx::new()],
            current_floor: 0,
            transition: None,
            mouse_pos: None,
            pinned_agent: None,
            ticker: crate::tui::renderer::TickerQueue::new(),
            theme,
            theme_picker: None,
            cached_layout: None,
            cat_pet: None,
            last_cat_pos: None,
            chitchat_state: std::collections::HashMap::new(),
            coffee_holders: std::collections::HashSet::new(),
            coffee_fetched_at: std::collections::HashMap::new(),
        }
    }

    pub fn current_floor(&self) -> usize {
        self.current_floor
    }

    pub fn cached_layout(&self) -> Option<&Layout> {
        self.cached_layout.as_ref()
    }

    pub fn current_floor_seed(&self) -> u64 {
        let nf = self.floor_ctxs.len();
        FloorMeta::for_floor(self.current_floor, nf).floor_seed
    }

    pub fn transition(&self) -> Option<&FloorTransition> {
        self.transition.as_ref()
    }

    pub fn navigate_floor(&mut self, target: usize, now: SystemTime) {
        if target == self.current_floor || self.transition.is_some() {
            return;
        }
        self.set_pinned_agent(None);
        self.transition = Some(FloorTransition::new(self.current_floor, target, now));
    }

    pub fn cancel_transition(&mut self) {
        self.transition = None;
    }

    pub fn set_mouse_pos(&mut self, pos: Option<(u16, u16)>) {
        self.mouse_pos = pos;
    }

    pub fn pinned_agent(&self) -> Option<ascii_agents_core::AgentId> {
        self.pinned_agent
    }

    pub fn set_pinned_agent(&mut self, id: Option<ascii_agents_core::AgentId>) {
        self.pinned_agent = id;
    }

    pub fn buf(&self) -> &RgbBuffer {
        &self.floor_bufs[self.current_floor]
    }

    pub fn set_theme(&mut self, theme: &'static crate::tui::theme::Theme) {
        if !std::ptr::eq(self.theme, theme) {
            self.theme = theme;
            for ctx in &mut self.floor_ctxs {
                ctx.cache = crate::tui::frame_cache::FrameCache::new();
            }
        }
    }

    pub fn set_theme_picker(&mut self, picker: Option<usize>) {
        self.theme_picker = picker;
    }

    pub fn set_cat_pet(&mut self, pet: Option<CatPetState>) {
        self.cat_pet = pet;
    }

    pub fn cat_pet(&self) -> Option<&CatPetState> {
        self.cat_pet.as_ref()
    }

    pub fn cached_cat_pos(&self) -> Option<(Point, &'static str)> {
        self.last_cat_pos
    }

    /// Drop the cached frame entries for agents no longer in `scene`.
    /// Forwarded so the render loop doesn't reach into the cache directly.
    pub fn evict_missing(&mut self, scene: &SceneState) {
        for ctx in &mut self.floor_ctxs {
            ctx.cache.evict_missing(scene);
        }
    }

    /// Invalidate all floors' router path caches. Call when the static
    /// walkable mask changes (terminal resize, max_desks change).
    pub fn invalidate_routes(&mut self) {
        for ctx in &mut self.floor_ctxs {
            ctx.router.invalidate();
        }
    }
}

impl<B: Backend> Renderer for TuiRenderer<B> {
    fn render(&mut self, scene: &SceneState, pack: &Pack, now: SystemTime) -> Result<()> {
        // Auto-expire cat pet state.
        if self.cat_pet.as_ref().is_some_and(|p| !p.is_active(now)) {
            self.cat_pet = None;
        }

        self.ticker.update(scene);

        // Compute how many floors the current scene needs.
        let nf = num_floors(scene).min(crate::tui::floor::MAX_FLOORS);

        // Grow vectors if needed.
        while self.floor_bufs.len() < nf {
            self.floor_bufs.push(RgbBuffer::filled(0, 0, Rgb(0, 0, 0)));
        }
        while self.floor_ctxs.len() < nf {
            self.floor_ctxs.push(FloorCtx::new());
        }

        // Cancel transition if target floors no longer exist.
        if let Some(ref tr) = self.transition {
            if tr.from_floor >= nf || tr.to_floor >= nf {
                self.transition = None;
            }
        }

        // Complete transition if done.
        if let Some(ref tr) = self.transition {
            if tr.is_done(now) {
                self.current_floor = tr.to_floor;
                self.transition = None;
            }
        }

        // Clamp current_floor after transition completion.
        if self.current_floor >= nf {
            self.current_floor = nf.saturating_sub(1);
        }

        let floor_info = if nf > 1 {
            Some((self.current_floor + 1, nf))
        } else {
            None
        };

        // --- Transition path: composite two floors sliding in/out ----------
        if let Some(ref tr) = self.transition {
            let from_floor = tr.from_floor;
            let to_floor = tr.to_floor;
            let t = tr.t(now);
            let going_down = to_floor > from_floor;

            // Build floor-scoped scenes for both floors.
            let (from_agents, from_dpf) = build_floor_scene(scene, from_floor);
            let mut from_scene = SceneState::new(from_dpf);
            for a in from_agents {
                from_scene.agents.insert(a.agent_id, a);
            }

            let (to_agents, to_dpf) = build_floor_scene(scene, to_floor);
            let mut to_scene = SceneState::new(to_dpf);
            for a in to_agents {
                to_scene.agents.insert(a.agent_id, a);
            }

            let term_size = self.terminal.size()?;
            let full_rect = Rect {
                x: 0,
                y: 0,
                width: term_size.width,
                height: term_size.height,
            };
            let scene_rect = Rect {
                x: 0,
                y: 0,
                width: full_rect.width,
                height: full_rect.height.saturating_sub(1),
            };

            let buf_w = scene_rect.width;
            let buf_h = scene_rect.height * 2;

            // Render both floors into their respective buffers.
            // Use split_at_mut to get mutable access to two different indices.
            let (lo, hi) = if from_floor < to_floor {
                (from_floor, to_floor)
            } else {
                (to_floor, from_floor)
            };

            let (bufs_lo, bufs_hi) = self.floor_bufs.split_at_mut(hi);
            let lo_buf = &mut bufs_lo[lo];
            let hi_buf = &mut bufs_hi[0];
            let (from_buf, to_buf) = if from_floor < to_floor {
                (lo_buf, hi_buf)
            } else {
                (hi_buf, lo_buf)
            };

            let (ctxs_lo, ctxs_hi) = self.floor_ctxs.split_at_mut(hi);
            let lo_ctx = &mut ctxs_lo[lo];
            let hi_ctx = &mut ctxs_hi[0];
            let (from_ctx, to_ctx) = if from_floor < to_floor {
                (lo_ctx, hi_ctx)
            } else {
                (hi_ctx, lo_ctx)
            };

            from_buf.ensure_size(buf_w, buf_h, self.theme.surface.bg_fallback);
            to_buf.ensure_size(buf_w, buf_h, self.theme.surface.bg_fallback);

            let from_meta = FloorMeta::for_floor(from_floor, nf);
            let to_meta = FloorMeta::for_floor(to_floor, nf);

            // Transitions hide text overlays, so use throwaway coffee
            // and chitchat state — they won't be rendered anyway.
            let mut transition_chitchat = std::collections::HashMap::new();
            let empty_coffee = std::collections::HashSet::new();
            let empty_fetched = std::collections::HashMap::new();

            if let Some(layout) =
                Layout::compute_with_seed(buf_w, buf_h, MAX_VISIBLE_DESKS, from_meta.floor_seed)
            {
                from_ctx.router.set_preferred_zone(layout.corridor);
                let _ = render_to_rgb_buffer(
                    &from_scene,
                    &layout,
                    pack,
                    now,
                    from_buf,
                    &mut from_ctx.cache,
                    &mut from_ctx.router,
                    &mut from_ctx.overlay,
                    &mut from_ctx.history,
                    self.theme,
                    from_meta,
                    None,
                    &mut transition_chitchat,
                    &empty_coffee,
                    &empty_fetched,
                );
            }

            if let Some(layout) =
                Layout::compute_with_seed(buf_w, buf_h, MAX_VISIBLE_DESKS, to_meta.floor_seed)
            {
                to_ctx.router.set_preferred_zone(layout.corridor);
                let _ = render_to_rgb_buffer(
                    &to_scene,
                    &layout,
                    pack,
                    now,
                    to_buf,
                    &mut to_ctx.cache,
                    &mut to_ctx.router,
                    &mut to_ctx.overlay,
                    &mut to_ctx.history,
                    self.theme,
                    to_meta,
                    None,
                    &mut transition_chitchat,
                    &empty_coffee,
                    &empty_fetched,
                );
            }

            // Compute y-offsets for vertical slide with divider gap.
            // t applies to total travel = screen_height + divider_height
            // so the easing covers the full distance including the gap.
            let h = scene_rect.height as f32;
            let divider_h = (scene_rect.height as f32) / 5.0;
            let total = h + divider_h;
            let (from_offset, to_offset) = if going_down {
                // Higher floor: current slides DOWN, new enters from TOP
                let from_y = (t * total) as i32;
                let to_y = -(total - t * total) as i32;
                (from_y, to_y)
            } else {
                // Lower floor: current slides UP, new enters from BOTTOM
                let from_y = -(t * total) as i32;
                let to_y = (total - t * total) as i32;
                (from_y, to_y)
            };

            let theme = self.theme;
            let theme_picker = self.theme_picker;

            self.terminal.draw(|f| {
                crate::tui::renderer::paint_footer(f, scene, full_rect, theme, floor_info);
                flush_buffer_to_term_at_offset(f, from_buf, scene_rect, from_offset);
                flush_buffer_to_term_at_offset(f, to_buf, scene_rect, to_offset);

                // Text overlays are hidden during transition — they can't
                // scroll with the pixel buffer in ratatui's coordinate system.
                // They reappear once the transition completes.

                if let Some(idx) = theme_picker {
                    crate::tui::renderer::paint_theme_picker(f, idx, full_rect, theme);
                }
            })?;

            self.cached_layout = None;
            return Ok(());
        }

        // --- Normal path: single floor ------------------------------------
        let (floor_agents, desks_per_floor) = build_floor_scene(scene, self.current_floor);
        let mut floor_scene = SceneState::new(desks_per_floor);
        for agent in floor_agents {
            floor_scene.agents.insert(agent.agent_id, agent);
        }

        // Evict coffee state for agents no longer in the scene.
        self.coffee_holders
            .retain(|id| scene.agents.contains_key(id));
        self.coffee_fetched_at
            .retain(|id, _| scene.agents.contains_key(id));

        let fctx = &mut self.floor_ctxs[self.current_floor];
        let mut draw_ctx = DrawCtx {
            buf: &mut self.floor_bufs[self.current_floor],
            cache: &mut fctx.cache,
            router: &mut fctx.router,
            overlay: &mut fctx.overlay,
            history: &mut fctx.history,
            mouse_pos: self.mouse_pos,
            pinned_agent: self.pinned_agent,
            ticker: &self.ticker,
            theme: self.theme,
            theme_picker: self.theme_picker,
            floor_info,
            floor: FloorMeta::for_floor(self.current_floor, nf),
            cat_pet: self.cat_pet.as_ref(),
            last_cat_pos: None,
            chitchat_state: &mut self.chitchat_state,
            chitchat_bubbles: Vec::new(),
            coffee_holders: &self.coffee_holders,
            coffee_fetched_at: &self.coffee_fetched_at,
            new_coffee_carriers: Vec::new(),
        };
        let result = draw_scene(&mut self.terminal, &floor_scene, pack, now, &mut draw_ctx);
        self.last_cat_pos = draw_ctx.last_cat_pos;
        // Persist newly detected coffee carriers.
        for id in draw_ctx.new_coffee_carriers {
            if self.coffee_holders.insert(id) {
                self.coffee_fetched_at.insert(id, now);
            }
        }
        if let Ok(ref layout_opt) = result {
            self.cached_layout = layout_opt.clone();
        }
        result.map(|_| ())
    }
}