triage-core 0.2.0

Shared session trait and types for Triage, the attention-routing terminal supervisor.
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
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;

use anyhow::{Result, ensure};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SessionId(String);

impl SessionId {
    pub fn new(id: impl Into<String>) -> Result<Self> {
        let id = id.into();
        ensure!(!id.trim().is_empty(), "session id must be set");
        Ok(Self(id))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for SessionId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ClientId(String);

impl ClientId {
    pub fn new(id: impl Into<String>) -> Result<Self> {
        let id = id.into();
        ensure!(!id.trim().is_empty(), "client id must be set");
        Ok(Self(id))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for ClientId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionSize {
    pub rows: usize,
    pub cols: usize,
    pub pixel_width: usize,
    pub pixel_height: usize,
    pub dpi: usize,
}

impl Default for SessionSize {
    fn default() -> Self {
        Self {
            rows: 24,
            cols: 80,
            pixel_width: 800,
            pixel_height: 480,
            dpi: 96,
        }
    }
}

impl SessionSize {
    pub fn validate(&self) -> Result<()> {
        ensure!(self.rows > 0, "session PTY rows must be greater than zero");
        ensure!(self.cols > 0, "session PTY cols must be greater than zero");
        ensure!(
            self.rows <= u16::MAX as usize,
            "session PTY rows must fit in u16"
        );
        ensure!(
            self.cols <= u16::MAX as usize,
            "session PTY cols must fit in u16"
        );
        ensure!(
            self.pixel_width <= u16::MAX as usize,
            "session PTY pixel width must fit in u16"
        );
        ensure!(
            self.pixel_height <= u16::MAX as usize,
            "session PTY pixel height must fit in u16"
        );
        ensure!(
            self.dpi <= u32::MAX as usize,
            "session terminal DPI must fit in u32"
        );
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionSnapshot {
    pub output_seq: u64,
    pub bytes_logged: u64,
    pub size: SessionSize,
    pub visible_rows: Vec<String>,
    pub styled_rows_start: usize,
    pub styled_rows: Vec<StyledRow>,
    pub cursor: TerminalCursor,
    pub current_working_directory: Option<PathBuf>,
    pub context: Option<SessionContext>,
    pub bracketed_paste_enabled: bool,
    pub exited: bool,
    /// Raw (untranslated) PTY output tail for client-side re-emulation — the
    /// single source of truth for history, byte-identical to the live Output
    /// stream. Empty when history is not carried (e.g. resize broadcasts) or
    /// from old hosts.
    #[serde(default)]
    pub raw_output: Vec<u8>,
    /// Byte offset of the first byte of [`Self::raw_output`] within the
    /// session's full output log (`bytes_logged` is the end offset).
    #[serde(default)]
    pub raw_output_start: u64,
    /// Local-LLM one-line description of what the session is doing, if one has
    /// been generated. `None` when summarization is disabled or not yet produced.
    #[serde(default)]
    pub snippet: Option<String>,
    /// Local-LLM longer-form summary (a few sentences) for the side-rail hover
    /// popover and future search. `None` until the detail pass produces it.
    #[serde(default)]
    pub snippet_detail: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionContext {
    pub repository_root: Option<PathBuf>,
    pub worktree_root: Option<PathBuf>,
    pub branch: Option<String>,
}

/// One session's rail metadata, as returned by [`SessionApi::list_session_contexts`].
///
/// Carries context and activity together because a client needs both to build its
/// session list: grouping sessions by repository and ordering them by recency.
/// Fetching them separately would leave the list momentarily grouped by one and
/// ordered by the other, so it would visibly rearrange itself after first paint.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionContextRow {
    pub session_id: SessionId,
    /// `None` when the session's working directory is outside any repository.
    pub context: Option<SessionContext>,
    /// Milliseconds since the Unix epoch of the session's most recent output.
    ///
    /// 0 means unknown: a session that has produced no output, or a daemon that
    /// predates activity tracking. Consumers order unknown last rather than
    /// treating it as the epoch, which would rank it as infinitely stale.
    pub last_activity_ms: u64,
}

/// Separator between the parts of [`SessionContext::localization_label`].
const LABEL_SEPARATOR: &str = "  ·  ";

impl SessionContext {
    /// The repository root's directory name (its last path component), if known.
    pub fn repository_name(&self) -> Option<String> {
        self.repository_root.as_deref().and_then(path_leaf_name)
    }

    /// The worktree root, but only when it is a *distinct* linked worktree —
    /// set and not equal to the repository root. Returns `None` when the
    /// worktree is unset or merely echoes the repository root (the common
    /// "working in the main checkout" case), so callers never render the same
    /// directory as both repo and worktree.
    pub fn distinct_worktree_root(&self) -> Option<&Path> {
        let worktree = self.worktree_root.as_deref()?;
        if Some(worktree) == self.repository_root.as_deref() {
            None
        } else {
            Some(worktree)
        }
    }

    /// The distinct worktree's directory name, if any. See
    /// [`Self::distinct_worktree_root`].
    pub fn worktree_name(&self) -> Option<String> {
        self.distinct_worktree_root().and_then(path_leaf_name)
    }

    /// The branch name, treating an empty string as absent.
    pub fn branch_name(&self) -> Option<&str> {
        self.branch.as_deref().filter(|branch| !branch.is_empty())
    }

    /// A compact one-line `repo · branch · worktree` localization label for the
    /// session. Omits absent parts, and hides the worktree leaf when it merely
    /// echoes the repository root (handled by [`Self::distinct_worktree_root`])
    /// or the branch name, so the label never repeats itself. Returns `None`
    /// when no part is known.
    ///
    /// This is the single source of truth for how a session's git location is
    /// rendered as one line — the daemon's detail-summary header and any other
    /// consumer share it so the format can't drift.
    pub fn localization_label(&self) -> Option<String> {
        let mut parts: Vec<String> = Vec::new();
        if let Some(repo) = self.repository_name() {
            parts.push(repo);
        }
        let branch = self.branch_name();
        if let Some(branch) = branch {
            parts.push(branch.to_string());
        }
        if let Some(worktree) = self.worktree_name()
            && Some(worktree.as_str()) != branch
        {
            parts.push(worktree);
        }
        (!parts.is_empty()).then(|| parts.join(LABEL_SEPARATOR))
    }
}

/// Last path component of `path` as a display string, or `None` when the path
/// has no final component (e.g. `/`). Lossy on non-UTF-8 components.
pub fn path_leaf_name(path: &Path) -> Option<String> {
    path.file_name()
        .map(|name| name.to_string_lossy().into_owned())
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TerminalCursor {
    pub row: usize,
    pub col: usize,
    pub visible: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StyledRow {
    pub spans: Vec<StyledSpan>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StyledSpan {
    pub text: String,
    pub style: TerminalStyle,
}

#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TerminalStyle {
    pub foreground: Option<TerminalColor>,
    pub background: Option<TerminalColor>,
    pub bold: bool,
    pub dim: bool,
    pub italic: bool,
    pub underline: bool,
    pub reverse: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct TerminalColor {
    pub red: u8,
    pub green: u8,
    pub blue: u8,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CompletedSession {
    pub output_seq: u64,
    pub bytes_logged: u64,
    pub visible_rows: Vec<String>,
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AttachMode {
    #[default]
    Observer,
    InteractiveController,
    AgentController,
}

impl AttachMode {
    pub fn grants_input(self) -> bool {
        !matches!(self, Self::Observer)
    }

    pub fn controller_kind(self) -> Option<InputControllerKind> {
        match self {
            AttachMode::Observer => None,
            AttachMode::InteractiveController => Some(InputControllerKind::Interactive),
            AttachMode::AgentController => Some(InputControllerKind::Agent),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum InputControllerKind {
    Interactive,
    Agent,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InputLeaseHolder {
    pub client_id: ClientId,
    pub kind: InputControllerKind,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InputLeaseState {
    pub holder: Option<InputLeaseHolder>,
    pub generation: u64,
}

impl InputLeaseState {
    pub fn observer_only() -> Self {
        Self {
            holder: None,
            generation: 0,
        }
    }

    pub fn acquire(&mut self, client_id: ClientId, kind: InputControllerKind) -> LeaseChange {
        let previous = self.holder.replace(InputLeaseHolder { client_id, kind });
        self.generation += 1;
        let action = if previous.is_some() {
            LeaseChangeAction::TakenOver
        } else {
            LeaseChangeAction::Acquired
        };
        LeaseChange {
            generation: self.generation,
            previous,
            current: self.holder.clone(),
            action,
        }
    }

    pub fn release(&mut self, client_id: &ClientId) -> Option<LeaseChange> {
        let current = self.holder.as_ref()?;
        if &current.client_id != client_id {
            return None;
        }

        let previous = self.holder.take();
        self.generation += 1;
        Some(LeaseChange {
            generation: self.generation,
            previous,
            current: None,
            action: LeaseChangeAction::Released,
        })
    }
}

impl Default for InputLeaseState {
    fn default() -> Self {
        Self::observer_only()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum LeaseChangeAction {
    Acquired,
    Released,
    TakenOver,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LeaseChange {
    pub generation: u64,
    pub previous: Option<InputLeaseHolder>,
    pub current: Option<InputLeaseHolder>,
    pub action: LeaseChangeAction,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StartSessionRequest {
    pub command: String,
    pub args: Vec<String>,
    pub cwd: Option<PathBuf>,
    pub size: SessionSize,
}

impl StartSessionRequest {
    pub fn new(command: impl Into<String>) -> Self {
        Self {
            command: command.into(),
            args: Vec::new(),
            cwd: None,
            size: SessionSize::default(),
        }
    }

    pub fn validate(&self) -> Result<()> {
        ensure!(
            !self.command.trim().is_empty(),
            "session command must be set"
        );
        self.size.validate()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AttachSessionRequest {
    pub session_id: SessionId,
    pub client_id: ClientId,
    pub mode: AttachMode,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AttachSessionResponse {
    pub snapshot: SessionSnapshot,
    pub lease: InputLeaseState,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WriteInputRequest {
    pub session_id: SessionId,
    pub client_id: ClientId,
    pub bytes: Vec<u8>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResizeSessionRequest {
    pub session_id: SessionId,
    pub size: SessionSize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RestoreSessionRequest {
    pub session_id: SessionId,
    pub size: SessionSize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StyledRowsRequest {
    pub session_id: SessionId,
    pub start: usize,
    pub end: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StyledRowsResponse {
    pub output_seq: u64,
    pub start: usize,
    pub rows: Vec<StyledRow>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InputLeaseRequest {
    pub session_id: SessionId,
    pub client_id: ClientId,
    pub kind: InputControllerKind,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionEvent {
    ResyncRequired {
        session_id: SessionId,
        latest_event_seq: u64,
        snapshot: SessionSnapshot,
    },
    Output {
        session_id: SessionId,
        output_seq: u64,
        bytes: Vec<u8>,
    },
    Snapshot {
        session_id: SessionId,
        snapshot: SessionSnapshot,
    },
    LeaseChanged {
        session_id: SessionId,
        change: LeaseChange,
    },
    Exited {
        session_id: SessionId,
        completed: CompletedSession,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionEventEnvelope {
    pub event_seq: u64,
    pub event: SessionEvent,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SubscribeSessionEventsRequest {
    pub session_id: SessionId,
    pub after_event_seq: Option<u64>,
}

pub type SessionEventReceiver = Receiver<SessionEventEnvelope>;

/// The server's self-reported version and update status, surfaced to clients on
/// the `Hello` handshake (Phase 1–2 of self-update) and over the local IPC
/// control protocol (Phase 4, the TUI banner). `latest_version` is `None` until
/// the daemon's background check has seen a published release.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServerUpdateInfo {
    /// The running daemon's version (its compiled `CARGO_PKG_VERSION`).
    pub server_version: String,
    /// Whether a strictly newer stable release has been observed.
    pub update_available: bool,
    /// The newest release tag seen, normalized without a leading `v`.
    pub latest_version: Option<String>,
}

pub trait SessionApi {
    fn list_sessions(&self) -> Result<Vec<SessionId>>;
    fn start_session(&self, request: StartSessionRequest) -> Result<SessionId>;
    fn attach_session(&self, request: AttachSessionRequest) -> Result<AttachSessionResponse>;
    fn subscribe_session_events(&self, session_id: SessionId) -> Result<SessionEventReceiver>;
    fn subscribe_session_events_from(
        &self,
        request: SubscribeSessionEventsRequest,
    ) -> Result<SessionEventReceiver> {
        if request.after_event_seq.is_some() {
            anyhow::bail!("event replay is not supported by this session API");
        }
        self.subscribe_session_events(request.session_id)
    }
    fn acquire_input_lease(&self, request: InputLeaseRequest) -> Result<LeaseChange>;
    fn release_input_lease(
        &self,
        session_id: SessionId,
        client_id: ClientId,
    ) -> Result<LeaseChange>;
    fn write_input(&self, request: WriteInputRequest) -> Result<()>;
    fn resize_session(&self, request: ResizeSessionRequest) -> Result<SessionSnapshot>;
    fn restore_session(&self, _request: RestoreSessionRequest) -> Result<SessionSnapshot> {
        anyhow::bail!("session restore is not supported by this session API")
    }
    fn snapshot_session(&self, session_id: SessionId) -> Result<SessionSnapshot>;
    fn styled_rows(&self, request: StyledRowsRequest) -> Result<StyledRowsResponse>;
    fn shutdown_session(&self, session_id: SessionId) -> Result<CompletedSession>;
    /// Current snippet for every session (id, one-liner, detail). Sessions
    /// without a snippet yet carry `None`. Default: no snippets (summarization
    /// unsupported).
    #[allow(clippy::type_complexity)]
    fn list_session_snippets(&self) -> Result<Vec<(SessionId, Option<String>, Option<String>)>> {
        Ok(Vec::new())
    }
    /// Every session's rail metadata (git context plus last-output time), so a
    /// client can build its whole session list from one request without
    /// subscribing to each session's event stream. Default: no rows.
    fn list_session_contexts(&self) -> Result<Vec<SessionContextRow>> {
        Ok(Vec::new())
    }
    /// Update status to embed in the `Hello` handshake. Defaults to "this build,
    /// nothing newer known" so non-daemon implementors (test mocks, the MCP
    /// recorder) need not care; the daemon's `SessionManager` overrides it.
    fn server_update_info(&self) -> ServerUpdateInfo {
        ServerUpdateInfo {
            server_version: env!("CARGO_PKG_VERSION").to_string(),
            update_available: false,
            latest_version: None,
        }
    }
}

impl<T: SessionApi + ?Sized> SessionApi for std::sync::Arc<T> {
    fn list_sessions(&self) -> Result<Vec<SessionId>> {
        (**self).list_sessions()
    }
    fn start_session(&self, request: StartSessionRequest) -> Result<SessionId> {
        (**self).start_session(request)
    }
    fn attach_session(&self, request: AttachSessionRequest) -> Result<AttachSessionResponse> {
        (**self).attach_session(request)
    }
    fn subscribe_session_events(&self, session_id: SessionId) -> Result<SessionEventReceiver> {
        (**self).subscribe_session_events(session_id)
    }
    fn subscribe_session_events_from(
        &self,
        request: SubscribeSessionEventsRequest,
    ) -> Result<SessionEventReceiver> {
        (**self).subscribe_session_events_from(request)
    }
    fn acquire_input_lease(&self, request: InputLeaseRequest) -> Result<LeaseChange> {
        (**self).acquire_input_lease(request)
    }
    fn release_input_lease(
        &self,
        session_id: SessionId,
        client_id: ClientId,
    ) -> Result<LeaseChange> {
        (**self).release_input_lease(session_id, client_id)
    }
    fn write_input(&self, request: WriteInputRequest) -> Result<()> {
        (**self).write_input(request)
    }
    fn resize_session(&self, request: ResizeSessionRequest) -> Result<SessionSnapshot> {
        (**self).resize_session(request)
    }
    fn restore_session(&self, request: RestoreSessionRequest) -> Result<SessionSnapshot> {
        (**self).restore_session(request)
    }
    fn snapshot_session(&self, session_id: SessionId) -> Result<SessionSnapshot> {
        (**self).snapshot_session(session_id)
    }
    fn styled_rows(&self, request: StyledRowsRequest) -> Result<StyledRowsResponse> {
        (**self).styled_rows(request)
    }
    fn shutdown_session(&self, session_id: SessionId) -> Result<CompletedSession> {
        (**self).shutdown_session(session_id)
    }
    #[allow(clippy::type_complexity)]
    fn list_session_snippets(&self) -> Result<Vec<(SessionId, Option<String>, Option<String>)>> {
        (**self).list_session_snippets()
    }
    fn list_session_contexts(&self) -> Result<Vec<SessionContextRow>> {
        (**self).list_session_contexts()
    }
    fn server_update_info(&self) -> ServerUpdateInfo {
        (**self).server_update_info()
    }
}

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

    #[test]
    fn observer_attach_is_default_and_does_not_grant_input() {
        assert_eq!(AttachMode::default(), AttachMode::Observer);
        assert!(!AttachMode::Observer.grants_input());
        assert!(AttachMode::InteractiveController.grants_input());
        assert!(AttachMode::AgentController.grants_input());
    }

    #[test]
    fn input_lease_tracks_acquire_takeover_and_release() {
        let mut lease = InputLeaseState::default();
        let tui = ClientId::new("local-tui").expect("client id");
        let agent = ClientId::new("agent").expect("client id");

        let acquired = lease.acquire(tui.clone(), InputControllerKind::Interactive);
        assert_eq!(acquired.action, LeaseChangeAction::Acquired);
        assert_eq!(acquired.generation, 1);
        assert_eq!(lease.holder.as_ref().unwrap().client_id, tui);

        let takeover = lease.acquire(agent.clone(), InputControllerKind::Agent);
        assert_eq!(takeover.action, LeaseChangeAction::TakenOver);
        assert_eq!(takeover.generation, 2);
        assert_eq!(takeover.previous.unwrap().client_id, tui);
        assert_eq!(lease.holder.as_ref().unwrap().client_id, agent);

        assert!(lease.release(&tui).is_none());
        let released = lease.release(&agent).expect("release current holder");
        assert_eq!(released.action, LeaseChangeAction::Released);
        assert_eq!(released.generation, 3);
        assert!(lease.holder.is_none());
    }

    #[test]
    fn session_size_validates_transport_bounds() {
        SessionSize::default().validate().expect("default size");

        let size = SessionSize {
            rows: 0,
            ..SessionSize::default()
        };
        assert!(size.validate().is_err());

        let size = SessionSize {
            cols: u16::MAX as usize + 1,
            ..SessionSize::default()
        };
        assert!(size.validate().is_err());
    }

    #[test]
    fn start_session_request_requires_command_and_valid_size() {
        let request = StartSessionRequest::new("/bin/sh");
        request.validate().expect("valid request");

        let request = StartSessionRequest::new(" ");
        assert!(request.validate().is_err());
    }

    fn ctx(repo: Option<&str>, worktree: Option<&str>, branch: Option<&str>) -> SessionContext {
        SessionContext {
            repository_root: repo.map(PathBuf::from),
            worktree_root: worktree.map(PathBuf::from),
            branch: branch.map(str::to_string),
        }
    }

    #[test]
    fn path_leaf_name_takes_the_last_component() {
        assert_eq!(
            path_leaf_name(Path::new("/home/dev/triage")).as_deref(),
            Some("triage")
        );
        // A path with no final component has no leaf.
        assert_eq!(path_leaf_name(Path::new("/")), None);
    }

    #[test]
    fn distinct_worktree_root_hides_the_repo_root() {
        // Worktree equal to the repo root is not distinct.
        assert_eq!(
            ctx(Some("/home/dev/triage"), Some("/home/dev/triage"), None).distinct_worktree_root(),
            None
        );
        // A linked worktree under the repo is distinct.
        assert_eq!(
            ctx(
                Some("/home/dev/triage"),
                Some("/home/dev/triage/worktrees/feat-summary"),
                None,
            )
            .distinct_worktree_root(),
            Some(Path::new("/home/dev/triage/worktrees/feat-summary"))
        );
        // Worktree set without a repo root is still distinct.
        assert_eq!(
            ctx(None, Some("/tmp/scratch"), None).distinct_worktree_root(),
            Some(Path::new("/tmp/scratch"))
        );
    }

    #[test]
    fn branch_name_treats_empty_as_absent() {
        assert_eq!(ctx(None, None, Some("main")).branch_name(), Some("main"));
        assert_eq!(ctx(None, None, Some("")).branch_name(), None);
        assert_eq!(ctx(None, None, None).branch_name(), None);
    }

    #[test]
    fn localization_label_joins_repo_branch_worktree() {
        // Linked worktree: all three parts, worktree leaf distinct from branch.
        assert_eq!(
            ctx(
                Some("/home/dev/triage"),
                Some("/home/dev/triage/worktrees/feat-summary"),
                Some("feat/summary"),
            )
            .localization_label()
            .as_deref(),
            Some("triage  ·  feat/summary  ·  feat-summary")
        );

        // Working in the repo root itself: worktree leaf is hidden.
        assert_eq!(
            ctx(
                Some("/home/dev/triage"),
                Some("/home/dev/triage"),
                Some("main"),
            )
            .localization_label()
            .as_deref(),
            Some("triage  ·  main")
        );

        // Worktree leaf that merely echoes the branch is suppressed.
        assert_eq!(
            ctx(
                Some("/home/dev/triage"),
                Some("/home/dev/triage/worktrees/feature"),
                Some("feature"),
            )
            .localization_label()
            .as_deref(),
            Some("triage  ·  feature")
        );

        // No git context at all: no label.
        assert_eq!(ctx(None, None, None).localization_label(), None);
    }
}