Lutra/ui/src/ipc.ts
danny f67f6b9f7c M4.2: Changes tool window with staging and commit
A Changes tab in the bottom panel (ui/src/components/vcs/changes/): the
project's changed files from git.status in Staged, Changes and Untracked
groups, re-read on start, project open, gitChanged and vcs.refresh
(serialised). A checkbox per file and per group stages or unstages through
git.stage / git.unstage (a staged rename passes both paths); Space stages,
Enter or a double-click runs vcs.showDiff when provided, else opens the
file. A message box with Amend and Commit (also Mod+Enter) runs flushDirty()
first, cancels when a save fails, then git.commit and toasts the short hash.
All git calls go through runWaiting.

UI commands vcs.openChanges (Mod+Alt+G), vcs.commit (Mod+K, focuses the
message box) and vcs.refresh in a new Git menu group; gitChanged added to
EngineEventPayload. 19 Vitest tests; palette, menu and catalog tests follow
the new commands. Docs: architecture, gaps G8, Git parity row 4% (est.),
ui/tooling checklists, roadmap M4 row, ROADMAP depth ~5.4% and log, README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 17:17:39 +01:00

346 lines
11 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;
}
| {
kind: "gitChanged";
/** Whether a usable git was found; unchecked. */
available: unknown;
/** The repository summary of `git.status`, or null; unchecked. */
repo: unknown;
/** Always true: re-query `git.status`. */
filesChanged: 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) };
}
}
/**
* Shows the native file picker of the desktop shell (the "Browse…" button
* of a path setting).
*
* @param title - the picker's title, from the catalog.
* @returns the chosen file's absolute path, null when the user cancelled,
* or the error the call failed with (for example outside the shell).
*/
export async function pickFile(title: string): Promise<RunResult<string | null>> {
try {
const value = await invoke<string | null>("pick_file", { title });
return { ok: true, value: typeof value === "string" ? value : null };
} catch (reason: unknown) {
return { ok: false, error: toEngineError(reason) };
}
}