M3.6: integrated terminal with PTY sessions and xterm.js sub-tabs

- crates/terminal: portable-pty sessions (ConPTY on Windows) with reader,
  writer and waiter threads, UTF-8 chunking, a 1 MiB output buffer with
  backpressure, a non-blocking input queue, resize, kill and exit codes;
  default shell pwsh -> powershell -> cmd on Windows, $SHELL or /bin/sh.
- Engine: terminal.create/input/resize/close, terminalOutput (capped per
  terminal and per pump, round-robin) and terminalExited through the pump;
  terminals close with the project and on app.quit.
- UI: Terminal tab in the bottom panel (tabs next to Find), xterm.js with
  the fit addon, sub-tabs, copy/paste, a focus rule that leaves plain Ctrl
  keys to the shell, terminal.open (Mod+Shift+T), --lt-terminal-* ANSI
  tokens in both themes (text colours AA) and a 4.5:1 minimum contrast.
- Tests: real-shell crate tests (UTF-8, backpressure), engine and TCP
  control tests, Vitest with a mocked xterm; live check on port 7936;
  docs and parity rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-18 11:25:30 +02:00
parent 5fa7f0c8b3
commit a8daf269fb
45 changed files with 3935 additions and 49 deletions

103
Cargo.lock generated
View file

@ -354,7 +354,7 @@ checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a"
dependencies = [ dependencies = [
"borsh-derive", "borsh-derive",
"bytes", "bytes",
"cfg_aliases", "cfg_aliases 0.2.2",
] ]
[[package]] [[package]]
@ -587,6 +587,12 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "cfg_aliases"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e"
[[package]] [[package]]
name = "cfg_aliases" name = "cfg_aliases"
version = "0.2.2" version = "0.2.2"
@ -1154,7 +1160,7 @@ dependencies = [
"rustc_version", "rustc_version",
"toml 1.1.8+spec-1.1.0", "toml 1.1.8+spec-1.1.0",
"vswhom", "vswhom",
"winreg", "winreg 0.56.0",
] ]
[[package]] [[package]]
@ -1285,6 +1291,17 @@ dependencies = [
"rustc_version", "rustc_version",
] ]
[[package]]
name = "filedescriptor"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d"
dependencies = [
"libc",
"thiserror 1.0.69",
"winapi",
]
[[package]] [[package]]
name = "find-msvc-tools" name = "find-msvc-tools"
version = "0.1.14" version = "0.1.14"
@ -2404,6 +2421,12 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "lazy_static"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
[[package]] [[package]]
name = "libappindicator" name = "libappindicator"
version = "0.9.0" version = "0.9.0"
@ -2608,6 +2631,7 @@ dependencies = [
"lutra-lsp", "lutra-lsp",
"lutra-search", "lutra-search",
"lutra-syntax", "lutra-syntax",
"lutra-terminal",
"lutra-testkit", "lutra-testkit",
"lutra-text", "lutra-text",
"lutra-vfs", "lutra-vfs",
@ -2687,6 +2711,12 @@ dependencies = [
[[package]] [[package]]
name = "lutra-terminal" name = "lutra-terminal"
version = "0.0.0" version = "0.0.0"
dependencies = [
"portable-pty",
"proptest",
"tempfile",
"thiserror 2.0.21",
]
[[package]] [[package]]
name = "lutra-testkit" name = "lutra-testkit"
@ -2861,6 +2891,18 @@ version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
[[package]]
name = "nix"
version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
"cfg_aliases 0.1.1",
"libc",
]
[[package]] [[package]]
name = "nom" name = "nom"
version = "7.1.3" version = "7.1.3"
@ -3539,6 +3581,27 @@ dependencies = [
"portable-atomic", "portable-atomic",
] ]
[[package]]
name = "portable-pty"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4a596a2b3d2752d94f51fac2d4a96737b8705dddd311a32b9af47211f08671e"
dependencies = [
"anyhow",
"bitflags 1.3.2",
"downcast-rs",
"filedescriptor",
"lazy_static",
"libc",
"log",
"nix",
"serial2",
"shared_library",
"shell-words",
"winapi",
"winreg 0.10.1",
]
[[package]] [[package]]
name = "potential_utf" name = "potential_utf"
version = "0.1.6" version = "0.1.6"
@ -4244,6 +4307,17 @@ dependencies = [
"syn 3.0.9", "syn 3.0.9",
] ]
[[package]]
name = "serial2"
version = "0.2.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b16809bc35793b19ce4e0c53924bc0dce3937f15487997cfdaed936004180730"
dependencies = [
"cfg-if",
"libc",
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "serialize-to-javascript" name = "serialize-to-javascript"
version = "0.1.2" version = "0.1.2"
@ -4286,6 +4360,22 @@ dependencies = [
"digest", "digest",
] ]
[[package]]
name = "shared_library"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a9e7e0f2bfae24d8a5b5a66c5b257a83c7412304311512a0c054cd5e619da11"
dependencies = [
"lazy_static",
"libc",
]
[[package]]
name = "shell-words"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77"
[[package]] [[package]]
name = "shlex" name = "shlex"
version = "1.3.0" version = "1.3.0"
@ -6281,6 +6371,15 @@ dependencies = [
"memchr", "memchr",
] ]
[[package]]
name = "winreg"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d"
dependencies = [
"winapi",
]
[[package]] [[package]]
name = "winreg" name = "winreg"
version = "0.56.0" version = "0.56.0"

View file

@ -64,7 +64,7 @@ claude mcp add lutra -- lutra mcp
## Status ## Status
**Pre-alpha (2026-10-17): M2 done.** You can open a folder, browse it in the project tree with live updates from disk, and edit and save files in tabs with syntax highlighting for PHP (and HTML, CSS, JS/TS, JSON, YAML, Markdown), with every command in a palette (`Mod+Shift+P`) and settings and the light or dark theme in a settings dialog (`Mod+,`); unsaved text survives a crash and is offered back on the next open; M2 added find in files (`Mod+Alt+F`) and go to file, class or symbol (`Mod+P`, `Mod+Alt+C`, `Mod+T`); PHP language features come next. About 12 agent hours remain to the MVP (M3: language server, terminal, CLI and MCP). [**ROADMAP.md**](ROADMAP.md) has the stage and what's next, **Pre-alpha (2026-10-17): M2 done.** You can open a folder, browse it in the project tree with live updates from disk, and edit and save files in tabs with syntax highlighting for PHP (and HTML, CSS, JS/TS, JSON, YAML, Markdown), with every command in a palette (`Mod+Shift+P`) and settings and the light or dark theme in a settings dialog (`Mod+,`); unsaved text survives a crash and is offered back on the next open; M2 added find in files (`Mod+Alt+F`) and go to file, class or symbol (`Mod+P`, `Mod+Alt+C`, `Mod+T`); M3 has begun with an integrated terminal (`Mod+Shift+T`); PHP language features come next. About 12 agent hours remain to the MVP (M3: language server, terminal, CLI and MCP). [**ROADMAP.md**](ROADMAP.md) has the stage and what's next,
[`docs/target-app-parity.md`](docs/target-app-parity.md) the parity assessment and [`docs/gaps.md`](docs/gaps.md) the ranked work list. [`docs/target-app-parity.md`](docs/target-app-parity.md) the parity assessment and [`docs/gaps.md`](docs/gaps.md) the ranked work list.
**First target (MVP, M1–M3):** open a project, project tree, tabs, editor with highlighting, find in files, **First target (MVP, M1–M3):** open a project, project tree, tabs, editor with highlighting, find in files,

View file

@ -2,7 +2,7 @@
**Stage: pre-alpha (M2 done)** · next: M3 language server, terminal, CLI and MCP (the MVP); alpha when the six core workflows work end to end (see [docs/roadmap.md › Alpha gate](docs/roadmap.md#alpha-gate)) **Stage: pre-alpha (M2 done)** · next: M3 language server, terminal, CLI and MCP (the MVP); alpha when the six core workflows work end to end (see [docs/roadmap.md › Alpha gate](docs/roadmap.md#alpha-gate))
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-20 · **Change:** minor (M3.10: autosave) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only > **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-20 · **Change:** minor (M3.10: autosave; M3.6: integrated terminal) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only
Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue interface, targeting the PhpStorm workflow. Agents can drive all of it over MCP, the `lutra` CLI and a JSON control channel. This page is the summary; the evidence is in [`docs/target-app-parity.md`](docs/target-app-parity.md) and the work list in [`docs/gaps.md`](docs/gaps.md). Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue interface, targeting the PhpStorm workflow. Agents can drive all of it over MCP, the `lutra` CLI and a JSON control channel. This page is the summary; the evidence is in [`docs/target-app-parity.md`](docs/target-app-parity.md) and the work list in [`docs/gaps.md`](docs/gaps.md).
@ -13,7 +13,7 @@ Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue in
| | Value | Kind | | | Value | Kind |
|---|---|---| |---|---|---|
| **Feature breadth** (PhpStorm's actions, tool windows, languages, integrations exist) | **~15%** (23 of 155 feature units of the public PhpStorm help have at least partial support; ~21% after the running cycle C4) | estimated | | **Feature breadth** (PhpStorm's actions, tool windows, languages, integrations exist) | **~15%** (23 of 155 feature units of the public PhpStorm help have at least partial support; ~21% after the running cycle C4) | estimated |
| **Feature depth** (weighted by use, scored by behaviour) | **~3.3%** (Editor core 11% × weight 12, Navigation 10% × weight 10, Project view 8% × weight 6, Search and replace 8% × weight 6, Settings 7% × weight 1, of 101) | estimated | | **Feature depth** (weighted by use, scored by behaviour) | **~3.8%** (Editor core 11% × weight 12, Navigation 10% × weight 10, Project view 8% × weight 6, Search and replace 8% × weight 6, Terminal 15% × weight 3, Settings 7% × weight 1, of 101) | estimated |
| **To MVP (M3)** | **~12 h left** (M3 = 80 h raw × 0.15; done so far: M1 ~5.6 h, M2 ~6.1 h, measured); was ~190 h before calibration | estimated (factor per cycle: C1 0.07, C2 0.10, C3 0.14) | | **To MVP (M3)** | **~12 h left** (M3 = 80 h raw × 0.15; done so far: M1 ~5.6 h, M2 ~6.1 h, measured); was ~190 h before calibration | estimated (factor per cycle: C1 0.07, C2 0.10, C3 0.14) |
| **To full parity** | **~450 h** at the current factor of ~0.15 (range 300–3,300 h; the factor has risen each cycle, and deep areas such as type inference and inspections have no data yet) | estimated | | **To full parity** | **~450 h** at the current factor of ~0.15 (range 300–3,300 h; the factor has risen each cycle, and deep areas such as type inference and inspections have no data yet) | estimated |
@ -25,11 +25,11 @@ Dimension hours overlap: language, framework and tooling hours are part of the f
| Dimension | % | One agent (h) | Doc | | Dimension | % | One agent (h) | Doc |
|---|---:|---:|---| |---|---:|---:|---|
| Features (depth) | ~3.2% | ~2,896 | [target-app-parity.md](docs/target-app-parity.md) | | Features (depth) | ~3.8% | ~2,892 | [target-app-parity.md](docs/target-app-parity.md) |
| UI/UX fidelity | 1% (est.) | ~150 on top of features | [ui-parity.md](docs/ui-parity.md) | | UI/UX fidelity | 1% (est.) | ~150 on top of features | [ui-parity.md](docs/ui-parity.md) |
| PHP language support | 0% | ~920 (in features) | [language-parity.md](docs/language-parity.md) | | PHP language support | 0% | ~920 (in features) | [language-parity.md](docs/language-parity.md) |
| Frameworks (Symfony, Laravel, Shopware, WordPress) | 0% | ~300 (in features) | [framework-parity.md](docs/framework-parity.md) | | Frameworks (Symfony, Laravel, Shopware, WordPress) | 0% | ~300 (in features) | [framework-parity.md](docs/framework-parity.md) |
| Tooling (Git, terminal, debugger, tests, Composer, DB) | 0% | ~730 (in features) | [tooling-parity.md](docs/tooling-parity.md) | | Tooling (Git, terminal, debugger, tests, Composer, DB) | <1% (est.) | ~726 (in features) | [tooling-parity.md](docs/tooling-parity.md) |
| Localization (en, de) | 5% | ~38 | [localization-parity.md](docs/localization-parity.md) | | Localization (en, de) | 5% | ~38 | [localization-parity.md](docs/localization-parity.md) |
| Performance | 0% | ~100 | [gaps.md › G12](docs/gaps.md) | | Performance | 0% | ~100 | [gaps.md › G12](docs/gaps.md) |
| Stability | 8% | ~95 | [gaps.md › G11](docs/gaps.md) | | Stability | 8% | ~95 | [gaps.md › G11](docs/gaps.md) |
@ -50,7 +50,7 @@ Stability 8%: no-panic lints, the engine guard, a fuzzed control protocol and a
| Refactoring | 0% | ~250 | | Refactoring | 0% | ~250 |
| Code style and formatting | 0% | ~120 | | Code style and formatting | 0% | ~120 |
| Version control (Git) | 0% | ~150 | | Version control (Git) | 0% | ~150 |
| Terminal | 0% | ~30 | | Terminal | 15% (est.) | ~26 |
| Run configurations | 0% | ~50 | | Run configurations | 0% | ~50 |
| Debugger (Xdebug) | 0% | ~120 | | Debugger (Xdebug) | 0% | ~120 |
| Testing (PHPUnit, Pest) | 0% | ~80 | | Testing (PHPUnit, Pest) | 0% | ~80 |
@ -77,6 +77,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
|---|---| |---|---|
| 2026-10-20 | M3.10: autosave. Changed files are saved when you leave the Lutra window, when you switch tabs and after 15 seconds without typing; each can be turned off in Settings › Editor. Files that were changed outside Lutra are left for you to decide. Later features such as deployment save everything first through the same step. | | 2026-10-20 | M3.10: autosave. Changed files are saved when you leave the Lutra window, when you switch tabs and after 15 seconds without typing; each can be turned off in Settings › Editor. Files that were changed outside Lutra are left for you to decide. Later features such as deployment save everything first through the same step. |
| 2026-10-19 | M3.8: agents can drive Lutra over MCP: `claude mcp add lutra -- lutra mcp`, then Claude can list and run every command, look at the window, read open files including unsaved changes and follow what happens. Closing Lutra needs an explicit confirmation. | | 2026-10-19 | M3.8: agents can drive Lutra over MCP: `claude mcp add lutra -- lutra mcp`, then Claude can list and run every command, look at the window, read open files including unsaved changes and follow what happens. Closing Lutra needs an explicit confirmation. |
| 2026-10-18 | M3.6: an integrated terminal: `Mod+Shift+T` opens a Terminal tab in the bottom panel (next to Find) running PowerShell or cmd on Windows and your shell elsewhere, in the project folder; several terminals as sub-tabs, copy and paste, Lutra's own colours in both themes. Plain Ctrl keys go to the shell; agents can create terminals, type into them and read their output over the control channel. |
| 2026-10-17 | M3.7: the `lutra` command: `lutra src/Kernel.php:42` opens the file at line 42 in the running Lutra or starts it, `lutra .` opens a folder, `lutra --wait FILE` returns when the tab is closed (for `git commit`). Starting Lutra a second time hands the path to the first window. Only your user account can talk to the running instance. | | 2026-10-17 | M3.7: the `lutra` command: `lutra src/Kernel.php:42` opens the file at line 42 in the running Lutra or starts it, `lutra .` opens a folder, `lutra --wait FILE` returns when the tab is closed (for `git commit`). Starting Lutra a second time hands the path to the first window. Only your user account can talk to the running instance. |
| 2026-10-17 | M2.6: go to any file, class or symbol by name: `Mod+P`, `Mod+Alt+C` and `Mod+T` open one popup with Files, Classes and Symbols tabs (Tab switches); results update as you type with the matched letters marked, library code is labelled, a hint shows while the index is still building, and Enter jumps there. Agents can open it with a query. | | 2026-10-17 | M2.6: go to any file, class or symbol by name: `Mod+P`, `Mod+Alt+C` and `Mod+T` open one popup with Files, Classes and Symbols tabs (Tab switches); results update as you type with the matched letters marked, library code is labelled, a hint shows while the index is still building, and Enter jumps there. Agents can open it with a query. |
| 2026-10-17 | M2.7: a Structure tool window next to Project (new left stripe, `Mod+2`) shows the classes, functions, methods, properties and constants of the active PHP file as a tree that follows tabs and edits; click or Enter jumps to the declaration. The file is reparsed in the background, so big files never stall typing. | | 2026-10-17 | M2.7: a Structure tool window next to Project (new left stripe, `Mod+2`) shows the classes, functions, methods, properties and constants of the active PHP file as a tree that follows tabs and edits; click or Enter jumps to the declaration. The file is reparsed in the background, so big files never stall typing. |
@ -97,6 +98,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
| Date | Change | Summary | | Date | Change | Summary |
|---|---|---| |---|---|---|
| 2026-10-20 | minor | M3.6: Terminal 0% → 15%, feature depth ~3.3% → ~3.8% |
| 2026-10-20 | minor | M3.10: autosave; Editor core 10% → 11% (est.), feature depth ~3.2% → ~3.3% | | 2026-10-20 | minor | M3.10: autosave; Editor core 10% → 11% (est.), feature depth ~3.2% → ~3.3% |
| 2026-10-18 | minor | Feature breadth measured against the full PhpStorm help inventory (155 units); M7–M9 added | | 2026-10-18 | minor | Feature breadth measured against the full PhpStorm help inventory (155 units); M7–M9 added |
| 2026-10-19 | minor | M3.8: MCP server; agent automation 18% → 26% (est.) | | 2026-10-19 | minor | M3.8: MCP server; agent automation 18% → 26% (est.) |

View file

@ -0,0 +1,176 @@
//! The integrated terminal over a real TCP control connection:
//! `terminal.create` answers at once, `terminalOutput` and `terminalExited`
//! arrive as event lines from the pump, `terminal.input` reaches the shell.
//!
//! ConPTY asks for the cursor position (`ESC[6n`) when it starts and waits
//! for the answer; the client answers like xterm.js does.
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::panic
)]
use std::io::{BufRead, BufReader, Write};
use std::net::TcpStream;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use lutra_testkit::EngineBackend;
use serde_json::{Value, json};
/// A client that answers requests and collects terminal events.
struct Client {
reader: BufReader<TcpStream>,
writer: TcpStream,
output: String,
exit: Option<Value>,
answered: usize,
next: u64,
}
impl Client {
fn connect(addr: std::net::SocketAddr) -> Self {
let stream = TcpStream::connect(addr).unwrap();
stream
.set_read_timeout(Some(Duration::from_secs(10)))
.unwrap();
Self {
writer: stream.try_clone().unwrap(),
reader: BufReader::new(stream),
output: String::new(),
exit: None,
answered: 0,
next: 0,
}
}
fn line(&mut self) -> Value {
let mut line = String::new();
self.reader.read_line(&mut line).expect("line within 10 s");
serde_json::from_str(&line).unwrap()
}
fn event(&mut self, event: &Value) {
match event["kind"].as_str() {
Some("terminalOutput") => self.output.push_str(event["data"].as_str().unwrap()),
Some("terminalExited") => self.exit = Some(event.clone()),
_ => {}
}
}
fn call(&mut self, method: &str, params: Value) -> Value {
self.next += 1;
let request = json!({"id": self.next, "method": method, "params": params});
self.writer
.write_all(format!("{request}\n").as_bytes())
.unwrap();
loop {
let line = self.line();
if let Some(event) = line.get("event") {
let event = event.clone();
self.event(&event);
} else {
return line;
}
}
}
fn execute(&mut self, command: &str, params: Value) -> Value {
self.call(
"engine.execute",
json!({"command": command, "params": params}),
)
}
/// Reads events until `done` holds or the terminal exited, answering
/// cursor-position queries.
fn until(&mut self, id: u64, done: impl Fn(&str) -> bool) {
let deadline = Instant::now() + Duration::from_secs(30);
while Instant::now() < deadline {
while self.answered < self.output.matches("\x1b[6n").count() {
let r = self.execute(
"terminal.input",
json!({"terminalId": id, "data": "\x1b[1;1R"}),
);
assert!(r.get("error").is_none(), "{r}");
self.answered += 1;
}
if self.exit.is_some() || done(&self.output) {
return;
}
let line = self.line();
if let Some(event) = line.get("event") {
let event = event.clone();
self.event(&event);
}
}
panic!("timed out; output so far: {:?}", self.output);
}
}
/// Pumps the backend every 20 ms, like the desktop's pump thread, until
/// dropped.
struct Pump(Arc<AtomicBool>);
impl Pump {
fn start(backend: Arc<EngineBackend>) -> Self {
let stop = Arc::new(AtomicBool::new(false));
let flag = stop.clone();
std::thread::spawn(move || {
while !flag.load(Ordering::Relaxed) {
backend.pump();
std::thread::sleep(Duration::from_millis(20));
}
});
Self(stop)
}
}
impl Drop for Pump {
fn drop(&mut self) {
self.0.store(true, Ordering::Relaxed);
}
}
#[test]
fn create_output_input_exit() {
let dir = tempfile::tempdir().unwrap();
let backend = Arc::new(EngineBackend::new());
let server = lutra_control::start(0, backend.clone()).unwrap();
let mut client = Client::connect(server.local_addr());
client.call("events.subscribe", json!({}));
let r = client.execute("project.open", json!({"path": dir.path()}));
assert!(r["result"]["root"].is_string(), "{r}");
let _pump = Pump::start(backend.clone());
let shell = if cfg!(windows) { "cmd.exe" } else { "sh" };
let r = client.execute(
"terminal.create",
json!({"shell": shell, "cols": 100, "rows": 30}),
);
let id = r["result"]["terminalId"].as_u64().expect("terminalId");
let r = client.execute(
"terminal.input",
json!({"terminalId": id, "data": "echo lutra-tcp\r"}),
);
assert!(r.get("error").is_none(), "{r}");
client.until(id, |out| out.matches("lutra-tcp").count() >= 2);
let r = client.execute(
"terminal.resize",
json!({"terminalId": id, "cols": 70, "rows": 20}),
);
assert!(r.get("error").is_none(), "{r}");
client.execute(
"terminal.input",
json!({"terminalId": id, "data": "exit 4\r"}),
);
client.until(id, |_| false);
let exit = client.exit.clone().unwrap();
assert_eq!(
exit,
json!({"kind": "terminalExited", "terminalId": id, "code": 4})
);
}

View file

@ -16,6 +16,7 @@ lutra-index.workspace = true
lutra-lsp.workspace = true lutra-lsp.workspace = true
lutra-search.workspace = true lutra-search.workspace = true
lutra-syntax.workspace = true lutra-syntax.workspace = true
lutra-terminal.workspace = true
lutra-text.workspace = true lutra-text.workspace = true
lutra-vfs.workspace = true lutra-vfs.workspace = true
serde = { version = "1.0.229", features = ["derive"] } serde = { version = "1.0.229", features = ["derive"] }

View file

@ -47,7 +47,8 @@ impl Command for Quit {
} }
} }
fn run(&self, _state: &mut State, _params: Value) -> Result<Outcome, EngineError> { fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
crate::cmd::terminal::close_all(state);
Ok(Outcome::effect(Effect::Quit)) Ok(Outcome::effect(Effect::Quit))
} }
} }

View file

@ -10,6 +10,7 @@ mod recovery;
pub mod search; pub mod search;
mod settings; mod settings;
pub mod syntax; pub mod syntax;
pub mod terminal;
pub mod theme; pub mod theme;
pub mod toolchain; pub mod toolchain;
pub mod ui; pub mod ui;
@ -53,5 +54,9 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
registry.register(Box::new(toolchain::Status))?; registry.register(Box::new(toolchain::Status))?;
registry.register(Box::new(toolchain::DownloadPhpactor))?; registry.register(Box::new(toolchain::DownloadPhpactor))?;
registry.register(Box::new(buffer::List))?; registry.register(Box::new(buffer::List))?;
registry.register(Box::new(terminal::Create))?;
registry.register(Box::new(terminal::Input))?;
registry.register(Box::new(terminal::Resize))?;
registry.register(Box::new(terminal::Close))?;
Ok(()) Ok(())
} }

View file

@ -0,0 +1,437 @@
//! The integrated terminal: `terminal.create`, `terminal.input`,
//! `terminal.resize` and `terminal.close`, and the events
//! `terminalOutput` and `terminalExited`.
//!
//! Each terminal is a [`lutra_terminal::Session`]: a shell in a pseudo
//! terminal whose reading, writing and waiting happen on threads of its own,
//! so no command blocks the engine lock on the shell. Output waits in the
//! session's bounded buffer (backpressure when full, see the crate) until
//! [`crate::Engine::pump_vfs`] calls [`pump`], which emits one
//! `terminalOutput` per terminal with at most [`MAX_OUTPUT_PER_TERMINAL`]
//! bytes, at most [`MAX_OUTPUT_PER_PUMP`] bytes over all terminals
//! (round-robin, so one busy terminal cannot starve the others). With the
//! desktop's pump every 100 ms that caps the stream at about 2.5 MB/s; the
//! shell waits when it writes faster. `terminalExited` follows the last
//! output of a shell that ended.
//!
//! Terminals belong to the project open when they were created: closing the
//! project (or opening another) closes them ([`sync_project`], run after
//! every command and every pump), and so does `app.quit` ([`close_all`]).
//! A terminal closed by Lutra reports `terminalExited` with `code: null`.
use std::collections::BTreeMap;
use std::ops::Bound;
use std::path::{Path, PathBuf};
use lutra_terminal::{Session, Shell, SpawnOptions, TerminalError};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::cmd::params::parse;
use crate::{Command, CommandSpec, EngineError, Event, Outcome, State};
/// Most terminals open at once.
pub const MAX_TERMINALS: usize = 16;
/// Most bytes of input one `terminal.input` takes.
pub const MAX_INPUT_BYTES: usize = 1 << 20;
/// Most bytes of output one pump emits for one terminal.
pub const MAX_OUTPUT_PER_TERMINAL: usize = 64 * 1024;
/// Most bytes of output one pump emits over all terminals.
pub const MAX_OUTPUT_PER_PUMP: usize = 256 * 1024;
/// Events of the terminal, appended to [`Event`] untagged: each serialises
/// with its own `kind`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(
tag = "kind",
rename_all = "camelCase",
rename_all_fields = "camelCase"
)]
pub enum TerminalEvent {
/// Output of a terminal, as UTF-8 text with the shell's escape
/// sequences; at most [`MAX_OUTPUT_PER_TERMINAL`] bytes.
TerminalOutput {
/// The terminal, as `terminal.create` returned it.
terminal_id: u64,
/// The text; never empty.
data: String,
},
/// A terminal ended: its shell exited or Lutra closed it. No events for
/// it follow.
TerminalExited {
/// The terminal.
terminal_id: u64,
/// The shell's exit code; `null` when Lutra closed the terminal or
/// the code is unknown.
code: Option<i64>,
},
}
/// The open terminals.
#[derive(Debug, Default)]
pub struct Terminals {
/// The id of the last terminal created; ids are never reused.
last_id: u64,
/// The terminal the last pump emitted output for first; the next pump
/// starts after it.
cursor: u64,
/// Open terminals by id.
sessions: BTreeMap<u64, Running>,
}
impl Terminals {
/// Number of open terminals.
pub fn len(&self) -> usize {
self.sessions.len()
}
/// Whether no terminal is open.
pub fn is_empty(&self) -> bool {
self.sessions.is_empty()
}
}
/// One open terminal.
#[derive(Debug)]
struct Running {
/// The shell.
session: Session,
/// Root of the project it belongs to.
root: PathBuf,
}
/// Root of the open project.
fn project_root(state: &State) -> Option<PathBuf> {
state
.project
.as_ref()
.map(|w| w.project.root().to_path_buf())
}
/// An engine error for a session error of command `id`.
fn session_error(id: &str, e: TerminalError) -> EngineError {
match e {
TerminalError::InvalidSize { .. } => EngineError::invalid_params(id, e.to_string()),
_ => EngineError::Failed(e.to_string()),
}
}
/// The open terminal `terminal_id`.
fn running<'a>(state: &'a State, id: &str, terminal_id: u64) -> Result<&'a Running, EngineError> {
state
.terminals
.sessions
.get(&terminal_id)
.ok_or_else(|| EngineError::invalid_params(id, format!("no terminal {terminal_id}")))
}
/// Params of `terminal.create`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
struct CreateParams {
/// Working directory: project-relative or absolute.
cwd: Option<String>,
/// Program to run instead of the default shell.
shell: Option<String>,
/// Columns.
cols: u16,
/// Rows.
rows: u16,
}
/// `terminal.create`: starts a shell in a new terminal.
pub struct Create;
impl Command for Create {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "terminal.create",
label: "New Terminal",
menu_path: None,
default_shortcut: None,
params: "{ cwd? (project-relative or absolute directory, default the project root), shell? (program name or path; default pwsh, then powershell, then cmd on Windows, $SHELL or /bin/sh elsewhere), cols, rows (1..=1000) }; returns { terminalId }, then events terminalOutput { terminalId, data } and terminalExited { terminalId, code }; at most 16 terminals",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let id = self.spec().id;
let p: CreateParams = parse(id, params)?;
if state.terminals.sessions.len() >= MAX_TERMINALS {
return Err(EngineError::Failed(format!(
"at most {MAX_TERMINALS} terminals can be open"
)));
}
let root = project_root(state).ok_or_else(|| EngineError::Disabled(id.to_string()))?;
let cwd = match p.cwd.as_deref() {
None | Some("") => root.clone(),
Some(dir) => root.join(Path::new(dir)),
};
if !cwd.is_dir() {
return Err(EngineError::invalid_params(
id,
format!("{} is not a directory", cwd.display()),
));
}
let shell = match p.shell.as_deref() {
None | Some("") => lutra_terminal::default_shell(),
Some(program) => Shell::new(
lutra_terminal::find_in_path(program).unwrap_or_else(|| PathBuf::from(program)),
),
};
let session = Session::spawn(SpawnOptions {
shell,
cwd,
cols: p.cols,
rows: p.rows,
env: Vec::new(),
})
.map_err(|e| session_error(id, e))?;
let terminals = &mut state.terminals;
terminals.last_id = terminals.last_id.saturating_add(1);
let terminal_id = terminals.last_id;
terminals
.sessions
.insert(terminal_id, Running { session, root });
Ok(Outcome::value(json!({ "terminalId": terminal_id })))
}
}
/// Params of `terminal.input`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
struct InputParams {
/// The terminal.
terminal_id: u64,
/// Keys or pasted text, as xterm.js sends them.
data: String,
}
/// `terminal.input`: sends input to a terminal's shell.
pub struct Input;
impl Command for Input {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "terminal.input",
label: "Terminal Input",
menu_path: None,
default_shortcut: None,
params: "{ terminalId, data (at most 1 MiB) }; returns null; failed when the shell has exited or is not reading its input",
}
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let id = self.spec().id;
let p: InputParams = parse(id, params)?;
if p.data.len() > MAX_INPUT_BYTES {
return Err(EngineError::invalid_params(
id,
format!("at most {MAX_INPUT_BYTES} bytes of input per call"),
));
}
running(state, id, p.terminal_id)?
.session
.write(p.data.as_bytes())
.map_err(|e| session_error(id, e))?;
Ok(Outcome::default())
}
}
/// Params of `terminal.resize`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
struct ResizeParams {
/// The terminal.
terminal_id: u64,
/// Columns.
cols: u16,
/// Rows.
rows: u16,
}
/// `terminal.resize`: changes a terminal's size.
pub struct Resize;
impl Command for Resize {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "terminal.resize",
label: "Resize Terminal",
menu_path: None,
default_shortcut: None,
params: "{ terminalId, cols, rows (1..=1000) }; returns null",
}
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let id = self.spec().id;
let p: ResizeParams = parse(id, params)?;
running(state, id, p.terminal_id)?
.session
.resize(p.cols, p.rows)
.map_err(|e| session_error(id, e))?;
Ok(Outcome::default())
}
}
/// Params of `terminal.close`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
struct CloseParams {
/// The terminal.
terminal_id: u64,
}
/// `terminal.close`: kills a terminal's shell.
pub struct Close;
impl Command for Close {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "terminal.close",
label: "Close Terminal",
menu_path: None,
default_shortcut: None,
params: "{ terminalId }; returns { closed }: false if the terminal already ended; a closed terminal reports terminalExited { code: null }",
}
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let p: CloseParams = parse(self.spec().id, params)?;
let closed = close(state, p.terminal_id);
Ok(Outcome::value(json!({ "closed": closed })))
}
}
/// Kills terminal `terminal_id`, drops its buffered output and emits
/// `terminalExited {code: null}`.
///
/// # Returns
/// Whether the terminal was open.
fn close(state: &mut State, terminal_id: u64) -> bool {
let Some(mut running) = state.terminals.sessions.remove(&terminal_id) else {
return false;
};
running.session.kill();
state.emit(Event::Terminal(TerminalEvent::TerminalExited {
terminal_id,
code: None,
}));
true
}
/// Closes every terminal, for `app.quit`.
pub fn close_all(state: &mut State) {
let ids: Vec<u64> = state.terminals.sessions.keys().copied().collect();
for terminal_id in ids {
close(state, terminal_id);
}
}
/// Closes the terminals of a project that is no longer open.
pub fn sync_project(state: &mut State) {
let root = project_root(state);
let stale: Vec<u64> = state
.terminals
.sessions
.iter()
.filter(|(_, r)| root.as_ref() != Some(&r.root))
.map(|(&id, _)| id)
.collect();
for terminal_id in stale {
close(state, terminal_id);
}
}
/// Moves buffered output into `terminalOutput` events and reports ended
/// shells with `terminalExited`; see the module documentation for the caps.
/// Closes the terminals of a project that is no longer open first.
pub fn pump(state: &mut State) {
sync_project(state);
let terminals = &mut state.terminals;
let cursor = terminals.cursor;
let order: Vec<u64> = terminals
.sessions
.range((Bound::Excluded(cursor), Bound::Unbounded))
.chain(terminals.sessions.range(..=cursor))
.map(|(&id, _)| id)
.collect();
let mut budget = MAX_OUTPUT_PER_PUMP;
let mut events = Vec::new();
let mut ended = Vec::new();
let mut first = None;
for terminal_id in order {
let Some(running) = terminals.sessions.get(&terminal_id) else {
continue;
};
if budget > 0 {
let data = running
.session
.take_output(budget.min(MAX_OUTPUT_PER_TERMINAL));
if !data.is_empty() {
budget = budget.saturating_sub(data.len());
first.get_or_insert(terminal_id);
events.push(TerminalEvent::TerminalOutput { terminal_id, data });
}
}
if let Some(exit) = running.session.exit() {
events.push(TerminalEvent::TerminalExited {
terminal_id,
code: exit.code,
});
ended.push(terminal_id);
}
}
if let Some(first) = first {
terminals.cursor = first;
}
for terminal_id in ended {
terminals.sessions.remove(&terminal_id);
}
for event in events {
state.emit(Event::Terminal(event));
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::TerminalEvent;
use crate::Event;
#[test]
fn event_shapes() {
let e = Event::Terminal(TerminalEvent::TerminalOutput {
terminal_id: 1,
data: "hi\r\n".into(),
});
assert_eq!(
serde_json::to_value(e).unwrap(),
json!({"kind": "terminalOutput", "terminalId": 1, "data": "hi\r\n"})
);
let e = Event::Terminal(TerminalEvent::TerminalExited {
terminal_id: 1,
code: Some(3),
});
assert_eq!(
serde_json::to_value(e).unwrap(),
json!({"kind": "terminalExited", "terminalId": 1, "code": 3})
);
let e = Event::Terminal(TerminalEvent::TerminalExited {
terminal_id: 2,
code: None,
});
assert_eq!(
serde_json::to_value(e).unwrap(),
json!({"kind": "terminalExited", "terminalId": 2, "code": null})
);
}
}

View file

@ -119,6 +119,7 @@ impl Engine {
} }
let outcome = command.run(state, params); let outcome = command.run(state, params);
crate::workspace::sync_buffer_dirs(state); crate::workspace::sync_buffer_dirs(state);
cmd::terminal::sync_project(state);
outcome outcome
}); });
state.commands_run = state.commands_run.saturating_add(1); state.commands_run = state.commands_run.saturating_add(1);
@ -134,6 +135,7 @@ impl Engine {
/// events (see [`cmd::search`]), merges index updates (see /// events (see [`cmd::search`]), merges index updates (see
/// [`cmd::goto`]), stores finished parses and starts due ones (see /// [`cmd::goto`]), stores finished parses and starts due ones (see
/// [`cmd::syntax`]) and returns every queued event. /// [`cmd::syntax`]) and returns every queued event.
/// Terminal output and exits become events too (see [`cmd::terminal`]).
/// Hosts call it regularly, e.g. every 100 ms from a background thread. /// Hosts call it regularly, e.g. every 100 ms from a background thread.
/// ///
/// # Errors /// # Errors
@ -148,6 +150,7 @@ impl Engine {
cmd::goto::sync(state); cmd::goto::sync(state);
cmd::syntax::pump(state, std::time::Instant::now()); cmd::syntax::pump(state, std::time::Instant::now());
cmd::toolchain::pump(state); cmd::toolchain::pump(state);
cmd::terminal::pump(state);
Ok(()) Ok(())
})?; })?;
Ok(state.take_events()) Ok(state.take_events())
@ -410,6 +413,10 @@ mod tests {
"settings.reset", "settings.reset",
"settings.set", "settings.set",
"syntax.outline", "syntax.outline",
"terminal.close",
"terminal.create",
"terminal.input",
"terminal.resize",
"test.disabled", "test.disabled",
"theme.list", "theme.list",
"theme.systemPreference", "theme.systemPreference",

View file

@ -197,6 +197,9 @@ pub enum Event {
/// PHP or Phpactor changed: `{php, phpactor}` as `toolchain.status` /// PHP or Phpactor changed: `{php, phpactor}` as `toolchain.status`
/// returns it. /// returns it.
ToolchainChanged(crate::cmd::toolchain::ToolchainStatus), ToolchainChanged(crate::cmd::toolchain::ToolchainStatus),
/// Terminal events (`terminalOutput`, `terminalExited`), see [`crate::cmd::terminal`].
#[serde(untagged)]
Terminal(crate::cmd::terminal::TerminalEvent),
} }
/// One match of [`Event::SearchResults`]. Positions are 0-based; columns /// One match of [`Event::SearchResults`]. Positions are 0-based; columns

View file

@ -43,6 +43,8 @@ pub struct State {
pub syntax: crate::cmd::syntax::Syntax, pub syntax: crate::cmd::syntax::Syntax,
/// PHP and Phpactor (`toolchain.status`). /// PHP and Phpactor (`toolchain.status`).
pub toolchain: crate::cmd::toolchain::Toolchain, pub toolchain: crate::cmd::toolchain::Toolchain,
/// Open integrated terminals (`terminal.*`).
pub terminals: crate::cmd::terminal::Terminals,
/// Number of notifications emitted, for their ids. /// Number of notifications emitted, for their ids.
notifications: u64, notifications: u64,
/// Events queued for the host, oldest first. /// Events queued for the host, oldest first.

View file

@ -62,6 +62,35 @@ pub const SYNTAX_TOKENS: &[&str] = &[
"operator", "operator",
]; ];
/// Terminal token names (`--lt-terminal-<name>`) every theme defines: the
/// terminal's background, text, cursor and selection, and the 16 ANSI
/// colours xterm.js maps escape sequences to. Every ANSI colour that shows
/// as text reaches 4.5:1 on `terminal-bg` (`ui/tests/theme/contrast.test.ts`);
/// the exceptions are the colour meant to vanish into the background: ANSI
/// black in the dark theme, white and bright white in the light one.
pub const TERMINAL_TOKENS: &[&str] = &[
"bg",
"fg",
"cursor",
"selection-bg",
"ansi-black",
"ansi-red",
"ansi-green",
"ansi-yellow",
"ansi-blue",
"ansi-magenta",
"ansi-cyan",
"ansi-white",
"ansi-bright-black",
"ansi-bright-red",
"ansi-bright-green",
"ansi-bright-yellow",
"ansi-bright-blue",
"ansi-bright-magenta",
"ansi-bright-cyan",
"ansi-bright-white",
];
/// The default dark theme. /// The default dark theme.
pub const DARK: Theme = Theme { pub const DARK: Theme = Theme {
id: "lutra-dark", id: "lutra-dark",
@ -97,6 +126,26 @@ pub const DARK: Theme = Theme {
("syntax-tag", "#e08b70"), ("syntax-tag", "#e08b70"),
("syntax-attribute", "#cdb87e"), ("syntax-attribute", "#cdb87e"),
("syntax-operator", "#b8afa6"), ("syntax-operator", "#b8afa6"),
("terminal-bg", "#191817"),
("terminal-fg", "#e6e1da"),
("terminal-cursor", "#d39a5c"),
("terminal-selection-bg", "#513f2c"),
("terminal-ansi-black", "#2e2b28"),
("terminal-ansi-red", "#ef7b6c"),
("terminal-ansi-green", "#a9bd7e"),
("terminal-ansi-yellow", "#e6c46f"),
("terminal-ansi-blue", "#8fa8e0"),
("terminal-ansi-magenta", "#c4a0d6"),
("terminal-ansi-cyan", "#7fbac6"),
("terminal-ansi-white", "#d0c9c1"),
("terminal-ansi-bright-black", "#9a928a"),
("terminal-ansi-bright-red", "#f59a8d"),
("terminal-ansi-bright-green", "#c2d69a"),
("terminal-ansi-bright-yellow", "#f2d88e"),
("terminal-ansi-bright-blue", "#aebff0"),
("terminal-ansi-bright-magenta", "#dbbde8"),
("terminal-ansi-bright-cyan", "#a2d3dc"),
("terminal-ansi-bright-white", "#f5f1ec"),
], ],
}; };
@ -135,6 +184,26 @@ pub const LIGHT: Theme = Theme {
("syntax-tag", "#a5432a"), ("syntax-tag", "#a5432a"),
("syntax-attribute", "#695d1a"), ("syntax-attribute", "#695d1a"),
("syntax-operator", "#5a5149"), ("syntax-operator", "#5a5149"),
("terminal-bg", "#fbfaf8"),
("terminal-fg", "#2a2622"),
("terminal-cursor", "#965a22"),
("terminal-selection-bg", "#e5d7c9"),
("terminal-ansi-black", "#2a2622"),
("terminal-ansi-red", "#b23a29"),
("terminal-ansi-green", "#4e6a24"),
("terminal-ansi-yellow", "#7a5808"),
("terminal-ansi-blue", "#2f55a4"),
("terminal-ansi-magenta", "#73479a"),
("terminal-ansi-cyan", "#24697a"),
("terminal-ansi-white", "#ddd6cd"),
("terminal-ansi-bright-black", "#6b625a"),
("terminal-ansi-bright-red", "#8f2a1c"),
("terminal-ansi-bright-green", "#3b5418"),
("terminal-ansi-bright-yellow", "#5f4404"),
("terminal-ansi-bright-blue", "#233f7f"),
("terminal-ansi-bright-magenta", "#5a3480"),
("terminal-ansi-bright-cyan", "#1a5260"),
("terminal-ansi-bright-white", "#f4f1ec"),
], ],
}; };
@ -280,6 +349,20 @@ mod tests {
} }
} }
#[test]
fn themes_define_the_terminal_tokens() {
for theme in BUILTIN {
let tokens = token_map(theme);
for name in TERMINAL_TOKENS {
assert!(
tokens.contains_key(&format!("--lt-terminal-{name}")),
"{} lacks terminal-{name}",
theme.id
);
}
}
}
#[test] #[test]
fn resolves_settings() { fn resolves_settings() {
assert_eq!(resolve("lutra-light", Some(true)), LIGHT); assert_eq!(resolve("lutra-light", Some(true)), LIGHT);

View file

@ -0,0 +1,212 @@
//! `terminal.*` with a real shell (`cmd.exe` on Windows, `/bin/sh`
//! elsewhere): output and exits arrive through the pump; project close and
//! `app.quit` close terminals.
//!
//! ConPTY asks for the cursor position (`ESC[6n`) when it starts and waits
//! for the answer, which xterm.js gives in the app and [`Pumped`] gives here.
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
use std::time::{Duration, Instant};
use lutra_engine::cmd::terminal::{MAX_OUTPUT_PER_TERMINAL, TerminalEvent};
use lutra_engine::{Engine, Event};
use serde_json::{Value, json};
use tempfile::TempDir;
fn shell() -> &'static str {
if cfg!(windows) { "cmd.exe" } else { "sh" }
}
fn open_project() -> (TempDir, Engine) {
let dir = tempfile::tempdir().unwrap();
let mut engine = Engine::new().unwrap();
engine
.execute("project.open", json!({"path": dir.path()}))
.unwrap();
(dir, engine)
}
fn create(engine: &mut Engine) -> u64 {
let out = engine
.execute(
"terminal.create",
json!({"shell": shell(), "cols": 100, "rows": 30}),
)
.unwrap();
out.value["terminalId"].as_u64().unwrap()
}
/// What the pump reported for one terminal.
#[derive(Default)]
struct Pumped {
output: String,
exit: Option<Option<i64>>,
largest: usize,
answered: usize,
}
/// Pumps until `done` holds or the terminal exited, for at most 30 s.
fn pump_until(engine: &mut Engine, id: u64, seen: &mut Pumped, done: impl Fn(&str) -> bool) {
let deadline = Instant::now() + Duration::from_secs(30);
while Instant::now() < deadline {
for event in engine.pump_vfs().unwrap() {
match event {
Event::Terminal(TerminalEvent::TerminalOutput { terminal_id, data })
if terminal_id == id =>
{
assert!(!data.is_empty());
seen.largest = seen.largest.max(data.len());
seen.output.push_str(&data);
}
Event::Terminal(TerminalEvent::TerminalExited { terminal_id, code })
if terminal_id == id =>
{
seen.exit = Some(code);
}
_ => {}
}
}
while seen.answered < seen.output.matches("\x1b[6n").count() {
input(engine, id, "\x1b[1;1R").unwrap();
seen.answered += 1;
}
if seen.exit.is_some() || done(&seen.output) {
return;
}
std::thread::sleep(Duration::from_millis(10));
}
}
fn input(engine: &mut Engine, id: u64, data: &str) -> Result<Value, lutra_engine::EngineError> {
engine
.execute("terminal.input", json!({"terminalId": id, "data": data}))
.map(|o| o.value)
}
#[test]
fn create_output_input_exit() {
let (_dir, mut engine) = open_project();
let id = create(&mut engine);
assert_eq!(engine.state().terminals.len(), 1);
let mut seen = Pumped::default();
input(&mut engine, id, "echo lutra-term\r").unwrap();
pump_until(&mut engine, id, &mut seen, |out| {
out.matches("lutra-term").count() >= 2
});
assert!(seen.output.contains("lutra-term"), "{:?}", seen.output);
engine
.execute(
"terminal.resize",
json!({"terminalId": id, "cols": 60, "rows": 20}),
)
.unwrap();
input(&mut engine, id, "exit 7\r").unwrap();
pump_until(&mut engine, id, &mut seen, |_| false);
assert_eq!(seen.exit, Some(Some(7)));
assert!(seen.largest <= MAX_OUTPUT_PER_TERMINAL);
assert!(engine.state().terminals.is_empty());
let err = input(&mut engine, id, "x").unwrap_err();
assert_eq!(err.code(), "invalid_params");
}
#[test]
fn bad_params_fail() {
let (_dir, mut engine) = open_project();
for params in [
json!({"cols": 0, "rows": 10}),
json!({"cols": 80, "rows": 1001}),
json!({"cols": 80}),
json!({"cols": 80, "rows": 24, "cwd": "no-such-dir"}),
json!({"cols": 80, "rows": 24, "extra": 1}),
] {
let err = engine
.execute("terminal.create", params.clone())
.unwrap_err();
assert_eq!(err.code(), "invalid_params", "{params}");
}
let err = engine
.execute(
"terminal.create",
json!({"cols": 80, "rows": 24, "shell": "lutra-no-such-shell-x"}),
)
.unwrap_err();
assert_eq!(err.code(), "failed");
let id = create(&mut engine);
let big = "x".repeat(lutra_engine::cmd::terminal::MAX_INPUT_BYTES + 1);
assert_eq!(
input(&mut engine, id, &big).unwrap_err().code(),
"invalid_params"
);
let err = engine
.execute(
"terminal.resize",
json!({"terminalId": id, "cols": 0, "rows": 5}),
)
.unwrap_err();
assert_eq!(err.code(), "invalid_params");
let err = engine
.execute(
"terminal.resize",
json!({"terminalId": 99, "cols": 10, "rows": 5}),
)
.unwrap_err();
assert_eq!(err.code(), "invalid_params");
}
#[test]
fn close_project_close_and_quit_end_terminals() {
let (_dir, mut engine) = open_project();
let a = create(&mut engine);
let out = engine
.execute("terminal.close", json!({"terminalId": a}))
.unwrap();
assert_eq!(out.value["closed"], true);
assert!(
out.events
.contains(&Event::Terminal(TerminalEvent::TerminalExited {
terminal_id: a,
code: None,
}))
);
let out = engine
.execute("terminal.close", json!({"terminalId": a}))
.unwrap();
assert_eq!(out.value["closed"], false);
let b = create(&mut engine);
let out = engine.execute("project.close", json!({})).unwrap();
assert!(
out.events
.contains(&Event::Terminal(TerminalEvent::TerminalExited {
terminal_id: b,
code: None,
}))
);
assert!(engine.state().terminals.is_empty());
let err = engine
.execute("terminal.create", json!({"cols": 80, "rows": 24}))
.unwrap_err();
assert_eq!(err.code(), "disabled");
let (_dir2, mut engine) = open_project();
let c = create(&mut engine);
let d = create(&mut engine);
assert!(d > c);
let out = engine.execute("app.quit", json!({})).unwrap();
for id in [c, d] {
assert!(
out.events
.contains(&Event::Terminal(TerminalEvent::TerminalExited {
terminal_id: id,
code: None,
}))
);
}
assert!(engine.state().terminals.is_empty());
}

View file

@ -12,6 +12,12 @@ publish.workspace = true
layer = 3 layer = 3
[dependencies] [dependencies]
portable-pty = "0.9.0"
thiserror = "2.0.21"
[lints] [lints]
workspace = true workspace = true
[dev-dependencies]
proptest.workspace = true
tempfile.workspace = true

View file

@ -1,4 +1,68 @@
//! Integrated terminal sessions for Lutra (layer L3). //! Integrated terminal sessions for Lutra (layer L3).
//! //!
//! Spawns shells in pseudo-terminals and streams their output to the frontend, //! Spawns shells in pseudo-terminals (`portable-pty`: ConPTY on Windows, a
//! where xterm.js renders it. //! Unix pty elsewhere) and hands their output to the engine, which streams
//! it to the frontend, where xterm.js renders it.
//!
//! A [`Session`] owns three threads, so that no call on it blocks its
//! caller (the engine holds its lock while it calls in):
//!
//! - the **reader** reads the pty, decodes UTF-8 with [`Utf8Chunker`]
//! (a multibyte character split across two reads is joined, invalid
//! bytes become U+FFFD) and appends the text to a bounded output buffer;
//! - the **writer** writes queued input to the pty;
//! - the **waiter** waits for the shell to exit, records the exit code and
//! closes the pty, which ends the reader (ConPTY only reports end of
//! output once the pseudo console is closed).
//!
//! **Output buffer and drop policy:** each session buffers at most
//! [`OUTPUT_CAP`] bytes of decoded text. When the buffer is full the reader
//! stops reading, so the shell blocks on its next write (backpressure, as in
//! a real terminal): output is never dropped while the session runs. Output
//! still buffered when the session is closed or killed is dropped.
//! [`Session::take_output`] drains the buffer in pieces of a size the caller
//! chooses, cut on character boundaries.
//!
//! **Input:** [`Session::write`] queues input for the writer thread; at most
//! [`INPUT_QUEUE_CHUNKS`] pieces of up to [`INPUT_CHUNK`] bytes wait. A full
//! queue refuses more input ([`TerminalError::InputFull`]) instead of
//! blocking.
//!
//! **Exit:** [`Session::exit`] reports the exit code once the shell exited
//! and its output was read to the end (or [`EXIT_GRACE`] passed, for a
//! background process that keeps the pty open) and drained.
mod session;
mod shell;
mod utf8;
pub use session::{
EXIT_GRACE, Exit, INPUT_CHUNK, INPUT_QUEUE_CHUNKS, MAX_SIZE, OUTPUT_CAP, Session, SpawnOptions,
};
pub use shell::{Shell, default_shell, find_in_path};
pub use utf8::Utf8Chunker;
/// Errors of terminal sessions.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum TerminalError {
/// The pseudo terminal could not be created or the shell not started.
#[error("cannot start the terminal: {0}")]
Spawn(String),
/// Resizing the pseudo terminal failed.
#[error("cannot resize the terminal: {0}")]
Resize(String),
/// A size outside `1..=MAX_SIZE` columns or rows.
#[error("invalid terminal size {cols}x{rows}")]
InvalidSize {
/// Requested columns.
cols: u16,
/// Requested rows.
rows: u16,
},
/// The input queue is full; the shell is not reading its input.
#[error("the terminal is not reading its input")]
InputFull,
/// The session has ended; it takes no more input or resizes.
#[error("the terminal has exited")]
Exited,
}

View file

@ -0,0 +1,410 @@
//! One shell in a pseudo terminal; see the crate documentation for the
//! threads, the output buffer and the drop policy.
use std::collections::VecDeque;
use std::ffi::OsString;
use std::io::{ErrorKind, Read, Write};
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, SyncSender, TrySendError, sync_channel};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::thread;
use std::time::{Duration, Instant};
use portable_pty::{ChildKiller, CommandBuilder, MasterPty, PtySize, native_pty_system};
use crate::{Shell, TerminalError, Utf8Chunker};
/// Most bytes of decoded output a session buffers before its reader stops
/// reading (backpressure).
pub const OUTPUT_CAP: usize = 1 << 20;
/// Largest piece of input queued at once; longer input is split.
pub const INPUT_CHUNK: usize = 64 * 1024;
/// Most pieces of input waiting for the writer thread.
pub const INPUT_QUEUE_CHUNKS: usize = 64;
/// Largest number of columns or rows.
pub const MAX_SIZE: u16 = 1000;
/// How long after the shell exited its output may stay open (a background
/// process holding the pty) before the exit is reported anyway.
pub const EXIT_GRACE: Duration = Duration::from_millis(500);
/// Size of one read from the pty.
const READ_BUF: usize = 16 * 1024;
/// How long a reader blocked by a full buffer sleeps before it checks
/// whether the session was closed.
const BACKPRESSURE_POLL: Duration = Duration::from_millis(100);
/// What to start.
#[derive(Debug, Clone)]
pub struct SpawnOptions {
/// The shell and its arguments.
pub shell: Shell,
/// Working directory of the shell.
pub cwd: PathBuf,
/// Columns, `1..=MAX_SIZE`.
pub cols: u16,
/// Rows, `1..=MAX_SIZE`.
pub rows: u16,
/// Extra environment variables, set after `TERM=xterm-256color`,
/// `COLORTERM=truecolor` and `TERM_PROGRAM=Lutra`.
pub env: Vec<(OsString, OsString)>,
}
/// How a session ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Exit {
/// The shell's exit code; `None` if it could not be read.
pub code: Option<i64>,
}
/// State the threads share with the session, behind [`Shared::output`].
#[derive(Debug, Default)]
struct Output {
/// Decoded output not taken yet, oldest first.
text: VecDeque<String>,
/// Total bytes in `text`.
bytes: usize,
/// The reader reached the end of the output.
eof: bool,
/// The session was closed; the reader stops and buffered output is
/// dropped.
closed: bool,
/// The shell exited: its code and when the waiter saw it.
exited: Option<(Option<i64>, Instant)>,
}
/// The output buffer and the condition the reader waits on while it is
/// full.
#[derive(Debug, Default)]
struct Shared {
/// The buffer.
output: Mutex<Output>,
/// Signalled when output was taken or the session closed.
room: Condvar,
}
impl Shared {
/// Locks the buffer, recovering it if a thread panicked while holding
/// it (the buffer stays consistent: every change is a single push or
/// pop).
fn lock(&self) -> MutexGuard<'_, Output> {
self.output.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Appends decoded output, waiting while the buffer is full.
///
/// # Returns
/// `false` once the session is closed; the reader stops then.
fn append(&self, text: String) -> bool {
let mut out = self.lock();
while out.bytes >= OUTPUT_CAP && !out.closed {
out = self
.room
.wait_timeout(out, BACKPRESSURE_POLL)
.map(|(guard, _)| guard)
.unwrap_or_else(|e| e.into_inner().0);
}
if out.closed {
return false;
}
if !text.is_empty() {
out.bytes = out.bytes.saturating_add(text.len());
out.text.push_back(text);
}
true
}
}
/// A running shell in a pseudo terminal. Dropping it kills the shell.
pub struct Session {
/// Output buffer shared with the threads.
shared: Arc<Shared>,
/// Input queue of the writer thread; `None` after [`Session::kill`].
input: Option<SyncSender<Vec<u8>>>,
/// The pty, for resizing; the waiter takes and closes it after the shell
/// exited.
master: Arc<Mutex<Option<Box<dyn MasterPty + Send>>>>,
/// Kills the shell.
killer: Box<dyn ChildKiller + Send + Sync>,
/// Process id of the shell, if the platform reports one.
pid: Option<u32>,
}
impl std::fmt::Debug for Session {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Session")
.field("pid", &self.pid)
.field("buffered", &self.buffered_bytes())
.finish_non_exhaustive()
}
}
/// Checks a size and turns it into a [`PtySize`].
fn pty_size(cols: u16, rows: u16) -> Result<PtySize, TerminalError> {
if !(1..=MAX_SIZE).contains(&cols) || !(1..=MAX_SIZE).contains(&rows) {
return Err(TerminalError::InvalidSize { cols, rows });
}
Ok(PtySize {
rows,
cols,
pixel_width: 0,
pixel_height: 0,
})
}
/// A spawn error from any displayable cause.
fn spawn_error(e: impl std::fmt::Display) -> TerminalError {
TerminalError::Spawn(e.to_string())
}
impl Session {
/// Starts a shell in a new pseudo terminal.
///
/// # Errors
/// [`TerminalError::InvalidSize`] for a size outside `1..=MAX_SIZE`,
/// [`TerminalError::Spawn`] if the pty cannot be created, the program
/// cannot be started (missing, not executable, bad working directory)
/// or a thread cannot be spawned.
pub fn spawn(options: SpawnOptions) -> Result<Self, TerminalError> {
let size = pty_size(options.cols, options.rows)?;
if !options.cwd.is_dir() {
return Err(TerminalError::Spawn(format!(
"{} is not a directory",
options.cwd.display()
)));
}
let pair = native_pty_system().openpty(size).map_err(spawn_error)?;
let mut cmd = CommandBuilder::new(&options.shell.program);
cmd.args(&options.shell.args);
cmd.cwd(&options.cwd);
cmd.env("TERM", "xterm-256color");
cmd.env("COLORTERM", "truecolor");
cmd.env("TERM_PROGRAM", "Lutra");
for (key, value) in &options.env {
cmd.env(key, value);
}
let mut child = pair.slave.spawn_command(cmd).map_err(spawn_error)?;
drop(pair.slave);
let mut killer = child.clone_killer();
let pid = child.process_id();
let started = (|| {
let reader = pair.master.try_clone_reader().map_err(spawn_error)?;
let writer = pair.master.take_writer().map_err(spawn_error)?;
let shared = Arc::new(Shared::default());
let master = Arc::new(Mutex::new(Some(pair.master)));
let (input, queue) = sync_channel(INPUT_QUEUE_CHUNKS);
let reader_shared = Arc::clone(&shared);
thread::Builder::new()
.name("lutra-terminal-read".into())
.spawn(move || read_loop(reader, &reader_shared))
.map_err(spawn_error)?;
thread::Builder::new()
.name("lutra-terminal-write".into())
.spawn(move || write_loop(writer, &queue))
.map_err(spawn_error)?;
let waiter_shared = Arc::clone(&shared);
let waiter_master = Arc::clone(&master);
thread::Builder::new()
.name("lutra-terminal-wait".into())
.spawn(move || {
let code = child.wait().ok().map(|s| i64::from(s.exit_code()));
waiter_shared.lock().exited = Some((code, Instant::now()));
let pty = waiter_master
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take();
drop(pty);
})
.map_err(spawn_error)?;
Ok::<_, TerminalError>((shared, master, input))
})();
let (shared, master, input) = match started {
Ok(parts) => parts,
Err(e) => {
let _ = killer.kill();
return Err(e);
}
};
Ok(Self {
shared,
input: Some(input),
master,
killer,
pid,
})
}
/// Queues input for the shell (keys, pasted text), as UTF-8 bytes.
/// Never blocks: a writer thread writes it.
///
/// # Errors
/// [`TerminalError::Exited`] after the session ended or was killed,
/// [`TerminalError::InputFull`] when [`INPUT_QUEUE_CHUNKS`] pieces are
/// already waiting (the shell is not reading); pieces queued before the
/// queue filled up stay queued.
pub fn write(&self, data: &[u8]) -> Result<(), TerminalError> {
if self.shared.lock().exited.is_some() {
return Err(TerminalError::Exited);
}
let Some(input) = &self.input else {
return Err(TerminalError::Exited);
};
for piece in data.chunks(INPUT_CHUNK) {
match input.try_send(piece.to_vec()) {
Ok(()) => {}
Err(TrySendError::Full(_)) => return Err(TerminalError::InputFull),
Err(TrySendError::Disconnected(_)) => return Err(TerminalError::Exited),
}
}
Ok(())
}
/// Changes the size of the pseudo terminal.
///
/// # Errors
/// [`TerminalError::InvalidSize`] outside `1..=MAX_SIZE`,
/// [`TerminalError::Exited`] after the shell exited,
/// [`TerminalError::Resize`] if the platform refuses.
pub fn resize(&self, cols: u16, rows: u16) -> Result<(), TerminalError> {
let size = pty_size(cols, rows)?;
let master = self.master.lock().unwrap_or_else(PoisonError::into_inner);
let Some(master) = master.as_ref() else {
return Err(TerminalError::Exited);
};
master
.resize(size)
.map_err(|e| TerminalError::Resize(e.to_string()))
}
/// Takes buffered output, oldest first, and wakes a reader waiting for
/// room.
///
/// # Parameters
/// - `max_bytes`: the most bytes to take. The cut falls on a character
/// boundary, so the result may be shorter; it holds at least one
/// character when output is buffered, even if that character is
/// longer than `max_bytes`.
///
/// # Returns
/// The text, empty when nothing is buffered.
pub fn take_output(&self, max_bytes: usize) -> String {
let mut out = self.shared.lock();
let mut taken = String::new();
while let Some(front) = out.text.front_mut() {
let room = max_bytes.saturating_sub(taken.len());
if front.len() <= room {
taken.push_str(front);
out.text.pop_front();
continue;
}
let mut cut = (0..=room)
.rev()
.find(|&i| front.is_char_boundary(i))
.unwrap_or(0);
if cut == 0 && taken.is_empty() {
cut = front.chars().next().map_or(front.len(), char::len_utf8);
}
if cut > 0 {
let rest = front.split_off(cut);
taken.push_str(front);
*front = rest;
}
break;
}
out.bytes = out.bytes.saturating_sub(taken.len());
drop(out);
if !taken.is_empty() {
self.shared.room.notify_all();
}
taken
}
/// Bytes of output buffered and not taken yet.
pub fn buffered_bytes(&self) -> usize {
self.shared.lock().bytes
}
/// How the session ended, once the shell exited, its output was read to
/// the end (or [`EXIT_GRACE`] passed) and every buffered byte was
/// taken. `None` while it runs or output is left.
pub fn exit(&self) -> Option<Exit> {
let out = self.shared.lock();
let (code, at) = out.exited?;
let drained = out.text.is_empty() && (out.eof || at.elapsed() >= EXIT_GRACE);
drained.then_some(Exit { code })
}
/// Process id of the shell, if the platform reports one.
pub fn pid(&self) -> Option<u32> {
self.pid
}
/// Kills the shell unless it already exited, stops the reader and drops
/// buffered output. The pty closes once the waiter sees the exit.
/// Killing is best effort: an error means the process is already gone,
/// so it is ignored.
pub fn kill(&mut self) {
let exited = {
let mut out = self.shared.lock();
out.closed = true;
out.text.clear();
out.bytes = 0;
out.exited.is_some()
};
self.shared.room.notify_all();
self.input = None;
if !exited {
let _ = self.killer.kill();
}
}
}
impl Drop for Session {
fn drop(&mut self) {
self.kill();
}
}
/// The reader thread: reads the pty until its end or an error, decodes
/// UTF-8 and appends the text, waiting while the buffer is full. A read
/// error ends the output like the end of the stream does (on Unix the pty
/// reports EIO once the shell is gone).
fn read_loop(mut reader: Box<dyn Read + Send>, shared: &Shared) {
let mut buf = vec![0u8; READ_BUF];
let mut utf8 = Utf8Chunker::new();
loop {
match reader.read(&mut buf) {
Ok(0) => break,
Ok(n) => {
let text = utf8.push(buf.get(..n).unwrap_or_default());
if !shared.append(text) {
return;
}
}
Err(e) if e.kind() == ErrorKind::Interrupted => {}
Err(_) => break,
}
}
if shared.append(utf8.finish()) {
shared.lock().eof = true;
}
}
/// The writer thread: writes queued input until the session drops its
/// queue or a write fails (the shell is gone; later input is refused by
/// [`Session::write`] once the exit is seen).
fn write_loop(mut writer: Box<dyn Write + Send>, queue: &Receiver<Vec<u8>>) {
for piece in queue {
if writer
.write_all(&piece)
.and_then(|()| writer.flush())
.is_err()
{
return;
}
}
}

View file

@ -0,0 +1,110 @@
//! Which shell a new terminal runs.
use std::ffi::OsString;
use std::path::{Path, PathBuf};
/// A program with its arguments.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Shell {
/// The program: a path, or a name looked up in `PATH`.
pub program: PathBuf,
/// Its arguments.
pub args: Vec<OsString>,
}
impl Shell {
/// A shell without arguments.
pub fn new(program: impl Into<PathBuf>) -> Self {
Self {
program: program.into(),
args: Vec::new(),
}
}
}
/// The shell for a new terminal when the user chose none.
///
/// - **Windows:** `pwsh.exe` (PowerShell 7) from `PATH`, else
/// `powershell.exe` (Windows PowerShell), else `%COMSPEC%`, else
/// `cmd.exe`. PowerShell starts with `-NoLogo`.
/// - **Unix:** `$SHELL`, else `/bin/sh`.
pub fn default_shell() -> Shell {
if cfg!(windows) {
for name in ["pwsh.exe", "powershell.exe"] {
if let Some(path) = find_in_path(name) {
return Shell {
program: path,
args: vec![OsString::from("-NoLogo")],
};
}
}
let comspec = std::env::var_os("COMSPEC")
.map(PathBuf::from)
.filter(|p| p.is_file());
return Shell::new(comspec.unwrap_or_else(|| PathBuf::from("cmd.exe")));
}
let shell = std::env::var_os("SHELL")
.filter(|s| !s.is_empty())
.map(PathBuf::from);
Shell::new(shell.unwrap_or_else(|| PathBuf::from("/bin/sh")))
}
/// Looks a program up in `PATH`.
///
/// # Parameters
/// - `name`: a file name such as `pwsh.exe`. On Windows a name without an
/// extension is also tried with each extension in `PATHEXT`.
///
/// # Returns
/// The first matching file, or `None`. A name with a directory part is
/// returned as is if it is a file.
pub fn find_in_path(name: &str) -> Option<PathBuf> {
let candidate = Path::new(name);
if candidate.components().count() > 1 {
return candidate.is_file().then(|| candidate.to_path_buf());
}
let path = std::env::var_os("PATH")?;
let extensions: Vec<String> = if cfg!(windows) && candidate.extension().is_none() {
std::env::var("PATHEXT")
.unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into())
.split(';')
.filter(|e| !e.is_empty())
.map(str::to_string)
.collect()
} else {
Vec::new()
};
for dir in std::env::split_paths(&path) {
let plain = dir.join(name);
if plain.is_file() {
return Some(plain);
}
for ext in &extensions {
let with_ext = dir.join(format!("{name}{ext}"));
if with_ext.is_file() {
return Some(with_ext);
}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_shell_exists() {
let shell = default_shell();
let found =
shell.program.is_file() || find_in_path(&shell.program.to_string_lossy()).is_some();
assert!(found, "{shell:?}");
}
#[test]
fn finds_programs_in_path() {
let name = if cfg!(windows) { "cmd" } else { "sh" };
assert!(find_in_path(name).is_some());
assert!(find_in_path("lutra-no-such-program-x").is_none());
}
}

137
crates/terminal/src/utf8.rs Normal file
View file

@ -0,0 +1,137 @@
//! Incremental UTF-8 decoding of pty output.
/// Turns a stream of bytes, read in arbitrary pieces, into text.
///
/// A multibyte character split across two pieces is held back until the
/// rest arrives. Invalid sequences become U+FFFD, one per maximal invalid
/// subpart, as [`String::from_utf8_lossy`] does.
#[derive(Debug, Default)]
pub struct Utf8Chunker {
/// The start of a character whose remaining bytes have not arrived;
/// at most 3 bytes.
pending: Vec<u8>,
}
impl Utf8Chunker {
/// A chunker with nothing pending.
pub fn new() -> Self {
Self::default()
}
/// Decodes the next piece of the stream.
///
/// # Returns
/// Every complete character so far, possibly empty. An incomplete
/// character at the end of `bytes` is kept for the next call.
pub fn push(&mut self, bytes: &[u8]) -> String {
let mut input = std::mem::take(&mut self.pending);
input.extend_from_slice(bytes);
let mut out = String::with_capacity(input.len());
let mut rest: &[u8] = &input;
loop {
match std::str::from_utf8(rest) {
Ok(text) => {
out.push_str(text);
break;
}
Err(e) => {
let (valid, after) = rest.split_at(e.valid_up_to());
out.push_str(&String::from_utf8_lossy(valid));
match e.error_len() {
Some(len) => {
out.push(char::REPLACEMENT_CHARACTER);
rest = after.get(len..).unwrap_or_default();
}
None => {
self.pending = after.to_vec();
break;
}
}
}
}
}
out
}
/// Ends the stream: an incomplete character still pending becomes
/// U+FFFD.
pub fn finish(&mut self) -> String {
let pending = std::mem::take(&mut self.pending);
String::from_utf8_lossy(&pending).into_owned()
}
/// Whether bytes of an incomplete character are held back.
pub fn has_pending(&self) -> bool {
!self.pending.is_empty()
}
}
#[cfg(test)]
mod tests {
use proptest::prelude::*;
use super::Utf8Chunker;
#[test]
fn joins_a_character_split_across_reads() {
let bytes = "aä€😀".as_bytes();
for split in 0..=bytes.len() {
let mut c = Utf8Chunker::new();
let (a, b) = bytes.split_at(split);
let text = c.push(a) + &c.push(b) + &c.finish();
assert_eq!(text, "aä€😀", "split at {split}");
}
}
#[test]
fn one_byte_at_a_time() {
let mut c = Utf8Chunker::new();
let mut text = String::new();
for b in "😀x".as_bytes() {
text.push_str(&c.push(&[*b]));
}
assert_eq!(text, "😀x");
assert!(!c.has_pending());
}
#[test]
fn invalid_bytes_become_replacement_characters() {
let mut c = Utf8Chunker::new();
assert_eq!(c.push(b"a\xffb"), "a\u{fffd}b");
assert_eq!(c.push(b"\xe2\x82"), "");
assert!(c.has_pending());
assert_eq!(c.push(b"x"), "\u{fffd}x");
assert_eq!(c.push(b"\xf0\x9f"), "");
assert_eq!(c.finish(), "\u{fffd}");
}
proptest! {
#[test]
fn matches_lossy_decoding_for_any_split(
bytes in proptest::collection::vec(any::<u8>(), 0..64),
cuts in proptest::collection::vec(0usize..64, 0..6),
) {
let mut cuts: Vec<usize> = cuts.into_iter().map(|c| c.min(bytes.len())).collect();
cuts.sort_unstable();
let mut c = Utf8Chunker::new();
let mut text = String::new();
let mut start = 0;
for cut in cuts.into_iter().chain([bytes.len()]) {
text.push_str(&c.push(&bytes[start..cut]));
start = cut;
}
text.push_str(&c.finish());
prop_assert_eq!(text, String::from_utf8_lossy(&bytes).into_owned());
}
#[test]
fn valid_text_round_trips(text in "\\PC{0,40}", cut in 0usize..200) {
let bytes = text.as_bytes();
let cut = cut.min(bytes.len());
let mut c = Utf8Chunker::new();
let out = c.push(&bytes[..cut]) + &c.push(&bytes[cut..]);
prop_assert_eq!(out, text);
prop_assert!(!c.has_pending());
}
}
}

View file

@ -0,0 +1,263 @@
//! Sessions with a real shell: `cmd.exe` on Windows, `/bin/sh` elsewhere.
//!
//! ConPTY asks for the cursor position (`ESC[6n`) when it starts and waits
//! for the answer; xterm.js gives it in the app, [`drive`] gives it here.
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
use std::ffi::OsString;
use std::time::{Duration, Instant};
use lutra_terminal::{Exit, OUTPUT_CAP, Session, Shell, SpawnOptions, TerminalError, find_in_path};
/// The platform's plain shell.
fn plain_shell() -> std::path::PathBuf {
if cfg!(windows) {
find_in_path("cmd.exe").unwrap()
} else {
"/bin/sh".into()
}
}
/// Runs a one-line command with `cmd /c` or `sh -c`.
fn command(windows: &[&str], unix: &str) -> Shell {
let args: Vec<OsString> = if cfg!(windows) {
std::iter::once("/c")
.chain(windows.iter().copied())
.map(OsString::from)
.collect()
} else {
vec!["-c".into(), unix.into()]
};
Shell {
program: plain_shell(),
args,
}
}
/// An interactive plain shell.
fn interactive() -> Shell {
let args = if cfg!(windows) {
vec![OsString::from("/q")]
} else {
Vec::new()
};
Shell {
program: plain_shell(),
args,
}
}
fn spawn(shell: Shell, cols: u16) -> Session {
Session::spawn(SpawnOptions {
shell,
cwd: std::env::temp_dir(),
cols,
rows: 24,
env: Vec::new(),
})
.unwrap()
}
/// Takes output until `done` holds for it or the session exited (then the
/// exit is returned), answering cursor-position queries, for at most 30 s.
fn drive(session: &Session, done: impl Fn(&str) -> bool) -> (String, Option<Exit>) {
let deadline = Instant::now() + Duration::from_secs(30);
let mut all = String::new();
let mut answered = 0;
loop {
all.push_str(&session.take_output(64 * 1024));
let asked = all.matches("\x1b[6n").count();
while answered < asked {
let _ = session.write(b"\x1b[1;1R");
answered += 1;
}
if let Some(exit) = session.exit() {
return (all, Some(exit));
}
if done(&all) || Instant::now() > deadline {
return (all, None);
}
std::thread::sleep(Duration::from_millis(10));
}
}
/// Drives the session to its end.
fn finish(session: &Session) -> (String, Exit) {
let (out, exit) = drive(session, |_| false);
(out, exit.expect("the session did not exit in time"))
}
#[test]
fn echo_output_and_exit_code() {
let s = spawn(command(&["echo", "lutra-ok"], "echo lutra-ok"), 80);
assert!(s.pid().is_some());
let (out, exit) = finish(&s);
assert!(out.contains("lutra-ok"), "{out:?}");
assert_eq!(exit.code, Some(0));
assert_eq!(s.write(b"x"), Err(TerminalError::Exited));
}
#[test]
fn reports_the_exit_code() {
let s = spawn(command(&["exit", "3"], "exit 3"), 80);
assert_eq!(finish(&s).1.code, Some(3));
}
#[test]
fn input_reaches_the_shell() {
let s = spawn(interactive(), 120);
s.write(b"echo lutra-in-%OS%-$0\r").unwrap();
let (out, exit) = drive(&s, |out| out.contains("lutra-in-"));
assert!(exit.is_none());
assert!(out.contains("lutra-in-"), "{out:?}");
s.write(b"exit 5\r").unwrap();
assert_eq!(finish(&s).1.code, Some(5));
}
#[test]
fn multibyte_output_survives_read_boundaries() {
let text = "äöü€".repeat(1500);
let s = spawn(
command(&["echo", &text], &format!("printf '%s' '{text}'")),
200,
);
let (out, exit) = finish(&s);
assert_eq!(exit.code, Some(0));
assert!(!out.contains('\u{fffd}'), "replacement character in output");
assert!(out.matches('€').count() >= 1500, "characters were lost");
}
/// Padding of each line in the backpressure test, so that the output is
/// well over twice [`OUTPUT_CAP`] even if ConPTY drops a few bytes.
const PAD: &str =
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
/// The shell prints a file of about 3 MB with `type` / `cat`, which is
/// fast, so the test depends on the buffer and not on how quickly a shell
/// loop runs on a busy machine.
#[test]
fn a_full_buffer_stops_the_shell_without_dropping_output() {
let lines = 30_000;
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("lines.txt");
let text: String = (1..=lines)
.map(|i| {
format!(
"line-{i}-{PAD}
"
)
})
.collect();
assert!(
text.len() > 2 * OUTPUT_CAP,
"the output must overfill the buffer by far"
);
std::fs::write(&file, text).unwrap();
let path = file.to_string_lossy().into_owned();
let s = spawn(command(&["type", &path], &format!("cat '{path}'")), 200);
let (mut out, exit) = drive(&s, |out| out.contains("line-1-"));
assert!(exit.is_none(), "the shell ended early: {out:?}");
let deadline = Instant::now() + Duration::from_secs(60);
while s.buffered_bytes() < OUTPUT_CAP {
assert!(Instant::now() < deadline, "the buffer never filled");
std::thread::sleep(Duration::from_millis(20));
}
std::thread::sleep(Duration::from_millis(500));
let buffered = s.buffered_bytes();
assert!(
buffered <= OUTPUT_CAP + 64 * 1024,
"buffered {buffered} bytes"
);
assert!(
s.exit().is_none(),
"the shell went on while the buffer was full"
);
let first = s.take_output(10);
assert!(first.len() <= 10 && !first.is_empty());
out.push_str(&first);
let deadline = Instant::now() + Duration::from_secs(120);
let exit = loop {
out.push_str(&s.take_output(256 * 1024));
if let Some(exit) = s.exit() {
break exit;
}
assert!(Instant::now() < deadline, "the shell did not finish");
std::thread::sleep(Duration::from_millis(5));
};
assert_eq!(exit.code, Some(0));
assert!(
out.contains(&format!("line-{lines}-")),
"the last line is missing"
);
let seen = (1..=lines)
.step_by(997)
.filter(|i| out.contains(&format!("line-{i}-")))
.count();
assert_eq!(seen, (1..=lines).step_by(997).count(), "lines were dropped");
}
#[test]
fn resizes_and_rejects_bad_sizes() {
let s = spawn(interactive(), 80);
s.resize(120, 40).unwrap();
assert!(matches!(
s.resize(0, 10),
Err(TerminalError::InvalidSize { .. })
));
assert!(matches!(
s.resize(80, 1001),
Err(TerminalError::InvalidSize { .. })
));
let _ = drive(&s, |out| !out.is_empty());
s.write(b"exit\r").unwrap();
finish(&s);
assert_eq!(s.resize(80, 24), Err(TerminalError::Exited));
}
#[test]
fn kill_ends_the_session() {
let mut s = spawn(interactive(), 80);
let _ = drive(&s, |out| !out.is_empty());
s.kill();
assert_eq!(s.write(b"x"), Err(TerminalError::Exited));
let deadline = Instant::now() + Duration::from_secs(10);
while s.exit().is_none() {
assert!(Instant::now() < deadline, "no exit after kill");
std::thread::sleep(Duration::from_millis(20));
}
assert_eq!(s.buffered_bytes(), 0);
}
#[test]
fn spawn_errors() {
let options = |shell: Shell, cwd: std::path::PathBuf, cols| SpawnOptions {
shell,
cwd,
cols,
rows: 24,
env: Vec::new(),
};
let tmp = std::env::temp_dir();
assert!(matches!(
Session::spawn(options(interactive(), tmp.join("lutra-no-such-dir"), 80)),
Err(TerminalError::Spawn(_))
));
assert!(matches!(
Session::spawn(options(
Shell::new("lutra-no-such-shell-x"),
tmp.clone(),
80
)),
Err(TerminalError::Spawn(_))
));
assert!(matches!(
Session::spawn(options(interactive(), tmp, 0)),
Err(TerminalError::InvalidSize { cols: 0, rows: 24 })
));
}

View file

@ -1,6 +1,6 @@
# Architecture # Architecture
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu, MCP server, autosave and `flushDirty` · **Last updated:** 2026-10-20 > **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu, MCP server, autosave and `flushDirty`, integrated terminal · **Last updated:** 2026-10-20
## Overview ## Overview
@ -113,7 +113,7 @@ Theme tokens are defined in Rust (`lutra_engine::theme`) and rendered as CSS cus
### Events ### Events
`lutra_engine::Event`, serialised as `{"kind": "<camelCase>", ...}`: `projectOpened {root, name}`, `projectClosed`, `treeChanged {dir}`, `bufferOpened {id, path}`, `bufferFocused {id}` (M1.13), `bufferChanged {id, version}`, `dirtyChanged {id, dirty}`, `bufferClosed {id}`, `fileChangedOnDisk {path, id, removed}`, `watchFailed {message}`, `recoveryAvailable {entries}` (M1.7, see Recovery journal), `uiCommand {id, params}` (M1.8, see UI commands), `recoveryResolved {paths}` (M1.15, see Recovery journal), `searchResults {searchId, path, matches}` and `searchDone {searchId, files, matches, truncated, cancelled, elapsedMs}` (M2.3, see Search). Events say what changed; clients fetch data with `project.children` and `buffer.get`. `file.open` on a file whose buffer is already open returns that buffer and emits `bufferFocused {id}` instead of `bufferOpened` (M1.13): a separate event, so that `bufferOpened` keeps meaning "a new buffer exists" (the host's `engine_ready` replay and other clients rely on that) while every client, including the editor, still learns that the user asked to see that buffer and activates its tab. `lutra_engine::Event`, serialised as `{"kind": "<camelCase>", ...}`: `projectOpened {root, name}`, `projectClosed`, `treeChanged {dir}`, `bufferOpened {id, path}`, `bufferFocused {id}` (M1.13), `bufferChanged {id, version}`, `dirtyChanged {id, dirty}`, `bufferClosed {id}`, `fileChangedOnDisk {path, id, removed}`, `watchFailed {message}`, `recoveryAvailable {entries}` (M1.7, see Recovery journal), `uiCommand {id, params}` (M1.8, see UI commands), `recoveryResolved {paths}` (M1.15, see Recovery journal), `searchResults {searchId, path, matches}` and `searchDone {searchId, files, matches, truncated, cancelled, elapsedMs}` (M2.3, see Search), `terminalOutput {terminalId, data}` and `terminalExited {terminalId, code}` (M3.6, see Terminal). Events say what changed; clients fetch data with `project.children` and `buffer.get`. `file.open` on a file whose buffer is already open returns that buffer and emits `bufferFocused {id}` instead of `bufferOpened` (M1.13): a separate event, so that `bufferOpened` keeps meaning "a new buffer exists" (the host's `engine_ready` replay and other clients rely on that) while every client, including the editor, still learns that the user asked to see that buffer and activates its tab.
Changes on disk reach the engine through `Engine::pump_vfs()`, which hosts call regularly (the desktop's pump thread every 100 ms; tests call it directly). It maps VFS events to `treeChanged` for the parent directories, reloads a clean buffer whose file changed (unless the file already matches, as after our own save) with `bufferChanged`, and reports `fileChangedOnDisk` for a dirty buffer, which keeps its text, or for a removed file. At most 10,000 VFS events are handled per pump. Changes on disk reach the engine through `Engine::pump_vfs()`, which hosts call regularly (the desktop's pump thread every 100 ms; tests call it directly). It maps VFS events to `treeChanged` for the parent directories, reloads a clean buffer whose file changed (unless the file already matches, as after our own save) with `bufferChanged`, and reports `fileChangedOnDisk` for a dirty buffer, which keeps its text, or for a removed file. At most 10,000 VFS events are handled per pump.
@ -210,7 +210,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- **Listing:** `listCommands` returns one list in id order: engine commands and UI commands. `CommandInfo` has `ui: bool`; UI commands also carry `labelKey`, use it as `label` (the engine has no English for them) and are always `enabled` as far as the engine knows. - **Listing:** `listCommands` returns one list in id order: engine commands and UI commands. `CommandInfo` has `ui: bool`; UI commands also carry `labelKey`, use it as `label` (the engine has no English for them) and are always `enabled` as far as the engine knows.
- **Running from outside:** `Engine::execute` on a UI command id queues `uiCommand {id, params}` and returns `null` (params are passed on unchanged). The desktop publishes the event to the window and to control subscribers like any other. The frontend runs the command, so `engine.execute palette.open` over the control channel opens the palette. A `uiCommand` the frontend cannot run (no handler, or disabled) becomes a warning toast. - **Running from outside:** `Engine::execute` on a UI command id queues `uiCommand {id, params}` and returns `null` (params are passed on unchanged). The desktop publishes the event to the window and to control subscribers like any other. The frontend runs the command, so `engine.execute palette.open` over the control channel opens the palette. A `uiCommand` the frontend cannot run (no handler, or disabled) becomes a warning toast.
- **Frontend:** `ui/src/commands/`: - **Frontend:** `ui/src/commands/`:
- `uiCommands.ts` lists the UI commands: `editor.reveal` (no shortcut, M2.2), `find.open` `Mod+Alt+F` (M2.4), `menu.open` `Alt+M` (M3.9), `palette.open` `Mod+Shift+P`, `settings.open` `Mod+,`, `view.toggleProjectTree` `Mod+1`. Since M3.9 the user-facing ones carry a `menuPath`. - `uiCommands.ts` lists the UI commands: `editor.reveal` (no shortcut, M2.2), `find.open` `Mod+Alt+F` (M2.4), `menu.open` `Alt+M` (M3.9), `palette.open` `Mod+Shift+P`, `settings.open` `Mod+,`, `terminal.open` `Mod+Shift+T` (M3.6), `view.toggleProjectTree` `Mod+1`. Since M3.9 the user-facing ones carry a `menuPath`.
- `keymap.ts` parses Lutra notation and matches by key code (letters, digits and US punctuation by `code`, so Alt and Shift layout effects don't matter). It also formats shortcuts for display with catalog modifier names. - `keymap.ts` parses Lutra notation and matches by key code (letters, digits and US punctuation by `code`, so Alt and Shift layout effects don't matter). It also formats shortcuts for display with catalog modifier names.
- `rank.ts` ranks for the palette. - `rank.ts` ranks for the palette.
- `store.ts` (Pinia `commands`) holds the merged list, the keymap, the handlers and the recent commands. - `store.ts` (Pinia `commands`) holds the merged list, the keymap, the handlers and the recent commands.
@ -235,7 +235,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- **Where:** `MainLayout.vue` has a slim header bar (28 px, `--lt-bg`, a `header` slot) whose default content is `ui/src/components/menu/AppMenu.vue`: a button with the Lucide `menu` icon top left. - **Where:** `MainLayout.vue` has a slim header bar (28 px, `--lt-bg`, a `header` slot) whose default content is `ui/src/components/menu/AppMenu.vue`: a button with the Lucide `menu` icon top left.
- **Contents (`menu.ts`):** every command in the store's entries with a `menuPath` (engine and UI), grouped by the path's first segment. Groups in Lutra's order File, Edit, View, Go, Help (unknown groups before Help, empty ones hidden), group headings from the catalog (`menu.group.*`). Items follow a fixed id order, others sorted by label after them. A UI command shows its catalog label; an engine command shows the rest of its path (the engine has no catalog, and the path is written for menus), so `buffer.close` reads Close Tab. Deeper paths are flattened as `A › B`. - **Contents (`menu.ts`):** every command in the store's entries with a `menuPath` (engine and UI), grouped by the path's first segment. Groups in Lutra's order File, Edit, View, Go, Help (unknown groups before Help, empty ones hidden), group headings from the catalog (`menu.group.*`). Items follow a fixed id order, others sorted by label after them. A UI command shows its catalog label; an engine command shows the rest of its path (the engine has no catalog, and the path is written for menus), so `buffer.close` reads Close Tab. Deeper paths are flattened as `A › B`.
- **Paths:** File (`project.openDialog`, `file.save`, `file.saveAll`, `buffer.close` → `File/Close Tab`, `project.close`, `app.quit`), View (`palette.open`, `view.toggleProjectTree`, `view.toggleStructure`, `find.open`, `settings.open`), Go (`goto.fileOpen`, `goto.classOpen`, `goto.symbolOpen`), Help (`app.about`). Edit stays empty until there are edit commands; the terminal toggle gets `View/Terminal` when M3.6 lands (its id is already in the order list). - **Paths:** File (`project.openDialog`, `file.save`, `file.saveAll`, `buffer.close` → `File/Close Tab`, `project.close`, `app.quit`), View (`palette.open`, `view.toggleProjectTree`, `view.toggleStructure`, `find.open`, `terminal.open` → `View/Terminal`, `settings.open`), Go (`goto.fileOpen`, `goto.classOpen`, `goto.symbolOpen`), Help (`app.about`). Edit stays empty until there are edit commands.
- **Opening:** the button (a second click closes) or `menu.open` (`Alt+M`, Lutra's own; also as `uiCommand`). It refreshes the enabled states and focuses the first item. - **Opening:** the button (a second click closes) or `menu.open` (`Alt+M`, Lutra's own; also as `uiCommand`). It refreshes the enabled states and focuses the first item.
- **Keyboard:** WAI-ARIA menu with roving focus: arrows wrap, Home/End, Enter/Space runs, Escape or Tab closes, printable keys type ahead (500 ms buffer; one letter cycles through items with that initial). Disabled items are focusable, dimmed (`aria-disabled`) and do nothing. - **Keyboard:** WAI-ARIA menu with roving focus: arrows wrap, Home/End, Enter/Space runs, Escape or Tab closes, printable keys type ahead (500 ms buffer; one letter cycles through items with that initial). Disabled items are focusable, dimmed (`aria-disabled`) and do nothing.
- **Modal rule:** `menu` is an exclusive `ModalId`; the menu is a launcher like the palette: `commands/store.ts` › `execute` closes it for every command but `menu.open`, so a shortcut, a palette command or an agent's `uiCommand` never leaves it open. A chosen command runs after the menu closed and returned the focus. - **Modal rule:** `menu` is an exclusive `ModalId`; the menu is a launcher like the palette: `commands/store.ts` › `execute` closes it for every command but `menu.open`, so a shortcut, a palette command or an agent's `uiCommand` never leaves it open. A chosen command runs after the menu closed and returned the focus.
@ -278,7 +278,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
### Find tool window (M2.4) ### Find tool window (M2.4)
- **Bottom panel:** `ui/src/components/layout/BottomPanel.vue`, under the editor and the left tool window, above the status bar: header with title, collapse/expand and close; a splitter on the top edge (pointer, or Up/Down with Shift for larger steps; 80–900 px, at most 75 % of the window). Height is view state of `MainLayout.vue`; later bottom tool windows (Problems, Terminal) reuse it. Only Find lives there today, so the panel shows while the Find store's `visible` is set; a tab strip comes with the second tool window. - **Bottom panel:** `ui/src/components/layout/BottomPanel.vue`, under the editor and the left tool window, above the status bar: header with title, collapse/expand and close; a splitter on the top edge (pointer, or Up/Down with Shift for larger steps; 80–900 px, at most 75 % of the window). Height is view state of `MainLayout.vue`; later bottom tool windows (Problems, Terminal) reuse it. Since M3.6 it also holds the Terminal tool window and shows tabs while both are visible (see Terminal).
- **Store:** `ui/src/stores/find.ts` (Pinia `find`, started by the main layout) holds the query, the options (`regex`, `caseSensitive`, `wholeWord`, include/exclude as comma-separated globs), the current `searchId`, the files with their matches (a `shallowRef`, replaced per event, kept sorted by path because files arrive in no fixed order), the `searchDone` summary and an inline error. - **Store:** `ui/src/stores/find.ts` (Pinia `find`, started by the main layout) holds the query, the options (`regex`, `caseSensitive`, `wholeWord`, include/exclude as comma-separated globs), the current `searchId`, the files with their matches (a `shallowRef`, replaced per event, kept sorted by path because files arrive in no fixed order), the `searchDone` summary and an inline error.
- **One search at a time:** a new search cancels the running one with `search.cancel` (the engine does not); results of other searches are ignored, and the answer of a search overtaken by a newer one is dropped and cancelled. - **One search at a time:** a new search cancels the running one with `search.cancel` (the engine does not); results of other searches are ignored, and the answer of a search overtaken by a newer one is dropped and cancelled.
- **Event race:** events and the `search.find` answer travel on different channels (Tauri event vs. invoke response), and the pump may publish results before the answer arrives. While `search.find` has not answered, search events are held (at most 5,000) and replayed for the returned id. - **Event race:** events and the `search.find` answer travel on different channels (Tauri event vs. invoke response), and the pump may publish results before the answer arrives. While `search.find` has not answered, search events are held (at most 5,000) and replayed for the returned id.
@ -330,6 +330,18 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- Shutdown: `shutdown(self)` sends `shutdown` (waits up to 2 s), `exit`, kills after 1 s, fails what is pending with `Stopped` and reports `Stopped`; it blocks for up to about 3 s, so callers run it off the engine lock. Dropping the `Server` requests the same stop in the background. - Shutdown: `shutdown(self)` sends `shutdown` (waits up to 2 s), `exit`, kills after 1 s, fails what is pending with `Stopped` and reports `Stopped`; it blocks for up to about 3 s, so callers run it off the engine lock. Dropping the `Server` requests the same stop in the background.
- URIs (`uri`): `path_to_uri` percent-encodes everything except unreserved characters, `/` and a drive colon (`file:///C:/a%20b.php`, UNC as `file://host/share`); `uri_to_path` accepts escapes in any case, an encoded drive colon and `localhost`, and upper-cases the drive letter; bad escapes, NUL and other schemes give `None`. - URIs (`uri`): `path_to_uri` percent-encodes everything except unreserved characters, `/` and a drive colon (`file:///C:/a%20b.php`, UNC as `file://host/share`); `uri_to_path` accepts escapes in any case, an encoded drive colon and `localhost`, and upper-cases the drive letter; bad escapes, NUL and other schemes give `None`.
- Tests: the fake server `src/bin/lutra-lsp-fake.rs` (a test fixture, started via `CARGO_BIN_EXE_lutra-lsp-fake`) covers initialize, server requests, log and stderr, typed requests and errors, queueing before ready, timeout and cancel with `$/cancelRequest`, incremental and full sync (the fake applies the changes and publishes the text as a diagnostic), malformed output, crash, restart and reopen, initialize errors, giving up with the backoff sequence, shutdown and spawn errors (13 tests, about 0.5 s). `real_phpactor` is ignored and runs with `LUTRA_PHPACTOR` (path to `phpactor.phar`, `LUTRA_PHP` for PHP); it was not run in M3.2 (no Phpactor on the dev machine yet; M3.1 downloads it). - Tests: the fake server `src/bin/lutra-lsp-fake.rs` (a test fixture, started via `CARGO_BIN_EXE_lutra-lsp-fake`) covers initialize, server requests, log and stderr, typed requests and errors, queueing before ready, timeout and cancel with `$/cancelRequest`, incremental and full sync (the fake applies the changes and publishes the text as a diagnostic), malformed output, crash, restart and reopen, initialize errors, giving up with the backoff sequence, shutdown and spawn errors (13 tests, about 0.5 s). `real_phpactor` is ignored and runs with `LUTRA_PHPACTOR` (path to `phpactor.phar`, `LUTRA_PHP` for PHP); it was not run in M3.2 (no Phpactor on the dev machine yet; M3.1 downloads it).
### Terminal (M3.6)
- **Library:** `crates/terminal` (L3) wraps `portable-pty` (MIT; ConPTY on Windows, a Unix pty elsewhere). `Session::spawn(SpawnOptions {shell, cwd, cols, rows, env})` starts the shell with `TERM=xterm-256color`, `COLORTERM=truecolor`, `TERM_PROGRAM=Lutra`. Each session has three threads, so no call blocks the caller: a reader (16 KiB reads, `Utf8Chunker` joins a character split across reads and turns invalid bytes into U+FFFD like `from_utf8_lossy`), a writer (input queue of at most 64 pieces of 64 KiB; a full queue fails with `InputFull` instead of blocking), and a waiter that records the exit code and then closes the pty, because ConPTY reports the end of output only once the pseudo console is closed. `default_shell()`: `pwsh.exe` from `PATH` (with `-NoLogo`), then `powershell.exe`, then `%COMSPEC%`/`cmd.exe` on Windows; `$SHELL` or `/bin/sh` on Unix.
- **Buffer and drop policy:** each session buffers at most 1 MiB of decoded text (`OUTPUT_CAP`). When it is full the reader stops reading, so the shell blocks on its next write (backpressure): nothing is dropped while a session runs. Output still buffered when a session is closed or killed is dropped. `exit()` reports the code once the shell exited, its output was read to the end (or 500 ms passed, for a background process that keeps the pty open) and the buffer is empty, so the exit always follows the last output.
- **Engine:** `cmd/terminal.rs`. `terminal.create {cwd?, shell?, cols, rows}` → `{terminalId}` (enabled with a project; cwd project-relative or absolute, default the root; 1–1000 columns and rows; at most 16 terminals), `terminal.input {terminalId, data}` (≤ 1 MiB), `terminal.resize {terminalId, cols, rows}`, `terminal.close {terminalId}` → `{closed}`. Events `terminalOutput {terminalId, data}` and `terminalExited {terminalId, code}` (`code: null` when Lutra closed the terminal) are the variants of `cmd::terminal::TerminalEvent`, appended to `Event` as one untagged variant so that `event.rs` takes a one-line append and each variant keeps its own `kind`. The pump emits one `terminalOutput` per terminal with at most 64 KiB, at most 256 KiB over all terminals, round-robin; with the desktop's 100 ms pump that caps the stream at about 2.5 MB/s and the shell waits beyond it. Under the engine lock only spawning, queueing input, resizing and killing happen.
- **Lifecycle:** a terminal belongs to the project open when it was created. `cmd::terminal::sync_project` runs after every command and every pump and closes terminals whose project is gone (`project.close`, another `project.open`); `app.quit` closes all of them. Dropping a session kills its shell; when the process ends without that, the OS closes the pseudo console (ConPTY) or hangs up the pty (Unix).
- **Cursor query:** ConPTY starts with `ESC[6n` and waits for the answer. xterm.js answers in the app; tests answer it themselves (`crates/terminal/tests/session.rs`, `crates/engine/tests/terminal.rs`, `crates/control/tests/terminal.rs`).
- **Store:** `ui/src/stores/terminal.ts` (Pinia `terminal`): tabs, the active terminal, visibility and expansion of the Terminal tab, an output history per terminal (at most 512 Ki UTF-16 units, oldest event chunks dropped first) that a view replays when it mounts, output that arrives before `terminal.create` answered kept by id, input sent in order with one `terminal.input` in flight (keys typed meanwhile go together), sizes deduplicated. `projectClosed` drops everything.
- **Views:** `ui/src/components/terminal/TerminalToolWindow.vue` has the sub-tab strip ("Local", "Local (2)"…, close buttons, a new-terminal button; Left/Right/Home/End/Delete on a tab) and one `TerminalView.vue` per terminal, kept mounted with `v-show`, so switching sub-tabs keeps xterm's screen; collapsing or hiding the panel unmounts them and the history restores them. `xterm.ts` is the only file that imports `@xterm/xterm` and `@xterm/addon-fit` (MIT), so tests mock it. The fit addon follows a `ResizeObserver` and reports the size with `terminal.resize`. Colours come from the `--lt-terminal-*` tokens (`terminal-bg`, `-fg`, `-cursor`, `-selection-bg` and 16 `-ansi-*` colours, Lutra's own palette), font and size from `--lt-font-mono` and `--lt-font-size-editor`; `themeChanged` re-themes running terminals. Every ANSI colour that shows as text reaches 4.5:1 on `terminal-bg` (contrast test), except the one meant to vanish (black in dark, white and bright white in light); xterm's `minimumContrastRatio` is 4.5, so text a program prints in such a colour (PSReadLine uses white) is darkened or lightened until it is readable. xterm's stylesheet paints the viewport black; the view overrides it with `--lt-terminal-bg`.
- **Focus and shortcut rule** (`ui/src/components/terminal/keys.ts`, applied by the commands store's keydown listener): while a terminal has the focus, only shortcuts with Mod+Shift or Mod+Alt reach Lutra (on macOS every Cmd shortcut); plain Ctrl keys (`Ctrl+C`, `Ctrl+W`, `Ctrl+P`, `Ctrl+1`…) go to the shell. Copy: `Mod+Shift+C`, or `Ctrl+C` with a selection (`Cmd+C` on macOS) through `navigator.clipboard.writeText`. Paste: `Mod+Shift+V` or `Ctrl+V` (`Cmd+V`) are left to the browser, whose `paste` event xterm handles, so no clipboard-read permission is needed.
- **Bottom panel tabs:** `BottomPanel.vue` takes `tabs` and `v-model:active`; with tabs the header shows a tab list instead of the title. `MainLayout.vue` shows Find and Terminal as tabs while both are visible; `find.open` and `terminal.open` make their tool window the active tab, the close button hides the active one, and expansion is kept per tool window.
- **`terminal.open`** (UI command, `Mod+Shift+T`, Lutra's own; enabled with a project): shows the Terminal tab, creates a terminal if none is running (always with `{new: true}`) and focuses it.
### Toolchain (M3.1) ### Toolchain (M3.1)
@ -376,6 +388,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
| 2026-10-20 | minor | M3.10: autosave (blur, tab switch, idle), `flushDirty`, `file.saveAll {skipConflicts}`, disk conflicts and own-write hashes in `Buffers` | | 2026-10-20 | minor | M3.10: autosave (blur, tab switch, idle), `flushDirty`, `file.saveAll {skipConflicts}`, disk conflicts and own-write hashes in `Buffers` |
| 2026-10-19 | minor | M3.8: MCP server (`lutra mcp`, dual era 2026-07-28 + legacy `initialize`), tools, resources, event buffer; `buffer.list` | | 2026-10-19 | minor | M3.8: MCP server (`lutra mcp`, dual era 2026-07-28 + legacy `initialize`), tools, resources, event buffer; `buffer.list` |
| 2026-10-19 | minor | M3.9: app menu (header bar, `menu.open`, grouping by `menuPath`, launcher under the modal rule); menu paths for user commands | | 2026-10-19 | minor | M3.9: app menu (header bar, `menu.open`, grouping by `menuPath`, launcher under the modal rule); menu paths for user commands |
| 2026-10-18 | minor | M3.6: integrated terminal (`crates/terminal` sessions, backpressure, `terminal.*`, `terminalOutput`/`terminalExited` via the pump, lifecycle, xterm.js views, terminal tokens, focus rule, bottom panel tabs) |
| 2026-10-18 | minor | M3.1: toolchain (PHP detection, pinned Phpactor download with SHA-256 check, network access note, D15), `toolchain.status`/`toolchain.downloadPhpactor`, `toolchainChanged`, bool and string settings | | 2026-10-18 | minor | M3.1: toolchain (PHP detection, pinned Phpactor download with SHA-256 check, network access note, D15), `toolchain.status`/`toolchain.downloadPhpactor`, `toolchainChanged`, bool and string settings |
| 2026-10-18 | minor | M3.2: LSP client library (`crates/lsp`: framing, supervision and restart, initialize, requests with timeout and cancel, server requests, document sync, fake server tests) | | 2026-10-18 | minor | M3.2: LSP client library (`crates/lsp`: framing, supervision and restart, initialize, requests with timeout and cancel, server requests, document sync, fake server tests) |
| 2026-10-17 | minor | M3.7: `lutra` CLI, single instance, rendezvous file and token listener, `app.auth`/`app.focus`, CLI to L6 | | 2026-10-17 | minor | M3.7: `lutra` CLI, single instance, rendezvous file and token listener, `app.auth`/`app.focus`, CLI to L6 |

View file

@ -1,6 +1,6 @@
# Gaps # Gaps
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download); G7 under way (`lutra` CLI and single instance, MCP server); G14 English UI catalog in place · **Last updated:** 2026-10-20 > **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G14 English UI catalog in place · **Last updated:** 2026-10-20
Every known shortfall, ranked. This is the work list: unless the owner gives a task, take the highest open gap. Hours are agent wall-clock hours for one agent, all estimated. Every known shortfall, ranked. This is the work list: unless the owner gives a task, take the highest open gap. Hours are agent wall-clock hours for one agent, all estimated.
@ -12,7 +12,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t
| G4 | Syntax and structure: tree-sitter PHP, ~~Lezer highlighting~~ (M2.2: PHP with embedded HTML plus HTML, CSS, JS/TS, JSON, YAML, Markdown; `--lt-syntax-*` tokens; `editor.reveal`), ~~file structure~~ (M2.7: Structure tool window, `syntax.outline`), semantic highlighting, folding in the editor | M2 | ~8 h | | G4 | Syntax and structure: tree-sitter PHP, ~~Lezer highlighting~~ (M2.2: PHP with embedded HTML plus HTML, CSS, JS/TS, JSON, YAML, Markdown; `--lt-syntax-*` tokens; `editor.reveal`), ~~file structure~~ (M2.7: Structure tool window, `syntax.outline`), semantic highlighting, folding in the editor | M2 | ~8 h |
| G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h | | G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h |
| G6 | Language server: completion, diagnostics, definition, hover, rename via Phpactor (~~PHP detection and Phpactor download~~, M3.1) | M3 | ~43 h | | G6 | Language server: completion, diagnostics, definition, hover, rename via Phpactor (~~PHP detection and Phpactor download~~, M3.1) | M3 | ~43 h |
| G7 | Terminal, ~~`lutra` CLI and single instance~~ (M3.7: open folders and files at a line, `--wait`, forwarding a second start, token-protected rendezvous), ~~MCP server~~ (M3.8: `lutra mcp` with list/execute every command, screenshot, read buffer, recent events, open buffers as resources; still missing: resource and tool change notifications, progress for long commands), files outside the open project (the CLI refuses them; needs out-of-project buffers or a second window), `lutra diff` | M3 | ~26 h | | G7 | ~~Terminal~~ (M3.6: PTY sessions, xterm.js sub-tabs in the bottom panel; settings, persistence, links and search still open), ~~`lutra` CLI and single instance~~ (M3.7: open folders and files at a line, `--wait`, forwarding a second start, token-protected rendezvous), ~~MCP server~~ (M3.8: `lutra mcp` with list/execute every command, screenshot, read buffer, recent events, open buffers as resources; still missing: resource and tool change notifications, progress for long commands), files outside the open project (the CLI refuses them; needs out-of-project buffers or a second window), `lutra diff` | M3 | ~16 h |
| G8 | Git integration | M4 | ~150 h | | G8 | Git integration | M4 | ~150 h |
| G9 | Debugger, test runner, Composer, run configurations | M5 | ~300 h | | G9 | Debugger, test runner, Composer, run configurations | M5 | ~300 h |
| G10 | Own indexer, type inference, inspections, refactorings | M6 | ~800 h | | G10 | Own indexer, type inference, inspections, refactorings | M6 | ~800 h |
@ -53,6 +53,7 @@ G6 progress: M3.2 landed the LSP client library in `crates/lsp`: JSON-RPC framin
| 2026-10-20 | minor | G2 shrunk: autosave and `flushDirty` (M3.10) | | 2026-10-20 | minor | G2 shrunk: autosave and `flushDirty` (M3.10) |
| 2026-10-19 | minor | G7: MCP server (M3.8) | | 2026-10-19 | minor | G7: MCP server (M3.8) |
| 2026-10-19 | minor | G3: app menu (M3.9) | | 2026-10-19 | minor | G3: app menu (M3.9) |
| 2026-10-18 | minor | G7: integrated terminal (M3.6), ~26 h → ~16 h |
| 2026-10-18 | minor | G6: PHP detection and pinned Phpactor download (M3.1) | | 2026-10-18 | minor | G6: PHP detection and pinned Phpactor download (M3.1) |
| 2026-10-18 | minor | G6: LSP client library (M3.2) | | 2026-10-18 | minor | G6: LSP client library (M3.2) |
| 2026-10-18 | minor | G17–G21 from the full PhpStorm inventory (deployment, editor productivity, remote, AI, breadth) | | 2026-10-18 | minor | G17–G21 from the full PhpStorm inventory (deployment, editor productivity, remote, AI, breadth) |

View file

@ -9,7 +9,7 @@ Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, t
| M0 | Foundation: workspace, lints, quality gate, command registry, control channel, empty window | done 2026-10-14 (CI workflow written, not yet run: hosted on Forgejo, runners unknown) | ~2 (measured) | | M0 | Foundation: workspace, lints, quality gate, command registry, control channel, empty window | done 2026-10-14 (CI workflow written, not yet run: hosted on Forgejo, runners unknown) | ~2 (measured) |
| M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | done 2026-10-16 (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge, M1.6 tabs and editor, M1.11 message catalog, M1.9a settings backend, M1.10 themes, M1.7 recovery journal, M1.12 notifications, M1.13 C1 follow-ups, M1.8 command palette and keymap, M1.14 app icon, M1.9b settings dialog; C2 live checks pending, gaming mode) | ~5.6 (measured: C1 2.5, C2 3.1) | | M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | done 2026-10-16 (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge, M1.6 tabs and editor, M1.11 message catalog, M1.9a settings backend, M1.10 themes, M1.7 recovery journal, M1.12 notifications, M1.13 C1 follow-ups, M1.8 command palette and keymap, M1.14 app icon, M1.9b settings dialog; C2 live checks pending, gaming mode) | ~5.6 (measured: C1 2.5, C2 3.1) |
| M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | done 2026-10-17 (C3: M2.1 tree-sitter syntax, M2.2 highlighting + `editor.reveal`, M2.3 search backend, M2.4 Find tool window, M2.5 symbol index + go-to commands, M2.6 go-to popup, M2.7 Structure tool window) | ~6.1 (measured) | | M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | done 2026-10-17 (C3: M2.1 tree-sitter syntax, M2.2 highlighting + `editor.reveal`, M2.3 search backend, M2.4 Find tool window, M2.5 symbol index + go-to commands, M2.6 go-to popup, M2.7 Structure tool window) | ~6.1 (measured) |
| M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | in progress (M3.7 CLI and single instance, M3.8 MCP server, M3.10 autosave done) | ~12 | | M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | in progress (M3.7 CLI and single instance, M3.8 MCP server, M3.10 autosave, M3.6 integrated terminal done) | ~12 |
| M4 | Git: status, diff, commit, branches, log, blame, conflicts | not started | ~150 | | M4 | Git: status, diff, commit, branches, log, blame, conflicts | not started | ~150 |
| M5 | Debugger (Xdebug via DAP), PHPUnit/Pest runner, Composer, run configurations | not started | ~300 | | M5 | Debugger (Xdebug via DAP), PHPUnit/Pest runner, Composer, run configurations | not started | ~300 |
| M6 | Own indexer and inspections; Symfony, Laravel, Shopware, WordPress support | not started | ~1,100 | | M6 | Own indexer and inspections; Symfony, Laravel, Shopware, WordPress support | not started | ~1,100 |
@ -35,6 +35,7 @@ By the raw estimates the alpha gate needs M1–M4 plus cross-platform verificati
| Date | Change | Summary | | Date | Change | Summary |
|---|---|---| |---|---|---|
| 2026-10-20 | minor | M3.10 autosave | | 2026-10-20 | minor | M3.10 autosave |
| 2026-10-18 | minor | M3.6 integrated terminal |
| 2026-10-18 | minor | M7–M9 added from the full PhpStorm help inventory (155 feature units); raw hours, calibrate ×0.15 | | 2026-10-18 | minor | M7–M9 added from the full PhpStorm help inventory (155 feature units); raw hours, calibrate ×0.15 |
| 2026-10-19 | minor | M3.8 MCP server | | 2026-10-19 | minor | M3.8 MCP server |
| 2026-10-17 | minor | M3.7 CLI and single instance | | 2026-10-17 | minor | M3.7 CLI and single instance |

View file

@ -1,6 +1,6 @@
# Target-app parity # Target-app parity
> **Status:** M1 done (text buffer, VFS, engine workspace, project tree, tabs and a plain-text editor, recovery, palette, settings and themes in the app); M2 started: PHP syntax highlighting, find in files with its tool window, the symbol index and the go-to popup, the Structure tool window · **Last updated:** 2026-10-20 · **Target:** PhpStorm 2026.x > **Status:** M1 done (text buffer, VFS, engine workspace, project tree, tabs and a plain-text editor, recovery, palette, settings and themes in the app); M2 started: PHP syntax highlighting, find in files with its tool window, the symbol index and the go-to popup, the Structure tool window; M3 started: the integrated terminal · **Last updated:** 2026-10-20 · **Target:** PhpStorm 2026.x
## How this is measured ## How this is measured
@ -23,7 +23,7 @@ Hours are the estimated agent wall-clock hours for one agent to reach behaviour
| Refactoring | 7 | 0% | everything | ~250 (est.) | — | | Refactoring | 7 | 0% | everything | ~250 (est.) | — |
| Code style and formatting | 4 | 0% | everything | ~120 (est.) | — | | Code style and formatting | 4 | 0% | everything | ~120 (est.) | — |
| Git | 8 | 0% | everything | ~150 (est.) | — | | Git | 8 | 0% | everything | ~150 (est.) | — |
| Terminal | 3 | 0% | everything | ~30 (est.) | — | | Terminal | 3 | 15% (est.) | renaming and splitting tabs, sessions kept across restarts, search in the output, clickable paths and links, drag and drop, command completion, terminal settings (shell path, start directory, environment, font, cursor shape, bell, copy on selection, middle-click paste), a key back to the editor, the PHP interpreter in `PATH`, a terminal in a file's directory, confirmation before killing a running process, moving a terminal into the editor | ~26 (est.) | M3.6: `crates/terminal` runs the shell in a pseudo terminal (`portable-pty`: ConPTY on Windows, Unix pty elsewhere) on its own reader, writer and waiter threads: UTF-8 split across reads joined, invalid bytes U+FFFD, a 1 MiB output buffer per session with backpressure (the shell waits, nothing is dropped while it runs), a non-blocking input queue, resize, kill, exit codes. Engine `terminal.create {cwd?, shell?, cols, rows}` / `terminal.input` / `terminal.resize` / `terminal.close`, events `terminalOutput` (≤ 64 KiB per terminal and 256 KiB per pump, round-robin) and `terminalExited {code}`; terminals close with the project and on `app.quit`. UI: a Terminal tab in the bottom panel (tabs next to Find), xterm.js with the fit addon, several terminals as sub-tabs (Local, Local (2)…) with close and new buttons, output replayed after collapsing the panel, copy (`Mod+Shift+C`, `Ctrl+C` with a selection) and paste (`Mod+Shift+V`, `Ctrl+V`), a focus rule that leaves plain Ctrl keys to the shell, Lutra's own ANSI colours (`--lt-terminal-*`, all text colours ≥ 4.5:1), `terminal.open` `Mod+Shift+T`. Tests: 8 session tests with real `cmd.exe` (echo, exit code, input, 6,000 multibyte characters without U+FFFD, 30,000 lines through a full buffer without losing a line, resize, kill, spawn errors) and UTF-8 proptests (`crates/terminal`), 3 engine tests (`crates/engine/tests/terminal.rs`), a TCP control test create → output → input → exit (`crates/control/tests/terminal.rs`), 20 Vitest tests with a mocked xterm (`ui/tests/terminal/`). Live check (Windows 11, debug build with bundled UI, control port 7936, temp project): `terminal.open` showed a pwsh prompt in the project root, first `terminalOutput` 0.2–0.5 s after the command; `php -v` printed PHP 8.4.24 within 0.5–1.5 s; `dir` listed the project; resizing the window changed the shell's width 144 → 190 → 105 → 142 columns (pwsh `WindowSize`); a second terminal as sub-tab "Local (2)"; Find and Terminal as bottom tabs; dark and light screenshots read; `exit 3` gave `terminalExited {code: 3}`; `app.quit` ended the app and its shells (measured). The live check found two bugs, fixed before the commit: xterm's own black viewport background showed as a bar under the last row, and programs printing ANSI white (PSReadLine) were unreadable on the light theme, so xterm now enforces a 4.5:1 minimum contrast. Typing, clicking and copy/paste were not driven in the app (the control channel has no input method); Vitest covers them. Graded against `plan/phpstorm/10-terminal.md` |
| Run configurations | 2 | 0% | everything | ~50 (est.) | — | | Run configurations | 2 | 0% | everything | ~50 (est.) | — |
| Debugger | 5 | 0% | everything | ~120 (est.) | — | | Debugger | 5 | 0% | everything | ~120 (est.) | — |
| Testing | 4 | 0% | everything | ~80 (est.) | — | | Testing | 4 | 0% | everything | ~80 (est.) | — |
@ -66,6 +66,7 @@ The project tree is the first user-visible feature (Project view 8%, estimated);
| Date | Change | Summary | | Date | Change | Summary |
|---|---|---| |---|---|---|
| 2026-10-20 | minor | M3.10: Editor core 10% → 11% (est.), autosave and `flushDirty`; hours 104 → 100 | | 2026-10-20 | minor | M3.10: Editor core 10% → 11% (est.), autosave and `flushDirty`; hours 104 → 100 |
| 2026-10-18 | minor | M3.6: Terminal 0% → 15% (est.), integrated terminal with xterm.js sub-tabs |
| 2026-10-18 | minor | Breadth inventory: 155 units from the public help, 23 partially supported | | 2026-10-18 | minor | Breadth inventory: 155 units from the public help, 23 partially supported |
| 2026-10-17 | minor | M2.6: Navigation 4% → 10% (est.), go-to popup; hours 108 → 102 | | 2026-10-17 | minor | M2.6: Navigation 4% → 10% (est.), go-to popup; hours 108 → 102 |
| 2026-10-17 | minor | M2.7: Navigation 0% → 4% (est.), Structure tool window; hours 112 → 108 | | 2026-10-17 | minor | M2.7: Navigation 0% → 4% (est.), Structure tool window; hours 112 → 108 |

View file

@ -1,8 +1,9 @@
# Tooling checklist # Tooling checklist
> **Status:** baseline · **Last updated:** 2026-10-13 > **Status:** integrated terminal partial (M3.6) · **Last updated:** 2026-10-18
- [ ] Integrated terminal with tabs - [ ] Integrated terminal with tabs
- M3.6 (2026-10-18): PTY sessions (pwsh → powershell → cmd on Windows, `$SHELL` or `/bin/sh` on Unix; cwd = project root) in the bottom panel's Terminal tab, several terminals as sub-tabs, xterm.js rendering with Lutra's colours, copy/paste, resize, exit codes; closed with the project. Missing: settings, persistence across restarts, split tabs, search, links, the PHP interpreter in `PATH`.
- [ ] Git: status, diff, commit, push/pull, branches, log, blame, conflict resolution - [ ] Git: status, diff, commit, push/pull, branches, log, blame, conflict resolution
- [ ] Composer: install, update, require, scripts - [ ] Composer: install, update, require, scripts
- [ ] PHP interpreters: local, Docker - [ ] PHP interpreters: local, Docker
@ -17,4 +18,5 @@
| Date | Change | Summary | | Date | Change | Summary |
|---|---|---| |---|---|---|
| 2026-10-18 | minor | Integrated terminal partial (M3.6) |
| 2026-10-13 | major | Baseline | | 2026-10-13 | major | Baseline |

View file

@ -1,6 +1,6 @@
# UI parity checklist # UI parity checklist
> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8), settings dialog with search (M1.9b), syntax highlighting and `editor.reveal` (M2.2), Find tool window in the bottom panel (M2.4), go-to popup (M2.6), left stripe and Structure tool window (M2.7), app menu (M3.9) · **Last updated:** 2026-10-19 > **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8), settings dialog with search (M1.9b), syntax highlighting and `editor.reveal` (M2.2), Find tool window in the bottom panel (M2.4), go-to popup (M2.6), left stripe and Structure tool window (M2.7), app menu (M3.9), Terminal tool window and bottom panel tabs (M3.6) · **Last updated:** 2026-10-20
- [ ] Main window: tool window stripes, editor area, status bar, navigation bar - [ ] Main window: tool window stripes, editor area, status bar, navigation bar
- M2.7 (2026-10-17): a left stripe with one tab per left tool window (Project, Structure); the shown one is marked, clicking it again hides the window. Still missing: right docking, several bottom tool windows, drag to rearrange, navigation bar, layout persistence. - M2.7 (2026-10-17): a left stripe with one tab per left tool window (Project, Structure); the shown one is marked, clicking it again hides the window. Still missing: right docking, several bottom tool windows, drag to rearrange, navigation bar, layout persistence.
@ -34,6 +34,7 @@
- [ ] Find tool window - [ ] Find tool window
- M2.4 (2026-10-17): docked in the new bottom panel (resizable by pointer and keyboard, collapses to its header, closes; results kept while closed). Query field with case / whole word / regex toggles (`aria-pressed`), include and exclude globs, status line with counts and time, cancel, truncated hint, refused query as an alert; results grouped by file with the match highlighted, a listbox with keyboard navigation; Enter or click reveals the match. `find.open` `Mod+Alt+F`. Missing: tabs per search, grouping options, a preview pane, expand/collapse per file, rerun and next/previous occurrence buttons, context menu, export, history. - M2.4 (2026-10-17): docked in the new bottom panel (resizable by pointer and keyboard, collapses to its header, closes; results kept while closed). Query field with case / whole word / regex toggles (`aria-pressed`), include and exclude globs, status line with counts and time, cancel, truncated hint, refused query as an alert; results grouped by file with the match highlighted, a listbox with keyboard navigation; Enter or click reveals the match. `find.open` `Mod+Alt+F`. Missing: tabs per search, grouping options, a preview pane, expand/collapse per file, rerun and next/previous occurrence buttons, context menu, export, history.
- [ ] Terminal tool window - [ ] Terminal tool window
- M3.6 (2026-10-18): a Terminal tab in the bottom panel (the panel shows Find and Terminal as tabs while both are open; Left/Right switch); xterm.js with the fit addon follows the panel size; several terminals as sub-tabs (Local, Local (2)…) with a close button each and a new-terminal button, Left/Right/Home/End/Delete on a sub-tab, an ended shell dims its tab and prints its exit code; output survives collapsing the panel; copy with `Mod+Shift+C` or `Ctrl+C` on a selection, paste with `Mod+Shift+V` or `Ctrl+V`; while a terminal has the focus plain Ctrl keys go to the shell and only Mod+Shift / Mod+Alt shortcuts reach Lutra; Lutra's own ANSI palette in both themes (text colours ≥ 4.5:1). `terminal.open` `Mod+Shift+T`. Missing: renaming and splitting tabs, a context menu, search, clickable links and paths, drag and drop, a key back to the editor, a confirmation before killing a running process, terminal settings.
- [ ] Git tool window - [ ] Git tool window
## Revision history ## Revision history
@ -41,6 +42,7 @@
| Date | Change | Summary | | Date | Change | Summary |
|---|---|---| |---|---|---|
| 2026-10-19 | minor | Main menu partial (M3.9) | | 2026-10-19 | minor | Main menu partial (M3.9) |
| 2026-10-18 | minor | Terminal tool window partial, bottom panel tabs (M3.6) |
| 2026-10-17 | minor | Go-to popup partial (M2.6) | | 2026-10-17 | minor | Go-to popup partial (M2.6) |
| 2026-10-17 | minor | Structure tool window partial, left stripe (M2.7) | | 2026-10-17 | minor | Structure tool window partial, left stripe (M2.7) |
| 2026-10-17 | minor | Find tool window partial, bottom panel (M2.4) | | 2026-10-17 | minor | Find tool window partial, bottom panel (M2.4) |

View file

@ -29,6 +29,8 @@
"@lezer/highlight": "^1.2.5", "@lezer/highlight": "^1.2.5",
"@lucide/vue": "^1.57.0", "@lucide/vue": "^1.57.0",
"@tauri-apps/api": "^2.12.3", "@tauri-apps/api": "^2.12.3",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"codemirror": "^6.0.2", "codemirror": "^6.0.2",
"pinia": "^4.0.3", "pinia": "^4.0.3",
"vue": "^3.5.44" "vue": "^3.5.44"

16
ui/pnpm-lock.yaml generated
View file

@ -47,6 +47,12 @@ importers:
'@tauri-apps/api': '@tauri-apps/api':
specifier: ^2.12.3 specifier: ^2.12.3
version: 2.12.3 version: 2.12.3
'@xterm/addon-fit':
specifier: ^0.11.0
version: 0.11.0
'@xterm/xterm':
specifier: ^6.0.0
version: 6.0.0
codemirror: codemirror:
specifier: ^6.0.2 specifier: ^6.0.2
version: 6.0.2 version: 6.0.2
@ -607,6 +613,12 @@ packages:
'@vue/server-renderer': '@vue/server-renderer':
optional: true optional: true
'@xterm/addon-fit@0.11.0':
resolution: {integrity: sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==}
'@xterm/xterm@6.0.0':
resolution: {integrity: sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==}
abbrev@5.0.0: abbrev@5.0.0:
resolution: {integrity: sha512-/XrFJgzQQQHpti1raDJC6m4ws6aNktmjBlhk8Fdlk7LwCEuDoieEJJY9OFHjfiFJFFRM2tK+Ky/IsfbbmlMu1w==} resolution: {integrity: sha512-/XrFJgzQQQHpti1raDJC6m4ws6aNktmjBlhk8Fdlk7LwCEuDoieEJJY9OFHjfiFJFFRM2tK+Ky/IsfbbmlMu1w==}
engines: {node: ^22.22.2 || ^24.15.0 || >=26.0.0} engines: {node: ^22.22.2 || ^24.15.0 || >=26.0.0}
@ -1954,6 +1966,10 @@ snapshots:
optionalDependencies: optionalDependencies:
'@vue/server-renderer': 3.5.44 '@vue/server-renderer': 3.5.44
'@xterm/addon-fit@0.11.0': {}
'@xterm/xterm@6.0.0': {}
abbrev@5.0.0: {} abbrev@5.0.0: {}
acorn-jsx@5.3.2(acorn@8.19.0): acorn-jsx@5.3.2(acorn@8.19.0):

View file

@ -8,7 +8,10 @@
* {@link UI_COMMANDS} (also before the engine lists them). * {@link UI_COMMANDS} (also before the engine lists them).
* - **Keymap:** one listener on the window in the capture phase, so * - **Keymap:** one listener on the window in the capture phase, so
* shortcuts also work while CodeMirror or an input has the focus. A * shortcuts also work while CodeMirror or an input has the focus. A
* disabled command's shortcut is swallowed and does nothing. * disabled command's shortcut is swallowed and does nothing. While a
* terminal has the focus, only shortcuts with Mod+Shift or Mod+Alt (any
* Cmd shortcut on macOS) reach Lutra; the shell gets the others (M3.6,
* `components/terminal/keys.ts`).
* - **Handlers:** components supply the behaviour of UI commands and the * - **Handlers:** components supply the behaviour of UI commands and the
* context of engine commands (the editor runs `file.save` with the active * context of engine commands (the editor runs `file.save` with the active
* buffer) with {@link useCommandsStore}'s `provide`. Other engine * buffer) with {@link useCommandsStore}'s `provide`. Other engine
@ -24,6 +27,7 @@ import { hasMessage, t } from "../i18n";
import { listCommands, onEngineEvent, run, type CommandInfo, type EngineEventPayload, type JsonValue } from "../ipc"; import { listCommands, onEngineEvent, run, type CommandInfo, type EngineEventPayload, type JsonValue } from "../ipc";
import { useNotificationsStore } from "../stores/notifications"; import { useNotificationsStore } from "../stores/notifications";
import { useModalsStore } from "./modals"; import { useModalsStore } from "./modals";
import { shortcutReachesLutra } from "../components/terminal/keys";
import { buildKeymap, commandFor, formatShortcut, isMac } from "./keymap"; import { buildKeymap, commandFor, formatShortcut, isMac } from "./keymap";
import { UI_COMMANDS } from "./uiCommands"; import { UI_COMMANDS } from "./uiCommands";
@ -291,7 +295,7 @@ export const useCommandsStore = defineStore("commands", () => {
*/ */
function onKeydown(event: KeyboardEvent): void { function onKeydown(event: KeyboardEvent): void {
const id = commandFor(keymap.value, event); const id = commandFor(keymap.value, event);
if (id === null) { if (id === null || !shortcutReachesLutra(event, isMac())) {
return; return;
} }
event.preventDefault(); event.preventDefault();

View file

@ -29,6 +29,7 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
{ id: "menu.open", labelKey: "command.menu.open", defaultShortcut: "Alt+M" }, { id: "menu.open", labelKey: "command.menu.open", defaultShortcut: "Alt+M" },
{ id: "palette.open", labelKey: "command.palette.open", menuPath: "View/Command Palette", defaultShortcut: "Mod+Shift+P" }, { id: "palette.open", labelKey: "command.palette.open", menuPath: "View/Command Palette", defaultShortcut: "Mod+Shift+P" },
{ id: "settings.open", labelKey: "command.settings.open", menuPath: "View/Settings…", defaultShortcut: "Mod+," }, { id: "settings.open", labelKey: "command.settings.open", menuPath: "View/Settings…", defaultShortcut: "Mod+," },
{ id: "terminal.open", labelKey: "command.terminal.open", menuPath: "View/Terminal", defaultShortcut: "Mod+Shift+T" },
{ id: "view.toggleProjectTree", labelKey: "command.view.toggleProjectTree", menuPath: "View/Project", defaultShortcut: "Mod+1" }, { id: "view.toggleProjectTree", labelKey: "command.view.toggleProjectTree", menuPath: "View/Project", defaultShortcut: "Mod+1" },
{ id: "view.toggleStructure", labelKey: "command.view.toggleStructure", menuPath: "View/Structure", defaultShortcut: "Mod+2" }, { id: "view.toggleStructure", labelKey: "command.view.toggleStructure", menuPath: "View/Structure", defaultShortcut: "Mod+2" },
]; ];

View file

@ -1,9 +1,14 @@
<script setup lang="ts"> <script setup lang="ts">
/** /**
* The bottom panel of the main window: a tool window docked under the * The bottom panel of the main window: tool windows docked under the
* editor (Find since M2.4; later Problems, Terminal and others). A header * editor (Find since M2.4, Terminal since M3.6; later Problems and others).
* with the title, a collapse/expand button and a close button, the content * A header with the title, a collapse/expand button and a close button, the
* slot, and a splitter on the top edge to resize it. * content slot, and a splitter on the top edge to resize it.
*
* Tabs (M3.6): with `tabs`, the header shows one tab per tool window
* instead of the title; a click (or Left/Right on a focused tab) emits
* `update:active`. The owner shows the active tool window's content in the
* slot, and closing hides the active one.
* *
* The splitter is dragged with the pointer or moved with Up/Down (Shift for * The splitter is dragged with the pointer or moved with Up/Down (Shift for
* larger steps) when focused. Collapsed, only the header shows. Height and * larger steps) when focused. Collapsed, only the header shows. Height and
@ -12,9 +17,17 @@
* what closing means. * what closing means.
*/ */
import { ChevronDown, ChevronUp, X } from "@lucide/vue"; import { ChevronDown, ChevronUp, X } from "@lucide/vue";
import { computed } from "vue"; import { computed, nextTick, ref } from "vue";
import { t } from "../../i18n"; import { t } from "../../i18n";
/** A tab of the bottom panel. */
export interface BottomTab {
/** Tool window id. */
id: string;
/** Its title. */
title: string;
}
/** Props of the bottom panel. */ /** Props of the bottom panel. */
const props = withDefaults( const props = withDefaults(
defineProps<{ defineProps<{
@ -28,8 +41,12 @@ const props = withDefaults(
maxHeight?: number; maxHeight?: number;
/** Whether the panel is expanded (true) or collapsed to its header. */ /** Whether the panel is expanded (true) or collapsed to its header. */
open?: boolean; open?: boolean;
/** Tool windows shown as tabs in the header; none shows the title. */
tabs?: readonly BottomTab[];
/** Id of the active tab. */
active?: string;
}>(), }>(),
{ height: 240, minHeight: 80, maxHeight: 900, open: true }, { height: 240, minHeight: 80, maxHeight: 900, open: true, tabs: () => [], active: "" },
); );
/** Events of the bottom panel. */ /** Events of the bottom panel. */
@ -40,8 +57,39 @@ const emit = defineEmits<{
"update:open": [open: boolean]; "update:open": [open: boolean];
/** The close button was pressed. */ /** The close button was pressed. */
close: []; close: [];
/** A tab was chosen. */
"update:active": [id: string];
}>(); }>();
/** The tab list element, to move the focus between tabs. */
const tabList = ref<HTMLElement | null>(null);
/**
* Moves between tabs with Left/Right and activates the new one.
*
* @param event - the key event on a tab.
* @param index - the index of that tab.
*/
async function onTabKey(event: KeyboardEvent, index: number): Promise<void> {
const count = props.tabs.length;
let next: number;
if (event.key === "ArrowRight") {
next = (index + 1) % count;
} else if (event.key === "ArrowLeft") {
next = (index - 1 + count) % count;
} else {
return;
}
event.preventDefault();
const tab = props.tabs[next];
if (!tab) {
return;
}
emit("update:active", tab.id);
await nextTick();
tabList.value?.querySelectorAll<HTMLElement>("[role=tab]")[next]?.focus();
}
/** Inline style carrying the current height. */ /** Inline style carrying the current height. */
const bodyStyle = computed(() => ({ height: `${String(props.height)}px` })); const bodyStyle = computed(() => ({ height: `${String(props.height)}px` }));
@ -118,7 +166,31 @@ function onSplitterKey(event: KeyboardEvent): void {
@keydown="onSplitterKey" @keydown="onSplitterKey"
/> />
<header class="bottom-panel__header"> <header class="bottom-panel__header">
<span class="bottom-panel__title">{{ title }}</span> <span
v-if="tabs.length === 0"
class="bottom-panel__title"
>{{ title }}</span>
<span
v-else
ref="tabList"
class="bottom-panel__tabs"
role="tablist"
:aria-label="t('common.toolWindow.bottomTabs')"
>
<button
v-for="(tab, index) in tabs"
:key="tab.id"
type="button"
role="tab"
class="bottom-panel__tab"
:class="{ 'bottom-panel__tab--active': tab.id === active }"
:aria-selected="tab.id === active"
:tabindex="tab.id === active ? 0 : -1"
:data-test="`bottom-tab-${tab.id}`"
@click="emit('update:active', tab.id)"
@keydown="onTabKey($event, index)"
>{{ tab.title }}</button>
</span>
<span class="bottom-panel__actions"> <span class="bottom-panel__actions">
<button <button
type="button" type="button"
@ -188,6 +260,39 @@ function onSplitterKey(event: KeyboardEvent): void {
white-space: nowrap; white-space: nowrap;
} }
.bottom-panel__tabs {
display: inline-flex;
align-self: stretch;
gap: var(--lt-space-xs, 2px);
min-width: 0;
}
.bottom-panel__tab {
padding: 0 var(--lt-space-m, 8px);
color: var(--lt-fg-muted);
font: inherit;
font-weight: 600;
background: transparent;
border: none;
border-bottom: 2px solid transparent;
cursor: pointer;
white-space: nowrap;
}
.bottom-panel__tab:hover {
color: var(--lt-fg);
}
.bottom-panel__tab--active {
color: var(--lt-fg);
border-bottom-color: var(--lt-accent);
}
.bottom-panel__tab:focus-visible {
outline: 2px solid var(--lt-accent);
outline-offset: -2px;
}
.bottom-panel__actions { .bottom-panel__actions {
display: inline-flex; display: inline-flex;
gap: var(--lt-space-xs, 2px); gap: var(--lt-space-xs, 2px);

View file

@ -15,10 +15,14 @@
* `view.toggleStructure` (`Mod+2`): each shows its tool window, or hides * `view.toggleStructure` (`Mod+2`): each shows its tool window, or hides
* the left window when that tool window is already shown. * the left window when that tool window is already shown.
* *
* The bottom panel ({@link BottomPanel}) holds the Find tool window. It * The bottom panel ({@link BottomPanel}) holds the Find and Terminal tool
* appears with the UI command `find.open` (`Mod+Alt+F`, supplied here so it * windows, as tabs in its header while both are shown. Find appears with
* works before the panel exists), collapses to its header and closes from * the UI command `find.open` (`Mod+Alt+F`), Terminal with `terminal.open`
* its header; the Find store keeps the results while it is closed. * (`Mod+Shift+T`, M3.6); both are supplied here so they work before the
* panel exists, and each makes its tool window the active tab. The panel
* collapses to its header; closing it hides the active tool window (the
* other one, if shown, becomes active). The Find store keeps the results
* and the Terminal store the running terminals while they are hidden.
* *
* A slim header bar along the top (M3.9) holds the app menu * A slim header bar along the top (M3.9) holds the app menu
* ({@link AppMenu}); its `header` slot can replace it. * ({@link AppMenu}); its `header` slot can replace it.
@ -28,7 +32,9 @@ import { computed, onBeforeUnmount, onMounted, ref } from "vue";
import { useCommandsStore } from "../../commands/store"; import { useCommandsStore } from "../../commands/store";
import { t } from "../../i18n"; import { t } from "../../i18n";
import { useFindStore } from "../../stores/find"; import { useFindStore } from "../../stores/find";
import { useTerminalStore } from "../../stores/terminal";
import FindToolWindow from "../find/FindToolWindow.vue"; import FindToolWindow from "../find/FindToolWindow.vue";
import TerminalToolWindow from "../terminal/TerminalToolWindow.vue";
import ProjectToolWindow from "../project/ProjectToolWindow.vue"; import ProjectToolWindow from "../project/ProjectToolWindow.vue";
import StatusBar from "../StatusBar.vue"; import StatusBar from "../StatusBar.vue";
import StructureToolWindow from "../structure/StructureToolWindow.vue"; import StructureToolWindow from "../structure/StructureToolWindow.vue";
@ -72,19 +78,81 @@ function toggleLeft(tool: LeftTool): void {
const commands = useCommandsStore(); const commands = useCommandsStore();
const find = useFindStore(); const find = useFindStore();
const terminal = useTerminalStore();
/** Tool windows of the bottom panel. */
type BottomTool = "find" | "terminal";
/** The bottom tool window last chosen. */
const bottomTool = ref<BottomTool>("find");
/** Bottom tool windows that are shown, in tab order. */
const bottomTools = computed(() => {
const tools: { id: BottomTool; title: string }[] = [];
if (find.visible) tools.push({ id: "find", title: t("find.toolWindow.title") });
if (terminal.visible) tools.push({ id: "terminal", title: t("terminal.toolWindow.title") });
return tools;
});
/** The active bottom tool window: the chosen one if shown, else the first. */
const bottomActive = computed<BottomTool | null>(() => {
const tools = bottomTools.value;
return tools.some((tool) => tool.id === bottomTool.value) ? bottomTool.value : (tools[0]?.id ?? null);
});
/** Expansion of the panel, kept per tool window by its store. */
const bottomOpen = computed({
get: () => (bottomActive.value === "terminal" ? terminal.expanded : find.expanded),
set: (open: boolean) => {
if (bottomActive.value === "terminal") {
terminal.expanded = open;
} else {
find.expanded = open;
}
},
});
/**
* Makes a bottom tool window the active tab.
*
* @param id - the tool window id from the panel.
*/
function chooseBottom(id: string): void {
if (id === "find" || id === "terminal") {
bottomTool.value = id;
}
}
/** Hides the active bottom tool window. */
function closeBottom(): void {
if (bottomActive.value === "terminal") {
terminal.hide();
} else {
find.hide();
}
}
/** Withdraws the command handlers; filled while mounted. */ /** Withdraws the command handlers; filled while mounted. */
let withdraw: (() => void)[] = []; let withdraw: (() => void)[] = [];
onMounted(() => { onMounted(() => {
find.start(); find.start();
terminal.start();
withdraw = [ withdraw = [
commands.provide("view.toggleProjectTree", { commands.provide("view.toggleProjectTree", {
run: () => { run: () => {
toggleLeft("project"); toggleLeft("project");
}, },
}), }),
commands.provide("find.open", { run: (params) => find.open(params) }), commands.provide("find.open", {
run: (params) => {
bottomTool.value = "find";
return find.open(params);
},
}),
commands.provide("terminal.open", {
run: (params) => {
bottomTool.value = "terminal";
return terminal.open(params);
},
enabled: () => commands.isEnabled("terminal.create"),
}),
commands.provide("view.toggleStructure", { commands.provide("view.toggleStructure", {
run: () => { run: () => {
toggleLeft("structure"); toggleLeft("structure");
@ -99,6 +167,7 @@ onBeforeUnmount(() => {
} }
withdraw = []; withdraw = [];
find.stop(); find.stop();
terminal.stop();
}); });
</script> </script>
@ -156,13 +225,20 @@ onBeforeUnmount(() => {
</main> </main>
</div> </div>
<BottomPanel <BottomPanel
v-if="find.visible" v-if="bottomActive !== null"
v-model:height="bottomHeight" v-model:height="bottomHeight"
v-model:open="find.expanded" v-model:open="bottomOpen"
:title="t('find.toolWindow.title')" :title="bottomTools.find((tool) => tool.id === bottomActive)?.title ?? ''"
@close="find.hide()" :tabs="bottomTools.length > 1 ? bottomTools : []"
:active="bottomActive"
@update:active="chooseBottom"
@close="closeBottom"
> >
<FindToolWindow /> <FindToolWindow v-show="bottomActive === 'find'" />
<TerminalToolWindow
v-if="terminal.visible"
v-show="bottomActive === 'terminal'"
/>
</BottomPanel> </BottomPanel>
<StatusBar /> <StatusBar />
</div> </div>

View file

@ -52,7 +52,7 @@ const ITEM_ORDER = [
"view.toggleProjectTree", "view.toggleProjectTree",
"view.toggleStructure", "view.toggleStructure",
"find.open", "find.open",
"terminal.toggle", "terminal.open",
"settings.open", "settings.open",
"goto.fileOpen", "goto.fileOpen",
"goto.classOpen", "goto.classOpen",

View file

@ -0,0 +1,221 @@
<script setup lang="ts">
/**
* The Terminal tool window (M3.6) in the bottom panel: a strip of sub-tabs,
* one per terminal, with a close button each and a button for a new
* terminal, above the shown terminal. Every terminal's view stays mounted
* while the window is, so switching sub-tabs keeps xterm's screen and
* scrollback; collapsing or hiding the panel unmounts them, and the store's
* history restores the output when they mount again.
*
* Sub-tabs are a tab list: Left/Right move between them, Home/End jump,
* Delete closes the focused one. An ended terminal's tab is dimmed.
*/
import { Plus, X } from "@lucide/vue";
import { nextTick, ref } from "vue";
import { t } from "../../i18n";
import { useTerminalStore } from "../../stores/terminal";
import TerminalView from "./TerminalView.vue";
const store = useTerminalStore();
/** The tab list element, to move the focus between tabs. */
const strip = ref<HTMLElement | null>(null);
/**
* Moves between sub-tabs with the keyboard.
*
* @param event - the key event on a tab.
* @param id - the terminal of that tab.
*/
async function onTabKey(event: KeyboardEvent, id: number): Promise<void> {
const ids = store.tabs.map((tab) => tab.id);
const index = ids.indexOf(id);
let next: number | undefined;
if (event.key === "ArrowRight") {
next = ids[(index + 1) % ids.length];
} else if (event.key === "ArrowLeft") {
next = ids[(index - 1 + ids.length) % ids.length];
} else if (event.key === "Home") {
next = ids[0];
} else if (event.key === "End") {
next = ids[ids.length - 1];
} else if (event.key === "Delete") {
event.preventDefault();
await store.close(id);
return;
} else {
return;
}
event.preventDefault();
if (next === undefined) {
return;
}
store.activeId = next;
await nextTick();
strip.value?.querySelector<HTMLElement>(`[data-terminal-tab="${String(next)}"]`)?.focus();
}
</script>
<template>
<div
class="terminal-window"
data-test="terminal-window"
>
<div class="terminal-window__bar">
<div
ref="strip"
class="terminal-window__tabs"
role="tablist"
:aria-label="t('terminal.tabs.label')"
>
<span
v-for="tab in store.tabs"
:key="tab.id"
class="terminal-window__tab"
:class="{
'terminal-window__tab--active': tab.id === store.activeId,
'terminal-window__tab--exited': tab.exited,
}"
>
<button
type="button"
role="tab"
class="terminal-window__tab-label"
:aria-selected="tab.id === store.activeId"
:tabindex="tab.id === store.activeId ? 0 : -1"
:data-terminal-tab="tab.id"
data-test="terminal-tab"
@click="store.activate(tab.id)"
@keydown="onTabKey($event, tab.id)"
>{{ tab.exited ? t('terminal.tab.exited', { title: tab.title }) : tab.title }}</button>
<button
type="button"
class="terminal-window__icon"
:title="t('terminal.tab.close', { title: tab.title })"
:aria-label="t('terminal.tab.close', { title: tab.title })"
data-test="terminal-tab-close"
@click="store.close(tab.id)"
>
<X :size="12" />
</button>
</span>
</div>
<button
type="button"
class="terminal-window__icon"
:title="t('terminal.new')"
:aria-label="t('terminal.new')"
data-test="terminal-new"
@click="store.open({ new: true })"
>
<Plus :size="14" />
</button>
</div>
<p
v-if="store.error !== null"
class="terminal-window__error"
role="alert"
data-test="terminal-error"
>
{{ t('terminal.error.create', { message: store.error }) }}
</p>
<div class="terminal-window__views">
<TerminalView
v-for="tab in store.tabs"
v-show="tab.id === store.activeId"
:key="tab.id"
:terminal-id="tab.id"
:active="tab.id === store.activeId"
role="tabpanel"
:aria-label="tab.title"
/>
</div>
</div>
</template>
<style scoped>
.terminal-window {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
height: 100%;
}
.terminal-window__bar {
display: flex;
align-items: center;
gap: var(--lt-space-xs, 2px);
flex: none;
padding: var(--lt-space-xs, 2px) var(--lt-space-s, 4px);
border-bottom: 1px solid var(--lt-border);
}
.terminal-window__tabs {
display: flex;
gap: var(--lt-space-xs, 2px);
min-width: 0;
overflow-x: auto;
}
.terminal-window__tab {
display: inline-flex;
align-items: center;
flex: none;
border-radius: var(--lt-radius, 4px);
color: var(--lt-fg-muted);
}
.terminal-window__tab--active {
color: var(--lt-fg);
background: var(--lt-tab-active-bg);
}
.terminal-window__tab--exited .terminal-window__tab-label {
font-style: italic;
}
.terminal-window__tab-label {
padding: var(--lt-space-xs, 2px) var(--lt-space-s, 4px) var(--lt-space-xs, 2px) var(--lt-space-m, 8px);
color: inherit;
font: inherit;
background: transparent;
border: none;
cursor: pointer;
white-space: nowrap;
}
.terminal-window__icon {
display: inline-flex;
align-items: center;
justify-content: center;
padding: var(--lt-space-xs, 2px);
color: var(--lt-fg-muted);
background: transparent;
border: none;
border-radius: var(--lt-radius, 4px);
cursor: pointer;
}
.terminal-window__icon:hover,
.terminal-window__tab-label:hover {
color: var(--lt-fg);
}
.terminal-window__tab-label:focus-visible,
.terminal-window__icon:focus-visible {
outline: 2px solid var(--lt-accent);
}
.terminal-window__error {
margin: 0;
padding: var(--lt-space-s, 4px) var(--lt-space-m, 8px);
color: var(--lt-error);
}
.terminal-window__views {
display: flex;
flex: 1;
min-height: 0;
background: var(--lt-terminal-bg);
}
</style>

View file

@ -0,0 +1,172 @@
<script setup lang="ts">
/**
* One terminal (M3.6): an xterm.js instance bound to an engine terminal.
*
* On mount it replays the output the store kept, then writes new output as
* it arrives. Keys and pasted text go to the store (`terminal.input`).
* The fit addon sizes the terminal to its element whenever the element
* changes size (panel splitter, window), and the store reports the size
* with `terminal.resize`. Colours, font and size come from the `--lt-*`
* tokens and follow `themeChanged`. Copy, paste and which shortcuts reach
* Lutra follow the rules in `keys.ts`.
*/
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import { isMac } from "../../commands/keymap";
import { onEngineEvent, type EngineEventPayload } from "../../ipc";
import { useTerminalStore } from "../../stores/terminal";
import { clipboardAction, TERMINAL_ATTRIBUTE } from "./keys";
import { createXterm, terminalTheme, type XtermHandle } from "./xterm";
/** Props of the view. */
const props = defineProps<{
/** The engine terminal. */
terminalId: number;
/** Whether this view is the shown sub-tab. */
active: boolean;
}>();
const store = useTerminalStore();
/** The element xterm renders into. */
const host = ref<HTMLElement | null>(null);
/** The terminal; null until mounted. */
let xterm: XtermHandle | null = null;
/** Cleanups to run on unmount. */
const cleanups: (() => void)[] = [];
/** Fits the terminal to its element and reports the size. */
function fit(): void {
if (!xterm || !props.active) {
return;
}
const size = xterm.fit();
if (size) {
void store.resize(props.terminalId, size.cols, size.rows);
}
}
/**
* Handles the clipboard keys; every other key goes to xterm.
*
* @param event - the key event xterm received.
* @returns false when xterm should not handle the key.
*/
function onKey(event: KeyboardEvent): boolean {
const term = xterm?.term;
if (!term) {
return true;
}
const action = clipboardAction(event, term.hasSelection(), isMac());
if (action === "copy") {
event.preventDefault();
const text = term.getSelection();
if (text !== "") {
navigator.clipboard.writeText(text).catch(() => undefined);
}
return false;
}
return action !== "paste";
}
/**
* Applies a new theme's tokens.
*
* @param event - an engine event.
*/
function onEvent(event: EngineEventPayload): void {
if (event.kind === "themeChanged" && xterm && typeof event.tokens === "object") {
const tokens = event.tokens;
xterm.term.options.theme = terminalTheme((name) => tokens[name] ?? "");
}
}
onMounted(() => {
const element = host.value;
if (!element) {
return;
}
xterm = createXterm(navigator.userAgent.includes("Windows"));
const term = xterm.term;
term.open(element);
term.attachCustomKeyEventHandler(onKey);
const { replay, detach } = store.attach(props.terminalId, (data) => {
term.write(data);
});
if (replay !== "") {
term.write(replay);
}
cleanups.push(detach);
const typed = term.onData((data) => {
store.input(props.terminalId, data);
});
cleanups.push(() => {
typed.dispose();
});
cleanups.push(onEngineEvent(onEvent));
if (typeof ResizeObserver !== "undefined") {
const observer = new ResizeObserver(() => {
fit();
});
observer.observe(element);
cleanups.push(() => {
observer.disconnect();
});
}
fit();
if (props.active) {
term.focus();
}
});
watch(
() => [props.active, store.focusRequest] as const,
([active]) => {
if (active && xterm) {
requestAnimationFrame(() => {
fit();
xterm?.term.focus();
});
}
},
);
onBeforeUnmount(() => {
for (const fn of cleanups) {
fn();
}
cleanups.length = 0;
xterm?.term.dispose();
xterm = null;
});
</script>
<template>
<div
ref="host"
class="terminal-view"
v-bind="{ [TERMINAL_ATTRIBUTE]: '' }"
data-test="terminal-view"
/>
</template>
<style scoped>
.terminal-view {
flex: 1;
min-height: 0;
min-width: 0;
padding: var(--lt-space-xs, 2px) 0 0 var(--lt-space-s, 4px);
background: var(--lt-terminal-bg);
}
.terminal-view :deep(.xterm) {
height: 100%;
}
.terminal-view :deep(.xterm .xterm-viewport) {
background-color: var(--lt-terminal-bg);
}
.terminal-view :deep(.xterm .composition-view) {
color: var(--lt-fg);
background: var(--lt-notice-bg);
}
</style>

View file

@ -0,0 +1,79 @@
/**
* Keyboard rules of the integrated terminal (M3.6).
*
* **Focus and shortcut rule:** while a terminal has the focus, keys belong
* to the shell. A Lutra shortcut still reaches Lutra when it uses Mod
* together with Shift or Alt (`Mod+Shift+P` palette, `Mod+Alt+F` Find,
* `Mod+Shift+T` terminal…), or on macOS any Cmd shortcut, since shells get
* no Cmd keys. Plain `Ctrl+<key>` and single keys go to the shell, so
* `Ctrl+C`, `Ctrl+W`, `Ctrl+P`, `Ctrl+R`, `Ctrl+1`… keep their shell
* meaning.
*
* **Copy and paste:** `Mod+Shift+C` copies the selection, `Mod+Shift+V`
* pastes. On Windows and Linux `Ctrl+C` copies when text is selected (and
* otherwise interrupts, as the shell expects) and `Ctrl+V` pastes; on macOS
* `Cmd+C` and `Cmd+V` do.
*/
/** Attribute on the element that holds a terminal. */
export const TERMINAL_ATTRIBUTE = "data-lt-terminal";
/**
* Whether the focus of a key event is inside a terminal.
*
* @param event - the key event.
* @returns true when its target lies in an element with
* {@link TERMINAL_ATTRIBUTE}.
*/
export function inTerminal(event: KeyboardEvent): boolean {
const target = event.target;
return target instanceof Element && target.closest(`[${TERMINAL_ATTRIBUTE}]`) !== null;
}
/**
* Whether a key event that matches a Lutra shortcut should run it, given
* the focus rule above.
*
* @param event - the key event.
* @param mac - whether Lutra runs on macOS.
* @returns false when a terminal has the focus and the shell should get
* the key.
*/
export function shortcutReachesLutra(event: KeyboardEvent, mac: boolean): boolean {
if (!inTerminal(event)) {
return true;
}
if (mac) {
return event.metaKey;
}
return event.ctrlKey && (event.shiftKey || event.altKey);
}
/** What a key in the terminal does with the clipboard. */
export type ClipboardAction = "copy" | "paste" | null;
/**
* The clipboard action of a key event in the terminal.
*
* @param event - the keydown event.
* @param hasSelection - whether the terminal has selected text.
* @param mac - whether Lutra runs on macOS.
* @returns the action, or null when the key goes to the shell.
*/
export function clipboardAction(event: KeyboardEvent, hasSelection: boolean, mac: boolean): ClipboardAction {
if (event.type !== "keydown" || event.altKey) {
return null;
}
const key = event.code;
const mod = mac ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;
if (!mod) {
return null;
}
if (key === "KeyC" && (event.shiftKey || hasSelection || mac)) {
return "copy";
}
if (key === "KeyV") {
return "paste";
}
return null;
}

View file

@ -0,0 +1,110 @@
/**
* The xterm.js boundary (M3.6): creates a terminal with the fit addon and
* maps Lutra's theme tokens onto xterm's theme. Kept apart so that tests
* can replace it (`vi.mock`), since jsdom cannot lay xterm out.
*/
import { FitAddon } from "@xterm/addon-fit";
import { Terminal, type ITheme } from "@xterm/xterm";
import "@xterm/xterm/css/xterm.css";
/** The parts of an xterm terminal the view uses. */
export interface XtermHandle {
/** The terminal. */
term: Pick<
Terminal,
| "open"
| "write"
| "focus"
| "dispose"
| "onData"
| "hasSelection"
| "getSelection"
| "attachCustomKeyEventHandler"
| "options"
| "cols"
| "rows"
>;
/** Fits the terminal into its element; returns the new size. */
fit: () => { cols: number; rows: number } | null;
}
/**
* Contrast xterm enforces for every glyph against its background (WCAG AA
* for text). Programs often assume a dark background and print ANSI white,
* which the light theme keeps light on purpose; xterm darkens such text
* until it reaches this ratio.
*/
export const MINIMUM_CONTRAST = 4.5;
/** ANSI colour names in xterm's order, as in `--lt-terminal-ansi-<name>`. */
export const ANSI_NAMES = ["black", "red", "green", "yellow", "blue", "magenta", "cyan", "white"] as const;
/**
* xterm's theme from Lutra's tokens.
*
* @param token - reads a token by its full name (`--lt-terminal-bg`);
* returns "" for a missing one, which xterm then replaces by its default.
* @returns the theme.
*/
export function terminalTheme(token: (name: string) => string): ITheme {
const read = (name: string): string | undefined => {
const value = token(`--lt-terminal-${name}`).trim();
return value === "" ? undefined : value;
};
const theme: Record<string, string | undefined> = {
background: read("bg"),
foreground: read("fg"),
cursor: read("cursor"),
cursorAccent: read("bg"),
selectionBackground: read("selection-bg"),
};
for (const name of ANSI_NAMES) {
theme[name] = read(`ansi-${name}`);
theme[`bright${name.charAt(0).toUpperCase()}${name.slice(1)}`] = read(`ansi-bright-${name}`);
}
return theme;
}
/**
* Reads a token from the document's computed style.
*
* @param name - the full custom property name.
* @returns its value, or "".
*/
export function documentToken(name: string): string {
return getComputedStyle(document.documentElement).getPropertyValue(name);
}
/**
* Creates a terminal.
*
* @param windows - whether the shell runs under ConPTY (Windows), which
* xterm handles specially when it reflows lines.
* @returns the terminal and its fit function.
*/
export function createXterm(windows: boolean): XtermHandle {
const fontSize = Number.parseFloat(documentToken("--lt-font-size-editor"));
const term = new Terminal({
allowProposedApi: false,
cursorBlink: true,
minimumContrastRatio: MINIMUM_CONTRAST,
scrollback: 5000,
fontFamily: documentToken("--lt-font-mono").trim() || "monospace",
fontSize: Number.isFinite(fontSize) ? fontSize : 14,
theme: terminalTheme(documentToken),
...(windows ? { windowsPty: { backend: "conpty" as const } } : {}),
});
const fitAddon = new FitAddon();
term.loadAddon(fitAddon);
return {
term,
fit: () => {
const size = fitAddon.proposeDimensions();
if (!size || !Number.isFinite(size.cols) || !Number.isFinite(size.rows) || size.cols < 1 || size.rows < 1) {
return null;
}
fitAddon.fit();
return { cols: term.cols, rows: term.rows };
},
};
}

View file

@ -13,6 +13,7 @@
"command.menu.open": "Open Main Menu", "command.menu.open": "Open Main Menu",
"command.palette.open": "Command Palette", "command.palette.open": "Command Palette",
"command.settings.open": "Settings…", "command.settings.open": "Settings…",
"command.terminal.open": "Terminal",
"command.unavailable": "{command} cannot run right now", "command.unavailable": "{command} cannot run right now",
"command.view.toggleProjectTree": "Show or Hide Project", "command.view.toggleProjectTree": "Show or Hide Project",
"command.view.toggleStructure": "Show or Hide Structure", "command.view.toggleStructure": "Show or Hide Structure",
@ -22,6 +23,7 @@
"common.dontSave": "Don't Save", "common.dontSave": "Don't Save",
"common.error.unexpectedResult": "unexpected result of {command}", "common.error.unexpectedResult": "unexpected result of {command}",
"common.save": "Save", "common.save": "Save",
"common.toolWindow.bottomTabs": "Bottom tool windows",
"common.toolWindow.collapse": "Collapse {title}", "common.toolWindow.collapse": "Collapse {title}",
"common.toolWindow.expand": "Expand {title}", "common.toolWindow.expand": "Expand {title}",
"common.toolWindow.hide": "Hide {title}", "common.toolWindow.hide": "Hide {title}",
@ -162,6 +164,17 @@
"structure.kind.trait": "Trait", "structure.kind.trait": "Trait",
"structure.toolWindow.title": "Structure", "structure.toolWindow.title": "Structure",
"structure.tree.label": "Declarations of the file", "structure.tree.label": "Declarations of the file",
"terminal.error.badAnswer": "The engine answered without a terminal id",
"terminal.error.create": "Cannot start a terminal: {message}",
"terminal.exited.closed": "Terminal closed",
"terminal.exited.code": "Process exited with code {code}",
"terminal.new": "New terminal",
"terminal.tab.close": "Close {title}",
"terminal.tab.exited": "{title} (ended)",
"terminal.tab.first": "Local",
"terminal.tab.numbered": "Local ({n})",
"terminal.tabs.label": "Terminals",
"terminal.toolWindow.title": "Terminal",
"theme.lutraDark": "Lutra Dark", "theme.lutraDark": "Lutra Dark",
"theme.lutraLight": "Lutra Light" "theme.lutraLight": "Lutra Light"
} }

View file

@ -106,6 +106,20 @@ export type EngineEventPayload =
symbols: unknown; symbols: unknown;
/** Build time in milliseconds; unchecked. */ /** Build time in milliseconds; unchecked. */
elapsedMs: unknown; elapsedMs: unknown;
}
| {
kind: "terminalOutput";
/** Terminal from `terminal.create`; unchecked, it comes from the engine. */
terminalId: unknown;
/** UTF-8 text with escape sequences; unchecked. */
data: unknown;
}
| {
kind: "terminalExited";
/** Terminal from `terminal.create`; unchecked. */
terminalId: unknown;
/** Exit code, null when Lutra closed it; unchecked. */
code: unknown;
}; };
/** Callback receiving engine events. */ /** Callback receiving engine events. */

408
ui/src/stores/terminal.ts Normal file
View file

@ -0,0 +1,408 @@
/**
* The Terminal tool window's state (M3.6): the open terminals (sub-tabs),
* their output and the panel's visibility.
*
* - **Sessions:** `create` runs `terminal.create` (cwd = project root, the
* engine's default shell) and adds a tab. Output arrives as
* `terminalOutput` events; `terminalExited` marks the tab as ended and
* writes a line saying so. Closing a tab runs `terminal.close` for a
* running one. The engine closes every terminal with the project, so
* `projectClosed` drops the tabs.
* - **Output history:** every terminal's output is kept here, at most
* {@link HISTORY_CAP} UTF-16 code units per terminal; older output is
* dropped from the front (whole event chunks, so an escape sequence may be
* cut). A view that mounts (switching tabs, expanding the panel) replays
* it, then receives new output through `attach`. Output that arrives
* before `terminal.create` answered is kept by id, since events and
* command results travel on different channels.
* - **Input:** keys go out in order, one `terminal.input` at a time; keys
* typed while one is in flight are sent together afterwards.
* - **Opening:** `open` (the UI command `terminal.open`) shows the panel,
* creates a terminal if none is running (or always with `{new: true}`)
* and asks the active view to take the focus.
* - **Untrusted input:** event fields are checked; events of unknown shape
* are ignored.
*/
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { t } from "../i18n";
import { onEngineEvent, run, type EngineEventPayload } from "../ipc";
import { useNotificationsStore } from "./notifications";
/** Most UTF-16 code units of output kept per terminal for replay. */
export const HISTORY_CAP = 512 * 1024;
/** Size a terminal starts with before its view measured itself. */
export const DEFAULT_SIZE = { cols: 80, rows: 24 } as const;
/** One terminal as the tab strip shows it. */
export interface TerminalTab {
/** Engine terminal id. */
id: number;
/** Tab label. */
title: string;
/** Whether the shell ended. */
exited: boolean;
}
/** Receives new output of one terminal. */
export type TerminalWriter = (data: string) => void;
/** Output kept for one terminal. */
interface History {
/** Chunks, oldest first. */
chunks: string[];
/** Total length of `chunks`. */
length: number;
}
/** Input of one terminal waiting to be sent. */
interface Outbox {
/** Text not sent yet. */
pending: string;
/** Whether a `terminal.input` is in flight. */
busy: boolean;
}
/**
* The text written into a terminal when its shell ended.
*
* @param code - the exit code, or null when Lutra closed it.
* @returns the line, dimmed, on a line of its own.
*/
export function exitLine(code: number | null): string {
const text = code === null ? t("terminal.exited.closed") : t("terminal.exited.code", { code });
return `\r\n\x1b[2m${text}\x1b[0m\r\n`;
}
/** The terminal store. */
export const useTerminalStore = defineStore("terminal", () => {
const notifications = useNotificationsStore();
/** Whether the Terminal tab is in the bottom panel. */
const visible = ref(false);
/** Whether the panel is expanded while the Terminal tab is active. */
const expanded = ref(true);
/** Open terminals in tab order. */
const tabs = ref<TerminalTab[]>([]);
/** The shown terminal, or null without tabs. */
const activeId = ref<number | null>(null);
/** Counts up whenever the active view should take the focus. */
const focusRequest = ref(0);
/** The last failed `terminal.create`, shown in the window. */
const error = ref<string | null>(null);
/** Number of terminals created, for the tab labels. */
let created = 0;
/** Output per terminal id; not reactive, views read it on mount. */
const history = new Map<number, History>();
/** Views listening for output, per terminal id. */
const writers = new Map<number, Set<TerminalWriter>>();
/** Pending input per terminal id. */
const outboxes = new Map<number, Outbox>();
/** Last size sent per terminal id. */
const sizes = new Map<number, string>();
/** Terminals that ended before their tab existed, with their exit code. */
const early = new Map<number, number | null>();
/** Ends the event subscription; null while stopped. */
let unsubscribe: (() => void) | null = null;
/** The active tab, if any. */
const active = computed(() => tabs.value.find((tab) => tab.id === activeId.value) ?? null);
/**
* Adds output to a terminal's history and hands it to its views.
*
* @param id - the terminal.
* @param data - the text.
*/
function append(id: number, data: string): void {
let kept = history.get(id);
if (!kept) {
kept = { chunks: [], length: 0 };
history.set(id, kept);
}
kept.chunks.push(data);
kept.length += data.length;
while (kept.length > HISTORY_CAP && kept.chunks.length > 1) {
kept.length -= kept.chunks.shift()?.length ?? 0;
}
for (const writer of writers.get(id) ?? []) {
writer(data);
}
}
/**
* Marks a terminal as ended and writes the exit line.
*
* @param id - the terminal.
* @param code - its exit code, or null.
*/
function ended(id: number, code: number | null): void {
const tab = tabs.value.find((candidate) => candidate.id === id);
if (!tab) {
early.set(id, code);
return;
}
if (tab.exited) {
return;
}
tab.exited = true;
outboxes.delete(id);
append(id, exitLine(code));
}
/**
* Handles engine events: terminal output and exits, and the project
* closing.
*
* @param event - the event; its fields are untrusted.
*/
function onEvent(event: EngineEventPayload): void {
if (event.kind === "terminalOutput") {
if (typeof event.terminalId === "number" && typeof event.data === "string" && event.data !== "") {
append(event.terminalId, event.data);
}
} else if (event.kind === "terminalExited") {
if (typeof event.terminalId === "number") {
ended(event.terminalId, typeof event.code === "number" ? event.code : null);
}
} else if (event.kind === "projectClosed") {
reset();
}
}
/** Drops every tab and its output; the engine closed the terminals. */
function reset(): void {
tabs.value = [];
activeId.value = null;
visible.value = false;
error.value = null;
history.clear();
outboxes.clear();
sizes.clear();
early.clear();
}
/**
* Starts a terminal and shows its tab.
*
* @param size - the size to start with.
* @returns the new terminal's id, or null if the engine refused.
*/
async function create(size: { cols: number; rows: number } = DEFAULT_SIZE): Promise<number | null> {
const result = await run<{ terminalId?: unknown }>("terminal.create", { cols: size.cols, rows: size.rows });
if (!result.ok) {
error.value = result.error.message;
return null;
}
const id = result.value.terminalId;
if (typeof id !== "number") {
error.value = t("terminal.error.badAnswer");
return null;
}
error.value = null;
created += 1;
const title = created === 1 ? t("terminal.tab.first") : t("terminal.tab.numbered", { n: created });
tabs.value.push({ id, title, exited: false });
activeId.value = id;
sizes.set(id, `${String(size.cols)}x${String(size.rows)}`);
if (early.has(id)) {
const code = early.get(id) ?? null;
early.delete(id);
ended(id, code);
}
focusRequest.value += 1;
return id;
}
/**
* Shows the Terminal tab: the UI command `terminal.open`. Creates a
* terminal when none is running, or always with `{new: true}`.
*
* @param params - the command params; untrusted.
*/
async function open(params: unknown = {}): Promise<void> {
const p = typeof params === "object" && params !== null && !Array.isArray(params) ? (params as Record<string, unknown>) : {};
visible.value = true;
expanded.value = true;
focusRequest.value += 1;
const running = tabs.value.filter((tab) => !tab.exited);
if (p.new === true || running.length === 0) {
await create();
} else if (active.value?.exited !== false) {
activeId.value = running[running.length - 1]?.id ?? null;
}
}
/**
* Shows a terminal's tab.
*
* @param id - the terminal.
*/
function activate(id: number): void {
if (tabs.value.some((tab) => tab.id === id)) {
activeId.value = id;
focusRequest.value += 1;
}
}
/**
* Closes a tab, killing its shell if it still runs. Closing the last tab
* hides the Terminal tab.
*
* @param id - the terminal.
*/
async function close(id: number): Promise<void> {
const index = tabs.value.findIndex((tab) => tab.id === id);
const tab = tabs.value[index];
if (!tab) {
return;
}
tabs.value.splice(index, 1);
history.delete(id);
outboxes.delete(id);
sizes.delete(id);
if (activeId.value === id) {
activeId.value = (tabs.value[index] ?? tabs.value[index - 1])?.id ?? null;
}
if (tabs.value.length === 0) {
visible.value = false;
}
if (!tab.exited) {
const result = await run("terminal.close", { terminalId: id });
if (!result.ok) {
notifications.notifyError("terminal.close", result.error);
}
}
}
/**
* Sends keys or pasted text to a terminal, in order.
*
* @param id - the terminal.
* @param data - the text from xterm.js.
*/
function input(id: number, data: string): void {
const tab = tabs.value.find((candidate) => candidate.id === id);
if (!tab || tab.exited || data === "") {
return;
}
let box = outboxes.get(id);
if (!box) {
box = { pending: "", busy: false };
outboxes.set(id, box);
}
box.pending += data;
void flush(id, box);
}
/**
* Sends a terminal's pending input unless a send is in flight, and keeps
* sending until nothing is pending. A refused input raises an error toast
* unless the terminal ended meanwhile.
*
* @param id - the terminal.
* @param box - its outbox.
*/
async function flush(id: number, box: Outbox): Promise<void> {
if (box.busy) {
return;
}
box.busy = true;
while (box.pending !== "" && outboxes.get(id) === box) {
const data = box.pending;
box.pending = "";
const result = await run("terminal.input", { terminalId: id, data });
if (!result.ok && outboxes.get(id) === box) {
notifications.notifyError("terminal.input", result.error);
}
}
box.busy = false;
}
/**
* Tells the engine a terminal's new size; repeated sizes are skipped.
*
* @param id - the terminal.
* @param cols - columns, at least 1.
* @param rows - rows, at least 1.
*/
async function resize(id: number, cols: number, rows: number): Promise<void> {
const tab = tabs.value.find((candidate) => candidate.id === id);
const c = Math.max(1, Math.min(1000, Math.floor(cols)));
const r = Math.max(1, Math.min(1000, Math.floor(rows)));
const key = `${String(c)}x${String(r)}`;
if (!tab || tab.exited || sizes.get(id) === key || !Number.isFinite(cols) || !Number.isFinite(rows)) {
return;
}
sizes.set(id, key);
const result = await run("terminal.resize", { terminalId: id, cols: c, rows: r });
if (!result.ok) {
sizes.delete(id);
}
}
/**
* Connects a view to a terminal's output.
*
* @param id - the terminal.
* @param writer - receives new output.
* @returns the output so far, for the view to replay, and a function
* that disconnects the view.
*/
function attach(id: number, writer: TerminalWriter): { replay: string; detach: () => void } {
let set = writers.get(id);
if (!set) {
set = new Set();
writers.set(id, set);
}
set.add(writer);
const replay = (history.get(id)?.chunks ?? []).join("");
return {
replay,
detach: () => {
set.delete(writer);
if (set.size === 0) {
writers.delete(id);
}
},
};
}
/** Hides the Terminal tab; terminals keep running. */
function hide(): void {
visible.value = false;
}
/** Starts listening to terminal events. Starting twice is a no-op. */
function start(): void {
unsubscribe ??= onEngineEvent(onEvent);
}
/** Stops listening. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
}
return {
visible,
expanded,
tabs,
activeId,
active,
focusRequest,
error,
create,
open,
activate,
close,
input,
resize,
attach,
hide,
start,
stop,
};
});

View file

@ -140,7 +140,7 @@ describe("en.json", () => {
it("uses flat dotted keys of known areas with string values", () => { it("uses flat dotted keys of known areas with string values", () => {
for (const [key, value] of Object.entries(en)) { for (const [key, value] of Object.entries(en)) {
expect(key).toMatch( expect(key).toMatch(
/^(app|command|project|editor|common|palette|theme|recovery|notification|settings|find|goto|structure|menu)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/, /^(app|command|project|editor|common|palette|theme|recovery|notification|settings|find|goto|structure|menu|terminal)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
); );
expect(typeof value).toBe("string"); expect(typeof value).toBe("string");
expect(value.trim()).not.toBe(""); expect(value.trim()).not.toBe("");

View file

@ -243,6 +243,7 @@ describe("AppMenu", () => {
expect(spec?.defaultShortcut).toBe("Alt+M"); expect(spec?.defaultShortcut).toBe("Alt+M");
expect(UI_COMMANDS.find((c) => c.id === "settings.open")?.menuPath).toBe("View/Settings…"); expect(UI_COMMANDS.find((c) => c.id === "settings.open")?.menuPath).toBe("View/Settings…");
expect(UI_COMMANDS.find((c) => c.id === "goto.fileOpen")?.menuPath).toBe("Go/File…"); expect(UI_COMMANDS.find((c) => c.id === "goto.fileOpen")?.menuPath).toBe("Go/File…");
expect(UI_COMMANDS.find((c) => c.id === "terminal.open")?.menuPath).toBe("View/Terminal");
}); });
it("opens from the button with groups, shortcuts and dimmed disabled items", async () => { it("opens from the button with groups, shortcuts and dimmed disabled items", async () => {
@ -265,6 +266,7 @@ describe("AppMenu", () => {
"view.toggleProjectTree", "view.toggleProjectTree",
"view.toggleStructure", "view.toggleStructure",
"find.open", "find.open",
"terminal.open",
"settings.open", "settings.open",
"goto.fileOpen", "goto.fileOpen",
"goto.classOpen", "goto.classOpen",

View file

@ -271,6 +271,7 @@ describe("CommandPalette", () => {
"settings.open", "settings.open",
"view.toggleProjectTree", "view.toggleProjectTree",
"view.toggleStructure", "view.toggleStructure",
"terminal.open",
]); ]);
const quit = wrapper.find("[data-command='app.quit']"); const quit = wrapper.find("[data-command='app.quit']");
expect(quit.find("[data-test=palette-shortcut]").text()).toBe("Ctrl+Q"); expect(quit.find("[data-test=palette-shortcut]").text()).toBe("Ctrl+Q");
@ -302,7 +303,7 @@ describe("CommandPalette", () => {
const wrapper = await mountPalette(); const wrapper = await mountPalette();
await press(PALETTE_KEY); await press(PALETTE_KEY);
await press({ key: "ArrowUp" }); await press({ key: "ArrowUp" });
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("view.toggleStructure"); expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("terminal.open");
await press({ key: "ArrowDown" }); await press({ key: "ArrowDown" });
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("project.close"); expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("project.close");
}); });

View file

@ -0,0 +1,547 @@
/**
* Tests of the integrated terminal (M3.6): the Terminal store (create,
* output before the answer, history cap and replay, ordered input,
* resize, exit, close, project close, untrusted events), the key rules
* (which shortcuts reach Lutra from a terminal, copy and paste), the theme
* mapping, the tool window with its sub-tabs over a mocked xterm, the
* bottom panel's tabs and `terminal.open` through the main layout next to
* Find. The engine is a fake behind the mocked Tauri `invoke` and `listen`.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { createPinia, setActivePinia, type Pinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const invoke = vi.hoisted(() => vi.fn());
const listen = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
vi.mock("@tauri-apps/api/event", () => ({ listen }));
/** A fake xterm: records writes, theme and focus; tests type through `type`. */
interface FakeTerm {
writes: string[];
focused: number;
disposed: boolean;
theme: unknown;
selection: string;
type: (data: string) => void;
key: (event: KeyboardEvent) => boolean;
}
const terms = vi.hoisted(() => [] as FakeTerm[]);
vi.mock("../../src/components/terminal/xterm", async (importOriginal) => {
const real = await importOriginal<typeof import("../../src/components/terminal/xterm")>();
return {
...real,
createXterm: () => {
let onData: (data: string) => void = () => undefined;
let onKey: (event: KeyboardEvent) => boolean = () => true;
const fake: FakeTerm = {
writes: [],
focused: 0,
disposed: false,
theme: null,
selection: "",
type: (data) => {
onData(data);
},
key: (event) => onKey(event),
};
terms.push(fake);
const term = {
open: () => undefined,
write: (data: string) => void fake.writes.push(data),
focus: () => void (fake.focused += 1),
dispose: () => void (fake.disposed = true),
onData: (cb: (data: string) => void) => {
onData = cb;
return { dispose: () => undefined };
},
hasSelection: () => fake.selection !== "",
getSelection: () => fake.selection,
attachCustomKeyEventHandler: (cb: (event: KeyboardEvent) => boolean) => {
onKey = cb;
},
options: {
set theme(value: unknown) {
fake.theme = value;
},
},
cols: 80,
rows: 24,
};
return { term, fit: () => ({ cols: 120, rows: 30 }) };
},
};
});
import { useCommandsStore } from "../../src/commands/store";
import BottomPanel from "../../src/components/layout/BottomPanel.vue";
import MainLayout from "../../src/components/layout/MainLayout.vue";
import { clipboardAction, shortcutReachesLutra, TERMINAL_ATTRIBUTE } from "../../src/components/terminal/keys";
import TerminalToolWindow from "../../src/components/terminal/TerminalToolWindow.vue";
import { terminalTheme } from "../../src/components/terminal/xterm";
import { HISTORY_CAP, useTerminalStore } from "../../src/stores/terminal";
import { useNotificationsStore } from "../../src/stores/notifications";
import themes from "../theme/themes.json";
/** Every `engine_execute` call, in order. */
let calls: { command: string; params: Record<string, unknown> }[];
/** Engine event callbacks of every subscription. */
let listeners: ((event: { payload: unknown }) => void)[];
/** Next terminal id the fake returns. */
let nextId: number;
/** Events the fake emits before `terminal.create` answers. */
let beforeAnswer: unknown[];
/** Resolvers of `terminal.input` calls held back by a test. */
let heldInputs: (() => void)[];
/** Whether `terminal.input` calls are held back. */
let holdInput: boolean;
/** Error the next `terminal.create` fails with, if any. */
let createError: { code: string; message: string } | null;
let pinia: Pinia;
let mounted: VueWrapper[];
/**
* Sends an engine event to every subscription.
*
* @param payload - the event.
*/
async function emit(payload: unknown): Promise<void> {
for (const listener of [...listeners]) {
listener({ payload });
}
await flushPromises();
}
/** The params of every call of a command. */
function paramsOf(command: string): Record<string, unknown>[] {
return calls.filter((c) => c.command === command).map((c) => c.params);
}
/**
* A key event whose target is `target`.
*
* @param init - the key fields.
* @param target - the element it is dispatched on.
*/
function keyOn(init: KeyboardEventInit, target: Element): KeyboardEvent {
const event = new KeyboardEvent("keydown", { bubbles: true, ...init });
Object.defineProperty(event, "target", { value: target });
return event;
}
beforeEach(() => {
pinia = createPinia();
setActivePinia(pinia);
calls = [];
listeners = [];
nextId = 1;
beforeAnswer = [];
heldInputs = [];
holdInput = false;
createError = null;
mounted = [];
terms.length = 0;
vi.stubGlobal("requestAnimationFrame", (cb: () => void) => {
cb();
return 0;
});
invoke.mockReset();
listen.mockReset();
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
listeners.push(callback);
return Promise.resolve(() => {
listeners = listeners.filter((l) => l !== callback);
});
});
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve([
{ id: "terminal.create", label: "New Terminal", params: "", enabled: true, ui: false },
]);
}
if (cmd !== "engine_execute" || !args) {
return Promise.resolve(null);
}
calls.push({ command: args.command, params: args.params });
if (args.command === "terminal.create") {
if (createError) {
return Promise.reject(Object.assign(new Error(createError.code), createError));
}
const terminalId = nextId;
nextId += 1;
for (const event of beforeAnswer) {
for (const listener of [...listeners]) {
listener({ payload: event });
}
}
return Promise.resolve({ terminalId });
}
if (args.command === "terminal.input" && holdInput) {
return new Promise((resolve) => {
heldInputs.push(() => {
resolve(null);
});
});
}
if (args.command === "terminal.close") {
return Promise.resolve({ closed: true });
}
return Promise.resolve(null);
});
});
afterEach(() => {
for (const wrapper of mounted) {
wrapper.unmount();
}
useTerminalStore(pinia).stop();
useCommandsStore(pinia).stop();
vi.unstubAllGlobals();
});
describe("terminal store", () => {
it("creates a terminal and keeps output that arrives before the answer", async () => {
const store = useTerminalStore(pinia);
store.start();
await flushPromises();
beforeAnswer = [{ kind: "terminalOutput", terminalId: 1, data: "PS> " }];
const id = await store.create({ cols: 100, rows: 30 });
expect(id).toBe(1);
expect(paramsOf("terminal.create")).toEqual([{ cols: 100, rows: 30 }]);
expect(store.tabs).toEqual([{ id: 1, title: "Local", exited: false }]);
beforeAnswer = [];
await store.create();
expect(store.tabs.map((t) => t.title)).toEqual(["Local", "Local (2)"]);
expect(store.activeId).toBe(2);
const written: string[] = [];
const { replay } = store.attach(1, (data) => written.push(data));
expect(replay).toBe("PS> ");
await emit({ kind: "terminalOutput", terminalId: 1, data: "ls\r\n" });
await emit({ kind: "terminalOutput", terminalId: 2, data: "other" });
expect(written).toEqual(["ls\r\n"]);
});
it("caps the history from the front and ignores malformed events", async () => {
const store = useTerminalStore(pinia);
store.start();
await flushPromises();
await store.create();
const chunk = "x".repeat(HISTORY_CAP / 4);
for (let i = 0; i < 6; i += 1) {
await emit({ kind: "terminalOutput", terminalId: 1, data: `${String(i)}${chunk}` });
}
await emit({ kind: "terminalOutput", terminalId: "1", data: "bad" });
await emit({ kind: "terminalOutput", terminalId: 1, data: 7 });
await emit({ kind: "terminalExited", terminalId: null, code: 0 });
const { replay } = store.attach(1, () => undefined);
expect(replay.length).toBeLessThanOrEqual(HISTORY_CAP);
expect(replay.startsWith("3")).toBe(true);
expect(replay).not.toContain("bad");
expect(store.tabs[0]?.exited).toBe(false);
});
it("sends input in order, one call at a time", async () => {
const store = useTerminalStore(pinia);
await store.create();
holdInput = true;
store.input(1, "a");
store.input(1, "b");
store.input(1, "c");
await flushPromises();
expect(paramsOf("terminal.input")).toEqual([{ terminalId: 1, data: "a" }]);
heldInputs.shift()?.();
await flushPromises();
expect(paramsOf("terminal.input")).toEqual([
{ terminalId: 1, data: "a" },
{ terminalId: 1, data: "bc" },
]);
heldInputs.shift()?.();
await flushPromises();
store.input(99, "x");
expect(paramsOf("terminal.input")).toHaveLength(2);
});
it("skips repeated sizes and clamps them", async () => {
const store = useTerminalStore(pinia);
await store.create({ cols: 80, rows: 24 });
await store.resize(1, 80, 24);
await store.resize(1, 120.7, 30);
await store.resize(1, 120, 30);
await store.resize(1, 5000, 0);
expect(paramsOf("terminal.resize")).toEqual([
{ terminalId: 1, cols: 120, rows: 30 },
{ terminalId: 1, cols: 1000, rows: 1 },
]);
});
it("marks an ended terminal, then closes tabs and hides with the last one", async () => {
const store = useTerminalStore(pinia);
store.start();
await flushPromises();
await store.open();
await store.create();
expect(store.visible).toBe(true);
await emit({ kind: "terminalExited", terminalId: 1, code: 3 });
expect(store.tabs[0]?.exited).toBe(true);
expect(store.attach(1, () => undefined).replay).toContain("Process exited with code 3");
store.input(1, "x");
await store.close(1);
expect(paramsOf("terminal.close")).toEqual([]);
expect(store.activeId).toBe(2);
await store.close(2);
expect(paramsOf("terminal.close")).toEqual([{ terminalId: 2 }]);
expect(store.visible).toBe(false);
expect(paramsOf("terminal.input")).toEqual([]);
});
it("opens one terminal, reuses it, and makes another with new", async () => {
const store = useTerminalStore(pinia);
await store.open();
await store.open();
expect(store.tabs).toHaveLength(1);
await store.open({ new: true });
expect(store.tabs).toHaveLength(2);
store.activate(1);
expect(store.activeId).toBe(1);
});
it("shows a refused create in place and drops everything on project close", async () => {
const store = useTerminalStore(pinia);
store.start();
await flushPromises();
createError = { code: "failed", message: "no shell" };
await store.open();
expect(store.error).toBe("no shell");
createError = null;
await store.open();
expect(store.error).toBeNull();
await emit({ kind: "projectClosed" });
expect(store.tabs).toEqual([]);
expect(store.visible).toBe(false);
});
it("raises a toast when input is refused", async () => {
const store = useTerminalStore(pinia);
await store.create();
invoke.mockImplementationOnce(() => Promise.reject(Object.assign(new Error("failed"), { code: "failed", message: "not reading" })));
store.input(1, "x");
await flushPromises();
expect(useNotificationsStore(pinia).toasts.map((t) => t.level)).toEqual(["error"]);
});
});
describe("terminal keys", () => {
const inside = document.createElement("div");
inside.setAttribute(TERMINAL_ATTRIBUTE, "");
const textarea = document.createElement("textarea");
inside.appendChild(textarea);
const outside = document.createElement("textarea");
it("lets the shell have plain Ctrl shortcuts while a terminal has the focus", () => {
expect(shortcutReachesLutra(keyOn({ code: "KeyP", ctrlKey: true }, textarea), false)).toBe(false);
expect(shortcutReachesLutra(keyOn({ code: "KeyW", ctrlKey: true }, textarea), false)).toBe(false);
expect(shortcutReachesLutra(keyOn({ code: "KeyP", ctrlKey: true, shiftKey: true }, textarea), false)).toBe(true);
expect(shortcutReachesLutra(keyOn({ code: "KeyF", ctrlKey: true, altKey: true }, textarea), false)).toBe(true);
expect(shortcutReachesLutra(keyOn({ code: "KeyP", ctrlKey: true }, outside), false)).toBe(true);
expect(shortcutReachesLutra(keyOn({ code: "KeyP", metaKey: true }, textarea), true)).toBe(true);
expect(shortcutReachesLutra(keyOn({ code: "KeyR", ctrlKey: true }, textarea), true)).toBe(false);
});
it("copies and pastes with Lutra's keys", () => {
const key = (init: KeyboardEventInit): KeyboardEvent => new KeyboardEvent("keydown", init);
expect(clipboardAction(key({ code: "KeyC", ctrlKey: true }), false, false)).toBeNull();
expect(clipboardAction(key({ code: "KeyC", ctrlKey: true }), true, false)).toBe("copy");
expect(clipboardAction(key({ code: "KeyC", ctrlKey: true, shiftKey: true }), false, false)).toBe("copy");
expect(clipboardAction(key({ code: "KeyV", ctrlKey: true }), false, false)).toBe("paste");
expect(clipboardAction(key({ code: "KeyV", metaKey: true }), false, true)).toBe("paste");
expect(clipboardAction(key({ code: "KeyC", metaKey: true }), false, true)).toBe("copy");
expect(clipboardAction(key({ code: "KeyC", ctrlKey: true }), true, true)).toBeNull();
expect(clipboardAction(new KeyboardEvent("keyup", { code: "KeyV", ctrlKey: true }), false, false)).toBeNull();
});
it("maps every terminal token of both themes onto xterm's theme", () => {
for (const theme of themes) {
const tokens: Record<string, string> = theme.tokens;
const mapped = terminalTheme((name) => tokens[name] ?? "") as Record<string, unknown>;
expect(mapped.background).toBe(tokens["--lt-terminal-bg"]);
expect(mapped.brightMagenta).toBe(tokens["--lt-terminal-ansi-bright-magenta"]);
expect(Object.values(mapped).every((v) => typeof v === "string" && v.startsWith("#"))).toBe(true);
expect(Object.keys(mapped)).toHaveLength(21);
}
expect(terminalTheme(() => "").background).toBeUndefined();
});
});
describe("terminal tool window", () => {
/** Mounts the window with a started store. */
async function mountWindow(): Promise<VueWrapper> {
const store = useTerminalStore(pinia);
store.start();
const wrapper = mount(TerminalToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(wrapper);
await flushPromises();
return wrapper;
}
it("shows sub-tabs, replays output, types, resizes and closes", async () => {
const store = useTerminalStore(pinia);
const wrapper = await mountWindow();
beforeAnswer = [{ kind: "terminalOutput", terminalId: 1, data: "hello " }];
await store.open();
await flushPromises();
expect(terms).toHaveLength(1);
expect(terms[0]?.writes).toEqual(["hello "]);
expect(terms[0]?.focused).toBeGreaterThan(0);
expect(paramsOf("terminal.resize")).toEqual([{ terminalId: 1, cols: 120, rows: 30 }]);
await emit({ kind: "terminalOutput", terminalId: 1, data: "world" });
expect(terms[0]?.writes).toEqual(["hello ", "world"]);
terms[0]?.type("dir\r");
await flushPromises();
expect(paramsOf("terminal.input")).toEqual([{ terminalId: 1, data: "dir\r" }]);
expect(wrapper.find(`[${TERMINAL_ATTRIBUTE}]`).exists()).toBe(true);
await wrapper.get("[data-test=terminal-new]").trigger("click");
await flushPromises();
const tabs = wrapper.findAll("[data-test=terminal-tab]");
expect(tabs.map((t) => t.text())).toEqual(["Local", "Local (2)"]);
expect(tabs[1]?.attributes("aria-selected")).toBe("true");
await tabs[1]?.trigger("keydown", { key: "ArrowLeft" });
expect(store.activeId).toBe(1);
expect(terms).toHaveLength(2);
await emit({ kind: "terminalExited", terminalId: 2, code: 0 });
expect(wrapper.findAll("[data-test=terminal-tab]")[1]?.text()).toBe("Local (2) (ended)");
await wrapper.findAll("[data-test=terminal-tab-close]")[0]?.trigger("click");
await flushPromises();
expect(paramsOf("terminal.close")).toEqual([{ terminalId: 1 }]);
expect(terms[0]?.disposed).toBe(true);
expect(store.activeId).toBe(2);
});
it("copies the selection and leaves paste to the browser", async () => {
const writeText = vi.fn(() => Promise.resolve());
vi.stubGlobal("navigator", { userAgent: "Windows", platform: "Win32", clipboard: { writeText } });
await mountWindow();
await useTerminalStore(pinia).open();
await flushPromises();
const term = terms[0];
if (!term) throw new Error("no terminal");
term.selection = "copied";
expect(term.key(new KeyboardEvent("keydown", { code: "KeyC", ctrlKey: true }))).toBe(false);
expect(writeText).toHaveBeenCalledWith("copied");
expect(term.key(new KeyboardEvent("keydown", { code: "KeyV", ctrlKey: true }))).toBe(false);
term.selection = "";
expect(term.key(new KeyboardEvent("keydown", { code: "KeyC", ctrlKey: true }))).toBe(true);
});
it("follows theme changes", async () => {
await mountWindow();
await useTerminalStore(pinia).open();
await flushPromises();
const light = themes.find((t) => t.id === "lutra-light");
await emit({ kind: "themeChanged", id: "lutra-light", dark: false, tokens: light?.tokens });
expect((terms[0]?.theme as { background?: string }).background).toBe(light?.tokens["--lt-terminal-bg"]);
});
it("shows a refused terminal as an alert", async () => {
const wrapper = await mountWindow();
createError = { code: "failed", message: "no shell" };
await useTerminalStore(pinia).open();
await flushPromises();
expect(wrapper.get("[data-test=terminal-error]").text()).toContain("no shell");
});
});
describe("bottom panel tabs", () => {
it("shows tabs instead of the title and switches with clicks and arrows", async () => {
const chosen: string[] = [];
const wrapper = mount(BottomPanel, {
attachTo: document.body,
props: {
title: "Find",
tabs: [
{ id: "find", title: "Find" },
{ id: "terminal", title: "Terminal" },
],
active: "find",
"onUpdate:active": (id: string) => {
chosen.push(id);
void wrapper.setProps({ active: id });
},
},
});
mounted.push(wrapper);
expect(wrapper.find(".bottom-panel__title").exists()).toBe(false);
expect(wrapper.get("[data-test=bottom-tab-find]").attributes("aria-selected")).toBe("true");
await wrapper.get("[data-test=bottom-tab-terminal]").trigger("click");
await wrapper.get("[data-test=bottom-tab-terminal]").trigger("keydown", { key: "ArrowRight" });
await flushPromises();
expect(chosen).toEqual(["terminal", "find"]);
expect(document.activeElement).toBe(wrapper.get("[data-test=bottom-tab-find]").element);
});
});
describe("terminal.open", () => {
/** Mounts the main layout with the commands store started. */
async function mountLayout(): Promise<VueWrapper> {
const wrapper = mount(MainLayout, {
attachTo: document.body,
global: { plugins: [pinia], stubs: { ProjectToolWindow: true, StatusBar: true, StructureToolWindow: true } },
});
mounted.push(wrapper);
await useCommandsStore(pinia).start();
await flushPromises();
return wrapper;
}
it("is registered with its own shortcut", async () => {
await mountLayout();
const registered = paramsOf("ui.registerCommands")[0]?.commands as { id: string; defaultShortcut?: string }[];
expect(registered.find((c) => c.id === "terminal.open")?.defaultShortcut).toBe("Mod+Shift+T");
});
it("opens the Terminal tab next to Find, switches and closes tool windows one by one", async () => {
const wrapper = await mountLayout();
window.dispatchEvent(new KeyboardEvent("keydown", { key: "T", code: "KeyT", ctrlKey: true, shiftKey: true, bubbles: true }));
await flushPromises();
expect(wrapper.find("[data-test=terminal-window]").isVisible()).toBe(true);
expect(wrapper.find(".bottom-panel__title").text()).toBe("Terminal");
expect(paramsOf("terminal.create")).toHaveLength(1);
window.dispatchEvent(new KeyboardEvent("keydown", { key: "f", code: "KeyF", ctrlKey: true, altKey: true, bubbles: true }));
await flushPromises();
expect(wrapper.get("[data-test=bottom-tab-find]").attributes("aria-selected")).toBe("true");
expect(wrapper.find("[data-test=terminal-window]").isVisible()).toBe(false);
await wrapper.get("[data-test=bottom-tab-terminal]").trigger("click");
expect(wrapper.find("[data-test=terminal-window]").isVisible()).toBe(true);
await wrapper.get("[data-test=bottom-panel-close]").trigger("click");
expect(wrapper.find("[data-test=terminal-window]").exists()).toBe(false);
expect(wrapper.find(".bottom-panel__title").text()).toBe("Find");
await wrapper.get("[data-test=bottom-panel-close]").trigger("click");
expect(wrapper.find("[data-test=bottom-panel]").exists()).toBe(false);
expect(paramsOf("terminal.close")).toEqual([]);
});
it("leaves plain Ctrl shortcuts to the focused terminal", async () => {
const wrapper = await mountLayout();
await useCommandsStore(pinia).execute("terminal.open");
await flushPromises();
const view = wrapper.get(`[${TERMINAL_ATTRIBUTE}]`).element;
const event = new KeyboardEvent("keydown", { key: "1", code: "Digit1", ctrlKey: true, bubbles: true, cancelable: true });
view.dispatchEvent(event);
expect(event.defaultPrevented).toBe(false);
const palette = new KeyboardEvent("keydown", { key: "P", code: "KeyP", ctrlKey: true, shiftKey: true, bubbles: true, cancelable: true });
view.dispatchEvent(palette);
expect(palette.defaultPrevented).toBe(true);
});
it("opens from an agent's uiCommand", async () => {
const wrapper = await mountLayout();
await emit({ kind: "uiCommand", id: "terminal.open", params: { new: true } });
expect(wrapper.find("[data-test=terminal-window]").exists()).toBe(true);
expect(paramsOf("terminal.create")).toHaveLength(1);
});
});

View file

@ -4,7 +4,10 @@
* UI draws text with reaches AA: 4.5:1 for body text, 3:1 for non-text * UI draws text with reaches AA: 4.5:1 for body text, 3:1 for non-text
* marks (cursor, modified dot, settings switch knob; WCAG 1.4.11). Every * marks (cursor, modified dot, settings switch knob; WCAG 1.4.11). Every
* syntax colour (`--lt-syntax-*`) reaches 4.5:1 on the editor background * syntax colour (`--lt-syntax-*`) reaches 4.5:1 on the editor background
* and on the active line. The themes come from * and on the active line. The terminal's text, cursor and every ANSI colour
* that shows as text reach AA on the terminal background (M3.6); the colour
* meant to vanish into it is exempt per theme (`TERMINAL_EXEMPT`). The
* themes come from
* `themes.json`, a snapshot that the Rust test `ui_snapshot_is_current` * `themes.json`, a snapshot that the Rust test `ui_snapshot_is_current`
* keeps equal to `lutra_engine::theme`. * keeps equal to `lutra_engine::theme`.
*/ */
@ -65,6 +68,35 @@ const SYNTAX_PAIRS: [string, string, number][] = SYNTAX.flatMap((name): [string,
[`syntax-${name}`, "editor-active-line-bg", TEXT], [`syntax-${name}`, "editor-active-line-bg", TEXT],
]); ]);
/** ANSI colour names, as in `TERMINAL_TOKENS` in `theme.rs`. */
const ANSI = ["black", "red", "green", "yellow", "blue", "magenta", "cyan", "white"] as const;
/** ANSI tokens that may blend into the background, per theme id. */
const TERMINAL_EXEMPT: Record<string, readonly string[]> = {
"lutra-dark": ["terminal-ansi-black"],
"lutra-light": ["terminal-ansi-white", "terminal-ansi-bright-white"],
};
/**
* The terminal's pairs for one theme: text and selection, the cursor, and
* every ANSI colour (normal and bright) that is not exempt.
*
* @param id - the theme id.
* @returns foreground token, background token and minimum ratio.
*/
function terminalPairs(id: string): [string, string, number][] {
const exempt = TERMINAL_EXEMPT[id] ?? [];
const ansi = ANSI.flatMap((name) => [`terminal-ansi-${name}`, `terminal-ansi-bright-${name}`]).filter(
(name) => !exempt.includes(name),
);
return [
["terminal-fg", "terminal-bg", TEXT],
["terminal-fg", "terminal-selection-bg", TEXT],
["terminal-cursor", "terminal-bg", LARGE],
...ansi.map((name): [string, string, number] => [name, "terminal-bg", TEXT]),
];
}
/** /**
* Relative luminance of a `#rrggbb` colour (WCAG 2.1 definition). * Relative luminance of a `#rrggbb` colour (WCAG 2.1 definition).
* *
@ -121,7 +153,12 @@ describe.each(themes)("theme $id", (theme) => {
expect(defined).toEqual([...SYNTAX].sort()); expect(defined).toEqual([...SYNTAX].sort());
}); });
it.each([...PAIRS, ...SYNTAX_PAIRS])("%s on %s reaches %d:1", (fg, bg, min) => { it("checks every terminal ANSI token it defines", () => {
const defined = Object.keys(tokens).filter((name) => name.startsWith("--lt-terminal-ansi-"));
expect(defined).toHaveLength(ANSI.length * 2);
});
it.each([...PAIRS, ...SYNTAX_PAIRS, ...terminalPairs(theme.id)])("%s on %s reaches %d:1", (fg, bg, min) => {
expect(contrast(token(fg), token(bg))).toBeGreaterThanOrEqual(min); expect(contrast(token(fg), token(bg))).toBeGreaterThanOrEqual(min);
}); });
}); });

View file

@ -37,7 +37,27 @@
"--lt-syntax-type": "#7fbac6", "--lt-syntax-type": "#7fbac6",
"--lt-syntax-variable": "#d8bba6", "--lt-syntax-variable": "#d8bba6",
"--lt-tab-active-bg": "#191817", "--lt-tab-active-bg": "#191817",
"--lt-tab-modified": "#d39a5c" "--lt-tab-modified": "#d39a5c",
"--lt-terminal-ansi-black": "#2e2b28",
"--lt-terminal-ansi-blue": "#8fa8e0",
"--lt-terminal-ansi-bright-black": "#9a928a",
"--lt-terminal-ansi-bright-blue": "#aebff0",
"--lt-terminal-ansi-bright-cyan": "#a2d3dc",
"--lt-terminal-ansi-bright-green": "#c2d69a",
"--lt-terminal-ansi-bright-magenta": "#dbbde8",
"--lt-terminal-ansi-bright-red": "#f59a8d",
"--lt-terminal-ansi-bright-white": "#f5f1ec",
"--lt-terminal-ansi-bright-yellow": "#f2d88e",
"--lt-terminal-ansi-cyan": "#7fbac6",
"--lt-terminal-ansi-green": "#a9bd7e",
"--lt-terminal-ansi-magenta": "#c4a0d6",
"--lt-terminal-ansi-red": "#ef7b6c",
"--lt-terminal-ansi-white": "#d0c9c1",
"--lt-terminal-ansi-yellow": "#e6c46f",
"--lt-terminal-bg": "#191817",
"--lt-terminal-cursor": "#d39a5c",
"--lt-terminal-fg": "#e6e1da",
"--lt-terminal-selection-bg": "#513f2c"
} }
}, },
{ {
@ -78,7 +98,27 @@
"--lt-syntax-type": "#24697a", "--lt-syntax-type": "#24697a",
"--lt-syntax-variable": "#7f4a34", "--lt-syntax-variable": "#7f4a34",
"--lt-tab-active-bg": "#fbfaf8", "--lt-tab-active-bg": "#fbfaf8",
"--lt-tab-modified": "#965a22" "--lt-tab-modified": "#965a22",
"--lt-terminal-ansi-black": "#2a2622",
"--lt-terminal-ansi-blue": "#2f55a4",
"--lt-terminal-ansi-bright-black": "#6b625a",
"--lt-terminal-ansi-bright-blue": "#233f7f",
"--lt-terminal-ansi-bright-cyan": "#1a5260",
"--lt-terminal-ansi-bright-green": "#3b5418",
"--lt-terminal-ansi-bright-magenta": "#5a3480",
"--lt-terminal-ansi-bright-red": "#8f2a1c",
"--lt-terminal-ansi-bright-white": "#f4f1ec",
"--lt-terminal-ansi-bright-yellow": "#5f4404",
"--lt-terminal-ansi-cyan": "#24697a",
"--lt-terminal-ansi-green": "#4e6a24",
"--lt-terminal-ansi-magenta": "#73479a",
"--lt-terminal-ansi-red": "#b23a29",
"--lt-terminal-ansi-white": "#ddd6cd",
"--lt-terminal-ansi-yellow": "#7a5808",
"--lt-terminal-bg": "#fbfaf8",
"--lt-terminal-cursor": "#965a22",
"--lt-terminal-fg": "#2a2622",
"--lt-terminal-selection-bg": "#e5d7c9"
} }
} }
] ]