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
//! Tab manager for coordinating multiple terminal tabs within a window
use super::{Tab, TabId};
use crate::config::Config;
use crate::profile::Profile;
use anyhow::Result;
use std::sync::Arc;
use tokio::runtime::Runtime;
/// Manages multiple terminal tabs within a single window
pub struct TabManager {
/// All tabs in this window, in order
pub(super) tabs: Vec<Tab>,
/// Currently active tab ID
pub(super) active_tab_id: Option<TabId>,
/// Counter for generating unique tab IDs
next_tab_id: TabId,
}
impl TabManager {
/// Create a new empty tab manager
pub fn new() -> Self {
Self {
tabs: Vec::new(),
active_tab_id: None,
next_tab_id: 1,
}
}
/// Set the active tab, flipping is_active flags on old and new tabs
pub(super) fn set_active_tab(&mut self, id: Option<TabId>) {
use std::sync::atomic::Ordering;
// Deactivate old tab and its panes
if let Some(old_id) = self.active_tab_id
&& let Some(old_tab) = self.tabs.iter().find(|t| t.id == old_id)
{
old_tab.is_active.store(false, Ordering::Relaxed);
if let Some(ref pm) = old_tab.pane_manager {
for pane in pm.all_panes() {
pane.is_active.store(false, Ordering::Relaxed);
}
}
}
// Activate new tab and its panes
if let Some(new_id) = id
&& let Some(new_tab) = self.tabs.iter().find(|t| t.id == new_id)
{
new_tab.is_active.store(true, Ordering::Relaxed);
if let Some(ref pm) = new_tab.pane_manager {
for pane in pm.all_panes() {
pane.is_active.store(true, Ordering::Relaxed);
}
}
}
self.active_tab_id = id;
}
/// Create a new tab and return its ID
///
/// # Arguments
/// * `config` - Terminal configuration
/// * `runtime` - Tokio runtime for async operations
/// * `inherit_cwd_from_active` - Whether to inherit working directory from active tab
/// * `grid_size` - Optional (cols, rows) override for initial terminal size.
/// When provided, these dimensions are used instead of config.cols/rows.
/// This is important when the renderer has already calculated the correct
/// grid size accounting for tab bar height.
pub fn new_tab(
&mut self,
config: &Config,
runtime: Arc<Runtime>,
inherit_cwd_from_active: bool,
grid_size: Option<(usize, usize)>,
) -> Result<TabId> {
// Optionally inherit working directory from active tab
let working_dir = if inherit_cwd_from_active {
self.active_tab().and_then(|tab| tab.get_cwd())
} else {
None
};
let id = self.next_tab_id;
self.next_tab_id += 1;
// Tab number is based on current count, not unique ID
let tab_number = self.tabs.len() + 1;
let tab = Tab::new(id, tab_number, config, runtime, working_dir, grid_size)?;
self.tabs.push(tab);
// Always switch to the new tab
self.set_active_tab(Some(id));
log::info!("Created new tab {} (total: {})", id, self.tabs.len());
Ok(id)
}
/// Create a new tab with a specific working directory
///
/// Used by arrangement restore to create tabs with saved CWDs.
pub fn new_tab_with_cwd(
&mut self,
config: &Config,
runtime: Arc<Runtime>,
working_dir: Option<String>,
grid_size: Option<(usize, usize)>,
) -> Result<TabId> {
let id = self.next_tab_id;
self.next_tab_id += 1;
let tab_number = self.tabs.len() + 1;
let tab = Tab::new(id, tab_number, config, runtime, working_dir, grid_size)?;
self.tabs.push(tab);
// Always switch to the new tab
self.set_active_tab(Some(id));
log::info!(
"Created new tab {} with cwd (total: {})",
id,
self.tabs.len()
);
Ok(id)
}
/// Create a new tab from a profile configuration
///
/// The profile specifies the working directory, command, and tab name.
///
/// # Arguments
/// * `config` - Terminal configuration
/// * `runtime` - Tokio runtime for async operations
/// * `profile` - Profile configuration to use
/// * `grid_size` - Optional (cols, rows) override for initial terminal size
pub fn new_tab_from_profile(
&mut self,
config: &Config,
runtime: Arc<Runtime>,
profile: &Profile,
grid_size: Option<(usize, usize)>,
) -> Result<TabId> {
let id = self.next_tab_id;
self.next_tab_id += 1;
let tab = Tab::new_from_profile(id, config, runtime, profile, grid_size)?;
self.tabs.push(tab);
// Always switch to the new tab
self.set_active_tab(Some(id));
log::info!(
"Created new tab {} from profile '{}' (total: {})",
id,
profile.name,
self.tabs.len()
);
Ok(id)
}
/// Close a tab by ID
/// Returns true if this was the last tab (window should close)
pub fn close_tab(&mut self, id: TabId) -> bool {
let index = self.tabs.iter().position(|t| t.id == id);
if let Some(idx) = index {
log::info!("Closing tab {} (index {})", id, idx);
// Remove the tab
self.tabs.remove(idx);
// If we closed the active tab, switch to another
if self.active_tab_id == Some(id) {
let new_id = if self.tabs.is_empty() {
None
} else {
// Prefer the tab at the same index (or previous if at end)
let new_idx = idx.min(self.tabs.len().saturating_sub(1));
Some(self.tabs[new_idx].id)
};
self.set_active_tab(new_id);
}
// Renumber tabs that still have default titles
self.renumber_default_tabs();
}
self.tabs.is_empty()
}
/// Remove a tab by ID without dropping it, returning the live Tab.
///
/// Handles active tab switching and renumbering just like `close_tab`,
/// but returns the `Tab` so the caller can keep it alive.
///
/// Returns `Some((tab, is_empty))` if the tab was found, `None` otherwise.
pub fn remove_tab(&mut self, id: TabId) -> Option<(Tab, bool)> {
let idx = self.tabs.iter().position(|t| t.id == id)?;
log::info!("Removing tab {} (index {}) without dropping", id, idx);
let tab = self.tabs.remove(idx);
// If we removed the active tab, switch to another
if self.active_tab_id == Some(id) {
let new_id = if self.tabs.is_empty() {
None
} else {
let new_idx = idx.min(self.tabs.len().saturating_sub(1));
Some(self.tabs[new_idx].id)
};
self.set_active_tab(new_id);
}
self.renumber_default_tabs();
let is_empty = self.tabs.is_empty();
Some((tab, is_empty))
}
/// Insert a live Tab at a specific index and make it active.
///
/// The index is clamped to `0..=self.tabs.len()`.
///
/// Returns the id the tab holds afterwards, which is **not** always the id
/// it arrived with.
///
/// A tab arriving from another window ("Move Tab to Window") brings that
/// window's id with it, and ids are allocated per manager, so the incoming
/// id can already belong to a tab here — window A's tab 2 landing in a
/// window that already holds ids 1 and 2. `get_tab` is a linear scan, so a
/// duplicate would make every id-keyed lookup resolve to whichever tab sits
/// first: setting a badge, writing an approved automation action, or
/// closing "that" tab would hit an unrelated terminal. A colliding tab is
/// therefore renumbered from this manager's counter.
///
/// Advancing the counter past the id it ends up with keeps this window from
/// later handing the same id to a new tab, which is what makes a `TabId`
/// safe to hold across frames — a queued automation confirmation, an
/// "Always Allow" grant, a deferred script action — instead of silently
/// resolving to an unrelated terminal once the original tab is gone.
///
/// A caller that captured the id before the move must use the returned
/// value: the pre-move id may now name a different tab, or no tab at all.
#[must_use = "a renumbered tab is only reachable through the returned id"]
pub fn insert_tab_at(&mut self, mut tab: Tab, index: usize) -> TabId {
let clamped = index.min(self.tabs.len());
if self.tabs.iter().any(|t| t.id == tab.id) {
// `next_tab_id` is always past every id in `tabs`, so it is free.
let renumbered = self.next_tab_id;
log::info!(
"Inserted tab id {} is already taken in this window; renumbering it to {}",
tab.id,
renumbered
);
tab.id = renumbered;
}
let id = tab.id;
self.next_tab_id = self.next_tab_id.max(id.saturating_add(1));
self.tabs.insert(clamped, tab);
self.set_active_tab(Some(id));
self.renumber_default_tabs();
// Guard the mutation rather than `get_tab`: this is the only path by
// which a tab this manager did not allocate enters `tabs`, and the
// lookups run per frame and inside loops.
debug_assert_eq!(
self.tabs.iter().filter(|t| t.id == id).count(),
1,
"tab id {id} is not unique after insert"
);
log::info!(
"Inserted tab {} at index {} (total: {})",
id,
clamped,
self.tabs.len()
);
id
}
/// Renumber tabs that have default titles based on their current position
pub(super) fn renumber_default_tabs(&mut self) {
for (idx, tab) in self.tabs.iter_mut().enumerate() {
tab.set_default_title(idx + 1);
}
}
/// Get a reference to the active tab
pub fn active_tab(&self) -> Option<&Tab> {
self.active_tab_id
.and_then(|id| self.tabs.iter().find(|t| t.id == id))
}
/// Get a mutable reference to the active tab
pub fn active_tab_mut(&mut self) -> Option<&mut Tab> {
let active_id = self.active_tab_id;
active_id.and_then(move |id| self.tabs.iter_mut().find(|t| t.id == id))
}
/// Get the number of tabs
pub fn tab_count(&self) -> usize {
self.tabs.len()
}
/// Get the number of visible (non-hidden) tabs
pub fn visible_tab_count(&self) -> usize {
self.tabs.iter().filter(|t| !t.is_hidden).count()
}
/// Get all visible (non-hidden) tabs as a slice-like iterator
pub fn visible_tabs(&self) -> Vec<&Tab> {
self.tabs.iter().filter(|t| !t.is_hidden).collect()
}
/// Check if there are multiple tabs
pub fn has_multiple_tabs(&self) -> bool {
self.tabs.len() > 1
}
/// Get the active tab ID
pub fn active_tab_id(&self) -> Option<TabId> {
self.active_tab_id
}
/// Get all tabs as a slice
pub fn tabs(&self) -> &[Tab] {
&self.tabs
}
/// Get all tabs as mutable slice
pub fn tabs_mut(&mut self) -> &mut [Tab] {
&mut self.tabs
}
/// Drain all tabs from the manager, returning them without dropping
///
/// This is used during fast shutdown to extract tabs so their terminals
/// can be dropped on background threads in parallel.
pub fn drain_tabs(&mut self) -> Vec<Tab> {
self.set_active_tab(None);
std::mem::take(&mut self.tabs)
}
/// Get a tab by ID
pub fn get_tab(&self, id: TabId) -> Option<&Tab> {
self.tabs.iter().find(|t| t.id == id)
}
/// Get a mutable reference to a tab by ID
pub fn get_tab_mut(&mut self, id: TabId) -> Option<&mut Tab> {
self.tabs.iter_mut().find(|t| t.id == id)
}
/// Mark non-active tabs as having activity when they receive output
pub fn mark_activity(&mut self, tab_id: TabId) {
if Some(tab_id) != self.active_tab_id
&& let Some(tab) = self.get_tab_mut(tab_id)
{
tab.activity.has_activity = true;
}
}
/// Update titles for all tabs
pub fn update_all_titles(
&mut self,
title_mode: par_term_config::TabTitleMode,
remote_format: par_term_config::RemoteTabTitleFormat,
remote_osc_priority: bool,
) {
for tab in &mut self.tabs {
tab.update_title(title_mode, remote_format, remote_osc_priority);
}
}
/// Duplicate the active tab (creates new tab with same working directory and color)
///
/// # Arguments
/// * `config` - Terminal configuration
/// * `runtime` - Tokio runtime for async operations
/// * `grid_size` - Optional (cols, rows) override for initial terminal size
pub fn duplicate_active_tab(
&mut self,
config: &Config,
runtime: Arc<Runtime>,
grid_size: Option<(usize, usize)>,
) -> Result<Option<TabId>> {
if let Some(tab_id) = self.active_tab_id {
self.duplicate_tab_by_id(tab_id, config, runtime, grid_size)
} else {
Ok(None)
}
}
/// Duplicate a specific tab by ID (creates new tab with same working directory and color)
///
/// # Arguments
/// * `source_tab_id` - The ID of the tab to duplicate
/// * `config` - Terminal configuration
/// * `runtime` - Tokio runtime for async operations
/// * `grid_size` - Optional (cols, rows) override for initial terminal size
pub fn duplicate_tab_by_id(
&mut self,
source_tab_id: TabId,
config: &Config,
runtime: Arc<Runtime>,
grid_size: Option<(usize, usize)>,
) -> Result<Option<TabId>> {
// Gather properties from source tab
let source_idx = self.tabs.iter().position(|t| t.id == source_tab_id);
let source_idx = match source_idx {
Some(idx) => idx,
None => return Ok(None),
};
let working_dir = self.tabs[source_idx].get_cwd();
let custom_color = self.tabs[source_idx].custom_color;
let custom_icon = self.tabs[source_idx].custom_icon.clone();
let id = self.next_tab_id;
self.next_tab_id += 1;
// Tab number is based on current count, not unique ID
let tab_number = self.tabs.len() + 1;
let mut tab = Tab::new(id, tab_number, config, runtime, working_dir, grid_size)?;
// Copy tab color from source
if let Some(color) = custom_color {
tab.set_custom_color(color);
}
// Copy custom icon from source
tab.custom_icon = custom_icon;
// Insert after source tab
self.tabs.insert(source_idx + 1, tab);
self.set_active_tab(Some(id));
Ok(Some(id))
}
/// Create and insert a new tab wrapping an existing Pane.
///
/// The pane's PTY, scroll state, and session logger are preserved.
/// No new shell is spawned. Returns the new tab's ID.
pub fn new_tab_from_pane(
&mut self,
pane: crate::pane::Pane,
config: &Config,
runtime: Arc<Runtime>,
insert_after: Option<TabId>,
) -> TabId {
let id = self.next_tab_id;
self.next_tab_id += 1;
let tab_number = self.tabs.len() + 1;
let tab = crate::tab::Tab::new_from_pane(id, pane, config, runtime, tab_number);
let insert_idx = insert_after
.and_then(|after_id| self.tabs.iter().position(|t| t.id == after_id))
.map(|idx| idx + 1)
.unwrap_or(self.tabs.len());
self.tabs.insert(insert_idx, tab);
self.set_active_tab(Some(id));
self.renumber_default_tabs();
id
}
/// Append an already-built tab, for tests that need a populated manager
/// without spawning shells (pair with [`Tab::new_stub`]).
#[cfg(test)]
pub(crate) fn push_tab_for_test(&mut self, tab: Tab) {
self.next_tab_id = self.next_tab_id.max(tab.id + 1);
if self.active_tab_id.is_none() {
self.active_tab_id = Some(tab.id);
}
self.tabs.push(tab);
}
/// Get index of active tab (0-based)
pub fn active_tab_index(&self) -> Option<usize> {
self.active_tab_id
.and_then(|id| self.tabs.iter().position(|t| t.id == id))
}
/// Clean up closed/dead tabs
pub fn cleanup_dead_tabs(&mut self) {
let dead_tabs: Vec<TabId> = self
.tabs
.iter()
.filter(|t| !t.is_running())
.map(|t| t.id)
.collect();
for id in dead_tabs {
log::info!("Cleaning up dead tab {}", id);
self.close_tab(id);
}
}
}
impl Default for TabManager {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use tokio::runtime::Builder;
fn test_runtime() -> Arc<tokio::runtime::Runtime> {
Arc::new(
Builder::new_current_thread()
.enable_all()
.build()
.expect("build test runtime"),
)
}
/// Create a TabManager with mock tabs for testing (no PTY, no runtime)
fn manager_with_ids(ids: &[TabId]) -> TabManager {
let mut mgr = TabManager::new();
for &id in ids {
let tab_number = mgr.tabs.len() + 1;
// Create a minimal tab struct directly for testing
mgr.tabs.push(Tab::new_stub(id, tab_number));
mgr.next_tab_id = mgr.next_tab_id.max(id + 1);
}
if let Some(last) = ids.last() {
mgr.active_tab_id = Some(*last);
}
mgr
}
#[test]
fn move_tab_to_index_forward() {
let mut mgr = manager_with_ids(&[1, 2, 3, 4]);
// Move tab 1 from index 0 to index 2
assert!(mgr.move_tab_to_index(1, 2));
let ids: Vec<TabId> = mgr.tabs.iter().map(|t| t.id).collect();
assert_eq!(ids, vec![2, 3, 1, 4]);
}
#[test]
fn move_tab_to_index_backward() {
let mut mgr = manager_with_ids(&[1, 2, 3, 4]);
// Move tab 3 from index 2 to index 0
assert!(mgr.move_tab_to_index(3, 0));
let ids: Vec<TabId> = mgr.tabs.iter().map(|t| t.id).collect();
assert_eq!(ids, vec![3, 1, 2, 4]);
}
#[test]
fn move_tab_to_index_same_position() {
let mut mgr = manager_with_ids(&[1, 2, 3]);
// Moving to same position is a no-op
assert!(!mgr.move_tab_to_index(2, 1));
let ids: Vec<TabId> = mgr.tabs.iter().map(|t| t.id).collect();
assert_eq!(ids, vec![1, 2, 3]);
}
#[test]
fn move_tab_to_index_out_of_bounds_clamped() {
let mut mgr = manager_with_ids(&[1, 2, 3]);
// Target index 100 should clamp to last position (2)
assert!(mgr.move_tab_to_index(1, 100));
let ids: Vec<TabId> = mgr.tabs.iter().map(|t| t.id).collect();
assert_eq!(ids, vec![2, 3, 1]);
}
#[test]
fn move_tab_to_index_invalid_id() {
let mut mgr = manager_with_ids(&[1, 2, 3]);
// Non-existent tab ID returns false
assert!(!mgr.move_tab_to_index(99, 0));
let ids: Vec<TabId> = mgr.tabs.iter().map(|t| t.id).collect();
assert_eq!(ids, vec![1, 2, 3]);
}
#[test]
fn move_tab_to_index_to_end() {
let mut mgr = manager_with_ids(&[1, 2, 3]);
// Move first tab to last position
assert!(mgr.move_tab_to_index(1, 2));
let ids: Vec<TabId> = mgr.tabs.iter().map(|t| t.id).collect();
assert_eq!(ids, vec![2, 3, 1]);
}
#[test]
fn move_tab_to_index_to_start() {
let mut mgr = manager_with_ids(&[1, 2, 3]);
// Move last tab to first position
assert!(mgr.move_tab_to_index(3, 0));
let ids: Vec<TabId> = mgr.tabs.iter().map(|t| t.id).collect();
assert_eq!(ids, vec![3, 1, 2]);
}
#[test]
#[ignore = "requires PTY spawn"]
fn remove_insert_round_trip_preserves_tab_fields() {
let mut mgr = TabManager::new();
let config = Config::default();
let runtime = test_runtime();
// Create two tabs so removing one leaves the manager non-empty.
let _ = mgr
.new_tab(&config, Arc::clone(&runtime), false, Some((80, 24)))
.expect("create tab 1");
let id = mgr
.new_tab(&config, Arc::clone(&runtime), false, Some((80, 24)))
.expect("create tab 2");
// Customize the target tab so we can assert round-trip fidelity.
{
let tab = mgr.get_tab_mut(id).expect("target tab exists");
tab.set_title("my-tab");
tab.user_named = true;
tab.set_custom_color([10, 20, 30]);
tab.custom_icon = Some("\u{f120}".to_string());
}
// Snapshot preserved fields.
let snapshot = {
let tab = mgr.get_tab(id).expect("target tab exists");
(
tab.id,
tab.title.clone(),
tab.has_default_title,
tab.user_named,
tab.custom_color,
tab.custom_icon.clone(),
)
};
// Round-trip: remove then re-insert at index 1.
let (live_tab, is_empty) = mgr.remove_tab(id).expect("remove returns Some");
assert!(!is_empty, "manager should still have tab 1");
let reinserted = mgr.insert_tab_at(live_tab, 1);
assert_eq!(
reinserted, id,
"a tab returning to the manager it left cannot collide, so it keeps its id"
);
let after = mgr
.get_tab(reinserted)
.expect("tab still present after round-trip");
assert_eq!(after.id, snapshot.0, "id mismatch");
assert_eq!(after.title, snapshot.1, "title mismatch");
assert_eq!(
after.has_default_title, snapshot.2,
"has_default_title mismatch"
);
assert_eq!(after.user_named, snapshot.3, "user_named mismatch");
assert_eq!(after.custom_color, snapshot.4, "custom_color mismatch");
assert_eq!(after.custom_icon, snapshot.5, "custom_icon mismatch");
}
#[test]
fn an_inserted_tab_id_is_never_handed_out_again() {
// A tab moved in from another window brings that window's id. Without
// advancing the counter, this manager would later allocate the same id
// for an unrelated tab, and anything holding the old id across frames —
// a queued automation confirmation, an "Always Allow" grant — would
// resolve to the wrong terminal.
let mut mgr = manager_with_ids(&[1, 2]);
let foreign = Tab::new_stub(9, 1);
let inserted = mgr.insert_tab_at(foreign, 1);
assert_eq!(inserted, 9, "an id that is free must be kept as-is");
let fresh = mgr.next_tab_id;
assert!(
fresh > 9,
"next id {} must not collide with the inserted id 9",
fresh
);
assert!(
mgr.tabs().iter().all(|tab| tab.id != fresh),
"the next id must be free"
);
}
#[test]
fn a_moved_in_tab_does_not_shadow_a_tab_that_already_holds_its_id() {
// Window A holds {1,2,3}, window B holds {1,2}; the user moves A's tab
// 2 into B. Ids are allocated per window, so B is handed a second tab
// claiming id 2. `get_tab` is a linear scan, so without renumbering
// every lookup of id 2 would resolve to B's *original* tab and the
// moved tab would be unreachable — a badge, or an approved automation
// write, would land in the wrong terminal.
const ORIGINAL: [u8; 3] = [10, 20, 30];
const MOVED: [u8; 3] = [40, 50, 60];
let mut window_b = manager_with_ids(&[1, 2]);
window_b
.get_tab_mut(2)
.expect("window B's own tab 2")
.set_custom_color(ORIGINAL);
// The tab arriving from window A, carrying window A's id.
let mut moved = Tab::new_stub(2, 1);
moved.set_custom_color(MOVED);
let moved_id = window_b.insert_tab_at(moved, 2);
assert_eq!(window_b.tab_count(), 3, "both tabs must survive the move");
// The lookups are the point: id distinctness below is only the means.
assert_eq!(
window_b
.get_tab(moved_id)
.expect("the moved tab is reachable by its returned id")
.custom_color,
Some(MOVED),
"get_tab(returned id) must resolve to the tab that moved in, \
not to the tab that was already holding that id"
);
assert_eq!(
window_b
.get_tab(2)
.expect("window B's original tab 2 is still reachable")
.custom_color,
Some(ORIGINAL),
"the tab that already held id 2 must keep it"
);
assert_ne!(moved_id, 2, "a colliding id must not be kept");
}
}