termden 0.8.2

Workspaces and tiled terminals for coding agents (Claude Code, opencode, pi)
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
use std::collections::HashMap;
use std::path::PathBuf;
use std::time::{Duration, Instant, SystemTime};

use alacritty_terminal::event::Event as TermEvent;
use alacritty_terminal::term::TermMode;
use gpui::{
    AnyElement, ClipboardItem, Context, FocusHandle, KeyDownEvent, MouseButton, MouseMoveEvent,
    MouseUpEvent, Pixels, Point, Render, ScrollHandle, ScrollWheelEvent, Timer, Window, div, font,
    prelude::*, px,
};
use termden_core::{
    AppState, Config, DropZone, Harness, HarnessId, HarnessKind, HarnessStatus, LayoutNode,
    Workspace, WorkspaceId,
};

use crate::actions;
use crate::canvas::{self, TRect};
use crate::control;
use crate::launch;
use crate::mock;
use crate::panel;
use crate::pty::{self, Session};
use crate::theme::Theme;
use crate::tile;
use crate::widgets::{dot, hspacer, kind_badge};

#[derive(Clone, Copy)]
pub struct DragState {
    pub harness: HarnessId,
    pub start: Point<Pixels>,
    pub pos: Point<Pixels>,
    pub active: bool,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Mode {
    /// Mock fleet for screenshots; only shell tiles are live; nothing saved.
    Demo,
    /// The real thing: persisted state, control socket, reload on rebuild.
    Live,
    /// Read-only twin of a Live instance (same state file, same tmux server)
    /// used by `termdenctl screenshot` to render it headlessly.
    Mirror,
}

/// Local "HH:MM", `ago` seconds in the past.
pub fn clock(ago: u64) -> String {
    // SAFETY: localtime_r only writes into the zeroed tm we pass.
    unsafe {
        let t = libc::time(std::ptr::null_mut()) - ago as libc::time_t;
        let mut tm: libc::tm = std::mem::zeroed();
        libc::localtime_r(&t, &mut tm);
        format!("{:02}:{:02}", tm.tm_hour, tm.tm_min)
    }
}

pub use termden_core::Activity;

pub struct TermdenApp {
    pub mode: Mode,
    pub config: Config,
    pub theme: Theme,
    pub workspaces: Vec<Workspace>,
    pub layouts: HashMap<WorkspaceId, LayoutNode>,
    pub active: WorkspaceId,
    pub focused: Option<HarnessId>,
    pub mail: Vec<termden_core::Mail>,
    /// Unread count each harness was last nudged about.
    pub mail_notified: HashMap<HarnessId, u16>,
    pub drag: Option<DragState>,
    pub drop_target: Option<(HarnessId, DropZone)>,
    /// Bumped on a timer; drives spinners and the cursor blink.
    pub tick: u64,
    /// Something visible changed since the last frame (terminal output, a
    /// status); the tick only redraws when this is set or something animates.
    redraw: bool,
    last_event_draw: Instant,
    /// Last time each workspace was active or had terminal traffic; idle
    /// agent-less ones unload (`unload_idle`).
    pub busy_at: HashMap<WorkspaceId, Instant>,
    /// A title bar is wanted but the desktop draws none (GNOME): show our own
    /// window buttons, and resize edges unless tiled or maximized.
    /// `Some(maximized)`; updated every render.
    pub own_chrome: Option<bool>,
    /// The window is snapped/maximized by the compositor (no resize edges).
    pub tiled: bool,
    /// The window manager can draw a title bar (`decorations.rs`).
    pub server_decorations: bool,
    /// Live terminals, keyed by harness. tmux owns the processes.
    pub sessions: HashMap<HarnessId, Session>,
    /// Keyboard focus for the whole window; keys go to the focused harness.
    pub focus: FocusHandle,
    pub activity: Vec<Activity>,
    pub activity_scroll: ScrollHandle,
    pub activity_smooth: crate::widgets::SmoothScroll,
    /// Set when a line is logged; the feed then scrolls to the newest on render.
    pub activity_stick: std::cell::Cell<bool>,
    /// Workspace whose "add harness" picker is open.
    pub adding: Option<WorkspaceId>,
    /// Right-click menu: workspace and window position of the click.
    pub ws_menu: Option<(WorkspaceId, (f32, f32))>,
    pub agent_menu: Option<(HarnessId, (f32, f32))>,
    pub menu_closing: Option<(crate::panel::MenuTarget, (f32, f32), Instant)>,
    /// Workspace awaiting a second click to confirm removal.
    pub confirm_remove: Option<(WorkspaceId, Instant)>,
    pub unloaded_open: bool,
    /// Harness whose close was requested once; a second request within a few
    /// seconds kills it.
    pub confirm_close: Option<(HarnessId, Instant)>,
    /// Tile shown over the whole canvas (active workspace only).
    pub zoomed: Option<HarnessId>,
    /// Split divider being dragged.
    pub resizing: Option<canvas::Divider>,
    /// Crossing dividers dragged along when a junction was pressed.
    pub resizing_extra: Vec<canvas::Divider>,
    /// Dragging the edge of the left panel.
    pub panel_resizing: bool,
    /// Auto-hide sidebar currently slid out because the pointer is on it.
    pub sidebar_peek: bool,
    /// 0 = hidden, 1 = fully slid out; eased toward `sidebar_peek` each frame.
    pub sidebar_anim: f32,
    pub sidebar_anim_at: Instant,
    pub settings_open: bool,
    pub update_status: Option<&'static str>,
    /// Theme chooser in settings (`None` = collapsed to one row).
    pub theme_browser: Option<crate::settings::ThemeBrowser>,
    pub theme_scroll: ScrollHandle,
    pub theme_smooth: crate::widgets::SmoothScroll,
    /// List row to bring into view once the theme panel has laid out (GPUI
    /// can only scroll to rows it has measured).
    pub theme_scroll_to: std::cell::Cell<Option<usize>>,
    /// A rebuilt binary or an agent asked for a restart; the sidebar offers
    /// it and the user confirms (`request_restart`).
    pub restart_pending: Option<String>,
    pub popups: [crate::popup::PopupPos; 2],
    /// Results agents shared with the user, newest last (`showcase.rs`).
    pub showcases: Vec<termden_core::Showcase>,
    /// Absolute tile rects of the active workspace, from the last frame.
    pub tile_rects: Vec<(HarnessId, TRect)>,
    pub viewport: (f32, f32),
    /// Terminal cell size in px, measured from the mono font.
    pub cell: (f32, f32),
    /// Tile and button of an in-progress terminal mouse press.
    mouse_press: Option<(HarnessId, u8, (u16, u16))>,
    /// Link under the pointer while ctrl is held: (tile, row, start col, cells).
    hover_url: Option<(HarnessId, u16, u16, u16)>,
    /// Newer release tag offered in the footer (`update.rs`).
    pub update: Option<crate::update::Update>,
    pub update_open: bool,
    /// Per-workspace token/MCP/uptime numbers (`stats.rs`), refreshed on the
    /// background executor.
    pub stats: crate::stats::StatsCache,
    /// Whether the stats pane is showing (persisted in the config).
    pub stats_scroll: ScrollHandle,
    scroll_lines: f32,
    /// Our own binary and its mtime at startup, for reload-on-rebuild.
    pub(crate) exe: Option<(PathBuf, SystemTime)>,
    pub started: Instant,
}

impl TermdenApp {
    pub fn new(config: Config, mode: Mode, cx: &mut Context<Self>) -> Self {
        let theme = Theme::for_id(&config.theme.0, &config);

        let mut state = match mode {
            Mode::Demo => mock::build(),
            Mode::Live | Mode::Mirror => AppState::load().unwrap_or_else(actions::first_run),
        };
        if mode == Mode::Live {
            actions::ensure_home(&mut state);
        }
        let active = state
            .active
            .filter(|id| state.workspaces.iter().any(|w| w.id == *id))
            .or(state.workspaces.first().map(|w| w.id))
            .unwrap_or(WorkspaceId::new(0));

        cx.spawn(async move |this, cx| {
            loop {
                Timer::after(Duration::from_millis(120)).await;
                let updated = this.update(cx, |this, cx| this.on_tick(cx));
                if updated.is_err() {
                    break;
                }
            }
        })
        .detach();

        if mode == Mode::Live {
            control::listen(cx);
            crate::choices::listen(cx);
            Self::watch_updates(cx);
        }
        crate::stats::watch(cx);

        let exe = (mode == Mode::Live)
            .then(|| {
                let path = std::env::current_exe().ok()?;
                let mtime = std::fs::metadata(&path).ok()?.modified().ok()?;
                Some((path, mtime))
            })
            .flatten();

        let mut workspaces = state.workspaces;
        termden_core::assign_agent_colors(&mut workspaces);
        let mut app = Self {
            mode,
            config,
            theme,
            workspaces,
            layouts: state.layouts,
            active,
            focused: state.focused,
            mail: state.mail,
            mail_notified: HashMap::new(),
            drag: None,
            drop_target: None,
            tick: 0,
            redraw: true,
            last_event_draw: Instant::now(),
            busy_at: HashMap::new(),
            own_chrome: None,
            tiled: false,
            server_decorations: true,
            sessions: HashMap::new(),
            focus: cx.focus_handle(),
            activity: state.activity,
            activity_scroll: ScrollHandle::new(),
            activity_smooth: Default::default(),
            activity_stick: std::cell::Cell::new(true),
            adding: None,
            ws_menu: None,
            agent_menu: None,
            menu_closing: None,
            confirm_remove: None,
            unloaded_open: false,
            confirm_close: None,
            zoomed: None,
            resizing: None,
            resizing_extra: Vec::new(),
            panel_resizing: false,
            sidebar_peek: false,
            sidebar_anim: 0.0,
            sidebar_anim_at: Instant::now(),
            settings_open: false,
            update_status: None,
            theme_browser: None,
            theme_scroll: ScrollHandle::new(),
            theme_smooth: Default::default(),
            theme_scroll_to: Default::default(),
            restart_pending: None,
            popups: Default::default(),
            showcases: state.showcases,
            tile_rects: Vec::new(),
            viewport: (0.0, 0.0),
            cell: (7.2, 19.0),
            mouse_press: None,
            hover_url: None,
            update: None,
            update_open: false,
            stats: Default::default(),
            stats_scroll: ScrollHandle::new(),
            scroll_lines: 0.0,
            exe,
            started: Instant::now(),
        };
        if mode == Mode::Demo {
            app.set_screen(HarnessId::STATS, true);
            mock::seed_activity(&mut app);
        } else {
            let verb = if std::env::var_os("TERMDEN_RELOADED").is_some() {
                "updated"
            } else {
                "started"
            };
            app.activity.retain(|e| e.name != "Termden");
            app.drop_placeholder_joins();
            app.log("Termden", verb.into(), 0);
        }
        app
    }

    /// Record window size and cell metrics; only a render has a `Window`.
    fn measure(&mut self, window: &mut Window) {
        let viewport = window.viewport_size();
        self.viewport = (f32::from(viewport.width), f32::from(viewport.height));
        let text = window.text_system();
        let font_id = text.resolve_font(&font(self.theme.mono_font.clone()));
        let cell_w = text
            .advance(font_id, px(self.theme.term_font), 'm')
            .map(|size| f32::from(size.width))
            .unwrap_or(7.2);
        self.cell = (cell_w, self.theme.term_line);
    }

    fn viewport_size(&self) -> gpui::Size<Pixels> {
        gpui::size(px(self.viewport.0), px(self.viewport.1))
    }

    /// Where the tiling canvas sits in this window, excluding the panel.
    pub fn canvas_rect(&self) -> TRect {
        canvas::canvas_rect(&self.config, self.viewport_size())
    }

    /// Every tile of a workspace laid out on the canvas, ignoring zoom.
    pub fn layout_tiles(&self, ws: WorkspaceId) -> Vec<(HarnessId, TRect)> {
        let rect = self.canvas_rect();
        self.layouts
            .get(&ws)
            .map(|layout| canvas::layout_rects(layout, rect, self.config.gap))
            .unwrap_or_default()
    }

    /// The tiles actually drawn: just the zoomed one, if any. Rendering,
    /// sessions and drop hit-testing all use this.
    pub fn visible_tiles(&self, ws: WorkspaceId) -> Vec<(HarnessId, TRect)> {
        let zoomed = self.zoomed.filter(|id| {
            ws == self.active && self.layouts.get(&ws).is_some_and(|l| l.contains(*id))
        });
        match zoomed {
            Some(id) => vec![(id, self.canvas_rect())],
            None => self.layout_tiles(ws),
        }
    }

    pub fn toggle_zoom(&mut self) {
        self.zoomed = match (self.zoomed, self.focused) {
            (Some(_), _) => None,
            (None, focused) => focused,
        };
    }

    /// Close on the second request (button or shortcut) within 3 seconds.
    pub fn request_close(&mut self, id: HarnessId) {
        match self.confirm_close {
            Some((armed, at)) if armed == id && at.elapsed() < Duration::from_secs(3) => {
                self.confirm_close = None;
                self.close_harness(id);
            }
            _ => self.confirm_close = Some((id, Instant::now())),
        }
    }

    pub fn remove_armed(&self, id: WorkspaceId) -> bool {
        self.confirm_remove
            .is_some_and(|(armed, at)| armed == id && at.elapsed() < Duration::from_secs(3))
    }

    pub fn close_armed(&self, id: HarnessId) -> bool {
        self.confirm_close
            .is_some_and(|(armed, at)| armed == id && at.elapsed() < Duration::from_secs(3))
    }

    /// Focus the nearest tile in a direction (by tile centres).
    fn focus_direction(&mut self, dx: f32, dy: f32) {
        let tiles = self.layout_tiles(self.active);
        let Some(from) = self
            .focused
            .and_then(|f| tiles.iter().find(|(id, _)| *id == f))
            .map(|(_, r)| *r)
        else {
            if let Some((id, _)) = tiles.first() {
                self.focus_harness(*id);
            }
            return;
        };
        let centre = |r: &TRect| (r.x + r.w / 2.0, r.y + r.h / 2.0);
        let (fx, fy) = centre(&from);
        let best = tiles
            .iter()
            .filter_map(|(id, rect)| {
                let (x, y) = centre(rect);
                let (vx, vy) = (x - fx, y - fy);
                let along = vx * dx + vy * dy;
                // Ahead of us, and more ahead than sideways.
                (along > 1.0 && along >= (vx * dy - vy * dx).abs() * 0.5)
                    .then(|| (*id, along + (vx * dy - vy * dx).abs() * 2.0))
            })
            .min_by(|a, b| a.1.total_cmp(&b.1));
        if let Some((id, _)) = best {
            self.focus_harness(id);
        }
    }

    fn cycle_workspace(&mut self, step: isize) {
        let len = self.workspaces.len() as isize;
        if len == 0 {
            return;
        }
        let index = self
            .workspaces
            .iter()
            .position(|w| w.id == self.active)
            .unwrap_or(0) as isize;
        let next = self.workspaces[(index + step).rem_euclid(len) as usize].id;
        self.activate_workspace(next);
    }

    /// Spawn sessions for visible tiles and keep every visible grid sized to
    /// its tile. Runs every frame and every tick (a window hidden on another
    /// workspace gets no frames, but harnesses added over the control socket
    /// must still start). Resizes are no-ops when unchanged.
    pub fn sync_sessions(&mut self, cx: &mut Context<Self>) {
        if self.viewport.0 <= 0.0 {
            return;
        }
        let cell = self.cell;
        self.tile_rects = self.visible_tiles(self.active);

        // Hidden tiles (other workspaces, behind a zoom) stay attached and
        // sized to their own layout so `screen`/`send` work on them too. The
        // demo keeps to what is on screen.
        let mut tiles = self.tile_rects.clone();
        if self.mode != Mode::Demo {
            for ws in self
                .workspaces
                .iter()
                .filter(|w| !w.unloaded)
                .map(|w| w.id)
                .collect::<Vec<_>>()
            {
                for (id, rect) in self.layout_tiles(ws) {
                    if !tiles.iter().any(|(t, _)| *t == id) {
                        tiles.push((id, rect));
                    }
                }
            }
        }

        for (id, rect) in tiles {
            let (cols, rows) = tile::grid_size(rect, cell);
            if let Some(session) = self.sessions.get_mut(&id) {
                session.resize(cols, rows, cell);
                continue;
            }
            let Some((workspace, harness)) = self.harness(id) else {
                continue;
            };
            let live = self.mode != Mode::Demo || harness.kind == HarnessKind::Shell;
            if !live || harness.status == HarnessStatus::Error {
                continue;
            }

            let cwd = resolve_cwd(&workspace.path, &harness.cwd);
            let command = match harness.kind {
                HarnessKind::Shell => None,
                kind if self.mode == Mode::Mirror => Some(kind.default_command().to_string()),
                kind => Some(launch::command(
                    id,
                    &harness.name,
                    kind,
                    workspace.home,
                    launch::memory_project(&workspace.path, workspace.home).as_deref(),
                )),
            };
            match Session::spawn(
                id,
                cwd,
                command.as_deref(),
                self.mode == Mode::Mirror,
                cols,
                rows,
                cell,
            ) {
                Ok((session, events)) => {
                    self.sessions.insert(id, session);
                    cx.spawn(async move |this, cx| {
                        while let Ok(event) = events.recv().await {
                            let alive = this.update(cx, |this, cx| {
                                this.on_term_event(id, event, cx);
                            });
                            if alive.is_err() {
                                break;
                            }
                        }
                    })
                    .detach();
                }
                Err(error) => {
                    eprintln!("termden: could not start harness {}: {error}", id.raw());
                    self.set_status(id, HarnessStatus::Error);
                    self.log_harness(id, "could not start".into());
                }
            }
        }
    }

    fn on_term_event(&mut self, id: HarnessId, event: TermEvent, cx: &mut Context<Self>) {
        // Output in a tile that is not on screen changes nothing visible.
        // Redraws are capped at ~30fps; the tick draws what was held back.
        if !matches!(event, TermEvent::Wakeup) || self.tile_rects.iter().any(|(t, _)| *t == id) {
            self.redraw = true;
            if self.last_event_draw.elapsed() >= Duration::from_millis(33) {
                self.last_event_draw = Instant::now();
                self.redraw = false;
                cx.notify();
            }
        }
        let focused = self.focused == Some(id);
        let Some(session) = self.sessions.get_mut(&id) else {
            return;
        };
        match event {
            TermEvent::Wakeup => session.last_output = Instant::now(),
            TermEvent::PtyWrite(text) => session.write(text.into_bytes()),
            TermEvent::Title(title) => session.title = title,
            TermEvent::ResetTitle => session.title.clear(),
            TermEvent::ClipboardStore(_, text) => {
                cx.write_to_clipboard(ClipboardItem::new_string(text));
            }
            TermEvent::Bell if !focused && !session.attention => {
                session.attention = true;
                self.log_harness(id, "needs your attention".into());
            }
            TermEvent::ChildExit(status) => {
                session.exited = true;
                let failed = !status.success();
                self.set_status(
                    id,
                    if failed {
                        HarnessStatus::Error
                    } else {
                        HarnessStatus::Idle
                    },
                );
                let message = if failed {
                    "stopped unexpectedly"
                } else {
                    "finished"
                };
                self.log_harness(id, message.into());
            }
            _ => {}
        }
    }

    /// Derive harness status from session activity until adapters report it.
    fn refresh_statuses(&mut self) {
        let mut updates = Vec::new();
        for (id, session) in &self.sessions {
            if session.exited {
                continue;
            }
            let quiet_typing = session
                .last_output
                .saturating_duration_since(session.last_input)
                > Duration::from_millis(300);
            let status = if session.attention {
                HarnessStatus::NeedsInput
            } else if session.last_output.elapsed() < Duration::from_millis(1500) && quiet_typing {
                HarnessStatus::Working
            } else {
                HarnessStatus::Idle
            };
            updates.push((*id, status));
        }
        for (id, status) in updates {
            if self.harness(id).is_some_and(|(_, h)| h.status != status) {
                self.set_status(id, status);
                self.redraw = true;
            }
        }
    }

    fn on_key_down(&mut self, event: &KeyDownEvent, cx: &mut Context<Self>) -> bool {
        let keystroke = &event.keystroke;
        let m = &keystroke.modifiers;
        if self.update_open {
            if keystroke.key == "escape" {
                self.update_open = false;
            }
            return true;
        }
        if self.settings_open {
            if self.theme_browser.is_some() {
                self.theme_browser_key(keystroke);
            } else if keystroke.key == "escape" {
                self.settings_open = false;
            }
            return true;
        }
        if m.control && m.shift {
            match keystroke.key.as_str() {
                "v" => {
                    let text = cx.read_from_clipboard().and_then(|item| item.text());
                    if let (Some(text), Some(session)) = (text, self.focused_session()) {
                        session.paste(&text);
                    }
                    return true;
                }
                "," => {
                    self.settings_open = true;
                    return true;
                }
                "t" => {
                    self.add_harness(self.active, HarnessKind::Shell);
                    return true;
                }
                "w" => {
                    if let Some(id) = self.focused {
                        self.request_close(id);
                    }
                    return true;
                }
                "z" => {
                    self.toggle_zoom();
                    return true;
                }
                "=" | "+" => {
                    self.set_font_size(self.config.font_size + 1.0);
                    return true;
                }
                "-" | "_" => {
                    self.set_font_size(self.config.font_size - 1.0);
                    return true;
                }
                "0" | ")" => {
                    self.set_font_size(Config::default().font_size);
                    return true;
                }
                "left" | "h" => {
                    self.focus_direction(-1.0, 0.0);
                    return true;
                }
                "right" | "l" => {
                    self.focus_direction(1.0, 0.0);
                    return true;
                }
                "up" | "k" => {
                    self.focus_direction(0.0, -1.0);
                    return true;
                }
                "down" | "j" => {
                    self.focus_direction(0.0, 1.0);
                    return true;
                }
                "pageup" => {
                    self.cycle_workspace(-1);
                    return true;
                }
                "pagedown" => {
                    self.cycle_workspace(1);
                    return true;
                }
                "r" if self.mode == Mode::Live => {
                    self.reload();
                    return true;
                }
                // Copy happens on mouse release (tmux selection -> OSC 52);
                // never let the shortcut leak through as ^C.
                "c" => return true,
                _ => {}
            }
        }

        let Some(session) = self.focused_session() else {
            return false;
        };
        if session.exited {
            // Enter on an exited tile starts it again.
            if keystroke.key == "enter" && !m.modified() {
                if let Some(id) = self.focused {
                    self.restart_harness(id);
                }
                return true;
            }
            return false;
        }
        let app_cursor = session.term.lock().mode().contains(TermMode::APP_CURSOR);
        let Some(bytes) = pty::key_bytes(keystroke, app_cursor) else {
            return false;
        };
        let clearing = keystroke.key == "enter" && !m.modified() && session.cursor_line_is_clear();
        session.input(bytes);
        if clearing && let Some(id) = self.focused {
            self.reset_identity(id);
        }
        true
    }

    fn focused_session(&mut self) -> Option<&mut Session> {
        self.sessions.get_mut(&self.focused?)
    }

    /// Grid cell under a window position, clamped to the tile.
    fn cell_at(&self, id: HarnessId, position: Point<Pixels>) -> Option<(u16, u16)> {
        let (_, rect) = self.tile_rects.iter().find(|(tile, _)| *tile == id)?;
        let session = self.sessions.get(&id)?;
        let (x, y) = tile::content_origin(*rect, session.rows, self.cell.1);
        let col = ((f32::from(position.x) - x) / self.cell.0).max(0.0) as u16;
        let row = ((f32::from(position.y) - y) / self.cell.1).max(0.0) as u16;
        Some((
            col.min(session.cols.saturating_sub(1)),
            row.min(session.rows.saturating_sub(1)),
        ))
    }

    /// Track the link a ctrl+click would open, for the hover underline.
    fn update_hover_url(&mut self, ctrl: bool, position: Point<Pixels>) {
        let (x, y) = (f32::from(position.x), f32::from(position.y));
        self.hover_url = ctrl
            .then(|| self.tile_rects.iter().find(|(_, r)| r.contains(x, y)))
            .flatten()
            .and_then(|&(id, _)| {
                let (col, row) = self.cell_at(id, position)?;
                let (start, len, _) = self.sessions.get(&id)?.url_at(col, row)?;
                Some((id, row, start, len))
            });
    }

    /// Underline (and hand cursor) over the hovered link.
    fn hover_url_element(&self) -> Option<AnyElement> {
        let (id, row, start, len) = self.hover_url?;
        let (_, rect) = self.tile_rects.iter().find(|(tile, _)| *tile == id)?;
        let session = self.sessions.get(&id)?;
        let (x, y) = tile::content_origin(*rect, session.rows, self.cell.1);
        Some(
            div()
                .id("hover-url")
                .absolute()
                .left(px(x + f32::from(start) * self.cell.0))
                .top(px(y + f32::from(row) * self.cell.1))
                .w(px(f32::from(len) * self.cell.0))
                .h(px(self.cell.1))
                .border_b_1()
                .border_color(self.theme.blue)
                .cursor_pointer()
                .into_any_element(),
        )
    }

    /// Ctrl+click: open the URL under the pointer instead of clicking into tmux.
    pub fn open_url_at(&self, id: HarnessId, position: Point<Pixels>) -> bool {
        let Some(url) = self
            .cell_at(id, position)
            .and_then(|(col, row)| self.sessions.get(&id)?.url_at(col, row))
            .map(|(_, _, url)| url)
        else {
            return false;
        };
        if let Ok(mut child) = std::process::Command::new("xdg-open").arg(url).spawn() {
            std::thread::spawn(move || child.wait());
        }
        true
    }

    pub fn terminal_mouse_down(
        &mut self,
        id: HarnessId,
        button: MouseButton,
        position: Point<Pixels>,
    ) {
        let code = match button {
            MouseButton::Left => pty::MOUSE_LEFT,
            MouseButton::Middle => pty::MOUSE_MIDDLE,
            MouseButton::Right => pty::MOUSE_RIGHT,
            _ => return,
        };
        let Some(cell) = self.cell_at(id, position) else {
            return;
        };
        if let Some(session) = self.sessions.get_mut(&id) {
            session.mouse(code, cell.0, cell.1, true);
            self.mouse_press = Some((id, code, cell));
        }
    }

    pub fn terminal_mouse_drag(&mut self, position: Point<Pixels>) {
        let Some((id, code, last)) = self.mouse_press else {
            return;
        };
        let Some(cell) = self.cell_at(id, position) else {
            return;
        };
        if cell == last {
            return;
        }
        if let Some(session) = self.sessions.get_mut(&id) {
            if session.wants_drag() {
                session.mouse(code | pty::MOUSE_DRAG, cell.0, cell.1, true);
            }
        }
        self.mouse_press = Some((id, code, cell));
    }

    pub fn terminal_mouse_up(&mut self, position: Point<Pixels>) {
        let Some((id, code, last)) = self.mouse_press.take() else {
            return;
        };
        let cell = self.cell_at(id, position).unwrap_or(last);
        if let Some(session) = self.sessions.get_mut(&id) {
            session.mouse(code, cell.0, cell.1, false);
        }
    }

    pub fn terminal_scroll(&mut self, id: HarnessId, event: &ScrollWheelEvent) {
        let Some(cell) = self.cell_at(id, event.position) else {
            return;
        };
        let line = px(self.cell.1);
        self.scroll_lines += f32::from(event.delta.pixel_delta(line).y) / self.cell.1;
        let Some(session) = self.sessions.get_mut(&id) else {
            return;
        };
        // tmux scrolls several lines per wheel report; one report per line
        // of accumulated delta keeps trackpads and wheels both usable.
        while self.scroll_lines.abs() >= 1.0 {
            let up = self.scroll_lines > 0.0;
            session.mouse(
                if up { pty::WHEEL_UP } else { pty::WHEEL_DOWN },
                cell.0,
                cell.1,
                true,
            );
            self.scroll_lines -= self.scroll_lines.signum();
        }
    }

    pub fn set_status(&mut self, id: HarnessId, status: HarnessStatus) {
        let mut first_work = false;
        let mut unannounced = false;
        let mut changed = false;
        if let Some(harness) = self
            .workspaces
            .iter_mut()
            .find_map(|workspace| workspace.harness_mut(id))
        {
            changed = harness.status != status;
            harness.status = status;
            unannounced = status == HarnessStatus::Working
                && harness.kind != HarnessKind::Shell
                && !harness.announced;
            if status == HarnessStatus::Working
                && harness.kind != HarnessKind::Shell
                // Startup output is not work: wait until the agent has said
                // who it is (or was named) before reporting its first turn.
                && harness.announced
                && !harness.started
            {
                harness.started = true;
                first_work = true;
            }
        }
        if first_work {
            self.log_harness(id, "started working".into());
        }
        // Names are assigned at creation; the first sign of work is arrival.
        if unannounced {
            self.announce_name(id);
        }
        // Agents already waiting when termden starts are not news.
        if status == HarnessStatus::NeedsInput
            && changed
            && self.started.elapsed() > Duration::from_secs(15)
            && let Some((_, harness)) = self.harness(id)
            && harness.kind != HarnessKind::Shell
        {
            notify(&harness.name, "needs your input");
        }
    }

    pub fn workspace(&self, id: WorkspaceId) -> Option<&Workspace> {
        self.workspaces.iter().find(|workspace| workspace.id == id)
    }

    pub fn workspace_mut(&mut self, id: WorkspaceId) -> Option<&mut Workspace> {
        self.workspaces
            .iter_mut()
            .find(|workspace| workspace.id == id)
    }

    pub fn harness(&self, id: HarnessId) -> Option<(&Workspace, &Harness)> {
        self.workspaces
            .iter()
            .find_map(|workspace| workspace.harness(id).map(|harness| (workspace, harness)))
    }

    pub fn screen_on(&self, screen: HarnessId) -> bool {
        self.layouts
            .get(&self.active)
            .is_some_and(|l| l.contains(screen))
    }

    /// Open the activity or stats screen beside the focused tile, or close it.
    pub fn toggle_screen(&mut self, screen: HarnessId, cx: &mut Context<Self>) {
        self.set_screen(screen, !self.screen_on(screen));
        cx.notify();
    }

    pub fn set_screen(&mut self, screen: HarnessId, open: bool) {
        let active = self.active;
        if self.screen_on(screen) == open {
            return;
        }
        if !open {
            if let Some(layout) = self.layouts.get_mut(&active)
                && !layout.remove(screen)
            {
                self.layouts.remove(&active);
            }
            if self.focused == Some(screen) {
                self.focused = self.layouts.get(&active).and_then(|l| l.first_leaf());
            }
            self.zoomed = self.zoomed.filter(|id| *id != screen);
        } else {
            self.activity_stick.set(true);
            let tiles = self.layout_tiles(active);
            let wanted = crate::stats::width(self.viewport.0);
            match self.layouts.get_mut(&active) {
                Some(layout) => {
                    let target = self
                        .focused
                        .filter(|f| layout.contains(*f))
                        .or_else(|| layout.first_leaf());
                    if let Some(target) = target {
                        layout.split_at(target, screen, termden_core::DropZone::Right);
                        let width = tiles
                            .iter()
                            .find(|(id, _)| *id == target)
                            .map_or(1.0, |(_, rect)| rect.w);
                        layout.set_share(screen, (wanted / width).min(0.5));
                    }
                }
                None => {
                    self.layouts.insert(active, LayoutNode::leaf(screen));
                }
            }
            self.focused = Some(screen);
        }
        self.save();
    }

    pub fn activate_workspace(&mut self, id: WorkspaceId) {
        self.active = id;
        if let Some(workspace) = self.workspace_mut(id) {
            workspace.expanded = true;
            workspace.unloaded = false;
        }

        let focused_in_workspace = self
            .focused
            .and_then(|focused| self.workspace(id).and_then(|ws| ws.harness(focused)))
            .is_some();
        if !focused_in_workspace {
            self.focused = self.layouts.get(&id).and_then(|layout| layout.first_leaf());
        }
        self.clear_attention();
        self.save();
    }

    pub fn toggle_workspace(&mut self, id: WorkspaceId) {
        if let Some(workspace) = self.workspace_mut(id) {
            workspace.expanded = !workspace.expanded;
        }
        self.save();
    }

    pub fn focus_harness(&mut self, id: HarnessId) {
        if id.is_screen() {
            self.focused = Some(id);
            return;
        }
        let workspace_id = self.harness(id).map(|(workspace, _)| workspace.id);
        if let Some(workspace_id) = workspace_id {
            self.active = workspace_id;
            if let Some(workspace) = self.workspace_mut(workspace_id) {
                workspace.expanded = true;
            }
            self.focused = Some(id);
            if self.zoomed.is_some() {
                self.zoomed = Some(id);
            }
            self.clear_attention();
            self.save();
        }
    }

    fn clear_attention(&mut self) {
        if let Some(session) = self.focused.and_then(|id| self.sessions.get_mut(&id)) {
            session.attention = false;
        }
    }

    pub fn set_font_size(&mut self, size: f32) {
        self.config.font_size = size.clamp(8.0, 24.0);
        self.theme = Theme::for_id(&self.config.theme.0, &self.config);
        if let Err(error) = self.config.save() {
            eprintln!("termden: could not save config: {error}");
        }
    }

    /// Switch the title bar setting and apply it to the open window.
    pub fn set_sidebar(&mut self, sidebar: termden_core::Sidebar) {
        self.config.sidebar = sidebar;
        self.sidebar_peek = false;
        if let Err(error) = self.config.save() {
            eprintln!("termden: could not save config: {error}");
        }
    }

    pub fn set_title_bar(&mut self, title_bar: termden_core::TitleBar, window: &Window) {
        self.config.title_bar = title_bar;
        window.request_decorations(if title_bar.wanted() && self.server_decorations {
            gpui::WindowDecorations::Server
        } else {
            gpui::WindowDecorations::Client
        });
        if let Err(error) = self.config.save() {
            eprintln!("termden: could not save config: {error}");
        }
    }

    /// Invisible strips along the window border that resize it, for desktops
    /// that leave that to the app (see `own_chrome`).
    fn resize_edges(&self, cx: &mut Context<Self>) -> Vec<AnyElement> {
        use gpui::{CursorStyle, ResizeEdge};
        if self.own_chrome != Some(false) || self.tiled {
            return Vec::new();
        }
        const T: f32 = 6.0; // grab thickness
        const C: f32 = 14.0; // corner size
        [
            (ResizeEdge::Top, CursorStyle::ResizeUpDown),
            (ResizeEdge::Bottom, CursorStyle::ResizeUpDown),
            (ResizeEdge::Left, CursorStyle::ResizeLeftRight),
            (ResizeEdge::Right, CursorStyle::ResizeLeftRight),
            (ResizeEdge::TopLeft, CursorStyle::ResizeUpLeftDownRight),
            (ResizeEdge::BottomRight, CursorStyle::ResizeUpLeftDownRight),
            (ResizeEdge::TopRight, CursorStyle::ResizeUpRightDownLeft),
            (ResizeEdge::BottomLeft, CursorStyle::ResizeUpRightDownLeft),
        ]
        .into_iter()
        .enumerate()
        .map(|(i, (edge, cursor))| {
            let strip = div().id(("resize-edge", i)).absolute().cursor(cursor);
            let strip = match edge {
                ResizeEdge::Top => strip.top_0().left(px(C)).right(px(C)).h(px(T)),
                ResizeEdge::Bottom => strip.bottom_0().left(px(C)).right(px(C)).h(px(T)),
                ResizeEdge::Left => strip.left_0().top(px(C)).bottom(px(C)).w(px(T)),
                ResizeEdge::Right => strip.right_0().top(px(C)).bottom(px(C)).w(px(T)),
                ResizeEdge::TopLeft => strip.top_0().left_0().size(px(C)),
                ResizeEdge::TopRight => strip.top_0().right_0().size(px(C)),
                ResizeEdge::BottomLeft => strip.bottom_0().left_0().size(px(C)),
                ResizeEdge::BottomRight => strip.bottom_0().right_0().size(px(C)),
            };
            strip
                .on_mouse_down(
                    MouseButton::Left,
                    cx.listener(move |_, _, window, cx| {
                        window.start_window_resize(edge);
                        cx.stop_propagation();
                    }),
                )
                .into_any_element()
        })
        .collect()
    }

    /// Keys while the theme panel is open: type to search, arrows preview,
    /// Enter keeps, Esc clears the search then closes.
    fn theme_browser_key(&mut self, keystroke: &gpui::Keystroke) {
        let Some(browser) = self.theme_browser.as_mut() else {
            return;
        };
        match keystroke.key.as_str() {
            "escape" if !browser.filter.is_empty() => browser.filter.clear(),
            "escape" | "enter" => self.theme_browser = None,
            "backspace" => {
                browser.filter.pop();
            }
            "up" | "down" | "left" | "right" => {
                let list = crate::theme::browse(&browser.filter);
                if list.is_empty() {
                    return;
                }
                let current = list.iter().position(|t| t.id == self.config.theme.0);
                let back = matches!(keystroke.key.as_str(), "up" | "left");
                let next = match current {
                    None => 0,
                    Some(i) if back => (i + list.len() - 1) % list.len(),
                    Some(i) => (i + 1) % list.len(),
                };
                let id = list[next].id;
                let row = crate::settings::panel_index(&browser.filter, id);
                self.set_theme(id);
                self.theme_scroll_to.set(row);
            }
            _ => {
                if let Some(ch) = keystroke.key_char.as_deref()
                    && !keystroke.modifiers.control
                    && !keystroke.modifiers.platform
                    && ch.chars().all(|c| !c.is_control())
                {
                    browser.filter.push_str(&ch.to_lowercase());
                }
            }
        }
    }

    pub fn cycle_theme(&mut self) {
        self.set_theme(crate::theme::next_id(&self.config.theme.0));
    }

    pub fn set_theme(&mut self, id: &str) {
        self.config.theme = termden_core::ThemeId(id.into());
        self.theme = Theme::for_id(id, &self.config);
        if let Err(error) = self.config.save() {
            eprintln!("termden: could not save config: {error}");
        }
    }

    pub fn begin_drag(&mut self, harness: HarnessId, position: Point<Pixels>) {
        self.focused = Some(harness);
        self.drag = Some(DragState {
            harness,
            start: position,
            pos: position,
            active: false,
        });
        self.drop_target = None;
    }

    pub fn on_mouse_move(&mut self, position: Point<Pixels>, window: &Window) {
        let mouse = (f32::from(position.x), f32::from(position.y));
        if let Some(p) = self.popups.iter_mut().find(|p| p.dragging()) {
            p.drag_to(mouse, self.viewport);
            return;
        }
        if self.config.sidebar == termden_core::Sidebar::AutoHide && !self.panel_resizing {
            let x = f32::from(position.x);
            let gap = self.config.gap;
            self.sidebar_peek = if self.sidebar_peek {
                x < gap * 2.0 + self.config.panel_width
            } else {
                x < 16.0 && self.drag.is_none() && self.resizing.is_none()
            };
        }
        if self.panel_resizing {
            let gap = self.config.gap;
            let max = (f32::from(self.viewport.0) * 0.5).max(220.0);
            self.config.panel_width = (f32::from(position.x) - gap * 1.5).clamp(200.0, max);
            return;
        }
        if let Some(divider) = &self.resizing {
            let pos = match divider.axis {
                termden_core::Axis::Horizontal => f32::from(position.x),
                termden_core::Axis::Vertical => f32::from(position.y),
            };
            let ratio = canvas::ratio_at(divider, self.config.gap, pos);
            let mut updates = vec![(divider.path.clone(), ratio)];
            for extra in &self.resizing_extra {
                let pos = match extra.axis {
                    termden_core::Axis::Horizontal => f32::from(position.x),
                    termden_core::Axis::Vertical => f32::from(position.y),
                };
                updates.push((
                    extra.path.clone(),
                    canvas::ratio_at(extra, self.config.gap, pos),
                ));
            }
            if let Some(layout) = self.layouts.get_mut(&self.active) {
                for (path, ratio) in updates {
                    layout.set_ratio(&path, ratio);
                }
            }
            return;
        }
        let Some(drag) = self.drag.as_mut() else {
            return;
        };

        drag.pos = position;
        if !drag.active {
            let dx = f32::from(position.x) - f32::from(drag.start.x);
            let dy = f32::from(position.y) - f32::from(drag.start.y);
            if dx * dx + dy * dy > 64.0 {
                drag.active = true;
            }
        }

        let active = drag.active;
        let dragged = drag.harness;
        if active {
            self.drop_target = self.hit_test(dragged, position, window);
        }
    }

    pub fn on_mouse_up(&mut self) {
        self.popups.iter_mut().for_each(|p| p.end_drag());
        if std::mem::take(&mut self.panel_resizing) {
            if let Err(error) = self.config.save() {
                eprintln!("termden: could not save config: {error}");
            }
            return;
        }
        if self.resizing.take().is_some() {
            self.resizing_extra.clear();
            self.save();
            return;
        }
        let Some(drag) = self.drag.take() else {
            return;
        };
        let Some((target, zone)) = self.drop_target.take() else {
            return;
        };
        if !drag.active {
            return;
        }

        let active = self.active;
        if let Some(layout) = self.layouts.get_mut(&active) {
            if layout.move_leaf(drag.harness, target, zone) {
                self.focused = Some(drag.harness);
            }
        }
        self.save();
    }

    fn hit_test(
        &self,
        dragged: HarnessId,
        position: Point<Pixels>,
        window: &Window,
    ) -> Option<(HarnessId, DropZone)> {
        let _ = window;
        let x = f32::from(position.x);
        let y = f32::from(position.y);

        for (id, tile) in self.visible_tiles(self.active) {
            if id == dragged || !tile.contains(x, y) {
                continue;
            }

            let rx = (x - tile.x) / tile.w.max(1.0);
            let ry = (y - tile.y) / tile.h.max(1.0);
            let zone = if rx < 0.25 {
                DropZone::Left
            } else if rx > 0.75 {
                DropZone::Right
            } else if ry < 0.25 {
                DropZone::Top
            } else if ry > 0.75 {
                DropZone::Bottom
            } else {
                DropZone::Center
            };
            return Some((id, zone));
        }

        None
    }

    fn render_ghost(&self) -> Option<AnyElement> {
        let drag = self.drag.as_ref()?;
        if !drag.active {
            return None;
        }
        let (workspace, harness) = self.harness(drag.harness)?;
        let theme = &self.theme;
        let accent = theme.accent(workspace.accent);
        let left = f32::from(drag.pos.x) - 100.0;
        let top = f32::from(drag.pos.y) - 26.0;

        Some(
            div()
                .absolute()
                .left(px(left))
                .top(px(top))
                .w(px(200.))
                .h(px(56.))
                .rounded(px(10.))
                .bg(theme.base)
                .border_2()
                .border_color(accent)
                .shadow_lg()
                .opacity(0.94)
                .flex()
                .flex_col()
                .overflow_hidden()
                .child(
                    div()
                        .flex()
                        .items_center()
                        .gap(px(7.))
                        .h(px(32.))
                        .px(px(9.))
                        .bg(theme.surface0.opacity(0.4))
                        .child(dot(theme.status(harness.status), 6.))
                        .child(
                            div()
                                .text_size(theme.ui(11.5))
                                .font_weight(gpui::FontWeight::MEDIUM)
                                .text_color(theme.text)
                                .child(harness.name.clone()),
                        )
                        .child(kind_badge(harness.kind, theme))
                        .child(hspacer())
                        .child(
                            div()
                                .text_size(theme.ui(9.))
                                .text_color(accent)
                                .child(workspace.name.clone()),
                        ),
                )
                .child(
                    div()
                        .flex()
                        .items_center()
                        .px(px(10.))
                        .h(px(24.))
                        .text_size(theme.ui(9.))
                        .text_color(theme.overlay)
                        .child("drop on an edge to split · center to swap"),
                ),
        )
        .map(|element| element.into_any_element())
    }
}

impl Render for TermdenApp {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        self.render_body(window, cx)
    }
}

impl TermdenApp {
    /// The 120ms frame tick: spinners, statuses, mail, rebuild check.
    fn on_tick(&mut self, cx: &mut Context<Self>) {
        self.tick = self.tick.wrapping_add(1);
        self.sync_sessions(cx);
        self.refresh_statuses();
        self.notify_mail(cx);
        if self.tick % 8 == 0 {
            self.check_rebuilt();
            self.unload_idle();
        }
        // A full redraw lays out the whole window; skip it when nothing moves.
        let animating = self.mode == Mode::Demo
            || self.update_downloading()
            || self
                .workspaces
                .iter()
                .flat_map(|w| &w.harnesses)
                .any(|h| h.has_live_subagents() || crate::panel::pending(h));
        let blink = self.tick % 4 == 0
            && self
                .focused
                .and_then(|id| self.sessions.get(&id))
                .is_some_and(|s| !s.exited);
        if std::mem::take(&mut self.redraw) || animating || blink {
            cx.notify();
        }
    }

    fn render_body(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
        self.measure(window);
        // GNOME reports maximized and snapped windows as tiled too, so tiling
        // only hides the resize edges, never the buttons (tiling WMs do not
        // get here: `Auto` wants no title bar there).
        let client = match window.window_decorations() {
            gpui::Decorations::Client { tiling } => Some(tiling.is_tiled()),
            gpui::Decorations::Server => None,
        };
        self.tiled = client == Some(true);
        self.own_chrome =
            (self.config.title_bar.wanted() && client.is_some()).then(|| window.is_maximized());
        self.sync_sessions(cx);
        let gap = self.config.gap;
        self.popups[crate::popup::SETTINGS].update(self.settings_open);
        self.popups[crate::popup::UPDATE].update(self.update_open);
        let pinned = self.config.sidebar == termden_core::Sidebar::Pinned;
        let now = Instant::now();
        let dt = now
            .duration_since(self.sidebar_anim_at)
            .as_secs_f32()
            .min(0.05);
        self.sidebar_anim_at = now;
        let target = if self.sidebar_peek { 1.0 } else { 0.0 };
        if self.sidebar_anim != target {
            let step = dt / 0.16;
            self.sidebar_anim = if target > self.sidebar_anim {
                (self.sidebar_anim + step).min(1.0)
            } else {
                (self.sidebar_anim - step).max(0.0)
            };
            window.request_animation_frame();
        }
        let eased = 1.0 - (1.0 - self.sidebar_anim).powi(2);
        let shown = pinned || self.sidebar_anim > 0.0;
        let mut panel = shown.then(|| panel::render(self, cx));
        let floating = if pinned { None } else { panel.take() };
        let canvas = canvas::render(self, window, cx);
        let ghost = self.render_ghost();

        // Client-drawn windows (GNOME) get no rounded corners from the
        // desktop; draw them unless maximized or snapped.
        let round_corners =
            self.own_chrome == Some(false) && !self.tiled && !window.is_fullscreen();
        div()
            .id("root")
            .relative()
            .size_full()
            .bg(self.theme.crust)
            .when(round_corners, |root| {
                root.rounded(px(self.config.corner_radius))
            })
            .font_family(self.theme.ui_font.clone())
            .track_focus(&self.focus)
            .on_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| {
                // F11 fullscreens the window (the terminals never see it).
                if event.keystroke.key == "f11" && !event.keystroke.modifiers.modified() {
                    window.toggle_fullscreen();
                    cx.stop_propagation();
                    return;
                }
                if this.on_key_down(event, cx) {
                    cx.stop_propagation();
                    cx.notify();
                }
            }))
            .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, window, cx| {
                if event.pressed_button.is_some() {
                    this.terminal_mouse_drag(event.position);
                }
                this.on_mouse_move(event.position, window);
                this.update_hover_url(event.modifiers.control, event.position);
                cx.notify();
            }))
            .on_modifiers_changed(cx.listener(
                |this, event: &gpui::ModifiersChangedEvent, window, cx| {
                    this.update_hover_url(event.modifiers.control, window.mouse_position());
                    cx.notify();
                },
            ))
            .on_mouse_up(
                MouseButton::Left,
                cx.listener(|this, event: &MouseUpEvent, _, cx| {
                    this.terminal_mouse_up(event.position);
                    this.on_mouse_up();
                    cx.notify();
                }),
            )
            .on_mouse_up_out(
                MouseButton::Left,
                cx.listener(|this, event: &MouseUpEvent, _, cx| {
                    this.terminal_mouse_up(event.position);
                    this.on_mouse_up();
                    cx.notify();
                }),
            )
            .on_mouse_up(
                MouseButton::Right,
                cx.listener(|this, event: &MouseUpEvent, _, _| {
                    this.terminal_mouse_up(event.position)
                }),
            )
            .on_mouse_up(
                MouseButton::Middle,
                cx.listener(|this, event: &MouseUpEvent, _, _| {
                    this.terminal_mouse_up(event.position)
                }),
            )
            .child(
                div()
                    .size_full()
                    .p(px(gap))
                    .flex()
                    .flex_row()
                    .gap(px(gap))
                    .children(panel)
                    .child(canvas),
            )
            .children(floating.map(|panel| {
                div()
                    .absolute()
                    .left(px(
                        gap - (1.0 - eased) * (self.config.panel_width + gap * 2.0)
                    ))
                    .top(px(gap))
                    .bottom(px(gap))
                    .child(panel)
            }))
            .children((pinned || self.sidebar_peek).then(|| {
                div()
                    .id("panel-resize")
                    .absolute()
                    .left(px(gap + self.config.panel_width))
                    .top(px(gap))
                    .bottom(px(gap))
                    .w(px(gap))
                    .cursor_col_resize()
                    .on_mouse_down(
                        MouseButton::Left,
                        cx.listener(|this, _, _, cx| {
                            this.panel_resizing = true;
                            cx.stop_propagation();
                        }),
                    )
            }))
            .children(self.resize_edges(cx))
            .children(self.hover_url_element())
            .children(crate::settings::render(self, window, cx))
            .children(crate::update::render(self, cx))
            .children(crate::panel::workspace_menu(self, cx))
            .children(crate::panel::agent_menu(self, cx))
            .children(ghost)
            .into_any_element()
    }
}

/// Workspace path joined with the harness cwd, `~` expanded. Falls back to
/// `$HOME` when the folder does not exist (the mock fleet points at some).
pub fn resolve_cwd(root: &str, cwd: &str) -> PathBuf {
    let home = PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| "/".into()));
    let root = match root.strip_prefix("~") {
        Some(rest) => home.join(rest.trim_start_matches('/')),
        None => PathBuf::from(root),
    };
    let path = root.join(cwd);
    if path.is_dir() { path } else { home }
}

/// Desktop notification for things that happen while the window is not in
/// front; silently nothing where `notify-send` is missing.
pub fn notify(who: &str, what: &str) {
    let _ = std::process::Command::new("notify-send")
        .args([
            "-a",
            "termden",
            "-i",
            "termden",
            "-h",
            "string:desktop-entry:termden",
            "--",
            who,
            what,
        ])
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn();
}