//! Local web GUI for settings. DESIGN.md sections 5.5 / 10.2. //! //! Security: //! - Binds to 127.0.0.1 only (unreachable from outside, no firewall warning either) //! - Random port + one-time token per launch //! - The token is verified both in the URL and the request header, preventing //! other processes on the same PC or a malicious web page (CSRF / DNS rebinding) from operating the config API //! - Host header is restricted to the 127.0.0.1 family (DNS rebinding countermeasure) //! - The master password is not handled here (kept entirely inside the TUI) use std::io::Cursor; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use anyhow::{Context as _, Result}; use rand::TryRng as _; use tiny_http::{Header, Response, Server}; /// Remote UI status passed to the settings screen (updated by the main app) #[derive(Default, Clone)] pub struct RemoteInfo { /// A runtime can close tabs before deleting a working folder. Settings /// opened on their own have no such runtime. pub board: bool, pub running: bool, pub url: String, /// Explanation for when it can't be enabled, or a note that needs attention pub note: String, /// End what a device is holding, by its row in the book. /// /// Taking a key away is this page's own business -- the book is a file and /// this page can write it. What it cannot do is drop the sockets already /// carrying a screen to that device, because those belong to the running /// remote. Without this, a revoked phone keeps watching until it next asks /// for something, which on a pushed screen may be never. /// /// Absent in the settings-only mode, where nothing is live to end. pub cut: Option, } /// How a connection is ended: named, and told to go. /// /// Given by whoever is holding the connections, because the settings screen /// knows which one a person just revoked and nothing about how to stop it pub type Cut = Arc; pub struct WebUi { pub url: String, stop: Arc, } impl WebUi { /// Starts a local server that edits the config file. /// config_path is the target being edited (usually config.json). /// password is a share of the master password held by the main app (used to encrypt secrets). /// **Never exposed to the page or the network** — used only on the server side, within the same process pub fn start_with( config_path: std::path::PathBuf, remote: Arc>, password: Arc>>, ) -> Result { let token = random_token()?; let server = Server::http("127.0.0.1:0") .map_err(|e| anyhow::anyhow!(crate::i18n::tp("webui.err.server_start", &[("e", &e.to_string())])))?; let port = server .server_addr() .to_ip() .context(crate::i18n::t("webui.err.port"))? .port(); let url = format!("http://127.0.0.1:{port}/?token={token}"); let stop = Arc::new(AtomicBool::new(false)); { let stop = Arc::clone(&stop); std::thread::spawn(move || { for req in server.incoming_requests() { if stop.load(Ordering::SeqCst) { break; } if let Err(e) = handle(req, &token, &config_path, &remote, &password) { crate::append_hook_log(&format!("WebUI: {e}")); } } }); } Ok(Self { url, stop }) } pub fn shutdown(&self) { self.stop.store(true, Ordering::SeqCst); } } fn random_token() -> Result { let mut bytes = [0u8; 24]; rand::rngs::SysRng .try_fill_bytes(&mut bytes) .map_err(|e| anyhow::anyhow!(crate::i18n::tp("webui.err.token", &[("e", &e.to_string())])))?; Ok(bytes.iter().map(|b| format!("{b:02x}")).collect()) } /// Marks a request that reached this loopback server through the remote proxy — /// i.e. the person operating it is on a phone, not at this PC. The proxy builds /// a fresh request and never forwards the phone's own headers, so this can only /// be set by us. Anything that would put a window on the PC's screen has to know /// (see `NATIVE_DIALOG_PATHS`). pub const REMOTE_CLIENT_HEADER: &str = "X-Remote-Client"; /// Which device in the book (`crate::clients`) a request through the remote /// proxy came from; empty when it was let in some other way. Built by the /// proxy like `REMOTE_CLIENT_HEADER`, never forwarded from the phone pub const REMOTE_DEVICE_HEADER: &str = "X-Remote-Device"; /// Endpoints whose whole job is to open a native dialog on this PC. From a phone /// there is nobody standing at that screen to answer it, so the request would sit /// there until it timed out — the app looking frozen from the phone's side. These /// are refused outright when the caller is remote. The page knows: its Browse /// button walks the PC's folders over /api/walk instead, and export/import are /// left off. const NATIVE_DIALOG_PATHS: [&str; 3] = [ "/api/pick", "/api/desk/export", "/api/desk/import", ]; /// The names of the tabs the settings say run as account `id`, wherever they /// were written: a desk's folders, and the tabs inside tabs fn tabs_running_as(doc: &serde_json::Value, id: &str) -> Vec { fn walk(v: &serde_json::Value, id: &str, out: &mut Vec) { match v { serde_json::Value::Object(map) => { if map.get("ai_account").and_then(|a| a.as_str()) == Some(id) { out.push(map.get("name").and_then(|n| n.as_str()).unwrap_or("?").to_string()); } map.values().for_each(|c| walk(c, id, out)); } serde_json::Value::Array(list) => list.iter().for_each(|c| walk(c, id, out)), _ => {} } } let mut out = Vec::new(); if let Some(desks) = doc.get("desks") { walk(desks, id, &mut out); } out } /// The values of key `mark` on every tab written anywhere in `doc` fn marks_in(doc: &serde_json::Value, mark: &str) -> Vec { fn walk(v: &serde_json::Value, mark: &str, out: &mut Vec) { match v { serde_json::Value::Object(map) => { if let Some(m) = map.get(mark).and_then(|m| m.as_str()) { out.push(m.to_string()); } map.values().for_each(|c| walk(c, mark, out)); } serde_json::Value::Array(list) => list.iter().for_each(|c| walk(c, mark, out)), _ => {} } } let mut out = Vec::new(); walk(doc, mark, &mut out); out } /// Settings answered somewhere that writes them at once -- the board's /// questions, a card's own buttons -- while a settings page may be open /// holding the value from before. A save that did not change one (the page /// says which, `keep`) leaves the file's value as it is const ANSWERED_ELSEWHERE: [&str; 2] = ["agent_hooks", "worktree_trust"]; /// `config` with each setting in `keep` that is answered elsewhere put back /// to what the file holds now fn keep_answers(config: &mut serde_json::Value, on_disk: &serde_json::Value, keep: &[String]) { let Some(doc) = config.as_object_mut() else { return }; for key in ANSWERED_ELSEWHERE.iter().filter(|k| keep.iter().any(|x| x == *k)) { match on_disk.get(*key) { Some(v) => { doc.insert(key.to_string(), v.clone()); } None => { doc.remove(*key); } } } } /// Every tab in `doc` carrying key `mark` with a value not in `keep` taken out fn drop_marks_not_in(doc: &mut serde_json::Value, mark: &str, keep: &[String]) { match doc { serde_json::Value::Object(map) => { for list in ["tabs", "children"] { if let Some(serde_json::Value::Array(tabs)) = map.get_mut(list) { tabs.retain(|t| t.get(mark).and_then(|m| m.as_str()).is_none_or(|m| keep.iter().any(|k| k == m))); } } map.values_mut().for_each(|c| drop_marks_not_in(c, mark, keep)); } serde_json::Value::Array(list) => list.iter_mut().for_each(|c| drop_marks_not_in(c, mark, keep)), _ => {} } } /// Account `id` taken out of the app's list in the settings file fn forget_account_in_settings(path: &std::path::Path, id: &str) -> anyhow::Result<()> { let text = std::fs::read_to_string(path)?; let mut doc: serde_json::Value = serde_json::from_str(text.trim_start_matches('\u{feff}'))?; if let Some(list) = doc.get_mut("ai_accounts").and_then(|l| l.as_array_mut()) { let before = list.len(); list.retain(|a| a.get("id").and_then(|i| i.as_str()) != Some(id)); if list.len() != before { crate::crypto::write_atomic(path, &serde_json::to_string_pretty(&doc)?)?; } } Ok(()) } fn header_value(req: &tiny_http::Request, name: &'static str) -> String { req.headers() .iter() .find(|h| h.field.equiv(name)) .map(|h| h.value.as_str().to_string()) .unwrap_or_default() } /// Maximum accepted request-body size. Big enough for any real config/secrets /// payload, small enough that a giant or slow body can't exhaust memory. /// How long the connection test waits. Long enough for a server on the other /// side of the world to answer, short enough that the button is not still /// spinning when somebody has given up on it const SERVER_TEST_MS: u64 = 25_000; const MAX_BODY: usize = 1 << 20; // 1 MiB /// The most one settings save may carry: it holds the settings and every desk /// file the page writes, each of which may be [`MAX_BODY`] on its own, as it /// could when each went in a request of its own const SAVE_MAX_BODY: usize = 64 * MAX_BODY; /// Read a request body, capped at `max` bytes. Returns None if it would exceed /// the cap (the caller answers 413), so an oversized body is never buffered. use crate::http::read_body; fn query_token(url: &str) -> String { url.split_once('?') .map(|(_, q)| q) .unwrap_or("") .split('&') .find_map(|kv| kv.strip_prefix("token=")) .unwrap_or("") .to_string() } /// Reads one raw query-string value. Callers use known ASCII keys. fn query_param(url: &str, key: &str) -> Option { let prefix = format!("{key}="); url.split_once('?')? .1 .split('&') .find_map(|kv| kv.strip_prefix(&prefix).map(|v| v.to_string())) } /// Minimal percent-encoding for a query-string value. pub(crate) use crate::urlcodec::encode as pct; /// Where to read how to install a program: git's and GitHub CLI's own pages, /// or the page the program's profile names pub fn install_page(prog: &str) -> Option { match prog.trim() { p if p.eq_ignore_ascii_case("git") => Some("https://git-scm.com/downloads".to_string()), p if p.eq_ignore_ascii_case("gh") => Some("https://cli.github.com/".to_string()), // The phone page in the person's language: it begins with putting // Tailscale on the PC and the phone, which is the install that matters here p if p.eq_ignore_ascii_case("tailscale") => Some(crate::i18n::t("settings.phone.guide.url")), p => crate::profile::install_url_for(p), } } /// Opens a URL in the user's default browser instead of the in-app WebView. /// Uses ShellExecuteW so the whole URL — query string, '&' and percent-escapes /// included — is handed to the shell verbatim (explorer.exe mis-parses those /// and falls back to opening a file window instead). #[cfg(not(windows))] pub fn open_external(url: &str) { // On a server there is nothing to open with, and the failure is quiet on // purpose -- nobody is sitting there to be told let _ = opened_external(url); } /// The same, saying whether the system took it: `open` on a Mac, and /// `xdg-open`, the agreement on Linux desktops #[cfg(not(windows))] pub fn opened_external(url: &str) -> bool { let opener = if cfg!(target_os = "macos") { "open" } else { "xdg-open" }; std::process::Command::new(opener).arg(url).spawn().is_ok() } #[cfg(windows)] pub fn open_external(url: &str) { let _ = opened_external(url); } /// The same, saying whether the system took it. Anything at or below 32 from /// the shell is a failure, and a machine with nothing registered to open http /// with is a real one -- Windows Sandbox is exactly that #[cfg(windows)] pub fn opened_external(url: &str) -> bool { use windows_sys::Win32::UI::Shell::ShellExecuteW; use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL; let op: Vec = "open\0".encode_utf16().collect(); let file: Vec = url.encode_utf16().chain(std::iter::once(0)).collect(); let said = unsafe { ShellExecuteW( std::ptr::null_mut(), op.as_ptr(), file.as_ptr(), std::ptr::null(), std::ptr::null(), SW_SHOWNORMAL, ) }; (said as isize) > 32 } /// Best-effort version of the system for a bug report (the field is optional). #[cfg(windows)] pub(crate) fn os_version() -> String { let mut ver = std::process::Command::new("cmd"); ver.args(["/C", "ver"]); crate::detach_console(&mut ver) .output() .ok() .and_then(|o| String::from_utf8(o.stdout).ok()) .map(|s| s.trim().to_string()) .unwrap_or_default() } /// The same away from Windows: the system's own name and version /// (`macOS 15.4 Sequoia`, `Linux 24.04 Ubuntu`) #[cfg(not(windows))] pub(crate) fn os_version() -> String { sysinfo::System::long_os_version().unwrap_or_default() } /// The GitHub "new bug report" URL, pre-filled with the build and OS so the /// reporter does not have to dig those out by hand. fn bug_report_url() -> String { let version = format!( "v{} (build {}, {})", env!("CARGO_PKG_VERSION"), env!("BUILD_TIME"), env!("BUILD_REV") ); format!( "https://github.com/styleio/ShikishaTerm/issues/new?template=bug_report.yml&version={}&windows={}", pct(&version), pct(&os_version()) ) } /// Runs ` --help` and returns its output, for the settings "Show flags" /// button. Asking the tool itself keeps the list accurate for whatever version /// is installed, with no per-CLI knowledge to maintain. Bounded by a timeout so /// a command that treats --help as "start" can't hang the settings page. fn cli_help(prog: &str) -> Result { use std::process::{Command, Stdio}; use std::sync::mpsc; use std::time::Duration; if prog.trim().is_empty() { return Err(String::new()); } // Started exactly like a tab launch: PATH + .exe/.cmd/.bat, and a shim // (how npm installs claude/gemini/…) the way a tab starts it. A bare // Command::new("claude") only looks for claude.exe and reports "not found". // An empty error string tells the page to show its own "is it installed?" note. if crate::tab::resolve_command(prog).is_none() { return Err(String::new()); } let argv = crate::tab::launch_argv(&[prog.to_string(), "--help".into()]); let mut cmd = Command::new(&argv[0]); cmd.args(&argv[1..]); for name in crate::tab::STARTER_ENV { cmd.env_remove(name); } cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); crate::detach_console(&mut cmd); let (tx, rx) = mpsc::channel(); std::thread::spawn(move || { let _ = tx.send(cmd.output()); }); match rx.recv_timeout(Duration::from_secs(8)) { Ok(Ok(out)) => { let mut s = String::from_utf8_lossy(&out.stdout).into_owned(); // Some tools print their help to stderr instead. if s.trim().is_empty() { s = String::from_utf8_lossy(&out.stderr).into_owned(); } Ok(s) } Ok(Err(e)) => Err(e.to_string()), Err(_) => Err("timed out".into()), } } /// Safely resolves the ?file=... path. /// Only allows .json files under the same directory as the config file, /// and rejects absolute paths or parent-directory references (..) (path traversal countermeasure) fn safe_desk_path( url: &str, config_path: &std::path::Path, ) -> Option { let raw = url .split_once('?')? .1 .split('&') .find_map(|kv| kv.strip_prefix("file="))?; safe_desk_file(&percent_decode(raw), config_path) } /// A desk definition file named as the settings page names it: a `.json` /// beside the settings file or under it, never above it nor anywhere else fn safe_desk_file(rel: &str, config_path: &std::path::Path) -> Option { let rel = std::path::Path::new(rel); if rel.is_absolute() { return None; } if rel .components() .any(|c| matches!(c, std::path::Component::ParentDir | std::path::Component::Prefix(_))) { return None; } if rel.extension().and_then(|e| e.to_str()) != Some("json") { return None; } let base = config_path.parent()?; Some(base.join(rel)) } /// Safely resolves the automation folder path (version without extension checking) fn safe_dir_path(url: &str, _config_path: &std::path::Path) -> Option { let raw = url .split_once('?')? .1 .split('&') .find_map(|kv| kv.strip_prefix("dir="))?; let decoded = percent_decode(raw); let rel = std::path::Path::new(&decoded); if rel.is_absolute() || decoded.is_empty() { return None; } if rel.components().any(|c| { matches!( c, std::path::Component::ParentDir | std::path::Component::Prefix(_) ) }) { return None; } // Uses the same resolution as the main app's automation loader: the layout root first, then beside the exe. // If this drifts, you get "the GUI says it's unconfigured but it actually runs" / "editing in the GUI has no effect" Some(crate::config::resolve_data_path(&decoded)) } /// The manual is embedded in the exe. It can always be referenced regardless of where it's /// launched from, and won't break even if the docs are forgotten in the distribution. /// To bundle a translation into the exe, add one line here (it's still read if placed in docs/ instead) const EMBEDDED_MANUALS: &[(&str, &str)] = &[ ("en", include_str!("../../../docs/AUTOMATION.md")), ("ja", include_str!("../../../docs/AUTOMATION.ja.md")), ]; /// Prefers a file placed alongside it, if any (so the user can add to it). /// Looks in order: localized version (AUTOMATION..md) → English → embedded fn load_manual(config_path: &std::path::Path) -> String { let mut dirs: Vec = Vec::new(); if let Some(d) = config_path.parent() { dirs.push(d.to_path_buf()); } dirs.push(crate::config::shipped_dir()); dirs.push(std::path::PathBuf::from(".")); let lang = crate::i18n::lang(); let mut names = Vec::new(); if lang != "en" { names.push(format!("AUTOMATION.{lang}.md")); } names.push("AUTOMATION.md".to_string()); for name in &names { for d in &dirs { for rel in [d.join("docs").join(name), d.join(name)] { if let Ok(s) = std::fs::read_to_string(rel) && !s.trim().is_empty() { return s; } } } } let embedded = |code: &str| EMBEDDED_MANUALS.iter().find(|(c, _)| *c == code).map(|(_, m)| *m); embedded(&lang).or_else(|| embedded("en")).unwrap_or_default().to_string() } /// Computes the remote UI status that should be displayed. /// If the main app is listening, uses that info; otherwise builds the connection /// info from config (so a QR code can still be shown when only settings is open, or right after enabling it) fn effective_remote(shared: &Arc>) -> RemoteInfo { let info = shared.lock().unwrap().clone(); if info.running && !info.url.is_empty() { return info; } let Some(c) = crate::config::load().filter(|c| c.remote.enabled) else { return RemoteInfo::default(); }; match crate::netaddr::resolve_bind(&c.remote.bind, c.remote.allow_public) { Ok((ip, _)) => RemoteInfo { running: true, url: format!( "http://{ip}:{}/?t={}", c.remote.port, crate::remote_token(&c, None) ), note: crate::i18n::t("settings.phone.only_while_running"), ..Default::default() }, Err(e) => RemoteInfo { running: false, url: String::new(), note: e, ..Default::default() }, } } /// The connection info the phone card is drawn from: the stand-in laid out for /// a promotional shot (`netaddr::demo_link`) when there is one, otherwise the /// real thing. The card is drawn as running in that case — there is a link to /// show, which is the only question this screen asks. fn remote_for_display(shared: &Arc>) -> (RemoteInfo, bool) { match crate::netaddr::demo_link() { Some(url) => ( RemoteInfo { running: true, url, note: String::new(), ..Default::default() }, true, ), None => (effective_remote(shared), false), } } /// Turns the chosen path into the form written to config. /// If it's under the config folder, makes it relative so the whole folder stays portable fn display_path(path: &std::path::Path, config_path: &std::path::Path) -> String { config_path .parent() .and_then(|base| path.strip_prefix(base).ok()) .map(|rel| rel.to_string_lossy().into_owned()) .unwrap_or_else(|| path.to_string_lossy().into_owned()) .replace('\\', "/") } /// The place to open first. ~/.ssh for a key, the config's location for a folder fn default_pick_dir(kind: &str, config_path: &std::path::Path) -> Option { if kind == "key" && let Some(home) = crate::home_dir() { let ssh = home.join(".ssh"); if ssh.is_dir() { return Some(ssh); } return Some(home); } config_path.parent().map(std::path::Path::to_path_buf) } /// Event files read/written from the settings screen. /// Both the session's and the browser's const EVENT_FILES: [&str; 8] = [ "on_start", "on_done", "on_question", "on_exit", "on_busy", "on_load", "on_press", "_shared", ]; /// Runs a locally installed AI CLI one-shot to generate Lua code. /// No API key needed (uses the user's subscription auth as-is). /// The generated result is always shown on screen and never saved until the user approves it /// Supported AI CLIs (name, non-interactive execution args, display name) const AI_ENGINES: [(&str, &[&str], &str); 3] = [ ("claude", &["-p"], "Claude Code"), ("codex", &["exec"], "Codex CLI"), ("gemini", &["-p", ""], "Gemini CLI"), ]; /// Turns the tab layout into descriptive text. Passed so the AI knows the destination number /// (since the user should be able to give instructions by tab name) fn describe_tabs(parsed: &serde_json::Value) -> String { let Some(tabs) = parsed.get("tabs").and_then(|v| v.as_array()) else { return String::new(); }; if tabs.is_empty() { return String::new(); } let me = parsed.get("self").and_then(|v| v.as_u64()).unwrap_or(0); let mut s = crate::i18n::t("ai.tabs.header"); s.push('\n'); for t in tabs { let i = t.get("index").and_then(|v| v.as_u64()).unwrap_or(0); let name = t.get("name").and_then(|v| v.as_str()).unwrap_or(""); let id = t.get("id").and_then(|v| v.as_str()).unwrap_or(""); // The name is there so the AI can tell which tab is which; the id is // the only thing that will actually reach it (see hooks::TabKey) s.push_str(&format!( "{i}. {name}{}", crate::i18n::tp("ai.tabs.id", &[("id", id)]) )); if i == me { s.push_str(&crate::i18n::t("ai.tabs.self")); } s.push('\n'); } s } fn generate_with_local_ai( event: &str, want: &str, layout: &str, engine: Option<&str>, config_path: &std::path::Path, ) -> Result { if want.trim().is_empty() { anyhow::bail!("{}", crate::i18n::t("automation.editor.want")); } // Pass the manual to the AI as a spec (the custom API isn't in its training data) let manual = load_manual(config_path); // Fix the output format with markers so it doesn't just reply with conversational text let prompt = crate::i18n::fill( crate::asking::AUTOMATION, &[ ("event", event), ("want", want), ("layout", layout), ("manual", &manual), ], ); let text = ask_local_ai(&prompt, engine)?; extract_lua(&text) } /// Have the assistant AI untangle one conflicted file. /// /// It is handed the file exactly as git left it -- both sides and the markers -- /// and gives back what the file should be. Nothing here decides that the answer /// is right: it is written to the working tree, where the person reads it as a /// diff and stages it, or throws it away. Proposing is the AI's half. pub fn resolve_conflict(name: &str, body: &str, engine: Option<&str>) -> Result { if !body.contains("<<<<<<<") { anyhow::bail!("{}", crate::i18n::tp("err.git.no_markers", &[("file", name)])); } // A file with a conflict in it is usually ordinary in size; one that is not // is not something to send half of, because half a file written back is // worse than the conflict const ROOM: usize = 60_000; if body.chars().count() > ROOM { anyhow::bail!("{}", crate::i18n::tp("err.git.too_big", &[("file", name)])); } let prompt = crate::i18n::fill(crate::asking::UNTANGLE, &[("file", name), ("body", body)]); let said = ask_local_ai(&prompt, engine)?; let text = strip_fence(&said); if text.trim().is_empty() { anyhow::bail!("{}", crate::i18n::tp("err.git.no_answer", &[("file", name)])); } if text.contains("<<<<<<<") || text.contains(">>>>>>>") { anyhow::bail!("{}", crate::i18n::tp("err.git.markers_left", &[("file", name)])); } Ok(text) } /// What a model says, minus the way models like to wrap it. A fenced block is /// taken as the answer; anything outside one is dropped, because a file that /// begins "Here is the resolved version:" does not compile fn strip_fence(said: &str) -> String { let text = said.trim(); let Some(start) = text.find("```") else { return text.to_string(); }; let after = &text[start + 3..]; // The rest of the fence line is the language, not content let body = match after.find('\n') { Some(nl) => &after[nl + 1..], None => "", }; match body.rfind("```") { Some(end) => body[..end].trim_end_matches('\n').to_string(), None => body.to_string(), } } /// Run the assistant AI once with this prompt on its standard input. /// /// The three things that ask an AI something -- write me Lua, suggest me a /// command, write me a commit message -- differ in what they ask and in /// nothing else. Spawning it lived in each of them until there were three pub fn ask_local_ai(prompt: &str, engine: Option<&str>) -> Result { let name = which_assistant(engine)?; // Asked the confined way first: an empty folder of its own, no tools, no // hooks, nothing to reach. Everything asked from this program is a // question -- none of it is a job -- and an assistant AI handed a // question in a project folder treats it as one. Asked why something had // stopped, one of them went and changed code and then said it had fixed // it, which is the whole reason this is written the way it is match ask_confined(name, prompt, ASK_SYSTEM, None, ASK_TIMEOUT) { Ok(said) => Ok(said), // An older CLI that does not know one of those options would fail // outright, and a question that cannot be asked at all is worse than // one asked with fewer walls. It still runs where the confined one // does -- an empty folder, nothing of the person's within reach -- // and the instruction rides in the question instead of in a flag Err(e) => { crate::append_hook_log(&format!( "a confined {name} call failed, asking with the plain options: {e:#}" )); ask_in_own_folder_plainly(name, prompt) } } } /// What every one-off question is told it is for. Not a prompt about any /// particular question -- the one thing true of all of them const ASK_SYSTEM: &str = "You are answering a question, not carrying out a task. Everything you need is in the message. Do not change, create, run or open anything."; /// How long a one-off question may take before it is abandoned const ASK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(180); /// The last resort: the CLI's plain options, still in a folder of its own. /// /// Fewer walls than [`ask_confined`] -- this one cannot promise the AI has no /// tools -- but not none: it is started somewhere empty, so what it can see /// is what it was given. Reached only when the confined way would not run fn ask_in_own_folder_plainly(name: &str, prompt: &str) -> Result { let (_, args, _) = AI_ENGINES .iter() .find(|(n, _, _)| *n == name) .with_context(|| crate::i18n::tp("webui.err.ai_not_found", &[("name", name)]))?; let args: Vec = args.iter().map(|s| s.to_string()).collect(); // No flag for it here, so the instruction goes where it cannot be refused let asked = format!("{ASK_SYSTEM}\n\n{prompt}"); let files: [(&str, &[u8]); 1] = [(CLAUDE_SETTINGS_FILE, br#"{"disableAllHooks": true}"#)]; let ran = run_in_own_folder(name, args, asked, &files, &[], ASK_TIMEOUT)?; if !ran.ok { let why: String = ran.err.trim().chars().take(300).collect(); anyhow::bail!("{}", crate::i18n::tp("ai.err.failed", &[("cmd", &ran.cmd), ("error", &why)])); } Ok(ran.out) } /// One-shot "natural language → one shell command" via the assistant AI /// (config's ai_engine, auto-detected when unset). The terminal's own launch /// command and recent screen ride along as the environment fingerprint: the /// prompt string, login banners, and recent output tell the model whether /// it's cmd / PowerShell / bash and which OS or distro sits behind an SSH — /// no probing protocol required pub fn suggest_with_local_ai( want: &str, shell: &str, screen: &str, env: &str, engine: Option<&str>, ) -> Result { if want.trim().is_empty() { anyhow::bail!("{}", crate::i18n::t("ai.suggest.want")); } // The environment card (🩺's captured survey) outranks screen guesswork let env_block = if env.trim().is_empty() { crate::asking::NO_SURVEY.to_string() } else { env.to_string() }; let prompt = crate::i18n::fill( crate::asking::ONE_COMMAND, &[("want", want), ("shell", shell), ("screen", screen), ("env", &env_block)], ); extract_cmd(&ask_local_ai(&prompt, engine)?) } /// Extracts the contents of <<>> (falling back to a lone code /// fence). Conversational text must never be typed into a terminal as-is fn extract_cmd(text: &str) -> Result { if let Some((_, rest)) = text.split_once("<<>>").map(|(b, _)| b).unwrap_or(rest); let cmd = body.trim(); if !cmd.is_empty() { return Ok(cmd.to_string()); } } if let Some((_, rest)) = text.split_once("```") && let Some((body, _)) = rest.split_once("```") { let body = body.trim_start_matches(|c: char| c.is_ascii_alphanumeric()); let cmd = body.trim(); if !cmd.is_empty() { return Ok(cmd.to_string()); } } anyhow::bail!("{}", crate::i18n::t("ai.suggest.no_cmd")) } /// Extracts the contents of <<>> from the AI's output. /// If there's no marker, strips a code fence and returns that instead; if there's no fence either, errors out /// (so conversational text doesn't get saved as code as-is) fn extract_lua(text: &str) -> Result { if let Some((_, rest)) = text.split_once("<<>>").map(|(b, _)| b).unwrap_or(rest); return Ok(body.trim().to_string()); } let stripped = strip_code_fence(text); // Minimum bar for "looks like code": contains shikisha.* or tab. if stripped.contains("shikisha.") || stripped.contains("tab.") { return Ok(stripped); } anyhow::bail!( "{}", crate::i18n::tp( "ai.err.no_code", &[("reply", &text.trim().chars().take(120).collect::())] ) ) } /// What the AI that would answer is called, as a person would name it -- /// "Claude Code" -- found the same way as the program itself. None when there /// is none to run pub fn local_ai_label(want: Option<&str>) -> Option<&'static str> { AI_ENGINES .iter() .filter(|(name, _, _)| want.is_none_or(|w| w == *name)) .find(|(name, _, _)| crate::tab::resolve_command(name).is_some()) .map(|(_, _, label)| *label) } /// How to start an installed AI program with `args`, the way a tab starts it fn launcher(name: &str, args: Vec) -> Option<(String, Vec)> { crate::tab::resolve_command(name)?; let mut argv = crate::tab::launch_argv(&[vec![name.to_string()], args].concat()); let program = argv.remove(0); Some((program, argv)) } /// The assistant AI that answers when one is asked for: the one chosen under /// Basic > Assistant AI, or with none chosen the first one installed. Its name /// and the name a person knows it by; nothing when it is not installed. /// /// The same order and the same test [`pick_local_ai`] uses, so the AI a tool /// says it will send to is the AI that is started pub fn assistant_ai(want: Option<&str>) -> Option<(&'static str, &'static str)> { AI_ENGINES .iter() .find(|(name, _, _)| want.is_none_or(|w| w == *name) && installed_lately(name)) .map(|(name, _, label)| (*name, *label)) } /// For how long an answer to "is this AI installed" is taken to still hold const INSTALLED_HOLDS: std::time::Duration = std::time::Duration::from_secs(5); /// Whether an AI's program is installed, as found within the last few /// seconds. /// /// Finding it means asking the disk about every folder on the PATH, for /// each ending a program can have: a few hundred questions. The work loop /// asks which assistant AI there is each time it says what the screen /// shows, sixty times a second, and asked afresh each time that was a third /// of all the loop did while nothing was happening -- and far more on a /// machine whose PATH is long, or whose disk is busy, where every one of /// those questions waits its turn and the whole window with it. An AI /// installed or taken off shows within these few seconds fn installed_lately(name: &str) -> bool { static FOUND: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); // (a test changes what is installed and asks again at once) let holds = if cfg!(test) { std::time::Duration::ZERO } else { INSTALLED_HOLDS }; let kept = FOUND.lock().unwrap_or_else(|e| e.into_inner()).iter().find(|(n, at, _)| n == name && at.elapsed() < holds).map(|(_, _, there)| *there); if let Some(there) = kept { return there; } // Looked for with nothing held: a folder on the PATH that is slow to // answer holds up whoever asks about this AI, and nobody asking about // another whose answer is already kept let there = crate::tab::resolve_command(name).is_some(); let mut found = FOUND.lock().unwrap_or_else(|e| e.into_inner()); found.retain(|(n, _, _)| n != name); found.push((name.to_string(), std::time::Instant::now(), there)); there } /// What the first-start setup offers: the assistant AIs, the installed ones to /// pick from and the rest with the way to install them, and whether GitHub CLI /// is here. The same list, in the same order, as Basic > Assistant AI, since /// that is where the pick is kept. pub fn setup_state() -> crate::uistate::SetupState { setup_state_of( |name| crate::tab::resolve_command(name).is_some(), |name| install_page(name).is_some(), ) } /// [`setup_state`], asked about a machine described rather than this one fn setup_state_of(installed: impl Fn(&str) -> bool, has_page: impl Fn(&str) -> bool) -> crate::uistate::SetupState { let mut out = crate::uistate::SetupState { gh: installed("gh"), ..Default::default() }; for (name, _, label) in AI_ENGINES { let ai = crate::uistate::SetupAi { id: name.to_string(), name: label.to_string(), install: has_page(name) }; match installed(name) { true => out.installed.push(ai), false => out.missing.push(ai), } } out } /// The name a person knows an assistant AI by, from its name in the settings pub fn assistant_label(name: &str) -> Option<&'static str> { AI_ENGINES.iter().find(|(n, _, _)| *n == name).map(|(_, _, label)| *label) } /// The name a picture is written under for the AIs that are handed a file. const PICTURE_FILE: &str = "picture.png"; /// The name the shape of the answer is written under, for the AI that reads it /// from a file. const SCHEMA_FILE: &str = "answer.schema.json"; /// How long an AI is given to read a picture before it is stopped. The slowest /// of the three took half a minute on a first run (2026-09-14); a minute and /// a half beyond that is somebody's network, not a program still thinking const PICTURE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120); /// What to start an assistant AI with so it reads one picture and answers /// `prompt` about it in the shape `schema` (a JSON Schema): the arguments /// after the program, what goes in on standard input, and whether the picture /// has to be on disk beside it. /// /// Two of the three hold the answer to the shape themselves -- Claude Code /// with `--json-schema`, Codex CLI with `--output-schema` -- and Gemini CLI has /// nothing of the kind, so for it the prompt is all there is. Whoever calls /// this reads the answer as that shape and asks again when it is not one. /// /// None of the three is given a way to reach anything but the picture. Text /// on a screen can say anything, "read this file and write it out" included, /// and the picture is exactly that text. Measured 2026-09-14, each returning /// the text of the test picture exactly, in about six seconds: /// - Claude Code takes the picture inside the message itself (stream-json) and /// runs with no tools at all /// - Codex CLI attaches it with `-i`, its commands held to read-only /// - Gemini CLI reads it with `@file`, in its read-only (plan) mode /// /// A picture goes to an AI only from the tools, and only from a desk that /// agreed to it -- that is decided in `snip.rs`, before this is ever reached fn picture_invocation(name: &str, prompt: &str, png: &[u8], schema: &str) -> Option<(Vec, String, bool)> { use base64::Engine as _; let v = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::>(); match name { "claude" => { let data = base64::engine::general_purpose::STANDARD.encode(png); let msg = serde_json::json!({ "type": "user", "message": {"role": "user", "content": [ {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": data}}, {"type": "text", "text": prompt}, ]}, }); Some(( v(&["-p", "--tools", "", "--json-schema", schema, "--input-format", "stream-json", "--output-format", "stream-json", "--verbose"]), format!("{msg}\n"), false, )) } "codex" => Some(( v(&["exec", "--skip-git-repo-check", "--sandbox", "read-only", "--output-schema", SCHEMA_FILE, "-i", PICTURE_FILE, "-"]), prompt.to_string(), true, )), "gemini" => Some(( v(&["--approval-mode", "plan", "-p", &format!("@{PICTURE_FILE}")]), prompt.to_string(), true, )), _ => None, } } /// Whether an assistant AI is one that is known to read a picture pub fn reads_pictures(name: &str) -> bool { picture_invocation(name, "", &[], "{}").is_some() } /// What an AI said, out of what it printed. Claude Code prints a line of JSON /// per event and the answer is in the last one -- the shaped answer, when it /// gave one, beside its text; the others print the answer fn picture_answer(name: &str, out: &str) -> Result { if name != "claude" { return Ok(out.trim().to_string()); } let done = out .lines() .filter_map(|l| serde_json::from_str::(l.trim()).ok()) .rfind(|v| v.get("type").and_then(|t| t.as_str()) == Some("result")) .context(crate::i18n::t("snip.ai.no_answer"))?; let text = done.get("result").and_then(|r| r.as_str()).unwrap_or_default().trim().to_string(); if done.get("is_error").and_then(|e| e.as_bool()).unwrap_or(false) { anyhow::bail!("{text}"); } Ok(match done.get("structured_output") { Some(shaped) if !shaped.is_null() => shaped.to_string(), _ => text, }) } /// Ask the assistant AI `name` about one picture, and wait for its answer, /// asked for in the shape `schema` (see [`picture_invocation`]). What comes /// back is the AI's answer as it gave it, to be read by the caller. /// /// The AI is started in a folder of its own with nothing else in it -- the /// picture, when that AI is handed a file, and the shape -- and the folder is /// gone again once it is done. Stopped after [`PICTURE_TIMEOUT`] pub fn ask_about_picture(name: &str, prompt: &str, png: &[u8], schema: &str) -> Result { let (args, input, on_disk) = picture_invocation(name, prompt, png, schema) .with_context(|| crate::i18n::tp("webui.err.ai_not_found", &[("name", name)]))?; let mut files: Vec<(&str, &[u8])> = vec![(SCHEMA_FILE, schema.as_bytes())]; if on_disk { files.push((PICTURE_FILE, png)); } let ran = run_in_own_folder(name, args, input, &files, &[], PICTURE_TIMEOUT)?; if !ran.ok { // Claude Code says what went wrong in its answer, not on stderr let said = picture_answer(name, &ran.out).err().map(|e| e.to_string()).unwrap_or_default(); let why = if ran.err.trim().is_empty() { said } else { ran.err.trim().to_string() }; anyhow::bail!("{}", crate::i18n::tp("ai.err.failed", &[("cmd", &ran.cmd), ("error", &why)])); } picture_answer(name, &ran.out) } /// What an AI started by [`run_in_own_folder`] left behind struct Ran { /// The program that was started, for saying which one failed cmd: String, ok: bool, out: String, err: String, } /// Start the assistant AI `name` once, in a folder of its own that holds only /// `files`, with `input` on its standard input, and stop it after `timeout`. /// /// A folder of its own for two reasons. Nothing the AI reads can reach past /// what it was handed -- and a project's instructions to its agents /// (CLAUDE.md, AGENTS.md, GEMINI.md) are not read in either, which is also /// much of what a one-line answer would otherwise be charged for. And whatever /// it writes beside itself is gone with the folder fn run_in_own_folder( name: &str, args: Vec, input: String, files: &[(&str, &[u8])], env: &[(&str, String)], timeout: std::time::Duration, ) -> Result { use std::io::Write as _; let dir = std::env::temp_dir() .join("shikisha-term") .join("ask") .join(crate::random_hex(8)); // `{dir}` in an argument or a variable is that folder: a file named from // it is read the same whether the program resolves names against where it // stands or against its own settings folder let at = dir.display().to_string(); let args = args.into_iter().map(|a| a.replace("{dir}", &at)).collect(); let (cmd, args) = launcher(name, args) .with_context(|| crate::i18n::tp("webui.err.ai_not_found", &[("name", name)]))?; std::fs::create_dir_all(&dir)?; struct Gone(std::path::PathBuf); impl Drop for Gone { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } } let _gone = Gone(dir.clone()); for (file, body) in files { std::fs::write(dir.join(file), body)?; } let mut spawner = std::process::Command::new(&cmd); // A CLI asked one question from here is nobody's child session for name in crate::tab::STARTER_ENV { spawner.env_remove(name); } spawner .args(&args) .current_dir(&dir) .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()); for (k, v) in env { spawner.env(k, v.replace("{dir}", &at)); } // The way in a tab's programs report through. An AI the app asks something // is not a tab, and its hooks must not speak for one spawner.env_remove(crate::api::ENV_PIPE); // Inheriting the console here would kill the mouse (same reason as open_browser) let mut child = crate::detach_console(&mut spawner) .spawn() .with_context(|| crate::i18n::tp("ai.err.cannot_run", &[("cmd", &cmd)]))?; // Each pipe on a thread of its own: a picture is megabytes going in, and an // AI that fills its output while its input is still being written would // otherwise wait on this side for good let mut stdin = child.stdin.take().context(crate::i18n::t("webui.err.stdin"))?; let feed = std::thread::spawn(move || { let _ = stdin.write_all(input.as_bytes()); }); fn drain(pipe: Option) -> std::thread::JoinHandle> { std::thread::spawn(move || { let mut buf = Vec::new(); if let Some(mut p) = pipe { let _ = p.read_to_end(&mut buf); } buf }) } let out = drain(child.stdout.take()); let err = drain(child.stderr.take()); let started = std::time::Instant::now(); let status = loop { if let Some(status) = child.try_wait()? { break status; } if started.elapsed() > timeout { let _ = child.kill(); let _ = child.wait(); anyhow::bail!( "{}", crate::i18n::tp("snip.ai.timeout", &[("seconds", &timeout.as_secs().to_string())]) ); } std::thread::sleep(std::time::Duration::from_millis(100)); }; let _ = feed.join(); Ok(Ran { cmd, ok: status.success(), out: String::from_utf8_lossy(&out.join().unwrap_or_default()).to_string(), err: String::from_utf8_lossy(&err.join().unwrap_or_default()).to_string(), }) } /// What the AI giving a short answer is told it is, in place of each CLI's own /// instructions for working on code -- thousands of tokens about tools it is /// not given const LIGHT_SYSTEM: &str = "You give one short reply containing only what is asked for. You have no tools and need none."; /// The file those instructions are written to, beside the AI const SYSTEM_FILE: &str = "system.md"; /// The settings file Claude Code is pointed at: its hooks off, so a question /// the app asks is not reported back to the app as a person's request const CLAUDE_SETTINGS_FILE: &str = "settings.json"; /// How long a short answer is waited for. Measured 2026-09-17 at one to seven /// seconds for each of the three; the rest is a slow network or a first start const LIGHT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(90); /// How an assistant AI is started: its arguments, and what goes into its /// environment (`{dir}` in either is the folder it runs in) type Invocation = (Vec, Vec<(&'static str, String)>); /// What to start an assistant AI with for a short answer that costs as little /// as it can: the arguments after the program, and what goes in its /// environment. The prompt goes in on standard input; the instructions are in /// [`SYSTEM_FILE`] beside it. Files rather than arguments, because two of the /// three are started through cmd.exe, which takes quotes apart. /// /// Everything a CLI loads for working on code is left out: its tools, its /// connected servers and plugins, its long instructions, its thinking, its /// hooks. Its conversation is not kept, so these do not turn up in the list of /// conversations to resume. Measured 2026-09-17 on a request for a name and a /// summary, against the same CLI started plainly: /// - Claude Code: about 1,400 tokens instead of 9,500. Its smallest model /// - Codex CLI: about 4,500 instead of 15,400. Low reasoning, read-only, no web /// search. Its model is the one the person chose: model names differ by /// account, and a wrong one is a failure rather than a saving. Features are /// turned off as settings rather than flags, because a flag it does not know /// stops it and a setting it does not know is passed over /// - Gemini CLI: about 2,800, where started plainly it spent turns looking /// through the folder with its tools. Read-only, its instructions replaced. /// Its own routing already sends a request this small to a small model /// /// `small` is the part a person can turn off (`summary_small_model`): the /// smallest model Claude Code has, and Codex's lowest reasoning. Everything /// else here stays whatever the answer is, because nothing else about it is a /// choice with two sides -- a name does not want tools, and nobody wants this /// in their list of conversations. Gemini is not asked either way: it routes a /// request this small itself, and naming a model there is a way to be wrong /// /// `schema` holds the AI to a shape for its answer, as a JSON Schema. Two of /// the three can be held to one, and each wants it a different way -- Claude /// Code takes it written out in the argument, Codex CLI takes the name of a /// file ([`SCHEMA_FILE`], which whoever asks has written beside it), and Gemini /// CLI has nothing of the kind, so for it the prompt is all there is. The same /// split as [`picture_invocation`], for the same reason: it is what each of /// them accepts. Whoever asks reads the answer as that shape and copes when it /// is not one /// /// `model`, when given, is the model it answers with, named the way that CLI /// names its models; it outranks `small`'s choice of model. Given only by /// whoever has been told a model by the person (see [`ask_installed`]), and /// only once [`model_name_fault`] has passed it fn light_invocation( name: &str, small: bool, model: Option<&str>, schema: Option<&str>, ) -> Option { let v = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::>(); match name { "claude" => { let mut args = v(&["-p"]); match model { Some(m) => args.extend(v(&["--model", m])), None if small => args.extend(v(&["--model", "haiku"])), None => {} } args.extend(v(&[ "--tools", "", "--no-session-persistence", "--strict-mcp-config", "--disable-slash-commands", "--settings", &format!("{{dir}}/{CLAUDE_SETTINGS_FILE}"), "--system-prompt-file", &format!("{{dir}}/{SYSTEM_FILE}"), ])); if let Some(shape) = schema { args.push("--json-schema".into()); args.push(shape.to_string()); } Some((args, vec![("MAX_THINKING_TOKENS", "0".to_string())])) } "codex" => { let mut args = v(&[ "exec", "--ephemeral", "--skip-git-repo-check", "--sandbox", "read-only", "--color", "never", "-c", "web_search=disabled", "-c", "mcp_servers={}", ]); if let Some(m) = model { args.extend(v(&["--model", m])); } if small { args.push("-c".into()); args.push("model_reasoning_effort=low".into()); } args.push("-c".into()); args.push(format!("model_instructions_file={{dir}}/{SYSTEM_FILE}")); if schema.is_some() { args.push("--output-schema".into()); args.push(format!("{{dir}}/{SCHEMA_FILE}")); } for feature in [ "apps", "browser_use", "computer_use", "image_generation", "goals", "hooks", "multi_agent", "plugins", "shell_tool", "sleep_tool", "tool_suggest", "unified_exec", "view_image", "skill_search", "personality", "memories", "in_app_browser", ] { args.push("-c".into()); args.push(format!("features.{feature}=false")); } args.push("-".into()); Some((args, Vec::new())) } "gemini" => { let mut args = v(&["--extensions", "none", "--allowed-mcp-server-names", "none", "--approval-mode", "plan"]); if let Some(m) = model { args.extend(v(&["--model", m])); } args.extend(v(&["-p", ""])); Some((args, vec![("GEMINI_SYSTEM_MD", format!("{{dir}}/{SYSTEM_FILE}"))])) } _ => None, } } /// Whether [`light_invocation`] can hold this AI to a shape by itself. The one /// that cannot is told the shape in its instructions instead (see /// [`ask_confined_as`]), which is all there is for it fn holds_shape(name: &str) -> bool { matches!(name, "claude" | "codex") } /// Why a model name cannot be handed to an installed AI, or `None` when it /// can. Two of the three are started through cmd.exe, which reads `&`, `|`, /// `%` and quotes as its own; a model's name never needs any of them, so a /// name is held to what model names are written with /// (`haiku`, `gpt-5-codex`, `gemini-2.5-flash`, `sonnet[1m]`) pub fn model_name_fault(model: &str) -> Option { let ok = !model.is_empty() && model.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | ':' | '[' | ']')); (!ok).then(|| crate::i18n::tp("err.choose.bad_model_name", &[("model", model)])) } /// Ask the assistant AI for a short answer, as cheaply as it can be asked /// ([`light_invocation`]). /// /// When the light way fails -- an older CLI that does not know one of its /// options -- it is asked once more the ordinary way. A name a folder waits a /// few seconds longer for is better than no name at all pub fn ask_local_ai_light(prompt: &str, engine: Option<&str>) -> Result { let (name, _) = assistant_ai(engine).with_context(|| match engine { Some(w) => crate::i18n::tp("webui.err.ai_not_found", &[("name", w)]), None => crate::i18n::t("webui.err.ai_missing"), })?; match ask_light_once(name, prompt) { Ok(said) => Ok(said), Err(e) => { crate::append_hook_log(&format!("a light {name} call failed, asking the ordinary way: {e:#}")); // Still confined: `ask_local_ai` runs in a folder of its own // whichever way it ends up asking ask_local_ai(prompt, Some(name)) } } } /// Ask the assistant AI for an answer in a shape, the light way. /// /// Told what it is for in `system`, rather than the one line a name or a tidy /// gets: this carries a question somebody typed, and the AI has to know what /// it is looking at. What comes back is the AI's answer as it gave it -- JSON /// when it held to the shape, and whatever it said when it did not, which /// whoever asked has to cope with. pub fn ask_local_ai_shaped( prompt: &str, system: &str, schema: &str, engine: Option<&str>, timeout: std::time::Duration, ) -> Result { let name = which_assistant(engine)?; ask_confined(name, prompt, system, Some(schema), timeout) } /// [`ask_local_ai_shaped`], always on the assistant AI's own model: for a /// question somebody typed and is waiting to read the answer to (the ?). The /// smallest model is a setting about names (`summary_small_model`), and read /// with the whole manual in front of it, it lost a long question and answered /// that the manual did not say what it said. The full one took no longer pub fn ask_local_ai_answering( prompt: &str, system: &str, schema: &str, timeout: std::time::Duration, ) -> Result { let name = which_assistant(None)?; ask_confined_as(name, false, None, prompt, system, Some(schema), timeout) } /// Ask a question that needs no tools at all, and take prose back. /// /// For the questions where everything the AI needs is already in the prompt /// and the only thing wanted is an opinion on it. **It is given no tools and /// its own empty folder**, which is not a nicety: asked the ordinary way, an /// assistant AI reads the question as a job and sets about doing it. Asked /// why something had stopped, one of them went and changed code, then said /// it had fixed it pub fn ask_local_ai_confined( prompt: &str, system: &str, engine: Option<&str>, timeout: std::time::Duration, ) -> Result { let name = which_assistant(engine)?; ask_confined(name, prompt, system, None, timeout) } /// Ask the assistant AI a question it answers by reading a folder: given tools /// that read (find a file, search its contents, read it) and nothing else -- /// no editing, no command that changes anything, no network. For the ? /// searching this program's own source when the manual has no answer. /// /// Slower than [`ask_local_ai_shaped`] by design: it reads, one file after /// another, where that one only answers pub fn ask_reading( folder: &std::path::Path, prompt: &str, system: &str, schema: &str, timeout: std::time::Duration, ) -> Result { let name = which_assistant(None)?; let (args, env) = reading_invocation(name, &folder.display().to_string(), schema) .with_context(|| crate::i18n::tp("webui.err.ai_not_found", &[("name", name)]))?; let system = match holds_shape(name) { true => system.to_string(), false => format!("{system}\n\n{SHAPE_TOLD}\n{schema}"), }; let files: Vec<(&str, &[u8])> = vec![ (SYSTEM_FILE, system.as_bytes()), (CLAUDE_SETTINGS_FILE, br#"{"disableAllHooks": true}"#), (SCHEMA_FILE, schema.as_bytes()), ]; let ran = run_in_own_folder(name, args, prompt.to_string(), &files, &env, timeout)?; if !ran.ok || ran.out.trim().is_empty() { let why: String = ran.err.trim().chars().take(300).collect(); anyhow::bail!("{}", crate::i18n::tp("ai.err.failed", &[("cmd", &ran.cmd), ("error", &why)])); } Ok(ran.out) } /// How each assistant AI is started to read `folder` and nothing else. The /// same precautions as [`light_invocation`] -- no hooks, no MCP servers, no /// slash commands, nothing kept -- with the reading tools let in, and the /// folder named as one it may read fn reading_invocation( name: &str, folder: &str, schema: &str, ) -> Option { let v = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::>(); match name { "claude" => Some(( v(&[ "-p", "--tools", "Read,Grep,Glob", "--allowedTools", "Read,Grep,Glob", "--add-dir", folder, "--no-session-persistence", "--strict-mcp-config", "--disable-slash-commands", "--settings", &format!("{{dir}}/{CLAUDE_SETTINGS_FILE}"), "--system-prompt-file", &format!("{{dir}}/{SYSTEM_FILE}"), "--json-schema", schema, ]), Vec::new(), )), "codex" => { // Its reading is done with shell commands, which the read-only // sandbox lets look and never change anything let mut args = v(&[ "exec", "--ephemeral", "--skip-git-repo-check", "--sandbox", "read-only", "--color", "never", "-C", folder, "-c", "web_search=disabled", "-c", "mcp_servers={}", "-c", &format!("model_instructions_file={{dir}}/{SYSTEM_FILE}"), "--output-schema", &format!("{{dir}}/{SCHEMA_FILE}"), ]); for feature in [ "apps", "browser_use", "computer_use", "image_generation", "goals", "hooks", "multi_agent", "plugins", "sleep_tool", "tool_suggest", "view_image", "skill_search", "personality", "memories", "in_app_browser", ] { args.push("-c".into()); args.push(format!("features.{feature}=false")); } args.push("-".into()); Some((args, Vec::new())) } "gemini" => Some(( v(&[ "--extensions", "none", "--allowed-mcp-server-names", "none", "--approval-mode", "plan", "--include-directories", folder, "-p", "", ]), vec![("GEMINI_SYSTEM_MD", format!("{{dir}}/{SYSTEM_FILE}"))], )), _ => None, } } /// Which assistant AI answers, said the same way wherever it is asked fn which_assistant(engine: Option<&str>) -> Result<&'static str> { let (name, _) = assistant_ai(engine).with_context(|| match engine { Some(w) => crate::i18n::tp("webui.err.ai_not_found", &[("name", w)]), None => crate::i18n::t("webui.err.ai_missing"), })?; Ok(name) } /// One question, in a folder of its own, with no tools and no hooks. /// /// The one way this program asks an assistant AI anything that is not a /// conversation. Written once because the alternative is three copies of the /// same list of precautions, and the copy that forgets one is the copy that /// lets an AI loose in whatever folder the app happened to be started from fn ask_confined( name: &str, prompt: &str, system: &str, schema: Option<&str>, timeout: std::time::Duration, ) -> Result { // Asked of the settings here rather than handed down: every caller wants // the same answer, and one that reads it for itself cannot be the one // that forgets let small = crate::config::load().and_then(|c| c.summary_small_model).unwrap_or(true); ask_confined_as(name, small, None, prompt, system, schema, timeout) } /// [`ask_confined`], with the model decided by the caller: `small` as that /// setting says, `model` as the person named one fn ask_confined_as( name: &str, small: bool, model: Option<&str>, prompt: &str, system: &str, schema: Option<&str>, timeout: std::time::Duration, ) -> Result { let (args, env) = light_invocation(name, small, model, schema) .with_context(|| crate::i18n::tp("webui.err.ai_not_found", &[("name", name)]))?; // The one that cannot be held to a shape is told it, where it cannot be // missed. Whoever asked still reads the answer leniently let system = match schema { Some(shape) if !holds_shape(name) => format!("{system}\n\n{SHAPE_TOLD}\n{shape}"), _ => system.to_string(), }; let mut files: Vec<(&str, &[u8])> = vec![ (SYSTEM_FILE, system.as_bytes()), (CLAUDE_SETTINGS_FILE, br#"{"disableAllHooks": true}"#), ]; if let Some(shape) = schema { files.push((SCHEMA_FILE, shape.as_bytes())); } let ran = run_in_own_folder(name, args, prompt.to_string(), &files, &env, timeout)?; if !ran.ok || ran.out.trim().is_empty() { let why: String = ran.err.trim().chars().take(300).collect(); anyhow::bail!("{}", crate::i18n::tp("ai.err.failed", &[("cmd", &ran.cmd), ("error", &why)])); } Ok(ran.out) } /// What an AI that cannot be held to a shape is told about it, before the shape const SHAPE_TOLD: &str = "Answer with a single JSON value that matches this JSON Schema, and nothing else:"; /// How long an installed AI is given to answer a page-driving question: a /// whole page goes in, and a large model reading one takes its time pub const INSTALLED_TIMEOUT: std::time::Duration = ASK_TIMEOUT; /// Ask the installed AI `name` (`claude`, `codex`, `gemini`) the way a model /// connection is asked, on the person's own subscription: `prompt` under /// `system`, the answer held to `schema` when there is one, with `model` or, /// left out, the model that AI uses by itself. /// /// Asked the confined way ([`ask_confined`]): an empty folder, no tools, no /// hooks, nothing kept. The page it is shown is data it judges, and an AI /// given tools and a page that says "delete this" is an AI that might pub fn ask_installed( name: &str, model: Option<&str>, prompt: &str, system: Option<&str>, schema: Option<&str>, ) -> Result { if let Some(why) = model.and_then(model_name_fault) { anyhow::bail!("{why}"); } let name = which_assistant(Some(name))?; let system = system.filter(|s| !s.trim().is_empty()).unwrap_or(ASK_SYSTEM); ask_confined_as(name, false, model, prompt, system, schema, INSTALLED_TIMEOUT) } /// The light way alone, with nothing to fall back on fn ask_light_once(name: &str, prompt: &str) -> Result { ask_confined(name, prompt, LIGHT_SYSTEM, None, LIGHT_TIMEOUT) } /// Strips the code fence AIs tend to add fn strip_code_fence(s: &str) -> String { let t = s.trim(); let Some(rest) = t.strip_prefix("```") else { return t.to_string(); }; let rest = rest.strip_prefix("lua").unwrap_or(rest); rest.trim_start_matches('\n') .rsplit_once("```") .map(|(body, _)| body) .unwrap_or(rest) .trim() .to_string() } /// Whether a replay.lua holds anything actually replayable (not just the /// header comments an empty run leaves behind) fn has_replay_code(text: &str) -> bool { text.lines() .any(|l| !l.trim().is_empty() && !l.trim_start().starts_with("--")) } use crate::urlcodec::decode_query as percent_decode; /// Responds with JSON /// Add privacy headers: keep the URL token out of the Referer header on any /// outbound request, and out of any on-disk cache (shared-computer hygiene). fn secure(resp: Response) -> Response { resp.with_header(Header::from_bytes(&b"Referrer-Policy"[..], &b"no-referrer"[..]).unwrap()) .with_header(Header::from_bytes(&b"Cache-Control"[..], &b"no-store"[..]).unwrap()) } /// A page with its placeholders (`__NAME__`) filled, each from `values`, in /// one pass over the page as written. /// /// One pass, not one `replace` a placeholder: a value filled in is the /// person's words as often as the app's -- a project's name among them -- and /// a later `replace` reached into it. A project called `__DICT__` had the /// whole dictionary poured into its name, and the page's script no longer /// parsed. Only what the page itself says is a placeholder; nothing a value /// brings is looked at again pub fn fill_page(page: &str, values: &[(&str, String)]) -> String { let mut out = String::with_capacity(page.len() + values.iter().map(|(_, v)| v.len()).sum::()); let mut rest = page; 'next: while let Some(at) = rest.find("__") { for (key, value) in values { if rest[at..].starts_with(key) { out.push_str(&rest[..at]); out.push_str(value); rest = &rest[at + key.len()..]; continue 'next; } } out.push_str(&rest[..at + 2]); rest = &rest[at + 2..]; } out.push_str(rest); out } /// The words a new tab's automation name is drawn from, as the page reads /// them. Drawn from `config::pet_nouns` so that a name minted in the page and /// one minted here come out of the same bag fn pet_nouns_json() -> String { serde_json::to_string(&crate::config::pet_nouns()).unwrap_or_else(|_| "[]".into()) } /// The words put in front of them (`config::pet_adjectives`), for the same reason fn pet_adjectives_json() -> String { serde_json::to_string(&crate::config::pet_adjectives()).unwrap_or_else(|_| "[]".into()) } /// This machine's own shell for the settings page, as {name, cmd} /// (`config::machine_shell`), and the line that opens Git Bash where this PC /// has it (`git_bash`, null where it has not) fn machine_shell_json() -> String { let (name, cmd) = crate::config::machine_shell(); serde_json::json!({ "name": name, "cmd": cmd, "git_bash": crate::config::git_bash_command() }).to_string() } /// What the quick-command editor has to know that `quick.rs` decides: the /// grid's bounds, how long a name and a body may be, where the icons are, /// and what a secret named in a body looks like. Handed over rather than /// written again in the page, so the two cannot hold different limits fn quick_json() -> String { use crate::quick as q; serde_json::json!({ "cols": q::COLS_DEFAULT, "rows": q::ROWS_DEFAULT, "colsMax": q::COLS_MAX, "rowsMax": q::ROWS_MAX, "pagesMax": q::PAGES_MAX, "labelMax": q::LABEL_MAX, "bodyMax": q::BODY_MAX, "icons": q::ICONS_PATH, "secretRef": q::SECRET_REF, }) .to_string() } /// What the settings page has on screen about where a project's worktrees go. /// /// Sent with every question about it rather than read from the saved file: /// the answer is about the settings being edited, which are not saved yet struct PlaceAsk { spec: String, prefix: String, project: Option, markers: crate::config::HostMarkers, } impl PlaceAsk { fn of(p: &serde_json::Value) -> PlaceAsk { let text = |k: &str| p.get(k).and_then(|v| v.as_str()).unwrap_or_default().trim().to_string(); PlaceAsk { spec: text("placement"), prefix: text("prefix"), project: Some(text("project")).filter(|n| !n.is_empty()), markers: p .get("markers") .filter(|m| m.is_object()) .and_then(|m| serde_json::from_value(m.clone()).ok()) .unwrap_or_default(), } } /// As [`crate::worktree::Placement::of`] would have it, from what is on /// screen: what is written, or the default, which is shown as written fn placement(&self) -> crate::worktree::Placement { crate::worktree::Placement { project: self.project.clone(), spec: match self.spec.is_empty() { true => crate::worktree::default_placement(), false => self.spec.clone(), }, prefix: self.prefix.clone(), } } } /// Whether a folder here can be a second name for another, remembered for a /// minute per folder: the page asks again whenever the place is changed, and /// the answer costs a folder made and taken away on what may be a share fn linkable_in(dir: &std::path::Path) -> Option { type Seen = std::collections::HashMap)>; static SEEN: std::sync::Mutex> = std::sync::Mutex::new(None); let kept = SEEN.lock().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|s| s.get(dir).cloned()); if let Some((when, said)) = kept && when.elapsed() < std::time::Duration::from_secs(60) { return said; } let said = crate::worktree::can_link_in(dir); SEEN.lock() .unwrap_or_else(|e| e.into_inner()) .get_or_insert_with(Default::default) .insert(dir.to_path_buf(), (std::time::Instant::now(), said)); said } /// The last "now make its first worktree" the settings page said, counted /// (see `/api/project/next`) static BRANCH_NEXT: std::sync::Mutex<(u64, String, bool)> = std::sync::Mutex::new((0, String::new(), false)); /// That ask, for the board's state. None until the page has said it once pub fn branch_next() -> Option { let next = BRANCH_NEXT.lock().unwrap_or_else(|e| e.into_inner()); (next.0 > 0).then(|| crate::uistate::BranchNext { seq: next.0, folder: next.1.clone(), rules: next.2 }) } /// "Now make its first worktree" (or, with `rules`, "now go through its rules /// first") said about the project whose checkout is `folder`, by the page or /// by the app itself once a machine it was preparing is ready pub fn ask_branch_next(folder: &str, rules: bool) -> u64 { let mut next = BRANCH_NEXT.lock().unwrap_or_else(|e| e.into_inner()); next.0 += 1; next.1 = folder.to_string(); next.2 = rules; next.0 } /// A project's MicroVM checkouts asked to be prepared, by the settings page, /// for the app to do on the board (see `/api/project/machine-setup`) #[derive(Debug, Clone, PartialEq, Eq)] pub struct PrepareAsk { /// The desk and the project, by who they are pub desk_id: String, pub project: String, /// The checkout to open the worktree dialog on once it is prepared, /// when the page was on its way there pub follow: Option, } static PREPARE_ASKS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); /// The asks since last taken pub fn take_prepare_asks() -> Vec { std::mem::take(&mut *PREPARE_ASKS.lock().unwrap_or_else(|e| e.into_inner())) } /// Folders on another machine asked to be deleted from a settings page with /// no way to the board of its own -- a phone's, opened whole -- by place key. /// Handed to the app, which deletes them as a press on the board does: the /// machine is asked first, and a row says how it goes static FOLDER_ACTIONS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); pub fn take_folder_actions() -> Vec { std::mem::take(&mut *FOLDER_ACTIONS.lock().unwrap_or_else(|e| e.into_inner())) } /// Deletes a MicroVM machine from the settings' list of machines, and says /// how that went. Waits on the machine: for a thread. /// /// A machine whose folder was taken off a list is kept with what that folder /// was, and the folder may still hold work: what is not committed, or not /// pushed, is lost with the machine. It is asked the same as the board asks /// before deleting a folder, and refused the same way -- put back on the /// list, the work can be pushed first. A machine the service no longer has /// has nothing left to lose fn drop_machine(id: &str) -> serde_json::Value { let Some(key) = crate::e2b::key() else { return serde_json::json!({ "ok": false, "error": crate::i18n::t("err.e2b.no_key") }); }; let off = crate::config::off_list(); let kept = off.get(id).and_then(|k| k.get("entry")).and_then(|entry| { let cwd = entry.get("cwd").and_then(|c| c.as_str())?.to_string(); let name = entry.get("host").and_then(|h| h.as_str())?.trim().to_string(); Some((name, cwd)) }); if let Some((name, cwd)) = kept { // The entry it was made from, when the settings still have it; else // the machine by its id alone, which is all a MicroVM is asked by let host = crate::config::load() .and_then(|c| c.hosts.into_iter().find(|h| h.name.trim() == name && h.is_made())) .unwrap_or_else(|| crate::config::HostSpec { name: name.clone(), kind: Some("e2b".into()), ..Default::default() }) .with_instance(Some(id)); match crate::worktree::far_ready_to_discard(&host, &cwd) { Ok(()) => {} // It answered, with work on it Err(e) if crate::worktree::is_refusal(&e) => { return serde_json::json!({ "ok": false, "error": crate::i18n::tp( "settings.machines.drop_unsaved", &[("folder", &cwd), ("why", &format!("{e:#}"))], ) }); } // It did not answer: gone, and nothing is left to lose; else // nothing is known about its work, and it is tried again later Err(e) if !crate::e2b::check_gone(id) => { return serde_json::json!({ "ok": false, "error": crate::i18n::tp( "settings.machines.drop_unchecked", &[("id", id), ("folder", &cwd), ("why", &format!("{e:#}"))], ) }); } Err(_) => {} } } match crate::e2b::kill(&key, id) { Ok(()) => serde_json::json!({ "ok": true }), Err(e) => { // Not let go of after all: nothing points at it, and a second // press is how it is tried again crate::e2b::take_back(id); serde_json::json!({ "ok": false, "error": format!("{e:#}") }) } } } /// The machine a folder on the desks is on, when it is not this one fn far_host_of(at: &std::path::Path) -> Option { crate::config::load().and_then(|c| { let (desks, _) = c.resolve_desks(); desks.into_iter().flat_map(|d| d.folders).find_map(|f| { let host = f.host.clone()?; f.cwd.as_deref().filter(|c| crate::uistate::is_place(c, Some(&host.name), at)).map(|_| host) }) }) } // Settings opened without a board still honor pinned and shared folders. fn settings_removal_guard(config_path: &std::path::Path, at: &std::path::Path) -> Result<()> { let text = std::fs::read_to_string(config_path)?; let cfg: crate::config::Config = serde_json::from_str(crate::config::without_bom(&text))?; let (desks, warnings) = cfg.resolve_desks(); if !warnings.is_empty() { anyhow::bail!(crate::i18n::t("err.folders.changed")); } for desk in &desks { if let Some(folder) = desk.folders.iter().find(|f| f.place().is_some_and(|p| crate::uistate::same_folder(&p, at))) { if let Some(why) = crate::foldercare::deletion_guard(folder, desk, &desks) { anyhow::bail!(crate::i18n::t(why)); } return Ok(()); } } anyhow::bail!(crate::i18n::t("err.folders.changed")) } /// The same read-only review for the window, a phone and settings. pub fn review_folder(key: &std::path::Path) -> serde_json::Value { let host = far_host_of(key); let (on, folder) = crate::uistate::place_of(key); if key.as_os_str().is_empty() || (on.is_some() && host.is_none()) { return serde_json::json!({"ok":false, "error":crate::i18n::t("err.folders.changed")}); } match crate::worktree::review::inspect(&folder, host.as_ref()) { Ok(review) => { let mut answer = serde_json::to_value(review).unwrap(); answer["ok"] = serde_json::json!(true); answer } Err(e) => serde_json::json!({"ok":false, "error":format!("{e:#}")}), } } /// Where the project a folder on another machine belongs to is checked out /// there fn far_home_of(at: &std::path::Path, host: &crate::config::HostSpec, desk: Option<&str>) -> Option { crate::config::load()?.project_of(desk, at)?.home_on(&host.name).map(|h| h.at.clone()) } /// Whether a folder on another machine is a branch's folder: one that is not /// the project's checkout there, the way the board tells them apart fn far_cut(at: &std::path::Path, home: Option<&str>) -> bool { let at = crate::uistate::place_of(at).1; home.is_some_and(|h| h.trim_end_matches('/') != at.to_string_lossy().replace('\\', "/").trim_end_matches('/')) } fn json_resp(v: serde_json::Value) -> Response>> { secure(Response::from_string(v.to_string()).with_header( Header::from_bytes(&b"Content-Type"[..], &b"application/json; charset=utf-8"[..]).unwrap(), )) } /// What one of the user's JSON files amounts to right now: usable text, or a /// refusal to hand it over with the reason attached. /// /// Split out from the responding so the decision can be tested on its own — /// what counts as "missing" versus "broken" is the whole point of this. enum UserJson { /// The file's text (or `empty` when it simply isn't there yet). Text(String), /// It exists but can't be used. Carries the HTTP status and the body that /// says why, so the settings page can point at the mistake. Refused(u16, serde_json::Value), } fn read_user_json(path: &std::path::Path, empty: &str) -> UserJson { let text = match std::fs::read_to_string(path) { Ok(t) => t, // Not there yet is not a refusal: that's a fresh install, and `empty` is // what it should look like. Err(e) if e.kind() == std::io::ErrorKind::NotFound => return UserJson::Text(empty.into()), Err(e) => { return UserJson::Refused( 500, serde_json::json!({ "ok": false, "path": path.to_string_lossy(), "error": e.to_string(), }), ); } }; match serde_json::from_str::(&text) { Ok(_) => UserJson::Text(text), // The text rides along so the page can show the offending line itself, // rather than making someone count to line 24 in an editor. Err(e) => UserJson::Refused( 409, serde_json::json!({ "ok": false, "path": path.to_string_lossy(), "error": e.to_string(), "line": e.line(), "column": e.column(), "text": text, }), ), } } /// Hands one of the user's JSON files to the settings page — and refuses plainly /// when the file is there but unusable. /// /// A file that doesn't exist yet is not a refusal: that's a fresh install, and /// `empty` is what it should look like. A file that exists but won't parse used /// to be answered with 200 and its broken text, which left the page with a /// thrown parse, an empty form and no explanation — and Save would then write /// that emptiness over the real thing. So say what's wrong and where, and let /// the page hold Save until it's fixed. fn serve_user_json(req: tiny_http::Request, path: &std::path::Path, empty: &str) -> Result<()> { match read_user_json(path, empty) { UserJson::Text(text) => { let resp = secure(Response::from_string(text).with_header( Header::from_bytes(&b"Content-Type"[..], &b"application/json; charset=utf-8"[..]) .unwrap(), )); req.respond(resp).map_err(Into::into) } UserJson::Refused(status, body) => req .respond(json_resp(body).with_status_code(status)) .map_err(Into::into), } } /// Path to the secrets file. Uses config's setting if present, otherwise secrets.json next to config.json fn secrets_file(config_path: &std::path::Path) -> std::path::PathBuf { crate::config::load() .and_then(|c| c.secrets_path()) .unwrap_or_else(|| { let mut p = config_path.to_path_buf(); p.set_file_name("secrets.json"); p }) } fn handle( req: tiny_http::Request, token: &str, config_path: &std::path::Path, remote: &Arc>, password: &Arc>>, ) -> Result<()> { // DNS rebinding countermeasure: Host must always be loopback let host = header_value(&req, "Host"); let host_ok = host.starts_with("127.0.0.1:") || host.starts_with("localhost:"); // The token only needs to match in either the URL or the X-Token header let supplied = { let h = header_value(&req, "X-Token"); if h.is_empty() { query_token(req.url()) } else { h } }; if !host_ok || !crate::crypto::token_eq(&supplied, token) { return req .respond(Response::from_string("forbidden").with_status_code(403)) .map_err(Into::into); } let method = req.method().as_str().to_string(); let path = req.url().split('?').next().unwrap_or("/").to_string(); // Whoever is asking: this PC's own window, or a phone coming in over the proxy let remote_client = header_value(&req, REMOTE_CLIENT_HEADER) == "1"; // Say no before a dialog can be opened at a screen nobody is looking at. The // page hides these buttons for a remote caller, so reaching here means a page // that was already open, or something calling the API directly if remote_client && NATIVE_DIALOG_PATHS.contains(&path.as_str()) { let mut req = req; // Drain the body first so the response isn't written over an unread request let _ = read_body(&mut req, MAX_BODY)?; return req .respond(json_resp(serde_json::json!({ "ok": false, "error": crate::i18n::t("settings.pick.no_remote"), }))) .map_err(Into::into); } match (method.as_str(), path.as_str()) { ("GET", "/") => { // Every value goes into the page's script as JSON, made safe to // stand there (`script_json`): some of it is the person's own // words, a project's name among them let js = |json: String| crate::script_json(&json); let html = fill_page( &crate::i18n::render(&themed(PAGE.to_string())), &[ ("__TOKEN__", token.to_string()), ("__HOTKEYS__", js(crate::hotkeys::catalog_json())), ("__QUICK__", js(quick_json())), ("__REMOTE__", if remote_client { "true" } else { "false" }.to_string()), ("__PACKAGED__", if crate::config::packaged() { "true" } else { "false" }.to_string()), ("__SYSTEM__", js(serde_json::Value::from(crate::system_name()).to_string())), ("__SHELL__", js(machine_shell_json())), ("__GRANTS__", js(crate::grants::catalog_json())), ( "__GITLUA__", js(serde_json::to_string(crate::hooks::COMMIT_MESSAGE_LUA).unwrap_or_else(|_| "\"\"".into())), ), ( "__PROTECT__", js(serde_json::to_string(&crate::git::DEFAULT_PROTECTED).unwrap_or_else(|_| "[]".into())), ), ("__THISPC__", js(serde_json::to_string(crate::config::THIS_PC).unwrap_or_default())), ("__PETNOUNS__", js(pet_nouns_json())), ("__PETADJECTIVES__", js(pet_adjectives_json())), ( "__SHIPPEDINSIDE__", js(serde_json::to_string(crate::inside::SHIPPED).unwrap_or_else(|_| "[]".into())), ), ("__INSIDESHOWN__", js(crate::inside::shown_json())), ("__DICT__", js(crate::i18n::dict_json())), ], ); let resp = secure(Response::from_string(html).with_header( Header::from_bytes(&b"Content-Type"[..], &b"text/html; charset=utf-8"[..]).unwrap(), )); req.respond(resp)?; } // Opening a settings screen, moving the panel, putting it away. None // of it happens here: what the panel asked for waits for the loop that // draws the window, which is the only thing that can do any of it ("POST", "/api/guide/open") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { return Ok(req.respond(json_resp(serde_json::json!({"error": "too big"})))?); }; let want = serde_json::from_str::(&body) .ok() .and_then(|v| v.get("screen").and_then(|s| s.as_str()).map(str::to_string)) .unwrap_or_default(); let body = match crate::guide::want_open(&want) { true => serde_json::json!({"ok": true}), false => serde_json::json!({"error": crate::i18n::t("guide.err.no_screen")}), }; req.respond(json_resp(body))?; } ("POST", "/api/guide/move") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { return Ok(req.respond(json_resp(serde_json::json!({"error": "too big"})))?); }; let by = serde_json::from_str::(&body).unwrap_or_default(); let n = |k: &str| by.get(k).and_then(|v| v.as_i64()).unwrap_or(0) as i32; crate::guide::want_move((n("x"), n("y"))); req.respond(json_resp(serde_json::json!({"ok": true})))?; } // The panel framed on a phone saying it is there. The window says it // for the panel it places; a frame the board stands over the settings // has nobody to say it but itself, and the settings screen beside it // will not let a box be picked for a ? that is not up ("POST", "/api/guide/here") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { return Ok(req.respond(json_resp(serde_json::json!({"error": "too big"})))?); }; let up = serde_json::from_str::(&body) .ok() .and_then(|v| v.get("up").and_then(|u| u.as_bool())) .unwrap_or(true); crate::guide::phone_here(up); req.respond(json_resp(serde_json::json!({"ok": true})))?; } ("POST", "/api/guide/shut") => { let mut req = req; let _ = read_body(&mut req, MAX_BODY)?; crate::guide::want_shut(); req.respond(json_resp(serde_json::json!({"ok": true})))?; } // The ? panel. Served from here because the token, the dictionary // and the phone's way in are already here; where it sits on the // screen is the app's business, not this server's ("GET", "/guide") => { let html = fill_page( &crate::i18n::render(&themed(crate::guide::page().to_string())), &[("__TOKEN__", token.to_string()), ("__DICT__", crate::script_json(&crate::i18n::dict_json()))], ); let resp = secure(Response::from_string(html).with_header( Header::from_bytes(&b"Content-Type"[..], &b"text/html; charset=utf-8"[..]).unwrap(), )); req.respond(resp)?; } // Put the question to the assistant AI. It takes tens of seconds, and // this server answers one request at a time, so it goes to a thread of // its own -- otherwise the settings screen behind the panel stops // answering for as long as the AI is thinking ("POST", "/api/guide/ask") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { return Ok(req.respond(json_resp(serde_json::json!({"error": "too big"})))?); }; let ask: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let question = ask.get("question").and_then(|q| q.as_str()).unwrap_or("").to_string(); let so_far: Vec = ask .get("so_far") .and_then(|s| serde_json::from_value(s.clone()).ok()) .unwrap_or_default(); let picked = crate::guide::picked(); let (tx, rx) = std::sync::mpsc::channel(); std::thread::spawn(move || { let _ = tx.send(crate::guide::ask(&question, &so_far, picked.as_ref())); }); let body = match rx.recv() { Ok(Ok(a)) => { let at = crate::guide::screen_of(&a.open) .map(|s| crate::i18n::tp("guide.open.at", &[("at", &crate::guide::where_it_is(s))])) .unwrap_or_default(); serde_json::json!({"say": a.say, "open": a.open, "fill": a.fill, "at": at}) } Ok(Err(e)) => serde_json::json!({"error": format!("{e:#}")}), Err(e) => serde_json::json!({"error": e.to_string()}), }; req.respond(json_resp(body))?; } // The program's own source, fetched for the ? to search: this version, // once, and again after an update. Its own request so the panel can say // it is fetching before it says it is searching ("POST", "/api/guide/source/fetch") => { let (tx, rx) = std::sync::mpsc::channel(); std::thread::spawn(move || { let _ = tx.send(crate::source::ready()); }); let body = match rx.recv() { Ok(Ok(at)) => serde_json::json!({"ok": true, "read": at.read}), Ok(Err(e)) => serde_json::json!({ "error": format!("{e:#}"), // What to do about it, when the answer is to install git "git": crate::tab::resolve_command("git").is_none(), }), Err(e) => serde_json::json!({"error": e.to_string()}), }; req.respond(json_resp(body))?; } // The question searched for in that source, by the assistant AI // reading it. Minutes rather than seconds, on a thread of its own ("POST", "/api/guide/source/ask") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { return Ok(req.respond(json_resp(serde_json::json!({"error": "too big"})))?); }; let ask: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let question = ask.get("question").and_then(|q| q.as_str()).unwrap_or("").to_string(); let so_far: Vec = ask .get("so_far") .and_then(|s| serde_json::from_value(s.clone()).ok()) .unwrap_or_default(); let (tx, rx) = std::sync::mpsc::channel(); std::thread::spawn(move || { let _ = tx.send(crate::source::ready().and_then(|at| { crate::guide::ask_source(&question, &so_far, &at).map(|a| (a, at.read)) })); }); let body = match rx.recv() { Ok(Ok((a, read))) => serde_json::json!({"say": a.say, "read": read}), Ok(Err(e)) => serde_json::json!({"error": format!("{e:#}")}), Err(e) => serde_json::json!({"error": e.to_string()}), }; req.respond(json_resp(body))?; } // The box somebody picked on the settings screen, and putting one down ("GET", "/api/guide/picked") => { req.respond(json_resp( serde_json::to_value(crate::guide::picked()).unwrap_or_default(), ))?; } ("POST", "/api/guide/picked") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { return Ok(req.respond(json_resp(serde_json::json!({"error": "too big"})))?); }; let want: Option = serde_json::from_str::(&body) .ok() .filter(|p| !p.label.trim().is_empty()); crate::guide::pick(want); req.respond(json_resp(serde_json::json!({"ok": true})))?; } // What the settings screen should write into the picked box. Left // here by the panel when a person presses the button under an answer, // and taken by the settings screen the next time it asks ("POST", "/api/guide/fill") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { return Ok(req.respond(json_resp(serde_json::json!({"error": "too big"})))?); }; let text = serde_json::from_str::(&body) .ok() .and_then(|v| v.get("text").and_then(|t| t.as_str()).map(str::to_string)) .unwrap_or_default(); let body = match crate::guide::picked() { Some(_) => { crate::guide::leave_to_fill(&text); serde_json::json!({"ok": true}) } None => serde_json::json!({"error": crate::i18n::t("guide.err.no_pick")}), }; req.respond(json_resp(body))?; } // Whether the panel is up, and anything it left to be written. One // question because the settings screen asks both on the same beat, // and because "write this" only means anything while it is up ("GET", "/api/guide/up") => { let up = crate::guide::is_up(); req.respond(json_resp(serde_json::json!({ "up": up, "fill": up.then(crate::guide::take_to_fill).flatten(), })))?; } // The result view: a finished run's transcript.md rendered as a chat // (AI-vs-AI discussion / code review / browser rally). Same token gate // as the settings page; the run id rides in the query string. ("GET", "/result") => { let html = crate::i18n::render(&themed(RESULT_PAGE.to_string())) .replace("__TOKEN__", token) .replace("__DICT__", &crate::script_json(&crate::i18n::dict_json())); let resp = secure(Response::from_string(html).with_header( Header::from_bytes(&b"Content-Type"[..], &b"text/html; charset=utf-8"[..]).unwrap(), )); req.respond(resp)?; } // How-to-write documentation (openable from the GUI, so the user doesn't have to hunt for the file) ("GET", "/help") => { let md = load_manual(config_path); let html = crate::i18n::render(&themed(HELP_PAGE.to_string())) .replace("__MD__", &crate::script_json(&serde_json::to_string(&md)?)); let resp = secure(Response::from_string(html).with_header( Header::from_bytes(&b"Content-Type"[..], &b"text/html; charset=utf-8"[..]).unwrap(), )); req.respond(resp)?; } ("GET", "/api/config") => serve_user_json(req, config_path, "{}")?, // Opens an external help/report page in the user's real browser (not // the in-app WebView). Destinations are whitelisted, so the page can // never be talked into acting as an open redirect. ("GET", "/api/open") => { let url = match query_param(req.url(), "dest").as_deref() { Some("bug") => Some(bug_report_url()), Some("discussions") => { Some("https://github.com/styleio/ShikishaTerm/discussions".to_string()) } Some("update-notes") => crate::update::notes_url(), // The manual on the site. The ? beside the gear used to be // this link and now answers instead, so the link lives inside // what answers -- nothing that was reachable has been taken away Some("manual") => Some(crate::i18n::t("tui.help.url")), // Where git comes from, for the ? to search the source with Some("git") => Some("https://git-scm.com/downloads".to_string()), // How to install the program a tab needs. The address is the // app's own, looked up by program name -- the page names a // program, never a place to go Some("install") => query_param(req.url(), "prog") .map(|p| percent_decode(&p)) .and_then(|p| install_page(&p)), // Windows' own page of notification switches, for a PC whose // notifications are turned off there (see /api/notify/pc) Some("pc-notifications") if cfg!(windows) => Some("ms-settings:notifications".to_string()), _ => None, }; match url { Some(u) => { open_external(&u); req.respond(json_resp(serde_json::json!({ "ok": true })))?; } None => { req.respond(Response::from_string("bad dest").with_status_code(400))?; } } } // Runs ` --help` so the settings page can show a CLI's real flags. // The program is the first token of the tab's command. // Which repository each of several folders is in, in one question. The // settings tree groups a desk's folders into its projects before it can // draw anything, and a round trip per folder drew the tree ungrouped // first and then again. Read off git's own files, never by running git ("POST", "/api/families") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let mut out = serde_json::Map::new(); for path in p.get("paths").and_then(|v| v.as_array()).into_iter().flatten().filter_map(|v| v.as_str()) { let at = std::path::Path::new(path.trim()); if at.as_os_str().is_empty() || out.contains_key(path) { continue; } let family = crate::repo::family_of(at); out.insert(path.to_string(), serde_json::json!({ "family": family.as_ref().map(|f| f.display().to_string()), "main": crate::repo::main_checkout(at).map(|m| m.display().to_string()), "cut": crate::repo::is_linked(at), "origin": crate::repo::origin_of(at), // A folder of decision records the repository already // has, offered when the project turns them on "adr": crate::adr::KNOWN_DIRS.iter().find(|d| at.join(d).is_dir()), })); } req.respond(json_resp(serde_json::json!({ "families": out })))?; } // Why a folder's automatic name and summary could not be written the // last time they were tried, if they could not. Kept by the loop that // tried, beside the app (`crate::labels::note_outcome`) ("GET", "/api/folder-label") => { let at = query_param(req.url(), "path") .map(|c| percent_decode(&c)) .unwrap_or_default(); // By place key: a folder of the same path on another machine is // another folder, and so is what went wrong naming it let at = match crate::uistate::place_of(std::path::Path::new(&at)) { (Some(host), path) => std::path::PathBuf::from(crate::uistate::place_key(Some(&host), &path)), (None, _) => crate::config::resolve_folder_cwd(&at), }; let failed = crate::labels::outcomes() .into_iter() .find(|(k, _)| crate::uistate::same_folder(std::path::Path::new(k), &at)) .and_then(|(_, v)| v.as_str().map(str::to_string)); req.respond(json_resp(serde_json::json!({ "failed": failed })))?; } // The AIs a server reached over SSH has, as last heard (see // crate::serverai): what a new tab in a folder there starts as. // Null until the server has answered once ("GET", "/api/server-ais") => { let name = query_param(req.url(), "host").map(|c| percent_decode(&c)).unwrap_or_default(); let host = crate::config::load().and_then(|c| c.hosts.into_iter().find(|h| h.name.trim() == name.trim())); let ais = host.as_ref().and_then(crate::serverai::known); req.respond(json_resp(serde_json::json!({ "ais": ais })))?; } // Every MicroVM machine the key has, and what in the settings each is. // The only place a machine nothing points at any more can be seen // from here: one left by a making that never finished, a folder taken // off the list, a project or a desk removed. Each is paid for until it // is deleted, so the list is where that is done ("GET", "/api/microvm/machines") => { let resp = match crate::e2b::key() { None => serde_json::json!({ "ok": false, "error": crate::i18n::t("err.e2b.no_key") }), Some(key) => match crate::e2b::list(&key) { Err(e) => serde_json::json!({ "ok": false, "error": format!("{e:#}") }), Ok(listed) => { // Settings that cannot be read whole: the machines // are listed, and none is offered for deleting let (used, unsure) = match crate::config::machines_in_use() { Ok(u) => (u, None), Err(why) => (Default::default(), Some(why)), }; // A folder taken off a list whose machine the service // no longer has cannot be put back: forgotten here, // where the whole list is in hand. The service answers a // page of at most a hundred; a full page may not be all // of them, and nothing is forgotten on its word if listed.len() < 100 { crate::config::prune_off_list(&listed.iter().map(|m| m.id.clone()).collect()); } let off = crate::config::off_list(); let rows: Vec = listed .iter() .map(|m| { serde_json::json!({ // Taken off a list with its machine kept: // what it was, to be put back "off_list": off.get(&m.id).and_then(|k| k.get("entry")).and_then(|e| e.get("cwd")).cloned(), "id": m.id, "state": m.state, "started": m.started, "ours": m.ours(), "project": m.marks.get("project"), "pc": m.marks.get("pc"), "used": used.get(&m.id).cloned().unwrap_or_default(), "making": !used.contains_key(&m.id) && crate::e2b::being_made(&m.id), }) }) .collect(); serde_json::json!({ "ok": true, "machines": rows, "unsure": unsure }) } }, }; req.respond(json_resp(resp))?; } // Delete one machine from that list. Refused while anything in the // settings still points at it: that one is deleted with its folder, // from the board, where its tabs are closed first ("POST", "/api/microvm/drop") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let id = p.get("id").and_then(|v| v.as_str()).unwrap_or_default().trim().to_string(); let resp = if id.is_empty() { serde_json::json!({ "ok": false }) } else if let Err(why) = crate::config::machines_in_use() { serde_json::json!({ "ok": false, "error": why }) } else if crate::config::machines_in_use().is_ok_and(|u| u.contains_key(&id)) { serde_json::json!({ "ok": false, "error": crate::i18n::t("settings.machines.in_use") }) } else if crate::e2b::being_made(&id) { serde_json::json!({ "ok": false, "error": crate::i18n::t("settings.machines.making_refused") }) } else if crate::e2b::key().is_none() { serde_json::json!({ "ok": false, "error": crate::i18n::t("err.e2b.no_key") }) } else { // Asked of the machine first, on a thread: the check wakes it // and waits on it, and this page is served one ask at a time std::thread::spawn(move || { let _ = req.respond(json_resp(drop_machine(&id))); }); return Ok(()); }; req.respond(json_resp(resp))?; } // A folder on another machine deleted from a settings page that has no // board of its own to tell (see FOLDER_ACTIONS) ("POST", "/api/folder/discard-far") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let folder = p.get("folder").and_then(|v| v.as_str()).unwrap_or_default().trim().to_string(); let resp = match folder.is_empty() { true => serde_json::json!({ "ok": false }), false => { let review = p.get("review").and_then(|v| v.as_str()).map(str::to_string); FOLDER_ACTIONS.lock().unwrap_or_else(|e| e.into_inner()).push(shikisha_shared::Ev::FolderDiscard {folder, unasked:false, review}); serde_json::json!({ "ok": true }) } }; req.respond(json_resp(resp))?; } // A MicroVM folder taken off a list, put back on it as it stood: the // desk it came from, or the one the page is on when that is gone ("POST", "/api/microvm/restore") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let id = p.get("id").and_then(|v| v.as_str()).unwrap_or_default().trim().to_string(); let desk = p.get("desk").and_then(|v| v.as_str()).unwrap_or_default().trim().to_string(); let resp = match crate::config::put_back_on_list(&id, &desk) { Ok(()) => serde_json::json!({ "ok": true }), Err(e) => serde_json::json!({ "ok": false, "error": format!("{e:#}") }), }; req.respond(json_resp(resp))?; } // Which project a folder belongs to, and whether its folder is one the // app made. The settings screen cannot work either out: both mean // looking at what git keeps behind the folder ("GET", "/api/family") => { let at = query_param(req.url(), "path") .map(|c| percent_decode(&c)) .unwrap_or_default(); let at = std::path::Path::new(at.trim()); // The desk the page is editing, since a project belongs to a desk let desk = query_param(req.url(), "desk").map(|d| percent_decode(&d)); // The project too, because the screen has to be able to say whose // setting it is looking at. A devcontainer belongs to a repository, // so a branch folder's page must point at the project rather than // offer to write one -- and the project's own page must offer it, // which is the half that was missing let named = crate::config::load() .and_then(|c| c.project_of(desk.as_deref(), at)); // A folder on another machine: nothing of it is on this disk. Its // project is the settings' answer, its branch what git there last // said (asked on a thread, see `git::far_place`), and it is a // branch's folder when it is not the project's checkout there -- // on a MicroVM every folder is a machine of its own, so git's own // word for a worktree says nothing. Deleting one is the board's, // which asks the machine first (see `farFolderDiscard`) if let Some(host) = far_host_of(at).filter(|_| !at.as_os_str().is_empty()) { // The path there, out of the place key the page named it by let path = crate::uistate::place_of(at).1; let branch = crate::elsewhere::Elsewhere::of(&host) .ok() .and_then(|m| crate::git::far_place(&m, &path, true).0); let home_at = named.as_ref().and_then(|p| p.home_on(&host.name)).map(|h| h.at.clone()); let checkout = home_at.clone().unwrap_or_else(|| path.to_string_lossy().to_string()); req.respond(json_resp(serde_json::json!({ "family": crate::uistate::far_family(&host.name, &checkout), "cut": far_cut(at, home_at.as_deref()), "branch": branch, "project": named.as_ref().map(|p| p.name.clone()), "project_at": home_at, "host": host.name, })))?; return Ok(()); } let resp = match at.as_os_str().is_empty() { true => serde_json::json!({ "family": null, "cut": false, "branch": null, "project": null, "project_at": null, }), false => serde_json::json!({ "family": crate::repo::family_of(at).map(|f| f.display().to_string()), "cut": crate::repo::is_linked(at), "branch": crate::repo::branch_of(at), "project": named.as_ref().map(|p| p.name.clone()), "project_at": named.and_then(|p| p.at), }), }; req.respond(json_resp(resp))?; } // The GitHub accounts git on this PC holds. With two of them "this PC's // git" cannot sign in until it is told which, so each is offered as a // choice of its own. Read fresh: the page asks once when it opens ("GET", "/api/pc-accounts") => { req.respond(json_resp(serde_json::json!({ "accounts": crate::pr::pc_accounts() })))?; } // A token put into the credential store git on this PC uses, the way a // push that signed in would leave it. Whose it is, GitHub is asked // first: the store files it under the login, and a token nobody can // name is one nobody can choose ("POST", "/api/pc-accounts/add") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let token = v.get("token").and_then(|t| t.as_str()).unwrap_or("").trim().to_string(); let said = match crate::pr::plain_token(&token) { false => Err(crate::i18n::t("settings.gitacct.token_rejected")), true => { let probe = crate::pr::probe(Some(token.clone())); match probe.login.filter(|_| probe.ok) { Some(login) => crate::pr::pc_store(&login, &token).map(|()| login), None => Err(crate::i18n::t("settings.gitacct.token_rejected")), } } }; req.respond(json_resp(match said { Ok(login) => serde_json::json!({ "ok": true, "login": login }), Err(error) => serde_json::json!({ "ok": false, "error": error }), }))?; } ("POST", "/api/pc-accounts/forget") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let login = v.get("login").and_then(|t| t.as_str()).unwrap_or("").trim().to_string(); let said = match crate::pr::plain_name(&login) { true => crate::pr::pc_forget(&login), false => Err(crate::i18n::t("settings.gitacct.name_bad")), }; req.respond(json_resp(match said { Ok(()) => serde_json::json!({ "ok": true }), Err(error) => serde_json::json!({ "ok": false, "error": error }), }))?; } // The accounts GitHub CLI (gh) is signed in as, every host. `gh` absent // is said apart from `gh` signed in nowhere ("GET", "/api/gh-accounts") => { req.respond(json_resp(match crate::pr::gh_accounts() { Some(accounts) => serde_json::json!({ "installed": true, "accounts": accounts }), None => serde_json::json!({ "installed": false, "accounts": [] }), }))?; } ("POST", "/api/gh-accounts/add") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let token = v.get("token").and_then(|t| t.as_str()).unwrap_or("").trim().to_string(); let host = v.get("host").and_then(|t| t.as_str()).unwrap_or("").trim().to_ascii_lowercase(); let host = if host.is_empty() { crate::config::GITHUB_HOST.to_string() } else { host }; let said = match (crate::pr::plain_token(&token), crate::pr::plain_name(&host)) { (false, _) => Err(crate::i18n::t("settings.gitacct.token_rejected")), (_, false) => Err(crate::i18n::t("settings.gitacct.host_bad")), (true, true) => crate::pr::gh_sign_in(&host, &token), }; req.respond(json_resp(match said { Ok(()) => serde_json::json!({ "ok": true }), Err(error) => serde_json::json!({ "ok": false, "error": error }), }))?; } ("POST", "/api/gh-accounts/forget") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let login = v.get("login").and_then(|t| t.as_str()).unwrap_or("").trim().to_string(); let host = v.get("host").and_then(|t| t.as_str()).unwrap_or("").trim().to_ascii_lowercase(); let said = match (crate::pr::plain_name(&login), crate::pr::plain_name(&host)) { (true, true) => crate::pr::gh_sign_out(&host, &login), _ => Err(crate::i18n::t("settings.gitacct.name_bad")), }; req.respond(json_resp(match said { Ok(()) => serde_json::json!({ "ok": true }), Err(error) => serde_json::json!({ "ok": false, "error": error }), }))?; } // A project's ignore file and what it makes git ignore, for the page // that decides how each line's files reach a new worktree. With `add`, // `remove` or `untrack` it changes something first; the answer is always // the state after, so the page draws what is really there ("POST", "/api/project/ignore") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let at = std::path::PathBuf::from(p.get("path").and_then(|v| v.as_str()).unwrap_or_default().trim()); // Always the checkout the project's worktrees are cut from let main = crate::repo::main_checkout(&at); let resp = match main { None => serde_json::json!({ "ok": false, "error": crate::i18n::t("err.worktree.not_a_repo") }), Some(main) => { let did = if let Some(line) = p.get("add").and_then(|v| v.as_str()) { crate::worktree::gitignore_add(&main, line) } else if let Some(r) = p.get("remove") { crate::worktree::gitignore_remove( &main, r.get("n").and_then(|v| v.as_u64()).unwrap_or(0) as usize, r.get("text").and_then(|v| v.as_str()).unwrap_or_default(), ) } else if let Some(list) = p.get("untrack").and_then(|v| v.as_array()) { let paths: Vec = list.iter().filter_map(|v| v.as_str().map(str::to_string)).collect(); crate::worktree::untrack(&main, &paths) } else { Ok(()) }; let found = crate::worktree::ignored(&main); let mut defaults: Vec = Vec::new(); for i in &found { if !defaults.iter().any(|d| d["source"] == i.source.as_str() && d["pattern"] == i.pattern.as_str()) { defaults.push(serde_json::json!({ "source": i.source, "pattern": i.pattern, "how": crate::worktree::default_how(&found, &i.source, &i.pattern), })); } } serde_json::json!({ "ok": did.is_ok(), "error": did.err().map(|e| format!("{e:#}")), "root": main.display().to_string(), "branch": crate::repo::branch_of(&main), "lines": crate::worktree::gitignore_lines(&main), "ignored": found, "defaults": defaults, "tracked": crate::worktree::tracked_but_ignored(&main), }) } }; req.respond(json_resp(resp))?; } // Where a project's worktrees would go, as the page has it now: the // folder one named `name` would get, what (if anything) says the // project is served where it stands, and whether a folder there can be // a second name for another. Asked while the place is being typed, so // the answer is the settings on screen and not the ones saved ("POST", "/api/project/place") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let at = std::path::PathBuf::from(p.get("path").and_then(|v| v.as_str()).unwrap_or_default().trim()); let resp = match crate::repo::main_checkout(&at) { None => serde_json::json!({ "ok": false, "error": crate::i18n::t("err.worktree.not_a_repo") }), Some(main) => { let asked = PlaceAsk::of(&p); let served = crate::worktree::served_in_place(&main, &asked.markers); let placement = asked.placement(); let name = p.get("name").and_then(|v| v.as_str()).map(str::trim).filter(|n| !n.is_empty()).unwrap_or("feature/x"); let branch = crate::worktree::with_prefix(&placement.prefix, name); // What the page offers to write, and why: never taken // unless it is written down let proposal = match served.is_some() { true => crate::worktree::beside_placement(), false => crate::worktree::default_placement(), }; let said = serde_json::json!({ "root": main.display().to_string(), "origin": main.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(), "spec": placement.spec, "default": crate::worktree::default_placement(), "beside": crate::worktree::beside_placement(), "proposal": proposal, "served": served, "branch": branch, }); match crate::worktree::place(&main, &placement, &branch) { Err(error) => { let mut out = said; out["ok"] = false.into(); out["error"] = error.into(); out } Ok(folder) => { let inside = crate::worktree::inside_checkout(&main, &folder); // Tried where the folder would be made: the nearest // folder on the way there that is already on disk let there = folder.ancestors().skip(1).find(|d| d.is_dir()).map(std::path::Path::to_path_buf); let probe = p.get("probe").and_then(serde_json::Value::as_bool).unwrap_or(false); let linkable = match (&there, probe && !inside) { (Some(d), true) => linkable_in(d), _ => None, }; let mut out = said; out["ok"] = (!inside).into(); if inside { out["error"] = crate::i18n::tp("err.worktree.inside_checkout", &[("path", &folder.display().to_string())]).into(); } out["folder"] = folder.display().to_string().into(); out["name"] = folder.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default().into(); out["linkable"] = serde_json::json!(linkable); out["long"] = (folder.display().to_string().chars().count() >= 180).into(); out } } } }; req.respond(json_resp(resp))?; } // How much each thing a project's ignore files match holds on disk. // Counted on a thread of its own: a build folder can hold hundreds of // thousands of files, and the rest of the page is not held up for it ("POST", "/api/project/sizes") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let at = std::path::PathBuf::from(p.get("path").and_then(|v| v.as_str()).unwrap_or_default().trim()); // The rules for places inside, as the page has them -- saved or // not -- so what is said is what they would copy let rules: Vec = p.get("inside").cloned().and_then(|v| serde_json::from_value(v).ok()).unwrap_or_default(); // With the app's own rules put in, the way the page has changed them let rules = crate::inside::effective(&rules); std::thread::spawn(move || { let resp = match crate::repo::main_checkout(&at) { None => serde_json::json!({ "ok": false, "error": crate::i18n::t("err.worktree.not_a_repo") }), Some(main) => { let paths: Vec = crate::worktree::ignored(&main).into_iter().map(|i| i.path).collect(); let inside = crate::inside::Inside::of(&rules); serde_json::json!({ "ok": true, "sizes": crate::worktree::sizes(&main, &paths, crate::inherit::SIZE_MOST, &inside), "large_bytes": crate::inherit::LARGE_BYTES, "large_files": crate::inherit::LARGE_FILES, }) } }; let _ = req.respond(json_resp(resp)); }); } // A project's rules for places inside have been put on screen: the // app's own rules as they stand now are no longer new to it ("POST", "/api/project/inside-shown") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); crate::inside::mark_shown(p.get("project").and_then(|v| v.as_str()).unwrap_or_default().trim()); req.respond(json_resp(serde_json::json!({ "ok": true })))?; } // The assistant AI's proposal for how each ignored thing reaches a new // worktree. Only a proposal: the page shows it, and the person saves // it or does not. Asked on a thread of its own, since an AI takes a // while and the page has other questions to ask in the meantime ("POST", "/api/project/inherit-ai") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let at = std::path::PathBuf::from(p.get("path").and_then(|v| v.as_str()).unwrap_or_default().trim()); let hint = p.get("hint").and_then(|v| v.as_str()).unwrap_or_default().to_string(); let asked = PlaceAsk::of(&p); std::thread::spawn(move || { let engine = crate::config::load().and_then(|c| c.ai_engine).filter(|e| !e.trim().is_empty()); // No assistant AI here: said as that, so the page can offer // the way to choose one rather than a failure to read if assistant_ai(engine.as_deref()).is_none() { let _ = req.respond(json_resp(serde_json::json!({ "ok": false, "no_ai": true, "error": crate::i18n::t("webui.err.ai_missing"), }))); return; } let resp = match crate::repo::main_checkout(&at) { None => serde_json::json!({ "ok": false, "error": crate::i18n::t("err.worktree.not_a_repo") }), Some(main) => { let served = crate::worktree::served_in_place(&main, &asked.markers); let placement = asked.placement(); let example = match crate::worktree::place( &main, &placement, &crate::worktree::with_prefix(&placement.prefix, "feature/x"), ) { Ok(f) => f, Err(error) => { let _ = req.respond(json_resp(serde_json::json!({ "ok": false, "error": error }))); return; } }; let linkable = example.ancestors().skip(1).find(|d| d.is_dir()).and_then(linkable_in); let facts = crate::inherit::Facts { main: &main, example: &example, served: served.as_deref(), linkable, hint: &hint, }; match crate::inherit::ask(&facts, engine.as_deref()) { Ok(lines) => serde_json::json!({ "ok": true, "lines": lines, "name": example.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(), "folder": example.display().to_string(), }), Err(e) => serde_json::json!({ "ok": false, "error": format!("{e:#}") }), } } }; let _ = req.respond(json_resp(resp)); }); } // A project's MicroVM checkouts to be prepared as its saved settings // say: the AI and the machine setup. Handed to the app, which does it // on threads of its own and shows a row on the board for each machine // -- an install takes minutes, and a page held that long looks stuck. // `follow` names the checkout the worktree dialog opens on afterwards ("POST", "/api/project/machine-setup") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let text = |k: &str| p.get(k).and_then(|v| v.as_str()).map(str::trim).filter(|s| !s.is_empty()).map(str::to_string); let resp = match (text("desk"), text("project")) { (Some(desk_id), Some(project)) => match crate::microvm::prepare_targets(&desk_id, &project) { Ok(t) => { // A machine being prepared already is not started again: // the ask joins the one running -- or, with settings // saved since it began, runs after it -- and the page // says which let machines: Vec> = t .homes .iter() .map(|(h, _)| h.instance.clone()) .chain(t.worktrees.iter().map(|(h, _)| h.instance.clone())) .collect(); let now = t.preparing.said(); let running: Vec = machines.iter().flatten().filter_map(|id| crate::microvm::preparing_with(id)).collect(); let already = running.iter().filter(|with| **with == now).count(); let again = running.len() - already; // Held by who the desk and the project are from here // on: renamed before the board takes it up, they are // still the ones asked for let ask = PrepareAsk { desk_id: t.desk_uid.clone(), project: t.project_uid.clone(), follow: text("follow") }; PREPARE_ASKS.lock().unwrap_or_else(|e| e.into_inner()).push(ask); serde_json::json!({ "ok": true, "started": true, "machines": machines.len(), "already": already, "again": again }) } Err(error) => serde_json::json!({ "ok": false, "error": error }), }, _ => serde_json::json!({ "ok": false, "error": crate::i18n::tp("err.project.missing", &[("name", "")]) }), }; req.respond(json_resp(resp))?; } // The assistant AI's proposal for a project's machine setup. Only a // proposal, as the one for what a worktree inherits is ("POST", "/api/project/machine-setup-ai") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let desk = p.get("desk").and_then(|v| v.as_str()).unwrap_or_default().to_string(); let project = p.get("project").and_then(|v| v.as_str()).unwrap_or_default().to_string(); let hint = p.get("hint").and_then(|v| v.as_str()).unwrap_or_default().to_string(); std::thread::spawn(move || { let engine = crate::config::load().and_then(|c| c.ai_engine).filter(|e| !e.trim().is_empty()); if assistant_ai(engine.as_deref()).is_none() { let _ = req.respond(json_resp(serde_json::json!({ "ok": false, "no_ai": true, "error": crate::i18n::t("webui.err.ai_missing"), }))); return; } let resp = match crate::microvm::propose_setup(&desk, &project, &hint, engine.as_deref()) { Ok(lines) => serde_json::json!({ "ok": true, "lines": lines }), Err(error) => serde_json::json!({ "ok": false, "error": error }), }; let _ = req.respond(json_resp(resp)); }); } // What a file a replacement is written for says now, and what it would // say in a worktree: every line that changes, before and after. Read // from the checkout, so what is shown is the file that will be copied ("POST", "/api/project/replace-preview") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let at = std::path::PathBuf::from(p.get("path").and_then(|v| v.as_str()).unwrap_or_default().trim()); let folder = std::path::PathBuf::from(p.get("folder").and_then(|v| v.as_str()).unwrap_or_default().trim()); let replaces: Vec = serde_json::from_value(p.get("replace").cloned().unwrap_or_default()).unwrap_or_default(); let files: Vec = p .get("files") .and_then(|v| v.as_array()) .map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()) .unwrap_or_default(); let resp = match crate::repo::main_checkout(&at) { None => serde_json::json!({ "ok": false, "error": crate::i18n::t("err.worktree.not_a_repo") }), Some(main) => { let filled: Vec = replaces .iter() .map(|r| crate::config::Replace { with: crate::worktree::fill_words(&r.with, &folder, &main, r.regex), ..r.clone() }) .collect(); let shown: Vec = files .iter() .take(10) .map(|f| { let text = std::fs::read_to_string(main.join(f)); match text.map_err(|e| e.to_string()).and_then(|t| { crate::worktree::apply_replaces(&t, &filled).map(|(after, unmatched)| (t, after, unmatched)) }) { Err(error) => serde_json::json!({ "file": f, "error": error }), Ok((before, after, unmatched)) => { let changed: Vec = before .lines() .zip(after.lines()) .enumerate() .filter(|(_, (a, b))| a != b) .take(30) .map(|(n, (a, b))| serde_json::json!({ "n": n + 1, "before": a, "after": b })) .collect(); serde_json::json!({ "file": f, "changed": changed, "unmatched": unmatched }) } } }) .collect(); serde_json::json!({ "ok": true, "files": shown }) } }; req.respond(json_resp(resp))?; } // "Now make its first worktree": the settings page, done with a new // project's rules, hands on to the board's dialog. Held here and read // into the board's state (see `branch_next`), which reaches the board // in the window and on a phone alike ("POST", "/api/project/next") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let folder = p.get("folder").and_then(|v| v.as_str()).unwrap_or_default().trim().to_string(); let resp = match folder.is_empty() { true => serde_json::json!({ "ok": false }), false => serde_json::json!({ "ok": true, "seq": ask_branch_next(&folder, false) }), }; req.respond(json_resp(resp))?; } // Read the contents before asking whether to discard them. No files // or settings are changed by this request. ("POST", "/api/folder/discard-check") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let key = std::path::PathBuf::from(p.get("folder").and_then(|v| v.as_str()).unwrap_or_default()); let board = remote.lock().unwrap_or_else(|e| e.into_inner()).board; std::thread::spawn(move || { let mut answer = review_folder(&key); answer["board"] = serde_json::json!(board); let _ = req.respond(json_resp(answer)); }); } // Opening a reviewed file uses the board's existing editor and diff. ("POST", "/api/folder/review-file") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let text = |key| p.get(key).and_then(|v| v.as_str()).unwrap_or_default().to_string(); if !remote.lock().unwrap_or_else(|e| e.into_inner()).board { req.respond(json_resp(serde_json::json!({"ok":false, "error":crate::i18n::t("settings.group.discard.board")})))?; } else { FOLDER_ACTIONS.lock().unwrap_or_else(|e| e.into_inner()).push(shikisha_shared::Ev::EditOpen { panel:format!("folder:{}", text("folder")), path:text("path"), diff:text("diff"), }); req.respond(json_resp(serde_json::json!({"ok":true})))?; } } // Throw a branch's folder away for good. Changes need the review the // person explicitly accepted. The answer waits on a // thread of its own so the rest of the page is not held up. `left` // says the folder is still on disk, which the page asks about ("POST", "/api/folder/discard") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let at = std::path::PathBuf::from( p.get("path").and_then(|v| v.as_str()).unwrap_or_default().trim(), ); let review = p.get("review").and_then(|v| v.as_str()).map(str::to_string); if remote.lock().unwrap_or_else(|e| e.into_inner()).board { FOLDER_ACTIONS.lock().unwrap_or_else(|e| e.into_inner()).push(shikisha_shared::Ev::FolderDiscard {folder:at.to_string_lossy().into_owned(), unasked:false, review}); req.respond(json_resp(serde_json::json!({"ok":true, "queued":true})))?; return Ok(()); } if let Err(e) = settings_removal_guard(config_path, &at).and_then(|_| crate::worktree::ready_to_discard_reviewed(&at, review.as_deref())) { req.respond(json_resp(serde_json::json!({ "ok": false, "error": format!("{e:#}") })))?; return Ok(()); } std::thread::spawn(move || { let resp = match crate::worktree::discard_waiting_reviewed(&at, review.as_deref()) { Ok(()) => serde_json::json!({ "ok": true }), Err(e) => { crate::append_hook_log(&format!("could not remove {}: {e:#}", at.display())); serde_json::json!({ "ok": false, "left": true, "error": format!("{e:#}") }) } }; let _ = req.respond(json_resp(resp)); }); } // Call a branch's folder's branch something else. Asked twice: once // with `go` unset, to put the line that would run in front of the // person, and once to run it ("POST", "/api/folder/rename") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let at = std::path::PathBuf::from( p.get("path").and_then(|v| v.as_str()).unwrap_or_default().trim(), ); let to = p.get("name").and_then(|v| v.as_str()).unwrap_or_default(); let go = p.get("go").and_then(serde_json::Value::as_bool).unwrap_or(false); // A folder on another machine is renamed by git there let far = far_host_of(&at); let planned = match &far { Some(host) => { let cut = far_cut(&at, far_home_of(&at, host, p.get("desk").and_then(|d| d.as_str())).as_deref()); let path = crate::uistate::place_of(&at).1.to_string_lossy().to_string(); // While a name is typed, the branch the page shows: the // machine is asked only on the press (see rename_plan_far) let known = match go { true => None, false => p .get("from") .and_then(|v| v.as_str()) .map(str::to_string) .or_else(|| crate::elsewhere::Elsewhere::of(host).ok().and_then(|m| crate::git::far_place(&m, std::path::Path::new(&path), false).0)), }; crate::worktree::rename_plan_far(host, &path, cut, to, known.as_deref()) } None => crate::worktree::rename_plan(&at, to), }; let resp = match planned { Err(e) => serde_json::json!({ "ok": false, "error": format!("{e:#}") }), Ok(plan) => match go { false => serde_json::json!({ "ok": true, "line": plan.line(), "sent": plan.sent_as, }), true => match far.as_ref().map_or_else(|| crate::worktree::rename(&plan), |h| crate::worktree::rename_far(h, &plan)) { Err(e) => serde_json::json!({ "ok": false, "error": format!("{e:#}") }), // The person renamed it, and knows. The AIs in the // folder do not, until their next turn Ok(()) => { crate::notice::branch_renamed(&at, &plan.from, &plan.to); serde_json::json!({ "ok": true, "done": true, "from": plan.from, "to": plan.to, "sent": plan.sent_as, }) } }, }, }; req.respond(json_resp(resp))?; } // What a project says its environment needs, and what could be // proposed when it says nothing. Both read here rather than guessed by // the page: they come from files on disk, and one of them is an offer // to write into somebody's repository ("GET", "/api/devcontainer") => { let at = query_param(req.url(), "path") .map(|c| percent_decode(&c)) .unwrap_or_default(); let at = std::path::Path::new(at.trim()); let root = crate::repo::main_checkout(at); let has = root.as_deref().and_then(crate::devcontainer::of); let offer = has .is_none() .then(|| root.as_deref().and_then(crate::devcontainer::propose)) .flatten(); // What this project has been told to run where it cannot have the // file. Read from the settings on disk rather than from the page, // which is editing a copy it has not saved yet let desk = query_param(req.url(), "desk").map(|d| percent_decode(&d)); let plain = crate::config::load() .as_ref() .and_then(|c| c.project_of(desk.as_deref(), at).and_then(|p| p.setup.clone())) .unwrap_or_default(); req.respond(json_resp( serde_json::json!({ "has": has, "offer": offer, "plain": plain }), ))?; } // Put the offered file in the project. Worked out again on this side, // so what lands is what this side proposed whatever a page said ("POST", "/api/devcontainer") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let at = std::path::PathBuf::from( p.get("path").and_then(|v| v.as_str()).unwrap_or_default().trim(), ); let resp = match crate::repo::main_checkout(&at) .as_deref() .and_then(crate::devcontainer::propose) { None => serde_json::json!({ "ok": false, "error": crate::i18n::t("err.devcontainer.nothing") }), Some(d) => match crate::devcontainer::save(&d) { Ok(()) => serde_json::json!({ "ok": true, "at": d.at }), Err(e) => serde_json::json!({ "ok": false, "error": format!("{e:#}") }), }, }; req.respond(json_resp(resp))?; } ("GET", "/api/cli-help") => { let prog = query_param(req.url(), "cmd") .map(|c| percent_decode(&c)) .and_then(|c| c.split_whitespace().next().map(str::to_string)) .unwrap_or_default(); let resp = match cli_help(&prog) { Ok(help) => serde_json::json!({ "ok": true, "help": help }), Err(e) => serde_json::json!({ "ok": false, "error": e }), }; req.respond(json_resp(resp))?; } // Sends a test notification to one destination described in the body // ({"type":"slack","webhook":…} etc). "@name" fields are expanded from // the secret store, so a saved destination can be tested too. // The phones that have asked to be buzzed, and the key a browser needs // to ask. Behind the token like every other settings route: the list // says which devices a person has, which is theirs to know. ("GET", "/api/push") => { let (key, err) = match crate::push::public_key() { Ok(k) => (k, String::new()), Err(e) => (String::new(), e), }; // `claimed`: whether it is known which device it is. A phone that // finds its own unclaimed registers again, which claims it let subs: Vec = crate::push::subs() .into_iter() .map(|s| serde_json::json!({ "endpoint": s.endpoint, "name": s.name, "claimed": !s.device.is_empty() })) .collect(); req.respond(json_resp(serde_json::json!({ "key": key, "error": err, "subs": subs, })))?; } ("POST", "/api/push/subscribe") => { // Whose it is comes from the door, not from the body: this PC's // own screen, or the device the remote proxy says it let in let device = if header_value(&req, REMOTE_CLIENT_HEADER) == "1" { header_value(&req, REMOTE_DEVICE_HEADER).to_string() } else { crate::push::HERE.to_string() }; let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let resp = match serde_json::from_str::(&body) { Ok(sub) if !sub.endpoint.is_empty() => { crate::push::remember(crate::push::Sub { device, ..sub }); serde_json::json!({ "ok": true }) } Ok(_) => serde_json::json!({ "ok": false, "error": "no endpoint" }), Err(e) => serde_json::json!({ "ok": false, "error": e.to_string() }), }; req.respond(json_resp(resp))?; } ("POST", "/api/push/forget") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let endpoint = v.get("endpoint").and_then(|e| e.as_str()).unwrap_or(""); let gone = crate::push::forget(endpoint); req.respond(json_resp(serde_json::json!({ "ok": gone })))?; } // How many tokens the AIs on this PC used, and what that would cost // by the token (`crate::tokens`). Asking starts a look at the // records when the last is not recent (`again`: whatever its age); // the answer is what is counted so far, and how the look stands -- // the card asks again until it has ended ("GET", "/api/tokens") => { let url = req.url().to_string(); let days = query_param(&url, "days").and_then(|d| d.parse::().ok()).unwrap_or(30).clamp(1, crate::tokens::DAYS_KEPT as u32); let cli = query_param(&url, "cli").filter(|c| c == "claude" || c == "codex"); crate::tokens::look(query_param(&url, "again").is_some()); // How the look stood before the counts were read: one that ended // while they were being read says it is still going, so the card // asks once more rather than showing a count from before its end let looking = crate::tokens::looking(); let body = match crate::tokens::report(&crate::tokens::path(), days, cli.as_deref()) { Ok(report) => serde_json::json!({"looking": looking, "report": report}), Err(e) => serde_json::json!({"looking": looking, "error": format!("{e:#}")}), }; req.respond(json_resp(body))?; } // The accounts of an AI's CLI (`crate::accounts`), as the settings on // disk hold them, each with who it is signed in as -- read off what the // CLI wrote in its folder, never a token ("GET", "/api/ai-accounts") => { let list: Vec = crate::config::load() .map(|c| c.ai_accounts) .unwrap_or_default() .into_iter() .map(|a| { crate::accounts::bring_over(&a.id); let dir = crate::accounts::dir_of(&a.id); let who = crate::accounts::kind(&a.cli).and_then(|k| crate::accounts::signed_in_as(k, &dir)); serde_json::json!({"id": a.id, "cli": a.cli, "made": dir.is_dir(), "who": who, "dir": dir.display().to_string()}) }) .collect(); req.respond(json_resp(serde_json::json!({"accounts": list})))?; } // Signing an account in: a tab of its AI opened as it, where the CLI // asks for the sign-in itself. The board opens it, in the folder in // front, so this is the same from a phone ("POST", "/api/ai-accounts/login") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { return Ok(req.respond(json_resp(serde_json::json!({"error": "too big"})))?); }; let id = serde_json::from_str::(&body) .ok() .and_then(|v| v.get("id").and_then(|s| s.as_str()).map(str::to_string)) .unwrap_or_default(); let saved = crate::config::load().is_some_and(|c| c.ai_accounts.iter().any(|a| a.id == id)); let body = match saved { false => serde_json::json!({"error": crate::i18n::t("msg.account.unsaved")}), true => { crate::accounts::want_login(&id); serde_json::json!({"ok": true}) } }; req.respond(json_resp(body))?; } // An account taken away, sign-in and all: refused while a tab in the // settings runs as it (its folder would be in use, and the tab would // come up as nobody); otherwise its folder goes, and the account goes // out of the settings on disk at the same time, so the two cannot // disagree when the page is not saved ("POST", "/api/ai-accounts/forget") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { return Ok(req.respond(json_resp(serde_json::json!({"error": "too big"})))?); }; let id = serde_json::from_str::(&body) .ok() .and_then(|v| v.get("id").and_then(|s| s.as_str()).map(str::to_string)) .unwrap_or_default(); let path = crate::config::config_file_path(); let doc: serde_json::Value = std::fs::read_to_string(&path) .ok() .and_then(|t| serde_json::from_str(t.trim_start_matches('\u{feff}')).ok()) .unwrap_or_default(); let users = tabs_running_as(&doc, &id); let body = if !users.is_empty() { serde_json::json!({"error": crate::i18n::tp("msg.account.in_use", &[("tabs", &users.join(", "))])}) } else if crate::accounts::in_use(&id) { // A tab still running as it although the settings no longer // say so (started before another account was chosen for it), // or a desk kept in a file of its own that names it serde_json::json!({"error": crate::i18n::t("msg.account.in_use_live")}) } else { match crate::accounts::forget(&id).and_then(|()| forget_account_in_settings(&path, &id)) { Ok(()) => serde_json::json!({"ok": true}), Err(e) => serde_json::json!({"error": format!("{e:#}")}), } }; req.respond(json_resp(body))?; } // Scheduled prompts: what came of each run, and when each comes next, // as the settings hold them on disk -- a form not yet saved has // neither. Read off the files the board's loop writes, so a phone's // settings see the same as the window's ("GET", "/api/routines") => { let routines = crate::config::load().map(|c| c.routines).unwrap_or_default(); let now = crate::hooks::epoch_ms() / 1000; let next = crate::routine::next_times(&routines, &crate::schedule::Kept::load(), now); // The start of each answer: the whole is read by itself, when // a run is opened (a page polls this, a phone among them) let mut book = crate::routine::Book::read(); for run in book.runs.values_mut().flatten() { if let Some(reply) = run.reply.as_mut() { *reply = crate::routine::excerpt(reply); } } req.respond(json_resp(serde_json::json!({"next": next, "runs": book.runs, "now": now})))?; } // One run's whole answer ("GET", "/api/routines/reply") => { let q = |k: &str| query_param(req.url(), k).unwrap_or_default(); let n: u64 = q("n").parse().unwrap_or(0); let mut book = crate::routine::Book::read(); let reply = book.run_mut(&q("id"), n).and_then(|r| r.reply.clone()).unwrap_or_default(); req.respond(json_resp(serde_json::json!({"reply": reply})))?; } // "Run now", for a prompt as it was saved. One the board has not read // yet, or that cannot run, is said rather than queued for nothing ("POST", "/api/routines/run") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { return Ok(req.respond(json_resp(serde_json::json!({"error": "too big"})))?); }; let id = serde_json::from_str::(&body) .ok() .and_then(|v| v.get("id").and_then(|s| s.as_str()).map(str::to_string)) .unwrap_or_default(); let saved = crate::config::load().and_then(|c| c.routines.into_iter().find(|r| r.id == id)); let body = match saved { None => serde_json::json!({"error": crate::i18n::t("routine.err.unsaved")}), Some(r) => match r.fault() { Some(why) => serde_json::json!({"error": crate::i18n::t(why)}), None => { crate::routine::want_run(&r.id); serde_json::json!({"ok": true}) } }, }; req.respond(json_resp(body))?; } ("POST", "/api/notify/test") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let resp = match serde_json::from_str::(&body) { Ok(mut dest) => { let pw = password.lock().unwrap().clone(); let tokens = crate::config::load() .map(|c| c.resolve_tokens(pw.as_deref())) .unwrap_or_default(); let deref = |v: &str| -> String { match v.strip_prefix('@') { Some(k) => tokens.get(k).cloned().unwrap_or_default(), None => v.to_string(), } }; match &mut dest { crate::notify::Destination::Slack { webhook } | crate::notify::Destination::Discord { webhook } => { *webhook = deref(webhook) } crate::notify::Destination::Telegram { token, chat_id } => { *token = deref(token); *chat_id = deref(chat_id); } crate::notify::Destination::Windows {} | crate::notify::Destination::Phone { .. } => {} } match crate::notify::send_blocking( &dest, &crate::i18n::t("err.main.test_notify_body"), ) { Ok(()) => serde_json::json!({ "ok": true }), Err(e) => serde_json::json!({ "ok": false, "error": e }), } } Err(e) => serde_json::json!({ "ok": false, "error": e.to_string() }), }; req.respond(json_resp(resp))?; } // Whether this PC's own notifications would be drawn at all. The // switches are Windows' and not ours, and with them off a banner is // taken without a word and never shown -- so the tick for this PC // says so beside itself, with the way to the switch ("GET", "/api/notify/pc") => { req.respond(json_resp(serde_json::json!({ "off": crate::notify::banners_turned_off() })))?; } // Standalone settings have no board to ask about a server's key. // Use the same pending questions and exact-fingerprint answer as it. ("GET", "/api/server/keys") => { req.respond(json_resp(serde_json::json!({"keys": crate::ssh::key_changes()})))?; } ("POST", "/api/server/key") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body)?; let resp = match crate::ssh::answer_key_change( v["machine"].as_str().unwrap_or_default(), v["fingerprint"].as_str().unwrap_or_default(), v["trust"].as_bool().unwrap_or(false), ) { Ok(trusted) => serde_json::json!({"ok":true, "trusted":trusted}), Err(e) => serde_json::json!({"ok":false, "error":format!("{e:#}")}), }; req.respond(json_resp(resp))?; } // Reach a server with the settings as they stand on screen, before any // of it is saved. What comes back is either "it answered and let us // in" or the server's own words about why it did not -- which is the // difference between fixing one field now and finding out at launch ("POST", "/api/server/test") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); // The credentials are read from the vault here, by the names the // tab settles on, and never travel through the page let pw = password.lock().unwrap().clone(); if let Some(c) = crate::config::load() { crate::ssh::use_secrets(c.resolve_tokens(pw.as_deref())); } let text = |k: &str| { v.get(k).and_then(|x| x.as_str()).unwrap_or_default().trim().to_string() }; let desk = text("desk"); let tab = text("tab"); let under = |what: &str| { (!desk.is_empty() && !tab.is_empty()).then(|| format!("ssh/{desk}/{tab}/{what}")) }; // Built by the same function a launch builds it with, from the // settings as the page has them. A copy of that function here had // already drifted: a bastion's port arrives as the text typed into // its box, which the copy did not read, so a bastion on any port // but 22 was tested on 22 and launched on the right one let spec = crate::view::server_spec( &text("host"), port_of(v.get("port")).unwrap_or(22), &text("user"), Some(&server_of_page(&v)), &under, ); let resp = if spec.host.is_empty() || spec.user.is_empty() { serde_json::json!({"ok": false, "error": crate::i18n::t("err.server.incomplete")}) } else { // Asking for a folder is the smallest thing that proves the // whole road: the address, the credential, and that the far // end will actually serve files over it match crate::ssh::files( &spec, crate::ssh::FileJob::List { path: ".".into() }, SERVER_TEST_MS, ) { Ok(_) => serde_json::json!({"ok": true}), Err(e) => serde_json::json!({"ok": false, "error": format!("{e:#}")}), } }; req.respond(json_resp(resp))?; } // Which server a tab's command reaches, in the one spelling its name // is filed under (`ssh::Spec::machine`). The settings screen asks // rather than working it out: the tab row finds a server's name by // this spelling, and a second way of writing it in the page would // file a name the tab row never finds ("POST", "/api/server/machine") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let command = v.get("command").and_then(|c| c.as_str()).unwrap_or_default(); let argv = crate::config::CommandSpec::Line(command.to_string()).argv(); let server = v.get("server").map(server_of_page); let machine = crate::view::machine_of(&argv, server.as_ref()); req.respond(json_resp(serde_json::json!({ "machine": machine })))?; } // Syntax-check a Lua snippet ({"code":"…"}) so the settings UI can refuse // to save a quick action whose Lua is broken. Compile-only, never runs it. ("POST", "/api/lint") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let code = serde_json::from_str::(&body) .ok() .and_then(|v| v.get("code").and_then(|c| c.as_str()).map(str::to_string)) .unwrap_or_default(); let resp = match crate::hooks::lint_lua(&code) { None => serde_json::json!({ "ok": true }), Some(e) => serde_json::json!({ "ok": false, "error": e }), }; req.respond(json_resp(resp))?; } // The command line a tab will really be launched with. The settings // screen shows what it is given here rather than working it out for // itself: a second implementation in the page would be a second answer // to "what runs", and the two would drift the first time either moved ("POST", "/api/launch-line") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let str_of = |k: &str| { v.get(k) .and_then(|x| x.as_str()) .map(str::to_string) .filter(|s| !s.trim().is_empty()) }; // A line, or the words apart when the program's path has spaces -- // the two ways a tab writes its command let argv = v .get("command") .and_then(|c| serde_json::from_value::(c.clone()).ok()) .unwrap_or_default() .argv(); // A tab in a folder on another machine starts nothing here: the // shell that opens there is typed the folder and then the command // -- with the conversation's arguments, as the launch writes them // (tab::far_launch) -- and that line is what is shown. A plain // terminal there is typed the folder alone. Nothing is looked for // on this PC if let Some(far) = v.get("far").filter(|f| f.is_object()) { let cwd = far.get("cwd").and_then(|c| c.as_str()).unwrap_or_default(); let run = crate::desk::far_run(&argv).map(|_| { crate::tab::far_launch_line( &argv, &str_of("profile"), crate::resume_plan_of(str_of("resume").as_deref()), &crate::i18n::t("settings.tab.command.newid"), ) }); let typed = crate::ssh::typed_first(Some(cwd), run.as_deref()); let carry = match run.is_some() { true => crate::tab::carry_unused(&argv, &str_of("profile")), false => Some("unsupported"), }; req.respond(json_resp(serde_json::json!({ "argv": typed.map(|l| vec![l.trim_end().to_string()]).unwrap_or_default(), "added": 0, "carry": carry, "missing": null, "install_url": null, })))?; return Ok(()); } let line = crate::tab::launch_line( &argv, &str_of("profile"), crate::resume_plan_of(str_of("resume").as_deref()), &crate::i18n::t("settings.tab.command.newid"), ); // Whether the tab's "come back to this conversation" switch has // anything to act on for this command, so the screen can grey a // switch that would decide nothing (and say which of the two // reasons it is) let carry = match argv.is_empty() { true => None, false => crate::tab::carry_unused(&argv, &str_of("profile")), }; // The program this tab would start, when it is not on this PC: // said while the tab is being made, not found out when it does not // appear. Only for a command that starts a program here -- an // address, a page or the app's own panels start nothing to look // for, except the git panel, which needs git let head = argv.first().cloned().unwrap_or_default(); let starts_nothing = crate::config::is_editor_panel(&argv) || crate::config::is_sftp_panel(&argv) || crate::config::browser_url_of(&argv).is_some() || crate::config::ssh_endpoint(&argv).is_some() || head.eq_ignore_ascii_case("model"); let wanted = match () { _ if crate::config::is_git_panel(&argv) => Some("git".to_string()), _ if starts_nothing || head.trim().is_empty() => None, _ => Some(head.clone()), }; let missing = wanted.filter(|p| crate::tab::resolve_command(p).is_none()); let install_url = missing.as_deref().and_then(install_page); req.respond(json_resp(serde_json::json!({ "argv": line.argv, "added": line.added, "carry": carry, "missing": missing, "install_url": install_url, })))?; } // Recent rally history (newest first). Returns the id plus an excerpt to help a human tell them apart ("GET", "/api/rally/list") => { let mut arr: Vec = Vec::new(); for dir in crate::exchange::recent_runs(60) { if arr.len() >= 20 { break; } let id = dir .file_name() .and_then(|s| s.to_str()) .unwrap_or("") .to_string(); let t = std::fs::read_to_string(dir.join("transcript.md")).unwrap_or_default(); let record = std::fs::read_to_string(dir.join("record.lua")).unwrap_or_default(); // Use the first line that isn't a heading (#) or blank as an identifying excerpt let title = t .lines() .find(|l| !l.trim_start().starts_with('#') && !l.trim().is_empty()) .map(|l| l.chars().take(60).collect::()); // Don't show empty runs (ones on_start merely created) in the history let has_record = record.lines().any(|l| !l.trim_start().starts_with("--") && !l.trim().is_empty()); match &title { Some(tt) => arr.push(serde_json::json!({ "id": id, "title": tt })), None if has_record => { arr.push(serde_json::json!({ "id": id, "title": crate::i18n::t("rally.md.actions_only") })) } None => {} } } let resp = Response::from_string(serde_json::Value::Array(arr).to_string()).with_header( Header::from_bytes(&b"Content-Type"[..], &b"application/json; charset=utf-8"[..]) .unwrap(), ); req.respond(resp)?; } // Raw transcript for the chat-style result view. Returns the run's // transcript.md verbatim plus a `kind` hint (a rally, or a discussion // recorded before discussions were taken out -- those records stay on // disk and stay readable -- told apart by whether the run recorded // executed Lua). The page parses the // Markdown itself; the untouched download stays available separately. ("GET", "/api/rally/transcript") => { let picked = req .url() .split_once('?') .and_then(|(_, q)| q.split('&').find_map(|kv| kv.strip_prefix("run="))) .map(percent_decode) .and_then(|id| crate::exchange::run_by_id(&id)); match picked.or_else(crate::exchange::latest_run) { Some(dir) => { let md = std::fs::read_to_string(dir.join("transcript.md")).unwrap_or_default(); let record = std::fs::read_to_string(dir.join("record.lua")).unwrap_or_default(); // A rally records the Lua it executed; a discussion never // does. That presence is the reliable tell, independent of // the (localized) transcript headings. let kind = if record .lines() .any(|l| !l.trim_start().starts_with("--") && !l.trim().is_empty()) { "rally" } else { "discuss" }; let id = dir.file_name().and_then(|s| s.to_str()).unwrap_or(""); // Whether a durable replay exists (beyond its header comments) — // the view shows its download button only when there is one let replay = std::fs::read_to_string(dir.join("replay.lua")) .map(|s| has_replay_code(&s)) .unwrap_or(false); let body = serde_json::json!({ "md": md, "kind": kind, "id": id, "replay": replay }) .to_string(); let resp = Response::from_string(body).with_header( Header::from_bytes( &b"Content-Type"[..], &b"application/json; charset=utf-8"[..], ) .unwrap(), ); req.respond(resp)?; } None => { req.respond(Response::from_string("{}").with_header( Header::from_bytes( &b"Content-Type"[..], &b"application/json; charset=utf-8"[..], ) .unwrap(), ))?; } } } // Every screen of the settings, each card and each thing set on it, // in the language on screen: what the settings' own search looks // through -- the same index the ? answers from, so the two agree ("GET", "/api/settings/index") => { let idx = crate::guide::index(&|k: &str| crate::i18n::t(k)); req.respond(json_resp(serde_json::to_value(&idx).unwrap_or_default()))?; } // What a bug report carries, made now and handed to the person, never // sent anywhere (`crate::diagnose`). How many things were hidden in it // goes along, so the page can say to look before attaching it // // Made and answered on a thread of its own: counting the folders, or a // disk that has stopped answering, can take many seconds, and this // server takes one request at a time -- the page would not load or // save anything until the file was ready ("GET", "/api/diagnostics") => { let _ = std::thread::Builder::new().name("shikisha-diagnostics".into()).spawn(move || { let said = match crate::diagnose::bundle() { Ok((name, bytes, hid)) => { let cd = format!("attachment; filename=\"{name}\""); let resp = Response::from_data(bytes) .with_header(Header::from_bytes(&b"Content-Type"[..], &b"application/zip"[..]).unwrap()) .with_header(Header::from_bytes(&b"Content-Disposition"[..], cd.as_bytes()).unwrap()) .with_header(Header::from_bytes(&b"X-Hidden"[..], hid.to_string().as_bytes()).unwrap()) .with_header(Header::from_bytes(&b"X-File-Name"[..], name.as_bytes()).unwrap()); req.respond(resp) } Err(e) => req.respond(Response::from_string(format!("{e:#}")).with_status_code(500)), }; if let Err(e) = said { crate::append_hook_log(&format!("WebUI: {e}")); } }); } // The durable replay script: css/xpath anchors only, no digest/ref // dependency — paste into ▶ run mode or an automation, on any PC. // ?run= for a specific run, otherwise the latest. 404 when the // run recorded nothing replayable ("GET", "/api/rally/replay") => { let picked = req .url() .split_once('?') .and_then(|(_, q)| q.split('&').find_map(|kv| kv.strip_prefix("run="))) .map(percent_decode) .and_then(|id| crate::exchange::run_by_id(&id)); let found = picked.or_else(crate::exchange::latest_run).and_then(|dir| { let text = std::fs::read_to_string(dir.join("replay.lua")).unwrap_or_default(); let name = dir.file_name().and_then(|s| s.to_str()).unwrap_or("run").to_string(); has_replay_code(&text).then_some((text, name)) }); match found { Some((text, name)) => { let cd = format!("attachment; filename=\"shikisha-macro-{name}.lua\""); let resp = Response::from_string(text) .with_header( Header::from_bytes( &b"Content-Type"[..], &b"text/plain; charset=utf-8"[..], ) .unwrap(), ) .with_header( Header::from_bytes(&b"Content-Disposition"[..], cd.as_bytes()) .unwrap(), ); req.respond(resp)?; } None => { req.respond(Response::from_string("no replay").with_status_code(404))?; } } } // Lets the rally result be downloaded as a single Markdown file. ?run= for a specific run, // otherwise the latest. Contents: the human-readable flow (transcript) + the verdict + the executed Lua (record, paste it to reproduce). // Whatever the orchestrator (AI+AI, etc.), leaving transcript.md/record.lua in the run folder lets it be downloaded through the same path ("GET", "/api/rally/download") => { let picked = req .url() .split_once('?') .and_then(|(_, q)| q.split('&').find_map(|kv| kv.strip_prefix("run="))) .map(percent_decode) .and_then(|id| crate::exchange::run_by_id(&id)); match picked.or_else(crate::exchange::latest_run) { Some(dir) => { let transcript = std::fs::read_to_string(dir.join("transcript.md")).unwrap_or_default(); let record = std::fs::read_to_string(dir.join("record.lua")).unwrap_or_default(); let mut md = String::new(); if transcript.trim().is_empty() { md.push_str(&crate::i18n::t("rally.md.empty")); } else { md.push_str(&transcript); } if !record.trim().is_empty() { md.push_str(&crate::i18n::t("rally.md.lua_heading")); md.push_str(&record.replace('\n', "\n ")); md.push('\n'); } let name = dir.file_name().and_then(|s| s.to_str()).unwrap_or("rally"); let cd = format!("attachment; filename=\"rally-{name}.md\""); let resp = Response::from_string(md) .with_header( Header::from_bytes( &b"Content-Type"[..], &b"text/markdown; charset=utf-8"[..], ) .unwrap(), ) .with_header( Header::from_bytes(&b"Content-Disposition"[..], cd.as_bytes()).unwrap(), ); req.respond(resp)?; } None => { req.respond(Response::from_string("no rally").with_status_code(404))?; } } } // Read/write a desk definition file (external file reference) ("GET", "/api/desk") => { let Some(p) = safe_desk_path(req.url(), config_path) else { return req .respond(Response::from_string("bad path").with_status_code(400)) .map_err(Into::into); }; serve_user_json(req, &p, r#"{"tabs":[]}"#)?; } ("POST", "/api/desk") => { let Some(p) = safe_desk_path(req.url(), config_path) else { return req .respond(Response::from_string("bad path").with_status_code(400)) .map_err(Into::into); }; let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; match serde_json::from_str::(&body) { Ok(mut doc) => { if let Some(dir) = p.parent() { let _ = std::fs::create_dir_all(dir); } // The same as the settings file: every tab leaves with a uid let before = doc.clone(); crate::config::fill_tab_uids(&mut doc); let body = match doc == before { true => body, false => serde_json::to_string_pretty(&doc).unwrap_or(body), }; crate::crypto::write_atomic(&p, &body)?; req.respond(Response::from_string(r#"{"ok":true}"#))?; } Err(e) => { let msg = serde_json::json!({ "ok": false, "error": e.to_string() }); req.respond(Response::from_string(msg.to_string()).with_status_code(400))?; } } } // ── Secrets (equivalent to GitHub Secrets) ──────────────────── // The master password is never exposed to the page or the network. // The listing returns only keys and descriptions; values are never returned ("GET", "/api/secrets") => { let path = secrets_file(config_path); let pw = password.lock().unwrap().clone(); let encrypted = std::fs::read_to_string(&path) .map(|t| crate::crypto::is_encrypted(&t)) .unwrap_or(false); let (mode, items): (&str, Vec) = if !path.exists() { ("empty", Vec::new()) } else if encrypted && pw.is_none() { // If it's encrypted and there's no password, we can't even show the listing ("locked", Vec::new()) } else { match crate::config::list_secrets(&path, pw.as_deref()) { Ok(list) => ( if encrypted { "encrypted" } else { "plaintext" }, list.into_iter() .map(|(k, m)| { serde_json::json!({ "key": k, "description": m.desc, "human": m.human, "ai": m.ai, "urls": m.urls, }) }) .collect(), ), Err(_) => ("locked", Vec::new()), } }; req.respond(json_resp(serde_json::json!({ "mode": mode, "has_password": pw.is_some(), "secrets": items, })))?; } ("POST", "/api/secrets/set") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let s = |k| p.get(k).and_then(|v| v.as_str()).unwrap_or(""); let (key, value) = (s("key").trim(), s("value")); let path = secrets_file(config_path); let pw = password.lock().unwrap().clone(); // An empty value means "leave the password alone" -- what a secret // is *for* can be changed without going to find it again. The store // refuses that for a name it has never seen let flag = |k, or| p.get(k).and_then(|v| v.as_bool()).unwrap_or(or); let urls: Vec = p .get("urls") .and_then(|v| v.as_array()) .map(|a| { a.iter() .filter_map(|h| h.as_str()) .map(|h| h.trim().to_string()) .filter(|h| !h.is_empty()) .collect() }) .unwrap_or_default(); // The same question the screen asked while it was being typed. A // line that reaches too far is refused here as well, because the // screen is not the only way in let bad = urls .iter() .find_map(|u| crate::config::url_fault(u).map(|why| (u.clone(), why))); let meta = crate::config::SecretMeta { human: flag("human", true), ai: flag("ai", false), urls, desc: s("description").to_string(), }; let resp = match bad { Some((u, why)) => serde_json::json!({ "ok": false, "error": format!("{}: {}", u, crate::i18n::t(why)), }), None => match crate::config::upsert_secret(&path, pw.as_deref(), key, &meta, value) { Ok(()) => serde_json::json!({ "ok": true }), Err(e) => serde_json::json!({ "ok": false, "error": e.to_string() }), }, }; req.respond(json_resp(resp))?; } // One secret filed again under another name, value and all, without the // value ever passing through the page. What a new desk does when it // starts from another desk's connections and destinations: each desk // keeps its own keys, so deleting one desk later cannot take the // other's with it. Only the names the program itself files keys under // can be copied, and only into the same kind ("POST", "/api/secrets/copy") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let s = |k| p.get(k).and_then(|v| v.as_str()).unwrap_or("").trim().to_string(); let (from, to) = (s("from"), s("to")); let kind = |k: &str| ["provider/", "notify/"].into_iter().find(|pre| k.starts_with(pre)); let path = secrets_file(config_path); let pw = password.lock().unwrap().clone(); let resp = match (kind(&from), kind(&to)) { (Some(a), Some(b)) if a == b && from != to => { let meta = crate::config::list_secrets(&path, pw.as_deref()) .ok() .and_then(|l| l.into_iter().find(|(k, _)| *k == from).map(|(_, m)| m)); match (crate::config::secret_value(&path, pw.as_deref(), &from), meta) { (Some(value), Some(meta)) => { match crate::config::upsert_secret(&path, pw.as_deref(), &to, &meta, &value) { Ok(()) => serde_json::json!({ "ok": true }), Err(e) => serde_json::json!({ "ok": false, "error": e.to_string() }), } } _ => serde_json::json!({ "ok": false, "missing": true }), } } _ => serde_json::json!({ "ok": false, "error": "not a copyable key" }), }; req.respond(json_resp(resp))?; } ("POST", "/api/secrets/delete") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let key = p.get("key").and_then(|v| v.as_str()).unwrap_or(""); let path = secrets_file(config_path); let pw = password.lock().unwrap().clone(); let resp = match crate::config::delete_secret(&path, pw.as_deref(), key) { Ok(()) => serde_json::json!({ "ok": true }), Err(e) => serde_json::json!({ "ok": false, "error": e.to_string() }), }; req.respond(json_resp(resp))?; } // List the available models for a provider (the "candidates" button). // Hits the OpenAI-compatible {base_url}/models so the user can pick a // real model name instead of guessing. Resolves an @secret api_key and // any custom headers just like resolve_provider does. ("POST", "/api/provider/models") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let s = |k| p.get(k).and_then(|v| v.as_str()).unwrap_or(""); let base_url = s("base_url").trim(); let api_key = s("api_key").trim(); let pw = password.lock().unwrap().clone(); let tokens = crate::config::load() .map(|c| c.resolve_tokens(pw.as_deref())) .unwrap_or_default(); let deref = |v: &str| -> String { match v.strip_prefix('@') { Some(k) => tokens.get(k).cloned().unwrap_or_default(), None => v.to_string(), } }; let mut headers = std::collections::HashMap::new(); if let Some(obj) = p.get("headers").and_then(|h| h.as_object()) { for (k, v) in obj { if let Some(vs) = v.as_str() { headers.insert(k.clone(), deref(vs)); } } } if headers.is_empty() && !api_key.is_empty() { headers.insert("Authorization".into(), format!("Bearer {}", deref(api_key))); } let resp = if base_url.is_empty() { serde_json::json!({ "ok": false, "error": crate::i18n::t("webui.err.empty_base_url") }) } else { match crate::bridge::list_models(base_url, &headers) { Ok(models) => serde_json::json!({ "ok": true, "models": models }), Err(e) => serde_json::json!({ "ok": false, "error": e.to_string() }), } }; req.respond(json_resp(resp))?; } // Export a single desk, scripts and all, as one file. // Addressed by index into the saved config — not the screen's in-progress edits ("POST", "/api/desk/export") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let index = p.get("index").and_then(|v| v.as_u64()).unwrap_or(0) as usize; let resp = match crate::deskpack::pack(config_path, index) { Ok((name, text)) => { let picked = picker().and_then(|p| { p.save( &crate::i18n::t("settings.desk.export.title"), config_path.parent(), &name, (&crate::i18n::t("settings.desk.file_kind"), "json"), ) }); match picked { // Write to the chosen location. This is fine to be outside the config folder, since the user picked it Some(path) => match crate::crypto::write_atomic(&path, &text) { Ok(()) => serde_json::json!({ "ok": true, "path": path.display().to_string(), }), Err(e) => { serde_json::json!({ "ok": false, "error": e.to_string() }) } }, None => serde_json::json!({ "ok": false, "cancelled": true }), } } Err(e) => serde_json::json!({ "ok": false, "error": format!("{e:#}") }), }; req.respond( Response::from_string(resp.to_string()).with_header( Header::from_bytes( &b"Content-Type"[..], &b"application/json; charset=utf-8"[..], ) .unwrap(), ), )?; } // Import an exported file. Adds one desk to the config ("POST", "/api/desk/import") => { let picked = picker().and_then(|p| { p.open( &crate::i18n::t("settings.desk.import.title"), config_path.parent(), (&crate::i18n::t("settings.desk.file_kind"), "json"), ) }); let resp = match picked { Some(path) => match std::fs::read_to_string(&path) .map_err(anyhow::Error::from) .and_then(|t| crate::deskpack::unpack(config_path, &t)) { Ok(placed) => serde_json::json!({ "ok": true, "name": placed.name, "files": placed.files, "moved": placed.moved.iter() .map(|(f, t)| serde_json::json!([f, t])) .collect::>(), }), Err(e) => serde_json::json!({ "ok": false, "error": format!("{e:#}") }), }, None => serde_json::json!({ "ok": false, "cancelled": true }), }; req.respond( Response::from_string(resp.to_string()).with_header( Header::from_bytes( &b"Content-Type"[..], &b"application/json; charset=utf-8"[..], ) .unwrap(), ), )?; } // Read/write automation (per-event files) ("GET", "/api/automation") => { let Some(dir) = safe_dir_path(req.url(), config_path) else { return req .respond(Response::from_string("bad path").with_status_code(400)) .map_err(Into::into); }; let mut map = serde_json::Map::new(); // A script written as one file holds every trigger in it. Read as a // folder it answered "nothing set" for a tab whose script runs if dir.is_file() { let body = std::fs::read_to_string(&dir).unwrap_or_default(); map.insert("file".into(), serde_json::Value::String(body)); } for name in EVENT_FILES.iter().filter(|_| !dir.is_file()) { let f = dir.join(format!("{name}.lua")); let body = std::fs::read_to_string(&f).unwrap_or_default(); map.insert(name.to_string(), serde_json::Value::String(body)); } let resp = Response::from_string(serde_json::Value::Object(map).to_string()) .with_header( Header::from_bytes( &b"Content-Type"[..], &b"application/json; charset=utf-8"[..], ) .unwrap(), ); req.respond(resp)?; } ("POST", "/api/automation") => { let Some(dir) = safe_dir_path(req.url(), config_path) else { return req .respond(Response::from_string("bad path").with_status_code(400)) .map_err(Into::into); }; let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let parsed: serde_json::Value = serde_json::from_str(&body)?; // One file, written back whole. Never a folder made in its place: // that would fail on the file already there, or, where the file was // missing, leave a folder with a script's name that nothing loads if let Some(code) = parsed.get("file").and_then(|v| v.as_str()) { if dir.is_dir() { req.respond(Response::from_string("not a file").with_status_code(400))?; return Ok(()); } crate::crypto::write_atomic(&dir, code)?; req.respond(Response::from_string(r#"{"ok":true}"#))?; return Ok(()); } if dir.is_file() { req.respond(Response::from_string("not a folder").with_status_code(400))?; return Ok(()); } std::fs::create_dir_all(&dir)?; for name in EVENT_FILES { let Some(code) = parsed.get(name).and_then(|v| v.as_str()) else { continue; }; let f = dir.join(format!("{name}.lua")); if code.trim().is_empty() { // Emptying it means "do nothing for this event" = delete the whole file let _ = std::fs::remove_file(&f); } else { crate::crypto::write_atomic(&f, code)?; } } req.respond(Response::from_string(r#"{"ok":true}"#))?; } // Opens the standard Windows file-picker dialog. // The browser can't hand over a real file path for safety reasons, so we open it on this side ("POST", "/api/pick") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let kind = p.get("kind").and_then(|v| v.as_str()).unwrap_or("file"); let fallback = crate::i18n::t("settings.pick.title"); let title = p.get("title").and_then(|v| v.as_str()).unwrap_or(&fallback); let start = p .get("start") .and_then(|v| v.as_str()) .filter(|s| !s.is_empty()) .map(std::path::PathBuf::from) .filter(|p| p.exists()) .or_else(|| default_pick_dir(kind, config_path)); let picked = picker().and_then(|p| match kind == "dir" { true => p.folder(title, start.as_deref()), false => p.open(title, start.as_deref(), ("", "")), }); let resp = match picked { Some(path) => { serde_json::json!({ "ok": true, "path": display_path(&path, config_path) }) } None => serde_json::json!({ "ok": false }), }; req.respond( Response::from_string(resp.to_string()).with_header( Header::from_bytes( &b"Content-Type"[..], &b"application/json; charset=utf-8"[..], ) .unwrap(), ), )?; } // The same folder list the sidebar walks, for the settings screen. // // A phone has no file dialog of its own, and /api/pick opens one on // the PC -- so this hands back what is in a folder and the page walks // it, the way the sidebar's "open another folder" already does. A file // is answered as itself, so a walk that lands on one is a choice made. // Read-only: nothing here writes, the form saves what was chosen ("POST", "/api/walk") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let want_files = p.get("files").and_then(|v| v.as_bool()).unwrap_or(false); let asked = p.get("path").and_then(|v| v.as_str()).unwrap_or("").trim(); // Paths in the settings are written relative to the config folder // when they are under it (display_path); read them back the same way let at = match asked { "" => String::new(), a => { let raw = std::path::Path::new(a); let full = if raw.is_absolute() { raw.to_path_buf() } else { config_path.parent().unwrap_or(std::path::Path::new(".")).join(raw) }; full.display().to_string() } }; let here = std::path::Path::new(&at); let resp = if !at.is_empty() && here.is_file() { serde_json::json!({ "ok": true, "file": true, "chosen": display_path(here, config_path), }) } else { let walk = if want_files { crate::uistate::BrowseState::with_files(&at) } else { crate::uistate::BrowseState::of(&at) }; serde_json::json!({ "ok": true, "at": walk.at, "up": walk.up, "dirs": walk.dirs, "files": walk.files, "error": walk.error, // What choosing this folder would write into the settings "chosen": if walk.at.is_empty() { String::new() } else { display_path(std::path::Path::new(&walk.at), config_path) }, }) }; req.respond(json_resp(resp))?; } // Status of the phone-usable feature (also returns which network is available) // What each AI CLI can do about carrying its conversation across a // restart, and — where it needs one — whether its hook is installed. // The person asked "will my conversation survive?", and this answers // that per CLI rather than describing a mechanism // The saved browser logins, to manage. Names and counts only -- the // cookies themselves never come back out of here ("GET", "/api/logins") => { let rows: Vec = crate::browserstate::list() .into_iter() .map(|e| serde_json::json!({ "label": e.label, "count": e.count })) .collect(); req.respond(json_resp(serde_json::json!(rows)))?; } // The answers about sites' notifications, to manage ("GET", "/api/sitenotices") => { let rows: Vec = crate::pagenotice::answers() .into_iter() .map(|(site, allow)| { let host = crate::pagenotice::shown(&site).to_string(); serde_json::json!({ "site": site, "host": host, "allow": allow }) }) .collect(); req.respond(json_resp(serde_json::json!(rows)))?; } ("POST", "/api/sitenotices/delete") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let site = v.get("site").and_then(|x| x.as_str()).unwrap_or_default(); let ok = crate::pagenotice::forget(site).is_ok(); req.respond(json_resp(serde_json::json!({ "ok": ok })))?; } ("POST", "/api/logins/delete") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let label = v.get("label").and_then(|x| x.as_str()).unwrap_or_default(); let ok = crate::browserstate::delete(label).is_ok(); req.respond(json_resp(serde_json::json!({ "ok": ok })))?; } // The saved page snapshots, newest first, each as a data URL so the // card can show it without a second authenticated image request. A // handful is the normal case; the newest are enough to glance at ("GET", "/api/snapshots") => { use base64::Engine as _; let b64 = base64::engine::general_purpose::STANDARD; let rows: Vec = crate::browserstate::snapshots() .into_iter() .take(24) .filter_map(|(label, path)| { let bytes = std::fs::read(&path).ok()?; let data = format!("data:image/png;base64,{}", b64.encode(&bytes)); Some(serde_json::json!({ "label": label, "data": data })) }) .collect(); req.respond(json_resp(serde_json::json!(rows)))?; } ("POST", "/api/snapshots/delete") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let label = v.get("label").and_then(|x| x.as_str()).unwrap_or_default(); let ok = crate::browserstate::delete_snapshot(label).is_ok(); req.respond(json_resp(serde_json::json!({ "ok": ok })))?; } // Which GitHub account a git account's token speaks as, and for how // much longer. Asked per account of one desk, because each keeps its // own token. // // The state and the date, never the value -- and a token that has run // out is said out loud rather than quietly becoming "no token", because // a row that stops showing pull request numbers looks exactly like a // branch that has none ("GET", "/api/github") => { let account = query_param(req.url(), "account") .map(|c| percent_decode(&c)) .unwrap_or_default(); // Asked of the account itself, as every other reader does: a gh // account's token comes from GitHub CLI, the others' from the store. // One not saved yet is not in the settings file, and has only the // store to ask let spec = crate::config::load() .and_then(|cfg| cfg.git_accounts.into_iter().find(|a| a.name == account.trim())); // Or one of the sign-ins this PC holds: git's credential store's, // by login (`pc`), or GitHub CLI's, by login on a host (`gh`). Both // are asked of the program that holds them, the same as when git // signs in as them; the token is read here and sent to GitHub only let pc = query_param(req.url(), "pc").map(|c| percent_decode(&c)).unwrap_or_default(); let gh = query_param(req.url(), "gh").map(|c| percent_decode(&c)).unwrap_or_default(); let host = query_param(req.url(), "host").map(|c| percent_decode(&c)).unwrap_or_default(); let host = if host.trim().is_empty() { crate::config::GITHUB_HOST.to_string() } else { host.trim().to_ascii_lowercase() }; let own = if crate::pr::plain_name(pc.trim()) { crate::pr::pc_token(Some(pc.trim())).ok() } else if crate::pr::plain_name(gh.trim()) && crate::pr::plain_name(&host) { crate::pr::gh_token_of(&host, gh.trim()) } else if account.trim().is_empty() { None } else { let pw = password.lock().unwrap().clone(); let look = |k: &str| crate::config::secret_value(&secrets_file(config_path), pw.as_deref(), k); match spec { Some(spec) => spec.token(&look), None => look(&crate::config::git_token_key(account.trim())), } }; let kind = own.as_deref().map(crate::config::token_kind); let said = crate::pr::probe(own); req.respond(json_resp(serde_json::json!({ "signed_in": said.ok, "source": said.source, "login": said.login, "expires_at": said.expires_at, "expires_days": said.expires_in_days, "status": said.status, "kind": kind, })))?; } // The secrets nothing in the settings claims any more. Answered here // rather than worked out on the screen, because what owns what is a // fact about the settings file and is tested with it ("GET", "/api/secrets/orphans") => { let path = secrets_file(config_path); let pw = password.lock().unwrap().clone(); let keys: Vec = crate::config::list_secrets(&path, pw.as_deref()) .map(|l| l.into_iter().map(|(k, _)| k).collect()) .unwrap_or_default(); let orphans = match crate::config::load() { Some(cfg) => crate::config::orphan_secrets(&cfg, &keys), // Without a config nothing can be said to be unclaimed, and // guessing here would offer to delete somebody's passwords None => Vec::new(), }; req.respond(json_resp(serde_json::json!({ "orphans": orphans })))?; } // Each AI's allowance as it stands now, read fresh for the settings // screen whether or not a tab of that AI is open, and whether this // machine has what the reading needs -- so the screen can say why a // reading is or is not there. Answered off this thread: Claude's is a // request to a service, and the other settings requests should not // wait behind it ("GET", "/api/usage") => { std::thread::spawn(move || { // Every AI at once, each on a thread of its own: one service // slow to answer must not hold up the others' lines let asks: Vec<_> = crate::limits::Source::ALL .into_iter() .map(|s| std::thread::spawn(move || (s, s.ready(), s.read()))) .collect(); // An array, in the order of the list: the screen shows them in // the order they come let out: Vec = asks .into_iter() .filter_map(|h| h.join().ok()) .map(|(s, ready, got)| { let reading = got.map(|l| { let wins: Vec = l .wins .iter() .map(|a| { serde_json::json!({ "span": a.span.map(|s| s.key()), "model": a.only, "pct": a.window.pct, "resets_at": a.window.resets_at, }) }) .collect(); serde_json::json!({"wins": wins, "as_of": l.as_of, "taken": l.taken, "record": l.from_record}) }); serde_json::json!({"key": s.key(), "name": s.name(), "ready": ready, "reading": reading}) }) .collect(); let _ = req.respond(json_resp(serde_json::Value::Array(out))); }); } // How many terminals this PC's resident process still holds, for the // line beside its setting (local-keeper plan §3). Off this thread: it // may wait on the resident process ("GET", "/api/keeper") => { std::thread::spawn(move || { let body = match crate::localkeep::held_count() { Ok(held) => serde_json::json!({ "ok": true, "held": held }), Err(e) => serde_json::json!({ "ok": false, "error": format!("{e:#}") }), }; let _ = req.respond(json_resp(body)); }); } // The person asked what it still holds to stop: every terminal it // holds ends, the AIs in them with it, and the resident process goes ("POST", "/api/keeper/stop") => { std::thread::spawn(move || { let body = match crate::localkeep::stop_all() { Ok(()) => serde_json::json!({ "ok": true }), Err(e) => serde_json::json!({ "ok": false, "error": format!("{e:#}") }), }; let _ = req.respond(json_resp(body)); }); } // What this machine already offers to open a tab on: the installed WSL // distributions and the hosts in the person's own ssh config. Both were // things the settings screen asked people to type from memory ("GET", "/api/discover") => { req.respond(json_resp(serde_json::json!({ "wsl": crate::discover::wsl_distros(), "ssh": crate::discover::ssh_hosts(), })))?; } // Which pseudo console the terminals are running on. There is nothing // to set: what decides it is whether the file shipped, so this reports // and the download fixes. It is here at all because both ways of // falling back to Windows' older one are completely silent ("GET", "/api/conpty") => { #[cfg(windows)] let body = { let r = crate::conpty::report(); serde_json::json!({ "bundled": r.bundled, "version": r.version, "path": r.path.display().to_string(), "missing": r.missing.map(|m| m.id()), }) }; // A unix pty is the system's own and needs nothing shipped beside // the exe, so there is nothing here to report on or to fix #[cfg(not(windows))] let body = serde_json::json!({ "bundled": false, "version": "", "path": "", "missing": serde_json::Value::Null, }); req.respond(json_resp(body))?; } // Every action the window has, with the key it answers to right now. // The names are the app's own, so the settings screen never has its // own idea of what this program can do // The keys that open the tools from any program: what each is set to, // whether it could be registered, and when it last arrived ("GET", "/api/hotkeys") => { req.respond(json_resp(serde_json::json!({ "rows": crate::hotkeys::rows(), "active": crate::hotkeys::active(), })))?; } // The icon set the quick-command picker chooses from. Asked for once, // when the picker is first opened ("GET", p) if crate::quick::asset(p).is_some() => { let bytes = crate::quick::asset(p).unwrap_or_default(); req.respond( Response::from_data(bytes) .with_header( Header::from_bytes(&b"Content-Type"[..], &b"text/plain; charset=utf-8"[..]).unwrap(), ) .with_header( Header::from_bytes(&b"Cache-Control"[..], &b"public, max-age=86400"[..]).unwrap(), ), )?; } // Where every quick command sits, worked out by the same function the // board is drawn from: after the grid is resized, and before the page // shows what a hand-written file says. The page never places a button // by a rule of its own, so the settings and the launcher cannot come to // disagree about where one is ("POST", "/api/quick/arrange") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { return req .respond(Response::from_string("payload too large").with_status_code(413)) .map_err(Into::into); }; match serde_json::from_str::(&body) { Ok(spec) => { let spec = crate::quick::arrange(&spec); req.respond(json_resp(serde_json::json!({ "ok": true, "svgs": crate::quick::drawings(&spec), "spec": spec, })))? } Err(e) => req.respond(json_resp(serde_json::json!({ "ok": false, "error": e.to_string(), })))?, } } ("GET", "/api/keys") => { let (map, errs) = crate::keys::Keys::load(crate::config::load().as_ref()); let shown: std::collections::HashMap<&str, String> = crate::keys::ACTIONS .iter() .map(|a| (a.name, String::new())) .chain( map.help_rows() .into_iter() .filter_map(|(k, d)| { let name = crate::keys::ACTIONS.iter().find(|a| a.desc == d)?.name; Some((name, k)) }), ) .collect(); // What has a key that works from any program is set in that list, // not twice: that key reaches it in this window as well let rows: Vec = crate::keys::ACTIONS .iter() .filter(|a| !crate::hotkeys::ON_THE_BOARD.contains(&a.name)) .map(|a| { serde_json::json!({ "name": a.name, "desc": crate::i18n::t(a.desc), "now": shown.get(a.name).cloned().unwrap_or_default(), }) }) .collect(); req.respond(json_resp(serde_json::json!({ "prefix": map.prefix_shown(), "rows": rows, "problems": errs, })))?; } // Every colour scheme this machine can name, in the order they are // found. The names come from what the person already has, so the list // is the point: a scheme they cannot see the name of is one they will // never type ("GET", "/api/themes") => { let rows: Vec = crate::theme::available() .into_iter() .map(|s| serde_json::json!({ "name": s.name, "colors": s.swatch() })) .collect(); // What is on screen right now comes back too, because a scheme // written out in the settings by hand is in no list and would // otherwise be a blank where the person's own colours are let look = crate::config::load().map(|c| c.appearance).unwrap_or_default(); let now = look.scheme(); req.respond(json_resp(serde_json::json!({ "default": crate::theme::DEFAULT_NAME, "current": { "name": now.name, "colors": now.swatch() }, "list": rows, })))?; } ("GET", "/api/resume") => { // What the person answered about each CLI's hook, shown as the // value it is: set up, left alone, or not asked yet let answers = crate::config::load().map(|c| c.agent_hooks).unwrap_or_default(); let rows: Vec = crate::profile::all() .into_iter() .filter_map(|p| { let r = p.resume.as_ref()?; // In the order the app itself tries them, so what is shown // is what will actually happen let how = if !r.new_id.is_empty() { "minted" } else if r.record.is_some() { "record" } else if r.hook.is_some() { "hook" } else if !r.newest_here.is_empty() { "newest" } else { "none" }; let hook = crate::agenthook::targets() .into_iter() .find(|t| t.name == p.name) .map(|t| { serde_json::json!({ "file": t.file.display().to_string(), "status": format!("{:?}", crate::agenthook::status(&t)) .split('(').next().unwrap_or("").to_string(), "preview": crate::agenthook::preview(&t), "approval": crate::agenthook::approval_file(&t).map(|f| f.display().to_string()), "answer": answers.get(&t.name).cloned().unwrap_or_default(), "used": crate::agenthook::in_use(&t), }) }); Some(serde_json::json!({ "name": p.name, "how": how, "hook": hook })) }) .collect(); req.respond(json_resp(serde_json::json!(rows)))?; } // Whether a new worktree is written into an AI CLI's own list of // trusted folders, for each CLI that keeps one: the answer kept, shown // as the value it is (written, not written, or not answered yet), and // the file the yes goes in ("GET", "/api/worktree-trust") => { let rows: Vec = crate::aitrust::rows() .into_iter() .map(|(k, answer, file)| serde_json::json!({ "ai": k.name, "answer": answer, "file": file })) .collect(); req.respond(json_resp(serde_json::json!(rows)))?; } ("POST", "/api/worktree-trust") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let ai = v.get("ai").and_then(|x| x.as_str()).unwrap_or_default().to_string(); let resp = match v.get("on").and_then(|x| x.as_bool()) { None => serde_json::json!({ "ok": false, "error": "say on or off" }), Some(on) => match crate::aitrust::set(&ai, on) { Ok(()) => serde_json::json!({ "ok": true }), Err(e) => serde_json::json!({ "ok": false, "error": e }), }, }; req.respond(json_resp(resp))?; } // The skill that teaches an AI to ask another tab, for each CLI that has // somewhere to keep one: how it stands, where it goes, and its words ("GET", "/api/skill") => { let rows: Vec = crate::skill::statuses() .into_iter() .filter(|(_, v)| v.state != "none") .map(|(ai, v)| serde_json::json!({ "ai": ai, "name": v.name, "state": v.state, "file": v.file, "preview": crate::skill::text(), })) .collect(); req.respond(json_resp(serde_json::json!(rows)))?; } ("POST", "/api/skill") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let ai = v.get("ai").and_then(|x| x.as_str()).unwrap_or_default(); let on = v.get("on").and_then(|x| x.as_bool()).unwrap_or(false); let known = crate::skill::statuses().get(ai).is_some_and(|s| s.state != "none"); let resp = if !known { serde_json::json!({ "ok": false, "error": "no such CLI" }) } else { let done = if on { crate::skill::install(ai).map(|_| ()) } else { crate::skill::remove(ai) }; match done { Ok(()) => serde_json::json!({ "ok": true, "state": crate::skill::status(ai).word() }), Err(e) => serde_json::json!({ "ok": false, "error": e.to_string() }), } }; req.respond(json_resp(resp))?; } // Take this app's hook entries out of the AI CLIs' files on a server, // there and then: asked before its entry is removed from the settings, // after which nothing could reach it to take them out. Named by the // entry, read from the settings on disk, so the page never hands over // an address or a path ("POST", "/api/farhooks/takeout") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let name = v.get("host").and_then(|x| x.as_str()).unwrap_or_default().trim().to_string(); let host = crate::config::load().and_then(|c| c.hosts.into_iter().find(|h| h.name.trim() == name)); let resp = match host { None => serde_json::json!({ "ok": false, "error": "no such server" }), Some(h) => match crate::agenthook::far_take_out_all(&h) { Ok(()) => serde_json::json!({ "ok": true }), Err(e) => serde_json::json!({ "ok": false, "error": e }), }, }; req.respond(json_resp(resp))?; } // What runs on a machine entry while the app is away (far-keep plan // §7.6): every terminal the bridge holds on each of its machines this // app has a line to. A machine with no line now is not asked ("GET", "/api/far/held") => { let host = query_param(req.url(), "host").map(|c| percent_decode(&c)).unwrap_or_default(); // A terminal is kept by who its tab is; the list says its name let names = crate::config::tab_names_by_uid(); let machines: Vec = crate::farlink::up_for(&host) .iter() .filter_map(|at| { let mut listed = crate::farterm::list_held(&crate::farterm::Place::Far(at.clone()))?; for t in listed["terms"].as_array_mut().into_iter().flatten() { if let Some(name) = t["tab"].as_str().and_then(|u| names.get(u)) { t["name"] = serde_json::json!(name); } } Some(serde_json::json!({ "machine": at.machine_key(), "address": at.address(), "gen": listed["gen"], "terms": listed["terms"], })) }) .collect(); req.respond(json_resp(serde_json::json!({ "ok": true, "machines": machines })))?; } // Stop one of them, whoever owns it ("POST", "/api/far/end") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let machine = v["machine"].as_str().unwrap_or_default(); let host = crate::farlink::host_of(machine).unwrap_or_default(); let at = crate::farlink::up_for(&host).into_iter().find(|a| a.machine_key() == machine); let resp = match at { Some(at) if crate::farterm::end_held(&crate::farterm::Place::Far(at.clone()), v["term"].as_u64().unwrap_or(0), v["gen"].as_str().unwrap_or_default()) => { serde_json::json!({ "ok": true }) } Some(_) => serde_json::json!({ "ok": false, "error": crate::i18n::t("settings.away.list.not_there") }), None => serde_json::json!({ "ok": false, "error": crate::i18n::t("settings.away.list.no_line") }), }; req.respond(json_resp(resp))?; } // The calls a machine entry's tabs made while the app was away // (far-keep plan §4.6), as its bridges last said ("GET", "/api/far/missed") => { let host = query_param(req.url(), "host").map(|c| percent_decode(&c)).unwrap_or_default(); // A call is written down under its tab's key file, which is named // for who the tab is; the list says the tab's name let names: std::collections::HashMap = crate::config::tab_names_by_uid() .into_iter() .map(|(uid, name)| (crate::farlink::key_name(&uid), name)) .collect(); let machines: Vec = crate::farlink::missed() .into_iter() .filter(|(machine, _, _)| crate::farlink::host_of(machine).as_deref() == Some(host.as_str())) .map(|(machine, address, book)| { let mut book = serde_json::json!(book); for c in book["calls"].as_array_mut().into_iter().flatten() { if let Some(name) = c["tab"].as_str().and_then(|k| names.get(k)) { c["name"] = serde_json::json!(name); } } serde_json::json!({ "machine": machine, "address": address, "book": book }) }) .collect(); req.respond(json_resp(serde_json::json!({ "ok": true, "machines": machines })))?; } // Struck out, once looked at: some of them, or all ("POST", "/api/far/missed/seen") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let calls: Option> = v.get("calls").and_then(|c| serde_json::from_value(c.clone()).ok()); let resp = match crate::farlink::seen_missed(v["machine"].as_str().unwrap_or_default(), calls) { Ok(()) => serde_json::json!({ "ok": true }), Err(e) => serde_json::json!({ "ok": false, "error": e }), }; req.respond(json_resp(resp))?; } // Show a tab's conversation on the board, by the name its key has ("POST", "/api/far/convo") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); crate::farlink::want_convo(v["tab"].as_str().unwrap_or_default()); req.respond(json_resp(serde_json::json!({ "ok": true })))?; } // The server versions this PC is paired with (far-keep plan §6.1, // §6.2): added by a code used once, each one's key kept in the // secrets, opened in a window of its own, asked how it stands, and // asked for a code for a phone ("POST", "/api/boards/pair") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let name = v["name"].as_str().unwrap_or_default().trim().to_string(); let code = v["code"].as_str().unwrap_or_default(); let resp = match crate::pairing::board_url(v["url"].as_str().unwrap_or_default()) { None => serde_json::json!({ "ok": false, "error": crate::i18n::t("err.board.bad_url") }), Some(_) if name.is_empty() => serde_json::json!({ "ok": false, "error": crate::i18n::t("settings.boards.name_required") }), Some(url) => { let me = std::env::var("COMPUTERNAME").unwrap_or_else(|_| "PC".into()); let pw = password.lock().unwrap().clone(); match crate::pairing::pair_with(&url, code, &me).and_then(|key| { let meta = crate::config::SecretMeta { human: false, ai: false, urls: Vec::new(), desc: format!("SHIKISHA Server {url}") }; crate::config::upsert_secret(&secrets_file(config_path), pw.as_deref(), &crate::config::board_key(&name), &meta, &key) }) { Ok(()) => serde_json::json!({ "ok": true, "url": url }), Err(e) => serde_json::json!({ "ok": false, "error": format!("{e:#}") }), } } }; req.respond(json_resp(resp))?; } ("POST", "/api/boards/open") | ("POST", "/api/boards/invite") | ("POST", "/api/boards/forget") => { let what = path.rsplit('/').next().unwrap_or_default().to_string(); let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let name = v["name"].as_str().unwrap_or_default().trim().to_string(); let pw = password.lock().unwrap().clone(); let secrets = secrets_file(config_path); let board = crate::config::load().and_then(|c| c.boards.into_iter().find(|b| b.name == name)); let key = crate::config::secret_value(&secrets, pw.as_deref(), &crate::config::board_key(&name)); let resp = match (what.as_str(), board, key) { ("forget", _, _) => match crate::config::delete_secret(&secrets, pw.as_deref(), &crate::config::board_key(&name)) { Ok(()) => serde_json::json!({ "ok": true }), Err(e) => serde_json::json!({ "ok": false, "error": format!("{e:#}") }), }, (_, None, _) => serde_json::json!({ "ok": false, "error": crate::i18n::t("settings.boards.not_saved") }), (_, Some(_), None) => serde_json::json!({ "ok": false, "error": crate::i18n::t("err.board.no_key") }), ("open", Some(_), Some(key)) => match crate::pairing::open_board(&name, &|_| Some(key.clone())) { Ok(()) => serde_json::json!({ "ok": true }), Err(e) => serde_json::json!({ "ok": false, "error": e }), }, (_, Some(b), Some(key)) => match crate::pairing::invite(&b.url, &key) { Ok(code) => { let link = format!("{}/?pair={}", b.url, code.replace('-', "")); serde_json::json!({ "ok": true, "code": code, "link": link, "svg": crate::netaddr::qr_svg(&link, 6) }) } Err(e) => serde_json::json!({ "ok": false, "error": format!("{e:#}") }), }, }; req.respond(json_resp(resp))?; } // How each stands: asked of them all at once, each with a few seconds ("GET", "/api/boards/status") => { let pw = password.lock().unwrap().clone(); let secrets = secrets_file(config_path); let boards = crate::config::load().map(|c| c.boards).unwrap_or_default(); let asked: Vec<_> = boards .into_iter() .map(|b| { let key = crate::config::secret_value(&secrets, pw.as_deref(), &crate::config::board_key(&b.name)); std::thread::spawn(move || match key { None => serde_json::json!({ "name": b.name, "ok": false, "error": crate::i18n::t("err.board.no_key") }), Some(key) => match crate::pairing::status(&b.url, &key) { Ok(s) => serde_json::json!({ "name": b.name, "ok": true, "tabs": s["tabs"], "working": s["working"], "version": s["version"] }), Err(e) => serde_json::json!({ "name": b.name, "ok": false, "error": format!("{e:#}") }), }, }) }) .collect(); let rows: Vec = asked.into_iter().filter_map(|h| h.join().ok()).collect(); req.respond(json_resp(serde_json::json!({ "ok": true, "boards": rows })))?; } // Put one CLI's hook in, or take it out. Named by profile, so the page // never hands over a path to write to ("POST", "/api/resume/hook") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let name = v.get("name").and_then(|x| x.as_str()).unwrap_or_default(); let on = v.get("on").and_then(|x| x.as_bool()).unwrap_or(false); let found = crate::agenthook::targets().into_iter().find(|t| t.name == name); let resp = match found { None => serde_json::json!({ "ok": false, "error": "no such CLI" }), Some(t) => { // The same answer the question at start takes, so the // next start keeps it: set up and kept right, or taken // out and left out rather than put back if !crate::config::save_agent_hook(&t.name, on) { crate::append_hook_log(&format!("hooks: the answer about {} could not be written to the settings", t.name)); } // In the CLI's own folder and in every account's folder // of it (`crate::accounts`): one answer for the CLI, so // "off" leaves nothing of this app's running anywhere let all: Vec<_> = crate::agenthook::targets() .into_iter() .filter(|x| x.name == t.name && (x.account.is_none() || crate::agenthook::in_use(x))) .collect(); let done = all.iter().try_for_each(|x| match on { true => crate::agenthook::keep_right(x).map(|_| ()), false => crate::agenthook::uninstall(x), }); match done { Ok(()) => serde_json::json!({ "ok": true, "status": format!("{:?}", crate::agenthook::status(&t)) .split('(').next().unwrap_or("").to_string(), }), Err(e) => serde_json::json!({ "ok": false, "error": e.to_string() }), } } }; req.respond(json_resp(resp))?; } // Where the external API is listening, so the settings screen can show // the pipe by name — a person writing a script against it needs the // exact string, and it carries the process id, so it is not guessable // from the docs alone. No token is ever handed out here: in `user` mode // it sits in the state folder's api-token, and in `children` mode it exists only in // the environment of what this app started ("GET", "/api/external") => { let path = crate::api::listening_on(); let resp = serde_json::json!({ "running": path.is_some(), "path": path, "token_file": crate::config::state_path("api-token").display().to_string(), }); req.respond(json_resp(resp))?; } ("GET", "/api/remote") => { let (info, demo) = remote_for_display(remote); // A stand-in address stands in for the whole card: it is presented // as the safe case, so the picture is of the feature rather than of // a warning about a network nobody is on let (ts, lan) = if demo { (Some(crate::netaddr::url_host(&info.url)), None) } else { ( crate::netaddr::tailscale_ip().map(|i| i.to_string()), crate::netaddr::lan_ip().map(|i| i.to_string()), ) }; // The full URL embeds the access token (= full-machine control), so // it is never drawn on the page. The origin is all the page gets; // the token reaches the phone inside the QR image, or the clipboard // by way of /api/remote/url when the copy button is pressed let origin = info.url.split("/?").next().unwrap_or("").to_string(); let resp = serde_json::json!({ "running": info.running, "origin": origin, "note": info.note, "tailscale": ts, "lan": lan, // What the link leads to, said in one word so the page can put // a colour on it "kind": crate::netaddr::shown_link(&info.url).1, // Whether a browser will treat this link as a secure context, // which decides whether a phone will keep the page on its home // screen. Sent as the answer rather than left to be read off // the origin: the origin is only ever a "is there anything to // show" flag on that page, and it stays that way. "https": origin.starts_with("https://"), }); req.respond( Response::from_string(resp.to_string()).with_header( Header::from_bytes( &b"Content-Type"[..], &b"application/json; charset=utf-8"[..], ) .unwrap(), ), )?; } // The connection link as text, for the clipboard and nowhere else. // It carries the token — the whole machine — so the page asks for it at // the moment the copy button is pressed and hands it straight to the // clipboard, never to the screen. Behind the same token gate as the // rest of this server, so this hands out nothing the QR did not already // The devices allowed in. Never the keys -- the book holds hashes, and // a screen that could show a key would be a screen worth stealing ("GET", "/api/remote/clients") => { let rows: Vec<_> = crate::clients::load() .clients .into_iter() .map(|c| { serde_json::json!({ "id": c.id, "name": c.name, "added": c.added, "seen": c.seen, }) }) .collect(); req.respond(json_resp(serde_json::json!({ "clients": rows })))?; } // Naming a device. A list of six-character ids is a list nobody can act // on; "kitchen iPad" is what makes revoking a decision rather than a guess ("POST", "/api/remote/clients/name") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let id = p.get("id").and_then(|v| v.as_str()).unwrap_or_default(); let name = p.get("name").and_then(|v| v.as_str()).unwrap_or_default(); let out = match crate::clients::rename(id, name) { Ok(()) => serde_json::json!({ "ok": true }), Err(e) => serde_json::json!({ "ok": false, "error": format!("{e:#}") }), }; req.respond(json_resp(out))?; } // Taking one device's key away. Both halves: the key, so its next // request is refused, and whatever it is holding now, so the screen it // already has stops being drawn ("POST", "/api/remote/clients/revoke") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let p: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let id = p.get("id").and_then(|v| v.as_str()).unwrap_or_default().to_string(); let gone = crate::clients::revoke(&id).unwrap_or(false); if gone { let cut = remote.lock().unwrap().cut.clone(); if let Some(cut) = cut { cut(&id); } } req.respond(json_resp(serde_json::json!({ "ok": gone })))?; } ("GET", "/api/remote/url") => { let (info, _) = remote_for_display(remote); req.respond(json_resp(serde_json::json!({ "url": info.url })))?; } // Connection QR code (avoids having to hand-type the URL and token) ("GET", "/api/remote/qr") => { let url = remote_for_display(remote).0.url; let svg = if url.is_empty() { String::new() } else { crate::netaddr::qr_svg(&url, 6) }; req.respond(Response::from_string(svg).with_header( Header::from_bytes(&b"Content-Type"[..], &b"image/svg+xml; charset=utf-8"[..]) .unwrap(), ))?; } // Checks which AI CLIs are available (determined before rendering, so the feature is hidden entirely if none) ("GET", "/api/ai") => { let list: Vec = AI_ENGINES .iter() .filter(|(name, _, _)| crate::tab::resolve_command(name).is_some()) .map(|(name, _, label)| serde_json::json!({ "id": name, "label": label, "pictures": reads_pictures(name) })) .collect(); let resp = Response::from_string(serde_json::json!({ "engines": list }).to_string()) .with_header( Header::from_bytes( &b"Content-Type"[..], &b"application/json; charset=utf-8"[..], ) .unwrap(), ); req.respond(resp)?; } // Generates Lua from natural language (one-shot run of a local AI CLI) ("POST", "/api/generate") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; let parsed: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); let event = parsed.get("event").and_then(|v| v.as_str()).unwrap_or("on_done"); let want = parsed.get("prompt").and_then(|v| v.as_str()).unwrap_or(""); // If none is specified, use config's ai_engine let from_cfg = std::fs::read_to_string(config_path) .ok() .and_then(|t| serde_json::from_str::(&t).ok()) .and_then(|c| c.ai_engine) .filter(|s| !s.is_empty()); let engine = parsed .get("engine") .and_then(|v| v.as_str()) .filter(|s| !s.is_empty()) .map(str::to_string) .or(from_cfg); let layout = describe_tabs(&parsed); let resp = match generate_with_local_ai(event, want, &layout, engine.as_deref(), config_path) { Ok(code) => serde_json::json!({ "ok": true, "code": code }), Err(e) => serde_json::json!({ "ok": false, "error": e.to_string() }), }; req.respond( Response::from_string(resp.to_string()).with_header( Header::from_bytes( &b"Content-Type"[..], &b"application/json; charset=utf-8"[..], ) .unwrap(), ), )?; } // The update: where it stands, and the presses that move it. All of // them answer with the state as it is afterwards, so the page draws // what the program holds and never what it hoped ("GET", "/api/update") => req.respond(json_resp(crate::update::snapshot()))?, ("POST", "/api/update/check") => { crate::update::request_check(); req.respond(json_resp(crate::update::snapshot()))?; } ("POST", "/api/update/install") => match crate::update::request_install() { Ok(()) => req.respond(json_resp(crate::update::snapshot()))?, Err(e) => req.respond(json_resp(serde_json::json!({ "ok": false, "error": e.to_string() })).with_status_code(409))?, }, ("POST", "/api/update/skip") => { crate::update::skip(); req.respond(json_resp(crate::update::snapshot()))?; } ("POST", "/api/update/discard") => { crate::update::discard(); req.respond(json_resp(crate::update::snapshot()))?; } ("POST", "/api/update/rollback") => match crate::update::request_rollback() { Ok(()) => req.respond(json_resp(crate::update::snapshot()))?, Err(e) => req.respond(json_resp(serde_json::json!({ "ok": false, "error": e.to_string() })).with_status_code(409))?, }, // The settings page saving: the settings, the desk files it writes, // and the secrets of every desk and tab whose id it changed, as one // save (`save_settings`) ("POST", "/api/settings/save") => { let mut req = req; // Said the way every answer here is said, so the page can show it let Some(body) = read_body(&mut req, SAVE_MAX_BODY)? else { let too = crate::i18n::tp("webui.err.save_too_large", &[("mib", &(SAVE_MAX_BODY >> 20).to_string())]); req.respond(json_resp(serde_json::json!({ "ok": false, "error": too })))?; return Ok(()); }; let pw = password.lock().unwrap().clone(); let resp = match serde_json::from_str::(&body) .map_err(anyhow::Error::from) .and_then(|p| save_settings(config_path, &secrets_file(config_path), pw.as_deref(), &p)) { Ok(renamed) => serde_json::json!({ "ok": true, "renamed": renamed }), Err(e) => serde_json::json!({ "ok": false, "error": format!("{e:#}") }), }; req.respond(json_resp(resp))?; } ("POST", "/api/config") => { let mut req = req; let Some(body) = read_body(&mut req, MAX_BODY)? else { req.respond(Response::from_string("payload too large").with_status_code(413))?; return Ok(()); }; // Always validate before saving, so broken JSON never wipes out the config match serde_json::from_str::(&body) { Ok(mut doc) => { // A line this page never gave a uid -- typed into its // text editor, or read from a file that had none -- is // written with the one reading it gives, so renaming it // later does not make it another tab let as_sent = doc.clone(); // A sign-in tab the app put on a desk and has since taken // off is not this page's to bring back: a page opened // while it was there still holds it let on_disk: serde_json::Value = std::fs::read_to_string(config_path) .ok() .and_then(|t| serde_json::from_str(t.trim_start_matches('\u{feff}')).ok()) .unwrap_or_default(); let mark = crate::runtime::SIGN_IN_MARK; drop_marks_not_in(&mut doc, mark, &marks_in(&on_disk, mark)); crate::config::fill_tab_uids(&mut doc); let body = match doc == as_sent { true => body, false => serde_json::to_string_pretty(&doc).unwrap_or(body), }; crate::crypto::write_atomic(config_path, &body)?; req.respond(Response::from_string(r#"{"ok":true}"#))?; } Err(e) => { let msg = serde_json::json!({ "ok": false, "error": e.to_string() }); req.respond( Response::from_string(msg.to_string()).with_status_code(400), )?; } } } _ => { req.respond(Response::new( 404.into(), vec![], Cursor::new(b"not found".to_vec()), None, None, ))?; } } Ok(()) } /// An automation name and its stable owner, independent of the file holding it. #[derive(Clone)] struct SettingsId { key: String, id: String, desk: Option, } impl SettingsId { fn prefixes(&self, ids: &[Self]) -> Vec { match &self.desk { None => vec![format!("{}.", self.id), format!("ssh/{}/", self.id), format!("notify/{}/", self.id)], Some(desk) => ids.iter().find(|d| &d.key == desk) .map(|d| vec![format!("ssh/{}/{}/", d.id, self.id)]).unwrap_or_default(), } } fn related(&self, owner: &str, ids: &[Self]) -> bool { self.key == owner || self.desk.as_deref() == Some(owner) || ids.iter().any(|id| id.key == owner && id.desk.as_deref() == Some(self.key.as_str())) } } fn valid_settings_id(id: &str) -> bool { !id.is_empty() && id.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-')) } /// The identities in exactly the documents the page read or is saving. /// Resolve missing uids the same way as settings migration, then follow a /// desk's own file when its tabs live there. fn settings_ids(docs: &[(std::path::PathBuf, serde_json::Value)], config: &std::path::Path) -> Vec { fn add(out: &mut Vec, row: &serde_json::Value, desk: Option<&str>) -> Option { let uid = row.get("uid")?.as_str()?; let id = row.get("id")?.as_str()?.trim(); if id.is_empty() { return None; } let key = format!("{}:{uid}", if desk.is_some() { "tab" } else { "desk" }); out.push(SettingsId { key: key.clone(), id: id.into(), desk: desk.map(str::to_string) }); Some(key) } fn tabs(out: &mut Vec, list: &serde_json::Value, desk: &str) { for row in list.as_array().into_iter().flatten() { add(out, row, Some(desk)); tabs(out, &row["children"], desk); } } let docs: Vec<_> = docs.iter().map(|(path, doc)| { let mut doc = doc.clone(); crate::config::fill_tab_uids(&mut doc); (path, doc) }).collect(); let mut out = Vec::new(); let Some((_, root)) = docs.iter().find(|(path, _)| path.as_path() == config) else { return out }; for desk in root["desks"].as_array().into_iter().flatten() { let key = add(&mut out, desk, None).unwrap_or_else(|| format!("desk:{}", desk["uid"].as_str().unwrap_or_default())); let body = desk["file"].as_str().and_then(|f| safe_desk_file(f, config)) .and_then(|file| docs.iter().find(|(path, _)| **path == file).map(|(_, doc)| doc)).unwrap_or(desk); tabs(&mut out, &body["tabs"], &key); for folder in body["folders"].as_array().into_iter().flatten() { tabs(&mut out, &folder["tabs"], &key); } } if !root["desks"].is_array() { tabs(&mut out, &root["tabs"], "legacy"); for folder in root["folders"].as_array().into_iter().flatten() { tabs(&mut out, &folder["tabs"], "legacy"); } } out } fn settings_id_moves(before: &[SettingsId], after: &[SettingsId]) -> Vec<(String, String, String)> { let mut moves = Vec::new(); for now in after { let Some(was) = before.iter().find(|old| old.key == now.key && old.id != now.id) else { continue }; for (from, to) in was.prefixes(before).into_iter().zip(now.prefixes(after)) { moves.push((from, to, now.key.clone())); } } moves } /// Save the settings, desk files and renamed secrets together. A failed /// write, including the completion record, rolls every changed file back. /// Secret references follow the exact committed renames returned to the page. fn save_settings( config_path: &std::path::Path, secrets: &std::path::Path, password: Option<&str>, p: &serde_json::Value, ) -> anyhow::Result> { use anyhow::Context as _; // From reading the answers kept to the last file written: an answer // given on the board meanwhile is written after this save, not under it let _one_at_a_time = crate::config::writing_answers(); // Recover before planning secret moves or taking another set of copies. // An unfinished rollback must never become the next save's baseline. finish_settings_save(config_path)?; let mut docs: Vec<(std::path::PathBuf, serde_json::Value)> = Vec::new(); for f in p.get("files").and_then(|v| v.as_array()).into_iter().flatten() { let rel = f.get("file").and_then(|v| v.as_str()).unwrap_or_default(); let path = safe_desk_file(rel, config_path).ok_or_else(|| anyhow::anyhow!("not a desk file: {rel}"))?; docs.push((path, f.get("body").cloned().unwrap_or_else(|| serde_json::json!({})))); } let mut config = p.get("config").filter(|c| c.is_object()).cloned().context("no settings to save")?; let keep: Vec = p .get("keep") .and_then(|v| v.as_array()) .map(|a| a.iter().filter_map(|k| k.as_str().map(str::to_string)).collect()) .unwrap_or_default(); if !keep.is_empty() { let on_disk: serde_json::Value = std::fs::read_to_string(config_path) .ok() .and_then(|t| serde_json::from_str(t.trim_start_matches('\u{feff}')).ok()) .unwrap_or_default(); keep_answers(&mut config, &on_disk, &keep); } docs.push((config_path.to_path_buf(), config)); let before = docs.iter().map(|(path, _)| { let value = match std::fs::read_to_string(path) { Ok(text) => serde_json::from_str(&text)?, Err(e) if e.kind() == std::io::ErrorKind::NotFound => serde_json::json!({}), Err(e) => return Err(e.into()), }; Ok((path.clone(), value)) }).collect::>>()?; let old_ids = settings_ids(&before, config_path); let new_ids = settings_ids(&docs, config_path); for id in &new_ids { let unchanged = old_ids.iter().any(|old| old.key == id.key && old.id == id.id); if !unchanged && !valid_settings_id(&id.id) { anyhow::bail!(crate::i18n::tp("settings.id.invalid", &[("id", &id.id)])); } } let legacy = settings_id_moves(&old_ids, &new_ids); let mut moves = Vec::new(); for m in p.get("moves").and_then(|v| v.as_array()).into_iter().flatten() { let end = |i: usize| m.get(i).and_then(|v| v.as_str()).unwrap_or_default().to_string(); let (from, to) = (end(0), end(1)); if !crate::config::secrets_movable(&from, &to) && !legacy.iter().any(|(a, b, _)| a == &from && b == &to) { anyhow::bail!(crate::i18n::t("settings.id.move_unmatched")); } moves.push((from, to)); } let plan = match moves.is_empty() || !secrets.exists() { true => Vec::new(), false => crate::config::plan_secret_moves(secrets, password, &moves)?, }; // Old ids could contain namespace separators. A genuine rename still // cannot move keys when another desk or tab could own the same prefix. for (from, to) in &moves { if !plan.iter().any(|(key, _)| key.starts_with(from)) { continue; } if let Some((_, _, owner)) = legacy.iter().find(|(a, b, _)| a == from && b == to) { for (ids, prefix) in [(&old_ids, from), (&new_ids, to)] { for id in ids.iter().filter(|id| !id.related(owner, ids)) { if id.prefixes(ids).iter().any(|p| p.starts_with(prefix) || prefix.starts_with(p)) { anyhow::bail!(crate::i18n::t("settings.id.move_ambiguous")); } } } } } let renamed: std::collections::HashMap = plan.iter().map(|(old, new)| (format!("@{old}"), format!("@{new}"))).collect(); let mut texts = Vec::new(); for (path, mut doc) in docs { crate::config::fill_tab_uids(&mut doc); refile_secret_names(&mut doc, &renamed); let text = serde_json::to_string_pretty(&doc)?; // Each file kept to what it could be when it was sent on its own if text.len() > MAX_BODY { let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); anyhow::bail!(crate::i18n::tp("webui.err.save_file_too_large", &[("file", &name), ("mib", &(MAX_BODY >> 20).to_string())])); } texts.push((path, text)); } // Written under a record of the save (`SaveRecord`): a save cut short -- // a write that failed, or this program ending in the middle of one -- is // put back to what was there before, now or at the next start. One cut // short before is finished first, so its copies are not taken for this one's let mut files: Vec = Vec::new(); if !plan.is_empty() { files.push(secrets.to_path_buf()); } files.extend(texts.iter().map(|(path, _)| path.clone())); let record = SaveRecord::begin(config_path, &files)?; record.commit(|| -> anyhow::Result<()> { if !plan.is_empty() { crate::config::rename_secrets(secrets, password, &plan)?; } for (path, text) in &texts { if let Some(dir) = path.parent() { std::fs::create_dir_all(dir)?; } crate::crypto::write_atomic(path, text).with_context(|| format!("{} could not be written", path.display()))?; } Ok(()) })?; Ok(renamed) } /// What a settings save keeps while it writes, so that it ends with every /// file written or every file as it was, whatever happens in between: a copy /// of each file it is about to write, beside it (`.before-save` -- the /// secrets' copy stays where the secrets are, and as locked as they are), and /// this record, beside the settings file (`.saving`), of which files /// and how far the save got. A record still there at a start is a save cut /// short, finished by [`finish_settings_save`] #[derive(serde::Serialize, serde::Deserialize)] struct SaveRecord { #[serde(skip)] at: std::path::PathBuf, /// `copying`: the copies are being made, and nothing is written yet. /// `writing`: files are being written, and every copy is made. /// `settled`: nothing is left to put back, and the copies are being cleared stage: String, files: Vec, } #[derive(serde::Serialize, serde::Deserialize)] struct SavedFile { path: std::path::PathBuf, /// Whether it was there before the save: one that was not is taken away /// again, rather than put back existed: bool, } /// `path` with `tail` after its name fn beside(path: &std::path::Path, tail: &str) -> std::path::PathBuf { let mut name = path.as_os_str().to_owned(); name.push(tail); name.into() } impl SaveRecord { /// The record written and every copy made, before anything is written. /// Nothing is left behind when that fails fn begin(config_path: &std::path::Path, files: &[std::path::PathBuf]) -> anyhow::Result { let mut record = SaveRecord { at: beside(config_path, ".saving"), stage: "copying".into(), files: files.iter().map(|path| SavedFile { path: path.clone(), existed: path.exists() }).collect(), }; record.write()?; let copied = record .files .iter() .filter(|f| f.existed) .try_for_each(|f| crate::crypto::write_atomic(&beside(&f.path, ".before-save"), &std::fs::read_to_string(&f.path)?)); if let Err(e) = copied.and_then(|()| { record.stage = "writing".into(); record.write() }) { record.clear(); return Err(e); } Ok(record) } fn write(&self) -> anyhow::Result<()> { crate::crypto::write_atomic(&self.at, &serde_json::to_string_pretty(self)?) } /// Every file as it was before the save. When one cannot be, the record /// and the copies stay, and the next start tries again fn put_back(mut self) -> anyhow::Result<()> { for f in &self.files { let back = match f.existed { true => std::fs::read_to_string(beside(&f.path, ".before-save")) .map_err(anyhow::Error::from) .and_then(|was| crate::crypto::write_atomic(&f.path, &was)), false => match std::fs::remove_file(&f.path) { Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e.into()), _ => Ok(()), }, }; if let Err(e) = back { crate::append_hook_log(&format!("settings: {} could not be put back as it was before the save: {e:#}", f.path.display())); return Err(e); } } self.settle() } /// Success includes the durable completion record. Otherwise both the /// files and secret names are put back before an error reaches the page. fn commit(mut self, write: impl FnOnce() -> anyhow::Result<()>) -> anyhow::Result<()> { let written = write().and_then(|()| self.settle()); if let Err(error) = written { if let Err(back) = self.put_back() { crate::append_hook_log(&format!("settings: rollback is still pending: {back:#}")); return Err(error.context(crate::i18n::t("webui.err.save_recover"))); } return Err(error); } Ok(()) } /// Nothing left to put back: said so first, so that a copy cleared is /// never one a start would need, then cleared fn settle(&mut self) -> anyhow::Result<()> { self.stage = "settled".into(); self.write().map_err(|e| e.context(crate::i18n::t("webui.err.save_finish")))?; self.clear(); Ok(()) } /// The copies, then the record fn clear(&self) { for f in &self.files { let _ = std::fs::remove_file(beside(&f.path, ".before-save")); } let _ = std::fs::remove_file(&self.at); } } /// A settings save this program did not live to finish, finished: one cut /// short while writing is put back to what was there before it (the settings /// page said nothing of it saving), and one cut short before writing or after /// it has its copies cleared. Run at the start, before the settings are read pub fn finish_settings_save(config_path: &std::path::Path) -> anyhow::Result<()> { let at = beside(config_path, ".saving"); let text = match std::fs::read_to_string(&at) { Ok(text) => text, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), Err(e) => return Err(anyhow::Error::from(e).context(crate::i18n::t("webui.err.save_recover"))), }; let mut record = serde_json::from_str::(&text) .map_err(|e| anyhow::Error::from(e).context(crate::i18n::t("webui.err.save_recover")))?; record.at = at; if record.stage == "writing" { record.put_back().map_err(|e| e.context(crate::i18n::t("webui.err.save_recover")))?; crate::append_hook_log("settings: a save cut short was put back to what was there before it"); } else { record.clear(); } Ok(()) } /// Every text in `doc` that names a secret by `@key`, named by where that /// secret went fn refile_secret_names(doc: &mut serde_json::Value, renamed: &std::collections::HashMap) { if renamed.is_empty() { return; } match doc { serde_json::Value::String(s) => { if let Some(new) = renamed.get(s.as_str()) { *s = new.clone(); } } serde_json::Value::Array(a) => a.iter_mut().for_each(|v| refile_secret_names(v, renamed)), serde_json::Value::Object(o) => o.values_mut().for_each(|v| refile_secret_names(v, renamed)), _ => {} } } /// A port as the settings page holds it: a number, or the text typed into a /// box. Anything that is not a port is no port fn port_of(v: Option<&serde_json::Value>) -> Option { match v? { serde_json::Value::Number(n) => n.as_u64().and_then(|n| u16::try_from(n).ok()), serde_json::Value::String(s) => s.trim().parse().ok(), _ => None, } } /// A server connection's own settings as the page holds them before they are /// saved -- the shape a tab's `server` block is written in, but with whatever /// the boxes hold (a port as text, an empty key) rather than what is saved fn server_of_page(v: &serde_json::Value) -> crate::config::ServerSpec { let text = |o: &serde_json::Value, k: &str| { Some(o.get(k).and_then(|x| x.as_str()).unwrap_or_default().trim().to_string()) .filter(|t| !t.is_empty()) }; crate::config::ServerSpec { key: text(v, "key"), jump: v.get("jump").filter(|j| j.is_object()).map(|j| crate::config::JumpSpec { host: text(j, "host").unwrap_or_default(), port: port_of(j.get("port")), user: text(j, "user").unwrap_or_default(), key: text(j, "key"), }), keepalive: v.get("keepalive").and_then(|x| x.as_u64()), file_command: text(v, "file_command"), remote_dir: text(v, "remote_dir"), } } // The settings screen. Unlike the main app's cyber look, it's a quiet UI that prioritizes readability // (sidebar + detail pane. The list shows only "what exists"; editing stays focused on one item at a time) /// The colours and the toast, poured into a page. /// /// Runs **before** the words are: an unknown `{{key}}` is replaced with the key /// itself, so a template left to that step would end up with the word THEME /// sitting in its stylesheet and no colours at all. /// /// Every page this server serves gets the same blocks, because they are all the /// same app: the settings screen, the transcript view and the manual are not /// three products with three looks, and a message means the same thing and /// behaves the same way on each of them (src/toast.rs). pub(crate) fn page_parts(html: String) -> String { crate::quick::render(crate::push::inject(crate::toast::render(html))) .replace("{{I18N_JS}}", crate::i18n::FILL_JS) .replace("{{SETTINGS_API_JS}}", include_str!("settings-api.js")) .replace("{{REMOVAL_REVIEW_JS}}", include_str!("removal-review.js")) .replace("{{SECRET_URL_JS}}", include_str!("secret-url.js")) .replace("{{SECRET_URL_POLICY}}", &crate::config::secret_url_policy_json()) .replace("{{ADR_DEFAULT_DIR}}", &serde_json::to_string(crate::adr::DEFAULT_DIR).unwrap_or_else(|_| "\"\"".into())) } pub(crate) fn themed(html: String) -> String { let look = crate::config::load().map(|c| c.appearance).unwrap_or_default(); let scheme = look.scheme(); page_parts(html) .replace("{{THEME}}", &scheme.css_vars()) // The colours a project or a server is offered, from the list the app // colours an unchosen one from -- so a picked colour and a worked-out // one are always from the same eight .replace( "{{MARK_COLOURS}}", &serde_json::to_string(&crate::uistate::PALETTE).unwrap_or_else(|_| "[]".into()), ) .replace( "{{SCHEME}}", if crate::theme::is_light(&scheme) { "light" } else { "dark" }, ) // What tells a project served where it stands, when nobody has said: // the settings show these and edit a copy of them .replace( "{{HOST_MARKERS}}", &serde_json::to_string(&crate::config::HostMarkers::default()).unwrap_or_else(|_| "{}".into()), ) // What a machine that is not this one is given when its entry or its // checkout says nothing, written into the forms as it is -- one // spelling, the app's own // The AIs a MicroVM can be given, from the profiles that say how .replace( "{{MACHINE_AIS}}", &serde_json::to_string( &crate::profile::machine_ais() .into_iter() .map(|a| serde_json::json!({ "key": a.key, "name": a.name })) .collect::>(), ) .unwrap_or_else(|_| "[]".into()), ) .replace( "{{FAR_DEFAULTS}}", &serde_json::json!({ "placement": crate::worktree::REMOTE_PLACEMENT, "beside": crate::worktree::MICROVM_PLACEMENT, "minutes": crate::config::MICROVM_MINUTES, "template": crate::config::MICROVM_TEMPLATE, "keepalive": crate::config::SSH_KEEPALIVE, "ai_order": crate::runtime::QUICK_AI_ORDER, }) .to_string(), ) } /// The settings page as it is written, before a language is laid over it. /// /// Read by the guide, which works out from this script which screens the /// settings have and which words each one shows. A reader, never a writer: /// what is served goes through [`crate::i18n::render`] as it always has. pub fn page() -> &'static str { PAGE } /// The screen an older name for one of a desk's settings leads to. /// /// The board holds names this page has carried before (`caps` for the /// automation doors), so that a button written once goes on working. One /// answer, in the page's own table, read by whoever has to follow the same /// link. What git does is a project's, asked for as `project-` with the /// folder, and is not in this table. pub fn desk_link(name: &str) -> Option<&'static str> { let table = PAGE.split_once("const DESK_LINKS = {")?.1.split_once("};")?.0; table .split(',') .filter_map(|kv| kv.split_once(':')) .map(|(k, v)| (k.trim().trim_matches('"'), v.trim().trim_matches('"'))) .find(|(k, _)| *k == name) .map(|(_, v)| v) } const PAGE: &str = r##" {{settings.title}}

{{settings.title}}

{{TOAST_HTML}} "##; /// The result view: a finished run's transcript.md rendered as a chat /// (WhatsApp-style bubbles for a discussion / code review; the same block /// renderer doubles for a browser rally's request→action→screen log). Verdicts /// and moderator notes become centered system cards. Tall bubbles (long prose /// or a pasted git diff) clamp with a "show all" toggle; the download button /// always hands over the full, untruncated Markdown. const RESULT_PAGE: &str = r##" {{result.title}}

{{result.title}}

{{TOAST_HTML}} "##; /// The manual display page (a simple renderer that only handles the Markdown subset needed here) const HELP_PAGE: &str = r##" {{help.page.title}}
"##; /// The desktop that can open a file dialog, if one is running. /// /// Set once by whatever owns that desktop. The settings server never builds /// one: a build with no desktop simply has no picker, and the page that asked /// is answered "no" instead of waiting on a dialog nobody can see. static PICKER: std::sync::OnceLock> = std::sync::OnceLock::new(); pub fn use_file_picker(p: Box) { let _ = PICKER.set(p); } fn picker() -> Option<&'static dyn shikisha_shared::FilePicker> { PICKER.get().map(|p| p.as_ref()) } #[cfg(test)] mod tests { /// A page opened while a sign-in tab was on the desk, saved after the app /// took it off, does not bring it back; one still there is kept, and so /// is everything else on the page #[test] fn a_saved_page_does_not_bring_back_a_sign_in_tab_taken_off() { let disk = serde_json::json!({"desks": [{"folders": [{"tabs": [ {"name": "codex"}, {"name": "claude sign-in", "sign_in_for": "4"}]}]}]}); let mut page = serde_json::json!({"desks": [{"folders": [{"tabs": [ {"name": "codex"}, {"name": "codex sign-in", "sign_in_for": "3"}, {"name": "claude sign-in", "sign_in_for": "4"}, {"name": "mine", "children": [{"name": "old", "sign_in_for": "2"}]}]}]}]}); super::drop_marks_not_in(&mut page, "sign_in_for", &super::marks_in(&disk, "sign_in_for")); let names: Vec = page["desks"][0]["folders"][0]["tabs"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap().to_string()).collect(); assert_eq!(names, ["codex", "claude sign-in", "mine"]); assert!(page["desks"][0]["folders"][0]["tabs"][2]["children"].as_array().unwrap().is_empty()); } #[test] fn standalone_settings_keep_pinned_and_shared_folders() { let root = std::env::temp_dir().join(format!("shikisha-removal-guard-{}", crate::random_hex(12))); std::fs::create_dir(&root).unwrap(); let at = root.join("work"); // Missing on disk: test the config guards themselves. let file = root.join("config.json"); let write = |value: serde_json::Value| std::fs::write(&file, value.to_string()).unwrap(); write(serde_json::json!({"desks":[{"id":"one", "name":"One", "folders":[{"cwd":at, "keep_first":true}]}]})); assert!(settings_removal_guard(&file, &at).is_err()); write(serde_json::json!({"desks":[{"id":"one", "name":"One", "folders":[{"cwd":at}]}, {"id":"two", "name":"Two", "folders":[{"cwd":at}]}]})); assert!(settings_removal_guard(&file, &at).is_err()); write(serde_json::json!({"desks":[{"id":"one", "name":"One", "folders":[{"cwd":at}]}]})); settings_removal_guard(&file, &at).unwrap(); assert!(settings_removal_guard(&file, &root.join("unknown")).is_err()); std::fs::remove_file(file).unwrap(); std::fs::remove_dir(root).unwrap(); } /// A folder with a settings file and a secret store, for a save to be /// tried against fn save_place(what: &str) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) { let dir = crate::test_temp(what); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let (config, secrets) = (dir.join("config.json"), dir.join("secrets.json")); std::fs::write(&config, r#"{"desks": [{"name": "A", "id": "a"}, {"name": "B", "id": "b"}]}"#).unwrap(); let meta = crate::config::SecretMeta::default(); for (key, value) in [("a.github", "token of a"), ("b.github", "token of b"), ("ssh/a/prod/password", "pw of a's tab")] { crate::config::upsert_secret(&secrets, None, key, &meta, value).unwrap(); } (dir, config, secrets) } #[test] fn settings_names_use_one_rule_and_legacy_names_can_be_repaired() { for with_secrets in [false, true] { for own_file in [false, true] { let (dir, config, secrets) = save_place("save-old-id"); let desk_uid = "11111111-2222-4333-8444-555555555555"; let tab_uid = "22222222-3333-4444-8555-666666666666"; let mut holder = serde_json::json!({"tabs":[{"id":"prod.dev","uid":tab_uid,"command":"sh","env":{"TOKEN":"@work.dev.github"}}]}); let mut doc = serde_json::json!({"desks":[{"name":"Work","id":"work.dev","uid":desk_uid}]}); if own_file { doc["desks"][0]["file"] = "desk.json".into(); std::fs::write(dir.join("desk.json"), holder.to_string()).unwrap(); } else { doc["desks"][0]["tabs"] = holder["tabs"].clone(); } std::fs::write(&config, doc.to_string()).unwrap(); if with_secrets { let meta = crate::config::SecretMeta::default(); crate::config::upsert_secret(&secrets, None, "work.dev.github", &meta, "kept").unwrap(); crate::config::upsert_secret(&secrets, None, "ssh/work.dev/prod.dev/password", &meta, "password").unwrap(); } else { std::fs::remove_file(&secrets).unwrap(); } let files = |body: &serde_json::Value| if own_file { serde_json::json!([{"file":"desk.json","body":body}]) } else { serde_json::json!([]) }; // Unchanged legacy ids remain savable; newly introduced ones do not. super::save_settings(&config, &secrets, None, &serde_json::json!({"config":doc,"files":files(&holder)})).unwrap(); let mut bad = doc.clone(); bad["desks"][0]["id"] = "new.invalid".into(); assert!(super::save_settings(&config, &secrets, None, &serde_json::json!({"config":bad,"files":files(&holder)})).is_err()); doc["desks"][0]["id"] = "work".into(); holder["tabs"][0]["id"] = "prod".into(); if !own_file { doc["desks"][0]["tabs"] = holder["tabs"].clone(); } let got = super::save_settings(&config, &secrets, None, &serde_json::json!({"config":doc,"files":files(&holder),"moves":[ ["work.dev.","work."],["ssh/work.dev/","ssh/work/"],["notify/work.dev/","notify/work/"], ["ssh/work.dev/prod.dev/","ssh/work/prod/"] ]})).unwrap(); if with_secrets { assert_eq!(got.get("@work.dev.github").map(String::as_str), Some("@work.github")); assert_eq!(crate::config::secret_value(&secrets, None, "work.github").as_deref(), Some("kept")); assert_eq!(crate::config::secret_value(&secrets, None, "ssh/work/prod/password").as_deref(), Some("password")); } else { assert!(got.is_empty()); } let _ = std::fs::remove_dir_all(dir); } } } #[test] fn new_desk_and_tab_names_follow_the_same_rule_even_without_uids() { let (dir, config, secrets) = save_place("save-new-id"); let was = std::fs::read_to_string(&config).unwrap(); for id in ["work.dev", "work/dev", "work dev", "仕事"] { for in_tab in [false, true] { let mut doc = serde_json::json!({"desks":[{"name":"New","id":"new","tabs":[{"id":"shell","command":"sh"}]}]}); if in_tab { doc["desks"][0]["tabs"][0]["id"] = id.into(); } else { doc["desks"][0]["id"] = id.into(); } let err = super::save_settings(&config, &secrets, None, &serde_json::json!({"config":doc})).unwrap_err(); assert_eq!(err.to_string(), crate::i18n::tp("settings.id.invalid", &[("id", id)])); assert_eq!(std::fs::read_to_string(&config).unwrap(), was); } } let _ = std::fs::remove_dir_all(dir); } /// An answer given on the board while the settings were open is not put /// back by a save that did not touch it; one the page changed is the page's #[test] fn a_save_keeps_answers_given_elsewhere_while_it_was_open() { let (dir, config, secrets) = save_place("save-keeps-answers"); std::fs::write(&config, r#"{"language":"en","worktree_trust":{"Gemini CLI":"off"},"agent_hooks":{"Codex CLI":"on"}}"#).unwrap(); // The page loaded before the answers changed to these let page = serde_json::json!({"language":"ja","worktree_trust":{"Gemini CLI":"on"}}); super::save_settings(&config, &secrets, None, &serde_json::json!({"config":page,"keep":["worktree_trust","agent_hooks","language"]})).unwrap(); let saved: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap(); assert_eq!(saved["language"], "ja", "only answers given elsewhere are kept from the file"); assert_eq!(saved["worktree_trust"]["Gemini CLI"], "off"); assert_eq!(saved["agent_hooks"]["Codex CLI"], "on", "kept though the page had none"); // Changed on the page (its text editor): the page's super::save_settings(&config, &secrets, None, &serde_json::json!({"config":page})).unwrap(); let saved: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap(); assert_eq!(saved["worktree_trust"]["Gemini CLI"], "on"); let _ = std::fs::remove_dir_all(dir); } #[test] fn ambiguous_legacy_secret_names_are_never_moved_by_guessing() { let (dir, config, secrets) = save_place("save-ambiguous-id"); let mut doc = serde_json::json!({"desks":[ {"name":"Work","id":"work","uid":"11111111-2222-4333-8444-555555555555"}, {"name":"Dev","id":"work.dev","uid":"22222222-3333-4444-8555-666666666666"} ]}); std::fs::write(&config, doc.to_string()).unwrap(); crate::config::upsert_secret(&secrets, None, "work.dev.token", &Default::default(), "not-guessed").unwrap(); let was = std::fs::read_to_string(&config).unwrap(); doc["desks"][1]["id"] = "dev".into(); let saved = super::save_settings(&config, &secrets, None, &serde_json::json!({"config":doc,"moves":[["work.dev.","dev."]]})); assert!(saved.is_err()); assert_eq!(std::fs::read_to_string(&config).unwrap(), was); assert_eq!(crate::config::secret_value(&secrets, None, "work.dev.token").as_deref(), Some("not-guessed")); assert!(crate::config::secret_value(&secrets, None, "dev.token").is_none()); let _ = std::fs::remove_dir_all(dir); } #[test] fn ids_swapped_between_two_desks_swap_their_secrets_and_what_names_them() { let (dir, config, secrets) = save_place("save-swap"); let saved = super::save_settings(&config, &secrets, None, &serde_json::json!({ "config": {"desks": [ {"name": "A", "id": "b", "notify": {"slack": {"webhook": "@a.github"}}}, {"name": "B", "id": "a"}]}, "moves": [["a.", "b."], ["ssh/a/", "ssh/b/"], ["b.", "a."], ["ssh/b/", "ssh/a/"]], })); assert!(saved.is_ok(), "{saved:?}"); let renamed = saved.unwrap(); assert_eq!(renamed.get("@a.github").map(String::as_str), Some("@b.github")); assert_eq!(renamed.get("@b.github").map(String::as_str), Some("@a.github")); let value = |k| crate::config::secret_value(&secrets, None, k); assert_eq!(value("b.github").as_deref(), Some("token of a"), "desk A's secret went under its new id"); assert_eq!(value("a.github").as_deref(), Some("token of b"), "desk B's secret was written over"); assert_eq!(value("ssh/b/prod/password").as_deref(), Some("pw of a's tab")); let doc: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap(); assert_eq!(doc["desks"][0]["notify"]["slack"]["webhook"], "@b.github", "what named the secret still names it"); let again = super::save_settings(&config, &secrets, None, &serde_json::json!({"config":doc,"moves":[]})).unwrap(); assert!(again.is_empty()); let twice: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap(); assert_eq!(twice["desks"][0]["notify"]["slack"]["webhook"], "@b.github"); let _ = std::fs::remove_dir_all(&dir); } #[test] fn a_tab_moves_by_its_own_place_inside_a_desk_that_moved_too() { let (dir, config, secrets) = save_place("save-tab"); let moves = [("a.", "c."), ("ssh/a/", "ssh/c/"), ("ssh/a/prod/", "ssh/c/live/")].map(|(f, t)| (f.to_string(), t.to_string())); let plan = crate::config::plan_secret_moves(&secrets, None, &moves).unwrap(); assert!(plan.contains(&("ssh/a/prod/password".into(), "ssh/c/live/password".into())), "{plan:?}"); assert!(plan.contains(&("a.github".into(), "c.github".into())), "{plan:?}"); let _ = (config, std::fs::remove_dir_all(&dir)); } #[test] fn a_secret_that_would_land_on_another_is_refused_and_nothing_is_saved() { let (dir, config, secrets) = save_place("save-taken"); let config_was = std::fs::read_to_string(&config).unwrap(); let secrets_was = std::fs::read_to_string(&secrets).unwrap(); // Desk A takes B's id while B keeps it: A's secret would land on B's let saved = super::save_settings(&config, &secrets, None, &serde_json::json!({ "config": {"desks": [{"name": "A", "id": "b"}, {"name": "B", "id": "b"}]}, "moves": [["a.", "b."]], })); let e = format!("{:#}", saved.unwrap_err()); assert!(e.contains("b.github"), "the key in the way is named: {e}"); assert_eq!(std::fs::read_to_string(&config).unwrap(), config_was); assert_eq!(std::fs::read_to_string(&secrets).unwrap(), secrets_was); let _ = std::fs::remove_dir_all(&dir); } #[test] #[cfg(windows)] fn a_locked_completion_record_never_acknowledges_a_save() { use std::os::windows::fs::OpenOptionsExt as _; let (dir, config, secrets) = save_place("save-commit-lock"); let was = std::fs::read_to_string(&config).unwrap(); let secrets_was = std::fs::read_to_string(&secrets).unwrap(); let record = super::SaveRecord::begin(&config, &[config.clone(), secrets.clone()]).unwrap(); let held = std::fs::OpenOptions::new().read(true).share_mode(1).open(&record.at).unwrap(); let answer = record.commit(|| { crate::crypto::write_atomic(&config, r#"{"language":"ja"}"#)?; crate::config::rename_secrets(&secrets, None, &[("a.github".into(), "c.github".into())]) }); assert!(answer.is_err(), "a save that recovery would undo was acknowledged"); assert_eq!(std::fs::read_to_string(&config).unwrap(), was); assert_eq!(std::fs::read_to_string(&secrets).unwrap(), secrets_was); let journal = super::beside(&config, ".saving"); let written = std::fs::read_to_string(&journal).unwrap(); assert!(super::save_settings(&config, &secrets, None, &serde_json::json!({"config":{"language":"en"}})).is_err()); assert_eq!(std::fs::read_to_string(&journal).unwrap(), written, "a new save overwrote pending recovery"); drop(held); super::finish_settings_save(&config).unwrap(); assert_eq!(std::fs::read_to_string(&config).unwrap(), was); assert!(!journal.exists()); super::save_settings(&config, &secrets, None, &serde_json::json!({"config":{"language":"ja"}})).unwrap(); super::finish_settings_save(&config).unwrap(); assert!(std::fs::read_to_string(&config).unwrap().contains("ja")); let _ = std::fs::remove_dir_all(dir); } #[test] fn unreadable_recovery_records_are_preserved_and_block_new_saves() { let (dir, config, secrets) = save_place("save-unreadable"); let was = std::fs::read_to_string(&config).unwrap(); let journal = super::beside(&config, ".saving"); std::fs::write(&journal, "{cut").unwrap(); assert!(super::finish_settings_save(&config).is_err()); assert!(super::save_settings(&config, &secrets, None, &serde_json::json!({"config":{}})).is_err()); assert_eq!(std::fs::read_to_string(&journal).unwrap(), "{cut"); assert_eq!(std::fs::read_to_string(&config).unwrap(), was); let _ = std::fs::remove_dir_all(dir); } #[test] fn a_save_cut_short_while_writing_is_put_back_at_the_next_start() { let (dir, config, secrets) = save_place("save-cut"); let (config_was, secrets_was) = (std::fs::read_to_string(&config).unwrap(), std::fs::read_to_string(&secrets).unwrap()); let made = dir.join("desks").join("new.json"); // The program ends after the secrets and one new desk file were // written, and before the settings were: the record is all that is left let record = super::SaveRecord::begin(&config, &[secrets.clone(), made.clone(), config.clone()]).unwrap(); crate::config::rename_secrets(&secrets, None, &[("a.github".into(), "c.github".into())]).unwrap(); std::fs::create_dir_all(made.parent().unwrap()).unwrap(); std::fs::write(&made, "{}").unwrap(); std::mem::forget(record); super::finish_settings_save(&config).unwrap(); assert_eq!(std::fs::read_to_string(&secrets).unwrap(), secrets_was, "the secrets were left moved"); assert_eq!(std::fs::read_to_string(&config).unwrap(), config_was); assert!(!made.exists(), "a file the save made was left behind"); let left: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()) .filter(|n| n.ends_with(".before-save") || n.ends_with(".saving")).collect(); assert!(left.is_empty(), "copies or the record were left: {left:?}"); let _ = std::fs::remove_dir_all(&dir); } #[test] fn a_save_cut_short_before_writing_leaves_every_file_as_it_is() { let (dir, config, secrets) = save_place("save-copying"); let record = super::SaveRecord::begin(&config, &[secrets.clone(), config.clone()]).unwrap(); // As though the program ended while the copies were being made let mut copying = serde_json::to_value(&record).unwrap(); copying["stage"] = "copying".into(); std::fs::write(super::beside(&config, ".saving"), copying.to_string()).unwrap(); std::mem::forget(record); // What was written since is not taken back: nothing of the save was std::fs::write(&config, r#"{"desks": []}"#).unwrap(); super::finish_settings_save(&config).unwrap(); assert_eq!(std::fs::read_to_string(&config).unwrap(), r#"{"desks": []}"#); assert!(!super::beside(&secrets, ".before-save").exists() && !super::beside(&config, ".saving").exists()); let _ = std::fs::remove_dir_all(&dir); } #[test] fn a_desk_file_too_large_to_have_been_sent_alone_is_refused_before_anything_is_written() { let (dir, config, secrets) = save_place("save-large"); let (config_was, secrets_was) = (std::fs::read_to_string(&config).unwrap(), std::fs::read_to_string(&secrets).unwrap()); let big = "x".repeat(super::MAX_BODY); let saved = super::save_settings(&config, &secrets, None, &serde_json::json!({ "config": {"desks": [{"name": "A", "id": "c"}]}, "files": [{"file": "desks/big.json", "body": {"note": big}}], "moves": [["a.", "c."]], })); assert!(format!("{:#}", saved.unwrap_err()).contains("big.json")); assert_eq!(std::fs::read_to_string(&config).unwrap(), config_was); assert_eq!(std::fs::read_to_string(&secrets).unwrap(), secrets_was); assert!(!dir.join("desks").join("big.json").exists()); let _ = std::fs::remove_dir_all(&dir); } #[test] fn a_write_that_fails_puts_back_every_one_made_before_it() { let (dir, _, secrets) = save_place("save-undo"); let secrets_was = std::fs::read_to_string(&secrets).unwrap(); // The secrets and a desk file written (and one desk file new), then // the settings file cannot be: a folder stands where it goes let blocked = dir.join("blocked"); std::fs::create_dir_all(blocked.join("config.json")).unwrap(); std::fs::create_dir_all(blocked.join("desks")).unwrap(); let desk = blocked.join("desks").join("a.json"); std::fs::write(&desk, r#"{"tabs": []}"#).unwrap(); let saved = super::save_settings(&blocked.join("config.json"), &secrets, None, &serde_json::json!({ "config": {"desks": [{"name": "A", "id": "c"}]}, "files": [ {"file": "desks/a.json", "body": {"tabs": [{"name": "t", "id": "t"}]}}, {"file": "desks/new.json", "body": {"tabs": []}}], "moves": [["a.", "c."]], })); assert!(saved.is_err(), "the settings could not be written"); assert_eq!(std::fs::read_to_string(&secrets).unwrap(), secrets_was, "the secrets moved and stayed moved"); assert_eq!(crate::config::secret_value(&secrets, None, "a.github").as_deref(), Some("token of a")); assert_eq!(std::fs::read_to_string(&desk).unwrap(), r#"{"tabs": []}"#, "the desk file stayed rewritten"); assert!(!blocked.join("desks").join("new.json").exists(), "a desk file the save made was left behind"); let _ = std::fs::remove_dir_all(&dir); } /// A folder on another machine is a branch's folder when it is not the /// project's checkout there -- on a MicroVM every folder is a checkout of /// its own, so git cannot say it #[test] fn a_far_folder_is_a_worktree_when_it_is_not_the_checkout() { let at = std::path::Path::new("/home/user/site-fix"); assert!(super::far_cut(at, Some("/home/user/site"))); assert!(!super::far_cut(std::path::Path::new("/home/user/site/"), Some("/home/user/site")), "the checkout is called a worktree"); assert!(!super::far_cut(at, None), "a folder of no known project is called a worktree"); } /// The light way of asking stays light when the small model is turned /// off: only the model goes. /// /// The setting is about one thing -- whether a name is written by the /// cheapest model the CLI has -- and everything else that makes this cheap /// (no tools, nothing kept, no thinking) has no second side to argue for. /// A checkbox that quietly turned the rest back on would cost the person /// nine thousand tokens for a folder's name /// A model the person named is the model each program is started with, /// and it outranks the small one; a name cmd.exe would read as its own /// never reaches a command line #[test] fn a_named_model_reaches_each_installed_ai() { for name in ["claude", "codex", "gemini"] { let (args, _) = super::light_invocation(name, true, Some("m-1"), None).expect("a light way"); let at = args.iter().position(|a| a == "--model").unwrap_or_else(|| panic!("{name}: {args:?}")); assert_eq!(args[at + 1], "m-1", "{name}: {args:?}"); assert_eq!(args.iter().filter(|a| *a == "--model").count(), 1, "{name}: {args:?}"); } for fine in ["haiku", "gpt-5-codex", "gemini-2.5-flash", "sonnet[1m]", "qwen3:8b"] { assert!(super::model_name_fault(fine).is_none(), "{fine}"); } for bad in ["a&calc", "x|y", "%PATH%", "a b", "\"q\"", ""] { assert!(super::model_name_fault(bad).is_some(), "{bad}"); } assert!(!super::holds_shape("gemini"), "gemini is told the shape in words"); assert!(super::holds_shape("claude") && super::holds_shape("codex")); } #[test] fn turning_the_small_model_off_turns_off_only_the_model() { let args = |name: &str, small: bool| { super::light_invocation(name, small, None, None).expect("this CLI has a light way").0.join(" ") }; assert!(args("claude", true).contains("--model haiku")); assert!(!args("claude", false).contains("--model"), "{}", args("claude", false)); assert!(args("codex", true).contains("model_reasoning_effort=low")); assert!(!args("codex", false).contains("model_reasoning_effort"), "{}", args("codex", false)); for small in [true, false] { let claude = args("claude", small); assert!(claude.contains("--tools --no-session-persistence"), "{claude}"); assert!(claude.contains("--disable-slash-commands"), "{claude}"); let codex = args("codex", small); assert!(codex.contains("--ephemeral") && codex.contains("--sandbox read-only"), "{codex}"); assert!(codex.contains("web_search=disabled"), "{codex}"); // Gemini routes a request this size itself; there is nothing to say assert!(!args("gemini", small).contains("--model")); } } /// What the two new answers about automatic names are asked on screen, and /// written down afterwards. /// /// A setting the page shows but never saves is worse than no setting: it /// answers the question in front of the person and forgets it on the next /// press. `summary_ai` was exactly that until this test existed -- the /// desk's card wrote it into the page's own copy, and the save built its /// desks field by field and never asked for it #[test] fn the_naming_settings_are_shown_and_kept() { for held in [ // Asked app-wide, under the assistant AI it defaults to r#"...namesAiRows(current, {"#, r#"checkDefaultOn(current, "summary_small_model", T["settings.summary_small.label"])"#, // Asked of a desk, in the card about its automatic names r#"checkDefaultOn(desk, "rename_branch", T["settings.labels.branch.label"])"#, // And kept: read into the page, and written back out r#"summary_ai: (w.summary_ai || "").trim(),"#, r#"rename_branch: w.rename_branch !== false,"#, r#"if ((w.summary_ai || "").trim()) o.summary_ai = w.summary_ai.trim();"#, r#"if (w.rename_branch === false) o.rename_branch = false;"#, // The project's prefix: shown, and kept when it says something r#"e.branch_prefix = prefixIn.value.trim(); else delete e.branch_prefix;"#, r#"for (const k of ["at", "setup", "branch_prefix"])"#, ] { assert!(super::PAGE.contains(held), "the settings page no longer has: {held}"); } } /// Every name a page calls is a name that page has. /// /// The script is a string as far as the compiler is concerned, so a /// function deleted along with the feature that used it takes no callers /// with it. The card that calls one draws nothing at all -- the browser /// stops mid-draw, the pane stays empty, and nobody is told. That is what /// `modelCandidates` did to "Automatic names" and to an AI tab set to a /// model connection, from 2026-09-18 until a person pressed it and asked. /// /// The pages are checked as they are served, shared blocks and all: the /// helpers another module splices in are the page's too. #[test] fn every_page_has_what_it_calls() { let served = |page: &str| { crate::shell::with_faces(super::page_parts(page.to_string())) }; for (which, page) in [ ("the settings page", super::PAGE), ("the result view", super::RESULT_PAGE), ("the manual", super::HELP_PAGE), // The board and the guide's panel are pages of this app too, and // a name that is not there breaks them the same silent way ("the board", crate::shell::PAGE), ("the guide's panel", crate::guide::page()), ] { let code = crate::pagelint::code_only(&crate::pagelint::scripts_of(&served(page))); let missing = crate::pagelint::dangling_calls(&code); assert!(missing.is_empty(), "{which} calls what it does not have: {missing:?}"); } } /// A server's settings are read the way the page holds them, before they /// are saved: a port as the text in its box. A bastion on port 2222 was /// tested on 22 while the text went unread #[test] fn a_server_is_read_as_the_page_holds_it() { let v = serde_json::json!({ "key": " ", "keepalive": 30, "file_command": "", "jump": {"host": " gw.example.com ", "port": "2222", "user": "me", "key": ""}, }); let sv = super::server_of_page(&v); let jump = sv.jump.as_ref().expect("the bastion was dropped"); assert_eq!((jump.host.as_str(), jump.port, jump.key.as_deref()), ("gw.example.com", Some(2222), None)); assert_eq!((sv.key.as_deref(), sv.keepalive, sv.file_command.as_deref()), (None, Some(30), None)); let spec = crate::view::server_spec("10.0.0.5", 22, "deploy", Some(&sv), &|_| None); assert_eq!(spec.machine(), "gw.example.com:2222>10.0.0.5:22"); assert_eq!(super::port_of(Some(&serde_json::json!(22))), Some(22)); assert_eq!(super::port_of(Some(&serde_json::json!("70000"))), None); assert_eq!(super::port_of(Some(&serde_json::json!(null))), None); } /// An AI handed a picture is handed nothing else it could reach with. /// The picture is a screen, and a screen can say "read this file and /// write it out" #[test] fn an_ai_reading_a_picture_reaches_nothing_but_the_picture() { let png = b"\x89PNG\r\n\x1a\n"; let schema = r#"{"type":"object"}"#; let (args, input, on_disk) = super::picture_invocation("claude", "read", png, schema).unwrap(); let tools = args.iter().position(|a| a == "--tools").expect("claude is given no tools option"); assert_eq!(args[tools + 1], "", "claude is given tools"); assert!(args.windows(2).any(|w| w == ["--json-schema", schema]), "claude is not given the shape of the answer"); assert!(!on_disk, "claude should not be given the picture as a file"); let msg: serde_json::Value = serde_json::from_str(input.trim()).unwrap(); assert_eq!(msg["message"]["content"][0]["type"], "image"); assert_eq!(msg["message"]["content"][1]["text"], "read"); let (args, input, on_disk) = super::picture_invocation("codex", "read", png, schema).unwrap(); assert!(args.windows(2).any(|w| w == ["--sandbox", "read-only"]), "codex is not read-only"); assert!(args.windows(2).any(|w| w == ["--output-schema", super::SCHEMA_FILE]), "codex is not given the shape of the answer"); assert!(on_disk && input == "read"); let (args, _, on_disk) = super::picture_invocation("gemini", "read", png, schema).unwrap(); assert!(args.windows(2).any(|w| w == ["--approval-mode", "plan"]), "gemini is not read-only"); assert!(on_disk); assert!(super::picture_invocation("aider", "read", png, schema).is_none()); for (name, _, _) in super::AI_ENGINES { assert!(super::reads_pictures(name), "{name} has no decided way to be given a picture"); } } /// Each installed assistant AI, started the way the tools start it, reads /// the text of a real picture. Costs a call to each; run by hand with /// `SHIKISHA_PICTURE= cargo test -- --ignored every_installed_ai` #[test] #[ignore] fn every_installed_ai_reads_a_picture() { let Ok(path) = std::env::var("SHIKISHA_PICTURE") else { return }; let png = std::fs::read(path).unwrap(); for (name, _, _) in super::AI_ENGINES { if crate::tab::resolve_command(name).is_none() { continue; } let t0 = std::time::Instant::now(); let said = super::ask_about_picture( name, &crate::snip::prompt_for("text"), &png, &crate::snip::shape_of("text").unwrap().to_string(), ); eprintln!("{name} {:.1}s -> {said:?}", t0.elapsed().as_secs_f32()); let said = said.unwrap_or_else(|e| panic!("{name} could not read it: {e:#}")); assert!(said.contains("\"text\""), "{name} did not answer in the required shape"); } } /// Each installed assistant AI answers a short question the light way, /// without falling back to the ordinary one. Costs a call to each; run by /// hand with `cargo test -- --ignored every_installed_ai_answers_lightly` #[test] #[ignore] fn every_installed_ai_answers_lightly() { for (name, _, _) in super::AI_ENGINES { if crate::tab::resolve_command(name).is_none() { continue; } let t0 = std::time::Instant::now(); let said = super::ask_light_once(name, "Reply with the single word PONG in capital letters."); eprintln!("{name} {:.1}s -> {said:?}", t0.elapsed().as_secs_f32()); let said = said.unwrap_or_else(|e| panic!("{name} could not be asked lightly: {e:#}")); assert!(said.contains("PONG"), "{name} did not answer what it was asked"); } } /// Claude Code's answer is the last event's, and an error it reports is an /// error, not an answer #[test] fn claude_codes_answer_is_read_out_of_its_events() { let out = "{\"type\":\"system\"}\n{\"type\":\"result\",\"is_error\":false,\"result\":\" 貸借対照表 \"}\n"; assert_eq!(super::picture_answer("claude", out).unwrap(), "貸借対照表"); let shaped = "{\"type\":\"result\",\"is_error\":false,\"result\":\"x\",\"structured_output\":{\"text\":\"貸借\"}}"; assert_eq!(super::picture_answer("claude", shaped).unwrap(), "{\"text\":\"貸借\"}", "the shaped answer is not read"); let bad = "{\"type\":\"result\",\"is_error\":true,\"result\":\"limit\"}"; assert!(super::picture_answer("claude", bad).is_err()); assert!(super::picture_answer("claude", "not json").is_err()); assert_eq!(super::picture_answer("codex", " text \n").unwrap(), "text"); } use super::*; /// A repository's own settings are offered in exactly one place: the /// project's page. /// /// The devcontainer and the setup belong to the repository, so the folders /// of one project -- its own checkout and each worktree -- must not each /// offer them; that is several places to change one fact, and the last one /// pressed wins. Every folder page points at the project instead. #[test] fn the_repositorys_own_settings_are_offered_where_the_repository_is() { // What a worktree inherits is on the rules page, what it runs on the // setup page -- both pages of the project assert!( PAGE.contains(r#"if (rulesOpen(p, "inherit")) c.append(el("div", {class:"rulesedit"}, inheritPart(desk, p)));"#) && PAGE.contains("extraFilesPart(desk, p)].filter(Boolean));") && PAGE.contains("if (sec.id === \"setup\") {\n if (microvmHomes(p).length) box.append(microvmCard(desk, p));\n box.append(envCard(desk, p));"), "the cards that belong to the repository are not on the project's page" ); assert!( PAGE.contains("if (home) box.insertBefore(elsewhereCard(desk, home), buttons);"), "a folder's page does not point at its project" ); assert!( !PAGE.contains("box.insertBefore(envCard("), "a folder page still offers the repository's settings itself" ); // Projects are a desk's own, and the page asks about them by desk assert!(PAGE.contains("projects: Array.isArray(w.projects) ? w.projects : [],")); assert!(PAGE.contains("\"&desk=\" + encodeURIComponent(desk.id || \"\")")); } /// A tab in a folder on another machine runs an AI that machine has, from /// every door: made new, or made an AI from the Kind picker -- which put /// this PC's `claude` on a server that had none, and the tab said /// "command not found". The picker marks what the machine lacks, and an /// AI it lacks is said where it is chosen #[test] fn a_far_tab_made_an_ai_runs_one_its_machine_has() { assert!(PAGE.contains(r#"setCommand(t, cmdInput, v === "ai" ? aiStartOf(t) : catStart(v));"#), "picking AI as the Kind puts this PC's AI on another machine"); assert!(PAGE.contains("const far = machineStart(desks[sel.desk] || {}, t.group || 0);"), "the AI a far tab starts as is not the one its machine has"); assert!(PAGE.contains("const ok = Array.isArray(has) ? has.includes(c.cmd)"), "the AI picker does not mark what the machine lacks"); assert!(PAGE.contains(r#"fill(T["settings.tab.ai.far_missing"], {host: far.host, ai: cli.label})"#), "an AI the machine lacks is not said where it is chosen"); } /// Every trigger this screen offers is a trigger that actually fires. /// /// The two lists live in different languages -- `HOOK_NAMES` in Rust says /// what the engine will call, `TAB_EVENTS` in the page's script says what /// a person may write -- and nothing but this joins them. An entry the /// page offers and the engine never calls is a box to type code into that /// silently never runs, which is worse than not offering it at all; an /// ending the engine can reach with no entry here can only be handled by /// editing a file by hand. /// `sel` is the page's one record of what is chosen, and every pane reads /// it. A local of the same name anywhere in a function hides it for the /// whole of that block, and a read of `sel.desk` before the local's line /// throws -- the pane is left blank with nothing on screen to say why. /// Adding a tab did exactly that once: the notification card named its /// dropdown `sel`, and every AI tab's pane came up empty. #[test] fn nothing_on_the_settings_page_hides_the_selection() { let shadows: Vec<&str> = ["const sel ", "let sel ", "var sel ", "const sel=", "let sel=", "(sel)", "(sel,", " sel =>", ", sel)"] .into_iter() .filter(|p| PAGE.matches(p).count() > usize::from(*p == "let sel ")) .collect(); assert!(PAGE.contains("let sel = {"), "the selection is no longer where this looks for it"); assert!(shadows.is_empty(), "something on the page is also called sel: {shadows:?}"); } #[test] fn every_trigger_the_screen_offers_is_one_the_engine_fires() { let block = PAGE .split("const TAB_EVENTS = [") .nth(1) .and_then(|r| r.split("];").next()) .expect("TAB_EVENTS is gone from the screen"); let offered: Vec<&str> = block .lines() .filter_map(|l| l.trim().strip_prefix("[\"")) .filter_map(|l| l.split('"').next()) .collect(); assert!(offered.len() >= 8, "the list of triggers is too short: {offered:?}"); for name in &offered { if *name == "_shared" { continue; // not a trigger: shared helpers the others call } assert!( crate::hooks::HOOK_NAMES.contains(name), "{name} is on the screen, but the engine never calls it" ); } // And every way a turn can end is reachable from here for state in [ crate::detect::TabState::Done, crate::detect::TabState::Failed, crate::detect::TabState::Limit, crate::detect::TabState::Background, ] { let hook = crate::hooks::ending_hook(state); assert!( offered.contains(&hook), "for {}, the hook {hook} cannot be chosen on the screen", state.label() ); } } /// A server tab's settings survive being saved from this screen. /// /// The page reads the settings into a flat list and writes them back from /// a fixed set of fields. A field left out of either half is not an error /// anywhere: it simply disappears the next time somebody presses Save, and /// the connection that worked yesterday cannot find its key. The screen /// where a person edits their settings must not be the thing that loses /// them, so both halves are checked here by name #[test] fn the_git_accounts_are_the_apps_and_survive_a_save() { // Read where the app's settings are read, written where they are // written, and never on a desk assert!(PAGE.contains("const appGitAccounts = () => (current.git_accounts = "), "the page has no app-level list"); assert!( PAGE.contains("if (gaccts.length) out.git_accounts = gaccts; else delete out.git_accounts;"), "writing drops the git accounts" ); assert!(!PAGE.contains("w.git_accounts"), "a desk still carries git accounts"); assert!(!PAGE.contains("desk.git_accounts"), "a desk still carries git accounts"); } /// An account is added from the picker that wanted one. /// /// Everything about a git account was on the desk's own page, and the /// place a person holds a token is the project's page, where the picker /// only offers what already exists. The last line of the picker opens the /// desk's list over the page, and closing it comes back to the picker with /// the account that was made #[test] fn a_token_can_be_added_from_the_picker_that_wants_one() { assert!( PAGE.contains(r#"s.append(el("option", {value:ADD_ACCOUNT}, T["settings.gitacct.add_here"]));"#), "the picker has no way to add an account" ); assert!(PAGE.contains("function gitAccountsWindow(done)"), "there is no window to add one in"); // The same list in both places, so a way of adding an account cannot // appear on the desk's page and not in the window assert_eq!( PAGE.matches("...gitAccountsParts()").count(), 2, "the window and the desk's page draw the accounts from different code" ); // Whatever the window is closed by, the picker reads the list again assert!( PAGE.contains(r#"back.addEventListener("mousedown", e => { if (e.target === back) done(); });"#), "closing the window by the backdrop leaves the picker showing the old list" ); // A name a person can type is letters, digits, _ and -, so the line // that adds one can never be mistaken for an account assert!(PAGE.contains(r#"const ADD_ACCOUNT = "@add";"#)); assert!(!crate::config::valid_secret_name("@add")); } /// The sign-ins this PC holds are listed with the desk's accounts: on the /// desk's page and in the window the picker opens, the same two cards, /// each read from the program that holds them and never copied. A refusal /// to sign in on the git column opens the project's account card #[test] fn the_pcs_sign_ins_are_listed_with_the_desks_accounts() { assert!( PAGE.contains(r#"build:() => [gitAccountsCard(), pcSignInsCard(), ghSignInsCard()]},"#), "the settings' Git accounts screen does not list the PC's sign-ins" ); assert!( PAGE.contains(r#"el("div", {class:"mbody"}, ...gitAccountsParts(), pcSignInsCard(), ghSignInsCard()),"#), "the window the picker opens does not list them" ); for asked in ["/api/pc-accounts/add", "/api/pc-accounts/forget", "/api/gh-accounts/add", "/api/gh-accounts/forget"] { assert!(PAGE.contains(asked), "nothing on the page asks {asked}"); } // Each sign-in can be called something -- "for the client" -- and the label // is written with the app's settings under the choice that names it assert!(PAGE.contains("function signInDialog(key, login, destroyWord, destroyAsk, destroy, done)")); assert!(PAGE.contains(r#"const key = THIS_PC + ":" + login;"#), "a PC sign-in's label is not keyed by its choice"); assert!(PAGE.contains(r#"const key = "@gh:" + a.host + "/" + a.login;"#)); // ...and each of gh's accounts is a choice of the pickers, by the same name assert!(PAGE.contains(r#"group(T["settings.gitacct.gh_title"]).append(el("option", {value: "@gh:" + at}, label ? label + " — " + said : said));"#)); assert!(PAGE.contains("if (Object.keys(slabels).length) out.sign_in_labels = slabels; else delete out.sign_in_labels;")); // Nothing chosen is this PC's git, so it is not a line of the picker, // and a choice of it written by an older version reads as nothing assert!(!PAGE.contains(r#"el("option", {value:THIS_PC}"#), "the picker still offers the PC's git as a choice"); assert!(PAGE.contains(r#"const chosen = chosen0 === THIS_PC ? "" : chosen0;"#)); // The git column: no menu of its own any more, and a way to the card // under a refusal that is about the account let board = crate::shell::page(); assert!(!board.contains("acctPick"), "the git column still has an account menu"); assert!(board.contains(r#"openSettings("project-gitacct", true, G.fix)"#), "a refusal has no way to the settings"); assert!(board.contains(r#"G.fix = !d.ok && d.why === "account" ? (d.folder || "") : "";"#)); } /// The token field says what will become of the token. /// /// It used to say it was kept encrypted, full stop. That is true only /// where somebody has set a master password; without one the store is /// written as it stands. The screen now says which of the two this is, /// and says the unsafe one in the colour for danger #[test] fn the_token_field_says_when_nothing_is_encrypting_it() { assert!(PAGE.contains(r#"T["settings.gitacct.token_plain"]"#), "nothing is said about a store with no password"); assert!( PAGE.contains(r#"const plain = storeMode === "plaintext" || storeMode === "empty";"#), "a store yet to be written is not counted as one with no password" ); let said = crate::i18n::t("settings.gitacct.token_hint"); assert!( !said.to_lowercase().contains("encrypt"), "the hint promises encryption that only a master password provides: {said}" ); } #[test] fn the_issue_tabs_settings_button_opens_the_project() { assert!( PAGE.contains(r#"const projectAsk = sec === "project" || (sec || "").startsWith("project-");"#), "there is no link to a project's page" ); // A refusal about the account lands on the card that chooses it, not // at the top of a long page with the card to be found somewhere below assert!(PAGE.contains(r#"acctCard.id = "project-gitacct";"#), "the account card has no address"); assert!( PAGE.contains(r#"if (sec === "project-gitacct") PC_ACCOUNTS_READ.then(() => lookAtCard(sec, 50));"#), "the link does not bring the card into view" ); // The folder as the settings spell it, not as the disk answers about // it: a project on a mapped network drive is written down under the // drive letter, and the page it is on cannot be found by the path the // drive points at assert!( crate::shell::page().contains(r#"openSettings("project-gitacct", true, proj.at || proj.dir)"#), "the Issue tab sends people to the folder instead of its project's account" ); } /// The words between one text and the next quote, wherever the text appears. fn named_after(text: &str, pat: &str) -> std::collections::BTreeSet { let mut out = std::collections::BTreeSet::new(); let mut at = 0; while let Some(i) = text[at..].find(pat) { let from = at + i + pat.len(); let Some(len) = text[from..].find('"') else { break }; out.insert(text[from..from + len].to_string()); at = from + len; } out } /// The body of a function or an object literal, by the line it starts on. fn body_of<'a>(text: &'a str, opens: &str, closes: &str) -> &'a str { let at = text.find(opens).unwrap_or_else(|| panic!("{opens} is gone")); let from = at + opens.len(); let len = text[from..].find(closes).unwrap_or_else(|| panic!("{opens} does not end")); &text[from..from + len] } /// Every screen the board sends somebody to is a screen this page has. /// /// A deep link is a word: the board hands `?section=` over and this /// page looks it up. Nothing fails when the word is not found -- the page /// opens on the general cards, and whoever pressed "edit this" is left /// looking for what they pressed. So a card renamed or taken away here, /// while the board goes on naming it, breaks a button silently and in the /// other file. This is the one thing that says so. /// /// It reads both pages rather than holding a list of its own: what the /// board asks for is every `openSettings("...")`, plus the two fields whose /// value is handed to that same function (a row's `settings:` and the git /// panel's `edit:`). A new field carrying a section has to be named here. #[test] fn every_screen_the_board_asks_for_is_one_the_settings_have() { let board = crate::shell::page(); let mut asks = named_after(&board, "openSettings(\""); asks.extend(named_after(&board, "settings: \"")); asks.extend(named_after(&board, "edit:\"")); assert!(asks.len() > 5, "the board's links are no longer being found: {asks:?}"); // What this page can be asked for: a card of its own, a desk's card by // the name the board uses for it, or a project's page let global = named_after(body_of(PAGE, "function globalSections() {", "\n}"), "{id:\""); let desk_ids = named_after(body_of(PAGE, "function deskSections(desk) {", "\n}"), "s(\""); let links = body_of(PAGE, "const DESK_LINKS = {", "};"); let desk_links: Vec<(String, String)> = links .split(',') .filter_map(|kv| kv.split_once(':')) .map(|(k, v)| { (k.trim().trim_matches('"').to_string(), v.trim().trim_matches('"').to_string()) }) .collect(); assert!(!global.is_empty() && !desk_ids.is_empty() && !desk_links.is_empty(), "the settings' own lists are no longer being found"); // The names that are neither: a project's page, and the cards on it let project = PAGE .contains(r#"const projectAsk = sec === "project" || (sec || "").startsWith("project-");"#); assert!(project, "the project's own page is no longer reachable by name"); // The one form the board opens by itself, over the board: a MicroVM // added from a picker. It has to be answered on this page assert!(PAGE.contains(r#"if (sec === "microvm-add") {"#), "the board's + MicroVM opens nothing"); for ask in &asks { // "words" is a browser tab's own models, reached by the tab's key, // and "words-slow" the same, opened to say why the page is slow // A project's page, or one card on it by the card's own id, which // has to be given out on the page as well as asked for let project_card = ask.starts_with("project-") && PAGE.contains(&format!("\"{ask}\"")); let known = global.contains(ask) || desk_links.iter().any(|(k, _)| k == ask) || ask == "project" || project_card || ask == "words" || ask == "words-slow" || ask == "microvm-add"; assert!(known, "the board sends people to \"{ask}\", which is no screen these settings have"); } // ...and the desk's own cards, which those names point at for (k, v) in &desk_links { assert!(desk_ids.contains(v), "\"{k}\" points at the desk card \"{v}\", which is gone"); } // A link that marks one field brings that field into view by its id, // so the id has to be given out somewhere as well as asked for here for id in named_after(PAGE, "lookAtCard(\"") { let given = PAGE.matches(&format!("\"{id}\"")).count(); assert!(given > 1, "nothing on the page is called \"{id}\", so the link marks nothing"); } } #[test] fn a_server_tabs_settings_survive_a_save() { assert!(PAGE.contains("server: t.server || null"), "reading drops the connection settings"); assert!( PAGE.contains(r#"for (const k of ["key", "jump", "keepalive", "file_command", "remote_dir"])"#), "writing drops the connection settings" ); // A tab that is not a server does not get an empty block, and a // bastion nobody named is not written down as one assert!(PAGE.contains("if (!Object.keys(node.server).length) delete node.server;"), "it writes out connection settings with nothing in them"); assert!(PAGE.contains(r#"if (!(v.host || "").trim()) continue;"#), "it writes out a jump host with no name"); } /// Conversational text must never be typed into a terminal — only what /// the markers (or a lone fence) carry gets through #[test] fn suggested_commands_come_only_from_markers() { assert_eq!( extract_cmd("環境はUbuntuと推定します。\n<<>>\n以上です").unwrap(), "free -h" ); assert_eq!(extract_cmd("```bash\nfree -h\n```").unwrap(), "free -h"); assert!(extract_cmd("メモリを見るには free -h を使います").is_err(), "plain prose is refused"); assert!(extract_cmd("<<>>").is_err(), "an empty suggestion is refused"); } /// A file that isn't there yet is a fresh install; a file that's there but /// broken is an emergency. Telling those two apart is the whole job here. /// /// The broken case used to reach the page as 200 with invalid JSON in the /// body: the parse threw, the form stayed empty, and pressing Save would /// then write that emptiness over the real configuration. So the refusal is /// explicit, and it carries enough to point at the mistake. #[test] fn a_broken_file_is_refused_with_the_spot_it_broke_at() { let dir = crate::test_temp("userjson"); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("config.json"); let _ = std::fs::remove_file(&path); // Missing: hand over the empty shape, no fuss. match read_user_json(&path, "{}") { UserJson::Text(t) => assert_eq!(t, "{}", "a file not made yet is handed over as an empty shape"), UserJson::Refused(..) => panic!("it must not refuse merely because the file is not made yet"), } // Fine: hand it over verbatim, so unknown keys and "//" notes survive. let good = "{\n \"//note\": \"kept\",\n \"max_chain\": 10\n}"; std::fs::write(&path, good).unwrap(); match read_user_json(&path, "{}") { UserJson::Text(t) => assert_eq!(t, good, "a file that was read is handed over exactly as written"), UserJson::Refused(..) => panic!("valid JSON was refused"), } // Broken: refuse, and say where. Naming the line is the point — a bare // "failed to load" would leave someone hunting through their own file. let bad = "{\n \"name\": \"実装\",\n \"cwd\": \"D:\\very\"\n}"; std::fs::write(&path, bad).unwrap(); let UserJson::Refused(status, body) = read_user_json(&path, "{}") else { panic!("broken JSON got through"); }; assert_eq!(status, 409); assert_eq!(body["ok"], serde_json::json!(false)); assert_eq!(body["line"], serde_json::json!(3), "it does not point at the broken line"); assert!(body["column"].as_u64().unwrap() > 0, "it does not point at the broken column"); assert_eq!( body["text"], serde_json::json!(bad), "without the original text, the screen cannot show the line in question" ); assert!( body["path"].as_str().unwrap().ends_with("config.json"), "it is not clear which file this is about" ); let _ = std::fs::remove_file(&path); } /// The connection link may reach the clipboard, never the screen. Printing /// it without the token showed an address that opens nothing; printing it /// with the token puts the key to the machine where a camera can see it. #[test] fn the_phone_card_hands_the_link_over_rather_than_printing_it() { let from = PAGE.find("function remoteCard()").expect("there is no remoteCard"); let len = PAGE[from..].find("function aiSelect()").expect("the card has no end"); let card = &PAGE[from..from + len]; assert!(card.contains("/api/remote/url"), "there is no place to take the URL for copying"); assert!(card.contains("netBadge"), "there is no badge for which network it connects to"); assert!(card.contains("copyText("), "it does not go through the shared clipboard path"); assert_eq!( card.matches("j.origin").count(), 1, "origin only decides whether there is anything to show. It must not be drawn on screen" ); } /// An Esc a dialog took is not an Esc for the sheet under it. /// /// A framed dialog closes on Esc and prevents the key's default; the page /// hears the same key afterwards, when the dialog is already gone, and /// used to close the whole sheet on it -- which, with unsaved work, put /// up a question that took every press until it was answered. Found by /// tools/debug/quick-actions.win.mjs driving the running app. #[test] fn an_escape_a_dialog_took_does_not_close_the_sheet() { let from = PAGE .find("if (SHEET) { e.preventDefault(); closeSettings(); }") .expect("the sheet no longer closes on Esc"); let guard = &PAGE[from.saturating_sub(400)..from]; assert!( guard.contains("e.defaultPrevented"), "the sheet's Esc does not step aside for a dialog that already took the key" ); } /// Opening a card must never count as an edit. /// /// The quick-actions card used to fill in `lua: false` while drawing, so /// merely looking at it lit up "unsaved" and then wrote that default into /// config.json on the next save. payload() already states this rule for /// itself; the card that feeds it has to live by it too. #[test] fn drawing_the_actions_card_writes_nothing() { let from = PAGE.find("function actionsCard()").expect("there is no actionsCard"); let body = &PAGE[from..from + 2400]; for write in ["a.label =", "a.body =", "a.lua ="] { for (i, _) in body.match_indices(write) { let start = body[..i].rfind('\n').map(|n| n + 1).unwrap_or(0); let end = body[i..].find('\n').map(|n| i + n).unwrap_or(body.len()); let line = body[start..end].trim(); // An assignment inside a handler is a human editing, and is fine. // One sitting in the drawing path is the bug. assert!( line.contains("addEventListener"), "it writes while drawing: {line}" ); } } } /// Saving the settings keeps what a folder says that this screen never /// draws. /// /// The screen loaded a folder as its name, id and folder, and saved it as /// those plus two keys it knew of. The app writes more onto a folder -- the /// machine it is on, the project it is a piece of, where it came from -- and /// every save erased them: a folder on a server became a folder here, and a /// project's setup command stopped reaching its worktrees. #[test] fn a_save_keeps_what_a_folder_says_that_this_screen_does_not_show() { let read = PAGE.find("function readFolders(").expect("there is no readFolders"); let read = &PAGE[read..read + 400]; assert!(!read.contains("({name:f.name, id:f.id, cwd:f.cwd})"), "it keeps only the keys decided when reading"); let of = PAGE.find("function foldersOf(").expect("there is no foldersOf"); assert!(PAGE[of..of + 600].contains("Object.assign({}, f,"), "reading drops keys"); let out = PAGE.find("const foldersOut = ").expect("there is no foldersOut"); let out = &PAGE[out..out + 900]; assert!(out.contains("Object.assign({}, g)"), "saving writes only the keys it knows"); assert!(!out.contains("const o = {};"), "saving writes only the keys it knows"); } /// A folder is taken out of the list with the tabs standing in it, rather /// than refused until somebody empties it first. /// /// Emptying it first was not a thing anybody could do: the tabs are /// written in these settings, so the next launch starts them again, and /// the folder was never tab-less for long enough to be taken out. The /// refusal was a wall with no door in it -- one folder, on the list /// forever. The lines go with the folder now, and the press asks first #[test] fn a_folder_goes_with_its_tabs_rather_than_waiting_to_be_emptied() { assert!(!PAGE.contains("if (tabsHere().length) { toast("), "the folder is still refused while it has tabs"); assert!(PAGE.contains("desk.tabs = (desk.tabs || []).filter(t => (t.group || 0) !== gi);"), "the tabs standing in the folder are left behind"); // ...and they are left behind pointing at whatever moved up into its // place, which is the bug the refusal was standing in front of assert!(PAGE.contains("desk.folders.splice(gi, 1); (desk.tabs || []).forEach(t => { if ((t.group || 0) > gi) t.group--; });"), "the folders below it are not renumbered"); assert!(PAGE.contains(r#"fill(T["settings.group.delete_confirm"],"#), "a folder with tabs in it goes without a word"); assert!(PAGE.contains(r#"if ((desk.folders || []).length <= 1) { toast(T["settings.group.last"], true); return false; }"#), "the last folder of a desk can be taken away"); } #[test] fn what_a_model_wraps_its_answer_in_is_not_part_of_the_answer() { assert_eq!(strip_fence("one\ntwo"), "one\ntwo", "plain in, plain out"); assert_eq!( strip_fence("Here it is:\n```rust\nfn main() {}\n```\nhope that helps"), "fn main() {}", "only what is inside the fence is the answer" ); // An opening fence with nothing closing it still gives up its contents assert_eq!(strip_fence("```\nline\n"), "line"); } /// The settings screen offers the languages this program has, and no /// others. Two lists that drift apart mean a language that can be chosen /// and has nothing behind it, or one that exists and cannot be reached #[test] fn the_settings_offer_exactly_the_languages_there_are() { let page = super::PAGE; for (code, called, _) in crate::i18n::LANGUAGES { assert!( page.contains(&format!("[\"{code}\", \"{called}\"]")), "the settings do not offer {code} ({called})" ); } // ...and offer no others. A code the picker has and this list does // not is a language somebody can choose with nothing behind it let picker = page .split("choose(current, \"language\"") .nth(1) .and_then(|rest| rest.split("]),").next()) .expect("the language picker has moved"); for line in picker.lines() { let Some(rest) = line.trim().strip_prefix("[\"") else { continue }; let Some((code, _)) = rest.split_once('\"') else { continue }; // The empty code is "follow the machine", not a language if code.is_empty() { continue; } assert!( crate::i18n::LANGUAGES.iter().any(|(c, _, _)| *c == code), "the settings offer {code}, which this program has no words for" ); } } #[test] fn manual_is_embedded_and_usable() { // The spec handed to the AI must be obtainable no matter where it's launched from (regardless of language) for (code, text) in EMBEDDED_MANUALS { assert!(text.contains("shikisha.send_to_tab"), "the spec for {code} is empty"); } let m = load_manual(std::path::Path::new("/nonexistent/config.json")); assert!(m.contains("shikisha."), "it falls back to the embedded one"); } /// The spec must explain every event the screen offers as a choice. /// /// This spec is passed to the AI as-is. If asked for an event it doesn't cover, /// the AI will honestly and correctly reply "that's not in the spec, so I won't do anything." /// If a feature is added but the spec isn't updated, that feature stays invisible to the AI /// Every assistant AI this program starts for a one-off question is /// started with its hands tied. /// /// Not a style rule. Asked an ordinary question in an ordinary folder, an /// assistant AI reads it as a job: asked why the program had stopped, one /// went and edited code and then reported that it had fixed it. Nothing /// this program asks is a job -- every one of these is a question whose /// answer is already in the prompt -- so each CLI is given the strongest /// "read only, no tools" it has. /// /// Checked by name, per program, so that adding a fourth AI fails here /// rather than quietly shipping one that can act #[test] fn a_one_off_question_never_hands_the_ai_any_tools() { // What each program has to be told, in its own words let required: [(&str, &[&str]); 3] = [ ("claude", &["--tools", "--no-session-persistence", "--strict-mcp-config", "--disable-slash-commands"]), ("codex", &["--sandbox", "read-only", "--ephemeral"]), ("gemini", &["--approval-mode", "plan", "--extensions", "none"]), ]; for (name, must) in required { let (args, _) = super::light_invocation(name, false, None, None) .unwrap_or_else(|| panic!("{name} has no confined way to be asked")); for want in must { assert!( args.iter().any(|a| a == want), "{name} is asked without {want}: {args:?}" ); } } // ...and every AI this program knows about is in that list. A new one // added to AI_ENGINES and forgotten here would be the one with tools for (name, _, _) in super::AI_ENGINES { assert!( required.iter().any(|(n, _)| *n == name), "{name} can be started but has no confined way written for it" ); } } /// The picture tools take the same care. A screenshot is handed over with /// a question about it, which is no more a job than any other question #[test] fn asking_about_a_picture_hands_over_no_tools_either() { let png = [0u8; 4]; for (name, must) in [ ("claude", vec!["--tools"]), ("codex", vec!["--sandbox", "read-only"]), ("gemini", vec!["--approval-mode", "plan"]), ] { let (args, _, _) = super::picture_invocation(name, "what does this say", &png, "{}") .unwrap_or_else(|| panic!("{name} cannot be asked about a picture")); for want in must { assert!(args.iter().any(|a| a == want), "{name}: {args:?}"); } } } #[test] fn the_manual_covers_every_event_the_screen_offers() { for (code, text) in EMBEDDED_MANUALS { for event in EVENT_FILES { // _shared isn't an event; it's a shared location if event == "_shared" { continue; } assert!( text.contains(event), "the spec for {code} does not explain {event} (the AI writes without knowing this event)" ); } } } /// Top-level const/let bindings must not be duplicated. /// A duplicate causes a SyntaxError, so the whole script fails to run and only static HTML is left. /// The result is a hard-to-diagnose break: the screen shows up but nothing works fn top_level_bindings(page: &str) -> Vec { page.lines() .filter_map(|l| l.strip_prefix("const ").or_else(|| l.strip_prefix("let "))) .filter_map(|rest| rest.split(|c: char| !(c.is_alphanumeric() || c == '_')).next()) .filter(|n| !n.is_empty()) .map(str::to_string) .collect() } fn assert_no_duplicate_bindings(name: &str, page: &str) { let names = top_level_bindings(page); for (i, n) in names.iter().enumerate() { assert!( !names[..i].contains(n), "{name}: `{n}` is declared twice at the top level (the whole script stops working)" ); } } /// A page's placeholders are filled from what the page says, once: a /// value that holds a placeholder's name -- a project called `__DICT__` /// -- is put in as it is, and the page's script still parses #[test] fn a_value_is_never_filled_into_again() { let page = "const A = __INSIDESHOWN__; const D = __DICT__; x__y __init__"; let filled = super::fill_page( page, &[("__INSIDESHOWN__", r#"{"__DICT__":1}"#.into()), ("__DICT__", r#"{"k":"v"}"#.into())], ); assert_eq!(filled, r#"const A = {"__DICT__":1}; const D = {"k":"v"}; x__y __init__"#); } /// Every word a new tab's automation name can be drawn as is one automation /// accepts as it stands, and there are enough of them that a desk of tabs /// does not run out. #[test] fn a_new_tab_is_named_from_words_automation_accepts() { let words = crate::config::pet_nouns(); assert!(words.len() >= 100, "too few words to draw from: {}", words.len()); for w in &words { assert!((3..=6).contains(&w.len()), "{w} is not a short word"); assert!(w.bytes().all(|b| b.is_ascii_lowercase()), "{w} is not a name automation takes as it is"); // The name the settings screen settles on for it is itself assert_eq!(crate::config::slug_id(w), *w, "{w} would be tidied into something else"); assert!(!crate::config::NOT_A_TAB_NAME.contains(w), "{w} is on the list of words a tab is not called"); } let json: Vec = serde_json::from_str(&super::pet_nouns_json()).expect("the list is not JSON"); assert_eq!(json.len(), words.len()); } /// A tab added from the settings is named by what it runs and called by a /// word of its own -- not by its command. Called by its command, a tab that /// started as Claude and was turned into SSH went on being "claude-2". #[test] fn a_new_tab_is_named_by_what_it_runs_and_called_by_a_word() { let add = PAGE.split("function addTabTo(desk, group) {").nth(1).expect("addTabTo is gone"); let add = &add[..add.find("\n}\n").expect("addTabTo does not end")]; assert!(add.contains("t.name = kindName(command);"), "a new tab is not named by what it runs"); assert!(add.contains("t.id = petId(desk, t);"), "a new tab is not called by a word of its own"); assert!(!add.contains("inferredTabId"), "a new tab is called by its command again"); // The name follows the kind while nobody has typed their own assert!(PAGE.contains("followKind(t, before);"), "changing what a tab runs no longer carries its name along"); // One card for what a tab runs, on its page and in the dialog alike assert!( PAGE.contains("box.append(launchCard(t, () => {") && PAGE.contains("const out = [launchCard(t)];"), "what a tab runs is not asked with the one card on its page and in the dialog" ); assert_eq!(PAGE.matches("launchCard(t").count(), 3, "what a tab runs is asked in more or fewer places than two"); } /// The style guide's list of where each part is in the code names only /// functions that are there, on the page it says. /// /// The list is what stops a second copy of a part being written: somebody /// about to write one looks there first. A name in it that no longer /// exists sends them looking for nothing -- and then writing their own #[test] fn every_code_entry_in_the_style_guide_exists() { let board = crate::shell::page(); let named = regex::Regex::new(r"`([A-Za-z_][A-Za-z0-9_]*)\(").unwrap(); for (lang, guide) in [ ("ja", include_str!("../../../docs/design/STYLEGUIDE.ja.md")), ("en", include_str!("../../../docs/design/STYLEGUIDE.md")), ] { let guide = guide.replace("\r\n", "\n"); let from = guide.find("").unwrap_or_else(|| panic!("{lang}: the list is gone")); let to = guide.find("").unwrap_or_else(|| panic!("{lang}: the list does not end")); let rows: Vec<&str> = guide[from..to].lines().filter(|l| l.starts_with("| ") && !l.starts_with("|---")).skip(1).collect(); assert!(rows.len() >= 10, "{lang}: only {} rows were read", rows.len()); for row in rows { let cells: Vec<&str> = row.split(" | ").collect(); let page = cells.last().copied().unwrap_or_default(); let names: Vec<&str> = named.captures_iter(row).map(|c| c.get(1).unwrap().as_str()).collect(); assert!(!names.is_empty(), "{lang}: a row names no function: {row}"); for name in names { let defined = format!("function {name}("); let found = (page.contains("webui.rs") && PAGE.contains(&defined)) || (page.contains("shell.rs") && board.contains(&defined)) || (page.contains("toast.rs") && crate::toast::JS.contains(&defined)); assert!(found, "{lang}: `{name}` is not a function on the page the style guide says ({page})"); } } } } /// The board's + asks only what the new tab runs, in a dialog, and a save /// that failed leaves the dialog there with the reason. #[test] fn the_board_plus_asks_one_question_in_a_dialog() { assert!(PAGE.contains(r#"if (q.get("float") === "1") { render(); enterFloat(wi, sel.tab); return; }"#), "the board's + opens the whole settings page again"); assert!(PAGE.contains("
") { rest = &rest[at + "") else { break }; script.push_str(&rest[..end]); script.push('\n'); rest = &rest[end..]; } assert!(script.len() > 10_000, "the script could not be pulled out of the page: {} characters", script.len()); let file = std::env::temp_dir().join(format!("shikisha-settings-{}.js", std::process::id())); std::fs::write(&file, &script).expect("could not write the script out"); let checked = std::process::Command::new("node").arg("--check").arg(&file).output(); let _ = std::fs::remove_file(&file); match checked { Ok(done) => assert!( done.status.success(), "the settings script dies whole on a syntax error:\n{}", String::from_utf8_lossy(&done.stderr) ), Err(e) => eprintln!("node is missing, so the syntax check did not run ({e}). It runs in CI"), } } #[test] fn settings_identities_work_without_secure_context_apis() { let from = PAGE.find("function newUid() {").expect("the shared identity generator"); let to = PAGE[from..].find("\n}").unwrap() + from + 2; let source = serde_json::to_string(&PAGE[from..to]).unwrap(); let script = format!(r#" const vm = require('node:vm'); const assert = require('node:assert/strict'); const {{webcrypto}} = require('node:crypto'); for (const crypto of [webcrypto, {{getRandomValues: b => webcrypto.getRandomValues(b)}}]) {{ const next = vm.runInNewContext({source} + '\nnewUid', {{crypto}}); const ids = Array.from({{length:128}}, () => next()); for (const id of ids) assert.match(id, /^[0-9a-f]{{8}}-[0-9a-f]{{4}}-4[0-9a-f]{{3}}-[89ab][0-9a-f]{{3}}-[0-9a-f]{{12}}$/); assert.equal(new Set(ids).size, ids.length); }} "#); match std::process::Command::new("node").arg("-e").arg(script).output() { Ok(done) => assert!(done.status.success(), "{}", String::from_utf8_lossy(&done.stderr)), Err(e) => eprintln!("node is missing, so the identity check did not run ({e}). It runs in CI"), } } /// The same dialog, framed over a board in a browser (?embed=1). /// /// A browser has no WebView to place this page in, so the board frames it /// instead. Framed, the way out is a word to the board: walking to "/" /// would load the board inside the frame, and the board is already there /// behind it. #[test] fn the_dialog_framed_over_a_board_talks_to_the_board() { assert!(PAGE.contains(r#"const EMBED = new URLSearchParams(location.search).get("embed") === "1";"#), "the page cannot tell it is framed"); assert!(PAGE.contains(r#"const toBoard = act => { try { window.parent.postMessage({cfg:act}, location.origin); } catch (e) {} };"#), "there is no way to answer the board, or it answers any origin"); assert!(PAGE.contains(r#"else if (EMBED) toBoard("close");"#), "closing a framed dialog loads the board inside the frame"); assert!(PAGE.contains(r#"else if (EMBED) toBoard("full");"#), "More settings leaves the whole of the settings in a dialog-sized frame"); // The frame draws the edge; a second one inside reads as a box in a box assert!(PAGE.contains(" body.embed.float #floatbox { border:0; }"), "the framed page draws an edge inside the frame's own"); assert!(PAGE.contains(r#"if (EMBED) document.body.classList.add("embed");"#), "nothing says the page is framed before it is painted"); // A sheet is a dialog one size up, so Escape is its way out -- and // this page is what hears that key, in the window as in a frame assert!(PAGE.contains(r#"const SHEET = new URLSearchParams(location.search).get("sheet") === "1";"#), "the page cannot tell it is standing over a board"); assert!(PAGE.contains(r#"if (SHEET) { e.preventDefault(); closeSettings(); }"#), "Escape does not put a sheet away"); assert!(crate::shell::page().contains(r#"if (sheet) { p.sheet = "1"; openCfgLayer(p, "sheet"); } else walkToSettings(p);"#), "a browser's sheet is never told that it is one"); } /// The screen must not still contain a raw `{{key}}` or `__DICT__`. /// A forgotten substitution would only be caught at runtime, so it's stopped here instead #[test] fn pages_are_fully_rendered() { for (name, page) in [("PAGE", PAGE), ("HELP_PAGE", HELP_PAGE), ("RESULT_PAGE", RESULT_PAGE)] { // Every page is coloured before it is worded, and each one says so // by asking for the block. A page that stopped asking would come up // with no colours defined and nothing would say why assert!(page.contains("{{THEME}}"), "{name} does not receive the colors"); let html = crate::i18n::render(&themed(page.to_string())) .replace("__TOKEN__", "t") .replace("__REMOTE__", "false") .replace("__PACKAGED__", "false") .replace("__SYSTEM__", "\"windows\"") .replace("__SHELL__", &machine_shell_json()) .replace("__HOTKEYS__", &crate::hotkeys::catalog_json()) .replace("__QUICK__", &quick_json()) .replace("__DICT__", "{}") .replace("__GRANTS__", "[]") .replace("__GITLUA__", "\"\"") .replace("__PROTECT__", "[]") .replace("__THISPC__", "\"@pc\"") .replace("__PETNOUNS__", "[]") .replace("__PETADJECTIVES__", "[]") .replace("__SHIPPEDINSIDE__", "[]") .replace("__INSIDESHOWN__", "{}") .replace("__MD__", "\"\""); // Checked on the finished page, not the template: the shared toast // is poured in on the way, and a page that kept a copy of one of // its names would only break once it was actually served assert_no_duplicate_bindings(name, &html); assert!(!html.contains("{{"), "an unfilled {{{{key}}}} is left in {name}"); assert!(!html.contains("__"), "an unfilled placeholder is left in {name}"); assert!(html.contains(""), "the lang attribute of {name}"); } } /// A phone reaching the settings over the proxy must never make a window /// appear on the PC. The page is served without the buttons, and the /// endpoints behind them answer with a refusal instead of a dialog that /// would hold the request open until someone walked over to the PC. /// The screen that lists devices, exercised the way the page does it. /// /// The point of the whole book is that a device can be named and taken /// away on its own, so that is what this walks: two devices in, one named, /// one revoked, and the other still there afterwards. /// Whose a phone registration is comes from the door it came in by: the /// device the remote proxy says it let in, or this PC's own screen. What /// the body says is not taken -- a device naming another there would /// otherwise outlive its own key under the other's name #[test] fn a_phone_registration_belongs_to_the_device_the_door_let_in() { let _book = crate::clients::tests::OwnBook::new(); let dir = std::env::temp_dir().join(format!("shikitest_{}", crate::random_hex(8))); std::fs::create_dir_all(&dir).unwrap(); let cfg = dir.join("config.json"); std::fs::write(&cfg, "{}").unwrap(); let ui = WebUi::start_with( cfg, Arc::new(std::sync::Mutex::new(RemoteInfo::default())), Arc::new(std::sync::Mutex::new(None)), ) .unwrap(); let (base, token) = ui.url.split_once("/?token=").unwrap(); let (base, token) = (base.to_string(), token.to_string()); let agent: ureq::Agent = ureq::Agent::config_builder() .http_status_as_error(false) .timeout_global(Some(std::time::Duration::from_secs(10))) .build() .new_agent(); let body = |endpoint: &str| { serde_json::json!({"endpoint": endpoint, "p256dh": "k", "auth": "a", "device": "someone-else"}).to_string() }; agent .post(&format!("{base}/api/push/subscribe")) .header("X-Token", &token) .header(REMOTE_CLIENT_HEADER, "1") .header(REMOTE_DEVICE_HEADER, "phone-1") .send(body("https://push.invalid/phone")) .unwrap(); agent .post(&format!("{base}/api/push/subscribe")) .header("X-Token", &token) .send(body("https://push.invalid/here")) .unwrap(); let whose = |endpoint: &str| crate::push::subs().into_iter().find(|s| s.endpoint == endpoint).map(|s| s.device); assert_eq!(whose("https://push.invalid/phone").as_deref(), Some("phone-1"), "the device the door let in is not the one kept"); assert_eq!(whose("https://push.invalid/here").as_deref(), Some(crate::push::HERE), "this PC's own screen is not kept as itself"); ui.shutdown(); let _ = std::fs::remove_dir_all(&dir); } #[test] fn the_settings_page_can_name_and_revoke_one_device() { let _book = crate::clients::tests::OwnBook::new(); let dir = std::env::temp_dir().join(format!("shikitest_{}", crate::random_hex(8))); std::fs::create_dir_all(&dir).unwrap(); let cfg = dir.join("config.json"); std::fs::write(&cfg, "{}").unwrap(); // What the running remote would hand over: a way to end what a revoked // device is holding. Recorded here rather than acted on, so the test // can say whether it was called let ended: Arc>> = Arc::new(std::sync::Mutex::new(Vec::new())); let heard = Arc::clone(&ended); let info = RemoteInfo { running: true, cut: Some(Arc::new(move |id: &str| heard.lock().unwrap().push(id.to_string()))), ..Default::default() }; let ui = WebUi::start_with( cfg, Arc::new(std::sync::Mutex::new(info)), Arc::new(std::sync::Mutex::new(None)), ) .unwrap(); let (base, token) = ui.url.split_once("/?token=").unwrap(); let (base, token) = (base.to_string(), token.to_string()); let agent: ureq::Agent = ureq::Agent::config_builder() .http_status_as_error(false) .timeout_global(Some(std::time::Duration::from_secs(10))) .build() .new_agent(); let (phone, _) = crate::clients::pair("").unwrap(); let (laptop, laptop_key) = crate::clients::pair("laptop").unwrap(); let listed = |agent: &ureq::Agent| -> serde_json::Value { let mut r = agent .get(&format!("{base}/api/remote/clients")) .header("X-Token", &token) .call() .unwrap(); serde_json::from_str(&r.body_mut().read_to_string().unwrap()).unwrap() }; // Both are listed, and no key is let seen = listed(&agent); let text = seen.to_string(); assert!(text.contains(&phone.id) && text.contains(&laptop.id), "the devices are not listed: {text}"); assert!(!text.contains(&laptop_key), "the key itself shows on the screen"); assert!(!text.contains(&laptop.hash), "even the hash used for matching shows"); // Naming one agent .post(&format!("{base}/api/remote/clients/name")) .header("X-Token", &token) .send(serde_json::json!({"id": phone.id, "name": "台所のiPad"}).to_string()) .unwrap(); assert!(listed(&agent).to_string().contains("台所のiPad"), "the name is not kept"); // Taking one away: the row goes, the running remote is told, and the // other device is untouched agent .post(&format!("{base}/api/remote/clients/revoke")) .header("X-Token", &token) .send(serde_json::json!({"id": phone.id}).to_string()) .unwrap(); let after = listed(&agent).to_string(); assert!(!after.contains(&phone.id), "it is not removed from the list: {after}"); assert!(after.contains(&laptop.id), "it was removed by mistake: {after}"); assert_eq!( ended.lock().unwrap().as_slice(), [phone.id.as_str()], "the key was taken away, but the screen that device is watching was not stopped" ); ui.shutdown(); let _ = std::fs::remove_dir_all(&dir); } #[test] fn a_phone_gets_no_native_dialogs() { let dir = std::env::temp_dir().join(format!("shikitest_{}", crate::random_hex(8))); std::fs::create_dir_all(&dir).unwrap(); let cfg = dir.join("config.json"); std::fs::write(&cfg, "{}").unwrap(); let ui = WebUi::start_with( cfg, Arc::new(std::sync::Mutex::new(RemoteInfo::default())), Arc::new(std::sync::Mutex::new(None)), ) .unwrap(); let (base, token) = ui.url.split_once("/?token=").unwrap(); let (base, token) = (base.to_string(), token.to_string()); let agent: ureq::Agent = ureq::Agent::config_builder() .http_status_as_error(false) .timeout_global(Some(std::time::Duration::from_secs(10))) .build() .new_agent(); // The page tells itself apart: same HTML, one flag let own = agent .get(&format!("{base}/")) .header("X-Token", &token) .call() .unwrap() .body_mut() .read_to_string() .unwrap(); assert!(own.contains("const REMOTE = false;"), "the PC's own window is not remote"); let phone = agent .get(&format!("{base}/")) .header("X-Token", &token) .header(REMOTE_CLIENT_HEADER, "1") .call() .unwrap() .body_mut() .read_to_string() .unwrap(); assert!(phone.contains("const REMOTE = true;"), "a proxied page must know it is remote"); // Every dialog endpoint answers, rather than opening a window and waiting. // A timeout here (not a failed assert) is the bug this guards against for path in NATIVE_DIALOG_PATHS { let mut r = agent .post(&format!("{base}{path}")) .header("X-Token", &token) .header(REMOTE_CLIENT_HEADER, "1") .header("Content-Type", "application/json") .send(r#"{"kind":"dir"}"#) .unwrap(); let v: serde_json::Value = serde_json::from_str(&r.body_mut().read_to_string().unwrap()).unwrap(); assert_eq!(v["ok"], serde_json::json!(false), "{path} should refuse a phone"); assert_eq!( v["error"].as_str().unwrap_or(""), crate::i18n::t("settings.pick.no_remote"), "{path} should say why" ); } ui.shutdown(); let _ = std::fs::remove_dir_all(&dir); } /// The phone chooses a folder from what is on the PC, not from memory. The /// walk is the sidebar's (uistate::BrowseState), reached from the settings /// screen, and it reads settings-style paths back the way they are written. #[test] fn a_phone_walks_the_pcs_folders_instead() { let dir = std::env::temp_dir().join(format!("shikitest_{}", crate::random_hex(8))); std::fs::create_dir_all(dir.join("scripts").join("inner")).unwrap(); std::fs::write(dir.join("scripts").join("secrets.json"), "{}").unwrap(); let cfg = dir.join("config.json"); std::fs::write(&cfg, "{}").unwrap(); let ui = WebUi::start_with( cfg, Arc::new(std::sync::Mutex::new(RemoteInfo::default())), Arc::new(std::sync::Mutex::new(None)), ) .unwrap(); let (base, token) = ui.url.split_once("/?token=").unwrap(); let (base, token) = (base.to_string(), token.to_string()); let agent: ureq::Agent = ureq::Agent::config_builder() .http_status_as_error(false) .timeout_global(Some(std::time::Duration::from_secs(10))) .build() .new_agent(); let walk = |body: &str| -> serde_json::Value { let mut r = agent .post(&format!("{base}/api/walk")) .header("X-Token", &token) .header(REMOTE_CLIENT_HEADER, "1") .header("Content-Type", "application/json") .send(body) .unwrap(); serde_json::from_str(&r.body_mut().read_to_string().unwrap()).unwrap() }; // The top is this computer: the person's own folder and the drives let top = walk(r#"{"path":""}"#); assert_eq!(top["ok"], serde_json::json!(true), "{top}"); assert!(top["up"].is_null(), "the top has nowhere to go back to: {top}"); assert!(!top["dirs"].as_array().unwrap().is_empty(), "the drives are not shown: {top}"); assert_eq!(top["chosen"], serde_json::json!(""), "the top is not a place that can be chosen"); // A settings-style relative path is read against the config folder, and // choosing the folder writes it back the same way let sub = walk(r#"{"path":"scripts"}"#); assert_eq!(sub["ok"], serde_json::json!(true), "{sub}"); assert!(sub["at"].as_str().unwrap().ends_with("scripts"), "{sub}"); assert_eq!(sub["chosen"], serde_json::json!("scripts"), "{sub}"); let dirs = sub["dirs"].as_array().unwrap(); assert_eq!(dirs.len(), 1, "{sub}"); assert!(dirs[0].as_str().unwrap().ends_with("inner")); assert!(sub["files"].as_array().unwrap().is_empty(), "files got mixed into choosing a folder: {sub}"); // Asked for files, the same folder lists them; walking onto one is the choice let with = walk(r#"{"path":"scripts","files":true}"#); let files = with["files"].as_array().unwrap(); assert_eq!(files.len(), 1, "{with}"); let file = files[0].as_str().unwrap().to_string(); let picked = walk(&serde_json::json!({"path": file, "files": true}).to_string()); assert_eq!(picked["file"], serde_json::json!(true), "{picked}"); assert_eq!(picked["chosen"], serde_json::json!("scripts/secrets.json"), "{picked}"); // A folder that cannot be read says why rather than showing nothing let gone = walk(&serde_json::json!({"path": dir.join("nowhere")}).to_string()); assert_eq!(gone["ok"], serde_json::json!(true), "{gone}"); assert!(gone["error"].as_str().map(|e| !e.is_empty()).unwrap_or(false), "{gone}"); ui.shutdown(); let _ = std::fs::remove_dir_all(&dir); } #[test] fn token_compare_rejects_mismatch() { assert!(crate::crypto::token_eq("abc123", "abc123")); assert!(!crate::crypto::token_eq("abc123", "abc124")); assert!(!crate::crypto::token_eq("abc", "abc123")); } #[test] fn token_is_parsed_from_query() { assert_eq!(query_token("/?token=deadbeef"), "deadbeef"); assert_eq!(query_token("/api/config?x=1&token=zz"), "zz"); assert_eq!(query_token("/"), ""); } #[test] fn tab_layout_is_described_for_the_ai() { let v: serde_json::Value = serde_json::from_str( r#"{"self":1,"tabs":[{"index":1,"name":"実装"},{"index":2,"name":"検査"}]}"#, ) .unwrap(); let s = describe_tabs(&v); // Pass the index-to-name mapping to the AI so it can be addressed by name assert!(s.contains("1. 実装"), "{s}"); assert!(s.contains("2. 検査"), "{s}"); assert!(s.contains("this script runs in"), "{s}"); // Adds nothing when there's no tab info assert_eq!(describe_tabs(&serde_json::json!({})), ""); } #[test] fn extracts_lua_from_ai_output() { // With marker (the expected shape) let s = "了解しました\n<<>>\n以上です"; assert_eq!(extract_lua(s).unwrap(), "shikisha.log(\"hi\")"); // Accepted with just a code fence too, as long as it looks like code let s2 = "```lua\nshikisha.send_to_tab(1, tab.output)\n```"; assert_eq!( extract_lua(s2).unwrap(), "shikisha.send_to_tab(1, tab.output)" ); // Errors out (and isn't saved) for conversational text alone assert!(extract_lua("どのような自動化を作りますか?").is_err()); } /// The network badge under a phone's QR opens the phone page, which begins /// with putting Tailscale on both ends: the board's window asks for it by /// this name, and the address is the app's own words, never the page's. #[test] fn tailscale_opens_the_phone_page() { let url = super::install_page("tailscale").unwrap_or_default(); assert!(url.starts_with("https://shikisha-term.com/") && url.ends_with("phone/"), "the badge opens {url:?}"); assert!(PAGE.contains(r#"href:T["settings.phone.guide.url"], target:"_blank"},"#), "the settings' badge opens nothing"); } /// The setup splits the assistant AIs by whether this PC has them, in the /// settings' own order, and says which have a page to install from. #[test] fn the_first_start_setup_offers_what_is_installed_and_points_at_the_rest() { let ids = |v: &[crate::uistate::SetupAi]| v.iter().map(|a| a.id.clone()).collect::>(); let st = super::setup_state_of(|n| n == "codex", |n| n != "gemini"); assert_eq!(ids(&st.installed), ["codex"]); assert!(!st.gh, "GitHub CLI is said to be here"); assert!(super::setup_state_of(|n| n == "gh", |_| true).gh, "GitHub CLI is not found"); assert_eq!(super::install_page("gh").as_deref(), Some("https://cli.github.com/"), "GitHub CLI's page is not its own"); assert_eq!(ids(&st.missing), ["claude", "gemini"], "the rest is out of order or missing"); assert!(st.missing[0].install && !st.missing[1].install, "a page is claimed that is not there"); assert_eq!(st.installed[0].name, "Codex CLI", "not the name the settings call it"); // Nothing installed: nothing to pick, all three to install let none = super::setup_state_of(|_| false, |_| true); assert!(none.installed.is_empty()); assert_eq!(ids(&none.missing), ["claude", "codex", "gemini"]); // Every one of them has a page in the profiles that ship for (name, _, _) in super::AI_ENGINES { assert!(crate::profile::install_url_for(name).is_some(), "{name} has no install page"); } } /// A git account can sign in with GitHub CLI: offered in the dialog, asks /// for no token, and is saved as such #[test] fn a_git_account_can_sign_in_with_github_cli() { assert!(PAGE.contains(r#"group("gh", T["settings.gitacct.by_gh"], T["settings.gitacct.add_gh"]"#), "gh is not offered"); assert!(PAGE.contains("const tokenWhy = !ssh && !gh && !hasToken"), "a gh account is asked for a token"); assert!(PAGE.contains(r#"else if (method === "gh") { it.method = "gh"; delete it.key; delete it.login; }"#), "a gh account is not saved as one"); assert!(PAGE.contains(r#"if (method !== "gh" && tokenIn.value.trim())"#), "a gh account files a token"); } /// A tab starts as the AI chosen in the setup, and with Yolo mode its /// flag is already in the command -- where the checkbox shows it #[test] fn a_new_tab_starts_as_the_chosen_ai_and_carries_yolo_in_its_command() { assert!(PAGE.contains("AI_CLIS.find(c => installed(c) && c.cmd === current.ai_engine)"), "the Assistant AI does not decide what a new tab runs"); assert!(PAGE.contains(r#"const flag = current.yolo ? cliFlagOf(head) : "";"#), "Yolo mode does not reach a new tab"); assert!(PAGE.contains(r#"check(current, "yolo", T["settings.yolo.label"])"#), "Yolo mode is not under Basic"); } #[test] fn picked_paths_stay_portable_when_inside_the_config_folder() { let cfg = std::path::Path::new("D:/app/config.json"); // Paths under the config folder become relative (so the whole folder stays portable) assert_eq!( display_path(std::path::Path::new("D:/app/scripts/reviewer"), cfg), "scripts/reviewer" ); // Paths outside it stay absolute, just with normalized separators assert_eq!( display_path(std::path::Path::new("C:\\Users\\me\\.ssh\\id_ed25519"), cfg), "C:/Users/me/.ssh/id_ed25519" ); } #[test] fn desk_path_rejects_traversal() { let cfg = std::path::Path::new("C:/app/config.json"); // Happy path assert!(safe_desk_path("/api/desk?file=desks/x.json", cfg).is_some()); // Path traversal, absolute paths, and non-JSON are rejected assert!(safe_desk_path("/api/desk?file=../secrets.json", cfg).is_none()); assert!(safe_desk_path("/api/desk?file=desks/../../x.json", cfg).is_none()); assert!( safe_desk_path( &format!("/api/desk?file={}", crate::outside_path("x.json")), cfg ) .is_none() ); assert!(safe_desk_path("/api/desk?file=desks/x.lua", cfg).is_none()); // URL-encoded .. is rejected too assert!(safe_desk_path("/api/desk?file=%2E%2E%2Fsecrets.json", cfg).is_none()); } /// A dialog is dismissed by a press on the backdrop, never by a click on it. /// /// A click is attributed to the nearest ancestor of where the button went /// down and where it came up, and the backdrop covers the whole screen. So /// selecting text in a field and releasing past the dialog's edge — a /// hurried drag to the end of a line — arrived as a click on the backdrop, /// and the form vanished taking everything typed into it. Where the press /// landed is the only thing that says what was meant. #[test] fn a_dialog_closes_on_the_press_that_started_outside_it() { let page = PAGE; assert!( page.contains(r#"back.addEventListener("mousedown", e => { if (e.target === back) back.remove(); });"#), "the modal closes on click instead of on press" ); assert!( !page.contains(r#"back.addEventListener("click""#), "the way of closing on a background click is back" ); } #[test] fn tokens_are_unique_and_long() { let a = random_token().unwrap(); let b = random_token().unwrap(); assert_eq!(a.len(), 48); assert_ne!(a, b); } /// Actually starts the server and verifies the auth and save behavior #[test] fn server_requires_token_and_saves_valid_json() { let dir = std::env::temp_dir().join("shikisha-webui-test"); std::fs::create_dir_all(&dir).unwrap(); let cfg = dir.join("config.json"); std::fs::write(&cfg, r#"{"max_chain":10}"#).unwrap(); let ui = WebUi::start_with( cfg.clone(), Arc::new(std::sync::Mutex::new(RemoteInfo::default())), Arc::new(std::sync::Mutex::new(None)), ) .unwrap(); let token = ui.url.split("token=").nth(1).unwrap().to_string(); let base = ui.url.split("/?").next().unwrap().to_string(); let agent = ureq::Agent::new_with_defaults(); // No token → 403 let status = agent .get(&format!("{base}/api/config")) .call() .map(|r| r.status().as_u16()) .unwrap_or_else(|e| match e { ureq::Error::StatusCode(c) => c, other => panic!("unexpected: {other}"), }); assert_eq!(status, 403, "without a token it is refused"); // Correct token → the current config can be read let body = agent .get(&format!("{base}/api/config?token={token}")) .call() .unwrap() .body_mut() .read_to_string() .unwrap(); assert!(body.contains("max_chain")); // Broken JSON is not saved let bad = agent .post(&format!("{base}/api/config?token={token}")) .send("{ broken") .map(|r| r.status().as_u16()) .unwrap_or_else(|e| match e { ureq::Error::StatusCode(c) => c, other => panic!("unexpected: {other}"), }); assert_eq!(bad, 400); assert_eq!( std::fs::read_to_string(&cfg).unwrap(), r#"{"max_chain":10}"#, "if validation fails, the original settings are kept" ); // Valid JSON is saved agent .post(&format!("{base}/api/config?token={token}")) .send(r#"{"max_chain":5}"#) .unwrap(); assert_eq!( std::fs::read_to_string(&cfg).unwrap(), r#"{"max_chain":5}"# ); ui.shutdown(); let _ = std::fs::remove_dir_all(&dir); } }