Lutra/ui/src/components/editor/bufferSync.ts
danny 578160a2ba M3.5: go to definition, find references and rename through Phpactor
Engine (`cmd/lsp_nav.rs`, on the pending outcomes of 20d1d28):
- `lsp.definition` (F12) and `lsp.references` (Shift+F12, sorted, with
  line previews) return project-relative locations; locations outside
  the project, such as PHAR stubs and symlink escapes, are dropped.
- `lsp.prepareRename` uses the word at the cursor when the server has
  no prepareProvider.
- `lsp.rename` (F2) applies the workspace edit (`lsp_nav/edit.rs`):
  1. Check everything first: inside the project, ranges fit (UTF-16,
     CRLF), open buffers unchanged since the request, no file
     operations, no incomplete edit.
  2. Write closed files atomically through the VFS, restoring earlier
     writes when a later one fails.
  3. Change open buffers through `buffer.edit` (dirty, undoable).
  4. Send each written file to Phpactor as didOpen/didSave/didClose
     plus didChangeWatchedFiles; without this its index kept the old
     names. Then the summary notification `notification.lsp.renamed`.

UI (`components/editor/nav/`):
- Mod+click goes to the definition, with a pointer cursor while Mod is
  held.
- A location picker for several definitions (exclusive modal).
- A References tab in the bottom panel, grouped by file.
- An inline rename field with a use/file count (exclusive modal).
- `BufferSync.beginUndoableRemote` puts the engine's rename edit into
  the editor history as one undo step per buffer.
- Catalog strings and tokens only.

Fake LSP server: `--script FILE` with scripted capabilities and
answers (additive next to M3.4's arms).

Tests:
- `crates/engine/tests/lsp_nav.rs` (fake): definition; bad positions;
  references; prepareRename; a multi-file rename incl. a closed CRLF
  file; refusals for outside the project, a bad range, a stale buffer,
  bad names and no server.
- The ignored real-Phpactor test covers definition, references and a
  rename and back across 3 files.
- Vitest `ui/tests/nav/`.

Live (Phpactor 2026.06.25.0, Windows, port 7935, tick on):
- definition 93 ms cold / 7-18 ms warm
- references ~140 ms
- prepareRename ~11 ms
- rename 28-59 ms
- index follows written files in 140 ms
- Phpactor 57 MB working set, ~1.6% of a core while ticking idle

Gate: 13 steps, 197 s, Vitest 484 + 1 skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:50:15 +02:00

418 lines
13 KiB
TypeScript

/**
* Keeps one CodeMirror editor state in step with one engine buffer.
*
* The engine is the source of truth. Local changes are sent with
* `buffer.edit {id, baseVersion, edits}`, at most one call at a time; changes
* typed while a call is in flight are composed and sent together next. The
* invariant is: local document = unsent(inflight(confirmed)), where
* `confirmed` is the engine text at `version`.
*
* Resync: when the engine rejects an edit with `stale_version`, or reports a
* newer version than ours through `bufferChanged` (a reload from disk, an
* edit from the control channel), the sync fetches the text with
* `buffer.get`, computes the remote change against `confirmed`, rebases the
* unsent local changes over it and applies the remote change to the editor.
* No local keystroke is lost; the rebased changes are then sent against the
* new version. Idea from https://codemirror.net/examples/collab/.
*/
import {
Annotation,
ChangeSet,
EditorState,
Transaction,
type Extension,
type TransactionSpec,
} from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { t } from "../../i18n";
import { run, type EngineError, type RunResult } from "../../ipc";
import { diffDocs, EngineText, separatorOf, type EngineEdit } from "./engineText";
/** A buffer as `file.open` and `buffer.get` describe it. */
export interface BufferInfo {
/** Buffer id. */
id: number;
/** Project-relative path. */
path: string;
/** Full text as the engine holds it. */
text: string;
/** Current version. */
version: number;
/** Whether the buffer has unsaved changes. */
dirty: boolean;
/** Line ending the buffer saves with. */
lineEnding: string;
}
/** Result of `buffer.edit`. */
export interface EditResult {
/** Buffer id. */
id: number;
/** Version after the edit. */
version: number;
/** Whether the buffer is dirty now. */
dirty: boolean;
}
/** Params of `buffer.edit`. */
export interface EditParams {
/** Buffer id. */
id: number;
/** Version the edits refer to. */
baseVersion: number;
/** The edits, in engine UTF-16 offsets of the text at `baseVersion`. */
edits: EngineEdit[];
}
/** How the sync reaches the engine; replaced by a fake in tests. */
export interface SyncTransport {
/** Runs `buffer.edit`. */
edit(params: EditParams): Promise<RunResult<EditResult>>;
/** Runs `buffer.get`. */
get(id: number): Promise<RunResult<BufferInfo>>;
}
/** Transport through the engine IPC. */
export const engineTransport: SyncTransport = {
edit: (params) =>
run<EditResult>("buffer.edit", {
id: params.id,
baseVersion: params.baseVersion,
edits: params.edits.map((e) => ({ from: e.from, to: e.to, insert: e.insert })),
}),
get: (id) => run<BufferInfo>("buffer.get", { id }),
};
/** Marks transactions that carry engine changes, so they are not sent back. */
export const remoteChange = Annotation.define<boolean>();
/**
* Checks that a value looks like a {@link BufferInfo}.
*
* @param value - an untrusted command result.
*/
export function isBufferInfo(value: unknown): value is BufferInfo {
if (typeof value !== "object" || value === null) {
return false;
}
const v = value as Record<string, unknown>;
return (
typeof v.id === "number" &&
typeof v.path === "string" &&
typeof v.text === "string" &&
typeof v.version === "number" &&
typeof v.dirty === "boolean"
);
}
/** Synchronises one buffer; see the module documentation. */
export class BufferSync {
/** Engine buffer id. */
readonly id: number;
/** The local editor state, always current. */
private current: EditorState;
/** The view showing this buffer, null while another tab is active. */
private view: EditorView | null = null;
/** Engine text at {@link version}. */
private confirmed: EngineText;
/** Engine version of {@link confirmed}. */
private version: number;
/** Highest version the engine reported for this buffer. */
private latestKnown: number;
/** Changes sent and not yet answered, relative to {@link confirmed}. */
private inflight: ChangeSet | null = null;
/** Local changes not sent yet, relative to `inflight(confirmed)`. */
private unsent: ChangeSet | null = null;
/** Whether a `buffer.get` for a resync is running. */
private resyncing = false;
/** Line break used for inserted text. */
private separator: string;
/** Set once the buffer is closed; nothing is sent afterwards. */
private disposed = false;
/** Callbacks waiting for {@link idle}. */
private waiters: (() => void)[] = [];
/**
* Remote changes up to this engine version enter the undo history
* (a rename, M3.5); `Infinity` while the version is not known yet, null
* when off.
*/
private undoableUntil: number | null = null;
/** Engine transport. */
private readonly transport: SyncTransport;
/** Receives errors that are not handled by a resync. */
private readonly onError: (error: EngineError) => void;
/**
* @param info - the buffer as the engine described it.
* @param extensions - editor extensions for the state.
* @param transport - how to reach the engine.
* @param onError - receives failures (shown by the editor store).
*/
constructor(
info: BufferInfo,
extensions: Extension,
transport: SyncTransport = engineTransport,
onError: (error: EngineError) => void = () => undefined,
) {
this.id = info.id;
this.confirmed = EngineText.fromEngine(info.text);
this.version = info.version;
this.latestKnown = info.version;
this.separator = separatorOf(info.lineEnding);
this.transport = transport;
this.onError = onError;
this.current = EditorState.create({ doc: this.confirmed.doc, extensions });
}
/** The current local editor state. */
get state(): EditorState {
return this.current;
}
/** Engine version the local document is based on. */
get baseVersion(): number {
return this.version;
}
/** Whether local changes have not reached the engine yet. */
get pending(): boolean {
return this.inflight !== null || this.unsent !== null || this.resyncing;
}
/**
* Shows this buffer in a view: the view takes over the local state and
* receives remote changes from now on.
*
* @param view - the editor view.
*/
attach(view: EditorView): void {
this.view = view;
view.setState(this.current);
}
/** Stops updating the view (another tab became active). */
detach(): void {
this.view = null;
}
/** Stops syncing; the buffer was closed. */
dispose(): void {
this.disposed = true;
this.view = null;
this.inflight = null;
this.unsent = null;
this.settle();
}
/**
* Creates and applies a transaction on the local state, as typing would.
*
* @param spec - the transaction.
*/
dispatch(spec: TransactionSpec): void {
this.applyTransactions([this.current.update(spec)]);
}
/**
* Applies transactions created from the current state (by the view or by
* {@link dispatch}). Local document changes are queued for the engine.
*
* @param transactions - the transactions, in order.
*/
applyTransactions(transactions: readonly Transaction[]): void {
const last = transactions[transactions.length - 1];
if (!last) {
return;
}
this.current = last.state;
for (const tr of transactions) {
if (tr.docChanged && tr.annotation(remoteChange) !== true) {
this.unsent = this.unsent ? this.unsent.compose(tr.changes) : tr.changes;
}
}
this.view?.update([...transactions]);
this.flush();
}
/**
* Notes a version reported by the engine (`bufferChanged`). A version
* newer than the local base starts a resync once nothing is in flight.
*
* @param version - the reported version.
*/
notifyVersion(version: number): void {
this.latestKnown = Math.max(this.latestKnown, version);
if (this.latestKnown > this.version && this.inflight === null) {
this.resync();
}
}
/**
* Makes the engine's next changes to this buffer undoable in the editor
* (they enter the history instead of bypassing it), until
* {@link endUndoableRemote}. Called before a command that edits open
* buffers on the user's behalf, such as `lsp.rename`.
*/
beginUndoableRemote(): void {
this.undoableUntil = Number.POSITIVE_INFINITY;
}
/**
* Ends {@link beginUndoableRemote} once the engine version `version` has
* been taken over; null ends it now (the command did not touch this
* buffer or failed).
*
* @param version - the buffer's version after the command, or null.
*/
endUndoableRemote(version: number | null): void {
this.undoableUntil = version === null || this.version >= version ? null : version;
}
/** Resolves once every local change has reached the engine. */
idle(): Promise<void> {
if (!this.pending || this.disposed) {
return Promise.resolve();
}
return new Promise((resolve) => this.waiters.push(resolve));
}
/**
* Wakes {@link idle} callers when nothing is pending.
*
* @param force - wake them even with pending changes (the engine could not
* be reached, so waiting longer would hang the caller).
*/
private settle(force = false): void {
if (!force && this.pending && !this.disposed) {
return;
}
const waiters = this.waiters;
this.waiters = [];
for (const wake of waiters) {
wake();
}
}
/** Sends the unsent changes, unless a call or a resync is running. */
private flush(): void {
if (this.disposed || this.inflight !== null || this.resyncing || this.unsent === null) {
this.settle();
return;
}
const changes = this.unsent;
this.inflight = changes;
this.unsent = null;
const params: EditParams = {
id: this.id,
baseVersion: this.version,
edits: this.confirmed.edits(changes, this.separator),
};
void this.transport.edit(params).then((result) => {
this.onEditResult(changes, result);
});
}
/**
* Handles the answer to a `buffer.edit`.
*
* @param changes - the changes that were sent.
* @param result - the engine's answer.
*/
private onEditResult(changes: ChangeSet, result: RunResult<EditResult>): void {
if (this.disposed || this.inflight !== changes) {
return;
}
this.inflight = null;
if (result.ok) {
this.confirmed = this.confirmed.apply(changes, this.separator);
this.version = result.value.version;
this.latestKnown = Math.max(this.latestKnown, this.version);
if (this.latestKnown > this.version) {
this.resync();
} else {
this.flush();
}
return;
}
this.unsent = this.unsent ? changes.compose(this.unsent) : changes;
if (result.error.code === "stale_version") {
this.resync();
} else {
this.onError(result.error);
this.resync(true);
}
}
/**
* Fetches the engine text and rebases local changes onto it.
*
* @param dropLocal - discard unsent local changes instead of rebasing them
* (after the engine refused them for a reason other than a stale base).
*/
private resync(dropLocal = false): void {
if (this.disposed || this.resyncing || this.inflight !== null) {
return;
}
this.resyncing = true;
void this.transport.get(this.id).then((result) => {
this.resyncing = false;
if (this.disposed) {
return;
}
if (!result.ok || !isBufferInfo(result.value)) {
this.onError(
result.ok ? { code: "ipc", message: t("common.error.unexpectedResult", { command: "buffer.get" }) } : result.error,
);
this.settle(true);
return;
}
this.rebase(result.value, dropLocal);
});
}
/**
* Moves the local document onto fresh engine text.
*
* @param info - the engine's current buffer.
* @param dropLocal - see {@link resync}.
*/
private rebase(info: BufferInfo, dropLocal: boolean): void {
const fresh = EngineText.fromEngine(info.text);
const remote = diffDocs(this.confirmed.doc, fresh.doc);
const local = this.unsent;
let toLocal: ChangeSet;
if (local === null) {
toLocal = remote;
} else if (dropLocal) {
toLocal = local.invert(this.confirmed.doc).compose(remote);
this.unsent = null;
} else {
toLocal = remote.map(local, true);
this.unsent = local.map(remote);
if (this.unsent.empty) {
this.unsent = null;
}
}
this.confirmed = fresh;
this.version = info.version;
this.latestKnown = Math.max(this.latestKnown, info.version);
this.separator = separatorOf(info.lineEnding);
const undoable = this.undoableUntil !== null && info.version <= this.undoableUntil && !dropLocal;
if (this.undoableUntil !== null && Number.isFinite(this.undoableUntil) && this.version >= this.undoableUntil) {
this.undoableUntil = null;
}
if (!toLocal.empty) {
this.applyTransactions([
this.current.update({
changes: toLocal,
annotations: [remoteChange.of(true), Transaction.addToHistory.of(undoable)],
}),
]);
}
if (this.latestKnown > this.version) {
this.resync();
} else {
this.flush();
}
}
}