Lutra/ui/src/ipc.ts
danny 20d1d28c32 M3.5: pending outcomes for commands that wait for the language server
Step 1 of M3.5: the shared mechanism. M3.4 and M3.5 build on it.

- Engine: `Outcome.pending: Option<Pending>`. `Pending::new(rx, timeout,
  finish)`; `Pending::wait()` is called without the engine lock and
  returns at the answer, a dropped sender or the deadline (timeout + 1 s).
  `Engine::resolve(answered)` then runs `finish(state, reply)` inside the
  guard, under the lock. `run_waiting(lock, cmd, params, publish)` does
  all three steps for hosts.
- Hosts: `Host::run`, `testkit::EngineBackend` and the control test
  backend use `run_waiting`.
- New IPC `engine_execute_waiting` (`#[tauri::command(async)]`, off the
  main thread) with `runWaiting()` in `ui/src/ipc.ts`. Only `lsp.*`
  requests use it.

Ordering guarantee:
- `engine_execute` stays synchronous on the main thread, so ordinary
  commands (`buffer.edit`) still run in call order.
- The order towards the server is fixed under the engine lock:
  `buffer.edit` queues its didChange on the session's FIFO queue before
  it returns, and `lsp::submit` queues the request on the same queue.
  A request therefore sees every edit whose `buffer.edit` returned
  first, and the UI awaits the sync's `idle()` before sending one.

Failures:
- A stall is caught by the request timeout, with the deadline as
  backstop.
- On restart, close, quit or crash the request is dropped or resolved
  as stopped, so the waiter gets an error, never a hang.

Tests: `crates/engine/tests/pending.rs` (answer, lock free while
waiting, dropped sender, deadline, resolve, lsp.restart while a
request is pending) and Vitest for `runWaiting`. Gate: 13 steps,
321 s, Vitest 443 + 1 skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 06:36:20 +02:00

320 lines
10 KiB
TypeScript

/**
* Bridge from the frontend to the engine.
*
* Every user-visible action runs as an engine command through {@link run}.
* Calls never reject: failures come back as `{ ok: false, error }` so that
* every caller has to handle them. State changes arrive as engine events
* through {@link onEngineEvent}.
*/
import { invoke } from "@tauri-apps/api/core";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
/** Name of the Tauri event that carries engine events. */
export const ENGINE_EVENT = "engine://event";
/**
* An engine event as the desktop shell emits it: the engine's `Event`,
* tagged by `kind`. Paths are project-relative with `/`; the root is `""`.
*/
export type EngineEventPayload =
| { kind: "projectOpened"; root: string; name: string }
| { kind: "projectClosed" }
| { kind: "treeChanged"; dir: string }
| { kind: "bufferOpened"; id: number; path: string }
| { kind: "bufferFocused"; id: number }
| { kind: "bufferChanged"; id: number; version: number }
| { kind: "dirtyChanged"; id: number; dirty: boolean }
| { kind: "bufferClosed"; id: number }
| { kind: "fileChangedOnDisk"; path: string; id: number; removed: boolean }
| { kind: "watchFailed"; message: string }
| { kind: "themeChanged"; id: string; dark: boolean; tokens: Record<string, string> }
| {
kind: "settingsChanged";
/** Keys whose effective value changed; unchecked, it comes from the engine. */
keys: unknown;
}
| {
kind: "recoveryAvailable";
entries: { path: string; savedAt: number; diskChanged: boolean }[];
}
| {
kind: "notification";
/** Unique id (`n1`, `n2`…); unchecked, it comes from the engine. */
id: unknown;
/** `info`, `warning` or `error`; unchecked. */
level: unknown;
/** Catalog key of the text; unchecked. */
messageKey?: unknown;
/** English fallback text; unchecked. */
message?: unknown;
/** Placeholder values; unchecked. */
params?: unknown;
}
| {
kind: "uiCommand";
/** Id of the UI command to run; unchecked, it comes from the engine. */
id: unknown;
/** The params it was run with, as given; unchecked. */
params?: unknown;
}
| {
kind: "recoveryResolved";
/** Paths restored or discarded; unchecked, it comes from the engine. */
paths: unknown;
}
| {
kind: "searchResults";
/** The search, as `search.find` returned it; unchecked. */
searchId: unknown;
/** Project-relative path of the file; unchecked. */
path: unknown;
/** `[{line, column, length, preview, previewColumn}]`; unchecked. */
matches: unknown;
}
| {
kind: "searchDone";
/** The search; unchecked, it comes from the engine. */
searchId: unknown;
/** Files with reported matches; unchecked. */
files: unknown;
/** Matches reported; unchecked. */
matches: unknown;
/** Whether the match cap left matches out; unchecked. */
truncated: unknown;
/** Whether the search was cancelled; unchecked. */
cancelled: unknown;
/** Wall time in milliseconds; unchecked. */
elapsedMs: unknown;
}
| {
kind: "outlineChanged";
/** Buffer whose outline changed; unchecked, it comes from the engine. */
id: unknown;
}
| {
kind: "indexProgress";
/** Files indexed so far; unchecked, it comes from the engine. */
done: unknown;
/** Files found to index; unchecked. */
total: unknown;
}
| {
kind: "indexReady";
/** Files in the index; unchecked, it comes from the engine. */
files: unknown;
/** Symbols in the index; unchecked. */
symbols: unknown;
/** Build time in milliseconds; unchecked. */
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;
}
| {
kind: "lspStatus";
/** `starting`, `ready`, `restarting`, `failed` or `stopped`; unchecked. */
state: unknown;
/** Why it restarts or failed; unchecked. */
message?: unknown;
}
| {
kind: "diagnosticsChanged";
/** Project-relative path of the file; unchecked, it comes from the engine. */
path: unknown;
/** `[{range, severity, message, source?, code?}]`, empty when cleared; unchecked. */
items: unknown;
};
/** Callback receiving engine events. */
export type EngineEventHandler = (event: EngineEventPayload) => void;
/** Whether the shell was told that the frontend listens (`engine_ready`). */
let announced = false;
/** Subscriptions started but not yet registered with the shell. */
let pending = 0;
/** Subscriptions registered with the shell and not ended. */
let live = 0;
/**
* Tells the shell that the frontend listens, once, as soon as a
* subscription is live and no started one is still being registered.
* Subscriptions made while the page mounts all start in the same tick, so
* every one of them receives the replay. A failed announcement is retried
* by the next subscription.
*/
function announce(): void {
if (announced || pending > 0 || live === 0) {
return;
}
announced = true;
invoke("engine_ready").catch(() => {
announced = false;
});
}
/**
* Subscribes to engine events. Once the subscriptions started together are
* registered, the shell is told that the frontend listens, so it replays
* the current project state and the notifications the page may have missed
* while loading. Outside the Tauri shell (tests, a plain browser)
* subscribing fails quietly and no events arrive.
*
* @param handler - called for every event, in order of arrival.
* @returns a function that ends the subscription.
*/
export function onEngineEvent(handler: EngineEventHandler): () => void {
let unlisten: UnlistenFn | null = null;
let cancelled = false;
pending += 1;
listen<EngineEventPayload>(ENGINE_EVENT, (event) => {
handler(event.payload);
})
.then((fn) => {
pending -= 1;
if (cancelled) {
fn();
} else {
unlisten = fn;
live += 1;
}
announce();
})
.catch(() => {
pending -= 1;
announce();
});
return () => {
cancelled = true;
if (unlisten) {
unlisten();
unlisten = null;
live -= 1;
}
};
}
/** A JSON value as exchanged with the engine. */
export type JsonValue =
| null
| boolean
| number
| string
| JsonValue[]
| { [key: string]: JsonValue };
/** An error reported by the engine, with a stable machine-readable code. */
export interface EngineError {
/** Stable code such as `unknown_command`, `invalid_params` or `internal`. */
code: string;
/** Message for the user. */
message: string;
}
/** Outcome of an engine call. */
export type RunResult<T> = { ok: true; value: T } | { ok: false; error: EngineError };
/** Static description of a command, as listed by the engine. */
export interface CommandInfo {
/** Command id, e.g. `app.about`. */
id: string;
/** Label shown in menus and the command palette; for UI commands the catalog key. */
label: string;
/** Catalog key of the label; set for UI commands. */
labelKey?: string;
/** Menu path such as `Help/About Lutra`, or null if not in a menu. */
menuPath: string | null;
/** Default shortcut in Lutra notation (`Mod+Q`), or null. */
defaultShortcut: string | null;
/** Documentation of the params object. */
params: string;
/** Whether the command can run in the current state. */
enabled: boolean;
/** Whether the frontend registered the command (`ui.registerCommands`) and runs it. */
ui?: boolean;
}
/**
* Turns whatever a failed `invoke` rejected with into an {@link EngineError}.
*
* @param reason - the rejection value; the shell sends `{ code, message }`.
* @returns the engine error, or an `ipc` error for anything else (for example
* when the page runs outside the Tauri shell).
*/
export function toEngineError(reason: unknown): EngineError {
if (typeof reason === "object" && reason !== null && "code" in reason && "message" in reason) {
const { code, message } = reason;
if (typeof code === "string" && typeof message === "string") {
return { code, message };
}
}
const message = reason instanceof Error ? reason.message : String(reason);
return { code: "ipc", message };
}
/**
* Runs an engine command.
*
* @param commandId - the command id, e.g. `app.about`.
* @param params - the command's params object.
* @returns the command's result, or the error it failed with.
*/
export async function run<T = JsonValue>(
commandId: string,
params: JsonValue = {},
): Promise<RunResult<T>> {
try {
const value = await invoke<T>("engine_execute", { command: commandId, params });
return { ok: true, value };
} catch (reason: unknown) {
return { ok: false, error: toEngineError(reason) };
}
}
/**
* Runs an engine command that waits for the language server (`lsp.*`,
* M3.5) on a worker thread of the shell, so the window stays responsive
* while the server works. Unlike {@link run}, calls are not ordered with
* other commands: let edits reach the engine first (`BufferSync.idle`).
*
* @param commandId - the command id, e.g. `lsp.definition`.
* @param params - the command's params object.
* @returns the command's result, or the error it failed with.
*/
export async function runWaiting<T = JsonValue>(
commandId: string,
params: JsonValue = {},
): Promise<RunResult<T>> {
try {
const value = await invoke<T>("engine_execute_waiting", { command: commandId, params });
return { ok: true, value };
} catch (reason: unknown) {
return { ok: false, error: toEngineError(reason) };
}
}
/**
* Lists every command the engine knows, with its current enabled state.
*
* @returns the commands, or the error the call failed with.
*/
export async function listCommands(): Promise<RunResult<CommandInfo[]>> {
try {
const value = await invoke<CommandInfo[]>("engine_list_commands");
return { ok: true, value };
} catch (reason: unknown) {
return { ok: false, error: toEngineError(reason) };
}
}