A desktop coding agent with free access to frontier models.
TypeScript
feat: the editor's language features run in the app
ogsamratb41081fd7e4c
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.tsindex 1e0f2347..0241dd50 100644--- a/apps/app/src/app/lib/omnirush-server.ts+++ b/apps/app/src/app/lib/omnirush-server.ts@@ -2917,14 +2917,14 @@ export function createOmniRushServerClient(options: { baseUrl: string; token?: ssignal,}),- /** The engine's language features for the editor (the project's own language servers); see the engine's /editor routes. */+ /** The editor's language features (the app server's language-server host, editor-lsp.ts). */editorLsp: <T = unknown>(workspaceId: string,op: "diagnostics" | "hover" | "definition" | "references" | "symbols" | "rename",payload: { path?: string; line?: number; character?: number; newName?: string; text?: string },signal?: AbortSignal,) =>- requestJson<T>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/opencode/editor/lsp/${op}`, {+ requestJson<T>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/editor/lsp/${op}`, {token,hostToken,method: "POST",diff --git a/apps/server/src/editor-lsp.e2e.test.ts b/apps/server/src/editor-lsp.e2e.test.tsnew file mode 100644index 00000000..3335faa0--- /dev/null+++ b/apps/server/src/editor-lsp.e2e.test.ts@@ -0,0 +1,103 @@+import { afterAll, describe, expect, test } from "bun:test";+import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { createEditorLsp, findProgram, type LspOp } from "./editor-lsp.js";++// Every editor language request against the real servers. The npm servers (typescript, pyright) are installed by+// the host itself into OMNIRUSH_LSP_E2E_TOOLS (set to run them); the others run when their program is on PATH.+const toolsDir = process.env.OMNIRUSH_LSP_E2E_TOOLS?.trim();+const roots: string[] = [];+const host = createEditorLsp({ toolsDir: toolsDir || join(tmpdir(), "omnirush-lsp-unused"), diagnosticsWaitMs: 30_000 });+afterAll(async () => {+ host.close();+ for (const root of roots) await rm(root, { recursive: true, force: true });+});++type Case = {+ server: string;+ available: boolean;+ files: Record<string, string>;+ file: string;+ /** The position of the use of `greet` (0-based). */+ use: { line: number; character: number };+ broken: string;+};++const CASES: Case[] = [+ {+ server: "typescript", available: Boolean(toolsDir) || Boolean(findProgram("typescript-language-server", "/nonexistent")),+ files: { "tsconfig.json": "{\"compilerOptions\":{\"strict\":true}}", "main.ts": "export function greet(name: string): string {\n return `hi ${name}`;\n}\nconst out: string = greet(\"a\");\n" },+ file: "main.ts", use: { line: 3, character: 21 }, broken: "const n: number = \"text\";\n",+ },+ {+ server: "pyright", available: Boolean(toolsDir) || Boolean(findProgram("pyright-langserver", "/nonexistent")),+ files: { "main.py": "def greet(name: str) -> str:\n return \"hi \" + name\n\nout = greet(\"a\")\n" },+ file: "main.py", use: { line: 3, character: 6 }, broken: "x: int = \"text\"\nundefined_name\n",+ },+ {+ server: "gopls", available: Boolean(findProgram("gopls", "/nonexistent")),+ files: { "go.mod": "module example.com/p\n\ngo 1.22\n", "main.go": "package main\n\nfunc greet(name string) string {\n\treturn \"hi \" + name\n}\n\nfunc main() {\n\t_ = greet(\"a\")\n}\n" },+ file: "main.go", use: { line: 7, character: 6 }, broken: "package main\n\nfunc main() {\n\tvar x int = \"text\"\n}\n",+ },+ {+ server: "rust-analyzer", available: Boolean(findProgram("rust-analyzer", "/nonexistent")),+ files: { "Cargo.toml": "[package]\nname = \"p\"\nversion = \"0.1.0\"\nedition = \"2021\"\n", "src/main.rs": "fn greet(name: &str) -> String {\n format!(\"hi {name}\")\n}\n\nfn main() {\n let _ = greet(\"a\");\n}\n" },+ file: "src/main.rs", use: { line: 5, character: 13 }, broken: "fn main() {\n let x = ;\n}\n",+ },+ {+ server: "clangd", available: Boolean(findProgram("clangd", "/nonexistent")),+ files: { "main.c": "int greet(int n) {\n return n + 1;\n}\n\nint main(void) {\n return greet(1);\n}\n" },+ file: "main.c", use: { line: 5, character: 9 }, broken: "int main(void) {\n return undefined_name;\n}\n",+ },+];++async function project(files: Record<string, string>): Promise<string> {+ const root = await mkdtemp(join(tmpdir(), "omnirush-lsp-"));+ roots.push(root);+ for (const [name, text] of Object.entries(files)) {+ await mkdir(join(root, name, ".."), { recursive: true });+ await writeFile(join(root, name), text);+ }+ return root;+}++describe("editor language features (editor-lsp.ts)", () => {+ test("refuses paths outside the project and answers an empty project", async () => {+ const root = await project({ "a.txt": "x" });+ expect(await host.run(root, "diagnostics", {})).toEqual([]);+ await expect(host.run(root, "hover", { path: "../outside.ts" })).rejects.toThrow(/outside the project/);+ expect(await host.run(root, "hover", { path: "a.txt" })).toEqual([]);+ expect(await host.run(root, "rename", { path: "a.txt", line: 0, character: 0, newName: "" })).toEqual([]);+ });++ for (const c of CASES) {+ (c.available ? test : test.skip)(`${c.server}: every operation, and unsaved text never stays`, async () => {+ const root = await project(c.files);+ const run = (op: LspOp, extra: Record<string, unknown> = {}) => host.run(root, op, { path: c.file, ...c.use, ...extra });+ // A server still loading its project (rust-analyzer runs cargo first) answers empty: asked again, bounded.+ for (let i = 0; i < 120 && ((await run("hover")) as unknown[]).length === 0; i += 1) await Bun.sleep(500);+ const symbols = await run("symbols") as Array<{ name?: string }>;+ expect(JSON.stringify(symbols)).toContain("greet");+ const hover = await run("hover") as unknown[];+ expect(hover.length).toBe(1);+ expect(JSON.stringify(hover)).toContain("greet");+ const definition = await run("definition") as unknown[];+ expect(definition.length).toBeGreaterThan(0);+ expect(JSON.stringify(definition)).toContain(c.file.split("/").pop()!);+ const references = await run("references") as unknown[];+ expect(references.length).toBeGreaterThanOrEqual(2);+ const rename = await run("rename", { newName: "welcome" }) as unknown[];+ expect(JSON.stringify(rename)).toContain("welcome");+ // Unsaved broken text: its diagnostics show for that request; the next request sees the disk file again.+ const unsaved = await run("diagnostics", { text: c.broken }) as Array<{ path: string; diagnostics: unknown[] }>;+ expect(unsaved.find((entry) => entry.path === c.file)?.diagnostics.length ?? 0).toBeGreaterThan(0);+ const disk = await run("diagnostics") as Array<{ path: string; diagnostics: Array<{ severity?: number }> }>;+ const errors = (disk.find((entry) => entry.path === c.file)?.diagnostics ?? []).filter((d) => d.severity === 1);+ expect(errors).toEqual([]);+ const all = await host.run(root, "diagnostics", {}) as Array<{ path: string }>;+ expect(all.every((entry) => !entry.path.startsWith(".."))).toBe(true);+ }, 300_000);+ }+});diff --git a/apps/server/src/editor-lsp.ts b/apps/server/src/editor-lsp.tsnew file mode 100644index 00000000..de54a679--- /dev/null+++ b/apps/server/src/editor-lsp.ts@@ -0,0 +1,324 @@+/**+ * The desktop editor's language features (diagnostics, hover, go to definition, references, symbols, rename),+ * served by the app's server. The 2.x engine has no language servers of its own, and this host is separate from+ * the agent: it only answers the editor (the same requests the 1.x engine's /editor/lsp routes answered).+ *+ * - Servers: typescript, pyright (each from PATH, else installed by the app with npm into its own folder, never+ * running install scripts), gopls, rust-analyzer and clangd (from PATH). A program is never taken from the+ * project's folder, and nothing is read from the project's opencode config.+ * - One server per (project, server), started on first use; closed with the app's server.+ * - A request with `text` (an unsaved buffer) runs alone: the text is opened for that request, then the file is+ * always opened again from disk, so unsaved text never stays in a server.+ */+import { spawn, execFile, type ChildProcess } from "node:child_process";+import { existsSync, mkdirSync, readFileSync } from "node:fs";+import { readFile } from "node:fs/promises";+import { delimiter, extname, isAbsolute, join, relative, resolve, sep } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++export type LspOp = "diagnostics" | "hover" | "definition" | "references" | "symbols" | "rename";+export const LSP_OPS: readonly LspOp[] = ["diagnostics", "hover", "definition", "references", "symbols", "rename"];+export type LspPayload = { path?: string; line?: number; character?: number; newName?: string; text?: string };++type Launch = { command: string; args: string[]; env?: Record<string, string> };+type ServerInfo = {+ id: string;+ extensions: string[];+ program: string;+ args: string[];+ /** npm packages the app installs when the program is not on PATH (the first one has the executable). */+ npm?: { packages: string[]; bin: string };+};++const SERVERS: ServerInfo[] = [+ { id: "typescript", extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"], program: "typescript-language-server", args: ["--stdio"],+ npm: { packages: ["[email protected]", "[email protected]"], bin: "typescript-language-server" } },+ { id: "pyright", extensions: [".py", ".pyi"], program: "pyright-langserver", args: ["--stdio"], npm: { packages: ["[email protected]"], bin: "pyright-langserver" } },+ { id: "gopls", extensions: [".go"], program: "gopls", args: [] },+ { id: "rust-analyzer", extensions: [".rs"], program: "rust-analyzer", args: [] },+ { id: "clangd", extensions: [".c", ".cc", ".cpp", ".cxx", ".c++", ".h", ".hh", ".hpp", ".hxx", ".m", ".mm"], program: "clangd", args: ["--background-index"] },+];++const LANGUAGE_IDS: Record<string, string> = {+ ".ts": "typescript", ".mts": "typescript", ".cts": "typescript", ".tsx": "typescriptreact", ".js": "javascript", ".mjs": "javascript",+ ".cjs": "javascript", ".jsx": "javascriptreact", ".py": "python", ".pyi": "python", ".go": "go", ".rs": "rust", ".c": "c", ".h": "c",+ ".m": "objective-c", ".mm": "objective-cpp",+};+const languageId = (file: string) => LANGUAGE_IDS[extname(file).toLowerCase()] ?? "cpp";++/** A program on PATH, never from inside the project. */+export function findProgram(program: string, projectRoot: string, env: NodeJS.ProcessEnv = process.env): string | null {+ const name = process.platform === "win32" && !/\.(exe|cmd)$/i.test(program) ? `${program}.exe` : program;+ for (const dir of (env.PATH ?? env.Path ?? "").split(delimiter)) {+ if (!dir || !isAbsolute(dir)) continue;+ const rel = relative(projectRoot, dir);+ if (!rel || (!rel.startsWith("..") && !isAbsolute(rel))) continue;+ if (existsSync(join(dir, name))) return join(dir, name);+ }+ return null;+}++const installs = new Map<string, Promise<string | null>>();+/** The npm server's executable script, installed once into the app's folder (no install scripts run). */+function installNpm(info: ServerInfo, toolsDir: string, projectRoot: string): Promise<string | null> {+ const npm = info.npm!;+ const prefix = join(toolsDir, info.id);+ const pkgName = npm.packages[0]!.replace(/@[^@/]+$/, "");+ const script = () => {+ try {+ const pkg = JSON.parse(readFileSync(join(prefix, "node_modules", pkgName, "package.json"), "utf8")) as { bin?: string | Record<string, string> };+ const rel = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.[npm.bin];+ return rel ? join(prefix, "node_modules", pkgName, rel) : null;+ } catch { return null; }+ };+ const existing = script();+ if (existing) return Promise.resolve(existing);+ let pending = installs.get(info.id);+ if (!pending) {+ pending = new Promise<string | null>((done) => {+ const npmBin = findProgram(process.platform === "win32" ? "npm.cmd" : "npm", projectRoot);+ if (!npmBin) return done(null);+ mkdirSync(prefix, { recursive: true });+ execFile(npmBin, ["install", "--prefix", prefix, "--ignore-scripts", "--no-audit", "--no-fund", "--silent", ...npm.packages],+ { timeout: 300_000, shell: process.platform === "win32" }, () => done(script()));+ }).finally(() => installs.delete(info.id));+ installs.set(info.id, pending);+ }+ return pending;+}++async function launchFor(info: ServerInfo, root: string, toolsDir: string): Promise<Launch | null> {+ const onPath = findProgram(info.program, root);+ if (onPath) return { command: onPath, args: info.args };+ if (!info.npm) return null;+ const script = await installNpm(info, toolsDir, root);+ // The app's own runtime runs the server's script (Electron as Node, or Node).+ return script ? { command: process.execPath, args: [script, ...info.args], env: { ELECTRON_RUN_AS_NODE: "1" } } : null;+}++/** Only the basics: no app tokens or engine password reach a language server. */+function basicEnv(): Record<string, string> {+ const out: Record<string, string> = {};+ for (const key of ["PATH", "Path", "HOME", "USER", "LOGNAME", "SHELL", "TMPDIR", "TMP", "TEMP", "LANG", "LC_ALL", "SystemRoot", "SYSTEMROOT", "WINDIR",+ "COMSPEC", "PATHEXT", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "GOPATH", "GOROOT", "GOFLAGS", "CARGO_HOME", "RUSTUP_HOME"]) {+ const value = process.env[key];+ if (value !== undefined) out[key] = value;+ }+ return out;+}++type Diagnostic = Record<string, unknown>;++/** One language server process over stdio (LSP's JSON-RPC framing). */+class LspClient {+ private readonly child: ChildProcess;+ private buffer = Buffer.alloc(0);+ private nextId = 1;+ private readonly waiting = new Map<number, (value: unknown) => void>();+ private readonly versions = new Map<string, number>();+ readonly diagnostics = new Map<string, Diagnostic[]>();+ private readonly diagnosticWaiters = new Map<string, Array<() => void>>();+ readonly ready: Promise<unknown>;+ private folder = "";+ closed = false;++ constructor(launch: Launch, root: string) {+ this.child = spawn(launch.command, launch.args, { cwd: root, stdio: ["pipe", "pipe", "ignore"], env: { ...basicEnv(), ...launch.env } });+ this.child.stdout!.on("data", (chunk: Buffer) => this.read(chunk));+ this.child.stdin!.on("error", () => this.close());+ this.child.on("exit", () => this.close());+ this.child.on("error", () => this.close());+ const folder = (this.folder = pathToFileURL(root).href);+ this.ready = this.request("initialize", {+ processId: process.pid, rootUri: folder, workspaceFolders: [{ uri: folder, name: root.split(sep).pop() || "project" }],+ capabilities: {+ textDocument: {+ synchronization: {}, hover: { contentFormat: ["markdown", "plaintext"] }, definition: { linkSupport: true }, references: {},+ documentSymbol: { hierarchicalDocumentSymbolSupport: true }, rename: {}, publishDiagnostics: { relatedInformation: true },+ },+ workspace: { workspaceFolders: true, configuration: true },+ },+ }, 60_000).then((result) => {+ this.notify("initialized", {});+ // Some servers (pyright) analyze nothing until they get settings: none come from the project.+ this.notify("workspace/didChangeConfiguration", { settings: {} });+ return result;+ });+ }++ private send(message: Record<string, unknown>): void {+ if (this.closed) return;+ const body = Buffer.from(JSON.stringify({ jsonrpc: "2.0", ...message }), "utf8");+ this.child.stdin!.write(Buffer.concat([Buffer.from(`Content-Length: ${body.length}\r\n\r\n`, "ascii"), body]));+ }++ private read(chunk: Buffer): void {+ this.buffer = Buffer.concat([this.buffer, chunk]);+ for (;;) {+ const end = this.buffer.indexOf("\r\n\r\n");+ if (end < 0) return;+ const length = Number(/Content-Length: *(\d+)/i.exec(this.buffer.subarray(0, end).toString("ascii"))?.[1] ?? Number.NaN);+ if (!Number.isFinite(length)) { this.buffer = this.buffer.subarray(end + 4); continue; }+ if (this.buffer.length < end + 4 + length) return;+ const body = this.buffer.subarray(end + 4, end + 4 + length).toString("utf8");+ this.buffer = this.buffer.subarray(end + 4 + length);+ let message: { id?: number | string; method?: string; params?: unknown; result?: unknown; error?: unknown };+ try { message = JSON.parse(body); } catch { continue; }+ if (message.method && message.id !== undefined) {+ // Server requests: no settings come from the project; everything else is acknowledged.+ const items = (message.params as { items?: unknown[] } | undefined)?.items;+ this.send({+ id: message.id,+ result: message.method === "workspace/configuration" ? (items ?? []).map(() => null)+ : message.method === "workspace/workspaceFolders" ? [{ uri: this.folder, name: "workspace" }] : null,+ });+ } else if (message.method === "textDocument/publishDiagnostics") {+ const params = message.params as { uri: string; diagnostics?: Diagnostic[] };+ this.diagnostics.set(params.uri, params.diagnostics ?? []);+ for (const wake of this.diagnosticWaiters.get(params.uri) ?? []) wake();+ } else if (typeof message.id === "number") {+ this.waiting.get(message.id)?.(message.error ? null : message.result);+ this.waiting.delete(message.id);+ }+ }+ }++ request(method: string, params: unknown, timeoutMs = 20_000): Promise<unknown> {+ if (this.closed) return Promise.resolve(null);+ const id = this.nextId++;+ return new Promise((done) => {+ const timer = setTimeout(() => { this.waiting.delete(id); done(null); }, timeoutMs);+ this.waiting.set(id, (value) => { clearTimeout(timer); done(value); });+ this.send({ id, method, params });+ });+ }++ notify(method: string, params: unknown): void {+ this.send({ method, params });+ }++ /** Opens (or replaces) the document with `text`, or the file's disk content. */+ async open(file: string, text?: string): Promise<void> {+ const uri = pathToFileURL(file).href;+ const content = text ?? (await readFile(file, "utf8").catch(() => ""));+ const version = (this.versions.get(uri) ?? 0) + 1;+ this.versions.set(uri, version);+ if (version === 1) this.notify("textDocument/didOpen", { textDocument: { uri, languageId: languageId(file), version, text: content } });+ else this.notify("textDocument/didChange", { textDocument: { uri, version }, contentChanges: [{ text: content }] });+ }++ /**+ * The diagnostics for `file` after an open: the first publish, then until the server goes quiet for a moment+ * (some servers publish the previous version's first), waited for at most `ms` in all.+ */+ waitForDiagnostics(file: string, ms: number, quietMs = 600): Promise<void> {+ const uri = pathToFileURL(file).href;+ return new Promise((done) => {+ let quiet: ReturnType<typeof setTimeout> | undefined;+ const finish = () => { clearTimeout(limit); clearTimeout(quiet); this.diagnosticWaiters.delete(uri); done(); };+ const limit = setTimeout(finish, ms);+ this.diagnosticWaiters.set(uri, [() => { clearTimeout(quiet); quiet = setTimeout(finish, quietMs); }]);+ });+ }++ close(): void {+ if (this.closed) return;+ this.closed = true;+ for (const done of this.waiting.values()) done(null);+ this.waiting.clear();+ try { this.child.kill(); } catch { /* gone */ }+ }+}++function asList(value: unknown): unknown[] {+ return Array.isArray(value) ? value : value ? [value] : [];+}++/** The editor's language features for every project of one app server. */+export function createEditorLsp(options: { toolsDir: string; diagnosticsWaitMs?: number }) {+ const clients = new Map<string, Promise<LspClient | null>>();+ let textLane: Promise<unknown> = Promise.resolve();++ function clientFor(root: string, file: string): Promise<LspClient | null> {+ const info = SERVERS.find((server) => server.extensions.includes(extname(file).toLowerCase()));+ if (!info) return Promise.resolve(null);+ const key = `${root}\0${info.id}`;+ const existing = clients.get(key);+ if (existing) {+ return existing.then((client) => {+ if (client && !client.closed) return client;+ if (clients.get(key) === existing) clients.delete(key);+ return client ? clientFor(root, file) : null;+ });+ }+ const pending = launchFor(info, root, options.toolsDir).then(async (launch) => {+ if (!launch) return null;+ const client = new LspClient(launch, root);+ return (await client.ready) && !client.closed ? client : (client.close(), null);+ }).catch(() => null);+ clients.set(key, pending);+ return pending;+ }++ /** Every diagnostic of the project's running servers, by project-relative path (only `only` when given). */+ async function projectDiagnostics(root: string, only?: string): Promise<Array<{ path: string; diagnostics: Diagnostic[] }>> {+ const out: Array<{ path: string; diagnostics: Diagnostic[] }> = [];+ for (const [key, pending] of clients) {+ if (!key.startsWith(`${root}\0`)) continue;+ const client = await pending;+ if (!client) continue;+ for (const [uri, diagnostics] of client.diagnostics) {+ const file = fileURLToPath(uri);+ if (only && resolve(file) !== resolve(only)) continue;+ const rel = relative(root, file);+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) continue;+ out.push({ path: rel.split(sep).join("/"), diagnostics });+ }+ }+ return out;+ }++ async function run(root: string, op: LspOp, payload: LspPayload): Promise<unknown> {+ if (op === "diagnostics" && !payload.path) return projectDiagnostics(root);+ if (op === "rename" && !payload.newName) return [];+ if (typeof payload.path !== "string" || !payload.path) throw new Error("path is required");+ const file = resolve(root, payload.path);+ const rel = relative(root, file);+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) throw new Error("path outside the project");+ const client = await clientFor(root, file);+ if (!client) return [];+ const position = { line: Math.max(0, Math.floor(payload.line ?? 0)), character: Math.max(0, Math.floor(payload.character ?? 0)) };+ const textDocument = { uri: pathToFileURL(file).href };+ const use = async (): Promise<unknown> => {+ const diagnosticsDone = op === "diagnostics" ? client.waitForDiagnostics(file, options.diagnosticsWaitMs ?? 5_000) : null;+ await client.open(file, payload.text);+ try {+ switch (op) {+ case "diagnostics": await diagnosticsDone; return await projectDiagnostics(root, file);+ case "hover": return [await client.request("textDocument/hover", { textDocument, position })].filter(Boolean);+ case "definition": return asList(await client.request("textDocument/definition", { textDocument, position }));+ case "references": return asList(await client.request("textDocument/references", { textDocument, position, context: { includeDeclaration: true } }));+ case "symbols": return asList(await client.request("textDocument/documentSymbol", { textDocument }));+ case "rename": return [await client.request("textDocument/rename", { textDocument, position, newName: payload.newName })].filter(Boolean);+ }+ return [];+ } finally {+ // Unsaved text never stays: the file is opened again from disk.+ if (payload.text !== undefined) await client.open(file);+ }+ };+ if (payload.text === undefined) return use();+ // One unsaved-text request at a time.+ const next = textLane.then(use, use);+ textLane = next.catch(() => undefined);+ return next;+ }++ return {+ run,+ close(): void {+ for (const pending of clients.values()) void pending.then((client) => client?.close());+ clients.clear();+ },+ };+}diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 90c16976..0188c86b 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -234,6 +234,7 @@ import { CloudProviderSync, parseCloudProviderDenSession } from "./cloud-provideimport { createEngineV2Preview, resolveInitialEngineV2PreviewState, type EngineV2Preview } from "./engine-v2-preview.js";import { MIGRATED_FROM } from "./engine-v2-migration.js";import { createV2BudgetWrap } from "./engine-v2-budget-wrap.js";+import { createEditorLsp, LSP_OPS, type LspOp, type LspPayload } from "./editor-lsp.js";import { APP_SECRET_HEADER, appRequestRefusal } from "./app-request-gate.js";import { isUploadFileDenied, sessionUploaderEnabled } from "./session-uploader.js";import { editorUserEditEvent, editorUserReviewEvent } from "./editor-events.js";@@ -303,6 +304,15 @@ async function capturePermissionMode(config: ServerConfig): Promise<ApprovalMode/** Automatic compaction (session-archive/auto-compact.ts), one per server: its counts live as long as the app. */const autoCompactorsByServer = new WeakMap<ServerConfig, AutoCompactor>();const engineV2ByServer = new WeakMap<ServerConfig, EngineV2Preview>();+const editorLspByServer = new WeakMap<ServerConfig, ReturnType<typeof createEditorLsp>>();+function editorLspFor(config: ServerConfig): ReturnType<typeof createEditorLsp> {+ let host = editorLspByServer.get(config);+ if (!host) {+ host = createEditorLsp({ toolsDir: join(runtimeStorageDir(config), "language-servers") });+ editorLspByServer.set(config, host);+ }+ return host;+}/*** How long a prompt waits for its chat's automatic compaction: the window* aborts a prompt request after 30 s, and the prompt's own capture steps@@ -1929,6 +1939,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {captureServerException(error, { method: "START", route: "startServer" });cloudProviderSync.stop();await engineV2Preview.stop().catch(() => undefined);+ editorLspByServer.get(config)?.close();engineInstanceReaper.close();clearEngineInstanceReaperForConfig(config);invalidateEngineMcpServerState(config, engineMcpServerState);@@ -2032,6 +2043,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {cloudProviderSync.stop();modelCatalogSync.stop();await engineV2Preview.stop().catch(() => undefined);+ editorLspByServer.get(config)?.close();engineInstanceReaper.close();clearEngineInstanceReaperForConfig(config);invalidateEngineMcpServerState(config, engineMcpServerState);@@ -5212,6 +5224,26 @@ function createRoutes(// The desktop editor. A save or a hunk review that names a chat the session// uploader is tracking adds a "user_edit" / "user_review" trace event to it;// nothing else in a chat's upload changes (editor-events.ts).+ // The editor's language features (editor-lsp.ts): the app's own language-server host.+ addRoute(routes, "POST", "/workspace/:id/editor/lsp/:op", "client", async (ctx) => {+ const op = ctx.params.op as LspOp;+ if (!LSP_OPS.includes(op)) throw new ApiError(404, "not_found", "Unknown language request");+ const workspace = await resolveWorkspace(config, ctx.params.id);+ if (workspace.workspaceType === "remote") throw new ApiError(404, "not_found", "Language features run for local projects only");+ const input = await readJsonBody(ctx.request);+ const payload: LspPayload = {+ ...(typeof input.path === "string" ? { path: input.path } : {}),+ ...(typeof input.line === "number" ? { line: input.line } : {}),+ ...(typeof input.character === "number" ? { character: input.character } : {}),+ ...(typeof input.newName === "string" ? { newName: input.newName } : {}),+ ...(typeof input.text === "string" ? { text: input.text } : {}),+ };+ try {+ return jsonResponse(await editorLspFor(config).run(await realpath(workspace.path).catch(() => workspace.path), op, payload));+ } catch (error) {+ throw new ApiError(400, "invalid_payload", error instanceof Error ? error.message : String(error));+ }+ });// /btw: a side question about a chat, answered without touching it (side-question.ts).addRoute(routes, "POST", "/workspace/:id/btw", "client", async (ctx) => {const workspace = await resolveWorkspace(config, ctx.params.id);