//! Clipboard reads use a test sink; the fake server records attachment and stash requests. use crate::support::{self, DIRECTORY, Fake, Harness, Log, WAIT, deref_harness}; use std::path::Path; use std::sync::Arc; use std::time::Duration; use base64::Engine; use opencode_local::cli_config::{Info, Prompt, PromptPaste}; use opencode_tui::features::links::testing; use opencode_tui::features::startup::Args; use opentui::native::ClipboardOutcome; use opentui::testing::TestApp; use serde_json::{Value, json}; const PNG: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="; fn fake() -> Fake { Fake::new(|seen| match (seen.method.as_str(), seen.path.as_str()) { ("GET", "/api/model") => { let model = support::merge( support::model("p", "m", "Model M"), json!({ "capabilities": { "tools": true, "input": ["text", "image"], "output": ["text"] } }), ); (200, support::list(DIRECTORY, json!([model]))) } _ => support::base(seen, DIRECTORY), }) } struct Setup { harness: Harness, seen: Log, home: opencode_util::temp::TempDir, } deref_harness!(Setup); impl Setup { fn new() -> Self { Self::with(opencode_util::temp::tempdir().unwrap(), Info::default(), false) } /// Enable copy-on-select explicitly across platforms. fn copying_on_select() -> Self { let info = opencode_local::cli_config::merge(&[Some(json!({ "terminal": { "copy": "select" } }))]); Self::with(opencode_util::temp::tempdir().unwrap(), info, false) } fn with(home: opencode_util::temp::TempDir, info: Info, local: bool) -> Self { let fake = fake(); let seen = fake.log(); let deps = opencode_tui::Deps { config: support::config(info), roots: support::roots(support::paths(home.path()), "latest"), ..support::deps(Arc::new(fake)) }; let harness = support::mount_on(TestApp::new(90, 30), deps, Args { local, ..Args::default() }); let setup = Self { harness, seen, home }; setup.wait_for("Model M"); setup } fn wait_text(&self, text: &str) { let found = self.app.wait_until(WAIT, || self.text() == text); assert!(found, "prompt is {:?}, not {text:?}", self.text()); } fn submit(&self) -> Value { let before = self.prompts().len(); self.app.press("return"); let sent = self.app.wait_until(WAIT, || self.prompts().len() > before); assert!(sent, "no prompt sent: {:?}", self.seen.lock().unwrap()); self.prompts().pop().unwrap() } fn prompts(&self) -> Vec { self.seen .lock() .unwrap() .iter() .filter(|seen| seen.method == "POST" && seen.path.ends_with("/prompt")) .map(|seen| seen.body.clone()) .collect() } fn stash_file(&self) -> String { std::fs::read_to_string(self.home.path().join("state/prompt-stash.jsonl")).unwrap_or_default() } fn wait_stash_file(&self, check: impl Fn(&str) -> bool) -> String { let found = self.app.wait_until(WAIT, || check(&self.stash_file())); assert!(found, "prompt-stash.jsonl is {:?}", self.stash_file()); self.stash_file() } } fn prompt_config(paste: Option, image_preview: bool) -> Info { Info { prompt: Some(Prompt { paste, image_preview: Some(image_preview), ..Prompt::default() }), ..Info::default() } } #[test] fn long_pastes_collapse_into_parts_that_send_their_text() { let setup = Setup::new(); setup.app.type_text("see "); setup.app.paste("one\r\ntwo\r\nthree"); setup.wait_text("see [Pasted ~3 lines] "); let long = "x".repeat(151); setup.app.paste(&long); setup.wait_text("see [Pasted ~3 lines] [Pasted ~1 lines] "); setup.app.type_text("go"); let sent = setup.submit(); assert_eq!(sent["text"], format!("see one\ntwo\nthree {long} go")); // History keeps the parts, so Up brings back the labels and the text behind them. setup.app.press("up"); setup.wait_text("see [Pasted ~3 lines] [Pasted ~1 lines] go"); let sent = setup.submit(); assert_eq!(sent["text"], format!("see one\ntwo\nthree {long} go")); // A paste replaces a selection that ends after the cursor, and its part marks its own label. setup.app.type_text("a"); setup.app.press("up"); setup.app.press("shift+right"); setup.app.paste("l1\nl2\nl3"); setup.wait_text("[Pasted ~3 lines] "); assert_eq!(setup.submit()["text"], "l1\nl2\nl3 "); } #[test] fn a_second_paste_or_a_click_expands_a_paste_and_backspace_removes_it() { let setup = Setup::new(); setup.app.paste("a\nb\nc"); setup.wait_text("[Pasted ~3 lines] "); setup.app.paste("a\nb\nc"); setup.wait_text("a\nb\nc "); setup.app.press("ctrl+c"); setup.app.paste("d\ne\nf"); setup.wait_text("[Pasted ~3 lines] "); let (x, y) = setup.find("[Pasted"); setup.app.click(x, y); setup.wait_text("d\ne\nf "); setup.app.press("ctrl+c"); setup.app.paste("g\nh\ni"); setup.wait_text("[Pasted ~3 lines] "); setup.app.press("backspace"); setup.app.press("backspace"); setup.wait_text(""); } #[test] fn undo_submits_the_restored_paste_and_a_fragment_as_text() { let pasted = "one\ntwo\nthree\nfour"; for (fragment, restored, sent) in [(false, "[Pasted ~4 lines] ", format!("{pasted} ")), (true, "[Pasted ~4 ", "[Pasted ~4 ".to_owned())] { let setup = Setup::new(); setup.app.paste(pasted); setup.wait_text("[Pasted ~4 lines] "); if fragment { // Remove the space after the label, then leave a fragment of it. setup.app.press("backspace"); setup.app.press("ctrl+w"); } setup.app.press("ctrl+u"); setup.wait_text(""); setup.app.press("super+z"); setup.wait_text(restored); assert_eq!(setup.submit()["text"], sent, "fragment: {fragment}"); } let setup = Setup::new(); setup.app.paste("a\nb\nc"); setup.app.type_text("and "); setup.app.paste("d\ne\nf"); setup.wait_text("[Pasted ~3 lines] and [Pasted ~3 lines] "); let (x, y) = setup.find("[Pasted"); setup.app.click(x, y); setup.wait_text("a\nb\nc and [Pasted ~3 lines] "); setup.app.press("super+z"); setup.wait_text(" and [Pasted ~3 lines] "); setup.app.press("super+z"); setup.wait_text("[Pasted ~3 lines] and [Pasted ~3 lines] "); assert_eq!(setup.submit()["text"], "a\nb\nc and d\ne\nf "); } // gh-triage-2012: the editor counts a tab as two cells and the text indexes bytes, so the prompt converts through the // buffer. A paste after a tab expands where its label is (a width count gave `\t[A\nB\nCZ`), and so after a wide // character and a joined emoji. #[test] fn a_paste_after_a_tab_or_wide_text_expands_in_place() { for prefix in ["\t", "界", "👩‍💻"] { let setup = Setup::new(); setup.app.paste(prefix); setup.app.paste("A\nB\nC"); setup.wait_text(&format!("{prefix}[Pasted ~3 lines] ")); setup.app.type_text("Z"); assert_eq!(setup.submit()["text"], format!("{prefix}A\nB\nC Z"), "after {prefix:?}"); } } // gh-triage-2012: Down on the last line moves to the end of the text, so typing appends. A width count took the end // for `d`'s start and left the cursor there: `ab\tcXd`. #[test] fn down_on_the_last_line_moves_to_the_end_after_a_tab_or_wide_text() { for middle in ["\t", "界", "👩‍💻"] { let setup = Setup::new(); let text = format!("ab{middle}cd"); setup.app.paste(&text); setup.wait_text(&text); setup.app.press("left"); setup.app.press("down"); setup.app.type_text("X"); setup.wait_text(&format!("{text}X")); } } #[test] fn copying_a_selection_over_a_paste_copies_its_text() { let capture = testing::capture(); let setup = Setup::copying_on_select(); setup.app.type_text("see "); setup.app.paste("a\nb\nc"); setup.wait_text("see [Pasted ~3 lines] "); let (x, y) = setup.find("see [Pasted"); // From "see" (not on the label, whose press would expand it) to the label's last cell. setup.app.drag((x, y), (x + 20, y)); let copied = setup.app.wait_until(WAIT, || !capture.0.copied.borrow().is_empty()); assert!(copied, "nothing copied:\n{}", setup.app.text()); assert_eq!(capture.0.copied.borrow().last().unwrap(), "see a\nb\nc"); } #[test] fn copying_a_selection_copies_the_paste_inside_it_not_an_earlier_one_with_the_same_label() { let capture = testing::capture(); let setup = Setup::copying_on_select(); setup.app.paste("a\nb\nc"); setup.wait_text("[Pasted ~3 lines] "); setup.app.type_text("and "); setup.app.paste("d\ne\nf"); setup.wait_text("[Pasted ~3 lines] and [Pasted ~3 lines] "); let (x, y) = setup.find("and [Pasted"); // From "and" to the second label's last cell: matching labels in order would copy the first paste. setup.app.drag((x, y), (x + 20, y)); let copied = setup.app.wait_until(WAIT, || !capture.0.copied.borrow().is_empty()); assert!(copied, "nothing copied:\n{}", setup.app.text()); assert_eq!(capture.0.copied.borrow().last().unwrap(), "and d\ne\nf"); } #[test] fn short_pastes_go_in_as_they_are_and_full_turns_compaction_off() { let setup = Setup::new(); setup.app.paste("short \u{1b}[31mred\u{1b}[0m\rpaste"); setup.wait_text("short red\npaste"); let full = Setup::with(opencode_util::temp::tempdir().unwrap(), prompt_config(Some(PromptPaste::Full), false), false); full.app.paste("a\nb\nc\nd"); full.wait_text("a\nb\nc\nd"); } #[test] fn clipboard_images_attach_preview_and_open_in_the_dialog() { let capture = testing::capture(); let png = base64::engine::general_purpose::STANDARD.decode(PNG).unwrap(); let setup = Setup::with(opencode_util::temp::tempdir().unwrap(), prompt_config(None, true), false); let read = || ClipboardOutcome::Read { mime_type: "image/png".into(), data: png.clone() }; // Another picture: the same image with a byte after its end, which decoders skip. let other = [png.clone(), vec![0]].concat(); let other_read = ClipboardOutcome::Read { mime_type: "image/png".into(), data: other.clone() }; capture.0.clipboard.borrow_mut().extend([read(), read(), other_read]); setup.app.press("ctrl+v"); setup.wait_text("[Image 1] "); setup.app.press("ctrl+v"); setup.wait_text("[Image 1] [Image 1] "); // Another image counts up. setup.app.press("ctrl+v"); setup.wait_text("[Image 1] [Image 1] [Image 2] "); // `i`: the preview dialog shows each image once, under its label. setup.app.press("ctrl+x"); setup.app.press("i"); let screen = setup.wait_for("Image 1 of 2"); assert!(screen.contains("[Image 1]"), "{screen}"); setup.app.press("escape"); setup.wait_gone("Image 1 of 1"); let sent = setup.submit(); let uri = format!("data:image/png;base64,{PNG}"); assert_eq!( sent["files"], json!([ { "uri": uri, "name": "clipboard", "mention": { "start": 0, "end": 9, "text": "[Image 1]" } }, { "uri": uri, "name": "clipboard", "mention": { "start": 10, "end": 19, "text": "[Image 1]" } }, { "uri": format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(&other)), "name": "clipboard", "mention": { "start": 20, "end": 29, "text": "[Image 2]" }, }, ]) ); assert_eq!(sent["text"], "[Image 1] [Image 1] [Image 2] "); } #[test] fn clipboard_text_pastes_and_read_errors_toast() { let capture = testing::capture(); let setup = Setup::new(); capture.0.clipboard.borrow_mut().extend([ ClipboardOutcome::Read { mime_type: "text/plain".into(), data: b"one\ntwo\nthree".to_vec() }, ClipboardOutcome::TimedOut, ClipboardOutcome::Unsupported, ClipboardOutcome::Empty, ]); setup.app.press("ctrl+v"); setup.wait_text("[Pasted ~3 lines] "); setup.app.press("ctrl+v"); setup.wait_for("Clipboard read timed out"); setup.app.press("ctrl+v"); setup.wait_for("Clipboard read is not supported on this system"); setup.app.paste(""); setup.app.advance(Duration::from_millis(5)); assert_eq!(setup.text(), "[Pasted ~3 lines] "); assert!(capture.0.clipboard.borrow().is_empty()); } #[test] fn pasted_paths_attach_files_and_svgs_paste_their_text() { let files = opencode_util::temp::tempdir().unwrap(); let png = files.path().join("shot one.png"); std::fs::write(&png, base64::engine::general_purpose::STANDARD.decode(PNG).unwrap()).unwrap(); let svg = files.path().join("logo.svg"); std::fs::write(&svg, "").unwrap(); let setup = Setup::with(opencode_util::temp::tempdir().unwrap(), prompt_config(None, true), true); // A dragged path arrives quoted or escaped; both attach. Windows has no escapes: `\` separates. let quoted = format!("'{}'", png.display()); setup.app.paste(&if cfg!(windows) { quoted } else { quoted.replace(' ', "\\ ") }); setup.wait_text("[Image 1] "); setup.app.paste(&format!("{}", svg.display())); setup.wait_text("[Image 1] [SVG: logo.svg] "); setup.app.paste("/tmp/notes.txt"); setup.wait_text("[Image 1] [SVG: logo.svg] /tmp/notes.txt"); let sent = setup.submit(); assert_eq!(sent["text"], "[Image 1] /tmp/notes.txt"); let url = url::Url::from_file_path(&png).unwrap(); assert_eq!( sent["files"], json!([{ "uri": format!("data:image/png;base64,{PNG}"), "source": { "type": "uri", "uri": url.as_str() }, "name": "shot one.png", "mention": { "start": 0, "end": 9, "text": "[Image 1]" }, }]) ); // A list of dropped paths splits at whitespace outside quotes, and each attaches. setup.app.paste(&format!("'{}' {}", png.display(), svg.display())); setup.wait_text("[Image 1] [SVG: logo.svg] "); } #[test] fn previews_show_above_the_prompt_and_a_click_opens_the_dialog() { let files = opencode_util::temp::tempdir().unwrap(); let bad = files.path().join("bad.png"); std::fs::write(&bad, b"not a png").unwrap(); let setup = Setup::with(opencode_util::temp::tempdir().unwrap(), prompt_config(None, true), false); setup.app.paste(&bad.display().to_string()); setup.wait_text("[Image 1] "); let (x, y) = setup.find("No preview"); let (_, prompt) = setup.find("[Image 1]"); assert!(y < prompt, "the preview sits above the prompt"); setup.app.click(x, y); let screen = setup.wait_for("Image 1 of 1"); let (_, title) = setup.find("Image 1 of 1"); assert!(setup.find("No preview").1 > title, "{screen}"); setup.app.press("escape"); setup.wait_gone("Image 1 of 1"); // Without the option, nothing shows. let off = Setup::new(); off.app.paste(&bad.display().to_string()); off.wait_text("[Image 1] "); assert!(!off.app.text().contains("No preview")); } #[test] fn a_failed_stash_save_shows_a_toast() { let setup = Setup::new(); std::fs::create_dir_all(setup.home.path().join("state/prompt-stash.jsonl")).unwrap(); setup.app.type_text("draft"); setup.dispatch("prompt.stash"); setup.wait_text(""); setup.wait_for("Could not save the stash"); assert_eq!(setup.tui.prompt.stash.list().len(), 1, "the entry stays in memory"); } #[test] fn stash_pushes_pops_and_lists_with_delete_confirm() { let setup = Setup::new(); setup.app.type_text("first idea"); setup.app.press("ctrl+j"); setup.app.type_text("more"); setup.dispatch("prompt.stash"); setup.wait_text(""); setup.app.paste("x\ny\nz"); setup.app.type_text("second"); setup.dispatch("prompt.stash"); setup.wait_text(""); let file = setup.wait_stash_file(|file| file.lines().count() == 2); let entries: Vec = file.lines().map(|line| serde_json::from_str(line).unwrap()).collect(); assert_eq!(entries[0]["prompt"]["text"], "first idea\nmore"); assert_eq!(entries[1]["prompt"]["pasted"][0]["text"], "x\ny\nz"); assert!(entries[1]["timestamp"].is_number()); // Pop restores the newest with its paste part. setup.dispatch("prompt.stash.pop"); setup.wait_text("[Pasted ~3 lines] second"); setup.wait_stash_file(|file| file.lines().count() == 1); setup.dispatch("prompt.stash"); setup.wait_text(""); // The list shows the newest first, each by its first line; Ctrl+D twice deletes; Enter takes one out. setup.dispatch("prompt.stash.list"); let screen = setup.wait_for("Stash"); let (newest, oldest) = (screen.find("[Pasted ~3 lines] second").unwrap(), screen.find("first idea").unwrap()); assert!(newest < oldest, "{screen}"); assert!(screen.contains("just now") && screen.contains("~2 lines") && !screen.contains("more"), "{screen}"); setup.app.press("ctrl+d"); setup.wait_for("Press ctrl+d again to confirm"); setup.app.press("ctrl+d"); setup.wait_gone("second"); setup.wait_stash_file(|file| file.lines().count() == 1); setup.app.press("return"); setup.wait_text("first idea\nmore"); setup.wait_gone("Press ctrl+d"); setup.wait_stash_file(str::is_empty); } #[test] fn stash_file_is_shared_with_typescript() { let Some(root) = support::ts_root() else { return }; let setup = Setup::new(); setup.app.type_text("from rust"); setup.dispatch("prompt.stash"); setup.app.paste("p\nq\nr"); setup.dispatch("prompt.stash"); let rust = setup.wait_stash_file(|file| file.lines().count() == 2); let state = setup.home.path().join("state"); let typescript = json!({ "text": "from typescript", "files": [], "agents": [], "skills": [], "pasted": [] }); let results = support::solid_oracle( "E.4-stash.ts", &root, &[&state], &json!([{ "list": true }, { "pop": true }, { "push": typescript }, { "list": true }]), ); assert_eq!( results, json!([["from rust", "[Pasted ~3 lines] "], "[Pasted ~3 lines] ", ["from rust", "from typescript"],]) ); let file = std::fs::read_to_string(state.join("prompt-stash.jsonl")).unwrap(); let lines: Vec<&str> = file.lines().collect(); assert_eq!(lines[0], rust.lines().next().unwrap()); assert_eq!(lines.len(), 2); let home = opencode_util::temp::TempDir::new().unwrap(); std::fs::create_dir_all(home.path().join("state")).unwrap(); std::fs::copy(state.join("prompt-stash.jsonl"), home.path().join("state/prompt-stash.jsonl")).unwrap(); let again = Setup::with(home, Info::default(), false); let loaded = again.app.wait_until(WAIT, || !again.tui.prompt.stash.is_empty()); assert!(loaded); again.dispatch("prompt.stash.pop"); again.wait_text("from typescript"); again.app.press("ctrl+c"); again.dispatch("prompt.stash.pop"); again.wait_text("from rust"); again.wait_stash_file(str::is_empty); } /// Append one unlocked line as an independent stash writer. fn ts_stash(state: &Path, text: &str) { use std::io::Write; let line = json!({ "prompt": { "text": text, "files": [], "agents": [], "skills": [], "pasted": [] }, "timestamp": 1, }); std::fs::create_dir_all(state).unwrap(); std::fs::OpenOptions::new() .create(true) .append(true) .open(state.join("prompt-stash.jsonl")) .unwrap() .write_all(format!("{line}\n").as_bytes()) .unwrap(); } #[test] fn a_stash_another_tui_made_survives_pop() { let setup = Setup::new(); setup.app.type_text("mine"); setup.dispatch("prompt.stash"); setup.wait_stash_file(|file| file.contains("\"mine\"")); ts_stash(&setup.home.path().join("state"), "ts-important-draft"); // Pop takes this TUI's newest entry, and drops only its line. setup.dispatch("prompt.stash.pop"); setup.wait_text("mine"); let file = setup.wait_stash_file(|file| !file.contains("\"mine\"")); assert!(file.contains("ts-important-draft"), "{file:?}"); } #[test] fn a_stash_made_while_the_stash_loads_is_kept() { let home = opencode_util::temp::TempDir::new().unwrap(); let state = home.path().join("state"); ts_stash(&state, "old"); // Broken lines keep the load busy past the first frames; it heals them away. let file = state.join("prompt-stash.jsonl"); let mut text = std::fs::read_to_string(&file).unwrap(); text.push_str(&"broken\n".repeat(2_000_000)); std::fs::write(&file, text).unwrap(); let setup = Setup::with(home, Info::default(), false); assert!(setup.tui.prompt.stash.is_empty(), "the load finished too early for this test"); // Without advancing the app: the load finishes on its thread, but the UI has not taken its result. let healed = (0..500).any(|_| { std::thread::sleep(Duration::from_millis(10)); std::fs::read_to_string(&file).is_ok_and(|text| text.lines().count() == 1) }); assert!(healed); std::thread::sleep(Duration::from_millis(50)); let early = json!({ "text": "early", "files": [], "agents": [], "skills": [], "pasted": [] }); setup.tui.prompt.stash.push(&setup.tui, early); let texts = || { setup .tui .prompt .stash .list() .iter() .map(|entry| entry["prompt"]["text"].as_str().unwrap().to_owned()) .collect::>() }; let merged = setup.app.wait_until(WAIT, || texts() == ["old", "early"]); assert!(merged, "the stash is {:?}", texts()); setup.wait_stash_file(|file| file.lines().count() == 2 && file.contains("\"early\"")); }