AI autocomplete: the engine is given the pane's directory, its errors are kept, and a hint that stands
llembas-tty / linux (push) Failing after 36s

The pane's directory came from the URL the shell integration reports
(file://<host><directory>) through the URL library's own conversion, which
refuses every URL that names a host. So the engine was started without
--cwd, which it requires, ended with a usage error, and its error output
was thrown away: no suggestion, no request, no word of it.

- llembas-line gains complete: whether a line is asked about (decide), the
  directory of a reported URL, one request at a time (Tracker), the engine's
  command line and its run (std only), and the last attempts in words. Tested
  with a stand-in engine that records its arguments, input and environment.
- the engine's timeout is an option (10 s by default); the autocomplete
  model chosen in the terminal is passed on; what the engine says on its
  standard error is the sentence shown.
- wezterm.llembas.complete_status(), .hint() (a word that stands at the
  cursor's row until it is taken away; gentle: never over a cell that shows
  something) and .data_dir().

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-12-02 13:24:57 +00:00
1 parent a78e7ad48c
commit 26e836d9e9
6 files changed
+1217 -153

No files matched your search

+880
View File
@@ -0,0 +1,880 @@
//! Asking LLeMbas for the rest of a line: whether to ask, what is asked, how
//! the engine is run, and what is remembered of it for the person.
//!
//! Nothing here knows a pane or a window. The window's side gives plain
//! values (what is typed, what is on) and gets back a decision; the engine is
//! run here too, with nothing but the standard library, so that the whole way
//! from "a line was typed" to "this is what the engine was given" is tested
//! without a terminal.
//!
//! What comes back from the engine is a model's text: it is cleaned to one
//! plain line ([`crate::suggest`]) and only ever offered, never run.
use crate::suggest;
use std::collections::{HashMap, VecDeque};
use std::io::{Read, Write};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant, SystemTime};
/// The pause in the typing before LLeMbas is asked, in milliseconds.
pub const PAUSE_MS: u64 = 350;
/// The fewest characters a line must have to be asked about.
pub const MIN_CHARS: usize = 3;
/// The most bytes of a line that is asked about.
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_MIN: u64 = 500;
/// The most the engine itself accepts.
pub const TIMEOUT_MS_MAX: u64 = 30_000;
/// How much longer than its own timeout the engine is waited for before it
/// is stopped: its start, and its saying that it gave up.
pub const GRACE_MS: u64 = 2_000;
/// How many attempts are remembered for the person.
pub const ATTEMPTS: usize = 8;
/// The timeout as it is used: what was asked for, within what the engine
/// takes; `0` is "nothing was said".
pub fn clamp_timeout(ms: u64) -> u64 {
if ms == 0 {
TIMEOUT_MS_DEFAULT
} else {
ms.clamp(TIMEOUT_MS_MIN, TIMEOUT_MS_MAX)
}
}
/// Why LLeMbas is not asked about a line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Skip {
/// The AI's autocomplete is off (or AI is).
Off,
/// No LLeMbas CLI was found.
NoEngine,
/// The pane is private.
Private,
/// The pane's shell is not on this machine.
NotThisMachine,
/// The cursor is not at the end of the line.
NotAtEnd,
/// Nothing is typed.
Empty,
/// The line starts with a space: by the shells' own custom such a line is
/// not for remembering, and it is not sent anywhere either.
LeadingSpace,
TooShort,
TooLong,
/// The terminal's own history had a suggestion: that one is shown.
History,
}
impl Skip {
/// In words, for the person.
pub fn sentence(self) -> &'static str {
match self {
Skip::Off => "AI autocomplete is off",
Skip::NoEngine => "the LLeMbas CLI (lembas) was not found",
Skip::Private => "the pane is private",
Skip::NotThisMachine => {
"the pane's shell is not on this machine (another domain, or its directory names another host)"
}
Skip::NotAtEnd => "the cursor was not at the end of the line",
Skip::Empty => "nothing was typed",
Skip::LeadingSpace => "the line starts with a space",
Skip::TooShort => "the line was shorter than 3 characters",
Skip::TooLong => "the line was too long",
Skip::History => "your own command history had a suggestion, and that one is shown",
}
}
}
/// What the window's side knows when a line could be asked about.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Conditions {
/// The AI's autocomplete is on (and AI is).
pub on: bool,
/// A LLeMbas CLI was found.
pub engine: bool,
pub private: bool,
/// The pane's shell is on this machine.
pub this_machine: bool,
/// The cursor is at the end of the input line.
pub at_end: bool,
/// The terminal's own history has a suggestion for the line.
pub history: bool,
}
/// Is LLeMbas asked about this line? `Ok` with the line as it is asked, or
/// why not. The first reason that holds is given, the switch first: with
/// autocomplete off nothing else is looked at.
pub fn decide<'a>(c: &Conditions, typed: &'a str) -> Result<&'a str, Skip> {
if !c.on {
return Err(Skip::Off);
}
if !c.engine {
return Err(Skip::NoEngine);
}
if c.private {
return Err(Skip::Private);
}
if !c.at_end {
return Err(Skip::NotAtEnd);
}
if typed.trim().is_empty() {
return Err(Skip::Empty);
}
if typed.starts_with(' ') {
return Err(Skip::LeadingSpace);
}
if typed.chars().count() < MIN_CHARS {
return Err(Skip::TooShort);
}
if typed.len() > MAX_BYTES || typed.chars().any(|c| c == '\n' || c == '\r') {
return Err(Skip::TooLong);
}
if c.history {
return Err(Skip::History);
}
if !c.this_machine {
return Err(Skip::NotThisMachine);
}
Ok(typed)
}
/// The directory in the path of a `file://` URL, as a pane's shell reported
/// it (OSC 7): percent-decoded, absolute, plain text. `None` when it is not
/// that.
///
/// The shell integration writes `file://<host><directory>`. A URL library's
/// own "to a file path" refuses every URL that names a host, so the path is
/// decoded here and the host is compared by [`same_host`].
pub fn dir_of_url_path(path: &str) -> Option<String> {
let bytes = path.as_bytes();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
let hex = |b: u8| (b as char).to_digit(16);
if let (Some(hi), Some(lo)) = (hex(bytes[i + 1]), hex(bytes[i + 2])) {
out.push((hi * 16 + lo) as u8);
i += 3;
continue;
}
}
out.push(bytes[i]);
i += 1;
}
let dir = String::from_utf8(out).ok()?;
if !dir.starts_with('/') || dir.chars().any(|c| c.is_control()) {
return None;
}
Some(dir)
}
/// Is `host`, as a pane's shell named it, the machine called `mine`? An empty
/// host and `localhost` are this machine; otherwise the names are compared
/// without case, whole or by their first label (`box` is `box.example.org`).
pub fn same_host(host: &str, mine: Option<&str>) -> bool {
let host = host.to_lowercase();
if host.is_empty() || host == "localhost" {
return true;
}
match mine {
Some(mine) => {
let mine = mine.to_lowercase();
let short = |s: &str| s.split('.').next().unwrap_or("").to_string();
mine == host || short(&mine) == short(&host)
}
None => false,
}
}
/// What the tracker says of a line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Poll {
/// The engine answered for exactly this line: the rest, or that there is none.
Answer(Option<String>),
/// It is being asked.
Waiting,
/// It is to be asked now: the number of the request.
Start(u64),
}
/// Which request is wanted now, and the last answer for each pane. One
/// request at a time: a newer line takes the place of an older one, whose
/// request is then stopped.
#[derive(Debug, Default)]
pub struct Tracker {
next_id: u64,
wanted: Option<(usize, String, u64)>,
answers: HashMap<usize, (String, Option<String>)>,
}
impl Tracker {
pub fn poll(&mut self, pane: usize, typed: &str) -> Poll {
if let Some((line, rest)) = self.answers.get(&pane) {
if line == typed {
return Poll::Answer(rest.clone());
}
}
if let Some((p, line, _)) = &self.wanted {
if *p == pane && line == typed {
return Poll::Waiting;
}
}
self.next_id += 1;
self.wanted = Some((pane, typed.to_string(), self.next_id));
Poll::Start(self.next_id)
}
pub fn still_wanted(&self, id: u64) -> bool {
matches!(&self.wanted, Some((_, _, wanted)) if *wanted == id)
}
/// The request ended: what it gave is the answer for that line.
pub fn finish(&mut self, id: u64, pane: usize, typed: String, rest: Option<String>) {
if self.still_wanted(id) {
self.wanted = None;
}
if self.answers.len() > 256 {
self.answers.clear();
}
self.answers.insert(pane, (typed, rest));
}
/// Forget every answer: what is on changed (another model, another
/// directory's settings), so a line may be asked about again.
pub fn forget(&mut self) {
self.answers.clear();
}
}
/// One request to the engine.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Request {
/// The path of the LLeMbas CLI.
pub cli: String,
/// `bash`, `zsh` or `fish`.
pub shell: String,
/// The pane's directory: absolute. The engine refuses a request without one.
pub cwd: String,
/// The line so far.
pub line: String,
/// The autocomplete model chosen in the terminal; empty for the engine's own choice.
pub model: String,
pub timeout_ms: u64,
/// The terminal's version, as the engine's environment says it (`LLEMBAS_TTY`).
pub version: String,
}
/// THE command line of a completion, in one place: what follows the CLI's path.
pub fn args(req: &Request) -> Vec<String> {
let mut args = vec![
"complete".to_string(),
"--shell".to_string(),
req.shell.clone(),
"--cwd".to_string(),
req.cwd.clone(),
"--timeout-ms".to_string(),
clamp_timeout(req.timeout_ms).to_string(),
];
if !req.model.is_empty() {
args.push("--model".to_string());
args.push(req.model.clone());
}
args
}
/// How a request ended.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
/// The rest of the line.
Suggestion(String),
/// The engine ran and suggested nothing; with what it said about that, if anything.
Nothing(String),
/// The engine ended with an error: its sentence.
Failed(String),
/// No answer in this many milliseconds: the engine was stopped.
TimedOut(u64),
/// The line changed while the engine was asked: it was stopped.
Cancelled,
/// The engine could not be started: why.
NotStarted(String),
}
impl Outcome {
/// The rest of the line this gave, if any.
pub fn rest(&self) -> Option<String> {
match self {
Outcome::Suggestion(rest) => Some(rest.clone()),
_ => None,
}
}
/// In words, for the person.
pub fn sentence(&self) -> String {
match self {
Outcome::Suggestion(rest) => format!("a suggestion: {}", shorten(rest, 60)),
Outcome::Nothing(said) if said.is_empty() => "nothing was suggested".to_string(),
Outcome::Nothing(said) => format!("nothing was suggested ({})", said),
Outcome::Failed(said) => format!("an error: {}", said),
Outcome::TimedOut(ms) => {
format!("no answer in {} ms: the engine was stopped", ms)
}
Outcome::Cancelled => "stopped: the line changed".to_string(),
Outcome::NotStarted(why) => format!("the engine could not be started: {}", why),
}
}
}
/// One plain line of at most `max` characters, for showing to the person.
pub fn shorten(text: &str, max: usize) -> String {
let line = text.lines().next().unwrap_or("");
let plain: String = line.chars().filter(|c| !c.is_control()).collect();
let plain = plain.trim();
if plain.chars().count() <= max {
return plain.to_string();
}
let mut out: String = plain.chars().take(max.saturating_sub(1)).collect();
out.push('\u{2026}');
out
}
fn read_some(source: Option<impl Read + Send + 'static>) -> std::sync::mpsc::Receiver<String> {
let (tx, rx) = std::sync::mpsc::channel();
if let Some(source) = source {
// On a thread of its own: a pipe that fills would otherwise hold the
// engine, and a pipe that something else keeps open would hold us.
let _ = std::thread::Builder::new()
.name("llembas-complete-read".to_string())
.spawn(move || {
let mut bytes = Vec::new();
let _ = source.take(8192).read_to_end(&mut bytes);
let _ = tx.send(String::from_utf8_lossy(&bytes).into_owned());
});
}
rx
}
/// Run the engine for one request and wait for it. `wanted` is asked again
/// and again: when it says no, the engine is stopped.
///
/// The line goes to the engine's standard input, which is then closed (the
/// engine reads to its end). `LLEMBAS_TTY` is set, as in every pane. What
/// 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 {
let timeout = clamp_timeout(req.timeout_ms);
let mut command = Command::new(&req.cli);
command
.args(args(req))
.env("LLEMBAS_TTY", &req.version)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = match command.spawn() {
Ok(child) => child,
Err(err) => return Outcome::NotStarted(format!("{}: {}", req.cli, err)),
};
if let Some(mut stdin) = child.stdin.take() {
let _ = stdin.write_all(req.line.as_bytes());
// dropped here: the engine sees the end of its input
}
let stdout = read_some(child.stdout.take());
let stderr = read_some(child.stderr.take());
let patience = Duration::from_millis(timeout + GRACE_MS);
let started = Instant::now();
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) => {}
Err(err) => {
let _ = child.kill();
let _ = child.wait();
return Outcome::Failed(format!("the engine could not be waited for: {}", err));
}
}
let still = wanted();
if !still || started.elapsed() > patience {
let _ = child.kill();
let _ = child.wait();
return if still {
Outcome::TimedOut(timeout + GRACE_MS)
} else {
Outcome::Cancelled
};
}
std::thread::sleep(Duration::from_millis(25));
};
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);
if !status.success() {
return Outcome::Failed(if said.is_empty() {
match status.code() {
Some(code) => format!("the engine ended with status {}", code),
None => "the engine was stopped by a signal".to_string(),
}
} else {
said
});
}
match suggest::clean_completion(&answer, &req.line) {
Some(rest) => Outcome::Suggestion(rest),
None => Outcome::Nothing(said),
}
}
/// One attempt, as it is remembered for the person. In memory only.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attempt {
pub at: SystemTime,
/// The line that was asked about, shortened.
pub line: String,
pub took_ms: u64,
pub outcome: Outcome,
}
/// The last few attempts, and the last reason nothing was asked.
#[derive(Debug, Default)]
pub struct Log {
attempts: VecDeque<Attempt>,
skipped: Option<(SystemTime, Skip)>,
}
fn ago(now: SystemTime, at: SystemTime) -> String {
let secs = now.duration_since(at).map(|d| d.as_secs()).unwrap_or(0);
if secs < 90 {
format!("{} s ago", secs)
} else if secs < 5400 {
format!("{} min ago", secs / 60)
} else {
format!("{} h ago", secs / 3600)
}
}
impl Log {
pub fn attempt(&mut self, at: SystemTime, line: &str, took_ms: u64, outcome: Outcome) {
if self.attempts.len() >= ATTEMPTS {
self.attempts.pop_front();
}
self.attempts.push_back(Attempt {
at,
line: shorten(line, 40),
took_ms,
outcome,
});
}
pub fn skip(&mut self, at: SystemTime, why: Skip) {
self.skipped = Some((at, why));
}
pub fn attempts(&self) -> impl Iterator<Item = &Attempt> {
self.attempts.iter()
}
pub fn clear(&mut self) {
self.attempts.clear();
self.skipped = None;
}
/// What the terminal's side of the autocomplete knows, in words: the
/// engine and model it would use, and what the last attempts gave.
pub fn status(&self, now: SystemTime, engine: &str, model: &str, timeout_ms: u64) -> String {
let mut lines = Vec::new();
lines.push(if engine.is_empty() {
"engine: the LLeMbas CLI (lembas) was not found".to_string()
} else {
format!("engine: {}", engine)
});
lines.push(if model.is_empty() {
"model: the engine's own choice (none is chosen in the terminal)".to_string()
} else {
format!("model: {}", model)
});
lines.push(format!(
"asked after a pause of {} ms in the typing; the engine is given {} ms",
PAUSE_MS,
clamp_timeout(timeout_ms)
));
if self.attempts.is_empty() {
lines.push("asked: not yet, since the terminal started".to_string());
} else {
lines.push("asked, the newest last:".to_string());
for a in &self.attempts {
lines.push(format!(
" {}, for \"{}\", after {} ms: {}",
ago(now, a.at),
a.line,
a.took_ms,
a.outcome.sentence()
));
}
}
if let Some((at, why)) = &self.skipped {
lines.push(format!(
"last not asked {}: {}",
ago(now, *at),
why.sentence()
));
}
lines.join("\n")
}
}
#[cfg(test)]
mod tests {
use super::*;
fn all_on() -> Conditions {
Conditions {
on: true,
engine: true,
private: false,
this_machine: true,
at_end: true,
history: false,
}
}
#[test]
fn when_a_line_is_asked_about() {
let c = all_on();
assert_eq!(decide(&c, "git che"), Ok("git che"));
assert_eq!(decide(&c, "ls "), Ok("ls "));
assert_eq!(decide(&c, "ls"), Err(Skip::TooShort));
assert_eq!(decide(&c, ""), Err(Skip::Empty));
assert_eq!(decide(&c, " "), Err(Skip::Empty));
assert_eq!(decide(&c, " secret thing"), Err(Skip::LeadingSpace));
let long: String = std::iter::repeat('x').take(MAX_BYTES + 1).collect();
assert_eq!(decide(&c, &long), Err(Skip::TooLong));
assert_eq!(decide(&c, "a\nb c"), Err(Skip::TooLong), "one line only");
}
#[test]
fn what_keeps_a_line_from_being_asked_about() {
let typed = "git che";
let with = |f: &dyn Fn(&mut Conditions)| {
let mut c = all_on();
f(&mut c);
decide(&c, typed)
};
assert_eq!(with(&|c| c.on = false), Err(Skip::Off));
assert_eq!(with(&|c| c.engine = false), Err(Skip::NoEngine));
assert_eq!(with(&|c| c.private = true), Err(Skip::Private));
assert_eq!(with(&|c| c.at_end = false), Err(Skip::NotAtEnd));
assert_eq!(with(&|c| c.history = true), Err(Skip::History));
assert_eq!(with(&|c| c.this_machine = false), Err(Skip::NotThisMachine));
// the switch is looked at first: with it off nothing else is said
let off = Conditions {
on: false,
engine: false,
private: true,
this_machine: false,
at_end: false,
history: true,
};
assert_eq!(decide(&off, ""), Err(Skip::Off));
// every reason has its sentence
for skip in [
Skip::Off,
Skip::NoEngine,
Skip::Private,
Skip::NotThisMachine,
Skip::NotAtEnd,
Skip::Empty,
Skip::LeadingSpace,
Skip::TooShort,
Skip::TooLong,
Skip::History,
] {
assert!(!skip.sentence().is_empty());
}
}
#[test]
fn the_directory_a_shell_reported() {
// what the shell integration writes: file://<host><directory>
assert_eq!(
dir_of_url_path("/home/person/project"),
Some("/home/person/project".to_string())
);
assert_eq!(
dir_of_url_path("/home/person/my%20project/%C3%A9t%C3%A9"),
Some("/home/person/my project/\u{e9}t\u{e9}".to_string())
);
assert_eq!(
dir_of_url_path("/100%/x"),
Some("/100%/x".to_string()),
"a percent sign that starts no escape stays"
);
assert_eq!(dir_of_url_path("/a%2"), Some("/a%2".to_string()));
assert_eq!(dir_of_url_path("/a%41"), Some("/aA".to_string()));
assert_eq!(dir_of_url_path(""), None);
assert_eq!(dir_of_url_path("relative/dir"), None);
assert_eq!(dir_of_url_path("/a%0Ab"), None, "no control character");
assert_eq!(dir_of_url_path("/a%FF"), None, "not text");
}
#[test]
fn whose_machine_a_directory_is_on() {
assert!(same_host("", None));
assert!(same_host("localhost", None));
assert!(same_host("workstation", Some("workstation")));
assert!(same_host("Workstation", Some("workstation")));
assert!(same_host("workstation.example.org", Some("workstation")));
assert!(same_host("workstation", Some("workstation.example.org")));
assert!(!same_host("laptop", Some("workstation")));
assert!(!same_host("laptop", None));
}
#[test]
fn one_request_at_a_time() {
let mut t = Tracker::default();
let first = match t.poll(1, "git che") {
Poll::Start(id) => id,
other => panic!("expected a start, got {:?}", other),
};
assert!(t.still_wanted(first));
assert_eq!(t.poll(1, "git che"), Poll::Waiting, "asked once for a line");
// the person types on: the older request is no longer wanted
let second = match t.poll(1, "git chec") {
Poll::Start(id) => id,
other => panic!("expected a start, got {:?}", other),
};
assert!(!t.still_wanted(first));
assert!(t.still_wanted(second));
t.finish(
second,
1,
"git chec".to_string(),
Some("kout main".to_string()),
);
assert!(!t.still_wanted(second));
assert_eq!(
t.poll(1, "git chec"),
Poll::Answer(Some("kout main".to_string()))
);
// an answer is for exactly its line
assert!(matches!(t.poll(1, "git check"), Poll::Start(_)));
// "nothing" is an answer too: the line is not asked about again
let third = match t.poll(2, "xyz") {
Poll::Start(id) => id,
other => panic!("expected a start, got {:?}", other),
};
t.finish(third, 2, "xyz".to_string(), None);
assert_eq!(t.poll(2, "xyz"), Poll::Answer(None));
// until what is on changes
t.forget();
assert!(matches!(t.poll(2, "xyz"), Poll::Start(_)));
}
fn request(cli: &str) -> Request {
Request {
cli: cli.to_string(),
shell: "bash".to_string(),
cwd: "/home/person/my project".to_string(),
line: "git che".to_string(),
model: String::new(),
timeout_ms: 0,
version: "1.2.3".to_string(),
}
}
#[test]
fn the_command_line_of_a_completion() {
let mut req = request("/opt/lembas");
assert_eq!(
args(&req),
[
"complete",
"--shell",
"bash",
"--cwd",
"/home/person/my project",
"--timeout-ms",
"10000"
]
);
req.model = "local/fast".to_string();
req.timeout_ms = 99_999;
let a = args(&req);
assert_eq!(a[a.len() - 2..], ["--model", "local/fast"]);
assert_eq!(a[6], "30000", "no more than the engine takes");
assert_eq!(clamp_timeout(1), TIMEOUT_MS_MIN);
assert_eq!(clamp_timeout(4000), 4000);
}
#[test]
fn what_is_remembered_for_the_person() {
let mut log = Log::default();
let t0 = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
let now = t0 + Duration::from_secs(12);
let empty = log.status(now, "", "", 0);
assert!(empty.contains("was not found"), "{}", empty);
assert!(empty.contains("the engine's own choice"), "{}", empty);
assert!(empty.contains("not yet"), "{}", empty);
log.attempt(t0, "git che", 420, Outcome::Suggestion("ckout main".into()));
log.attempt(t0, "kubectl get", 12_000, Outcome::TimedOut(12_000));
log.attempt(
t0,
"docker ru",
80,
Outcome::Failed("lembas complete: not logged in".into()),
);
log.skip(t0, Skip::History);
let status = log.status(now, "/opt/lembas", "local/fast", 4000);
assert!(status.contains("engine: /opt/lembas"), "{}", status);
assert!(status.contains("model: local/fast"), "{}", status);
assert!(status.contains("given 4000 ms"), "{}", status);
assert!(
status.contains("12 s ago, for \"git che\", after 420 ms: a suggestion: ckout main"),
"{}",
status
);
assert!(status.contains("no answer in 12000 ms"), "{}", status);
assert!(status.contains("an error: lembas complete: not logged in"));
assert!(status.contains("last not asked 12 s ago: your own command history"));
// no more than a few are kept, the oldest go
for i in 0..20 {
log.attempt(
t0,
&format!("line {}", i),
1,
Outcome::Nothing(String::new()),
);
}
assert_eq!(log.attempts().count(), ATTEMPTS);
assert_eq!(log.attempts().next().unwrap().line, "line 12");
// nothing that could act on a terminal is kept of a line or an answer
assert_eq!(shorten("a\u{1b}[31mb\nsecond", 60), "a[31mb");
assert_eq!(shorten("abcdefgh", 4), "abc\u{2026}");
}
/// The engine is run for real, with a stand-in for `lembas`: a script
/// that writes down what it was given. One test, one stand-in after the
/// other: a file that was just written is run by this thread alone.
#[cfg(unix)]
#[test]
fn the_engine_as_it_is_run() {
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
let dir = std::env::temp_dir().join(format!(
"llembas-line-complete-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0)
));
std::fs::create_dir_all(&dir).unwrap();
let stand_in = |name: &str, body: &str| -> PathBuf {
let path = dir.join(name);
std::fs::write(&path, format!("#!/bin/sh\n{}\n", body)).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).unwrap();
path
};
let read =
|name: &str| -> String { std::fs::read_to_string(dir.join(name)).unwrap_or_default() };
let cli = |path: &Path| path.to_str().unwrap().to_string();
let always = || true;
// 1. What the engine is given: its arguments one by one, the line on
// its standard input and then the end of it, LLEMBAS_TTY.
let recorder = stand_in(
"lembas-records",
&format!(
"d='{}'\nfor a in \"$@\"; do printf '%s\\n' \"$a\"; done > \"$d/argv\"\n\
cat > \"$d/stdin\"\nprintf '%s' \"${{LLEMBAS_TTY-unset}}\" > \"$d/env\"\n\
printf 'git checkout main\\n'",
dir.display()
),
);
let mut req = request(&cli(&recorder));
req.model = "local/fast".to_string();
req.timeout_ms = 4000;
assert_eq!(
run(&req, &always),
Outcome::Suggestion("ckout main".to_string()),
"the line repeated by the model is not offered twice"
);
assert_eq!(
read("argv"),
"complete\n--shell\nbash\n--cwd\n/home/person/my project\n--timeout-ms\n4000\n--model\nlocal/fast\n"
);
assert_eq!(
read("stdin"),
"git che",
"the line, and the end of the input: the stand-in's cat came back"
);
assert_eq!(read("env"), "1.2.3");
// 2. Nothing suggested, with what the engine said of it.
let quiet = stand_in(
"lembas-quiet",
"cat > /dev/null\necho 'lembas complete: no suggestion in 4000 ms' >&2",
);
assert_eq!(
run(&request(&cli(&quiet)), &always),
Outcome::Nothing("lembas complete: no suggestion in 4000 ms".to_string())
);
// 3. An error is the engine's own sentence, never silence.
let failing = stand_in(
"lembas-fails",
"cat > /dev/null\necho 'lembas complete: --cwd must be an absolute directory' >&2\necho 'usage: ...' >&2\nexit 2",
);
assert_eq!(
run(&request(&cli(&failing)), &always),
Outcome::Failed("lembas complete: --cwd must be an absolute directory".to_string())
);
let silent = stand_in("lembas-silent", "exit 3");
assert_eq!(
run(&request(&cli(&silent)), &always),
Outcome::Failed("the engine ended with status 3".to_string())
);
// 4. No engine at that path.
match run(&request(&cli(&dir.join("no-such-lembas"))), &always) {
Outcome::NotStarted(why) => assert!(why.contains("no-such-lembas"), "{}", why),
other => panic!("expected NotStarted, got {:?}", other),
}
// 5. An engine that does not answer is stopped: when its time is
// over, and at once when the line is no longer wanted.
let slow = stand_in("lembas-slow", "cat > /dev/null\nexec sleep 30");
let mut req = request(&cli(&slow));
req.timeout_ms = TIMEOUT_MS_MIN;
let started = Instant::now();
assert_eq!(
run(&req, &always),
Outcome::TimedOut(TIMEOUT_MS_MIN + GRACE_MS)
);
assert!(started.elapsed() < Duration::from_secs(10));
let started = Instant::now();
let asked = std::cell::Cell::new(0);
let twice = || {
asked.set(asked.get() + 1);
asked.get() < 3
};
assert_eq!(run(&req, &twice), Outcome::Cancelled);
assert!(started.elapsed() < Duration::from_secs(2));
// 6. What a model says is text: one plain line of it is offered.
let hostile = stand_in(
"lembas-hostile",
"cat > /dev/null\nprintf 'ckout \\033[31mmain\\nrm -rf /\\n'",
);
assert_eq!(
run(&request(&cli(&hostile)), &always),
Outcome::Suggestion("ckout [31mmain".to_string())
);
let _ = std::fs::remove_dir_all(&dir);
}
}
+3
View File
@@ -6,11 +6,14 @@
//! - [`history`]: the terminal's own history of commands it saw run.
//! - [`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
//! engine is run, and what is remembered of it for the person.
//!
//! Everything takes plain values and returns plain values. Text that came
//! from a pane, a file or a model is text here and nothing else: it is never
//! run, and nothing in it survives that could act on a terminal.
pub mod complete;
pub mod editor;
pub mod history;
pub mod suggest;
+95 -118
View File
@@ -4,40 +4,24 @@
//! The line so far goes to `lembas complete --shell …` on its standard
//! input, off the window's own thread, after a pause in the typing; a request
//! that is no longer wanted is stopped. What comes back is a model's text: it
//! is cleaned to one plain line (`llembas_line::suggest`) and only ever
//! offered, never run.
//! is cleaned to one plain line and only ever offered, never run.
//!
//! Whether a line is asked about, how the engine is run and what is kept of
//! each attempt for the person is `llembas_line::complete`, which is where
//! the tests are; this file gives it the pane and the thread.
use super::state;
use llembas_line::suggest;
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::collections::HashMap;
use std::io::{Read, Write};
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::time::{Duration, Instant};
/// The pause in the typing before LLeMbas is asked.
const PAUSE: Duration = Duration::from_millis(350);
/// How long an answer is waited for.
const PATIENCE: Duration = Duration::from_secs(5);
/// The fewest characters a line must have to be asked about.
const MIN_CHARS: usize = 3;
const MAX_BYTES: usize = 2000;
#[derive(Default)]
struct Ai {
next_id: u64,
/// The request that is wanted now: the pane, the line, its number.
wanted: Option<(PaneId, String, u64)>,
/// The last answer for a pane: the line it was for, and the rest (or that
/// there was none).
answers: HashMap<PaneId, (String, Option<String>)>,
}
use std::time::{Duration, Instant, SystemTime};
lazy_static::lazy_static! {
static ref AI: Mutex<Ai> = Mutex::new(Ai::default());
static ref TRACKER: Mutex<Tracker> = Mutex::new(Tracker::default());
/// The last attempts, for "LLeMbas: autocomplete status". In memory only.
static ref LOG: Mutex<Log> = Mutex::new(Log::default());
}
/// The shell of a pane by its name, as `lembas complete --shell` takes it.
@@ -57,125 +41,118 @@ fn shell_of(pane: &Arc<dyn Pane>) -> &'static str {
}
fn still_wanted(id: u64) -> bool {
matches!(&AI.lock().wanted, Some((_, _, wanted)) if *wanted == id)
TRACKER.lock().still_wanted(id)
}
fn finish(id: u64, pane_id: PaneId, typed: String, rest: Option<String>) {
let mut ai = AI.lock();
if matches!(&ai.wanted, Some((_, _, wanted)) if *wanted == id) {
ai.wanted = None;
fn ask(id: u64, pane_id: PaneId, req: Request) {
std::thread::sleep(Duration::from_millis(complete::PAUSE_MS));
if !still_wanted(id) {
return;
}
if ai.answers.len() > 256 {
ai.answers.clear();
let at = SystemTime::now();
let started = Instant::now();
let outcome = complete::run(&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
return;
}
ai.answers.insert(pane_id, (typed, rest));
drop(ai);
// in the terminal's log (the debug overlay shows it), without the line
match &outcome {
Outcome::Suggestion(_) | Outcome::Nothing(_) => {
log::debug!(
"LLeMbas autocomplete: {} after {} ms",
if outcome.rest().is_some() {
"a suggestion"
} else {
"nothing"
},
took
);
}
other => log::warn!("LLeMbas autocomplete ({}): {}", req.cli, other.sentence()),
}
let rest = outcome.rest();
LOG.lock().attempt(at, &req.line, took, outcome);
TRACKER.lock().finish(id, pane_id, req.line, rest);
state::changed();
Mux::notify_from_any_thread(MuxNotification::PaneOutput(pane_id));
}
fn ask(
id: u64,
pane_id: PaneId,
typed: String,
cli: String,
shell: &'static str,
cwd: Option<String>,
) {
std::thread::sleep(PAUSE);
if !still_wanted(id) {
/// Nothing was asked about the line that is typed now, and why: for the
/// status.
pub fn skipped(why: Skip) {
// what is true of nearly every line is not worth keeping in place of a
// reason that says something
if matches!(why, Skip::Off | Skip::Empty | Skip::NotAtEnd) {
return;
}
let mut command = Command::new(&cli);
command.arg("complete").arg("--shell").arg(shell);
if let Some(cwd) = &cwd {
command.arg("--cwd").arg(cwd);
LOG.lock().skip(SystemTime::now(), why);
}
/// What is on changed (the model, the directory's settings): a line that was
/// answered may be asked about again.
pub fn forget_answers() {
TRACKER.lock().forget();
}
/// The terminal's side of the autocomplete in words, for the person.
pub fn status() -> String {
let options = state::options();
let mut text = LOG.lock().status(
SystemTime::now(),
&options.cli,
&options.ac_model,
options.ac_timeout_ms,
);
if !options.ai_complete {
text = format!(
"The terminal is not asking now: AI autocomplete (or AI) is off.\n{}",
text
);
}
command
.arg("--timeout-ms")
.arg("2500")
.env("LLEMBAS_TTY", config::llembas_tty_version())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null());
let mut child = match command.spawn() {
Ok(child) => child,
Err(_) => {
finish(id, pane_id, typed, None);
return;
}
};
if let Some(mut stdin) = child.stdin.take() {
let _ = stdin.write_all(typed.as_bytes());
}
let started = Instant::now();
let ok = loop {
match child.try_wait() {
Ok(Some(status)) => break status.success(),
Ok(None) => {}
Err(_) => break false,
}
let wanted = still_wanted(id);
if !wanted || started.elapsed() > PATIENCE {
let _ = child.kill();
let _ = child.wait();
if wanted {
finish(id, pane_id, typed, None);
}
return;
}
std::thread::sleep(Duration::from_millis(25));
};
let mut answer = String::new();
if ok {
if let Some(out) = child.stdout.take() {
let _ = out.take(8192).read_to_string(&mut answer);
}
}
let rest = suggest::clean_completion(&answer, &typed);
finish(id, pane_id, typed, rest);
text
}
/// The rest of the line, when LLeMbas has answered for exactly this line.
/// Otherwise `None`, and LLeMbas is asked (once for a line): when the answer
/// comes the pane is drawn again.
/// comes the pane is drawn again. The caller has decided that the line is
/// asked about (`llembas_line::complete::decide`).
pub fn suggestion(
pane: &Arc<dyn Pane>,
typed: &str,
cli: &str,
cwd: Option<String>,
options: &state::Options,
cwd: String,
) -> Option<String> {
if typed.starts_with(' ') || typed.len() > MAX_BYTES || typed.chars().count() < MIN_CHARS {
return None;
}
let pane_id = pane.pane_id();
let mut ai = AI.lock();
if let Some((line, rest)) = ai.answers.get(&pane_id) {
if line == typed {
return rest.clone();
}
}
if let Some((p, line, _)) = &ai.wanted {
if *p == pane_id && line == typed {
return None;
}
}
ai.next_id += 1;
let id = ai.next_id;
ai.wanted = Some((pane_id, typed.to_string(), id));
drop(ai);
let shell = shell_of(pane);
let typed = typed.to_string();
let cli = cli.to_string();
let id = match TRACKER.lock().poll(pane_id, typed) {
Poll::Answer(rest) => return rest,
Poll::Waiting => return None,
Poll::Start(id) => id,
};
let req = Request {
cli: options.cli.clone(),
shell: shell_of(pane).to_string(),
cwd,
line: typed.to_string(),
model: options.ac_model.clone(),
timeout_ms: options.ac_timeout_ms,
version: config::llembas_tty_version().to_string(),
};
let spawned = std::thread::Builder::new()
.name("llembas-complete".to_string())
.spawn(move || ask(id, pane_id, typed, cli, shell, cwd));
.spawn(move || ask(id, pane_id, req));
if let Err(err) = spawned {
log::warn!(
"LLeMbas: could not start a thread to ask for a completion: {:#}",
err
);
LOG.lock().attempt(
SystemTime::now(),
typed,
0,
Outcome::NotStarted(format!("no thread: {}", err)),
);
}
None
}
+115 -32
View File
@@ -19,6 +19,7 @@
//! cells and places the result.
use super::{complete, state};
use llembas_line::complete::{decide, dir_of_url_path, same_host, Conditions};
use llembas_line::suggest;
use llembas_line::tokens::{self, Kind, Role};
use llembas_line::zone::{self, Zone};
@@ -164,17 +165,10 @@ fn this_host() -> Option<String> {
/// Is `host` (of a pane's directory, as its shell reported it) this machine?
fn is_this_host(host: &str) -> bool {
let host = host.to_lowercase();
if host.is_empty() || host == "localhost" {
return true;
}
match this_host() {
Some(mine) => {
let short = |s: &str| s.split('.').next().unwrap_or("").to_string();
mine == host || short(&mine) == short(&host)
}
None => false,
}
same_host(host, this_host().as_deref())
}
/// What can be looked up for a pane whose shell is on this machine: whether a
@@ -197,13 +191,27 @@ impl Lookups {
if !is_this_host(url.host_str().unwrap_or("")) {
return None;
}
url.to_file_path().ok()
// The shell integration reports `file://<host><directory>`,
// and the URL's own "to a file path" refuses every URL that
// names a host: so the path is decoded for what it is.
dir_of_url_path(url.path()).map(PathBuf::from)
}
None => None,
};
Some(Lookups { cwd })
}
/// The directory a program started for this pane is given: the pane's
/// own, else the person's home.
fn dir(&self) -> String {
self.cwd
.as_ref()
.and_then(|cwd| cwd.to_str())
.filter(|cwd| cwd.starts_with('/'))
.map(|cwd| cwd.to_string())
.unwrap_or_else(|| config::HOME_DIR.to_string_lossy().into_owned())
}
/// A word as a path of this machine; `None` when it cannot be one.
fn resolve(&self, word: &str) -> Option<PathBuf> {
if word.is_empty() || word.len() > 512 {
@@ -367,38 +375,41 @@ fn ghost(
cols: usize,
plan: &mut Plan,
) {
if !zone.at_end() {
return;
}
let at_end = zone.at_end();
let typed = zone.typed();
if typed.trim().is_empty() {
return;
}
let pane_id = pane.pane_id();
let mut found: Option<(String, suggest::Source)> = None;
if options.suggestions {
if at_end && options.suggestions && !typed.trim().is_empty() {
if let Some(rest) = state::history_suggest(typed) {
found = Some((rest, suggest::Source::History));
}
}
// LLeMbas is asked only when the history has nothing, never for a private
// pane, and only for a shell on this machine.
if found.is_none()
&& options.ai_complete
&& !options.cli.is_empty()
&& !state::is_private(pane_id)
{
if let Some(lookups) = Lookups::for_pane(pane) {
let cwd = lookups
.cwd
.as_ref()
.and_then(|cwd| cwd.to_str())
.map(|cwd| cwd.to_string());
if let Some(rest) = complete::suggestion(pane, typed, &options.cli, cwd) {
found = Some((rest, suggest::Source::Ai));
// pane, and only for a shell on this machine: `decide` is the one place
// that says so, and why not when not.
if options.ai_complete {
let lookups = Lookups::for_pane(pane);
let conditions = Conditions {
on: options.ai_complete,
engine: !options.cli.is_empty(),
private: state::is_private(pane_id),
this_machine: lookups.is_some(),
at_end,
history: found.is_some(),
};
match (decide(&conditions, typed), lookups) {
(Ok(line), Some(lookups)) => {
if let Some(rest) = complete::suggestion(pane, line, options, lookups.dir()) {
found = Some((rest, suggest::Source::Ai));
}
}
(Err(why), _) => complete::skipped(why),
(Ok(_), None) => {}
}
}
if !at_end {
return;
}
let (rest, source) = match found {
Some(found) => found,
None => return,
@@ -428,6 +439,47 @@ fn ghost(
plan.suggestion = Some(rest);
}
/// A standing word that must cover nothing (a command waits at the prompt):
/// dimmed, at the right of the cursor's row when all of it fits beside what
/// the row shows; else on the row below when that row is empty; else cut,
/// beside what the row shows; else not at all.
fn place_gentle(
text: &str,
line: &Line,
below: Option<&Line>,
row: StableRowIndex,
taken: usize,
cols: usize,
colors: &state::Colors,
plan: &mut Plan,
) {
let mut attr = CellAttributes::default();
match colors.ghost {
Some(color) => {
attr.set_foreground(color);
}
None => {
attr.set_intensity(Intensity::Half);
}
}
let wanted = text_width(text);
let free = cols.saturating_sub(used_cols(line).max(taken) + 2);
let (row, shown) = if free >= wanted {
(row, text.to_string())
} else if below.map(used_cols) == Some(0) && cols > 2 {
(row + 1, suggest::fit(text, cols - 1, &char_width))
} else if free >= 12 {
(row, suggest::fit(text, free, &char_width))
} else {
return;
};
if shown.is_empty() {
return;
}
let col = cols.saturating_sub(text_width(&shown));
plan.row_mut(row).texts.push((col, shown, attr));
}
/// A word from the terminal, at the right of a row.
fn place_notice(
text: &str,
@@ -466,6 +518,7 @@ fn compute(
active: bool,
options: &state::Options,
notice: Option<String>,
hint: Option<state::Hint>,
cursor: &StableCursorPosition,
dims: &RenderableDimensions,
) -> Option<Plan> {
@@ -475,6 +528,7 @@ fn compute(
let around = MAX_ROWS as StableRowIndex;
let mut cursor_line: Option<Line> = None;
let mut below_line: Option<Line> = None;
let mut taken = 0;
if !alt {
let first = (cursor.y - around).max(dims.scrollback_top);
@@ -502,9 +556,34 @@ fn compute(
}
taken = taken.max(cursor.x + 1);
cursor_line = Some(lines[at].clone());
if cursor.y < bottom {
below_line = lines.get(at + 1).cloned();
}
}
}
// A word in passing is shown first; the standing word is there again
// when its moment is over. A gentle one never covers anything, so in a
// full-screen program it is simply not drawn.
let (notice, gentle) = match (notice, hint) {
(Some(text), _) => (Some(text), None),
(None, Some(hint)) if hint.gentle => (None, Some(hint.text)),
(None, Some(hint)) => (Some(hint.text), None),
(None, None) => (None, None),
};
if let (Some(text), Some(line)) = (&gentle, &cursor_line) {
place_gentle(
text,
line,
below_line.as_ref(),
cursor.y,
taken,
dims.cols,
&options.colors,
&mut plan,
);
}
if let Some(text) = notice {
if alt || cursor_line.is_none() {
let (top, lines) = pane.get_lines(bottom..bottom + 1);
@@ -544,7 +623,11 @@ pub fn plan_for(pane: &Arc<dyn Pane>, active: bool) -> Option<Arc<Plan>> {
let options = state::options();
let pane_id = pane.pane_id();
let notice = state::notice(pane_id);
if !(options.suggestions || options.highlight || options.ai_complete) && notice.is_none() {
let hint = state::hint(pane_id);
if !(options.suggestions || options.highlight || options.ai_complete)
&& notice.is_none()
&& hint.is_none()
{
return None;
}
// The pane itself, never something drawn over it (search, copy mode, the
@@ -570,7 +653,7 @@ pub fn plan_for(pane: &Arc<dyn Pane>, active: bool) -> Option<Arc<Plan>> {
return plan.clone();
}
}
let plan = compute(pane, active, &options, notice, &cursor, &dims).map(Arc::new);
let plan = compute(pane, active, &options, notice, hint, &cursor, &dims).map(Arc::new);
let mut plans = PLANS.lock();
if plans.len() > 256 {
plans.clear();
+64 -3
View File
@@ -61,8 +61,8 @@ fn colors(table: Option<Table>) -> mlua::Result<Colors> {
pub fn register(lua: &Lua) -> anyhow::Result<()> {
let module = get_or_create_sub_module(lua, "llembas")?;
// configure { suggestions =, highlight =, ai_complete =, cli =, history =,
// history_max =, colors = { … } }
// configure { suggestions =, highlight =, ai_complete =, cli =, ac_model =,
// ac_timeout_ms =, history =, history_max =, colors = { … } }
module.set(
"configure",
lua.create_function(|_, table: Table| {
@@ -75,11 +75,23 @@ pub fn register(lua: &Lua) -> anyhow::Result<()> {
.get::<_, Option<bool>>("ai_complete")?
.unwrap_or(false),
cli: table.get::<_, Option<String>>("cli")?.unwrap_or_default(),
ac_model: table
.get::<_, Option<String>>("ac_model")?
.unwrap_or_default()
.chars()
.filter(|c| !c.is_control())
.take(128)
.collect(),
ac_timeout_ms: table.get::<_, Option<u64>>("ac_timeout_ms")?.unwrap_or(0),
history: table.get::<_, Option<bool>>("history")?.unwrap_or(false),
history_max: table.get::<_, Option<usize>>("history_max")?.unwrap_or(0),
colors: colors(table.get::<_, Option<Table>>("colors")?)?,
};
state::set_options(options);
if options != state::options() {
// another model, another engine: a line may be asked about again
super::complete::forget_answers();
state::set_options(options);
}
Ok(())
})?,
)?;
@@ -128,6 +140,55 @@ pub fn register(lua: &Lua) -> anyhow::Result<()> {
})?,
)?;
// hint(pane id, text or nil, gentle, source pane id or nil): a word that
// stands at the cursor's row of the pane until it is taken away (nil), or
// until the pane it tells of (the display) is gone. Drawn, never written.
module.set(
"hint",
lua.create_function(
|_,
(pane_id, text, gentle, source): (
usize,
Option<String>,
Option<bool>,
Option<usize>,
)| {
let text: String = text
.unwrap_or_default()
.chars()
.filter(|c| !c.is_control())
.take(200)
.collect();
let hint = if text.trim().is_empty() {
None
} else {
Some(state::Hint {
text,
gentle: gentle.unwrap_or(false),
source,
})
};
state::set_hint(pane_id, hint);
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.
module.set(
"complete_status",
lua.create_function(|_, _: ()| Ok(super::complete::status()))?,
)?;
// data_dir(): the terminal's own data directory, the person's alone.
module.set(
"data_dir",
lua.create_function(|_, _: ()| Ok(config::DATA_DIR.to_string_lossy().into_owned()))?,
)?;
// set_private(pane id, on): a private pane's commands are not remembered
// and nothing of it is sent to LLeMbas for a completion.
module.set(
+60
View File
@@ -63,6 +63,10 @@ pub struct Options {
pub ai_complete: bool,
/// The path of the LLeMbas CLI; empty when there is none.
pub cli: String,
/// The autocomplete model chosen in the terminal; empty for the engine's own.
pub ac_model: String,
/// How long the engine is given for a completion; 0 for the default.
pub ac_timeout_ms: u64,
pub history: bool,
pub history_max: usize,
pub colors: Colors,
@@ -82,6 +86,8 @@ lazy_static::lazy_static! {
static ref PRIVATE: Mutex<HashSet<PaneId>> = Mutex::new(HashSet::new());
/// A word for the person at the cursor's row of a pane, and until when.
static ref NOTICES: Mutex<HashMap<PaneId, (String, Instant)>> = 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<HashMap<PaneId, Hint>> = Mutex::new(HashMap::new());
static ref COMMANDS: Mutex<Option<Commands>> = Mutex::new(None);
/// Where the command last remembered for a pane stood on its screen.
static ref REMEMBERED: Mutex<HashMap<PaneId, (StableRowIndex, usize)>> =
@@ -154,6 +160,60 @@ pub fn notice(pane_id: PaneId) -> Option<String> {
live
}
/// 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.
#[derive(Debug, Clone, PartialEq)]
pub struct Hint {
pub text: String,
/// Drawn dimmed and only where nothing else is: beside what the row
/// shows, or on the empty row below. It never covers a cell that shows
/// something.
pub gentle: bool,
/// The pane whose state it tells (the display). When that pane is gone,
/// so is the hint.
pub source: Option<PaneId>,
}
/// Set the standing word of a pane, or take it away.
pub fn set_hint(pane_id: PaneId, hint: Option<Hint>) {
let mut hints = HINTS.lock();
let same = hints.get(&pane_id) == hint.as_ref();
if same {
return;
}
match hint {
Some(hint) => {
if hints.len() > 256 {
hints.clear();
}
hints.insert(pane_id, hint);
}
None => {
hints.remove(&pane_id);
}
}
drop(hints);
changed();
}
/// The standing word of a pane, while the pane it tells of is there.
pub fn hint(pane_id: PaneId) -> Option<Hint> {
let mut hints = HINTS.lock();
let hint = hints.get(&pane_id)?.clone();
if let Some(source) = hint.source {
let there = match mux::Mux::try_get() {
Some(mux) => mux.get_pane(source).is_some(),
None => false,
};
if !there {
hints.remove(&pane_id);
return None;
}
}
Some(hint)
}
/// The file of the terminal's own command history: in its own data
/// directory, the person's alone.
pub fn history_path() -> PathBuf {