A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix clipboard copy in terminal and tmux (#3318)
kt33315ed7c83c
diff --git a/README.md b/README.mdindex bce05fd9cd..339ae6dcd3 100644--- a/README.md+++ b/README.md@@ -64,6 +64,12 @@ Prime Agent combines a persistent Python control environment with durable harnes- **Agents communicate directly:** running agents can exchange messages and orchestrate one another without routing everything through the user.- **Long tasks keep moving:** automatic compaction, persistent goals, heartbeats, schedules, autonomous mode, and retained subagents preserve progress across turns and terminal sessions.+## Clipboard over SSH and tmux++Prime Agent uses the local clipboard tool (such as `pbcopy`) when available. In tmux it asks the attached tmux client to forward a clipboard buffer if that client advertises the `Ms` capability. This works with tmux's default `set-clipboard external`, unlike application-origin OSC 52. Without tmux, remote copies request delivery using OSC 52. Terminal requests cannot confirm that your local clipboard changed, so Prime Agent reports them as unconfirmed.++Nested tmux servers and terminals may still block delivery. An outer tmux with `set-clipboard external` can reject the inner server's OSC 52. In that case, run `tmux set -s set-clipboard on` on the outer server, or use native terminal selection (Shift-drag in most terminals; Option-drag in iTerm2) followed by Cmd-C. macOS Terminal.app does not support OSC 52; iTerm2 requires its “Applications in terminal may access clipboard” setting.+## Getting StartedStart Prime Agent from the repository or directory you want it to work in:diff --git a/crates/pa-cli/tests/clipboard_auth_commands_e2e.rs b/crates/pa-cli/tests/clipboard_auth_commands_e2e.rsindex 2bd0df7ac5..9d15c1f6f3 100644--- a/crates/pa-cli/tests/clipboard_auth_commands_e2e.rs+++ b/crates/pa-cli/tests/clipboard_auth_commands_e2e.rs@@ -711,7 +711,7 @@ async fn tui_copy_emits_the_ts_osc52_sequence() {"the empty-transcript error renders:\n{rendered}");assert!(- rendered.contains("Copied last agent message to clipboard"),+ rendered.contains("Clipboard request sent; paste in the local terminal to verify delivery"),"the copy status renders:\n{rendered}");assert!(@@ -787,13 +787,16 @@ async fn tui_copy_toast_coalesces_consecutive_copies_and_auto_dismisses() {// The coalesced count-bump toast renders (observed, not// slept-for): the third copy's ack is the (x3) label.pa_tui::interactive::HeadlessStep::WaitRender {- needle: "Copied last agent message to clipboard (x3)".to_string(),+ needle:+ "Clipboard request sent; paste in the local terminal to verify delivery (x3)"+ .to_string(),timeout_ms: 10_000,},// Past the toast's TTL: the overlay dismisses (the newest// frame stops carrying the ack).pa_tui::interactive::HeadlessStep::WaitGone {- needle: "Copied last agent message to clipboard".to_string(),+ needle: "Clipboard request sent; paste in the local terminal to verify delivery"+ .to_string(),timeout_ms: 10_000,},],@@ -815,7 +818,7 @@ async fn tui_copy_toast_coalesces_consecutive_copies_and_auto_dismisses() {);}}- let label = "Copied last agent message to clipboard";+ let label = "Clipboard request sent; paste in the local terminal to verify delivery";// Every copy registered: the headless OSC 52 sink is one buffer for// the whole run, so the exact TS sequence appears three times// concatenated - one emission per copy.diff --git a/crates/pa-cli/tests/interactive_daemon_e2e.rs b/crates/pa-cli/tests/interactive_daemon_e2e.rsindex 93aeac9e4c..f2db37a8dd 100644--- a/crates/pa-cli/tests/interactive_daemon_e2e.rs+++ b/crates/pa-cli/tests/interactive_daemon_e2e.rs@@ -1569,20 +1569,51 @@ async fn tui_dispatches_slash_commands_menu_and_suggestions() {pa_tui::interactive::HeadlessStep::WaitIdle { timeout_ms: 30_000 },// Unknown command: the exact TS suggestion error.pa_tui::interactive::HeadlessStep::Submit("/modle".to_string()),- // The autocomplete menu: typed input like a user keystroke by- // keystroke, completed with Enter, then submitted.+ // Probe pass over the autocomplete menu (typed keystroke by+ // keystroke, completed with Enter). The attach-time+ // slash-command catalog refresh is still in flight here: its+ // background `get_commands` response swaps the provider and+ // closes an open dropdown when it lands (TS+ // `setAutocompleteProvider` parity), so this pass may lose its+ // menu to the swap. Two cases keep the asserted passes below+ // behind the landing: with the menu still open, the+ // `skill:goal` row renders in a post-landing frame and the+ // barrier pops at the landing; a landing that closes the menu+ // without re-parking never renders the needle, and the 15s+ // bound — past the 10s fetch deadline — is what waits out+ // that case.pa_tui::interactive::HeadlessStep::Type("/".to_string()),- // A real user pauses between keystrokes: the parked suggestion- // request materializes (the dropdown opens) before Enter, the- // state the terminal loop reaches after one input-idle tick.pa_tui::interactive::HeadlessStep::SettleIdle,pa_tui::interactive::HeadlessStep::Type("goa".to_string()),pa_tui::interactive::HeadlessStep::SettleIdle,+ pa_tui::interactive::HeadlessStep::WaitRender {+ needle: "skill:goal".to_string(),+ timeout_ms: 15_000,+ },// With the dropdown open, Enter completes the selected// suggestion (`/goal `); the second Enter submits it.pa_tui::interactive::HeadlessStep::Type("\n".to_string()),pa_tui::interactive::HeadlessStep::Type("\n".to_string()),pa_tui::interactive::HeadlessStep::WaitIdle { timeout_ms: 30_000 },+ // The menu assertions run against the landed catalog: the first+ // registry entry selected at `/`, `/goa` fuzzy-matching goal —+ // no in-flight swap can close these dropdowns between+ // materialize and render.+ pa_tui::interactive::HeadlessStep::Type("/".to_string()),+ pa_tui::interactive::HeadlessStep::SettleIdle,+ pa_tui::interactive::HeadlessStep::WaitRender {+ needle: "\u{203a} settings".to_string(),+ timeout_ms: 30_000,+ },+ pa_tui::interactive::HeadlessStep::Type("goa".to_string()),+ pa_tui::interactive::HeadlessStep::SettleIdle,+ pa_tui::interactive::HeadlessStep::WaitRender {+ needle: "\u{203a} goal".to_string(),+ timeout_ms: 30_000,+ },+ pa_tui::interactive::HeadlessStep::Type("\n".to_string()),+ pa_tui::interactive::HeadlessStep::Type("\n".to_string()),+ pa_tui::interactive::HeadlessStep::WaitIdle { timeout_ms: 30_000 },// `/model` LAST: the inline menu-panel opens and owns the keys// from here on (TS `showConfigurationMenu`).pa_tui::interactive::HeadlessStep::Submit("/model".to_string()),diff --git a/crates/pa-tui/src/auth_panel.rs b/crates/pa-tui/src/auth_panel.rsindex 2f4594faea..29fee5963b 100644--- a/crates/pa-tui/src/auth_panel.rs+++ b/crates/pa-tui/src/auth_panel.rs@@ -468,6 +468,7 @@ const BROWSER_DEFAULT_INSTRUCTIONS: &str = "Complete the sign-in in your browser#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub(crate) enum CopyStatus {Copied,+ Requested,Failed,}@@ -823,7 +824,8 @@ impl AuthPanel {};let url = scrub_controls(&url).replace('\n', "");self.copy_status = match crate::clipboard::copy_to_clipboard(&url, sink) {- Ok(()) => Some(CopyStatus::Copied),+ Ok(crate::clipboard::CopyOutcome::Confirmed) => Some(CopyStatus::Copied),+ Ok(crate::clipboard::CopyOutcome::Requested) => Some(CopyStatus::Requested),Err(_) => Some(CopyStatus::Failed),};}diff --git a/crates/pa-tui/src/auth_panel/render.rs b/crates/pa-tui/src/auth_panel/render.rsindex 1cd15de8e2..fc8ac8a5b8 100644--- a/crates/pa-tui/src/auth_panel/render.rs+++ b/crates/pa-tui/src/auth_panel/render.rs@@ -303,10 +303,12 @@ pub(crate) fn auth_actions_row(if let Some(state) = copy_state {let tone = match state {CopyStatus::Copied => ThemeColor::Success,+ CopyStatus::Requested => ThemeColor::Warning,CopyStatus::Failed => ThemeColor::Error,};let text = match state {CopyStatus::Copied => "Copied sign-in link",+ CopyStatus::Requested => "Sign-in link sent to terminal clipboard (unconfirmed)",CopyStatus::Failed => "Failed to copy sign-in link",};parts.push(vec![theme.fg_span(tone, text.to_string())]);diff --git a/crates/pa-tui/src/auth_panel/tests.rs b/crates/pa-tui/src/auth_panel/tests.rsindex 2335031008..19197f75e9 100644--- a/crates/pa-tui/src/auth_panel/tests.rs+++ b/crates/pa-tui/src/auth_panel/tests.rs@@ -765,6 +765,7 @@ fn the_copy_binding_copies_the_mounted_url_into_the_actions_row() {let rows = frame_text(&mut panel);assert!(rows.iter().any(|row| row.contains("Copied sign-in link")+ || row.contains("Sign-in link sent to terminal clipboard (unconfirmed)")|| row.contains("Failed to copy sign-in link")),"the copy outcome rides the actions row: {rows:?}");diff --git a/crates/pa-tui/src/clipboard.rs b/crates/pa-tui/src/clipboard.rsindex e3ee6cf0a2..ba4ed628c4 100644--- a/crates/pa-tui/src/clipboard.rs+++ b/crates/pa-tui/src/clipboard.rs@@ -1,11 +1,8 @@-//! Terminal clipboard writes (TS `utils/clipboard.ts` `copyToClipboard`):-//! the platform clipboard tools first (they hold selection ownership), then-//! the OSC 52 escape for remote sessions or when no tool copied. The OSC 52-//! payload cap and the final error text are TS-verbatim; the TS native-//! `clipboard-rs` addon (skipped on Linux by TS itself) has no Rust-//! counterpart, so the tool chain plus OSC 52 is the full port.--use std::io::Write;+//! Terminal clipboard requests. Local clipboard tools confirm delivery;+//! tmux buffer forwarding and OSC 52 cannot confirm receipt by the user's+//! terminal. All user-facing copy paths share this chain and its size cap.++use std::io::{Read, Write};use std::process::{Command, Stdio};use std::time::Duration;@@ -17,18 +14,152 @@ pub(crate) enum OscSink {}impl OscSink {- fn write_sequence(&mut self, sequence: &str) {+ fn write_sequence(&mut self, sequence: &str) -> std::io::Result<()> {match self {OscSink::Stdout => {let mut out = std::io::stdout();- // The sequence is zero-width; a write failure (closed pipe)- // must not fail the copy attempt chain.- let _ = out.write_all(sequence.as_bytes());- let _ = out.flush();+ out.write_all(sequence.as_bytes())?;+ out.flush()+ }+ OscSink::Buffer(buffer) => {+ buffer.extend_from_slice(sequence.as_bytes());+ Ok(())+ }+ }+ }+}++/// tmux with `external` or `off` discards application-origin OSC 52.+/// A tmux-owned buffer can still be forwarded with `external` when an+/// attached client advertises the Ms clipboard capability.+pub(crate) fn tmux_blocks_osc52() -> bool {+ if std::env::var_os("TMUX").is_none() {+ return false;+ }+ tmux_output(&["show", "-s", "set-clipboard"])+ .is_some_and(|output| tmux_clipboard_setting_blocks(output.as_bytes()))+}++fn tmux_clipboard_setting_blocks(output: &[u8]) -> bool {+ matches!(+ String::from_utf8_lossy(output).trim(),+ "set-clipboard external" | "set-clipboard off"+ )+}++pub(crate) const TMUX_CLIPBOARD_BLOCKED: &str =+ "tmux cannot forward this copy to a clipboard. Check its attached client's Ms capability and each outer tmux hop.";+pub(crate) const CLIPBOARD_REQUESTED: &str =+ "Clipboard request sent; paste in the local terminal to verify delivery";+/// The oversized remote fallback's report: the helper wrote the machine+/// the TUI runs on, not the user's local clipboard.+const OVERSIZED_REMOTE_COPIED: &str =+ "Payload too large for terminal forwarding; copied to the remote machine's clipboard instead";++fn tmux_output(args: &[&str]) -> Option<String> {+ let mut child = Command::new("tmux")+ .args(args)+ .stdin(Stdio::null())+ .stderr(Stdio::null())+ .stdout(Stdio::piped())+ .spawn()+ .ok()?;+ probe_output(&mut child)+}++/// One bounded probe's output, or `None` when the child fails or misses+/// the deadline: the pipe drains from its own thread for the whole life+/// of the child (the `pipe_to` writer-thread shape), so a probe writing+/// past the pipe buffer still exits.+fn probe_output(child: &mut std::process::Child) -> Option<String> {+ let stdout = child.stdout.take();+ let reader = std::thread::spawn(move || {+ let mut output = String::new();+ stdout+ .and_then(|mut pipe| pipe.read_to_string(&mut output).ok())+ .map(|_| output)+ });+ let deadline = std::time::Instant::now() + HELPER_TIMEOUT;+ let status = loop {+ match child.try_wait() {+ Ok(Some(status)) => break Some(status),+ Ok(None) if std::time::Instant::now() >= deadline => {+ let _ = child.kill();+ let _ = child.wait();+ break None;+ }+ Ok(None) => std::thread::sleep(PIPE_POLL),+ Err(_) => {+ let _ = child.kill();+ let _ = child.wait();+ break None;}- OscSink::Buffer(buffer) => buffer.extend_from_slice(sequence.as_bytes()),}+ }?;+ // The child exited, so its pipe reaches EOF and the reader ends.+ let output = reader.join().ok().flatten()?;+ status.success().then_some(output)+}++/// Ask tmux to originate the clipboard write. `external` allows tmux's own+/// writes, unlike the application OSC 52 path. No terminal protocol confirms+/// that an outer tmux or terminal actually received the request.+pub(crate) fn copy_via_tmux(text: &str) -> bool {+ let Ok(pane) = std::env::var("TMUX_PANE") else {+ return false;+ };+ // `set-clipboard` is a server option on every tmux since 2.6; tmux+ // before 3.0 picks the probe's option tree from the flags alone, so+ // without `-s` the session tree rejects the name and forwarding is+ // silently skipped.+ if tmux_output(&["show-options", "-s", "-gv", "set-clipboard"])+ .is_none_or(|value| value.trim() == "off")+ {+ return false;+ }+ let Some(window) = tmux_output(&["display-message", "-p", "-t", &pane, "#{window_id}"]) else {+ return false;+ };+ let Some(clients) = tmux_output(&[+ "list-clients",+ "-F",+ "#{client_activity} #{window_id} #{client_name}",+ ]) else {+ return false;+ };+ let Some(client) = pane_client(&clients, window.trim()) else {+ return false;+ };+ let client = client.as_str();+ let Some(terminal) = tmux_output(&["show-messages", "-T", "-t", client]) else {+ return false;+ };+ if !terminal.lines().any(|line| {+ line.split_once("Ms: (string) ")+ .is_some_and(|(_, capability)| !capability.trim().is_empty())+ }) {+ return false;}+ pipe_to("tmux", &["load-buffer", "-w", "-t", client, "-"], text)+}++/// The client a pane's copy is forwarded to: the most recently active+/// client whose current window IS the pane's window. The typist types+/// through that client, so it receives the copy; a busier client on+/// another window must not — its user's clipboard would take the+/// payload, and a sign-in link can ride a copy. Clients sharing the+/// window (a mirrored session) fall back to activity, which can only+/// misdeliver to someone already viewing the pane.+fn pane_client(clients: &str, pane_window: &str) -> Option<String> {+ clients+ .lines()+ .filter_map(|line| {+ let (activity, rest) = line.split_once(' ')?;+ let (window, client) = rest.split_once(' ')?;+ (window == pane_window).then_some((activity.parse::<u64>().ok()?, client))+ })+ .max_by_key(|(activity, _)| *activity)+ .map(|(_, client)| client.to_string())}/// TS `isRemoteSession`: any SSH or mosh transport means the local tools@@ -189,43 +320,88 @@ fn copy_to_x11(text: &str) -> bool {|| pipe_to("xsel", &["--clipboard", "--input"], text)}-/// Copy `text` to the user's clipboard (TS `copyToClipboard`): platform-/// tools, then OSC 52 for remote sessions or when no tool copied. Errors-/// resolve with the TS wording.-pub(crate) fn copy_to_clipboard(text: &str, sink: &mut OscSink) -> Result<(), String> {+/// Copy text using a local platform tool or request delivery via the terminal.+/// A terminal request has no acknowledgement from the local clipboard.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum CopyOutcome {+ Confirmed,+ Requested,+}++/// A platform helper's success: a local session's helper wrote the user's+/// own clipboard, while a remote session's helper wrote the machine the+/// TUI runs on — the user's local terminal cannot paste from it, and the+/// payload is too large for OSC 52 — so the copy reports where the text+/// landed instead of confirming delivery.+fn helper_outcome(remote: bool) -> Result<CopyOutcome, String> {+ if remote {+ Err(OVERSIZED_REMOTE_COPIED.to_string())+ } else {+ Ok(CopyOutcome::Confirmed)+ }+}++pub(crate) fn copy_to_clipboard(text: &str, sink: &mut OscSink) -> Result<CopyOutcome, String> {copy_with_env(text, sink, &Env::process())}-fn copy_with_env(text: &str, sink: &mut OscSink, env: &Env) -> Result<(), String> {- let mut copied = false;- if !copied {- copied = match std::env::consts::OS {+/// The containing tmux's rejected-application-OSC 52 explanation, only+/// while the payload could ride OSC 52 at all: an oversized payload never+/// reaches the terminal channel, so it must not blame tmux's client+/// capability or the outer hops — the plain failure wording covers it.+fn tmux_clipboard_blocked(carriable: bool, blocks: impl FnOnce() -> bool) -> Option<String> {+ (carriable && blocks()).then(|| TMUX_CLIPBOARD_BLOCKED.to_string())+}++fn copy_with_env(text: &str, sink: &mut OscSink, env: &Env) -> Result<CopyOutcome, String> {+ let remote = is_remote_session(env);+ // The cap gate is a length check, not the encoding: the local+ // helpers below take the raw payload, and only an OSC 52 write+ // needs the encoded sequence.+ let carriable = crate::osc52::carries(text);+ // Remote tools target the wrong machine and can stall the input loop+ // before terminal forwarding. Keep them for payloads too large for OSC 52.+ let copied = if matches!(sink, OscSink::Buffer(_)) || (remote && carriable) {+ false+ } else {+ match std::env::consts::OS {"macos" => pipe_to("pbcopy", &[], text),"windows" => pipe_to("clip", &[], text),_ => copy_on_linux(text, env),- };- }- let remote = is_remote_session(env);- if copied && !remote {- return Ok(());+ }+ };+ if copied {+ return helper_outcome(remote);}- if remote || !copied {- if let Some(sequence) = crate::osc52::sequence(text) {- sink.write_sequence(&sequence);- copied = true;+ if matches!(sink, OscSink::Stdout) && std::env::var_os("TMUX").is_some() {+ // The containing tmux originates this copy even with its default+ // `set-clipboard external`; raw application OSC 52 is rejected there.+ if carriable && copy_via_tmux(text) {+ return Ok(CopyOutcome::Requested);+ }+ if let Some(error) = tmux_clipboard_blocked(carriable, tmux_blocks_osc52) {+ return Err(error);}}- if copied {- Ok(())- } else {- Err("Failed to copy to clipboard".to_string())+ if let Some(sequence) = crate::osc52::sequence(text) {+ sink.write_sequence(&sequence)+ .map_err(|error| format!("Failed to write clipboard request: {error}"))?;+ return Ok(CopyOutcome::Requested);}+ Err("Failed to copy to clipboard".to_string())}#[cfg(test)]mod tests {use super::*;+ #[test]+ fn tmux_application_clipboard_policy() {+ assert!(tmux_clipboard_setting_blocks(b"set-clipboard external\n"));+ assert!(tmux_clipboard_setting_blocks(b"set-clipboard off\n"));+ assert!(!tmux_clipboard_setting_blocks(b"set-clipboard on\n"));+ }+fn plain_env() -> Env {Env::scripted([("SSH_CONNECTION", None),@@ -250,7 +426,10 @@ mod tests {#[test]fn a_small_text_without_tools_emits_osc52() {let mut sink = OscSink::Buffer(Vec::new());- copy_with_env("parity text", &mut sink, &plain_env()).expect("copy succeeds via OSC 52");+ assert_eq!(+ copy_with_env("parity text", &mut sink, &plain_env()),+ Ok(CopyOutcome::Requested)+ );match sink {OscSink::Buffer(buffer) => {let bytes = String::from_utf8(buffer).expect("utf8");@@ -261,7 +440,81 @@ mod tests {}#[test]- fn a_remote_session_emits_osc52_even_after_a_tool_copy() {+ #[cfg(unix)]+ fn a_probe_that_fills_the_pipe_still_drains_and_exits() {+ use std::process::{Command, Stdio};+ // The payload overruns any platform's pipe buffer: the drain runs+ // while the child is alive, or the child blocks on its write and+ // the probe misses the deadline.+ let mut child = Command::new("sh")+ .args(["-c", "head -c 262144 /dev/zero | tr '\\0' x"])+ .stdin(Stdio::null())+ .stderr(Stdio::null())+ .stdout(Stdio::piped())+ .spawn()+ .expect("sh spawns");+ let output = probe_output(&mut child).expect("the probe drains the full pipe");+ assert_eq!(output.len(), 262_144);+ }++ #[test]+ fn the_pane_window_client_wins_over_a_busier_client_elsewhere() {+ // The busier client sits on another window: its user must not+ // receive the copy; the client viewing the pane's window does.+ let clients = "1780000000 @2 /dev/pts/2\n1770000000 @1 /dev/pts/1\n";+ assert_eq!(pane_client(clients, "@1").as_deref(), Some("/dev/pts/1"));+ // No client views the pane's window: forwarding must not guess.+ assert_eq!(pane_client(clients, "@3"), None);+ }++ #[test]+ fn an_oversized_payload_never_blames_tmux_capability() {+ assert_eq!(+ tmux_clipboard_blocked(false, || true),+ None,+ "an oversized payload cannot ride the terminal channel at all"+ );+ assert_eq!(+ tmux_clipboard_blocked(true, || true),+ Some(TMUX_CLIPBOARD_BLOCKED.to_string())+ );+ assert_eq!(tmux_clipboard_blocked(true, || false), None);+ }++ #[test]+ fn a_remote_helper_success_never_confirms_local_delivery() {+ assert_eq!(+ helper_outcome(true),+ Err(OVERSIZED_REMOTE_COPIED.to_string())+ );+ assert_eq!(helper_outcome(false), Ok(CopyOutcome::Confirmed));+ }++ #[test]+ fn a_remote_oversized_payload_falls_through_without_a_confirmed_copy() {+ // The helper fallback writes the remote machine's clipboard, which+ // can never confirm the user's local delivery; with no helper to+ // run (the headless sink's shape) the copy simply fails.+ let mut sink = OscSink::Buffer(Vec::new());+ let env = Env::scripted([+ ("SSH_CONNECTION", Some("1.2.3.4")),+ ("SSH_CLIENT", None),+ ("MOSH_CONNECTION", None),+ ("TERMUX_VERSION", None),+ ("WAYLAND_DISPLAY", None),+ ("XDG_SESSION_TYPE", None),+ ("DISPLAY", None),+ ]);+ let big = "a".repeat(200_001);+ assert_eq!(+ copy_with_env(&big, &mut sink, &env),+ Err("Failed to copy to clipboard".to_string())+ );+ assert!(matches!(sink, OscSink::Buffer(buffer) if buffer.is_empty()));+ }++ #[test]+ fn a_remote_session_emits_osc52_without_local_tools() {let mut sink = OscSink::Buffer(Vec::new());let env = Env::scripted([("SSH_CONNECTION", Some("1.2.3.4")),diff --git a/crates/pa-tui/src/osc52.rs b/crates/pa-tui/src/osc52.rsindex 064fd2b85f..59fab2e36e 100644--- a/crates/pa-tui/src/osc52.rs+++ b/crates/pa-tui/src/osc52.rs@@ -7,14 +7,22 @@/// above it is refused rather than desynchronizing the terminal render.pub(crate) const MAX_ENCODED_LENGTH: usize = 100_000;+/// Whether `text` fits the cap, by length alone: base64 output is+/// exactly `4 * ceil(bytes / 3)` characters, so callers gate on the cap+/// without building the encoding — a local helper takes the raw+/// payload, and the encoding belongs to the OSC 52 write alone.+pub(crate) fn carries(text: &str) -> bool {+ text.len().div_ceil(3) * 4 <= MAX_ENCODED_LENGTH+}+/// The OSC 52 clipboard sequence for `text` (clipboard selection `c`),/// or `None` when the encoded payload exceeds the cap.pub(crate) fn sequence(text: &str) -> Option<String> {use base64::Engine;- let encoded = base64::engine::general_purpose::STANDARD.encode(text);- if encoded.len() > MAX_ENCODED_LENGTH {+ if !carries(text) {return None;}+ let encoded = base64::engine::general_purpose::STANDARD.encode(text);Some(format!("\x1b]52;c;{encoded}\x07"))}@@ -32,6 +40,23 @@ mod tests {assert_eq!(sequence("").as_deref(), Some("\x1b]52;c;\x07"));}+ #[test]+ fn the_length_gate_agrees_with_the_encoded_cap() {+ // 75_000 raw bytes encode to exactly the 100_000-character cap.+ let at_cap = "a".repeat(75_000);+ assert!(carries(&at_cap));+ assert!(sequence(&at_cap).is_some());+ let over = "a".repeat(75_001);+ assert!(!carries(&over));+ assert!(sequence(&over).is_none());+ // The length gate and the real encoding agree across the+ // boundary and below it.+ for size in [0, 1, 2, 3, 6, 70_000, 74_999, 75_000, 75_001, 200_001] {+ let text = "a".repeat(size);+ assert_eq!(carries(&text), sequence(&text).is_some(), "size {size}");+ }+ }+#[test]fn oversized_payloads_are_refused() {// 100_001 base64 characters of source payload.diff --git a/crates/pa-tui/src/session_ui/keys.rs b/crates/pa-tui/src/session_ui/keys.rsindex a46f8342cc..4136a3a4a9 100644--- a/crates/pa-tui/src/session_ui/keys.rs+++ b/crates/pa-tui/src/session_ui/keys.rs@@ -259,17 +259,11 @@ impl SessionUi {}}- /// Copy a finished selection out (TS `copySelection` +- /// `copyFullscreenSelection`): OSC 52 works locally, over SSH, and- /// through tmux (`set-clipboard`), so the write goes straight to the- /// terminal; a headless run has no terminal and records the text for- /// its verifier instead. A successful copy surfaces the- /// "Copied selection to clipboard" action toast (the ephemeral- /// overlay, not the TS `showStatus` chat row — sanctioned divergence),- /// a failed write the failure row (TS `showError`).+ /// Copy a finished selection through the shared platform/tmux/OSC 52+ /// chain. A headless run records the text for its verifier instead.+ /// Only a local platform-tool write confirms delivery; a terminal+ /// request is reported as unconfirmed.fn copy_selection(&mut self, text: &str, view: &mut AgentView) {- use base64::Engine;- use std::io::Write;let lines = text.lines().count().max(1);self.copies.push(text.to_string());self.track_selection(lines);@@ -277,16 +271,14 @@ impl SessionUi {self.toast("Copied selection to clipboard", view);return;}- let encoded = base64::engine::general_purpose::STANDARD.encode(text.as_bytes());- let mut out = std::io::stdout();- match out.write_all(format!("\x1b]52;c;{encoded}\x07").as_bytes()) {- Ok(()) => {- let _ = out.flush();+ match crate::clipboard::copy_to_clipboard(text, &mut self.osc_sink) {+ Ok(crate::clipboard::CopyOutcome::Confirmed) => {self.toast("Copied selection to clipboard", view);}- Err(error) => {- self.error_row(&format!("Failed to copy selection: {error}"), view);+ Ok(crate::clipboard::CopyOutcome::Requested) => {+ self.toast(crate::clipboard::CLIPBOARD_REQUESTED, view);}+ Err(error) => self.error_row(&error, view),}}@@ -1123,54 +1115,20 @@ impl SessionUi {}}crate::editor::EditorEvent::ClipboardWrite(text) => {- // A selection cut/copy. On a live terminal it takes- // TS `copySelection`'s shape exactly: the OSC 52- // sequence goes straight to the terminal (it works- // locally, over SSH, and through tmux- // `set-clipboard`), the same write the mouse- // selection's `copy_selection` below performs. The- // platform-tool chain (child processes whose- // `wait()` has no timeout) never runs on this path:- // a stalled xclip/wl-copy/pbcopy can neither freeze- // the prompt nor leak an unkillable blocking task,- // and no background task accumulates. The toast is- // success-only; a failed write shows the error row.- // A headless run has no terminal to write to and no- // stalling children (the tools fail to spawn- // instantly), so it keeps the synchronous platform- // chain and its captured OSC sink stays verifiable.+ // An editor cut/copy follows the same clipboard path as+ // mouse selection. Headless tests retain the selection.if std::io::IsTerminal::is_terminal(&std::io::stdout()) {- use std::io::Write;- // The sequence goes through `osc52::sequence`, so- // the encoded-payload cap applies to this path- // like every other OSC 52 write: an oversized- // sequence desynchronizes the terminal, so the- // copy reports failure instead of writing it.- match crate::osc52::sequence(&text) {- Some(sequence) => {- let mut out = std::io::stdout();- match out.write_all(sequence.as_bytes()) {- Ok(()) => {- let _ = out.flush();- self.toast("Copied selection to clipboard", view);- }- Err(error) => {- self.error_row(- &format!("Failed to copy selection: {error}"),- view,- );- }- }+ match crate::clipboard::copy_to_clipboard(&text, &mut self.osc_sink) {+ Ok(crate::clipboard::CopyOutcome::Confirmed) => {+ self.toast("Copied selection to clipboard", view);}- None => {- self.error_row("Failed to copy selection to clipboard", view);+ Ok(crate::clipboard::CopyOutcome::Requested) => {+ self.toast(crate::clipboard::CLIPBOARD_REQUESTED, view);}- }- } else {- match crate::clipboard::copy_to_clipboard(&text, &mut self.osc_sink) {- Ok(()) => self.toast("Copied selection to clipboard", view),Err(message) => self.error_row(&message, view),}+ } else {+ self.toast("Copied selection to clipboard", view);}}_ => {}diff --git a/crates/pa-tui/src/session_ui/share.rs b/crates/pa-tui/src/session_ui/share.rsindex a7f0ddcf1c..3676504aaa 100644--- a/crates/pa-tui/src/session_ui/share.rs+++ b/crates/pa-tui/src/session_ui/share.rs@@ -473,7 +473,12 @@ impl SessionUi {return Ok(());};match crate::clipboard::copy_to_clipboard(&text, &mut self.osc_sink) {- Ok(()) => self.toast("Copied last agent message to clipboard", view),+ Ok(crate::clipboard::CopyOutcome::Confirmed) => {+ self.toast("Copied last agent message to clipboard", view);+ }+ Ok(crate::clipboard::CopyOutcome::Requested) => {+ self.toast(crate::clipboard::CLIPBOARD_REQUESTED, view);+ }Err(message) => self.error_row(&message, view),}Ok(())