Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
03f0f34dce
|
||
|
|
b803aa39d9
|
||
|
|
03f4e2b9dc
|
||
|
|
6e55ec7ebf
|
||
|
|
dc630ca398
|
||
|
|
3839c7311c
|
||
|
|
26e836d9e9
|
No files matched your search
@@ -3,6 +3,70 @@
|
||||
What changed in each release of LLeMbas TTY. WezTerm's own changes are in
|
||||
`docs/changelog.md`, as upstream keeps them.
|
||||
|
||||
## 1.0.0-beta.5 — 2026-12-02
|
||||
|
||||
### Fixed
|
||||
|
||||
- **AI autocomplete never asked.** The terminal started the engine without the pane's
|
||||
directory, which the engine requires: the directory was taken from what the shell
|
||||
integration reports (`file://<host><directory>`) in a way that fails for every address
|
||||
that names a host — which is every one the integration writes. The engine ended with a
|
||||
usage error, its error output was discarded, and nothing was shown: no suggestion, no
|
||||
request to the server, no word about it. The directory is now read correctly (so are the
|
||||
paths that the highlighting marks as existing, which had the same fault for relative
|
||||
paths), and when there is none the person's home is given.
|
||||
- **What an attempt gave is never silent.** The engine's own sentence — not logged in, no
|
||||
model chosen, a timeout — is kept and shown by *LLeMbas: autocomplete status*, and written
|
||||
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 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
|
||||
for as long as the display asks, moves with you to another pane of the tab, and goes when
|
||||
it is answered or the display closes.
|
||||
|
||||
### Added
|
||||
|
||||
- **Settings are remembered, for this machine and for a working directory.** Every switch
|
||||
and choice — AI, AI autocomplete, suggestions, highlighting, mode, chat model,
|
||||
autocomplete model, display width — is in the command palette twice: *— here* for the
|
||||
pane's directory, *— everywhere* for the machine; the directory's own wins. A key keeps
|
||||
the choice where this directory's settings already are. The settings of the active pane's
|
||||
directory apply, and follow you from directory to directory. Kept by the LLeMbas CLI
|
||||
(`lembas terminal settings`, CLI 2.0.0-beta.20 or newer) in its own directory on this
|
||||
machine; with an older CLI a choice holds until the terminal closes, said once. The
|
||||
options in the configuration file are the starting values: a value set through the
|
||||
terminal wins.
|
||||
- **LLeMbas: settings** — what applies in this pane and where each value comes from, with a
|
||||
line that forgets the directory's own.
|
||||
- **LLeMbas: autocomplete status** — whether the AI's autocomplete is on and by whose
|
||||
choice, the engine and model it would use, and the last attempts: when, for which line,
|
||||
how long, and what came back.
|
||||
- **LLeMbas: display width** — the display's part of the pane.
|
||||
- **Manual mode without an approval card** (with a CLI that places commands, 2.0.0-beta.20
|
||||
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-<n>.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
|
||||
|
||||
- `llembas-line` gains `complete`: whether a line is asked about and why not, the directory
|
||||
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.
|
||||
- `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
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -35,10 +35,16 @@ WezTerm — see `LICENSE.md`.
|
||||
its own: it shows what LLeMbas says, the tools it uses that are not the shell, and what it
|
||||
asks you. `Ctrl+Shift+D` hides and shows it.
|
||||
- **Commands happen in your pane.** When LLeMbas runs a command it is typed at your prompt
|
||||
as if you typed it, and its output is in your scrollback. In *manual* mode every command
|
||||
is asked first; `Ctrl+Shift+Y` allows, `Ctrl+Shift+J` denies, from your own pane. In *auto*
|
||||
mode the commands the CLI's rules allow are typed without asking. There are no file-edit
|
||||
tools here: this is for terminal work, and the CLI or the IDE are a key away.
|
||||
as if you typed it, and its output is in your scrollback. In *manual* mode the command is
|
||||
placed at your prompt and not entered: `Enter` runs it, you may change it first, and
|
||||
`Ctrl+C` (or clearing the line) dismisses it — a dimmed hint beside it says so, and no
|
||||
approval card stands in the way. In *auto* mode the commands the CLI's rules allow are
|
||||
typed and entered without asking. (With a LLeMbas CLI older than 2.0.0-beta.20, manual mode
|
||||
asks in the display before typing: `Ctrl+Shift+Y` allows, `Ctrl+Shift+J` denies, from your
|
||||
own pane.) Whatever else LLeMbas asks — a question, a permission for a tool that is not
|
||||
the shell — stands at your cursor's row with the keys that answer it, until it is answered.
|
||||
There are no file-edit tools here: this is for terminal work, and the CLI or the IDE are a
|
||||
key away.
|
||||
- **The CLI itself, whole.** `Ctrl+Shift+S` opens `lembas` in a new tab, in the pane's
|
||||
directory, exactly as if you had typed it.
|
||||
- **AI on and off.** `Ctrl+Shift+I` switches all of it at any moment; the option `ai` says
|
||||
@@ -52,28 +58,37 @@ WezTerm — see `LICENSE.md`.
|
||||
else just goes on typing;
|
||||
- *colours*: the command (when it exists), options, strings, variables, the signs between
|
||||
commands, comments, and paths that exist;
|
||||
- *AI autocomplete*, off unless you turn it on: when your history has nothing for the
|
||||
line, LLeMbas is asked after a pause and its answer shows in the same place, in italics.
|
||||
- *AI autocomplete*, off unless you turn it on (*LLeMbas: AI autocomplete on/off* in the
|
||||
command palette; choose its model with *LLeMbas: choose autocomplete model*): when your
|
||||
history has nothing for the line, LLeMbas is asked after a pause and its answer shows in
|
||||
the same place, in italics. *LLeMbas: autocomplete status* says in words whether it is
|
||||
on, which engine and model it uses, and what the last attempts gave — a suggestion,
|
||||
nothing, a timeout, or the engine's own error sentence.
|
||||
- **Your choices are remembered** — for this machine, and for a working directory where you
|
||||
want it different there. See *Settings* below.
|
||||
|
||||
| Key | Command palette (`Ctrl+Shift+P`) | What it does |
|
||||
|---|---|---|
|
||||
| `Ctrl+Shift+A` | LLeMbas: ask the model | The ask line. The question goes with the *terminal context* of your pane (below). |
|
||||
| | LLeMbas: ask about this screen | The same, with what is visible on the screen instead of the last commands — also from a full-screen program. |
|
||||
| `Ctrl+Shift+S` | LLeMbas: open the CLI | `lembas`, whole, in a new tab. |
|
||||
| `Ctrl+Shift+I` | LLeMbas: AI on/off | The switch. |
|
||||
| `Ctrl+Shift+I` | LLeMbas: AI on/off — here / — everywhere | The switch. |
|
||||
| `Ctrl+Shift+Y` | LLeMbas: approve (allow once) | Answers what LLeMbas asks, from your pane. |
|
||||
| | LLeMbas: approve always | Where the question offers it (never for a command typed into your pane). |
|
||||
| `Ctrl+Shift+J` | LLeMbas: deny | |
|
||||
| `Ctrl+Shift+G` | LLeMbas: stop the turn | |
|
||||
| | LLeMbas: new conversation | A tab has one conversation, which goes on until you start a new one. |
|
||||
| `Ctrl+Shift+D` | LLeMbas: show/hide the display | Hidden, it runs on behind your pane. |
|
||||
| | LLeMbas: choose model | The terminal's own chat model, from your server's list. |
|
||||
| | LLeMbas: choose autocomplete model | The terminal's own autocomplete model. |
|
||||
| | LLeMbas: choose mode | *manual* or *auto*. |
|
||||
| | LLeMbas: choose model — here / — everywhere | The terminal's own chat model, from your server's list. |
|
||||
| | LLeMbas: choose autocomplete model — here / — everywhere | The terminal's own autocomplete model. |
|
||||
| | LLeMbas: choose mode — here / — everywhere | *manual* or *auto*. |
|
||||
| | LLeMbas: display width — here / — everywhere | The display's part of the pane, from the next time it opens. |
|
||||
| `Ctrl+Shift+H` | LLeMbas: private pane on/off | Nothing of the pane is passed on, and its commands are not remembered. |
|
||||
| | LLeMbas: suggestions on/off | |
|
||||
| | LLeMbas: syntax highlighting on/off | |
|
||||
| | LLeMbas: AI autocomplete on/off | |
|
||||
| | LLeMbas: suggestions on/off — here / — everywhere | |
|
||||
| | LLeMbas: syntax highlighting on/off — here / — everywhere | |
|
||||
| | LLeMbas: AI autocomplete on/off — here / — everywhere | |
|
||||
| | LLeMbas: settings | What applies in this pane and where each value comes from; forgets this directory's own. |
|
||||
| | LLeMbas: autocomplete status | The AI's autocomplete in words: on or off, engine, model, the last attempts. |
|
||||
| | LLeMbas: clear command history | |
|
||||
| | LLeMbas: log in | `lembas login`, in a new tab. |
|
||||
| `Ctrl+Shift+E` | LLeMbas: open LLeMbas IDE here | LLeMbas IDE in a new tab, in the pane's directory. |
|
||||
@@ -131,13 +146,53 @@ 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 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.
|
||||
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 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
|
||||
|
||||
What you switch and choose in the terminal is remembered: AI on or off, AI autocomplete,
|
||||
suggestions, highlighting, the mode, the chat model, the autocomplete model and the display's
|
||||
width. Each is in the command palette twice:
|
||||
|
||||
- **… — here** keeps it for the working directory of the pane you are in;
|
||||
- **… — everywhere** keeps it for this machine.
|
||||
|
||||
A directory's own value wins over the machine's there. A key (`Ctrl+Shift+I`, or one you gave
|
||||
to `model` or `mode`) keeps the choice *here* when this directory already has settings of
|
||||
its own, and *everywhere* otherwise; the word shown at your cursor says which. The settings
|
||||
of the directory of the pane you are in apply: change directory, or pane, and the
|
||||
suggestions, the colours, the autocomplete, the model and mode on the ask line and what the
|
||||
next display starts with follow.
|
||||
|
||||
**LLeMbas: settings** lists what applies now and where each value comes from — *here* (with
|
||||
the directory), *everywhere*, or the configuration — and has a line that forgets this
|
||||
directory's own settings.
|
||||
|
||||
They are kept by the LLeMbas CLI in its own directory on this machine (its README has the
|
||||
path and the commands: `lembas terminal settings`), not in the working directory, and are
|
||||
sent nowhere. Nothing is read until your first LLeMbas key or palette entry; once you have
|
||||
chosen something through the terminal, they are read at the first prompt, so that they hold
|
||||
from the start. The options in your configuration file are the starting values only: a value
|
||||
you set through the terminal wins over the file, until you remove it (*LLeMbas: settings*,
|
||||
or `lembas terminal settings set … <key>=default`).
|
||||
|
||||
With a LLeMbas CLI that has no such store (before 2.0.0-beta.20) everything works as before:
|
||||
a choice holds until the terminal closes, and the terminal says once that remembering it
|
||||
needs a newer CLI.
|
||||
|
||||
**Kept on this machine, sent nowhere:**
|
||||
|
||||
@@ -191,6 +246,8 @@ require('llembas').apply(config, {
|
||||
ide = { key = 'E', mods = 'CTRL|SHIFT' },
|
||||
ask_screen = false, always = false, new = false, model = false, mode = false,
|
||||
},
|
||||
-- (ai, mode, display.width, suggestions, highlight and autocomplete are starting values:
|
||||
-- what you choose in the terminal is remembered and wins - see Settings)
|
||||
display = { width = 0.33 }, -- of the pane it opens beside
|
||||
mode = 'manual', -- the mode a display starts in; or 'auto'
|
||||
context = {
|
||||
@@ -203,6 +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 = 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,
|
||||
|
||||
+64
-1
@@ -99,7 +99,10 @@ 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 <model>` | `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-<n>.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 of `lembas complete --shell <bash\|zsh\|fish> [--cwd <dir>] --timeout-ms 2500` | `wezterm-gui/src/llembas/complete.rs` | prints only the rest; nothing means no suggestion |
|
||||
| asks for the rest of a line: the line on standard input (then closed) of `lembas complete --shell <bash\|zsh\|fish> --cwd <dir> --timeout-ms <n> [--model <id>] [--debug]`, with `LLEMBAS_TTY` set; `<n>` 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 <dir> --json` → `{ effective = { <key> = <value> }, from = { <key> = "default" \| "global" \| "<directory>" }, directory = { path } \| null }`; `lembas terminal settings set (--global \| --cwd <dir>) --json <key>=<value>` (`default` removes it); `lembas terminal settings forget --cwd <dir> --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-<n>.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 <the command>` | `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 `<runtime directory>/llembas-tty/status-<process id of the terminal>`:
|
||||
two terminals number their panes alike, so each keeps its records apart. Directories of
|
||||
@@ -117,6 +120,58 @@ named `context-<unix seconds>-<random>.json`:
|
||||
It is still version 1 (which the CLI reads): `exit` is `null`, and the blocks carry no
|
||||
`seq`. Files older than ten minutes are removed the next time one is written.
|
||||
|
||||
### Settings: when the engine is asked
|
||||
|
||||
`init.lua` (*What the person chose, remembered*). `M.value(key)` is the one place a setting
|
||||
is read: the store's value for the directory that applies (`directory`, then `global`), else
|
||||
what was chosen in this run (`session`: a CLI without the store, or a write it refused),
|
||||
else the options (`config`). A store value whose source is `default` is not used: the
|
||||
options are the defaults.
|
||||
|
||||
- Nothing is read at start-up. `settings_awake`: from the first key or palette entry of
|
||||
LLeMbas in this run — or from the first prompt, when the empty file `settings-chosen` in
|
||||
the terminal's data directory says the person chose something through the terminal before
|
||||
(written at the first successful `set`).
|
||||
- `follow(pane)` makes the settings of the active pane's directory the ones that apply: at a
|
||||
new prompt of the active pane (the status record), at `update-status` (the active pane
|
||||
changed) and at every key of LLeMbas. What the store said of a directory is kept for a
|
||||
minute (`wezterm.GLOBAL`, at most 64 directories); the whole of it is dropped after one of
|
||||
our own writes. A directory whose shell reports another host is not asked about.
|
||||
- Every call of the engine is `wezterm.run_child_process` inside an event handler, which is
|
||||
asynchronous: the window's thread is never held.
|
||||
- A change of the applying settings goes to the terminal's own part (`configure`), to the
|
||||
ask line's prefix and to the next display's arguments (`-m`, `--mode`, the split's size).
|
||||
A display that runs is not changed by a change of directory.
|
||||
|
||||
### A word that stands
|
||||
|
||||
`wezterm.llembas.hint(pane id, text | nil, gentle, source pane id)` keeps a word at the
|
||||
cursor's row of a pane until it is taken away, or until the source pane (the display) is
|
||||
gone. `sync_hint` in `init.lua` makes it what the display says now (`lembas_ask`): at the
|
||||
display's user variables and at `update-status`. An approval or a question may be drawn
|
||||
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: 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); 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
|
||||
|
||||
`wezterm-gui/src/llembas/decorate.rs`, at the moment a pane is painted: the rows near the
|
||||
@@ -133,6 +188,14 @@ and when the options are off. The suggestion is drawn only in the pane that has
|
||||
keyboard, over blank cells only. Whether a command or a path exists is looked up only for a
|
||||
local pane whose shell reports this machine as its host.
|
||||
|
||||
The AI's suggestion: `llembas_line::complete::decide` says whether the line is asked about
|
||||
and, when not, why (`Skip`); `Tracker` allows one request at a time and remembers the answer
|
||||
for a line; `run` starts the engine (standard library only, so `cargo test -p llembas-line`
|
||||
runs it against a stand-in script); `Log` keeps the last eight attempts in memory for
|
||||
`wezterm.llembas.complete_status()`. The pane's directory is decoded from the path of the
|
||||
address its shell reported (`dir_of_url_path`): the URL library's own conversion to a file
|
||||
path refuses every address that names a host, and the shell integration always names one.
|
||||
|
||||
## Checking a change without building
|
||||
|
||||
```
|
||||
|
||||
@@ -0,0 +1,977 @@
|
||||
//! 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 = 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;
|
||||
/// 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)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// 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,
|
||||
/// 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.
|
||||
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());
|
||||
}
|
||||
if req.debug {
|
||||
args.push("--debug".to_string());
|
||||
}
|
||||
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 {
|
||||
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<String>) {
|
||||
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<String>) -> 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();
|
||||
// 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() {
|
||||
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 {
|
||||
/// What the engine said of its decisions at the newest attempt.
|
||||
decisions: Vec<String>,
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
/// What the engine said of its decisions at the attempt just kept.
|
||||
pub fn decisions(&mut self, lines: Vec<String>) {
|
||||
self.decisions = lines;
|
||||
}
|
||||
|
||||
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 !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 {}: {}",
|
||||
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(),
|
||||
debug: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[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",
|
||||
"8000"
|
||||
]
|
||||
);
|
||||
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");
|
||||
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);
|
||||
}
|
||||
|
||||
#[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::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: &PathBuf| 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));
|
||||
|
||||
// 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",
|
||||
"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);
|
||||
}
|
||||
}
|
||||
@@ -4,15 +4,20 @@
|
||||
//! - [`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
|
||||
//! 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 mark;
|
||||
pub mod suggest;
|
||||
pub mod tokens;
|
||||
pub mod zone;
|
||||
@@ -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=<the status record's id>
|
||||
//! seq=<the status record's 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<String> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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")];
|
||||
|
||||
@@ -22,7 +22,11 @@ M.CONTRACT = 2
|
||||
M.CAP = {
|
||||
display = 'terminal_surface', -- `lembas terminal`, the display
|
||||
models = 'terminal_models', -- `lembas terminal models`
|
||||
settings = 'terminal_settings', -- `lembas terminal settings`: what the person chose, remembered
|
||||
placed = 'terminal_placed', -- manual mode: a command placed at the prompt, not entered
|
||||
}
|
||||
-- The contract a part came with, where that is later than M.CONTRACT.
|
||||
M.CAP_CONTRACT = { settings = 3, placed = 3 }
|
||||
|
||||
M.LIMITS = {
|
||||
max_blocks = 20, -- the most command blocks a context may carry
|
||||
@@ -138,6 +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). 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,
|
||||
@@ -492,6 +500,7 @@ function M.options(user)
|
||||
o.mode = d.mode
|
||||
end
|
||||
o.history.max = math.floor(clamp(o.history.max, 0, 100000, d.history.max))
|
||||
o.autocomplete_timeout_ms = math.floor(clamp(o.autocomplete_timeout_ms, 500, 30000, d.autocomplete_timeout_ms))
|
||||
for name, default in pairs(M.COLORS) do
|
||||
if not M.is_color(o.colors[name]) then
|
||||
warnings[#warnings + 1] = 'colors.' .. name .. ": expected a palette number 0-255, '#rrggbb' or false"
|
||||
@@ -575,6 +584,10 @@ function M.session_from_vars(vars)
|
||||
return s
|
||||
end
|
||||
|
||||
-- THE word the display's `lembas_ask` starts with while a command it placed at
|
||||
-- the person's prompt waits for them, in one place.
|
||||
M.PLACED_KIND = 'placed'
|
||||
|
||||
-- What the display asks of the person now, from its `lembas_ask` variable:
|
||||
-- "<kind> <keys> <text>", as in "approval yn terminal_run: make test".
|
||||
-- nil when nothing is asked (or the value is not that).
|
||||
@@ -583,6 +596,12 @@ function M.parse_ask(value)
|
||||
return nil
|
||||
end
|
||||
local line = M.one_line(value, 200)
|
||||
-- A command placed at the person's prompt, which waits for them to run it,
|
||||
-- change it or dismiss it: "placed <the command>". It takes no key of ours.
|
||||
local placed = line == M.PLACED_KIND and '' or line:match('^' .. M.PLACED_KIND .. ' (.*)$')
|
||||
if placed then
|
||||
return { kind = 'placed', keys = '', text = placed }
|
||||
end
|
||||
local kind, keys, text = line:match('^(%a+) (%S+) ?(.*)$')
|
||||
if kind ~= 'approval' and kind ~= 'question' then
|
||||
return nil
|
||||
@@ -1086,7 +1105,8 @@ end
|
||||
|
||||
-- Does that CLI have this part (a key of M.CAP)?
|
||||
function M.cli_has(info, part)
|
||||
return type(info) == 'table' and info.contract >= M.CONTRACT and info.has[M.CAP[part]] == true
|
||||
local contract = M.CAP_CONTRACT[part] or M.CONTRACT
|
||||
return type(info) == 'table' and info.contract >= contract and info.has[M.CAP[part]] == true
|
||||
end
|
||||
|
||||
function M.version_json_args(cli)
|
||||
@@ -1224,6 +1244,205 @@ function M.terminal_models(decoded)
|
||||
return out
|
||||
end
|
||||
|
||||
----------------------------------------------------------------------------
|
||||
-- What the person chose, remembered: the engine's store of the terminal's
|
||||
-- settings (`lembas terminal settings`), for this machine and for a working
|
||||
-- directory. Everything the terminal assumes of it is in this part.
|
||||
|
||||
-- The settings, in the order they are shown. kind: 'switch' (on or off),
|
||||
-- 'mode', 'model', 'width' (the display's part of the pane).
|
||||
M.SETTINGS = {
|
||||
{ key = 'ai', kind = 'switch', name = 'AI' },
|
||||
{ key = 'autocomplete', kind = 'switch', name = 'AI autocomplete' },
|
||||
{ key = 'suggestions', kind = 'switch', name = 'suggestions' },
|
||||
{ key = 'highlight', kind = 'switch', name = 'syntax highlighting' },
|
||||
{ key = 'mode', kind = 'mode', name = 'mode' },
|
||||
{ key = 'main_model', kind = 'model', name = 'chat model' },
|
||||
{ key = 'autocomplete_model', kind = 'model', name = 'autocomplete model' },
|
||||
{ key = 'display_width', kind = 'width', name = 'display width' },
|
||||
}
|
||||
|
||||
M.SETTING = {}
|
||||
for _, s in ipairs(M.SETTINGS) do
|
||||
M.SETTING[s.key] = s
|
||||
end
|
||||
|
||||
-- what the store takes for the display's width
|
||||
M.WIDTH_MIN, M.WIDTH_MAX = 0.2, 0.6
|
||||
|
||||
-- A value of a setting as the layer keeps it, from what the store said or
|
||||
-- what the person picked; nil when it is not a value of that setting.
|
||||
function M.setting_value(key, v)
|
||||
local s = M.SETTING[key]
|
||||
if not s then
|
||||
return nil
|
||||
end
|
||||
if s.kind == 'switch' then
|
||||
if v == true or v == 'true' or v == 'on' then
|
||||
return true
|
||||
elseif v == false or v == 'false' or v == 'off' then
|
||||
return false
|
||||
end
|
||||
return nil
|
||||
elseif s.kind == 'mode' then
|
||||
return M.MODES[v] and v or nil
|
||||
elseif s.kind == 'model' then
|
||||
return M.is_model_ref(v) and v or nil
|
||||
elseif s.kind == 'width' then
|
||||
local n = tonumber(v)
|
||||
if not n or n ~= n or n <= 0 then
|
||||
return nil
|
||||
end
|
||||
-- a part of the pane, or the same in percent
|
||||
if n > 1 then
|
||||
n = n / 100
|
||||
end
|
||||
if n < M.WIDTH_MIN or n > M.WIDTH_MAX then
|
||||
return nil
|
||||
end
|
||||
return n
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- A value as it is written on the engine's command line; nil when it is none.
|
||||
function M.setting_text(key, v)
|
||||
v = M.setting_value(key, v)
|
||||
if v == nil then
|
||||
return nil
|
||||
end
|
||||
if type(v) == 'boolean' then
|
||||
return v and 'true' or 'false'
|
||||
elseif type(v) == 'number' then
|
||||
return string.format('%.2f', v)
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
-- A value as the person reads it.
|
||||
function M.setting_shown(key, v)
|
||||
local s = M.SETTING[key]
|
||||
if v == nil or not s then
|
||||
return s and s.kind == 'model' and "the engine's own choice" or 'not set'
|
||||
end
|
||||
if type(v) == 'boolean' then
|
||||
return v and 'on' or 'off'
|
||||
elseif type(v) == 'number' then
|
||||
return string.format('%d%%', math.floor(v * 100 + 0.5))
|
||||
end
|
||||
return M.one_line(tostring(v), 64)
|
||||
end
|
||||
|
||||
-- THE commands of the store, in one place.
|
||||
function M.settings_args(cli, cwd)
|
||||
return { cli, 'terminal', 'settings', '--cwd', cwd, '--json' }
|
||||
end
|
||||
|
||||
-- level: 'here' (the directory `cwd`) or 'everywhere' (this machine).
|
||||
-- value nil: the key is removed at that level. nil when there is nothing to run.
|
||||
function M.settings_set_args(cli, level, cwd, key, value)
|
||||
if not M.SETTING[key] then
|
||||
return nil
|
||||
end
|
||||
local text = 'default'
|
||||
if value ~= nil then
|
||||
text = M.setting_text(key, value)
|
||||
if not text then
|
||||
return nil
|
||||
end
|
||||
end
|
||||
local args = { cli, 'terminal', 'settings', 'set' }
|
||||
if level == 'here' then
|
||||
if type(cwd) ~= 'string' or cwd:sub(1, 1) ~= '/' then
|
||||
return nil
|
||||
end
|
||||
args[#args + 1] = '--cwd'
|
||||
args[#args + 1] = cwd
|
||||
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, '--json' }
|
||||
end
|
||||
|
||||
-- What `lembas terminal settings --cwd <dir> --json` printed, decoded, as the
|
||||
-- flat table the layer keeps for a directory:
|
||||
-- directory = <the path of the directory's own entry>, or '' when it has none
|
||||
-- v_<key> = the value that applies (absent: none)
|
||||
-- f_<key> = where it comes from: 'default', 'global' or 'directory'
|
||||
-- p_<key> = for 'directory', the path of the entry it comes from
|
||||
-- nil when it is not that. Only values of the right kind are kept; a value
|
||||
-- that is not one counts as "default", so a store this layer does not
|
||||
-- understand changes nothing.
|
||||
function M.settings_entry(decoded)
|
||||
if type(decoded) ~= 'table' or type(decoded.effective) ~= 'table' then
|
||||
return nil
|
||||
end
|
||||
local from = type(decoded.from) == 'table' and decoded.from or {}
|
||||
local e = { directory = '' }
|
||||
if type(decoded.directory) == 'table' and type(decoded.directory.path) == 'string' then
|
||||
e.directory = M.one_line(decoded.directory.path, 1024)
|
||||
end
|
||||
for _, s in ipairs(M.SETTINGS) do
|
||||
local v = M.setting_value(s.key, decoded.effective[s.key])
|
||||
local f = from[s.key]
|
||||
if v == nil or type(f) ~= 'string' or f == '' or f == 'default' then
|
||||
e['f_' .. s.key] = 'default'
|
||||
if v ~= nil then
|
||||
e['v_' .. s.key] = v
|
||||
end
|
||||
elseif f == 'global' then
|
||||
e['f_' .. s.key] = 'global'
|
||||
e['v_' .. s.key] = v
|
||||
else
|
||||
e['f_' .. s.key] = 'directory'
|
||||
e['p_' .. s.key] = M.one_line(f, 1024)
|
||||
e['v_' .. s.key] = v
|
||||
end
|
||||
end
|
||||
return e
|
||||
end
|
||||
|
||||
-- Where a value comes from, as the person reads it.
|
||||
-- from: 'directory' | 'global' | 'default' | 'session' | 'config'
|
||||
function M.setting_source(from, path)
|
||||
if from == 'directory' then
|
||||
return 'here (' .. M.one_line(path or '', 60) .. ')'
|
||||
elseif from == 'global' then
|
||||
return 'everywhere'
|
||||
elseif from == 'session' then
|
||||
return 'until the terminal closes'
|
||||
elseif from == 'config' then
|
||||
return 'the configuration'
|
||||
end
|
||||
return 'default'
|
||||
end
|
||||
|
||||
-- One line of the settings list: "mode: auto · here (/home/me/project)".
|
||||
function M.setting_line(key, value, from, path)
|
||||
local s = M.SETTING[key]
|
||||
return string.format('%s: %s · %s', s and s.name or key, M.setting_shown(key, value), M.setting_source(from, path))
|
||||
end
|
||||
|
||||
-- Is `host`, as a pane's shell named the machine of its directory, the
|
||||
-- machine called `mine`? An empty host and localhost are; otherwise by name,
|
||||
-- whole or by the first label, without case. Unknown `mine`: taken as yes.
|
||||
function M.same_host(host, mine)
|
||||
if type(host) ~= 'string' or host == '' or host:lower() == 'localhost' then
|
||||
return true
|
||||
end
|
||||
if type(mine) ~= 'string' or mine == '' then
|
||||
return true
|
||||
end
|
||||
local a, b = host:lower(), mine:lower()
|
||||
return a == b or a:match('^[^%.]*') == b:match('^[^%.]*')
|
||||
end
|
||||
|
||||
-- What stands before the question on the ask line, so that the person sees
|
||||
-- which model and mode will answer before sending: "llembas qwen · auto".
|
||||
function M.ask_prefix(model, mode, screen)
|
||||
@@ -1474,6 +1693,20 @@ M.messages = {
|
||||
private_on = 'This pane is now private: nothing of it is passed to LLeMbas, and its commands are not remembered.',
|
||||
private_off = 'This pane is no longer private.',
|
||||
switched = '%s %s',
|
||||
-- where a choice was kept: appended to what was said
|
||||
kept_here = ' · here',
|
||||
kept_everywhere = ' · everywhere',
|
||||
kept_session = ' · until the terminal closes',
|
||||
remember_needs_cli = ' (remembering it needs a newer LLeMbas CLI: lembas update)',
|
||||
remember_failed = ' (it could not be kept: the LLeMbas CLI refused; it holds until the terminal closes)',
|
||||
placed = 'Enter runs · edit freely · Ctrl+C dismisses',
|
||||
placed_first = 'A command from LLeMbas waits at your prompt: Enter runs it, Ctrl+C dismisses it.',
|
||||
forgot = "This directory's own settings are forgotten.",
|
||||
nothing_to_forget = 'This directory has no settings of its own.',
|
||||
width_set = 'display width: %s (from the next time the display opens)',
|
||||
settings_session = 'These hold until the terminal closes: remembering them needs a newer LLeMbas CLI (lembas update).',
|
||||
settings_about = 'What applies in this pane, and where each comes from. A choice made "here" is kept for this directory, '
|
||||
.. 'one made "everywhere" for this machine; the directory\'s own wins.',
|
||||
history_cleared = 'The command history of this terminal is cleared.',
|
||||
needs_terminal = 'This is drawn by the terminal itself, and this build has no such part.',
|
||||
}
|
||||
|
||||
+725
-94
File diff suppressed because it is too large.
Load diff
@@ -101,12 +101,20 @@ 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', '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
|
||||
end
|
||||
end
|
||||
-- the terminal's side of the autocomplete in words, and its data directory
|
||||
-- (a test sets n.status_text and n.dir)
|
||||
function n.complete_status()
|
||||
return n.status_text or 'engine: none'
|
||||
end
|
||||
function n.data_dir()
|
||||
return n.dir or ''
|
||||
end
|
||||
function n.last(name)
|
||||
for i = #n.calls, 1, -1 do
|
||||
if n.calls[i][1] == name then
|
||||
|
||||
+495
-14
@@ -783,21 +783,26 @@ test('apply: keys, events, and nothing else happens', function()
|
||||
check(w.handlers[name] ~= nil, 'handler for ' .. name)
|
||||
end
|
||||
local entries = w.emit 'augment-command-palette'
|
||||
eq(#entries, 21, 'the palette entries')
|
||||
eq(#entries, 32, 'the palette entries')
|
||||
local names = {}
|
||||
for _, e in ipairs(entries) do
|
||||
names[e.brief] = e.action.args
|
||||
end
|
||||
eq(names['LLeMbas: ask the model'], 'llembas-ask', 'ask')
|
||||
eq(names['LLeMbas: open the CLI'], 'llembas-cli', 'open the CLI')
|
||||
eq(names['LLeMbas: AI on/off'], 'llembas-ai', 'the switch')
|
||||
eq(names['LLeMbas: AI on/off — here'], 'llembas-ai-here', 'the switch, kept for this directory')
|
||||
eq(names['LLeMbas: AI on/off — everywhere'], 'llembas-ai-everywhere', 'the switch, kept for this machine')
|
||||
eq(names['LLeMbas: AI autocomplete on/off — here'], 'llembas-autocomplete-here', 'so is every switch')
|
||||
eq(names['LLeMbas: display width — everywhere'], 'llembas-width-everywhere', 'and every choice')
|
||||
eq(names['LLeMbas: settings'], 'llembas-settings', 'what applies, and from where')
|
||||
eq(names['LLeMbas: autocomplete status'], 'llembas-autocomplete-status', 'the autocomplete in words')
|
||||
eq(names['LLeMbas: approve (allow once)'], 'llembas-approve', 'approve')
|
||||
eq(names['LLeMbas: deny'], 'llembas-deny', 'deny')
|
||||
eq(names['LLeMbas: stop the turn'], 'llembas-stop', 'stop')
|
||||
eq(names['LLeMbas: new conversation'], 'llembas-new', 'new')
|
||||
eq(names['LLeMbas: show/hide the display'], 'llembas-display', 'display')
|
||||
eq(names['LLeMbas: choose model'], 'llembas-model', 'model')
|
||||
eq(names['LLeMbas: choose mode'], 'llembas-mode', 'mode')
|
||||
eq(names['LLeMbas: choose model — here'], 'llembas-model-here', 'model')
|
||||
eq(names['LLeMbas: choose mode — everywhere'], 'llembas-mode-everywhere', 'mode')
|
||||
eq(names['LLeMbas: set up (CLI and IDE)'], 'llembas-setup', 'set-up')
|
||||
for _, e in ipairs(entries) do
|
||||
check(w.handlers[e.action.args] ~= nil, 'a handler behind ' .. e.brief)
|
||||
@@ -816,7 +821,11 @@ test('apply: everything can be turned off', function()
|
||||
keys = { ask = false, cli = false, ai = false, approve = false, deny = false, stop = false, display = false, private = false, ide = false },
|
||||
})
|
||||
eq(#config2.keys, 0, 'no keys')
|
||||
eq(w2.handlers['update-status'], nil, 'no bar')
|
||||
local win_off, pane_off = fake.window(), fake.pane { id = 1 }
|
||||
fake.tab { pane_off }
|
||||
w2.emit('update-status', win_off, pane_off)
|
||||
eq(win_off.status, nil, 'no bar')
|
||||
eq(#w2.spawned, 0, 'and looking at a pane starts nothing')
|
||||
eq(w2.handlers['format-tab-title'], nil, 'no tab mark')
|
||||
eq(w2.handlers['augment-command-palette'], nil, 'no palette')
|
||||
local _, w3 = layer({}, { nonsense = 1 })
|
||||
@@ -900,7 +909,7 @@ test('AI switch: said where the person is, and the terminal is told', function()
|
||||
local win, pane = fake.window(), fake.pane { id = 3 }
|
||||
w.emit('llembas-ai', win, pane)
|
||||
eq(l.is_on 'ai', false, 'off')
|
||||
eq(native.last 'notice'[3], 'AI off', 'said at the cursor, not in a dialog')
|
||||
eq(native.last 'notice'[3], 'AI off' .. core.messages.remember_needs_cli, 'said at the cursor, not in a dialog; and once, that it is not remembered')
|
||||
eq(#win.actions, 0, 'no overlay')
|
||||
eq(native.last 'configure'[2].ai_complete, false, 'the AI stops completing')
|
||||
eq(native.last 'configure'[2].suggestions, true, 'history suggestions are not AI')
|
||||
@@ -922,7 +931,7 @@ test('switches of what the terminal draws', function()
|
||||
w.emit('llembas-suggestions', win, pane)
|
||||
eq(l.is_on 'suggestions', false, 'off')
|
||||
eq(native.last 'configure'[2].suggestions, false, 'told')
|
||||
eq(native.last 'notice'[3], 'suggestions off', 'said')
|
||||
eq(native.last 'notice'[3], 'suggestions off' .. core.messages.remember_needs_cli, 'said')
|
||||
w.emit('llembas-highlight', win, pane)
|
||||
eq(native.last 'configure'[2].highlight, false, 'highlighting')
|
||||
w.emit('llembas-autocomplete', win, pane)
|
||||
@@ -1249,7 +1258,8 @@ test('the CLI whole: a new tab, never a split', function()
|
||||
eq(a.args.args[1], dir .. '/bin/lembas', 'the CLI')
|
||||
eq(a.args.cwd, '/home/u/proj', "in the pane's directory")
|
||||
eq(#pane.splits, 0, 'no split')
|
||||
eq(#w.spawned, 0, 'nothing started behind the person')
|
||||
eq(#w.spawned, 1, 'one thing started behind the person')
|
||||
eq(spawned(w, '--version --json'), 1, 'the CLI asked what it can do, at the first key of LLeMbas')
|
||||
w.emit('llembas-login', win, pane)
|
||||
eq(table.concat(win.actions[2].action.args.args, ' '), dir .. '/bin/lembas login', 'log in, in a tab too')
|
||||
end)
|
||||
@@ -1288,7 +1298,7 @@ test('approve, deny, always, stop: sent to the display while the person stays in
|
||||
eq(#cli_pane.sent, 0, "a key is never sent into the CLI's own interface")
|
||||
end)
|
||||
|
||||
test('the display asks: said where the person is', function()
|
||||
test('the display asks: said where the person is, for as long as it waits', function()
|
||||
local native = fake.native()
|
||||
local _, w = new_layer { native = native }
|
||||
local win = fake.window()
|
||||
@@ -1296,14 +1306,458 @@ test('the display asks: said where the person is', function()
|
||||
local display = fake.pane { id = 2, vars = { lembas_state = 'asking', lembas_surface = 'display' } }
|
||||
fake.tab { pane, display }
|
||||
win.active = pane
|
||||
w.emit('user-var-changed', win, display, 'lembas_ask', 'approval yn terminal_run: make\27[2J test')
|
||||
local call = native.last 'notice'
|
||||
eq(call[2], pane, "in the person's pane")
|
||||
display.vars.lembas_ask = 'approval yn terminal_run: make\27[2J test'
|
||||
w.emit('user-var-changed', win, display, 'lembas_ask', display.vars.lembas_ask)
|
||||
local call = native.last 'hint'
|
||||
eq(call[2], 1, "in the person's pane")
|
||||
eq(call[3], 'LLeMbas asks: terminal_run: make[2J test (Ctrl+Shift+Y allow, Ctrl+Shift+J deny)', 'what, and the keys; cleaned')
|
||||
local n = native.count 'notice'
|
||||
eq(call[4], false, 'it may stand over the end of the row: it is to be seen')
|
||||
eq(call[5], 2, 'and it goes when the display does')
|
||||
eq(native.count 'notice', 0, 'not a word that is gone in a moment')
|
||||
local n = native.count 'hint'
|
||||
w.emit('update-status', win, pane)
|
||||
w.emit('user-var-changed', win, display, 'lembas_state', 'asking')
|
||||
eq(native.count 'hint', n, 'it stands: not set again while nothing changed')
|
||||
-- answered: taken away
|
||||
display.vars.lembas_ask = ''
|
||||
display.vars.lembas_state = 'tools'
|
||||
w.emit('user-var-changed', win, display, 'lembas_ask', '')
|
||||
eq(native.last 'hint'[2], 1, 'the same pane')
|
||||
eq(native.last 'hint'[3], nil, 'nothing stands there now')
|
||||
n = native.count 'hint'
|
||||
w.emit('user-var-changed', win, pane, 'lembas_ask', 'approval yn from a pane that is no display')
|
||||
eq(native.count 'notice', n, 'nothing asked, or not the display: nothing said')
|
||||
eq(native.count 'hint', n, 'not the display: nothing said')
|
||||
-- the person is in another pane of the tab than the one the display was started from
|
||||
local other = fake.pane { id = 3 }
|
||||
fake.tab { pane, other, display }
|
||||
win.active = other
|
||||
display.vars.lembas_ask = 'question 12 Which one?'
|
||||
w.emit('user-var-changed', win, display, 'lembas_ask', display.vars.lembas_ask)
|
||||
eq(native.last 'hint'[2], 3, 'where the person is')
|
||||
-- AI off: nothing stands
|
||||
w.emit('llembas-ai', win, other)
|
||||
w.emit('update-status', win, other)
|
||||
eq(native.last 'hint'[3], nil, 'taken away with AI off')
|
||||
end)
|
||||
|
||||
test('manual mode: a command placed at the prompt, and a hint that covers nothing', function()
|
||||
local dir = fresh_dir 'placed'
|
||||
with_cli(dir)
|
||||
local native = fake.native()
|
||||
local _, w = new_layer { native = native }
|
||||
local win = fake.window()
|
||||
local pane = fake.pane { id = 1, zones = ZONES }
|
||||
fake.tab({ pane }, 4)
|
||||
win.active = pane
|
||||
w.emit('llembas-ask-line', win, pane, 'run the tests')
|
||||
local display = pane.last_split
|
||||
display.vars = { lembas_state = 'asking', lembas_surface = 'display', lembas_session = 's', lembas_ask = 'placed make test' }
|
||||
w.emit('user-var-changed', win, display, 'lembas_ask', 'placed make test')
|
||||
local call = native.last 'hint'
|
||||
eq(call[2], 1, 'in the pane the display was started from')
|
||||
eq(call[3], 'Enter runs · edit freely · Ctrl+C dismisses', 'what the person can do')
|
||||
eq(call[4], true, 'gentle: beside the command or below it, never over it')
|
||||
eq(#pane.sent, 0, 'drawn, never written to the pane')
|
||||
-- the keys that answer an approval have nothing to answer here
|
||||
w.emit('llembas-approve', win, pane)
|
||||
eq(#display.sent, 0, 'nothing sent to the display')
|
||||
check(native.last 'notice'[3]:find('Enter runs it', 1, true), 'said instead')
|
||||
-- and a new question waits for the person's decision
|
||||
w.emit('llembas-ask-line', win, pane, 'and then?')
|
||||
eq(#display.sent, 0, 'not sent while the command waits')
|
||||
-- the person ran it or dismissed it: the display says so, the hint goes
|
||||
display.vars.lembas_ask = nil
|
||||
display.vars.lembas_state = 'tools'
|
||||
w.emit('user-var-changed', win, display, 'lembas_ask', '')
|
||||
eq(native.last 'hint'[3], nil, 'gone')
|
||||
-- the hint belongs to one prompt: when the shell says the command runs, it is over at
|
||||
-- once, whenever the display comes to say so
|
||||
local function record(seq, state)
|
||||
return string.format('llembas-tty-status=1\nid=7.1\nseq=%d\nstate=%s\n', seq, state)
|
||||
end
|
||||
w.emit('user-var-changed', win, pane, 'llembas_tty_status', record(3, 'prompt'))
|
||||
display.vars.lembas_state = 'asking'
|
||||
display.vars.lembas_ask = 'placed make test'
|
||||
w.emit('user-var-changed', win, display, 'lembas_ask', 'placed make test')
|
||||
eq(native.last 'hint'[3], 'Enter runs · edit freely · Ctrl+C dismisses', 'placed again: shown again')
|
||||
w.emit('update-status', win, pane)
|
||||
eq(native.last 'hint'[3], 'Enter runs · edit freely · Ctrl+C dismisses', 'it stands while the prompt does')
|
||||
w.emit('user-var-changed', win, pane, 'llembas_tty_status', record(3, 'running'))
|
||||
eq(native.last 'hint'[3], nil, 'Enter was pressed: gone, though the display still says placed')
|
||||
w.emit('update-status', win, pane)
|
||||
eq(native.last 'hint'[3], nil, 'and it stays gone')
|
||||
-- left at the prompt after the wait: the hint stays, and a new question goes through
|
||||
display.vars.lembas_ask = ''
|
||||
w.emit('user-var-changed', win, display, 'lembas_ask', '')
|
||||
w.emit('user-var-changed', win, pane, 'llembas_tty_status', record(4, 'prompt'))
|
||||
display.vars.lembas_ask = 'placed make lint'
|
||||
display.vars.lembas_state = 'idle'
|
||||
w.emit('user-var-changed', win, display, 'lembas_ask', 'placed make lint')
|
||||
eq(native.last 'hint'[3], 'Enter runs · edit freely · Ctrl+C dismisses', 'still at the prompt')
|
||||
w.emit('llembas-ask-line', win, pane, 'what was that for?')
|
||||
eq(#display.sent, 1, 'a question is sent when the turn no longer waits')
|
||||
-- core: the word is in one place
|
||||
eq(core.parse_ask('placed git status --short').kind, 'placed', 'kind')
|
||||
eq(core.parse_ask('placed git status --short').text, 'git status --short', 'the command, whole')
|
||||
eq(core.parse_ask('placed').text, '', 'even with none')
|
||||
eq(core.parse_ask('placedx y z'), nil, 'another word is not it')
|
||||
end)
|
||||
|
||||
-- A CLI with the store of the terminal's settings (contract 3).
|
||||
JSON['INFO3'] = {
|
||||
name = 'lembas',
|
||||
version = '2.0.0-beta.20',
|
||||
terminal_contract = 3,
|
||||
capabilities = { 'terminal_surface', 'terminal_models', 'terminal_settings', 'terminal_placed' },
|
||||
}
|
||||
-- nothing chosen anywhere
|
||||
JSON['S_NONE'] = {
|
||||
cwd = '/home/u/proj',
|
||||
effective = { ai = true, autocomplete = false, suggestions = true, highlight = true, mode = 'manual', display_width = 0.33 },
|
||||
from = { ai = 'default', autocomplete = 'default', suggestions = 'default', highlight = 'default', mode = 'default', display_width = 'default' },
|
||||
global = {},
|
||||
}
|
||||
-- chosen for the machine, and this directory has its own
|
||||
JSON['S_PROJ'] = {
|
||||
cwd = '/home/u/proj',
|
||||
effective = {
|
||||
ai = true,
|
||||
autocomplete = true,
|
||||
suggestions = false,
|
||||
highlight = true,
|
||||
mode = 'auto',
|
||||
main_model = 'open/big',
|
||||
autocomplete_model = 'open/flash',
|
||||
display_width = 40,
|
||||
},
|
||||
from = {
|
||||
ai = 'default',
|
||||
autocomplete = 'global',
|
||||
suggestions = '/home/u/proj',
|
||||
highlight = 'default',
|
||||
mode = '/home/u/proj',
|
||||
main_model = 'global',
|
||||
autocomplete_model = 'global',
|
||||
display_width = '/home/u/proj',
|
||||
},
|
||||
global = { autocomplete = true },
|
||||
directory = { path = '/home/u/proj' },
|
||||
}
|
||||
-- another directory: only what was chosen for the machine
|
||||
JSON['S_OTHER'] = {
|
||||
cwd = '/home/u/other',
|
||||
effective = { ai = true, autocomplete = true, suggestions = true, highlight = true, mode = 'manual', main_model = 'open/big', autocomplete_model = 'open/flash' },
|
||||
from = { ai = 'default', autocomplete = 'global', suggestions = 'default', highlight = 'default', mode = 'default', main_model = 'global', autocomplete_model = 'global' },
|
||||
global = { autocomplete = true },
|
||||
}
|
||||
|
||||
local function store_layer(results, native, options)
|
||||
local r = { ['--version --json'] = { true, 'INFO3' }, ['terminal models --json'] = { true, 'MODELS' } }
|
||||
for k, v in pairs(results or {}) do
|
||||
r[k] = v
|
||||
end
|
||||
local l, w = layer({ child_results = r, json_parse = json_parse, native = native }, options)
|
||||
return l, w, r
|
||||
end
|
||||
|
||||
test('settings: what the store says, as the layer keeps it', function()
|
||||
local e = core.settings_entry(JSON['S_PROJ'])
|
||||
eq(e.directory, '/home/u/proj', 'the directory has settings of its own')
|
||||
eq(e.f_ai, 'default', 'never chosen')
|
||||
eq(e.f_autocomplete, 'global', 'chosen for the machine')
|
||||
eq(e.v_autocomplete, true, 'its value')
|
||||
eq(e.f_mode, 'directory', 'chosen for the directory')
|
||||
eq(e.p_mode, '/home/u/proj', 'which one')
|
||||
eq(e.v_display_width, 0.4, 'percent is a part of the pane')
|
||||
eq(core.settings_entry(JSON['S_NONE']).directory, '', 'no settings of its own')
|
||||
eq(core.settings_entry(nil), nil, 'not that')
|
||||
eq(core.settings_entry { effective = 'x' }, nil, 'nor that')
|
||||
-- a value that is none of that setting's counts as never chosen
|
||||
local odd = core.settings_entry {
|
||||
effective = { mode = 'edit', ai = 'maybe', main_model = 'x; rm -rf /', display_width = 7, suggestions = 'off' },
|
||||
from = { mode = 'global', ai = 'global', main_model = '/d', display_width = 'global', suggestions = 'global' },
|
||||
}
|
||||
eq(odd.f_mode, 'default', 'no edit mode here')
|
||||
eq(odd.v_mode, nil, 'and no value')
|
||||
eq(odd.f_ai, 'default', 'a switch is on or off')
|
||||
eq(odd.f_main_model, 'default', 'only what looks like a model')
|
||||
eq(odd.f_display_width, 'default', 'a width the display cannot have')
|
||||
eq(odd.v_suggestions, false, '"off" is off')
|
||||
-- values, to and fro
|
||||
eq(core.setting_text('ai', false), 'false', 'a switch on the command line')
|
||||
eq(core.setting_text('display_width', 0.4), '0.40', 'a width')
|
||||
eq(core.setting_text('mode', 'edit'), nil, 'not a mode')
|
||||
eq(core.setting_shown('display_width', 0.33), '33%', 'a width as read')
|
||||
eq(core.setting_shown('ai', true), 'on', 'a switch as read')
|
||||
eq(core.setting_shown('main_model', nil), "the engine's own choice", 'no model chosen')
|
||||
eq(core.setting_line('mode', 'auto', 'directory', '/home/u/proj'), 'mode: auto · here (/home/u/proj)', 'a line of the list')
|
||||
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 --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 --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')
|
||||
check(not core.cli_has(core.cli_info(JSON['INFO2']), 'settings'), 'a CLI without')
|
||||
local named_early = core.cli_info { version = 'x', terminal_contract = 2, capabilities = { 'terminal_settings' } }
|
||||
check(not core.cli_has(named_early, 'settings'), 'the name alone, under an older contract, is not it')
|
||||
-- whose machine a directory is on
|
||||
check(core.same_host('', 'workstation'), 'no host')
|
||||
check(core.same_host('localhost', 'workstation'), 'localhost')
|
||||
check(core.same_host('Workstation.example.org', 'workstation'), 'by the first label')
|
||||
check(not core.same_host('laptop', 'workstation'), 'another machine')
|
||||
check(core.same_host('laptop', nil), 'unknown: taken as this one')
|
||||
end)
|
||||
|
||||
test('settings: nothing is read until the first key of LLeMbas', function()
|
||||
local dir = fresh_dir 'lazy'
|
||||
with_cli(dir)
|
||||
local native = fake.native()
|
||||
native.dir = dir .. '/run'
|
||||
local l, w = store_layer({ ['terminal settings --cwd /home/u/proj --json'] = { true, 'S_PROJ' } }, native)
|
||||
local win, pane = fake.window(), fake.pane { id = 1, cwd = 'file://workstation/home/u/proj' }
|
||||
fake.tab { pane }
|
||||
win.active = pane
|
||||
eq(#w.spawned, 0, 'applying starts nothing')
|
||||
w.emit('update-status', win, pane)
|
||||
w.emit('user-var-changed', win, pane, 'llembas_tty_status', 'llembas-tty-status=1\nid=1.1\nseq=1\nstate=prompt\ncwd=/home/u/proj\n')
|
||||
eq(spawned(w, '--version --json') + spawned(w, 'terminal settings --cwd /home/u/proj --json'), 0, 'a prompt and a look start nothing either')
|
||||
eq(l.is_on 'suggestions', true, 'the options hold')
|
||||
-- the first key of LLeMbas: the settings of the pane's directory are read and apply
|
||||
w.emit('llembas-private', win, pane)
|
||||
eq(spawned(w, 'terminal settings --cwd /home/u/proj --json'), 1, 'read')
|
||||
eq(l.is_on 'suggestions', false, "the directory's own")
|
||||
eq(l.is_on 'autocomplete', true, "the machine's")
|
||||
local c = native.last 'configure'[2]
|
||||
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, 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
|
||||
w.emit('update-status', win, pane)
|
||||
w.emit('llembas-private', win, pane)
|
||||
eq(spawned(w, 'terminal settings --cwd /home/u/proj --json'), 1, 'once')
|
||||
end)
|
||||
|
||||
test('settings: chosen before, they hold from the first prompt, and follow the directory', function()
|
||||
local dir = fresh_dir 'follow'
|
||||
with_cli(dir)
|
||||
write_file(dir .. '/run/settings-chosen', '')
|
||||
local native = fake.native()
|
||||
native.dir = dir .. '/run'
|
||||
local l, w = store_layer({
|
||||
['terminal settings --cwd /home/u/proj --json'] = { true, 'S_PROJ' },
|
||||
['terminal settings --cwd /home/u/other --json'] = { true, 'S_OTHER' },
|
||||
}, native)
|
||||
local win = fake.window()
|
||||
local pane = fake.pane { id = 1, cwd = 'file://workstation/home/u/proj' }
|
||||
fake.tab { pane }
|
||||
win.active = pane
|
||||
eq(#w.spawned, 0, 'applying starts nothing')
|
||||
w.emit('user-var-changed', win, pane, 'llembas_tty_status', 'llembas-tty-status=1\nid=1.1\nseq=1\nstate=prompt\ncwd=/home/u/proj\n')
|
||||
eq(l.is_on 'suggestions', false, 'from the first prompt on')
|
||||
eq(l.value 'mode', 'auto', "the directory's mode")
|
||||
-- cd: the next prompt is in another directory
|
||||
pane.spec.cwd = 'file://workstation/home/u/other'
|
||||
w.emit('user-var-changed', win, pane, 'llembas_tty_status', 'llembas-tty-status=1\nid=1.1\nseq=2\nstate=prompt\ncwd=/home/u/other\n')
|
||||
eq(l.is_on 'suggestions', true, 'the other directory has none of its own')
|
||||
eq(l.value 'mode', 'manual', 'the option, where the store has no value')
|
||||
eq(native.last 'configure'[2].suggestions, true, 'the terminal is told')
|
||||
-- and back: known, not read again
|
||||
pane.spec.cwd = 'file://workstation/home/u/proj'
|
||||
w.emit('update-status', win, pane)
|
||||
eq(l.is_on 'suggestions', false, 'back')
|
||||
eq(spawned(w, 'terminal settings --cwd /home/u/proj --json'), 1, 'what is known of a directory is kept for a while')
|
||||
-- a prompt of a pane the person is not in changes nothing
|
||||
local beside = fake.pane { id = 2, cwd = 'file://workstation/home/u/other' }
|
||||
fake.tab { pane, beside }
|
||||
w.emit('user-var-changed', win, beside, 'llembas_tty_status', 'llembas-tty-status=1\nid=2.1\nseq=1\nstate=prompt\ncwd=/home/u/other\n')
|
||||
eq(l.is_on 'suggestions', false, 'the active pane decides')
|
||||
-- a shell on another machine inside the pane: its directory says nothing here
|
||||
local remote = fake.pane { id = 3, cwd = 'file://faraway/srv/app' }
|
||||
fake.tab { remote }
|
||||
w.hostname = function()
|
||||
return 'workstation'
|
||||
end
|
||||
win.active = remote
|
||||
local before = #w.spawned
|
||||
w.emit('update-status', win, remote)
|
||||
eq(#w.spawned, before, 'not asked about')
|
||||
-- a display started here gets the model, the mode and the width that apply
|
||||
win.active = pane
|
||||
local alone = fake.pane { id = 5, zones = ZONES, cwd = 'file://workstation/home/u/proj' }
|
||||
fake.tab({ alone }, 8)
|
||||
w.emit('llembas-ask-line', win, alone, 'q')
|
||||
local args = table.concat(alone.splits[1].args, ' ')
|
||||
check(args:find('-m open/big', 1, true), 'the chat model: ' .. args)
|
||||
check(args:find('--mode auto', 1, true), 'the mode: ' .. args)
|
||||
eq(alone.splits[1].size, 0.4, 'the width')
|
||||
end)
|
||||
|
||||
test('settings: a choice is kept, here or everywhere', function()
|
||||
local dir = fresh_dir 'keep'
|
||||
with_cli(dir)
|
||||
local native = fake.native()
|
||||
native.dir = dir .. '/run'
|
||||
local l, w, r = store_layer({
|
||||
['terminal settings --cwd /home/u/other --json'] = { true, 'S_OTHER' },
|
||||
['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' }
|
||||
fake.tab { pane }
|
||||
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 --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')
|
||||
-- said to be for this directory
|
||||
JSON['S_OTHER2'] = {
|
||||
effective = { ai = true, autocomplete = true, suggestions = true, highlight = false, mode = 'manual' },
|
||||
from = { ai = 'default', autocomplete = 'global', suggestions = 'default', highlight = '/home/u/other', mode = 'default' },
|
||||
directory = { path = '/home/u/other' },
|
||||
}
|
||||
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 --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 --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 --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)
|
||||
local a = win.actions[#win.actions].action
|
||||
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 --json display_width=0.50'), 1, 'kept')
|
||||
w.emit('llembas-width-pick-everywhere', win, pane, '7')
|
||||
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
|
||||
local labels = {}
|
||||
for _, c in ipairs(list.choices) do
|
||||
labels[#labels + 1] = c.label
|
||||
end
|
||||
local all = table.concat(labels, '\n')
|
||||
check(all:find('syntax highlighting: off · here (/home/u/other)', 1, true), 'from the directory: ' .. all)
|
||||
check(all:find('AI autocomplete: on · everywhere', 1, true), 'from the machine')
|
||||
check(all:find('mode: manual · the configuration', 1, true), 'from the options')
|
||||
check(all:find("chat model: the engine's own choice", 1, true), 'none chosen')
|
||||
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 --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 --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'] = {
|
||||
effective = { mode = 'auto' },
|
||||
from = { mode = '/home/u/other' },
|
||||
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 --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 --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 --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 --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')
|
||||
check(native.last 'notice'[3]:find('could not be kept', 1, true), 'said')
|
||||
end)
|
||||
|
||||
test('settings: a CLI without the store keeps working, for this run', function()
|
||||
local dir = fresh_dir 'nostore'
|
||||
with_cli(dir)
|
||||
local native = fake.native()
|
||||
native.dir = dir .. '/run'
|
||||
local l, w = new_layer { native = native }
|
||||
local win = fake.window()
|
||||
local pane = fake.pane { id = 1, cwd = 'file:///home/u/proj' }
|
||||
fake.tab { pane }
|
||||
w.emit('llembas-highlight-here', win, pane)
|
||||
eq(l.is_on 'highlight', false, 'off')
|
||||
eq(native.last 'notice'[3], 'syntax highlighting off' .. core.messages.remember_needs_cli, 'said once that it is not remembered')
|
||||
w.emit('llembas-suggestions-everywhere', win, pane)
|
||||
eq(native.last 'notice'[3], 'suggestions off', 'once')
|
||||
eq(io.open(dir .. '/run/settings-chosen', 'r'), nil, 'nothing was kept, so nothing is read at the next start')
|
||||
w.emit('llembas-mode-pick-here', win, pane, 'auto')
|
||||
eq(l.value 'mode', 'auto', 'the mode, for this run')
|
||||
for _, args in ipairs(w.spawned) do
|
||||
check(not table.concat(args, ' '):find('terminal settings', 1, true), 'the store is never asked of a CLI that has none')
|
||||
end
|
||||
w.emit('llembas-settings', win, pane)
|
||||
local a = win.actions[#win.actions].action.args
|
||||
check(a.description:find('needs a newer LLeMbas CLI', 1, true), 'the list says so')
|
||||
local all = ''
|
||||
for _, c in ipairs(a.choices) do
|
||||
all = all .. c.label .. '\n'
|
||||
end
|
||||
check(all:find('mode: auto · until the terminal closes', 1, true), 'and where a value is from: ' .. all)
|
||||
check(not all:find('Forget', 1, true), 'nothing to forget')
|
||||
end)
|
||||
|
||||
test('autocomplete status: in words', function()
|
||||
local dir = fresh_dir 'acstatus'
|
||||
with_cli(dir)
|
||||
local native = fake.native()
|
||||
native.status_text = 'engine: /x/lembas\nmodel: open/flash\nasked, the newest last:\n 3 s ago, for "git che", after 420 ms: an error: \27[31mnot logged in'
|
||||
local _, w = new_layer({ native = native }, { autocomplete = true })
|
||||
local win = fake.window()
|
||||
local pane = fake.pane { id = 1 }
|
||||
fake.tab { pane }
|
||||
w.emit('llembas-autocomplete-status', win, pane)
|
||||
local text = described(win)
|
||||
check(text:find('AI autocomplete is on.', 1, true), 'on: ' .. text)
|
||||
check(text:find('AI autocomplete: on · the configuration', 1, true), 'by whose choice')
|
||||
check(text:find('engine: /x/lembas', 1, true), 'the engine')
|
||||
check(text:find('an error: [31mnot logged in', 1, true), 'what came back, cleaned')
|
||||
w.emit('llembas-ai', win, pane)
|
||||
w.emit('llembas-autocomplete-status', win, pane)
|
||||
check(described(win):find('but AI is off', 1, true), 'AI off is said')
|
||||
-- without the terminal's own part
|
||||
local _, w2 = new_layer {}
|
||||
local win2 = fake.window()
|
||||
w2.emit('llembas-autocomplete-status', win2, pane)
|
||||
check(described(win2):find('AI autocomplete is off', 1, true), 'off by default')
|
||||
check(described(win2):find('drawn by the terminal itself', 1, true), 'and no such part here')
|
||||
end)
|
||||
|
||||
test('new conversation', function()
|
||||
@@ -1530,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'
|
||||
|
||||
+23
-3
@@ -110,16 +110,36 @@ 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', '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 = '', history = true, history_max = 10,
|
||||
suggestions = true, highlight = true, ai_complete = false, cli = '/opt/x/lembas', ac_model = 'local/fast',
|
||||
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)))
|
||||
local ok2 = pcall(n.set_private, 3, true)
|
||||
out[#out + 1] = 'set_private=' .. tostring(ok2)
|
||||
-- a word that stands, set and taken away again; the autocomplete in words
|
||||
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)
|
||||
status = ok4 and tostring(status) or ''
|
||||
out[#out + 1] = 'status=' .. tostring(status:find('engine: /opt/x/lembas', 1, true) ~= nil
|
||||
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) == '/')
|
||||
end
|
||||
require('llembas').apply(config, { autocomplete = true })
|
||||
local f = io.open(wezterm.home_dir .. '/native.txt', 'w')
|
||||
@@ -129,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 set_private=function command_ended=function clear_history=function configure=true set_private=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
|
||||
|
||||
+116
-116
@@ -4,42 +4,31 @@
|
||||
//! 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::atomic::{AtomicBool, Ordering};
|
||||
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 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<dyn Pane>) -> &'static str {
|
||||
let name = pane
|
||||
@@ -57,125 +46,136 @@ 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, 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
|
||||
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()),
|
||||
}
|
||||
if matches!(outcome, Outcome::Suggestion(_) | Outcome::Nothing(_)) {
|
||||
// the engine answered: the model is there
|
||||
COLD.store(false, Ordering::Relaxed);
|
||||
}
|
||||
let rest = outcome.rest();
|
||||
{
|
||||
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));
|
||||
}
|
||||
|
||||
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(cold: bool) {
|
||||
TRACKER.lock().forget();
|
||||
if cold {
|
||||
COLD.store(true, Ordering::Relaxed);
|
||||
}
|
||||
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());
|
||||
}
|
||||
|
||||
/// 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 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)
|
||||
));
|
||||
}
|
||||
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);
|
||||
}
|
||||
if !options.ai_complete {
|
||||
text = format!(
|
||||
"The terminal is not asking now: AI autocomplete (or AI) is off.\n{}",
|
||||
text
|
||||
);
|
||||
}
|
||||
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: 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())
|
||||
.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
|
||||
}
|
||||
@@ -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,
|
||||
@@ -461,11 +513,28 @@ 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<dyn Pane>) -> 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<dyn Pane>,
|
||||
active: bool,
|
||||
options: &state::Options,
|
||||
notice: Option<String>,
|
||||
hint: Option<state::Hint>,
|
||||
cursor: &StableCursorPosition,
|
||||
dims: &RenderableDimensions,
|
||||
) -> Option<Plan> {
|
||||
@@ -475,6 +544,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);
|
||||
@@ -482,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<zone::Row> = 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<zone::Row> = 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);
|
||||
@@ -502,9 +589,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 +656,13 @@ 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);
|
||||
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;
|
||||
}
|
||||
// The pane itself, never something drawn over it (search, copy mode, the
|
||||
@@ -570,7 +688,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();
|
||||
|
||||
@@ -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,31 @@ 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),
|
||||
ac_debug: table.get::<_, Option<bool>>("ac_debug")?.unwrap_or(false),
|
||||
input_mark: table.get::<_, Option<bool>>("input_mark")?.unwrap_or(false),
|
||||
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);
|
||||
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(())
|
||||
})?,
|
||||
)?;
|
||||
@@ -128,6 +148,93 @@ 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);
|
||||
if Mux::try_get().is_some() {
|
||||
Mux::notify_from_any_thread(MuxNotification::PaneOutput(pane_id));
|
||||
}
|
||||
Ok(true)
|
||||
},
|
||||
)?,
|
||||
)?;
|
||||
|
||||
// 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<String>,
|
||||
Option<u64>,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
)| {
|
||||
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.
|
||||
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(
|
||||
|
||||
@@ -35,7 +35,7 @@ fn cols_for_row(zone: &SemanticZone, row: StableRowIndex) -> std::ops::Range<usi
|
||||
|
||||
/// The text of a zone: its rows joined, with a line break where a row ended
|
||||
/// and was not carried on by wrapping.
|
||||
fn zone_text(pane: &Arc<dyn Pane>, zone: &SemanticZone) -> String {
|
||||
pub(super) fn zone_text(pane: &Arc<dyn Pane>, 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;
|
||||
|
||||
@@ -63,6 +63,14 @@ 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,
|
||||
/// 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,
|
||||
@@ -82,6 +90,12 @@ 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());
|
||||
/// Where the shell of a pane stands, as its status record said.
|
||||
static ref STATUS: Mutex<HashMap<PaneId, PaneStatus>> = Mutex::new(HashMap::new());
|
||||
/// The input mark last written for a pane: the record's id and seq, typed.
|
||||
static ref MARKS: Mutex<HashMap<PaneId, (String, u64, bool)>> = 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 +168,127 @@ pub fn notice(pane_id: PaneId) -> Option<String> {
|
||||
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<PaneStatus>) {
|
||||
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<PaneStatus> {
|
||||
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.
|
||||
#[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 {
|
||||
|
||||
Reference in new issue
Block a user