pixtuoid 0.6.1

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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//! Hit-test functions for mouse interaction: agent hover, coffee machine
//! click-to-open, and furniture tooltip detection.

use std::time::SystemTime;

use pixtuoid_core::{AgentId, SceneState};

use crate::tui::layout::{Layout, Size};
use crate::tui::pet::PetKind;
use crate::tui::pixel_painter::character_anchor;
use crate::tui::pose;

/// Hit-test the mouse cursor against each agent's current sprite footprint.
/// Returns the agent under `(mx, my)` (in terminal cell coordinates), or
/// `None` if no agent occupies that cell.
///
/// The character sprite is 8×12 pixels, which in cell space is 8 cells
/// wide × 6 cells tall (one cell = 2 vertical pixels). We test against
/// that exact bounding box anchored on the agent's `character_anchor`.
pub(crate) fn hit_test_agent(
    scene: &SceneState,
    layout: &Layout,
    now: SystemTime,
    rctx: &mut pose::RouteCtx<'_>,
    mx: u16,
    my: u16,
) -> Option<AgentId> {
    // Width-in-cells (sprite is 8 px wide; we don't divide x by 2 because
    // each pixel column is one cell column in the half-block grid).
    const SPRITE_W_CELLS: u16 = 8;
    // Height-in-cells: sprite is 12 px tall = 6 cells.
    const SPRITE_H_CELLS: u16 = 6;
    for agent in scene.agents.values() {
        let Some(anchor) = character_anchor(agent, layout, now, rctx) else {
            continue;
        };
        let cell_x = anchor.x;
        let cell_y = anchor.y / 2;
        if mx >= cell_x
            && mx < cell_x.saturating_add(SPRITE_W_CELLS)
            && my >= cell_y
            && my < cell_y.saturating_add(SPRITE_H_CELLS)
        {
            return Some(agent.agent_id);
        }
    }
    None
}

/// Lightweight hit-test for click-to-pin without needing router/overlay state.
/// Uses home desk positions only (no walking agents).
pub fn hit_test_from_tui(scene: &SceneState, layout: &Layout, mx: u16, my: u16) -> Option<AgentId> {
    const SPRITE_W: u16 = 8;
    const SPRITE_H_CELLS: u16 = 6;
    for agent in scene.agents.values() {
        if agent.desk_index >= layout.home_desks.len() {
            continue;
        }
        let desk = &layout.home_desks[agent.desk_index];
        let ax = desk.x + 1;
        let ay = desk.y.saturating_sub(4);
        let cell_x = ax;
        let cell_y = ay / 2;
        if mx >= cell_x
            && mx < cell_x.saturating_add(SPRITE_W)
            && my >= cell_y
            && my < cell_y.saturating_add(SPRITE_H_CELLS)
        {
            return Some(agent.agent_id);
        }
    }
    None
}

/// Hit-test whether the mouse is over the pantry coffee machine.
/// Returns true if `(mx, my)` (terminal cell coords) falls on the coffee
/// machine section of the pantry counter sprite.
pub fn hit_test_coffee_machine(layout: &Layout, mx: u16, my: u16) -> bool {
    let pantry_wp = layout
        .waypoints
        .iter()
        .find(|w| matches!(w.kind, crate::tui::layout::WaypointKind::Pantry));
    let Some(wp) = pantry_wp else {
        return false;
    };
    let Size { w: cw, h: ch } = layout.pantry_counter_size;
    let sprite_x = wp.pos.x.saturating_sub(cw / 2);
    let sprite_y = wp.pos.y.saturating_sub(ch / 2);
    let (coffee_x0, coffee_x1) = if cw >= 32 {
        (sprite_x + 11, sprite_x + 18)
    } else {
        (sprite_x + 8, sprite_x + 13)
    };
    let coffee_y0 = sprite_y;
    let coffee_y1 = sprite_y + ch;
    let cell_y = my * 2;
    mx >= coffee_x0 && mx < coffee_x1 && cell_y >= coffee_y0 && cell_y < coffee_y1
}

/// Hit-test all furniture items in the office. Returns a short label
/// if `(mx, my)` (terminal cell coords) falls on any known item.
/// The coffee machine is handled separately for its click-to-open
/// behavior — this function covers the remaining decorations.
pub fn hit_test_furniture(layout: &Layout, mx: u16, my: u16) -> Option<&'static str> {
    use crate::tui::layout::{
        furniture_def, Furniture, PlantItem, PlantKind, PodDecor, PodDecorItem, WallDecor,
        WallDecorItem, WaypointKind, DESK_H, DESK_W, ELEVATOR_H, ELEVATOR_W,
    };
    // Hover boxes derive from the one furniture table — `.visual` (the visible
    // sprite) for what the user points at, `.footprint` where the obstacle is
    // the thing — so a geometry edit can't leave a stale hit box behind.
    let visual = |f| furniture_def(f).visual;
    let footprint = |f| furniture_def(f).footprint.unwrap_or(Size { w: 0, h: 0 });
    let px = mx;
    let py = my * 2;

    let hit = |x: u16, y: u16, w: u16, h: u16| -> bool {
        px >= x && px < x.saturating_add(w) && py >= y && py < y.saturating_add(h)
    };

    // Home desks
    for desk in &layout.home_desks {
        if hit(desk.x, desk.y, DESK_W + 2, DESK_H) {
            return Some("Desk");
        }
    }

    // Lounge couch: one 20px hover region centred on the sofa. It's 3 seat
    // waypoints now, so per-seat boxes would over-cover and multi-fire — hit
    // it once at couch_sprite_center, mirroring the single furniture paint.
    if let Some(c) = layout.couch_sprite_center {
        if hit(c.x.saturating_sub(10), c.y.saturating_sub(3), 20, 7) {
            return Some("Lounge Sofa");
        }
    }

    // Waypoints
    for wp in &layout.waypoints {
        let Size { w, h } = match wp.kind {
            // Couch hovers via the one-time region above (3 seat waypoints).
            WaypointKind::Couch => continue,
            WaypointKind::Pantry => layout.pantry_counter_size,
            // Meeting slots hover via the dedicated meeting_sofas loop below.
            WaypointKind::MeetingSofa | WaypointKind::MeetingStand => continue,
            // Footprint owned by furniture_def — same shape the mask + stand
            // point use, so the hover box can't drift from them.
            other => match furniture_def(other.furniture()).footprint {
                Some(fp) => fp,
                None => continue,
            },
        };
        let wx = wp.pos.x.saturating_sub(w / 2);
        let wy = wp.pos.y.saturating_sub(h / 2);
        if hit(wx, wy, w, h) {
            return Some(match wp.kind {
                WaypointKind::Pantry => "Pantry Counter",
                WaypointKind::PhoneBooth => "Phone Booth",
                WaypointKind::StandingDesk => "Standing Desk",
                WaypointKind::VendingMachine => "Vending Machine",
                WaypointKind::Printer => "Printer",
                // Proven unreachable today (couch + meeting slots `continue`
                // above), but this is a per-frame mouse path: skip an unexpected
                // kind rather than panic the whole TUI if a future refactor adds
                // a WaypointKind or drops one of those earlier `continue`s.
                WaypointKind::Couch | WaypointKind::MeetingSofa | WaypointKind::MeetingStand => {
                    continue
                }
            });
        }
    }

    // Meeting sofas (20px sprite, centred on the sofa point).
    for sofa in &layout.meeting_sofas {
        let Size { w, h } = visual(Furniture::MeetingSofaBody); // full 20px sprite, not the 16px footprint
        if hit(
            sofa.x.saturating_sub(w / 2),
            sofa.y.saturating_sub(h / 2),
            w,
            h,
        ) {
            return Some("Meeting Sofa");
        }
    }

    // Meeting tables
    for t in &layout.meeting_tables {
        let Size { w, h } = visual(Furniture::MeetingTable);
        if hit(t.x.saturating_sub(w / 2), t.y.saturating_sub(h / 2), w, h) {
            return Some("Meeting Table");
        }
    }

    // Pantry table
    if let Some(t) = layout.pantry_table {
        let Size { w, h } = footprint(Furniture::PantryTable);
        if hit(t.x.saturating_sub(w / 2), t.y.saturating_sub(h / 2), w, h) {
            return Some("Pantry Table");
        }
    }

    // Pantry chairs
    for chair in &layout.pantry_chairs {
        let Size { w, h } = footprint(Furniture::PantryChair); // left-biased offset 2 matches the mask stamp
        if hit(chair.x.saturating_sub(2), chair.y.saturating_sub(2), w, h) {
            return Some("Chair");
        }
    }

    // Plants
    for &PlantItem { kind, pos } in &layout.plants {
        let Size { w, h } = visual(kind.furniture()); // hover the whole visible plant, not just its ground base
        if hit(
            pos.x.saturating_sub(w / 2),
            pos.y.saturating_sub(h / 2),
            w,
            h,
        ) {
            return Some(match kind {
                PlantKind::Ficus => "Ficus",
                PlantKind::Tall => "Tall Plant",
                PlantKind::Flower => "Flower Pot",
                PlantKind::Succulent => "Succulent",
            });
        }
    }

    // Floor lamp
    if let Some(lamp) = layout.floor_lamp {
        let Size { w, h } = visual(Furniture::FloorLamp); // full 4×10 lamp sprite
        if hit(
            lamp.x.saturating_sub(w / 2),
            lamp.y.saturating_sub(h / 2),
            w,
            h,
        ) {
            return Some("Floor Lamp");
        }
    }

    // Wall decor
    for &WallDecorItem { kind, pos } in &layout.wall_decor {
        let Size { w, h } = furniture_def(kind.furniture()).visual;
        if hit(pos.x, pos.y, w, h) {
            return Some(match kind {
                WallDecor::Whiteboard => "Whiteboard",
                WallDecor::Bookshelf => "Bookshelf",
                WallDecor::BulletinBoard => "Bulletin Board",
                WallDecor::ExitSign => "Exit Sign",
                WallDecor::MeetingScreen => "Meeting Screen",
            });
        }
    }

    // Pod decor (aisle items)
    for &PodDecorItem { kind, pos } in &layout.pod_decor {
        let Size { w, h } = furniture_def(kind.furniture()).visual;
        if hit(
            pos.x.saturating_sub(w / 2),
            pos.y.saturating_sub(h / 2),
            w,
            h,
        ) {
            return Some(match kind {
                PodDecor::PlantTall => "Tall Plant",
                PodDecor::Whiteboard => "Whiteboard",
                PodDecor::Tv => "TV Stand",
                PodDecor::PhoneBooth => "Phone Booth",
                PodDecor::StandingDesk => "Standing Desk",
            });
        }
    }

    // Lounge side table
    if let Some(t) = layout.lounge_side_table {
        if hit(t.x.saturating_sub(3), t.y.saturating_sub(2), 7, 4) {
            return Some("Side Table");
        }
    }

    // Meeting room procedural items (coat rack, doormat)
    if let Some(mr) = layout.meeting_room {
        if mr.width > 20 {
            let cx = mr.x + mr.width - 5;
            let cy = mr.y + mr.height / 2 - 4;
            if hit(cx.saturating_sub(2), cy, 5, 8) {
                return Some("Coat Rack");
            }
        }
        if mr.width > 10 {
            let mat_x = mr.x + mr.width + 1;
            let mat_y = mr.y + mr.height / 2 - 2;
            if hit(mat_x, mat_y, 4, 5) {
                return Some("Doormat");
            }
        }
    }

    // Pantry room procedural items (water cooler, trash bin)
    if let Some(pr) = layout.pantry_room {
        if pr.height > 25 && pr.width > 12 {
            let wx = pr.x + pr.width - 6;
            let wy = pr.y + 8;
            if hit(wx, wy, 3, 6) {
                return Some("Water Cooler");
            }
        }
        if pr.height > 20 {
            let tx = pr.x + 3;
            let ty = pr.y + pr.height - 14;
            if hit(tx, ty, 4, 5) {
                return Some("Trash Bin");
            }
        }
    }

    // Door / elevator
    if let Some(d) = layout.door {
        if hit(d.x, d.y, ELEVATOR_W, ELEVATOR_H) {
            return Some("Elevator");
        }
    }

    None
}

/// Hit-test whether the mouse is over the office pet.
/// `pet_pos` is the pet's center anchor in pixel coordinates.
/// `kind` selects the species; `anim_name` selects the bounding box size
/// via `PetKind::hitbox`.
///
/// Returns true if `(mx, my)` (terminal cell coords) falls inside
/// the sprite's footprint.
pub fn hit_test_pet(
    kind: PetKind,
    pet_pos: crate::tui::layout::Point,
    anim_name: &str,
    mx: u16,
    my: u16,
) -> bool {
    let Size { w, h } = kind.hitbox(anim_name);
    let tl_x = pet_pos.x.saturating_sub(w / 2);
    let tl_y = pet_pos.y.saturating_sub(h / 2);
    let cell_y = my * 2;
    mx >= tl_x && mx < tl_x.saturating_add(w) && cell_y >= tl_y && cell_y < tl_y.saturating_add(h)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn coffee_machine_hit_test_returns_false_for_origin() {
        let layout = Layout::compute(160, 200, 4).expect("layout");
        assert!(!hit_test_coffee_machine(&layout, 0, 0));
    }

    #[test]
    fn coffee_machine_hit_test_returns_true_for_machine_area() {
        let layout = Layout::compute(160, 200, 4).expect("layout");
        let pantry_wp = layout
            .waypoints
            .iter()
            .find(|w| w.kind == crate::tui::layout::WaypointKind::Pantry)
            .expect("pantry");
        let Size { w: cw, h: ch } = layout.pantry_counter_size;
        let sprite_x = pantry_wp.pos.x.saturating_sub(cw / 2);
        let sprite_y = pantry_wp.pos.y.saturating_sub(ch / 2);
        let mid_x = if cw >= 32 {
            sprite_x + 14
        } else {
            sprite_x + 10
        };
        let mid_cell_y = (sprite_y + ch / 2) / 2;
        assert!(
            hit_test_coffee_machine(&layout, mid_x, mid_cell_y),
            "expected hit at coffee machine area ({mid_x}, {mid_cell_y})"
        );
    }

    #[test]
    fn furniture_hit_test_returns_none_for_empty_space() {
        let layout = Layout::compute(160, 200, 4).expect("layout");
        // Open floor must report no furniture. Scan for an empty cell rather
        // than hardcoding one — which mid-floor cells are open shifts when the
        // pod aisle spacing is retuned (a hardcoded point goes stale and lands
        // on a reflowed desk). If hit_test_furniture wrongly matched
        // everywhere, no empty cell would be found and `.expect` would panic.
        let empty = (0..(layout.buf_h / 2))
            .flat_map(|cy| (0..layout.buf_w).map(move |cx| (cx, cy)))
            .find(|&(cx, cy)| hit_test_furniture(&layout, cx, cy).is_none())
            .expect("some open-floor cell must report no furniture");
        assert_eq!(hit_test_furniture(&layout, empty.0, empty.1), None);
    }

    #[test]
    fn furniture_hit_test_finds_desk() {
        let layout = Layout::compute(160, 200, 4).expect("layout");
        let desk = layout.home_desks.first().expect("desk");
        let cell_y = (desk.y + 2) / 2;
        assert_eq!(
            hit_test_furniture(&layout, desk.x + 2, cell_y),
            Some("Desk")
        );
    }

    #[test]
    fn furniture_hit_test_finds_elevator() {
        let layout = Layout::compute(160, 200, 4).expect("layout");
        let door = layout.door.expect("door");
        let cell_y = (door.y + 7) / 2;
        assert_eq!(
            hit_test_furniture(&layout, door.x + 8, cell_y),
            Some("Elevator")
        );
    }

    #[test]
    fn furniture_hit_test_finds_meeting_table() {
        let layout = Layout::compute(160, 200, 4).expect("layout");
        let table = layout.meeting_tables.first().expect("table");
        let cell_y = table.y / 2;
        assert_eq!(
            hit_test_furniture(&layout, table.x, cell_y),
            Some("Meeting Table")
        );
    }

    #[test]
    fn furniture_hit_test_respects_floor_seed() {
        // seed=1 → Lounge variant (no meeting room)
        let layout1 = Layout::compute_with_seed(160, 200, 4, 1).expect("layout");
        assert!(layout1.meeting_tables.is_empty());
        let layout0 = Layout::compute(160, 200, 4).expect("layout");
        if let Some(table) = layout0.meeting_tables.first() {
            let cell_y = table.y / 2;
            assert_ne!(
                hit_test_furniture(&layout1, table.x, cell_y),
                Some("Meeting Table"),
            );
        }
    }

    #[test]
    fn cat_hit_test_inside_sit_sprite() {
        use crate::tui::layout::Point;
        // cat_sit is 6x6. Center at (50, 80).
        // Top-left pixel: (50-3, 80-3) = (47, 77).
        // cell_y for my=39 → 78, which is inside [77..83).
        // mx=50 inside [47..53).
        let pos = Point { x: 50, y: 80 };
        assert!(hit_test_pet(PetKind::Cat, pos, "cat_sit", 50, 39));
    }

    #[test]
    fn cat_hit_test_outside_returns_false() {
        use crate::tui::layout::Point;
        let pos = Point { x: 50, y: 80 };
        // Way outside the 6x6 sprite.
        assert!(!hit_test_pet(PetKind::Cat, pos, "cat_sit", 10, 10));
    }

    // --- hit_test_from_tui (click-to-pin, home-desk-only) -----------------

    fn scene_with_agent_at_desk(desk_index: usize) -> (SceneState, AgentId) {
        use pixtuoid_core::state::{ActivityState, AgentSlot};
        use std::path::Path;
        use std::sync::Arc;
        let id = AgentId::from_transcript_path("/pin/0.jsonl");
        let slot = AgentSlot {
            agent_id: id,
            source: Arc::from("cc"),
            session_id: Arc::from("s"),
            cwd: Arc::from(Path::new("/repo")),
            label: Arc::from("a"),
            state: ActivityState::Idle,
            state_started_at: SystemTime::UNIX_EPOCH,
            created_at: SystemTime::UNIX_EPOCH,
            last_event_at: SystemTime::UNIX_EPOCH,
            exiting_at: None,
            pending_idle_at: None,
            desk_index,
            floor_idx: 0,
            tool_call_count: 0,
            active_ms: 0,
            unknown_cwd: false,
            parent_id: None,
        };
        let mut scene = SceneState::uniform(16);
        scene.agents.insert(id, slot);
        (scene, id)
    }

    #[test]
    fn from_tui_hits_agent_at_its_desk_anchor() {
        let layout = Layout::compute(160, 200, 4).expect("layout");
        let (scene, id) = scene_with_agent_at_desk(0);
        let d = layout.home_desks[0];
        // Mirror hit_test_from_tui's own anchor geometry.
        let cx = d.x + 1;
        let cy = d.y.saturating_sub(4) / 2;
        assert_eq!(hit_test_from_tui(&scene, &layout, cx, cy), Some(id));
    }

    #[test]
    fn from_tui_misses_empty_space() {
        let layout = Layout::compute(160, 200, 4).expect("layout");
        let (scene, _id) = scene_with_agent_at_desk(0);
        assert_eq!(hit_test_from_tui(&scene, &layout, 0, 0), None);
    }

    #[test]
    fn from_tui_skips_agent_with_out_of_range_desk() {
        let layout = Layout::compute(160, 200, 4).expect("layout");
        // desk_index past the layout's home-desk count ⇒ `continue` arm.
        let (scene, _id) = scene_with_agent_at_desk(layout.home_desks.len() + 100);
        // No agent occupies any cell — scan a few and confirm None everywhere.
        for &(mx, my) in &[(0u16, 0u16), (40, 20), (80, 40)] {
            assert_eq!(hit_test_from_tui(&scene, &layout, mx, my), None);
        }
    }

    // --- hit_test_furniture: kinds the compute path never emits -------------
    // compute_with_seed never produces PlantKind::Ficus or WallDecor::Bulletin
    // Board, so the harness real-layout loop can't reach those two return arms.
    // Push them into the pub Vecs of a computed layout and hit their centers.

    #[test]
    fn furniture_hit_test_ficus_via_synthetic_plant() {
        use crate::tui::layout::Point;
        let mut layout = Layout::compute(160, 200, 4).expect("layout");
        let pos = Point { x: 40, y: 40 };
        layout.plants.push(crate::tui::layout::PlantItem {
            kind: crate::tui::layout::PlantKind::Ficus,
            pos,
        });
        // Plants are center-anchored on `pos`; hover the center cell.
        assert_eq!(hit_test_furniture(&layout, pos.x, pos.y / 2), Some("Ficus"));
    }

    #[test]
    fn furniture_hit_test_bulletin_board_via_synthetic_wall_decor() {
        use crate::tui::layout::Point;
        let mut layout = Layout::compute(160, 200, 4).expect("layout");
        // Wall decor is TOP-LEFT anchored at `pos` (not centered). Place it in
        // open space so no earlier furniture arm shadows it.
        let pos = Point { x: 60, y: 30 };
        layout.wall_decor.push(crate::tui::layout::WallDecorItem {
            kind: crate::tui::layout::WallDecor::BulletinBoard,
            pos,
        });
        assert_eq!(
            hit_test_furniture(&layout, pos.x, pos.y / 2),
            Some("Bulletin Board")
        );
    }

    #[test]
    fn cat_hit_test_sleep_smaller_box() {
        use crate::tui::layout::Point;
        // cat_sleep is 6x4. Center at (50, 80).
        // Top-left: (47, 78). Bottom-right: (53, 82).
        let pos = Point { x: 50, y: 80 };
        // cell_y for my=41 → 82, which is at the boundary (82 >= 82 is false for < check).
        // Actually wait: tl_y = 80 - 2 = 78, h=4 so range is [78..82). cell_y=82 is OUT.
        assert!(!hit_test_pet(PetKind::Cat, pos, "cat_sleep", 50, 41));
        // cell_y for my=40 → 80, inside [78..82).
        assert!(hit_test_pet(PetKind::Cat, pos, "cat_sleep", 50, 40));
    }
}