winx-code-agent 0.2.348

Remote-first Rust MCP runtime with Streamable HTTP, durable PTYs, and guarded agent tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
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
//! `BashCommand` facade and action dispatcher.
//!
//! Execution, output/status rendering, interactive input, and TUI driving live
//! in focused submodules under `tools/bash_command/`.

mod execution;
mod interaction;
mod output;
mod tui;

use std::path::PathBuf;
use std::sync::Arc;

use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;
use tracing::{debug, error, info};

pub use super::background_shell::{BackgroundShellManager, ExitedShellInfo};
use crate::errors::{Result, WinxError};
use crate::runtime::{
    lock_session_store, BashCommandRuntimeResult, EmbeddedShellRuntime, ShellActionOptions,
    ShellExecutionToken, ShellRuntime, ShellTarget,
};
use crate::state::bash_state::BashState;
use crate::state::live_terminal::ScreenUpdate;
use crate::state::pty::PtyShell;
use crate::types::{normalize_thread_id, BashCommand, BashCommandAction};

use execution::{execute_command, CommandExecutionContext};
use interaction::{execute_send_ascii, execute_send_specials, execute_send_text};
use output::{execute_status_check, finalize_tombstone};
use tui::{execute_screen, execute_wait_for_turn};

type SharedPtyShell = Arc<Mutex<Option<PtyShell>>>;

/// Authoritative process state produced by the shell runtime. It is transported
/// separately from human-readable terminal output, so command text cannot spoof
/// orchestration state by printing Winx-looking markers.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BashProcessStatus {
    Running,
    Exited,
}

/// Machine-readable state of one `BashCommand` action.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct BashCommandState {
    pub process_status: BashProcessStatus,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub background_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub running_for_seconds: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i32>,
    pub cwd: PathBuf,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub turn_state: Option<crate::state::turn::TurnState>,
}

impl BashCommandState {
    pub const fn is_running(&self) -> bool {
        matches!(self.process_status, BashProcessStatus::Running)
    }
}

/// Human-readable output plus runtime-owned state. Only `state` drives MCP
/// orchestration; `output` is presentation and may contain arbitrary child text.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct BashCommandResult {
    pub output: String,
    pub state: BashCommandState,
}

pub(crate) fn runtime_rendered(
    mut body: String,
    legacy_status: &str,
    state: BashCommandState,
    compact_requested: bool,
    command_generation: Option<u64>,
    output_truncated: bool,
) -> BashCommandRuntimeResult {
    let compact_output = if compact_requested {
        Some(std::mem::take(&mut body))
    } else {
        body.push_str(legacy_status);
        None
    };
    BashCommandRuntimeResult {
        result: BashCommandResult { output: body, state },
        compact_output,
        command_generation,
        execution_token: None,
        generation_bound_actions: true,
        dropped_output_file: None,
        output_truncated,
    }
}

/// Per-adapter delivery state used by daemon guardians. Embedded callers keep
/// using the cursor stored directly on `PtyShell`, preserving legacy behavior.
#[derive(Debug, Default)]
pub(crate) struct ShellDeliveryCursor {
    generation: Option<u64>,
    delivered_output: String,
    last_returned_hash: Option<u64>,
    screen_snapshot: Option<Vec<String>>,
}

impl ShellDeliveryCursor {
    fn sync_generation(&mut self, generation: u64) {
        if self.generation != Some(generation) {
            self.generation = Some(generation);
            self.delivered_output.clear();
            self.last_returned_hash = None;
            self.screen_snapshot = None;
        }
    }

    fn screen_update(&mut self, current: Vec<String>, threshold: usize) -> ScreenUpdate {
        let update = match self.screen_snapshot.as_ref() {
            Some(previous) => {
                let rows = previous.len().max(current.len());
                let changed = (0..rows)
                    .filter_map(|index| {
                        let before = previous.get(index).map_or("", String::as_str);
                        let after = current.get(index).map_or("", String::as_str);
                        (before != after).then(|| (index + 1, after.to_string()))
                    })
                    .collect::<Vec<_>>();
                if changed.is_empty() {
                    ScreenUpdate::Unchanged
                } else if changed.len() <= threshold {
                    ScreenUpdate::Diff(changed)
                } else {
                    ScreenUpdate::Full(current.clone())
                }
            }
            None => ScreenUpdate::Full(current.clone()),
        };
        self.screen_snapshot = Some(current);
        update
    }
}

fn main_shell(bash_state: &BashState) -> SharedPtyShell {
    let mut store = lock_session_store();
    store.bind_main(&bash_state.current_thread_id, &bash_state.pty_shell);
    store
        .resolve(&bash_state.current_thread_id, &ShellTarget::Main)
        .unwrap_or_else(|| bash_state.pty_shell.clone())
}

// Default block window when the client omits `wait_for_seconds`. Usage logs
// showed remote clients omit it and then burn one full LLM round-trip per 5 s
// re-check on long commands (runs of up to 18 consecutive polls); a larger
// window resolves most commands in a single call while staying far below the
// 120 s HTTP request timeout.
const DEFAULT_TIMEOUT: f64 = 15.0;
fn effective_wait_for_seconds(wait_for_seconds: Option<f32>) -> f64 {
    wait_for_seconds.map_or(DEFAULT_TIMEOUT, |seconds| f64::from(seconds).max(0.0))
}

/// Guardian foreground preflight. The caller owns the session operation
/// writer, so this never races token validation and runs before delivery cursor
/// or foreground-command gates are acquired.
pub(crate) async fn guardian_foreground_shell_needs_reset(
    bash_state: &mut BashState,
    options: &ShellActionOptions,
) -> anyhow::Result<bool> {
    let shell = main_shell(bash_state);
    let (missing, running) = {
        let guard = shell.lock().await;
        (guard.is_none(), guard.as_ref().is_some_and(|shell| shell.command_running))
    };
    if running {
        return Ok(false);
    }
    if missing {
        bash_state.init_pty_shell().await?;
        return Ok(false);
    }
    let cleared = output::clear_to_run_async(&shell, DEFAULT_TIMEOUT).await;
    #[cfg(test)]
    let cleared = cleared && !options.force_clear_to_run_failure;
    #[cfg(not(test))]
    let _ = options;
    Ok(!cleared)
}

fn send_utf8_in_byte_chunks(shell: &mut PtyShell, text: &str, chunk_size: usize) -> Result<()> {
    let mut start = 0;
    while start < text.len() {
        let mut end = (start + chunk_size).min(text.len());
        while !text.is_char_boundary(end) {
            end -= 1;
        }
        if end == start {
            end =
                text[start..].char_indices().nth(1).map_or(text.len(), |(index, _)| start + index);
        }
        shell.send_text(&text[start..end]).map_err(|error| {
            WinxError::CommandExecutionError(format!("Failed to write PTY input: {error}"))
        })?;
        start = end;
    }
    Ok(())
}

/// Handle a `BashCommand` using the embedded runtime.
pub async fn handle_tool_call(
    bash_state: &Arc<Mutex<Option<BashState>>>,
    command: BashCommand,
) -> Result<String> {
    handle_tool_call_with_runtime(&EmbeddedShellRuntime, bash_state, command).await
}

/// Backwards-compatible text-only API used by direct library callers.
pub async fn handle_tool_call_with_runtime(
    runtime: &dyn ShellRuntime,
    bash_state: &Arc<Mutex<Option<BashState>>>,
    command: BashCommand,
) -> Result<String> {
    Ok(handle_tool_call_with_runtime_detailed(runtime, bash_state, command).await?.output)
}

/// Execute a `BashCommand` while preserving the runtime-owned typed state.
pub async fn handle_tool_call_with_runtime_detailed(
    runtime: &dyn ShellRuntime,
    bash_state: &Arc<Mutex<Option<BashState>>>,
    command: BashCommand,
) -> Result<BashCommandResult> {
    runtime.run_action(bash_state, command).await
}

pub(crate) async fn handle_embedded_tool_call(
    bash_state: &Arc<Mutex<Option<BashState>>>,
    command: BashCommand,
) -> Result<BashCommandResult> {
    Ok(handle_embedded_tool_call_inner(
        bash_state,
        command,
        None,
        ShellActionOptions::default(),
        false,
    )
    .await?
    .result)
}

pub(crate) async fn handle_embedded_tool_call_detailed(
    bash_state: &Arc<Mutex<Option<BashState>>>,
    command: BashCommand,
    options: ShellActionOptions,
) -> Result<BashCommandRuntimeResult> {
    handle_embedded_tool_call_inner(bash_state, command, None, options, false).await
}

pub(crate) async fn handle_embedded_tool_call_with_cursor_detailed(
    bash_state: &Arc<Mutex<Option<BashState>>>,
    command: BashCommand,
    delivery_cursor: &Arc<Mutex<ShellDeliveryCursor>>,
    options: ShellActionOptions,
    foreground_preflight_complete: bool,
) -> Result<BashCommandRuntimeResult> {
    let mut delivery_cursor = delivery_cursor.lock().await;
    handle_embedded_tool_call_inner(
        bash_state,
        command,
        Some(&mut delivery_cursor),
        options,
        foreground_preflight_complete,
    )
    .await
}

async fn capture_embedded_state(
    bash_state: &Arc<Mutex<Option<BashState>>>,
    thread_id: &str,
) -> Result<(BashState, tokio::sync::OwnedRwLockReadGuard<()>)> {
    let guard = bash_state.lock().await;
    let state = guard.as_ref().ok_or(WinxError::BashStateNotInitialized)?;
    let operation_barrier = lock_session_store().operation_barrier(thread_id);
    let operation_guard = operation_barrier.read_owned().await;
    Ok((state.clone(), operation_guard))
}

#[tracing::instrument(level = "info", skip(bash_state, command, delivery_cursor))]
async fn handle_embedded_tool_call_inner(
    bash_state: &Arc<Mutex<Option<BashState>>>,
    command: BashCommand,
    delivery_cursor: Option<&mut ShellDeliveryCursor>,
    options: ShellActionOptions,
    foreground_preflight_complete: bool,
) -> Result<BashCommandRuntimeResult> {
    let action_kind = match &command.action_json {
        BashCommandAction::Command { .. } => "command",
        BashCommandAction::StatusCheck { .. } => "status_check",
        BashCommandAction::SendText { .. } => "send_text",
        BashCommandAction::SendSpecials { .. } => "send_specials",
        BashCommandAction::SendAscii { .. } => "send_ascii",
        BashCommandAction::Screen { .. } => "screen",
        BashCommandAction::WaitForTurn { .. } => "wait_for_turn",
    };
    info!(thread_id = %command.thread_id, action = action_kind, "BashCommand tool called");

    let thread_id = normalize_thread_id(&command.thread_id);
    if thread_id.is_empty() {
        error!("Empty thread_id provided in BashCommand");
        return Err(WinxError::ThreadIdMismatch(
            "Error: No saved bash state found for thread ID \"\". Please initialize first with this ID."
                .to_string(),
        ));
    }

    let mut local_state = {
        let guard = bash_state.lock().await;
        let Some(state) = &*guard else {
            error!("BashState not initialized");
            return Err(WinxError::BashStateNotInitialized);
        };
        state.clone()
    };

    if thread_id != local_state.current_thread_id {
        let loaded = local_state.load_state_from_disk(&thread_id).map_err(|error| {
            WinxError::CommandExecutionError(format!(
                "Failed to load saved bash state for thread_id `{thread_id}`: {error}"
            ))
        })?;
        if !loaded {
            return Err(WinxError::ThreadIdMismatch(format!(
                "Error: No saved bash state found for thread_id `{thread_id}`. Please initialize first with this ID."
            )));
        }
        if let Some(state) = bash_state.lock().await.as_mut() {
            *state = local_state.clone();
        }
    }

    // BashState -> session barrier is the same order used by
    // configure_session. Keep BashState locked until the owned read guard is
    // acquired so reset cannot replace the incarnation after capture but
    // before token validation/action execution.
    let (captured_state, operation_guard) = capture_embedded_state(bash_state, &thread_id).await?;
    local_state = captured_state;

    if let Some(expected) = options.expected_execution.as_ref() {
        if expected.guardian_epoch == "embedded" {
            let current_epoch = local_state
                .pty_shell
                .lock()
                .await
                .as_ref()
                .map(|shell| format!("{:016x}", shell.incarnation()));
            if Some(expected.session_epoch.as_str()) != current_epoch.as_deref() {
                return Err(WinxError::InvalidInput(
                    "execution token belongs to a previous embedded shell incarnation".to_string(),
                ));
            }
        }
    }

    lock_session_store().bind_main(&local_state.current_thread_id, &local_state.pty_shell);
    let timeout_secs = effective_wait_for_seconds(command.wait_for_seconds);
    let mut result = execute_bash_action(
        &mut local_state,
        &command.action_json,
        timeout_secs,
        delivery_cursor,
        options,
        foreground_preflight_complete,
    )
    .await;

    let completed_session_epoch = local_state.pty_shell.lock().await.as_ref().map_or_else(
        || "uninitialized".to_string(),
        |shell| format!("{:016x}", shell.incarnation()),
    );
    if let Ok(outcome) = &mut result {
        if let Some(generation) = outcome.command_generation {
            outcome.execution_token = Some(ShellExecutionToken {
                guardian_epoch: "embedded".to_string(),
                session_epoch: completed_session_epoch.clone(),
                generation,
            });
        }
        if let BashCommandAction::Command { ref command, .. } = command.action_json {
            let command = command.trim();
            if outcome.result.output.starts_with(command) {
                outcome.result.output = outcome.result.output[command.len()..].to_string();
            }
            if outcome.compact_output.as_ref().is_some_and(|output| output.starts_with(command)) {
                let output = outcome.compact_output.take().unwrap_or_default();
                outcome.compact_output = Some(output[command.len()..].to_string());
            }
        }
    }

    drop(operation_guard);
    sync_embedded_cwd_if_current(bash_state, &local_state, &completed_session_epoch).await;

    result
}

async fn sync_embedded_cwd_if_current(
    bash_state: &Arc<Mutex<Option<BashState>>>,
    local_state: &BashState,
    completed_session_epoch: &str,
) {
    // configure_session callers own BashState before taking the operation
    // barrier. Acquire BashState only after releasing the read side above and
    // never let a completed old incarnation overwrite reset's cwd.
    if let Some(state) = bash_state.lock().await.as_mut() {
        let current_session_epoch = state.pty_shell.lock().await.as_ref().map_or_else(
            || "uninitialized".to_string(),
            |shell| format!("{:016x}", shell.incarnation()),
        );
        if current_session_epoch == completed_session_epoch {
            state.cwd.clone_from(&local_state.cwd);
        }
    }
}

/// Keep the durable agent-session record in lockstep with what the foreground
/// PTY runs: a command that launches a known interactive agent overwrites the
/// record; anything else clears it (the main PTY runs one foreground program
/// at a time). The record is what lets a restart that lost the PTY surface a
/// resume hint (`claude --continue`, ...) instead of losing the conversation
/// silently. Best-effort — persistence failures never fail the command.
fn record_foreground_agent_launch(bash_state: &BashState, command: &str) {
    use crate::state::agent_resume;
    let thread_id = &bash_state.current_thread_id;
    match agent_resume::detect_agent_launch(command) {
        Some(agent) => {
            let record = agent_resume::AgentSessionRecord {
                agent: agent.to_string(),
                command: command.to_string(),
                cwd: bash_state.cwd.to_string_lossy().into_owned(),
                launched_at_unix_ms: agent_resume::now_unix_ms(),
            };
            if let Err(error) = agent_resume::save_agent_session(thread_id, &record) {
                debug!(%error, agent, "failed to persist agent-session record");
            }
        }
        None => {
            if let Err(error) = agent_resume::clear_agent_session(thread_id) {
                debug!(%error, "failed to clear agent-session record");
            }
        }
    }
}

#[allow(clippy::too_many_lines)]
async fn execute_bash_action(
    bash_state: &mut BashState,
    action: &BashCommandAction,
    timeout_secs: f64,
    delivery_cursor: Option<&mut ShellDeliveryCursor>,
    options: ShellActionOptions,
    foreground_preflight_complete: bool,
) -> Result<BashCommandRuntimeResult> {
    let mut is_background = false;
    let mut background_id: Option<String> = None;

    let background_shell = match action {
        BashCommandAction::Command { .. } => None,
        BashCommandAction::StatusCheck { bg_command_id, .. }
        | BashCommandAction::SendText { bg_command_id, .. }
        | BashCommandAction::SendSpecials { bg_command_id, .. }
        | BashCommandAction::SendAscii { bg_command_id, .. }
        | BashCommandAction::Screen { bg_command_id, .. }
        | BashCommandAction::WaitForTurn { bg_command_id, .. } => {
            if let Some(id) = bg_command_id {
                let mut manager = lock_session_store();
                manager.prune_finished_shells();
                if let Some(shell) = manager.get_shell(&bash_state.current_thread_id, id) {
                    is_background = true;
                    background_id = Some(id.clone());
                    Some(shell)
                } else if let Some(tombstone) =
                    manager.peek_tombstone(&bash_state.current_thread_id, id)
                {
                    drop(manager);
                    return finalize_tombstone(
                        bash_state,
                        id,
                        tombstone,
                        action,
                        options.compact_output,
                    );
                } else {
                    let error = format!(
                        "No shell found running with command id {}.\n{}",
                        id,
                        manager.get_running_info(&bash_state.current_thread_id)
                    );
                    return Err(WinxError::InvalidInput(error));
                }
            } else {
                None
            }
        }
    };

    match action {
        BashCommandAction::Command { command, is_background, allow_multi } => {
            let result = execute_command(
                bash_state,
                command,
                *is_background,
                *allow_multi,
                timeout_secs,
                delivery_cursor,
                CommandExecutionContext { options: &options, foreground_preflight_complete },
            )
            .await;
            if result.is_ok() && !*is_background {
                record_foreground_agent_launch(bash_state, command);
            }
            result
        }
        BashCommandAction::StatusCheck { scrollback_lines, verbose, .. } => {
            execute_status_check(
                bash_state,
                background_shell,
                is_background,
                background_id.as_deref(),
                timeout_secs,
                *scrollback_lines,
                *verbose,
                delivery_cursor,
                options,
            )
            .await
        }
        BashCommandAction::SendText { send_text, submit, .. } => {
            execute_send_text(
                bash_state,
                send_text,
                *submit,
                background_shell,
                is_background,
                background_id.as_deref(),
                timeout_secs,
                delivery_cursor,
                options.compact_output,
            )
            .await
        }
        BashCommandAction::SendSpecials { send_specials, submit, .. } => {
            execute_send_specials(
                bash_state,
                send_specials,
                *submit,
                background_shell,
                is_background,
                background_id.as_deref(),
                timeout_secs,
                delivery_cursor,
                options.compact_output,
            )
            .await
        }
        BashCommandAction::SendAscii { send_ascii, submit, .. } => {
            execute_send_ascii(
                bash_state,
                send_ascii,
                *submit,
                background_shell,
                is_background,
                background_id.as_deref(),
                timeout_secs,
                delivery_cursor,
                options.compact_output,
            )
            .await
        }
        BashCommandAction::Screen { lines, diff, .. } => {
            execute_screen(
                bash_state,
                background_shell,
                is_background,
                background_id.as_deref(),
                *lines,
                *diff,
                delivery_cursor,
                options.compact_output,
            )
            .await
        }
        BashCommandAction::WaitForTurn {
            recognizer,
            quiet_ms,
            timeout_seconds,
            lines,
            wait_through_busy,
            ..
        } => {
            execute_wait_for_turn(
                bash_state,
                background_shell,
                is_background,
                background_id.as_deref(),
                recognizer.as_deref(),
                *quiet_ms,
                *timeout_seconds,
                *lines,
                *wait_through_busy,
                options.compact_output,
            )
            .await
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        effective_wait_for_seconds, runtime_rendered, BashCommandState, BashProcessStatus,
    };

    fn exited_state() -> BashCommandState {
        BashCommandState {
            process_status: BashProcessStatus::Exited,
            background_id: None,
            running_for_seconds: None,
            exit_code: Some(0),
            cwd: "/workspace".into(),
            turn_state: None,
        }
    }

    #[test]
    fn legacy_rendering_does_not_build_a_compact_payload_without_negotiation() {
        let result = runtime_rendered(
            "child output".to_string(),
            "\nstatus = process exited",
            exited_state(),
            false,
            Some(1),
            false,
        );
        assert_eq!(result.result.output, "child output\nstatus = process exited");
        assert_eq!(result.compact_output, None);
    }

    #[test]
    fn compact_rendering_is_built_directly_from_runtime_body() {
        let result = runtime_rendered(
            "child output".to_string(),
            "\nstatus = process exited",
            exited_state(),
            true,
            Some(1),
            false,
        );
        assert_eq!(result.compact_output.as_deref(), Some("child output"));
        assert!(result.result.output.is_empty());
    }

    #[test]
    fn requested_wait_is_not_silently_capped() {
        assert!((effective_wait_for_seconds(Some(120.0)) - 120.0).abs() < f64::EPSILON);
        assert!((effective_wait_for_seconds(Some(150.0)) - 150.0).abs() < f64::EPSILON);
    }

    #[test]
    fn omitted_wait_uses_the_larger_default_window() {
        assert!((effective_wait_for_seconds(None) - 15.0).abs() < f64::EPSILON);
    }
}