diff --git a/CHANGELOG.md b/CHANGELOG.md index 885c14334..e5db6a866 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,8 @@ What changed in each release of LLeMbas TTY. WezTerm's own changes are in to the terminal's log. - **The engine is given time.** It was stopped after 2.5 seconds, before a model on the person's own machine could be loaded for its first answer; and a request that is closed - stops the loading. Now ten seconds by default, and an option: `autocomplete_timeout_ms`. + stops the loading. Now eight seconds by default (an option: `autocomplete_timeout_ms`), and + twenty for the first request after autocomplete is switched on or its model changes. - The autocomplete model chosen in the terminal is passed to the engine with each request. - **What LLeMbas asks stands until it is answered.** The word at the cursor's row that says an approval or a question waits, with its keys, was gone after four seconds; it now stays @@ -49,6 +50,12 @@ What changed in each release of LLeMbas TTY. WezTerm's own changes are in or newer): the command is put at your prompt and not entered; a dimmed hint — *Enter runs · edit freely · Ctrl+C dismisses* — is drawn beside it, or on the empty row below, never over it, and goes when you have decided. Nothing of the hint is written to the pane. +- **The input mark.** With AI on, the terminal writes beside each pane's status record + whether anything stands on the input line of that prompt (`pane-.input`: the record's + id and seq, `typed=0` or `1` — never the text). By it LLeMbas places a command only at an + empty prompt, whatever the prompt looks like, and never adds to what you typed. +- With an engine that knows `--debug` (contract 3), *autocomplete status* also shows what + the engine said of each of its decisions at the newest attempt. ### For developers @@ -56,8 +63,9 @@ What changed in each release of LLeMbas TTY. WezTerm's own changes are in in a reported address, one request at a time, the engine's command line and its run, and the attempts in words — tested in CI with a stand-in engine that records its arguments, its input and its environment. -- `wezterm.llembas.hint`, `.complete_status`, `.data_dir`; `configure` takes `ac_model` and - `ac_timeout_ms`. +- `llembas-line` gains `mark` (the input mark's text and file). +- `wezterm.llembas.hint`, `.status`, `.complete_status`, `.data_dir`; `configure` takes + `ac_model`, `ac_timeout_ms`, `ac_debug` and `input_mark`. ## 1.0.0-beta.4 — 2026-12-02 diff --git a/README.md b/README.md index db0d4d39a..5c7eeaab5 100644 --- a/README.md +++ b/README.md @@ -146,16 +146,20 @@ in the terminal's runtime directory; LLeMbas deletes it after reading it and the terminal removes any that are left after ten minutes. **While a conversation runs**, LLeMbas can read the pane you asked from and type commands -into it, by its own permissions: in manual mode it asks for each command first. That is the -CLI's business; it never types at a password prompt. +into it, by its own permissions: in manual mode a command is placed at your prompt for you +to run, and only at an empty prompt — nothing is ever added to what you typed. That is the +CLI's business; it never types at a password prompt. So that it knows your prompt is empty +whatever your prompt looks like, the terminal writes, with AI on, a four-line *input mark* +beside each pane's status record: which prompt it is of, and whether anything stands on its +input line — never what. **AI autocomplete**, when you turned it on: the line you are typing is sent to `lembas complete` after a pause, when your own history has no suggestion for it — never an empty line, a line of fewer than three characters, a line that starts with a space, a private pane, or a shell on another machine. What comes back is shown as text; nothing runs -until you take it and press Enter. The engine is given ten seconds for an answer -(`autocomplete_timeout_ms`): a model on your own machine may have to be loaded for the first -one. The last few attempts — the start of the line, how long it took, what came back — are +until you take it and press Enter. The engine is given eight seconds for an answer +(`autocomplete_timeout_ms`), and twenty for the first one after you switch autocomplete on or +change its model: a model on your own machine may have to be loaded. The last few attempts — the start of the line, how long it took, what came back — are kept in memory for *LLeMbas: autocomplete status* and go when the terminal closes. ## Settings @@ -256,7 +260,7 @@ require('llembas').apply(config, { suggestions = true, -- the rest of the line from your own command history highlight = true, -- the command line in colours autocomplete = false, -- AI: true, drawn by the terminal; 'shell', by the shell integration - autocomplete_timeout_ms = 10000, -- how long LLeMbas is given for the rest of a line + autocomplete_timeout_ms = 8000, -- how long LLeMbas is given for the rest of a line history = { enabled = true, max = 5000 }, colors = { -- a number of your colour scheme's palette, '#rrggbb', or false prefix = 6, ghost = 8, notice = 3, diff --git a/llembas/README.md b/llembas/README.md index ed0492e03..ca98bdfb5 100644 --- a/llembas/README.md +++ b/llembas/README.md @@ -99,8 +99,9 @@ where each point is in the code (one function or constant each, in `lua/llembas/ | lists and sets the terminal's two models: `lembas terminal models --json`, `lembas terminal models set --main\|--autocomplete ` | `models_args`, `models_set_args`, `terminal_models` | keeps them | | exports `LLEMBAS_TTY` (version), `LLEMBAS_TTY_PANE`, `LLEMBAS_TTY_EXECUTABLE`, `LLEMBAS_TTY_STATUS_DIR` to every pane | Rust (identity), `apply` | types into a pane with `$LLEMBAS_TTY_EXECUTABLE cli send-text --pane-id N --no-paste`, reads it with `cli get-text` | | the shell integration writes the pane's status record at every prompt and when a command starts: `$LLEMBAS_TTY_STATUS_DIR/pane-.status` and the user variable `llembas_tty_status`; the layer writes the file from the variable for a shell that could not (`via=uservar`) | `shell/llembas-tty.sh`, `parse_status`, `status_text`, `status_dir`, `status_dir_of` | waits for it after typing a command | -| asks for the rest of a line: the line on standard input (then closed) of `lembas complete --shell --cwd --timeout-ms [--model ]`, with `LLEMBAS_TTY` set; `--cwd` is always given (the engine requires it): the pane's directory, else the home directory | `llembas_line::complete` (`args`, `run`, `decide`), `wezterm-gui/src/llembas/complete.rs` | prints only the rest; nothing means no suggestion; what it writes to standard error is the sentence shown by *autocomplete status* | -| reads and writes what the person chose (contract 3, `terminal_settings`): `lembas terminal settings --cwd --json` → `{ effective = { = }, from = { = "default" \| "global" \| "" }, directory = { path } \| null }`; `lembas terminal settings set (--global \| --cwd ) =` (`default` removes it); `lembas terminal settings forget --cwd `. Keys: `ai`, `autocomplete`, `suggestions`, `highlight` (`true`/`false`), `mode`, `main_model`, `autocomplete_model`, `display_width` (a part of the pane, `0.2` to `0.6`, written `0.40`; percent is read too) | `SETTINGS`, `settings_args`, `settings_set_args`, `settings_forget_args`, `settings_entry`, `setting_value`, `setting_text` | keeps them, for the machine and by directory | +| asks for the rest of a line: the line on standard input (then closed) of `lembas complete --shell --cwd --timeout-ms [--model ] [--debug]`, with `LLEMBAS_TTY` set; `` is 8000 (the option), and 20000 at least for the first request after a change; `--debug` only once the CLI said it has contract 3; `--cwd` is always given (the engine requires it): the pane's directory, else the home directory | `llembas_line::complete` (`args`, `run`, `decide`), `wezterm-gui/src/llembas/complete.rs` | prints only the rest; nothing means no suggestion; what it writes to standard error is the sentence shown by *autocomplete status* | +| reads and writes what the person chose (contract 3, `terminal_settings`): `lembas terminal settings --cwd --json` → `{ effective = { = }, from = { = "default" \| "global" \| "" }, directory = { path } \| null }`; `lembas terminal settings set (--global \| --cwd ) --json =` (`default` removes it); `lembas terminal settings forget --cwd --json` (the entry's own path, which may be a directory above the pane's: the nearest entry applies). Keys: `ai`, `autocomplete`, `suggestions`, `highlight` (`true`/`false`), `mode`, `main_model`, `autocomplete_model`, `display_width` (a part of the pane, `0.2` to `0.6`, written `0.40`; percent is read too) | `SETTINGS`, `settings_args`, `settings_set_args`, `settings_forget_args`, `settings_entry`, `setting_value`, `setting_text` | keeps them, for the machine and by directory | +| writes the input mark `pane-.input` beside the status record (mode 0600, written whole): `llembas-tty-input=1`, `id=`, `seq=` (the status record's), `typed=0\|1` | `llembas_line::mark`, `state::mark_input`, `decorate::compute`; the layer hands the record over with `wezterm.llembas.status` | places a command only at an empty prompt; the mark counts while its id and seq are the record's and the record is at `prompt` | | shows a hint while a command placed at the prompt waits for the person (contract 3, `terminal_placed`): `lembas_ask` = `placed ` | `PLACED_KIND`, `parse_ask`, `messages.placed` | places the command without Enter and watches the status record: a new prompt with `ran=1` is "ran", one without is "dismissed" | The status directory is `/llembas-tty/status-`: @@ -151,18 +152,25 @@ display's user variables and at `update-status`. An approval or a question may b reversed over the end of the row, as a notice is; a *gentle* hint (a placed command) is drawn only beside what the row shows or on the empty row below, and not at all otherwise. -### Whether the input at the prompt is empty +### Whether the input at the prompt is empty: the input mark The engine places a command only at an empty prompt. The shell's hook cannot say how much is -typed (it runs before the line is edited), so the status record carries no such field. What -is typed is known at one place only: the terminal's screen, where the shell integration -marks the input cells. The engine reads it there, as it reads everything of a pane -(`cli get-text`): its rule for a prompt that ends in a prompt character. The engine's -specification also names an *input mark* a terminal may write (`pane-.input`, beside the -status record). This terminal does not write one yet: what it knows of the input line it -knows when the pane is painted — a frame behind the typing, and not at all for a pane that -is not shown or an empty line (which has no input cell to find) — so a mark written from -there could say "empty" when it is not. See *Later*. +typed (it runs before the line is edited); the terminal can, because the shell integration +marks the input cells. So the terminal writes the *input mark* of the engine's specification. + +- The layer hands each status record to the terminal's own part (`wezterm.llembas.status`: + pane, id, seq, state, the status directory) — with AI on, for a local pane; otherwise it + says the pane is no longer followed, and the mark is removed. +- When a pane whose shell is at a prompt is painted (`decorate::compute`), `typed` is: an + input cell that shows something on the cursor's row; else an input zone that nothing + follows and that shows something (a line carried on over rows). The mark is written when + the record or the answer changed (`state::mark_input`), beside the record, whole. +- What it cannot be: ahead of the screen. It is as old as the last painting of the pane — a + frame behind the typing, and not kept up for a pane that is not shown. A mark of an + earlier prompt does not count (its `seq` is not the record's), and while a new prompt is + being drawn the mark errs towards `typed=1`: a command is then not placed, never added to + something typed. +- Marks of terminals that are gone are removed with their status records. ## What the terminal draws on the input line @@ -271,12 +279,5 @@ API the layer calls (`pane:get_semantic_zones`, `get_text_from_semantic_zone`, - **The shell's aliases and functions** are not known to the terminal, so a command that is one is not marked as existing (and `colors.unknown` is off by default for that reason). The shell integration could publish their names. -- **The input mark** (the engine's `pane-.input`: whether anything stands on the input line - at this prompt). To write it truthfully the terminal has to tell an empty input line from - one it cannot see: `llembas_line::zone` would say why it found no line (no input cell at a - prompt the status record vouches for is "empty"; too long, or a program in the pane, is - "unknown" — then no mark), the layer would hand the status record's `id` and `seq` to the - terminal's own part, and the mark would be written when the answer changes. It stays a - frame behind the typing. - **Context file version 2** (`blocks[].seq`, `host`): the terminal would keep the status record's `seq` with each command it saw. diff --git a/llembas/line/src/complete.rs b/llembas/line/src/complete.rs index 9b9c8e393..01a15852a 100644 --- a/llembas/line/src/complete.rs +++ b/llembas/line/src/complete.rs @@ -25,7 +25,13 @@ pub const MAX_BYTES: usize = 2000; /// How long the engine is given for an answer when nothing else is said. A /// model that runs on the person's own machine may have to be loaded for the /// first answer, and an engine that is stopped before that never loads it. -pub const TIMEOUT_MS_DEFAULT: u64 = 10_000; +pub const TIMEOUT_MS_DEFAULT: u64 = 8_000; +/// What the first request gets after autocomplete was switched on or its +/// model changed: the model may not be loaded yet. +pub const TIMEOUT_MS_COLD: u64 = 20_000; +/// What the engine starts a line with that says one of its decisions +/// (`--debug`): lengths and names, never the line. +pub const DEBUG_PREFIX: &str = "lembas complete: debug: "; pub const TIMEOUT_MS_MIN: u64 = 500; /// The most the engine itself accepts. pub const TIMEOUT_MS_MAX: u64 = 30_000; @@ -45,6 +51,16 @@ pub fn clamp_timeout(ms: u64) -> u64 { } } +/// The timeout of one request: the first after a change is given longer. +pub fn timeout_for(ms: u64, cold: bool) -> u64 { + let timeout = clamp_timeout(ms); + if cold { + timeout.max(TIMEOUT_MS_COLD) + } else { + timeout + } +} + /// Why LLeMbas is not asked about a line. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Skip { @@ -266,6 +282,9 @@ pub struct Request { pub timeout_ms: u64, /// The terminal's version, as the engine's environment says it (`LLEMBAS_TTY`). pub version: String, + /// Ask the engine to say each of its decisions (`--debug`): only of an + /// engine that knows the option. + pub debug: bool, } /// THE command line of a completion, in one place: what follows the CLI's path. @@ -283,6 +302,9 @@ pub fn args(req: &Request) -> Vec { args.push("--model".to_string()); args.push(req.model.clone()); } + if req.debug { + args.push("--debug".to_string()); + } args } @@ -365,6 +387,18 @@ fn read_some(source: Option) -> std::sync::mpsc::Rec /// the engine writes to its standard error is kept: it is the sentence that /// says why there is no suggestion. pub fn run(req: &Request, wanted: &dyn Fn() -> bool) -> Outcome { + run_said(req, wanted).0 +} + +/// [`run`], and with it what the engine said of its decisions (`--debug`), +/// a line each, for the person. +pub fn run_said(req: &Request, wanted: &dyn Fn() -> bool) -> (Outcome, Vec) { + let mut decisions = Vec::new(); + let outcome = run_inner(req, wanted, &mut decisions); + (outcome, decisions) +} + +fn run_inner(req: &Request, wanted: &dyn Fn() -> bool, decisions: &mut Vec) -> Outcome { let timeout = clamp_timeout(req.timeout_ms); let mut command = Command::new(&req.cli); command @@ -409,7 +443,23 @@ pub fn run(req: &Request, wanted: &dyn Fn() -> bool) -> Outcome { }; let wait = Duration::from_millis(500); let answer = stdout.recv_timeout(wait).unwrap_or_default(); - let said = shorten(&stderr.recv_timeout(wait).unwrap_or_default(), 200); + // The engine's decisions apart from its sentence: the first line that + // is not one of them. + let mut said = String::new(); + for line in stderr.recv_timeout(wait).unwrap_or_default().lines() { + match line.strip_prefix(DEBUG_PREFIX) { + Some(decision) => { + if decisions.len() < 16 { + decisions.push(shorten(decision, 160)); + } + } + None => { + if said.is_empty() { + said = shorten(line, 200); + } + } + } + } if !status.success() { return Outcome::Failed(if said.is_empty() { match status.code() { @@ -439,6 +489,8 @@ pub struct Attempt { /// The last few attempts, and the last reason nothing was asked. #[derive(Debug, Default)] pub struct Log { + /// What the engine said of its decisions at the newest attempt. + decisions: Vec, attempts: VecDeque, skipped: Option<(SystemTime, Skip)>, } @@ -467,6 +519,11 @@ impl Log { }); } + /// What the engine said of its decisions at the attempt just kept. + pub fn decisions(&mut self, lines: Vec) { + self.decisions = lines; + } + pub fn skip(&mut self, at: SystemTime, why: Skip) { self.skipped = Some((at, why)); } @@ -513,6 +570,12 @@ impl Log { )); } } + if !self.decisions.is_empty() { + lines.push("the engine, at the newest of them:".to_string()); + for d in &self.decisions { + lines.push(format!(" {}", d)); + } + } if let Some((at, why)) = &self.skipped { lines.push(format!( "last not asked {}: {}", @@ -680,6 +743,7 @@ mod tests { model: String::new(), timeout_ms: 0, version: "1.2.3".to_string(), + debug: false, } } @@ -695,7 +759,7 @@ mod tests { "--cwd", "/home/person/my project", "--timeout-ms", - "10000" + "8000" ] ); req.model = "local/fast".to_string(); @@ -703,7 +767,13 @@ mod tests { let a = args(&req); assert_eq!(a[a.len() - 2..], ["--model", "local/fast"]); assert_eq!(a[6], "30000", "no more than the engine takes"); + req.debug = true; + assert_eq!(args(&req).last().map(|s| s.as_str()), Some("--debug")); assert_eq!(clamp_timeout(1), TIMEOUT_MS_MIN); + // the first request after a change is given longer + assert_eq!(timeout_for(0, false), 8000); + assert_eq!(timeout_for(0, true), 20_000); + assert_eq!(timeout_for(25_000, true), 25_000); assert_eq!(clamp_timeout(4000), 4000); } @@ -865,6 +935,33 @@ mod tests { assert_eq!(run(&req, &twice), Outcome::Cancelled); assert!(started.elapsed() < Duration::from_secs(2)); + // 7. An engine asked to say its decisions: they are kept apart from + // its sentence. + let talking = stand_in( + "lembas-talks", + "cat > /dev/null\necho 'lembas complete: debug: shell bash, cwd /x, timeout 8000 ms' >&2\n\ + echo 'lembas complete: debug: not logged in, no request' >&2\n\ + echo 'lembas complete: not logged in' >&2\nexit 1", + ); + let mut req = request(&cli(&talking)); + req.debug = true; + let (outcome, decisions) = run_said(&req, &always); + assert_eq!( + outcome, + Outcome::Failed("lembas complete: not logged in".to_string()) + ); + assert_eq!(decisions.len(), 2); + assert_eq!(decisions[0], "shell bash, cwd /x, timeout 8000 ms"); + let mut log = Log::default(); + log.attempt(SystemTime::now(), "git che", 30, outcome); + log.decisions(decisions); + let status = log.status(SystemTime::now(), "/x/lembas", "", 0); + assert!( + status.contains(" shell bash, cwd /x, timeout 8000 ms"), + "{}", + status + ); + // 6. What a model says is text: one plain line of it is offered. let hostile = stand_in( "lembas-hostile", diff --git a/llembas/line/src/lib.rs b/llembas/line/src/lib.rs index 7c426974b..639e503d1 100644 --- a/llembas/line/src/lib.rs +++ b/llembas/line/src/lib.rs @@ -4,6 +4,7 @@ //! - [`editor`]: the ask line's own small line editor, and how it fits a row. //! - [`zone`]: the shell's input line, read from the cells of the screen. //! - [`history`]: the terminal's own history of commands it saw run. +//! - [`mark`]: the input mark, by which LLeMbas knows a prompt is empty. //! - [`suggest`]: what is offered after the cursor, and how much a key takes. //! - [`tokens`]: the parts of a shell command line, for its colours. //! - [`complete`]: asking LLeMbas for the rest of a line - whether to, how the @@ -16,6 +17,7 @@ pub mod complete; pub mod editor; pub mod history; +pub mod mark; pub mod suggest; pub mod tokens; pub mod zone; diff --git a/llembas/line/src/mark.rs b/llembas/line/src/mark.rs new file mode 100644 index 000000000..445ed0b00 --- /dev/null +++ b/llembas/line/src/mark.rs @@ -0,0 +1,148 @@ +//! The input mark: whether anything stands on the input line of a pane's +//! prompt, written by the terminal for LLeMbas, which places a command only +//! at an empty prompt (the engine's specification, *A command placed at the +//! prompt*). +//! +//! A small file beside the pane's status record, the person's alone, written +//! whole: +//! +//! ```text +//! llembas-tty-input=1 +//! id= +//! seq= +//! typed=0 | 1 +//! ``` +//! +//! It counts only while `id` and `seq` are those of the pane's status record +//! and that record is at a prompt, so a mark that was not kept up says +//! nothing rather than something wrong. + +use std::io::Write; +use std::path::{Path, PathBuf}; + +pub const MAGIC: &str = "llembas-tty-input=1"; + +/// The mark's file for a pane, in the directory of the status records. +pub fn path(dir: &Path, pane: usize) -> PathBuf { + dir.join(format!("pane-{}.input", pane)) +} + +/// Is this the id of a status record? 1 to 64 letters, digits, `.`, `_`, +/// `:` or `-`. Anything else is never written into a file. +pub fn valid_id(id: &str) -> bool { + !id.is_empty() + && id.len() <= 64 + && id + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | ':' | '-')) +} + +/// The mark as it is written; `None` for an id that is none. +pub fn text(id: &str, seq: u64, typed: bool) -> Option { + if !valid_id(id) { + return None; + } + Some(format!( + "{}\nid={}\nseq={}\ntyped={}\n", + MAGIC, + id, + seq, + if typed { 1 } else { 0 } + )) +} + +/// Write the mark of a pane: beside the file, closed to everybody else, then +/// moved over it, so that a reader sees the old mark or the new one. +pub fn write(dir: &Path, pane: usize, id: &str, seq: u64, typed: bool) -> std::io::Result<()> { + let text = text(id, seq, typed).ok_or_else(|| { + std::io::Error::new(std::io::ErrorKind::InvalidInput, "not a status record's id") + })?; + let path = path(dir, pane); + let tmp = dir.join(format!("pane-{}.input.{}", pane, std::process::id())); + let mut options = std::fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let written = options + .open(&tmp) + .and_then(|mut file| file.write_all(text.as_bytes())) + .and_then(|_| std::fs::rename(&tmp, &path)); + if written.is_err() { + let _ = std::fs::remove_file(&tmp); + } + written +} + +/// Take a pane's mark away. That there is none is no error. +pub fn remove(dir: &Path, pane: usize) -> std::io::Result<()> { + match std::fs::remove_file(path(dir, pane)) { + Err(err) if err.kind() != std::io::ErrorKind::NotFound => Err(err), + _ => Ok(()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_mark_as_written() { + assert_eq!( + text("4242.1700000000", 17, false).unwrap(), + "llembas-tty-input=1\nid=4242.1700000000\nseq=17\ntyped=0\n" + ); + assert!(text("4242.1700000000", 18, true) + .unwrap() + .ends_with("seq=18\ntyped=1\n")); + assert_eq!(text("", 1, false), None); + assert_eq!(text("a\nseq=9", 1, false), None, "one fact a line"); + assert_eq!(text("a b", 1, false), None); + assert!(valid_id("host-1:2_3.4")); + assert!(!valid_id(&"x".repeat(65))); + assert_eq!( + path(Path::new("/run/t/status-1"), 12), + PathBuf::from("/run/t/status-1/pane-12.input") + ); + } + + #[test] + fn the_mark_in_its_file() { + let dir = std::env::temp_dir().join(format!( + "llembas-line-mark-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0) + )); + std::fs::create_dir_all(&dir).unwrap(); + write(&dir, 3, "77.5", 4, true).unwrap(); + let file = path(&dir, 3); + assert_eq!( + std::fs::read_to_string(&file).unwrap(), + "llembas-tty-input=1\nid=77.5\nseq=4\ntyped=1\n" + ); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(&file).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o600, "the person's alone"); + } + // written whole again, and nothing is left beside it + write(&dir, 3, "77.5", 5, false).unwrap(); + assert!(std::fs::read_to_string(&file) + .unwrap() + .ends_with("seq=5\ntyped=0\n")); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1); + assert!(write(&dir, 3, "not an id", 5, false).is_err()); + remove(&dir, 3).unwrap(); + assert!(!file.exists()); + remove(&dir, 3).unwrap(); + // a directory that is not there: an error, and nothing is made + assert!(write(&dir.join("gone"), 1, "a", 1, false).is_err()); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/llembas/line/src/zone.rs b/llembas/line/src/zone.rs index 796b6f2fa..4b32baccb 100644 --- a/llembas/line/src/zone.rs +++ b/llembas/line/src/zone.rs @@ -113,6 +113,13 @@ fn extend_run(row: &[Cell], k: usize) -> (usize, usize) { (from, to) } +/// Does a row hold input that shows something? (An input cell that is blank +/// does not count: a line that was typed and wiped is empty.) +pub fn row_has_input(row: &Row) -> bool { + row.iter() + .any(|cell| cell.input && !cell.text.trim().is_empty()) +} + /// Find the input line the cursor is on. /// /// - `rows`: some rows of the screen, top to bottom, among them the cursor's; @@ -228,6 +235,17 @@ mod tests { cells } + #[test] + fn whether_a_row_holds_input() { + assert!(row_has_input(&row("$ git st", "ppiiiiii"))); + assert!(!row_has_input(&row("$ ", "pp")), "an empty prompt"); + assert!( + !row_has_input(&row("$ ", "ppiii")), + "typed and wiped: blank input cells are no input" + ); + assert!(!row_has_input(&Vec::new())); + } + #[test] fn the_line_after_the_prompt() { let rows = vec![row("$ git st", "ppiiiiii")]; diff --git a/llembas/lua/llembas/core.lua b/llembas/lua/llembas/core.lua index ce0da4676..8d63f90d3 100644 --- a/llembas/lua/llembas/core.lua +++ b/llembas/lua/llembas/core.lua @@ -142,9 +142,10 @@ function M.defaults() -- terminal like every suggestion. 'shell': by the shell integration instead (zsh draws -- it itself, bash completes on Ctrl+X Ctrl+A), as before the terminal drew its own. autocomplete = false, - -- How long LLeMbas is given for the rest of a line, in milliseconds (500 to 30000). A - -- model on your own machine may have to be loaded for its first answer. - autocomplete_timeout_ms = 10000, + -- How long LLeMbas is given for the rest of a line, in milliseconds (500 to 30000). The + -- first request after autocomplete is switched on or its model changes is given 20000 + -- at least: a model on your own machine may have to be loaded for its first answer. + autocomplete_timeout_ms = 8000, -- The terminal's own history of commands it saw run, for the suggestions. history = { enabled = true, @@ -1360,12 +1361,13 @@ function M.settings_set_args(cli, level, cwd, key, value) else args[#args + 1] = '--global' end + args[#args + 1] = '--json' args[#args + 1] = key .. '=' .. text return args end function M.settings_forget_args(cli, cwd) - return { cli, 'terminal', 'settings', 'forget', '--cwd', cwd } + return { cli, 'terminal', 'settings', 'forget', '--cwd', cwd, '--json' } end -- What `lembas terminal settings --cwd --json` printed, decoded, as the diff --git a/llembas/lua/llembas/init.lua b/llembas/lua/llembas/init.lua index 83c252ba8..fe9f2035e 100644 --- a/llembas/lua/llembas/init.lua +++ b/llembas/lua/llembas/init.lua @@ -226,6 +226,14 @@ local function key_name(name, palette_name) return '"' .. palette_name .. '" in the command palette' end +-- Does the CLI found say its decisions when asked (`lembas complete --debug`, +-- with contract 3)? From what it already said of itself: nothing is started. +function M.engine_explains() + local cli = M.find_cli() + local cached = cli and global('cli_info')['c:' .. cli] + return cached ~= nil and cached.known == true and type(cached.contract) == 'number' and cached.contract >= 3 +end + -- Tell the terminal's own part what is on. Called when the layer is applied -- and whenever a switch moves. local function push_native() @@ -243,6 +251,12 @@ local function push_native() -- the autocomplete model chosen in the terminal; '' leaves it to the engine ac_model = M.value 'autocomplete_model' or '', ac_timeout_ms = opts.autocomplete_timeout_ms, + -- an engine of contract 3 says each of its decisions when asked (--debug); + -- known only once the CLI was asked what it can do, which is never done here + ac_debug = M.engine_explains(), + -- the input mark of each pane whose shell reports where it stands: by it + -- LLeMbas knows that a prompt is empty before it places a command there + input_mark = ai, history = opts.history.enabled, history_max = opts.history.max, colors = opts.colors, @@ -701,7 +715,8 @@ sweep_status = function() elseif io.open('/proc/self/stat', 'r') then local ok2, files = pcall(wezterm.read_dir, dir) for _, f in ipairs(ok2 and type(files) == 'table' and files or {}) do - if (f:match('([^/]+)$') or ''):match('^pane%-%d+%.status') then + local name = f:match('([^/]+)$') or '' + if name:match('^pane%-%d+%.status') or name:match('^pane%-%d+%.input') then os.remove(f) end end @@ -1515,6 +1530,17 @@ local function status_changed(window, pane, value) end -- where this shell stands, for a hint that belongs to one prompt global('status_at')[pane_key(pane:pane_id())] = string.format('%s:%d:%s', rec.id, rec.seq, rec.state) + -- and for the terminal's own part, which writes the pane's input mark + -- beside the status record. Only with AI on: its one reader is LLeMbas. + local n0 = native() + if n0 and n0.status then + local dir = M.is_on 'ai' and is_local(pane) and status_dir() or nil + if dir then + pcall(n0.status, pane:pane_id(), rec.id, rec.seq, rec.state, dir) + else + pcall(n0.status, pane:pane_id(), nil) + end + end sync_hint(window, pane) -- a new prompt of the pane the person is in: its directory may be another if rec.state == 'prompt' then diff --git a/llembas/tests/fake_wezterm.lua b/llembas/tests/fake_wezterm.lua index 7690b7624..9108de758 100644 --- a/llembas/tests/fake_wezterm.lua +++ b/llembas/tests/fake_wezterm.lua @@ -101,7 +101,7 @@ end -- The terminal's own part (`wezterm.llembas`), recording what it is asked. function F.native() local n = { calls = {} } - for _, name in ipairs { 'ask_line', 'configure', 'notice', 'hint', 'set_private', 'command_ended', 'clear_history' } do + for _, name in ipairs { 'ask_line', 'configure', 'notice', 'hint', 'status', 'set_private', 'command_ended', 'clear_history' } do n[name] = function(...) n.calls[#n.calls + 1] = { name, ... } return true diff --git a/llembas/tests/run.lua b/llembas/tests/run.lua index df4ec8a42..eaa694ff4 100644 --- a/llembas/tests/run.lua +++ b/llembas/tests/run.lua @@ -1494,13 +1494,13 @@ test('settings: what the store says, as the layer keeps it', function() eq(core.setting_line('ai', true, 'global'), 'AI: on · everywhere', 'for the machine') -- the commands eq(table.concat(core.settings_args('lembas', '/d'), ' '), 'lembas terminal settings --cwd /d --json', 'read') - eq(table.concat(core.settings_set_args('lembas', 'here', '/d', 'mode', 'auto'), ' '), 'lembas terminal settings set --cwd /d mode=auto', 'for the directory') - eq(table.concat(core.settings_set_args('lembas', 'everywhere', '/d', 'ai', false), ' '), 'lembas terminal settings set --global ai=false', 'for the machine') - eq(table.concat(core.settings_set_args('lembas', 'everywhere', nil, 'mode', nil), ' '), 'lembas terminal settings set --global mode=default', 'removed') + eq(table.concat(core.settings_set_args('lembas', 'here', '/d', 'mode', 'auto'), ' '), 'lembas terminal settings set --cwd /d --json mode=auto', 'for the directory') + eq(table.concat(core.settings_set_args('lembas', 'everywhere', '/d', 'ai', false), ' '), 'lembas terminal settings set --global --json ai=false', 'for the machine') + eq(table.concat(core.settings_set_args('lembas', 'everywhere', nil, 'mode', nil), ' '), 'lembas terminal settings set --global --json mode=default', 'removed') eq(core.settings_set_args('lembas', 'here', nil, 'mode', 'auto'), nil, 'no directory: nothing to run') eq(core.settings_set_args('lembas', 'here', '/d', 'mode', 'edit'), nil, 'not a value: nothing to run') eq(core.settings_set_args('lembas', 'here', '/d', 'nonsense', 'x'), nil, 'not a setting') - eq(table.concat(core.settings_forget_args('lembas', '/d'), ' '), 'lembas terminal settings forget --cwd /d', 'forget') + eq(table.concat(core.settings_forget_args('lembas', '/d'), ' '), 'lembas terminal settings forget --cwd /d --json', 'forget') -- the capability: named, and of contract 3 check(core.cli_has(core.cli_info(JSON['INFO3']), 'settings'), 'a CLI with the store') check(core.cli_has(core.cli_info(JSON['INFO3']), 'placed'), 'and with placing') @@ -1538,7 +1538,9 @@ test('settings: nothing is read until the first key of LLeMbas', function() eq(c.suggestions, false, 'the terminal is told') eq(c.ai_complete, true, 'what completes') eq(c.ac_model, 'open/flash', 'and with which model') - eq(c.ac_timeout_ms, 10000, 'and how long the engine is given') + eq(c.ac_timeout_ms, 8000, 'and how long the engine is given') + eq(c.ac_debug, true, 'an engine of contract 3 is asked to say its decisions') + eq(c.input_mark, true, 'and the input mark is written') local mode, from, path = l.value 'mode' eq(mode .. ' ' .. from .. ' ' .. path, 'auto directory /home/u/proj', 'a value, and where it comes from') -- looked at again and again: read once while it is fresh @@ -1609,12 +1611,12 @@ test('settings: a choice is kept, here or everywhere', function() native.dir = dir .. '/run' local l, w, r = store_layer({ ['terminal settings --cwd /home/u/other --json'] = { true, 'S_OTHER' }, - ['terminal settings set --global suggestions=false'] = { true, '' }, - ['terminal settings set --cwd /home/u/other highlight=false'] = { true, '' }, - ['terminal settings set --cwd /home/u/other mode=auto'] = { true, '' }, - ['terminal settings set --cwd /home/u/other autocomplete_model=open/flash'] = { true, '' }, - ['terminal settings set --global display_width=0.50'] = { true, '' }, - ['terminal settings forget --cwd /home/u/other'] = { true, '' }, + ['terminal settings set --global --json suggestions=false'] = { true, '' }, + ['terminal settings set --cwd /home/u/other --json highlight=false'] = { true, '' }, + ['terminal settings set --cwd /home/u/other --json mode=auto'] = { true, '' }, + ['terminal settings set --cwd /home/u/other --json autocomplete_model=open/flash'] = { true, '' }, + ['terminal settings set --global --json display_width=0.50'] = { true, '' }, + ['terminal settings forget --cwd /home/u/other --json'] = { true, '' }, }, native) local win = fake.window() local pane = fake.pane { id = 1, cwd = 'file:///home/u/other' } @@ -1622,7 +1624,7 @@ test('settings: a choice is kept, here or everywhere', function() win.active = pane -- the key (no level said): this directory has nothing of its own, so for the machine w.emit('llembas-suggestions', win, pane) - eq(spawned(w, 'terminal settings set --global suggestions=false'), 1, 'kept for the machine') + eq(spawned(w, 'terminal settings set --global --json suggestions=false'), 1, 'kept for the machine') eq(native.last 'notice'[3], 'suggestions off · everywhere', 'and said where') check(io.open(dir .. '/run/settings-chosen', 'r') ~= nil, 'from now on the settings are read at the first prompt') eq(spawned(w, 'terminal settings --cwd /home/u/other --json'), 2, 'read again after our own writing') @@ -1634,17 +1636,17 @@ test('settings: a choice is kept, here or everywhere', function() } r['terminal settings --cwd /home/u/other --json'] = { true, 'S_OTHER2' } w.emit('llembas-highlight-here', win, pane) - eq(spawned(w, 'terminal settings set --cwd /home/u/other highlight=false'), 1, 'kept for the directory') + eq(spawned(w, 'terminal settings set --cwd /home/u/other --json highlight=false'), 1, 'kept for the directory') eq(native.last 'notice'[3], 'syntax highlighting off · here', 'said') eq(l.is_on 'highlight', false, 'and it applies') eq(native.last 'configure'[2].highlight, false, 'the terminal is told') -- now the directory has settings of its own: the key keeps the next choice there w.emit('llembas-mode-pick', win, pane, 'auto') - eq(spawned(w, 'terminal settings set --cwd /home/u/other mode=auto'), 1, 'the key follows where the directory already is') + eq(spawned(w, 'terminal settings set --cwd /home/u/other --json mode=auto'), 1, 'the key follows where the directory already is') eq(native.last 'notice'[3], 'mode: auto · here', 'said') -- a model: kept in the store, not by the older command w.emit('llembas-autocomplete-model-pick-here', win, pane, 'open/flash') - eq(spawned(w, 'terminal settings set --cwd /home/u/other autocomplete_model=open/flash'), 1, 'the autocomplete model, for the directory') + eq(spawned(w, 'terminal settings set --cwd /home/u/other --json autocomplete_model=open/flash'), 1, 'the autocomplete model, for the directory') eq(spawned(w, 'terminal models set --autocomplete open/flash'), 0, 'not kept twice') -- the width of the display w.emit('llembas-width-everywhere', win, pane) @@ -1652,9 +1654,9 @@ test('settings: a choice is kept, here or everywhere', function() eq(a.action, 'InputSelector', 'a list of widths') eq(a.args.action.args, 'llembas-width-pick-everywhere', 'the pick says where') w.emit('llembas-width-pick-everywhere', win, pane, '0.50') - eq(spawned(w, 'terminal settings set --global display_width=0.50'), 1, 'kept') + eq(spawned(w, 'terminal settings set --global --json display_width=0.50'), 1, 'kept') w.emit('llembas-width-pick-everywhere', win, pane, '7') - eq(spawned(w, 'terminal settings set --global display_width=7.00'), 0, 'only a width the display can have') + eq(spawned(w, 'terminal settings set --global --json display_width=7.00'), 0, 'only a width the display can have') -- the list: what applies, where it comes from, and forgetting the directory's own w.emit('llembas-settings', win, pane) local list = win.actions[#win.actions].action.args @@ -1670,10 +1672,10 @@ test('settings: a choice is kept, here or everywhere', function() check(all:find("Forget this directory's own settings", 1, true), 'forget') r['terminal settings --cwd /home/u/other --json'] = { true, 'S_OTHER' } w.emit('llembas-settings-pick', win, pane, 'forget') - eq(spawned(w, 'terminal settings forget --cwd /home/u/other'), 1, 'forgotten') + eq(spawned(w, 'terminal settings forget --cwd /home/u/other --json'), 1, 'forgotten') eq(l.is_on 'highlight', true, 'and the machine\'s apply again') w.emit('llembas-settings-pick', win, pane, 'forget') - eq(spawned(w, 'terminal settings forget --cwd /home/u/other'), 1, 'nothing left to forget') + eq(spawned(w, 'terminal settings forget --cwd /home/u/other --json'), 1, 'nothing left to forget') -- settings kept for a directory above this one apply here: a key joins them there, -- and forgetting names that directory JSON['S_SUB'] = { @@ -1682,19 +1684,19 @@ test('settings: a choice is kept, here or everywhere', function() directory = { path = '/home/u/other' }, } r['terminal settings --cwd /home/u/other/src --json'] = { true, 'S_SUB' } - r['terminal settings set --cwd /home/u/other suggestions=false'] = { true, '' } - r['terminal settings forget --cwd /home/u/other'] = { true, '' } + r['terminal settings set --cwd /home/u/other --json suggestions=false'] = { true, '' } + r['terminal settings forget --cwd /home/u/other --json'] = { true, '' } local sub = fake.pane { id = 4, cwd = 'file:///home/u/other/src' } fake.tab { sub } win.active = sub w.emit('llembas-suggestions', win, sub) - eq(spawned(w, 'terminal settings set --cwd /home/u/other suggestions=false'), 1, 'kept where the applying settings are') + eq(spawned(w, 'terminal settings set --cwd /home/u/other --json suggestions=false'), 1, 'kept where the applying settings are') w.emit('llembas-settings-pick', win, sub, 'forget') - eq(spawned(w, 'terminal settings forget --cwd /home/u/other'), 2, 'the entry itself is forgotten') + eq(spawned(w, 'terminal settings forget --cwd /home/u/other --json'), 2, 'the entry itself is forgotten') win.active = pane w.emit('llembas-settings-pick', win, pane, 'k:mode') w.emit('llembas-settings-pick', win, pane, nil) - eq(spawned(w, 'terminal settings forget --cwd /home/u/other'), 2, 'any other line does nothing') + eq(spawned(w, 'terminal settings forget --cwd /home/u/other --json'), 2, 'any other line does nothing') -- the store refuses: the choice holds for this run, and that is said w.emit('llembas-ai-everywhere', win, pane) eq(l.is_on 'ai', false, 'it holds') @@ -1982,6 +1984,33 @@ test('status records of terminals that are gone are removed when a display start env.XDG_RUNTIME_DIR = false end) +test('status record: the terminal is told where a shell stands, for the input mark', function() + local dir = fresh_dir 'mark' + with_cli(dir) + local native = fake.native() + local _, w = new_layer { native = native } + local win, pane = fake.window(), fake.pane { id = 4 } + fake.tab { pane } + win.active = pane + eq(native.last 'configure'[2].input_mark, true, 'with AI on the mark is written') + eq(native.last 'configure'[2].ac_debug, false, 'the engine was not asked what it can do: nothing assumed') + w.emit('user-var-changed', win, pane, 'llembas_tty_status', 'llembas-tty-status=1\nid=9.1\nseq=6\nstate=prompt\n') + local call = native.last 'status' + eq(call[2], 4, 'the pane') + eq(call[3] .. ' ' .. call[4] .. ' ' .. call[5], '9.1 6 prompt', "the record's id, seq and state") + check(call[6]:sub(1, 1) == '/', 'and where the records are kept') + -- a pane of another machine's domain, or AI off: no longer followed + local far = fake.pane { id = 5, domain = 'SSH:far' } + fake.tab { far } + w.emit('user-var-changed', win, far, 'llembas_tty_status', 'llembas-tty-status=1\nid=9.2\nseq=1\nstate=prompt\n') + eq(native.last 'status'[2], 5, 'said of that pane') + eq(native.last 'status'[3], nil, 'that it is not followed') + w.emit('llembas-ai', win, pane) + eq(native.last 'configure'[2].input_mark, false, 'AI off: no mark') + w.emit('user-var-changed', win, pane, 'llembas_tty_status', 'llembas-tty-status=1\nid=9.1\nseq=7\nstate=prompt\n') + eq(native.last 'status'[3], nil, 'and the pane is let go') +end) + test('status record: private panes, AI off, history off', function() local dir = fresh_dir 'status2' env.LLEMBAS_TTY_STATUS_DIR = dir .. '/run' diff --git a/llembas/tests/smoke.sh b/llembas/tests/smoke.sh index 92f134f28..97682206a 100755 --- a/llembas/tests/smoke.sh +++ b/llembas/tests/smoke.sh @@ -110,12 +110,12 @@ local config = wezterm.config_builder() local n = wezterm.llembas local out = { 'module=' .. type(n) } if type(n) == 'table' then - for _, name in ipairs { 'ask_line', 'configure', 'notice', 'hint', 'complete_status', 'data_dir', 'set_private', 'command_ended', 'clear_history' } do + for _, name in ipairs { 'ask_line', 'configure', 'notice', 'hint', 'status', 'complete_status', 'data_dir', 'set_private', 'command_ended', 'clear_history' } do out[#out + 1] = name .. '=' .. type(n[name]) end local ok, err = pcall(n.configure, { suggestions = true, highlight = true, ai_complete = false, cli = '/opt/x/lembas', ac_model = 'local/fast', - ac_timeout_ms = 4000, history = true, history_max = 10, + ac_timeout_ms = 4000, ac_debug = true, input_mark = true, history = true, history_max = 10, colors = { ghost = 8, command = '#00ff00', unknown = false }, }) out[#out + 1] = 'configure=' .. tostring(ok) .. (ok and '' or (' ' .. tostring(err))) @@ -125,6 +125,9 @@ if type(n) == 'table' then local ok3, err3 = pcall(function() n.hint(3, 'Enter runs', true, 4) n.hint(3, nil) + -- where a pane's shell stands, and that it is no longer followed + n.status(3, '77.5', 4, 'prompt', wezterm.home_dir) + n.status(3, nil) end) out[#out + 1] = 'hint=' .. tostring(ok3) .. (ok3 and '' or (' ' .. tostring(err3))) local ok4, status = pcall(n.complete_status) @@ -133,6 +136,7 @@ if type(n) == 'table' then and status:find('model: local/fast', 1, true) ~= nil and status:find('given 4000 ms', 1, true) ~= nil and status:find('AI autocomplete (or AI) is off', 1, true) ~= nil + and status:find('the next request is given 20000 ms', 1, true) ~= nil and status:find('not yet', 1, true) ~= nil) local ok5, dir = pcall(n.data_dir) out[#out + 1] = 'data_dir=' .. tostring(ok5 and type(dir) == 'string' and dir:sub(1, 1) == '/') @@ -145,7 +149,7 @@ return config LUA native_keys="$(clean "$TTY" show-keys --lua 2>"$work/keys-err.txt")" native="$(cat "$work/home/native.txt" 2>/dev/null)" - expect "wezterm.llembas is there, with every function the layer uses" "$native" '^module=table ask_line=function configure=function notice=function hint=function complete_status=function data_dir=function set_private=function command_ended=function clear_history=function configure=true set_private=true hint=true status=true data_dir=true$' + expect "wezterm.llembas is there, with every function the layer uses" "$native" '^module=table ask_line=function configure=function notice=function hint=function status=function complete_status=function data_dir=function set_private=function command_ended=function clear_history=function configure=true set_private=true hint=true status=true data_dir=true$' expect "the layer applies over it" "$native_keys" "llembas-ask" if [ -e "$work/home/.local/share/llembas-tty/command-history" ]; then bad "a command history was written though no command ran"; else ok "no command history is written before a command ran"; fi else diff --git a/wezterm-gui/src/llembas/complete.rs b/wezterm-gui/src/llembas/complete.rs index 06ff346d8..dc280e298 100644 --- a/wezterm-gui/src/llembas/complete.rs +++ b/wezterm-gui/src/llembas/complete.rs @@ -15,6 +15,7 @@ use llembas_line::complete::{self, Log, Outcome, Poll, Request, Skip, Tracker}; use mux::pane::{CachePolicy, Pane, PaneId}; use mux::{Mux, MuxNotification}; use parking_lot::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::time::{Duration, Instant, SystemTime}; @@ -24,6 +25,10 @@ lazy_static::lazy_static! { static ref LOG: Mutex = Mutex::new(Log::default()); } +/// The next request is the first after autocomplete was switched on or its +/// model changed: it is given longer. +static COLD: AtomicBool = AtomicBool::new(true); + /// The shell of a pane by its name, as `lembas complete --shell` takes it. fn shell_of(pane: &Arc) -> &'static str { let name = pane @@ -51,7 +56,7 @@ fn ask(id: u64, pane_id: PaneId, req: Request) { } let at = SystemTime::now(); let started = Instant::now(); - let outcome = complete::run(&req, &|| still_wanted(id)); + let (outcome, decisions) = complete::run_said(&req, &|| still_wanted(id)); let took = started.elapsed().as_millis() as u64; if outcome == Outcome::Cancelled { // the person typed on: the newer line is asked about instead @@ -72,8 +77,16 @@ fn ask(id: u64, pane_id: PaneId, req: Request) { } other => log::warn!("LLeMbas autocomplete ({}): {}", req.cli, other.sentence()), } + if matches!(outcome, Outcome::Suggestion(_) | Outcome::Nothing(_)) { + // the engine answered: the model is there + COLD.store(false, Ordering::Relaxed); + } let rest = outcome.rest(); - LOG.lock().attempt(at, &req.line, took, outcome); + { + let mut log = LOG.lock(); + log.attempt(at, &req.line, took, outcome); + log.decisions(decisions); + } TRACKER.lock().finish(id, pane_id, req.line, rest); state::changed(); Mux::notify_from_any_thread(MuxNotification::PaneOutput(pane_id)); @@ -92,8 +105,11 @@ pub fn skipped(why: Skip) { /// What is on changed (the model, the directory's settings): a line that was /// answered may be asked about again. -pub fn forget_answers() { +pub fn forget_answers(cold: bool) { TRACKER.lock().forget(); + if cold { + COLD.store(true, Ordering::Relaxed); + } } /// The terminal's side of the autocomplete in words, for the person. @@ -105,6 +121,12 @@ pub fn status() -> String { &options.ac_model, options.ac_timeout_ms, ); + if COLD.load(Ordering::Relaxed) { + text.push_str(&format!( + "\nthe next request is given {} ms: the first after a change, for a model that may have to be loaded", + complete::timeout_for(options.ac_timeout_ms, true) + )); + } if !options.ai_complete { text = format!( "The terminal is not asking now: AI autocomplete (or AI) is off.\n{}", @@ -136,8 +158,9 @@ pub fn suggestion( cwd, line: typed.to_string(), model: options.ac_model.clone(), - timeout_ms: options.ac_timeout_ms, + timeout_ms: complete::timeout_for(options.ac_timeout_ms, COLD.load(Ordering::Relaxed)), version: config::llembas_tty_version().to_string(), + debug: options.ac_debug, }; let spawned = std::thread::Builder::new() .name("llembas-complete".to_string()) diff --git a/wezterm-gui/src/llembas/decorate.rs b/wezterm-gui/src/llembas/decorate.rs index 38fb75499..9e2081014 100644 --- a/wezterm-gui/src/llembas/decorate.rs +++ b/wezterm-gui/src/llembas/decorate.rs @@ -513,6 +513,22 @@ fn place_notice( plan.row_mut(row).texts.push((col, shown, attr)); } +/// Does an input line stand in the pane that nothing follows, and does it +/// show something? Asked when the cursor's own row holds no input: a line +/// carried on over rows, or none at all. +fn input_stands(pane: &Arc) -> bool { + let zones = match pane.get_semantic_zones() { + Ok(zones) => zones, + Err(_) => return false, + }; + match zones.last() { + Some(zone) if zone.semantic_type == SemanticType::Input => { + !super::record::zone_text(pane, zone).trim().is_empty() + } + _ => false, + } +} + fn compute( pane: &Arc, active: bool, @@ -536,8 +552,25 @@ fn compute( let at = cursor.y - top; if at >= 0 && (at as usize) < lines.len() { let at = at as usize; - if options.suggestions || options.highlight || options.ai_complete { - let rows: Vec = lines.iter().map(row_of).collect(); + // The input mark: whether anything stands on the input line of + // the prompt the pane's status record is of. LLeMbas places a + // command only at an empty one. + let marking = if options.input_mark { + state::status_at_prompt(pane.pane_id()) + } else { + None + }; + let drawing = options.suggestions || options.highlight || options.ai_complete; + let rows: Vec = if drawing || marking.is_some() { + lines.iter().map(row_of).collect() + } else { + Vec::new() + }; + if let Some(status) = &marking { + let typed = zone::row_has_input(&rows[at]) || input_stands(pane); + state::mark_input(pane.pane_id(), status, typed); + } + if drawing { if let Some(zone) = zone::input_zone(&rows, at, cursor.x, dims.cols, MAX_ROWS) { if options.highlight { highlight(pane, &options.colors, &zone, top, &mut plan); @@ -624,9 +657,11 @@ pub fn plan_for(pane: &Arc, active: bool) -> Option> { let pane_id = pane.pane_id(); let notice = state::notice(pane_id); let hint = state::hint(pane_id); + let marking = options.input_mark && state::status_at_prompt(pane_id).is_some(); if !(options.suggestions || options.highlight || options.ai_complete) && notice.is_none() && hint.is_none() + && !marking { return None; } diff --git a/wezterm-gui/src/llembas/lua.rs b/wezterm-gui/src/llembas/lua.rs index c631840a8..280dd6435 100644 --- a/wezterm-gui/src/llembas/lua.rs +++ b/wezterm-gui/src/llembas/lua.rs @@ -83,13 +83,21 @@ pub fn register(lua: &Lua) -> anyhow::Result<()> { .take(128) .collect(), ac_timeout_ms: table.get::<_, Option>("ac_timeout_ms")?.unwrap_or(0), + ac_debug: table.get::<_, Option>("ac_debug")?.unwrap_or(false), + input_mark: table.get::<_, Option>("input_mark")?.unwrap_or(false), history: table.get::<_, Option>("history")?.unwrap_or(false), history_max: table.get::<_, Option>("history_max")?.unwrap_or(0), colors: colors(table.get::<_, Option>("colors")?)?, }; - if options != state::options() { - // another model, another engine: a line may be asked about again - super::complete::forget_answers(); + let old = state::options(); + if options != old { + // another model, another engine: a line may be asked about + // again; and the first answer after such a change may take + // longer (the model may have to be loaded) + let cold = (options.ai_complete && !old.ai_complete) + || options.ac_model != old.ac_model + || options.cli != old.cli; + super::complete::forget_answers(cold); state::set_options(options); } Ok(()) @@ -177,6 +185,42 @@ pub fn register(lua: &Lua) -> anyhow::Result<()> { )?, )?; + // status(pane id, id or nil, seq, state, directory): where the shell of a + // pane stands, as its status record said; nil when the layer no longer + // follows it. With it the terminal writes the pane's input mark. + module.set( + "status", + lua.create_function( + |_, + (pane_id, id, seq, state_name, dir): ( + usize, + Option, + Option, + Option, + Option, + )| { + let status = match (id, seq, dir) { + (Some(id), Some(seq), Some(dir)) + if llembas_line::mark::valid_id(&id) && dir.starts_with('/') => + { + Some(state::PaneStatus { + id, + seq, + prompt: state_name.as_deref() == Some("prompt"), + dir: dir.into(), + }) + } + _ => None, + }; + state::set_status(pane_id, status); + if Mux::try_get().is_some() { + Mux::notify_from_any_thread(MuxNotification::PaneOutput(pane_id)); + } + Ok(true) + }, + )?, + )?; + // complete_status(): the terminal's side of the AI's autocomplete in // words - the engine and the model it would use, the last attempts and // what each gave. Lines of plain text. diff --git a/wezterm-gui/src/llembas/record.rs b/wezterm-gui/src/llembas/record.rs index 99ff3d846..58f4fc010 100644 --- a/wezterm-gui/src/llembas/record.rs +++ b/wezterm-gui/src/llembas/record.rs @@ -35,7 +35,7 @@ fn cols_for_row(zone: &SemanticZone, row: StableRowIndex) -> std::ops::Range, zone: &SemanticZone) -> String { +pub(super) fn zone_text(pane: &Arc, zone: &SemanticZone) -> String { let (top, lines) = pane.get_lines(zone.start_y..zone.end_y + 1); let mut text = String::new(); let mut wrapped = true; diff --git a/wezterm-gui/src/llembas/state.rs b/wezterm-gui/src/llembas/state.rs index 0cde25c15..68465d380 100644 --- a/wezterm-gui/src/llembas/state.rs +++ b/wezterm-gui/src/llembas/state.rs @@ -67,6 +67,10 @@ pub struct Options { pub ac_model: String, /// How long the engine is given for a completion; 0 for the default. pub ac_timeout_ms: u64, + /// The engine knows `--debug`: it is asked to say its decisions. + pub ac_debug: bool, + /// Write the input mark of panes whose status record is known (AI is on). + pub input_mark: bool, pub history: bool, pub history_max: usize, pub colors: Colors, @@ -88,6 +92,10 @@ lazy_static::lazy_static! { static ref NOTICES: Mutex> = Mutex::new(HashMap::new()); /// A word that stands at the cursor's row of a pane until it is taken away. static ref HINTS: Mutex> = Mutex::new(HashMap::new()); + /// Where the shell of a pane stands, as its status record said. + static ref STATUS: Mutex> = Mutex::new(HashMap::new()); + /// The input mark last written for a pane: the record's id and seq, typed. + static ref MARKS: Mutex> = Mutex::new(HashMap::new()); static ref COMMANDS: Mutex> = Mutex::new(None); /// Where the command last remembered for a pane stood on its screen. static ref REMEMBERED: Mutex> = @@ -160,6 +168,73 @@ pub fn notice(pane_id: PaneId) -> Option { live } +/// Where the shell of a pane stands: its status record's id and seq, whether +/// it is at a prompt, and the directory the records are kept in. +#[derive(Debug, Clone, PartialEq)] +pub struct PaneStatus { + pub id: String, + pub seq: u64, + pub prompt: bool, + pub dir: PathBuf, +} + +/// The layer says where a pane's shell stands, or that it no longer knows. +pub fn set_status(pane_id: PaneId, status: Option) { + let mut all = STATUS.lock(); + if all.get(&pane_id) == status.as_ref() { + return; + } + match status { + Some(status) => { + if all.len() > 512 { + all.clear(); + } + all.insert(pane_id, status); + } + None => { + if let Some(old) = all.remove(&pane_id) { + let _ = llembas_line::mark::remove(&old.dir, pane_id); + } + MARKS.lock().remove(&pane_id); + } + } + drop(all); + // the pane is looked at again: its input mark is of this record now + changed(); +} + +/// The status of a pane whose shell is at a prompt. +pub fn status_at_prompt(pane_id: PaneId) -> Option { + STATUS + .lock() + .get(&pane_id) + .filter(|status| status.prompt) + .cloned() +} + +/// Write the input mark of a pane when what it says changed: whether +/// anything stands on the input line of the prompt this record is of. +pub fn mark_input(pane_id: PaneId, status: &PaneStatus, typed: bool) { + let now = (status.id.clone(), status.seq, typed); + let mut marks = MARKS.lock(); + if marks.get(&pane_id) == Some(&now) { + return; + } + match llembas_line::mark::write(&status.dir, pane_id, &status.id, status.seq, typed) { + Ok(()) => { + if marks.len() > 512 { + marks.clear(); + } + marks.insert(pane_id, now); + } + Err(err) => { + // no mark is no harm: LLeMbas then reads the prompt from the screen + log::debug!("LLeMbas: the input mark could not be written: {:#}", err); + marks.remove(&pane_id); + } + } +} + /// A word that stands at the cursor's row of a pane for as long as what it /// says holds: LLeMbas waits for an answer, or a command that LLeMbas placed /// at the prompt waits for the person. The layer sets it and takes it away.