car-server-core 0.52.1

Transport-neutral library for the CAR daemon JSON-RPC dispatcher (used by car-server and tokhn-daemon)
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
//! Pure state core for the browser drawer: WHO is driving the browser
//! (agent vs user) and WHAT the drawer shows (tabs, action label, sign-in
//! strip, blackout).
//!
//! Two pieces, both pure — state + event -> new state (+ effects as data).
//! No I/O, no timers, no channels live here; [`super::browser_tools`]
//! supplies those around this core (a blocking poll for the agent-pause-at-
//! tool-boundary check, the real clock for the disconnect grace period). The
//! wire surface (`browser.view.*` RPCs, event fanout, and the actual gating
//! of the screencast pump using [`ControlState::is_blackout_active`]) is a
//! later task's job entirely — nothing here does I/O or knows about JSON-RPC.
//!
//! - [`ControlState`] — the control-ownership state machine: who drives,
//!   the agent's current action label, and the pending sign-in request.
//!   [`ControlState::apply`] is the only way to change it. Exposes the two
//!   predicates callers gate on: [`ControlState::may_agent_act`] (the
//!   tool-boundary pause check, also what closes the approval race — see
//!   its doc comment) and [`ControlState::is_blackout_active`] (what the
//!   frame/recording layer will gate on).
//! - [`PresentationState`] / [`Presentation`] — the presentation-state
//!   model: a [`ControlState`] plus the current tab list, projected into
//!   the snapshot a later wire surface will serialize, stamped with a
//!   monotonic `revision` that only advances when something actually
//!   changed — the seam a snapshot+delta subscription needs.

use car_browser::TabInfo;

/// Who is driving the browser right now.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ControlOwner {
    /// No agent has attached to the browser during the current run — the
    /// user's own browser, zero ceremony, no strip shown.
    #[default]
    NoAgent,
    Agent,
    User,
}

/// A pending sign-in request, surfaced as the drawer's orange strip.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingSignIn {
    /// Plain-words prompt for the strip, e.g. "Sign in at accounts.example.com".
    pub message: String,
}

/// One input to the control-ownership state machine.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ControlEvent {
    /// An agent attaches to the browser at the start of a run — the first
    /// browse-related tool call of the run.
    AgentAttached,
    /// The agent is about to perform a labeled browse action, e.g. "Filling
    /// trip details on …" — sourced from the browse tool invocation.
    AgentActionStarted(String),
    /// That action returned (or was cancelled). Paired with the event above
    /// on EVERY exit from the browse call, because nothing else clears the
    /// label: `RunEnded` was the only clear, so the drawer's action strip
    /// reported the last browse action as still running for the rest of the
    /// turn — including while the agent was doing something else entirely,
    /// or nothing at all.
    AgentActionFinished,
    /// User presses "Take control".
    TakeControl,
    /// User presses "Hand back to CAR". Also how a pending sign-in resolves
    /// early — it's the SAME affordance, since a pending sign-in already
    /// hands page input to the user.
    HandBack,
    /// The run ends. Immediate, no grace period: the user's browser again,
    /// zero ceremony.
    RunEnded,
    /// The connection holding user control dropped. Starts a grace period —
    /// the caller owns the actual clock; see [`ControlEffect::StartGracePeriod`].
    ControlHolderDisconnected,
    /// The stated grace period elapsed with no reconnect or hand-back.
    GracePeriodExpired,
    /// An agent action needs the user to sign in.
    SignInRequested(String),
    /// The person drove the browser — a click, a keystroke, a paste, a
    /// navigation from the drawer. Not an ownership change: it is the evidence
    /// that somebody is actually AT the browser right now, which is what
    /// decides whether a sign-in timeout may end their window (see
    /// [`ControlState::user_engaged`]).
    UserInput,
    /// `browser_await_signin`'s own detection loop (URL heuristic, or its
    /// timeout) settled the pending sign-in on its own, without a hand-back.
    SignInResolved { signed_in: bool },
}

/// Something the caller applying an event — or a caller of ITS result —
/// should act on. Emitted alongside the new state; the reducer never
/// performs these itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ControlEffect {
    /// Start the disconnect grace-period timer. Feed `GracePeriodExpired`
    /// back in once it elapses; if control was handed back first, the late
    /// expiry is a no-op (see the reducer's own handling).
    StartGracePeriod,
    /// A pending sign-in resolved as a SIDE EFFECT of this event — a
    /// hand-back while `browser_await_signin` was still waiting, or the run
    /// ending — rather than because a `SignInResolved` event was fed in
    /// directly. Mirrors what `browser_await_signin` itself would return.
    SignInResolved { signed_in: bool },
}

/// The control-ownership state machine. Pure: [`ControlState::apply`] is the
/// only way to change it, and it never touches a clock, a socket, or a lock.
///
/// Every event is safe to feed at any time — an event that doesn't apply to
/// the current state (`HandBack` with nothing handed back, a stale
/// `GracePeriodExpired` after an on-time hand-back) is a no-op rather than
/// an error, because these are UI-driven events a real client can double-
/// fire under an ordinary race without that being a bug.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ControlState {
    owner: ControlOwner,
    current_action: Option<String>,
    pending_signin: Option<PendingSignIn>,
    /// Whether the person has engaged with the browser since the current
    /// sign-in was requested — took control, or drove it directly.
    ///
    /// The sign-in timeout's contract is "the strip clears, the agent receives
    /// the same timeout result, and control returns to it" — which is right
    /// when the timer expired because nobody ever came. It is wrong when
    /// somebody is mid-credential-entry, because clearing the strip lifts the
    /// blackout under them: the model's page reads reopen and an in-flight
    /// recording (a `FrameAudience::Model` consumer kept registered precisely
    /// so it resumes) starts writing the login form to disk.
    ///
    /// This flag is what separates the two. Set by `TakeControl` and by
    /// `UserInput`; cleared when a sign-in is requested (each window judges
    /// its own) and when one resolves.
    ///
    /// **The rule is uniform across every agent-side ending.** The timeout was
    /// the first one to consult it and for one round it was the only one, which
    /// left `RunEnded` — a turn finishing, a `browser_await_signin` returning
    /// its timeout error, the reaper aborting the run — resolving the sign-in
    /// and lifting the blackout under a person still at the credential form.
    /// Whatever ends on the AGENT's side, the person's window persists until a
    /// signal from the PERSON: hand-back, or the disconnect grace expiring.
    user_engaged: bool,
    /// Whether the run that attached this agent has ended.
    ///
    /// Needed because `RunEnded` while the user holds control is deliberately
    /// deferred — ownership and the blackout survive until hand-back — so at
    /// hand-back time the reducer has to know whether there is still an agent
    /// to hand back TO. Without it, hand-back after a run ended would return
    /// control to an agent that no longer exists and leave the strip up
    /// forever.
    run_ended: bool,
}

impl ControlState {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn owner(&self) -> ControlOwner {
        self.owner
    }

    pub fn current_action(&self) -> Option<&str> {
        self.current_action.as_deref()
    }

    pub fn pending_signin(&self) -> Option<&PendingSignIn> {
        self.pending_signin.as_ref()
    }

    /// Is a person demonstrably at this browser right now — holding control,
    /// or having driven it since the current sign-in was requested?
    ///
    /// The one question the sign-in timeout has to answer. See
    /// [`ControlState::user_engaged`].
    pub fn user_engaged(&self) -> bool {
        self.user_engaged || self.owner == ControlOwner::User
    }

    /// Everything about this state a drawer subscriber can observe — what
    /// `PresentationState::apply_control` bumps its revision on.
    ///
    /// `user_engaged` is deliberately absent; see that call site.
    fn visible_state(&self) -> (ControlOwner, Option<String>, Option<PendingSignIn>, bool) {
        (
            self.owner,
            self.current_action.clone(),
            self.pending_signin.clone(),
            self.run_ended,
        )
    }

    /// The tool-boundary check a browse tool call makes before it runs:
    /// "may the agent act right now?" `false` whenever the user holds
    /// control (or no agent has attached at all).
    ///
    /// This is also what closes the **approval race**: a browse action
    /// pending at an approval prompt (a separate, pre-existing concern —
    /// see `assistant::governance`/`agent_loop::ApprovalDecision`, not
    /// modeled here) must not execute while the user holds control even if
    /// it gets approved mid-race, and must run only after hand-back. That
    /// falls out for free as long as the caller re-checks
    /// `may_agent_act()` at the moment it is ABOUT TO EXECUTE the approved
    /// action, rather than caching the answer from when approval was
    /// requested or granted — approval and execution are different moments,
    /// and only the second one may be gated on stale information for this
    /// to be correct. See the `approval_race_*` test below.
    pub fn may_agent_act(&self) -> bool {
        self.owner == ControlOwner::Agent
    }

    /// Whether the user explicitly holds control right now — `owner ==
    /// User`, nothing else.
    ///
    /// This is deliberately NOT the same predicate as `may_agent_act`
    /// (`owner == Agent`): they only disagree in the `NoAgent` case, where
    /// `may_agent_act` is `false` (correct for the tool-boundary check,
    /// which always runs after the calling tool has already attached) but
    /// `user_holds_control` is also `false` (correct for a call site that
    /// needs to gate BEFORE it has attached — e.g. `browser_record_start`/
    /// `browser_record_stop`/`browser_await_signin`, which check this
    /// before ever touching a session, so their very first invocation ever
    /// — `NoAgent`, nothing to wait for — is never mistaken for the user
    /// holding control). Use `may_agent_act` when the caller has already
    /// established a session; use this when it hasn't yet.
    pub fn user_holds_control(&self) -> bool {
        self.owner == ControlOwner::User
    }

    /// Whether no screenshot/frame may reach the model right now. `true`
    /// while the user holds control OR a sign-in is pending — sign-in
    /// implies the same privacy boundary even though it's the agent's own
    /// `browser_await_signin` call, not an explicit Take Control press,
    /// that puts the page in front of the user.
    pub fn is_blackout_active(&self) -> bool {
        self.owner == ControlOwner::User || self.pending_signin.is_some()
    }

    /// Apply one event, mutating in place, and return what the caller (or a
    /// caller of its result) should do as a result.
    pub fn apply(&mut self, event: ControlEvent) -> Vec<ControlEffect> {
        match event {
            ControlEvent::AgentAttached => {
                self.owner = ControlOwner::Agent;
                self.run_ended = false;
                Vec::new()
            }
            ControlEvent::AgentActionStarted(label) => {
                self.current_action = Some(label);
                Vec::new()
            }
            ControlEvent::AgentActionFinished => {
                self.current_action = None;
                Vec::new()
            }
            ControlEvent::TakeControl => {
                if self.owner == ControlOwner::Agent {
                    self.owner = ControlOwner::User;
                }
                self.user_engaged = true;
                Vec::new()
            }
            ControlEvent::UserInput => {
                self.user_engaged = true;
                Vec::new()
            }
            ControlEvent::HandBack => {
                let mut effects = Vec::new();
                if self.pending_signin.take().is_some() {
                    effects.push(ControlEffect::SignInResolved { signed_in: false });
                }
                if self.owner == ControlOwner::User {
                    // Back to the agent — unless its run already ended while
                    // the user was driving, in which case there is no agent
                    // to hand back TO and this is the moment the ceremony
                    // ends: no strip, no blackout, the user's own browser.
                    self.owner = if self.run_ended {
                        ControlOwner::NoAgent
                    } else {
                        ControlOwner::Agent
                    };
                }
                effects
            }
            ControlEvent::RunEnded => {
                let mut effects = Vec::new();
                // The user holding control OUTLIVES the run. "The agent's
                // turn ending on its own while the user holds control does
                // not reclaim control: the strip keeps stating the user has
                // control until hand-back."
                //
                // The privacy half is why this is not merely cosmetic: the
                // blackout is derived from ownership, so clearing ownership
                // here also lifted it — a recording spanning a user-control
                // or sign-in window would resume capturing frames the moment
                // the run happened to end, mid-window, with the person still
                // driving. Leaving both in place until an explicit hand-back
                // closes that.
                //
                // A pending sign-in is likewise NOT resolved here: the page
                // is still in front of the person, still blacked out, and
                // hand-back is what settles it (honestly, as
                // `signed_in: false` if they never completed it).
                self.run_ended = true;
                self.current_action = None;
                if self.owner == ControlOwner::User {
                    return effects;
                }
                // Engaged WITHOUT a Take control press — the ordinary sign-in
                // flow, where the orange strip IS the affordance and
                // `require_control` admits input so the person can type
                // without pressing anything. Ownership is blind to it, which
                // is why this branch reads engagement instead.
                //
                // The run really has ended, so ownership goes to `NoAgent`;
                // what does NOT go is the pending sign-in, and with it the
                // blackout, because the person is at the credential form right
                // now. Their own signal settles it — hand-back, or the
                // disconnect grace (`BrowserView::note_watcher_disconnect`) —
                // each of which resolves it honestly as `signed_in: false`.
                // The agent is unaffected either way: `browser_await_signin`
                // has already returned its timeout error to the model.
                if self.user_engaged {
                    self.owner = ControlOwner::NoAgent;
                    return effects;
                }
                if self.pending_signin.take().is_some() {
                    effects.push(ControlEffect::SignInResolved { signed_in: false });
                }
                self.owner = ControlOwner::NoAgent;
                effects
            }
            ControlEvent::ControlHolderDisconnected => {
                // A pending sign-in with nobody holding control is the engaged
                // window above: the person's connection going away is the only
                // signal left that says they are not coming back, so it starts
                // the same clock a holder's disconnect does. Reaching this arm
                // at all requires the caller to have established that the
                // connection was watching THIS view — see
                // `BrowserView::note_watcher_disconnect`.
                if self.owner == ControlOwner::User || self.pending_signin.is_some() {
                    vec![ControlEffect::StartGracePeriod]
                } else {
                    Vec::new()
                }
            }
            ControlEvent::GracePeriodExpired => {
                // Same question hand-back asks — and it has to answer BOTH
                // halves of it, not just ownership.
                //
                // `is_blackout_active()` is `owner == User || pending_signin
                // .is_some()`, so reverting ownership while leaving a pending
                // sign-in set leaves a live blackout with nobody holding the
                // wheel to end it: the strip stays up forever, and every
                // model-facing read stays gated behind a person who has
                // already gone. Reachable on the shared process-lifetime
                // `BrowserTools` — sign-in requested, user takes control, the
                // host quits, the run is cancelled inside the grace window
                // (so `RunEnded` takes the deferred `owner == User` branch
                // that deliberately does not touch `pending_signin`), then
                // grace expires. Nothing else clears it after that.
                //
                // Resolved honestly as `signed_in: false`, exactly as
                // hand-back does: the person vanished mid-flow, so the
                // sign-in did not complete.
                let mut effects = Vec::new();
                if self.pending_signin.take().is_some() {
                    effects.push(ControlEffect::SignInResolved { signed_in: false });
                }
                if self.owner == ControlOwner::User {
                    self.owner = if self.run_ended {
                        ControlOwner::NoAgent
                    } else {
                        ControlOwner::Agent
                    };
                }
                effects
            }
            ControlEvent::SignInRequested(message) => {
                self.pending_signin = Some(PendingSignIn { message });
                // Each sign-in window judges its own engagement. A person who
                // typed during a PREVIOUS sign-in says nothing about whether
                // anyone is at the browser for this one.
                self.user_engaged = self.owner == ControlOwner::User;
                Vec::new()
            }
            ControlEvent::SignInResolved { .. } => {
                self.pending_signin = None;
                self.user_engaged = false;
                Vec::new()
            }
        }
    }
}

/// The presentation-state model — what the drawer shows. A snapshot type,
/// not itself a reducer: [`PresentationState`] is the mutable holder,
/// [`Presentation`] is what it projects out for a wire surface to serialize.
#[derive(Debug, Clone, PartialEq)]
pub struct Presentation {
    /// Monotonically increases by one on every change (a control-state
    /// transition that actually did something, or a tab-list update).
    /// Two snapshots at the same revision are content-identical, which is
    /// the seam a later snapshot+delta subscription needs.
    pub revision: u64,
    pub owner: ControlOwner,
    pub current_action: Option<String>,
    pub pending_signin: Option<PendingSignIn>,
    pub blackout_active: bool,
    /// id / URL / title / active, per tab — see [`car_browser::TabInfo`].
    pub tabs: Vec<TabInfo>,
}

/// Combines the control-ownership state machine with the current tab list,
/// bumping a monotonic revision on every actual change — never on a no-op
/// event or a re-set of identical tabs — so a subscriber never mistakes "I
/// asked" for "it changed."
#[derive(Debug, Clone, Default)]
pub struct PresentationState {
    control: ControlState,
    tabs: Vec<TabInfo>,
    revision: u64,
}

impl PresentationState {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn control(&self) -> &ControlState {
        &self.control
    }

    /// Apply one control-ownership event. Bumps `revision` iff the control
    /// state actually changed as a result.
    pub fn apply_control(&mut self, event: ControlEvent) -> Vec<ControlEffect> {
        // Compared on what a subscriber can SEE, not on the whole reducer
        // state. `user_engaged` is bookkeeping for the sign-in timeout, and
        // `UserInput` fires on every click and keystroke — letting it bump the
        // revision would emit a presentation event per input, at input rate,
        // for something nothing renders.
        let before = self.control.visible_state();
        let effects = self.control.apply(event);
        if self.control.visible_state() != before {
            self.revision += 1;
        }
        effects
    }

    /// Replace the tab list — fed from `ChromiumBackend::list_tabs()` (or a
    /// future `subscribe_tabs()` update). Bumps `revision` iff it actually
    /// changed.
    pub fn set_tabs(&mut self, tabs: Vec<TabInfo>) {
        if self.tabs != tabs {
            self.tabs = tabs;
            self.revision += 1;
        }
    }

    /// The current snapshot. Cheap to call repeatedly — only
    /// `apply_control`/`set_tabs` advance `revision`, not this.
    pub fn snapshot(&self) -> Presentation {
        Presentation {
            revision: self.revision,
            owner: self.control.owner(),
            current_action: self.control.current_action().map(str::to_string),
            pending_signin: self.control.pending_signin().cloned(),
            blackout_active: self.control.is_blackout_active(),
            tabs: self.tabs.clone(),
        }
    }
}

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

    /// The un-engaged branch of the timeout ruling: nobody ever came, so the
    /// contract's semantics apply exactly — the strip clears, the blackout
    /// lifts, control returns to the agent. Latching here is what wedged the
    /// one-shot `car do` path, which has no drawer, no Hand back, and no
    /// run-end signal reaching this reducer at all.
    #[test]
    fn a_signin_nobody_engaged_with_is_resolvable_on_timeout() {
        let mut state = ControlState::new();
        state.apply(ControlEvent::AgentAttached);
        state.apply(ControlEvent::SignInRequested("Sign in at x".into()));

        assert!(
            !state.user_engaged(),
            "nobody took control and nobody typed"
        );
        // What the timeout then does.
        state.apply(ControlEvent::SignInResolved { signed_in: false });
        assert!(!state.is_blackout_active(), "the blackout lifts");
        assert_eq!(state.owner(), ControlOwner::Agent, "control returns to it");
    }

    /// The engaged branch, by INPUT rather than by Take control — the case
    /// ownership cannot see, and the ordinary sign-in flow, since the orange
    /// strip is the affordance and nobody presses anything.
    #[test]
    fn typing_during_a_signin_makes_it_the_persons_window() {
        let mut state = ControlState::new();
        state.apply(ControlEvent::AgentAttached);
        state.apply(ControlEvent::SignInRequested("Sign in at x".into()));

        state.apply(ControlEvent::UserInput);

        assert!(
            state.user_engaged(),
            "somebody is at the credential form, whatever the owner flag says"
        );
        assert_eq!(
            state.owner(),
            ControlOwner::Agent,
            "and never pressed anything"
        );
        assert!(state.is_blackout_active());
    }

    /// Take control is the other way in, and each window judges its own: a
    /// person who engaged with a PREVIOUS sign-in says nothing about this one.
    #[test]
    fn engagement_is_scoped_to_the_current_signin_window() {
        let mut state = ControlState::new();
        state.apply(ControlEvent::AgentAttached);
        state.apply(ControlEvent::SignInRequested("first".into()));
        state.apply(ControlEvent::UserInput);
        assert!(state.user_engaged());

        // That one settles, and the agent later asks again.
        state.apply(ControlEvent::HandBack);
        state.apply(ControlEvent::SignInRequested("second".into()));
        assert!(
            !state.user_engaged(),
            "a fresh window starts with nobody in it"
        );

        // Taking control counts too.
        state.apply(ControlEvent::TakeControl);
        assert!(state.user_engaged());
    }

    /// `UserInput` fires on every click and keystroke, so it must not be
    /// presentation state — a revision bump per input would emit a
    /// `browser.view.event` per input, at input rate, for something nothing
    /// renders.
    #[test]
    fn user_input_does_not_bump_the_presentation_revision() {
        let mut p = PresentationState::new();
        p.apply_control(ControlEvent::AgentAttached);
        let before = p.snapshot().revision;
        for _ in 0..25 {
            p.apply_control(ControlEvent::UserInput);
        }
        assert_eq!(p.snapshot().revision, before);
    }

    /// The invariant that makes "the timeout does not resolve the sign-in"
    /// safe: a pending sign-in nobody completes still cannot latch forever,
    /// because all three settling events clear it honestly. Without this the
    /// timeout was the only clearer — and it fires on a timer, which is not
    /// evidence the person finished or left.
    ///
    /// **Scoped to the UN-engaged window**, which is what these three events
    /// may settle on their own. Nobody typed and nobody took control here (a
    /// `SignInRequested` with `owner == Agent` seeds `user_engaged` false), so
    /// there is no person whose blackout this could lift. The engaged case is
    /// `a_run_ending_under_an_engaged_person_keeps_their_window` below.
    #[test]
    fn every_settling_event_clears_an_unengaged_pending_signin() {
        for settle in [
            ControlEvent::HandBack,
            ControlEvent::RunEnded,
            ControlEvent::GracePeriodExpired,
        ] {
            let mut state = ControlState::new();
            state.apply(ControlEvent::AgentAttached);
            state.apply(ControlEvent::SignInRequested("Sign in at x".into()));
            assert!(state.is_blackout_active());

            let effects = state.apply(settle.clone());

            assert!(
                state.pending_signin().is_none(),
                "{settle:?} must settle a sign-in nobody completed"
            );
            assert!(
                !state.is_blackout_active(),
                "{settle:?} must lift the blackout"
            );
            assert_eq!(
                effects,
                vec![ControlEffect::SignInResolved { signed_in: false }],
                "{settle:?} must report it honestly"
            );
        }
    }

    /// `is_blackout_active()` is `owner == User || pending_signin.is_some()`,
    /// so reverting ownership while leaving a pending sign-in set leaves a
    /// live blackout with nobody holding the wheel to end it — the strip up
    /// forever and every model-facing read gated behind a person who has gone.
    #[test]
    fn grace_expiry_resolves_a_pending_signin_the_way_hand_back_does() {
        let mut state = ControlState::new();
        state.apply(ControlEvent::AgentAttached);
        state.apply(ControlEvent::SignInRequested("Sign in at x".into()));
        state.apply(ControlEvent::TakeControl);
        assert!(state.is_blackout_active());

        // The controller vanished and never came back.
        state.apply(ControlEvent::ControlHolderDisconnected);
        let effects = state.apply(ControlEvent::GracePeriodExpired);

        assert_eq!(state.owner(), ControlOwner::Agent);
        assert!(
            state.pending_signin().is_none(),
            "a sign-in nobody is completing must not outlive the person completing it"
        );
        assert!(
            !state.is_blackout_active(),
            "and the blackout must lift with it"
        );
        assert_eq!(
            effects,
            vec![ControlEffect::SignInResolved { signed_in: false }],
            "reported honestly: they never finished"
        );
    }

    fn sample_tabs(url: &str, title: &str) -> Vec<TabInfo> {
        // TabId is opaque outside car-browser by design (Task 2's report:
        // "ids are never reused") — mint real ones through TabRegistry
        // itself, the same generic-over-a-cheap-handle seam Task 2's own
        // tests use, rather than trying to fabricate one.
        let (mut registry, _rx) = car_browser::tabs::TabRegistry::<&'static str>::new();
        registry.open("handle", url, title);
        registry.list()
    }

    // ---- owner transitions ----

    #[test]
    fn no_agent_is_the_default_owner() {
        assert_eq!(ControlState::new().owner(), ControlOwner::NoAgent);
    }

    #[test]
    fn agent_attaches_and_becomes_owner() {
        let mut s = ControlState::new();
        let effects = s.apply(ControlEvent::AgentAttached);
        assert_eq!(s.owner(), ControlOwner::Agent);
        assert!(effects.is_empty());
    }

    #[test]
    fn take_control_hands_owner_to_user() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::TakeControl);
        assert_eq!(s.owner(), ControlOwner::User);
    }

    #[test]
    fn take_control_is_a_noop_without_an_agent() {
        // "no ceremony" — there is nothing to take yet.
        let mut s = ControlState::new();
        s.apply(ControlEvent::TakeControl);
        assert_eq!(s.owner(), ControlOwner::NoAgent);
    }

    #[test]
    fn hand_back_returns_owner_to_agent() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::TakeControl);
        s.apply(ControlEvent::HandBack);
        assert_eq!(s.owner(), ControlOwner::Agent);
    }

    #[test]
    fn hand_back_without_taking_control_is_a_noop() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        let effects = s.apply(ControlEvent::HandBack);
        assert_eq!(s.owner(), ControlOwner::Agent);
        assert!(effects.is_empty());
    }

    #[test]
    fn run_end_clears_ownership_with_no_ceremony() {
        // The AGENT-holding case: the run ends while the agent still owns the
        // browser, so there is nothing to hand back and the ceremony ends
        // immediately — no strip, every control live.
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::AgentActionStarted("Navigating".to_string()));
        s.apply(ControlEvent::RunEnded);
        assert_eq!(s.owner(), ControlOwner::NoAgent);
        assert_eq!(s.current_action(), None);
    }

    /// "The agent's turn ending on its own while the user holds control does
    /// not reclaim control: the strip keeps stating the user has control
    /// until hand-back."
    ///
    /// This case previously asserted the opposite — `RunEnded` cleared
    /// ownership unconditionally — which is the bug the live verification
    /// caught: the user was driving, the run ended on its own, and the drawer
    /// silently reported `owner=none blackout=false` with the person still at
    /// the keyboard.
    #[test]
    fn a_run_ending_while_the_user_drives_does_not_reclaim_control() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::AgentActionStarted("Navigating".to_string()));
        s.apply(ControlEvent::TakeControl);
        s.apply(ControlEvent::RunEnded);

        assert_eq!(s.owner(), ControlOwner::User, "the user is still driving");
        assert_eq!(
            s.current_action(),
            None,
            "but the agent is no longer doing anything, so the action line clears"
        );
    }

    /// The privacy half, and the reason this is not merely cosmetic: the
    /// blackout is derived from ownership, so clearing ownership at run end
    /// also LIFTED it — a recording spanning a user-control window would
    /// resume capturing frames the moment the run happened to end, with the
    /// person still driving.
    #[test]
    fn a_run_ending_while_the_user_drives_does_not_lift_the_blackout() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::TakeControl);
        assert!(s.is_blackout_active());

        s.apply(ControlEvent::RunEnded);
        assert!(
            s.is_blackout_active(),
            "no frame may reach the model or a recording while the user is still driving"
        );

        s.apply(ControlEvent::HandBack);
        assert!(!s.is_blackout_active(), "hand-back is what lifts it");
    }

    /// A sign-in is likewise not settled by the run ending underneath it: the
    /// page is still in front of the person. Hand-back settles it honestly.
    #[test]
    fn a_run_ending_mid_signin_leaves_the_strip_up_until_hand_back() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::TakeControl);
        s.apply(ControlEvent::SignInRequested("Sign in at x".to_string()));
        let effects = s.apply(ControlEvent::RunEnded);

        assert!(effects.is_empty(), "nothing was resolved by the run ending");
        assert!(s.pending_signin().is_some(), "the strip stays up");
        assert!(s.is_blackout_active());

        let effects = s.apply(ControlEvent::HandBack);
        assert_eq!(
            effects,
            vec![ControlEffect::SignInResolved { signed_in: false }],
            "hand-back settles it, honestly"
        );
        assert!(s.pending_signin().is_none());
    }

    /// The round-8 blocker, and the half `a_run_ending_mid_signin_leaves_the
    /// _strip_up_until_hand_back` above could not reach: it presses Take
    /// control first, so it only ever covered `owner == User`. The ORDINARY
    /// sign-in flow has no Take control press at all — the strip is the
    /// affordance and `require_control` admits input while a sign-in is
    /// pending — so `owner` stays `Agent` and the run ending resolved the
    /// sign-in, lifted the blackout, and reopened the model's page reads (and
    /// any in-flight recording) on a live credential form.
    #[test]
    fn a_run_ending_under_an_engaged_person_keeps_their_window() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::SignInRequested("Sign in at x".to_string()));
        // They never pressed Take control; they typed.
        s.apply(ControlEvent::UserInput);
        assert_eq!(s.owner(), ControlOwner::Agent, "precondition: no take");

        let effects = s.apply(ControlEvent::RunEnded);
        assert!(
            effects.is_empty(),
            "an agent-side ending resolves nothing for a person who is still here"
        );
        assert!(s.pending_signin().is_some(), "the strip stays up");
        assert!(
            s.is_blackout_active(),
            "no frame may reach the model or a recording while they are typing"
        );
        assert_eq!(
            s.owner(),
            ControlOwner::NoAgent,
            "the run really did end — what survives is the person's window, not the agent"
        );

        // Their own signal, and it is honest about what happened.
        let effects = s.apply(ControlEvent::HandBack);
        assert_eq!(
            effects,
            vec![ControlEffect::SignInResolved { signed_in: false }]
        );
        assert!(!s.is_blackout_active(), "hand-back is what lifts it");
        assert_eq!(s.owner(), ControlOwner::NoAgent);
    }

    /// The other person-side signal the engaged window may end on: their
    /// connection went away and the grace period elapsed. Without this the
    /// window above would have exactly one exit, and a person who closed the
    /// laptop mid-sign-in would leave the blackout latched for the daemon's
    /// life — wedging every later run's browse call behind it.
    #[test]
    fn the_disconnect_grace_settles_an_engaged_window_the_run_ended_under() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::SignInRequested("Sign in at x".to_string()));
        s.apply(ControlEvent::UserInput);
        s.apply(ControlEvent::RunEnded);
        assert!(s.is_blackout_active());

        // No holder — they never took control — so the ARM has to key on the
        // pending sign-in rather than on ownership.
        assert_eq!(
            s.apply(ControlEvent::ControlHolderDisconnected),
            vec![ControlEffect::StartGracePeriod],
            "a person-facing window with no holder still arms the clock"
        );
        let effects = s.apply(ControlEvent::GracePeriodExpired);
        assert_eq!(
            effects,
            vec![ControlEffect::SignInResolved { signed_in: false }],
            "they vanished mid-flow, so the sign-in did not complete"
        );
        assert!(!s.is_blackout_active());
    }

    /// The un-engaged side of the same arm: a connection dropping on a browser
    /// nobody is signing into and nobody has taken must not start a clock.
    #[test]
    fn a_disconnect_with_no_person_facing_window_arms_nothing() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        assert!(s.apply(ControlEvent::ControlHolderDisconnected).is_empty());
    }

    /// Hand-back after the run already ended has no agent to hand back TO —
    /// so it lands on the no-ceremony state, not on a strip pointing at an
    /// agent that is gone.
    #[test]
    fn hand_back_after_the_run_ended_lands_on_no_agent() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::TakeControl);
        s.apply(ControlEvent::RunEnded);
        s.apply(ControlEvent::HandBack);

        assert_eq!(s.owner(), ControlOwner::NoAgent);
        assert!(!s.is_blackout_active());
        assert_eq!(s.current_action(), None);
    }

    /// Ordinary hand-back — the run is still going — still returns to the
    /// agent. The deferred-run-end path must not have changed that.
    #[test]
    fn hand_back_during_a_live_run_still_returns_control_to_the_agent() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::TakeControl);
        s.apply(ControlEvent::HandBack);
        assert_eq!(s.owner(), ControlOwner::Agent);
    }

    /// The disconnect grace period asks hand-back's question, so it needs
    /// hand-back's answer: revert to the agent, or to nobody if the run ended
    /// while the vanished controller held the wheel.
    #[test]
    fn a_grace_expiry_after_the_run_ended_reverts_to_no_agent() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::TakeControl);
        s.apply(ControlEvent::ControlHolderDisconnected);
        s.apply(ControlEvent::RunEnded);
        s.apply(ControlEvent::GracePeriodExpired);

        assert_eq!(s.owner(), ControlOwner::NoAgent);
        assert!(!s.is_blackout_active());
    }

    /// A fresh run attaching resets the flag, so a later hand-back inside
    /// THAT run returns control to it rather than to nobody.
    #[test]
    fn a_new_run_attaching_clears_the_previous_run_ended_state() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::RunEnded);
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::TakeControl);
        s.apply(ControlEvent::HandBack);
        assert_eq!(s.owner(), ControlOwner::Agent);
    }

    #[test]
    fn agent_action_while_user_holds_control_does_not_reclaim_ownership() {
        // "The agent's turn ending on its own while the user holds control
        // does not reclaim control." There is no event in this reducer that
        // reclaims ownership except HandBack/RunEnded/GracePeriodExpired —
        // prove that feeding agent activity while owner=User does not
        // silently do so either.
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::TakeControl);
        s.apply(ControlEvent::AgentActionStarted(
            "Filling a form".to_string(),
        ));
        assert_eq!(s.owner(), ControlOwner::User);
    }

    // ---- blackout enforcement ----

    #[test]
    fn blackout_is_inactive_by_default() {
        assert!(!ControlState::new().is_blackout_active());
    }

    #[test]
    fn blackout_activates_when_user_takes_control() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::TakeControl);
        assert!(s.is_blackout_active());
    }

    #[test]
    fn blackout_deactivates_on_hand_back() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::TakeControl);
        s.apply(ControlEvent::HandBack);
        assert!(!s.is_blackout_active());
    }

    #[test]
    fn blackout_activates_on_pending_signin_even_while_agent_owns() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::SignInRequested(
            "Sign in at example.com".to_string(),
        ));
        assert_eq!(s.owner(), ControlOwner::Agent);
        assert!(s.is_blackout_active());
    }

    #[test]
    fn blackout_stays_active_until_signin_resolves() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::SignInRequested("Sign in".to_string()));
        assert!(s.is_blackout_active());
        s.apply(ControlEvent::SignInResolved { signed_in: true });
        assert!(!s.is_blackout_active());
    }

    #[test]
    fn blackout_requires_both_user_control_and_signin_to_clear() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::TakeControl);
        s.apply(ControlEvent::SignInRequested("Sign in".to_string()));
        assert!(s.is_blackout_active());
        // HandBack clears BOTH at once (owner and the pending sign-in).
        s.apply(ControlEvent::HandBack);
        assert!(!s.is_blackout_active());
        assert_eq!(s.owner(), ControlOwner::Agent);
        assert_eq!(s.pending_signin(), None);
    }

    // ---- sign-in lifecycle ----

    #[test]
    fn signin_requested_surfaces_the_pending_strip_with_its_message() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::SignInRequested(
            "Sign in at example.com".to_string(),
        ));
        assert_eq!(
            s.pending_signin(),
            Some(&PendingSignIn {
                message: "Sign in at example.com".to_string()
            })
        );
    }

    #[test]
    fn signin_resolved_true_clears_the_strip() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::SignInRequested("Sign in".to_string()));
        s.apply(ControlEvent::SignInResolved { signed_in: true });
        assert_eq!(s.pending_signin(), None);
    }

    #[test]
    fn signin_resolved_false_on_timeout_clears_the_strip() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::SignInRequested("Sign in".to_string()));
        s.apply(ControlEvent::SignInResolved { signed_in: false });
        assert_eq!(s.pending_signin(), None);
    }

    #[test]
    fn hand_back_resolves_a_pending_signin_as_not_signed_in() {
        // "Hand-back triggers resolution of browse_await_signin; ... hand-
        // back without signing in returns signed_in: false" — and this
        // works even without an explicit prior Take Control, since a
        // pending sign-in implies the same "user has the page" state.
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::SignInRequested("Sign in".to_string()));
        let effects = s.apply(ControlEvent::HandBack);
        assert_eq!(s.pending_signin(), None);
        assert_eq!(
            effects,
            vec![ControlEffect::SignInResolved { signed_in: false }]
        );
        // The agent, which never lost run-scoped ownership during a plain
        // sign-in, keeps driving.
        assert_eq!(s.owner(), ControlOwner::Agent);
    }

    #[test]
    fn run_ended_clears_a_pending_signin_too() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::SignInRequested("Sign in".to_string()));
        let effects = s.apply(ControlEvent::RunEnded);
        assert_eq!(s.pending_signin(), None);
        assert_eq!(
            effects,
            vec![ControlEffect::SignInResolved { signed_in: false }]
        );
    }

    // ---- agent-pause-at-tool-boundary ----

    #[test]
    fn agent_may_not_act_before_any_agent_attaches() {
        assert!(!ControlState::new().may_agent_act());
    }

    #[test]
    fn agent_may_act_once_attached() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        assert!(s.may_agent_act());
    }

    #[test]
    fn agent_may_not_act_while_user_holds_control() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::TakeControl);
        assert!(!s.may_agent_act());
    }

    #[test]
    fn agent_may_act_again_after_hand_back() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::TakeControl);
        s.apply(ControlEvent::HandBack);
        assert!(s.may_agent_act());
    }

    #[test]
    fn user_holds_control_is_false_before_any_agent_attaches() {
        // The critical difference from may_agent_act: a call site gating
        // BEFORE it has attached (record_start/record_stop/await_signin)
        // must not mistake "nobody has attached yet" for "the user is
        // driving" — there is nothing to wait for.
        assert!(!ControlState::new().user_holds_control());
    }

    #[test]
    fn user_holds_control_is_false_while_the_agent_owns() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        assert!(!s.user_holds_control());
    }

    #[test]
    fn user_holds_control_is_true_once_the_user_takes_control() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::TakeControl);
        assert!(s.user_holds_control());
    }

    #[test]
    fn user_holds_control_is_false_again_after_hand_back() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::TakeControl);
        s.apply(ControlEvent::HandBack);
        assert!(!s.user_holds_control());
    }

    // ---- grace-period revert ----

    #[test]
    fn disconnect_while_user_holds_control_starts_a_grace_period() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::TakeControl);
        let effects = s.apply(ControlEvent::ControlHolderDisconnected);
        assert_eq!(effects, vec![ControlEffect::StartGracePeriod]);
        // Still held — the grace period hasn't expired yet.
        assert_eq!(s.owner(), ControlOwner::User);
    }

    #[test]
    fn disconnect_without_user_control_is_a_noop() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        let effects = s.apply(ControlEvent::ControlHolderDisconnected);
        assert!(effects.is_empty());
        assert_eq!(s.owner(), ControlOwner::Agent);
    }

    #[test]
    fn grace_period_expiry_reverts_control_to_agent() {
        // "an agent is never parked forever behind a vanished controller."
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::TakeControl);
        s.apply(ControlEvent::ControlHolderDisconnected);
        s.apply(ControlEvent::GracePeriodExpired);
        assert_eq!(s.owner(), ControlOwner::Agent);
    }

    #[test]
    fn hand_back_before_grace_expiry_makes_the_late_expiry_a_noop() {
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        s.apply(ControlEvent::TakeControl);
        s.apply(ControlEvent::ControlHolderDisconnected);
        s.apply(ControlEvent::HandBack);
        assert_eq!(s.owner(), ControlOwner::Agent);
        // A stale timer firing after an on-time hand-back must not panic or
        // do anything odd — the owner is already Agent.
        let effects = s.apply(ControlEvent::GracePeriodExpired);
        assert!(effects.is_empty());
        assert_eq!(s.owner(), ControlOwner::Agent);
    }

    // ---- approval race ----

    #[test]
    fn approval_race_action_blocked_while_user_holds_control_runs_only_after_handback() {
        // The approval system itself (whether a browse action needs a human
        // sign-off before it runs) lives elsewhere — this reducer only owns
        // the owner gate. What has to hold here: a caller that re-checks
        // may_agent_act() at the moment it is about to EXECUTE an approved
        // action (not when it was proposed/approved) can never run that
        // action while the user holds control, and it becomes runnable the
        // instant hand-back happens.
        let mut s = ControlState::new();
        s.apply(ControlEvent::AgentAttached);
        assert!(s.may_agent_act(), "proposal time: agent still owns");

        // The user takes control while the action sits at an (external)
        // approval prompt.
        s.apply(ControlEvent::TakeControl);
        // Approval lands (external event, not modeled here) — but the gate,
        // re-checked now, still says no.
        assert!(
            !s.may_agent_act(),
            "approved but must not execute while the user holds control"
        );

        s.apply(ControlEvent::HandBack);
        assert!(s.may_agent_act(), "now it may run");
    }

    // ---- presentation state / revision ----

    #[test]
    fn revision_starts_at_zero() {
        assert_eq!(PresentationState::new().snapshot().revision, 0);
    }

    #[test]
    fn revision_bumps_on_a_real_control_change() {
        let mut p = PresentationState::new();
        p.apply_control(ControlEvent::AgentAttached);
        assert_eq!(p.snapshot().revision, 1);
    }

    #[test]
    fn revision_does_not_bump_on_a_noop_event() {
        let mut p = PresentationState::new();
        // No agent attached yet — TakeControl is a no-op.
        p.apply_control(ControlEvent::TakeControl);
        assert_eq!(p.snapshot().revision, 0);
    }

    #[test]
    fn revision_bumps_when_tabs_actually_change() {
        let mut p = PresentationState::new();
        p.set_tabs(sample_tabs("https://example.com", "Example"));
        assert_eq!(p.snapshot().revision, 1);
    }

    #[test]
    fn revision_does_not_bump_when_tabs_are_reset_to_the_same_value() {
        let mut p = PresentationState::new();
        let tabs = sample_tabs("https://example.com", "Example");
        p.set_tabs(tabs.clone());
        p.set_tabs(tabs);
        assert_eq!(p.snapshot().revision, 1);
    }

    #[test]
    fn snapshot_reflects_owner_action_signin_blackout_and_tabs_together() {
        let mut p = PresentationState::new();
        p.apply_control(ControlEvent::AgentAttached);
        p.apply_control(ControlEvent::AgentActionStarted(
            "Filling trip details on example.com".to_string(),
        ));
        p.set_tabs(sample_tabs("https://example.com", "Example"));
        let snap = p.snapshot();
        assert_eq!(snap.owner, ControlOwner::Agent);
        assert_eq!(
            snap.current_action.as_deref(),
            Some("Filling trip details on example.com")
        );
        assert_eq!(snap.pending_signin, None);
        assert!(!snap.blackout_active);
        assert_eq!(snap.tabs.len(), 1);
        assert!(snap.tabs[0].active);
        assert_eq!(snap.tabs[0].url, "https://example.com");
    }
}