Lutra/ui/src/ipc.ts
danny e128400246 H3: Phpactor UX: fast tick while indexing, progress, messages, php -l
- Session tick: 1 ms while Phpactor reports work-done progress and in a
  session's first 120 s, otherwise 25 ms as before. Fast intervals use
  thread::sleep, because recv_timeout wakes at most ~64/s on Windows.
  First useful completion on 2,000 classes: 71.6 s -> 20.7-26.9 s.
- $/progress -> lspProgress {active, title?, message?, percentage?},
  progress in lsp.status, a status-bar item (LspProgressItem).
- window/showMessage -> notification.lsp.message (repeats within 30 s and
  the known Windows lint-provider complaint only logged); showMessage,
  logMessage and stderr in a 1,000-line log, new command lsp.log.
- Lutra's own php -l on Windows (lsp/php_lint.rs): on open and save, one
  worker thread, lutra_proc::spawn, stdin, 10 s timeout, output caps;
  merged into diagnosticsChanged with source "php -l".
- editor.completion.delayMs stays 0 (measured: 100 ms only delays the
  list; Phpactor marks every list incomplete).
- Fake server: scripted notifications after initialized.

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

348 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 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: "lspProgress";
/** Whether a work-done progress task runs; unchecked. */
active: unknown;
/** Its title; unchecked. */
title?: unknown;
/** Its latest message; unchecked. */
message?: unknown;
/** 0–100; unchecked. */
percentage?: 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) };
}
}
/**
* 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) };
}
}