import { readFileSync, type Stats, statSync, writeFileSync } from "node:fs"; import path from "node:path"; import { pathToFileURL } from "node:url"; import { collectSupportedFiles, resolveRoot, resolveSupportedFile, } from "./files.js"; import { LspClient } from "./lsp-client.js"; import { ensureLspInstalled } from "./lsp-install.js"; import { applyTextEdits, hasOverlappingTextEdits, splitWorkspaceEdits, } from "./text-edits.js"; import type { CodeAction, DiagnosticEntry, LspServerAdapter, LspTextEdit, StatusContext, } from "./types.js"; export const DEFAULT_FILE_LIMIT = 50; /** Cap on rendered diagnostics per lane/tool; extras are truncated with a count. */ export const DEFAULT_MAX_DIAGNOSTICS = 200; /** Cap on LSP lanes running at once: each lane spawns its own server process * (jdtls alone is a JVM with a 2 GB heap), so an unbounded parallel dispatch * across every installed language server would stampede the machine. */ export const MAX_PARALLEL_LSP_LANES = 4; /** * Run async tasks with at most `limit` in flight, preserving result order. * Tasks must not reject: callers isolate per-task errors themselves (both * lsp tool entry points do), and a rejecting task would lose the remaining * queued tasks' results. */ export async function withConcurrencyLimit( tasks: Array<() => Promise>, limit: number, ): Promise { const results: T[] = new Array(tasks.length); let next = 0; const workers = Array.from( { length: Math.min(limit, tasks.length) }, async () => { while (next < tasks.length) { const index = next++; results[index] = await tasks[index](); } }, ); await Promise.all(workers); return results; } export async function runDiagnostics( adapter: LspServerAdapter, params: { root?: string; paths?: string[]; limit?: number; files?: string[]; autoInstall?: boolean; maxDiagnostics?: number; }, timeoutMs: number, signal: AbortSignal | undefined, ctx: StatusContext, statusKey: string, ) { throwIfAborted(signal, adapter); const root = resolveRoot(params.root); const command = adapter.defaultCommand; const files = params.files ?? collectSupportedFiles( adapter, root, params.paths, params.limit ?? DEFAULT_FILE_LIMIT, ); if (files.length === 0) { return textResult( `${adapter.name} LSP found no supported files to check.`, { root, command, files: [], summary: { files: 0, diagnostics: 0 }, }, ); } const { result, autoInstalled } = await withLspClient( adapter, root, timeoutMs, signal, ctx, statusKey, "diagnostics", params.autoInstall, async (client) => { const openedFiles: Array<{ file: string; uri: string }> = []; try { for (const file of files) { throwIfAborted(signal, adapter); const uri = pathToFileURL(file).href; const text = readFileSync(file, "utf8"); client.didOpen(uri, text, adapter.languageIdFor(file)); openedFiles.push({ file, uri }); } // Per-file isolation mirrors runFix: one file's timeout or // mid-run server crash becomes that file's error entry, never // a lost lane that discards the diagnostics already collected // for every other file. const settled = await Promise.allSettled( openedFiles.map(async ({ file, uri }) => ({ file, uri, diagnostics: await client.diagnostics(uri), })), ); // A caller cancel is still a whole-call outcome, not a // per-file failure. throwIfAborted(signal, adapter); const entries: DiagnosticEntry[] = settled.map((outcome, index) => { const { file, uri } = openedFiles[index]; const relativePath = path.relative(root, file) || file; if (outcome.status === "fulfilled") { return { path: relativePath, uri, diagnostics: outcome.value.diagnostics, }; } return { path: relativePath, uri, diagnostics: [], error: outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason), }; }); return textResult( formatDiagnostics(adapter, entries, params.maxDiagnostics), { root, command, files: entries, summary: summarize(entries), }, ); } finally { for (const { uri } of openedFiles) client.didClose(uri); } }, ); return noteAutoInstalled(result, autoInstalled); } export async function runFix( adapter: LspServerAdapter, params: { root?: string; paths: string[]; kind?: string; write?: boolean; autoInstall?: boolean; }, timeoutMs: number, signal: AbortSignal | undefined, ctx: StatusContext, statusKey: string, ) { const root = resolveRoot(params.root); const actionKind = params.kind?.trim() || "source.fixAll"; const { result, autoInstalled } = await withLspClient( adapter, root, timeoutMs, signal, ctx, statusKey, "fix", params.autoInstall, async (client) => { // One client for all files of this adapter: batch fix amortizes the // spawn/initialize cost instead of paying it per file. const perFile: FileFixEntry[] = []; // Wall-clock budget for the whole call: per-request timeouts only // bound each LSP round-trip, so a slow server over a long batch // could otherwise hang the call for minutes per file. const fixDeadline = Date.now() + FIX_OVERALL_BUDGET_MS; for (const requestedPath of params.paths) { throwIfAborted(signal, adapter); if (Date.now() >= fixDeadline) { perFile.push({ ok: false, relativePath: path.relative(root, requestedPath) || requestedPath, requestedPath, error: FIX_BUDGET_EXHAUSTED_MESSAGE, }); continue; } try { const file = resolveSupportedFile(adapter, root, requestedPath); const uri = pathToFileURL(file).href; const statBefore = statSync(file); const text = readFileSync(file, "utf8"); client.didOpen(uri, text, adapter.languageIdFor(file)); let resolvedActions: CodeAction[]; let selectedActions: CodeAction[]; let edits: LspTextEdit[]; let otherDocumentUris: string[]; let skippedResourceOperations: string[]; let newText: string; try { const diagnostics = await client.diagnostics(uri); throwIfAborted(signal, adapter); const actions = await client.codeActions( uri, text, diagnostics, actionKind, ); throwIfAborted(signal, adapter); resolvedActions = await client.resolveActions(actions); throwIfAborted(signal, adapter); selectedActions = selectCodeActions(resolvedActions, actionKind); const splits = selectedActions.map((action) => splitWorkspaceEdits(action.edit, uri), ); edits = splits.flatMap((split) => split.edits); otherDocumentUris = [ ...new Set(splits.flatMap((split) => split.otherDocumentUris)), ]; skippedResourceOperations = [ ...new Set(splits.flatMap((split) => split.resourceOperations)), ]; if (hasOverlappingTextEdits(text, edits)) { const relativePath = path.relative(root, file) || file; throw new Error( `${adapter.name} LSP returned overlapping code-action edits for ${relativePath}; ` + "use a narrower action kind.", ); } newText = applyTextEdits(text, edits); } finally { client.didClose(uri); } const changed = newText !== text; throwIfAborted(signal, adapter); // Stale-write guard: the workspace copy may have been edited // (IDE buffer save, another agent, the user) between the // read above and the write below. Overwriting from stale // content would silently drop those changes, so the file is // left untouched and reported as this file's failure. const writeError = params.write && changed ? writeIfUnchanged( file, statBefore.mtimeMs, statBefore.size, newText, ) : undefined; if (writeError) { perFile.push({ ok: false, relativePath: path.relative(root, file) || file, requestedPath, error: writeError, }); continue; } perFile.push({ ok: true, file, uri, relativePath: path.relative(root, file) || file, text, newText, changed, resolvedActions, selectedActions, edits, otherDocumentUris, skippedResourceOperations, }); } catch (error) { // A caller cancel must abort the whole run; anything else is // this file's failure. The remaining files still get their // chance, and already-written files stay visible in the report. if (signal?.aborted) throw error; perFile.push({ ok: false, relativePath: path.relative(root, requestedPath) || requestedPath, requestedPath, error: error instanceof Error ? error.message : String(error), }); } } const failedFiles = perFile.filter((entry) => !entry.ok); if (perFile.length === 1 && perFile[0].ok) { const single = perFile[0]; return textResult( formatEditSummary( adapter, "fix", root, single.file, single.changed, params.write, single.newText, ) + skippedChangesNote(single), { path: path.relative(root, single.file) || single.file, uri: single.uri, changed: single.changed, write: params.write ?? false, kind: actionKind, actions: single.resolvedActions.map(({ title, kind }) => ({ title, kind, })), appliedActions: single.selectedActions.map(({ title, kind }) => ({ title, kind, })), edits: single.edits, otherDocumentUris: single.otherDocumentUris, skippedResourceOperations: single.skippedResourceOperations, text: params.write ? undefined : single.newText, }, ); } if (perFile.length === 1 && !perFile[0].ok) { // A single-file failure still throws out of runFix; the tool // layer isolates it into that route's failure section. The // real difference is on success: only single-file calls // return the full preview text (batch returns summaries). throw new Error(perFile[0].error); } // Batch mode: summaries only; full preview text stays a single-file feature. const okFiles = perFile.filter( (entry): entry is Extract => entry.ok, ); const changedCount = okFiles.filter((entry) => entry.changed).length; const header = `${adapter.name} LSP fix: ${changedCount} of ${perFile.length} file(s) ${params.write ? "updated" : "have changes"}${failedFiles.length > 0 ? `, ${failedFiles.length} failed` : ""}.`; const sections = perFile.map((entry) => { if (!entry.ok) { return `${entry.relativePath}: failed (${entry.error})`; } const relativePath = path.relative(root, entry.file) || entry.file; const status = entry.changed ? params.write ? "updated" : "has changes" : "unchanged"; const note = entry.changed && !params.write ? " (single-path call previews the full text)" : ""; const skippedCount = entry.otherDocumentUris.length + entry.skippedResourceOperations.length; const skippedNote = skippedCount > 0 ? ` [${skippedCount} change(s) for other documents/resources skipped]` : ""; return `${relativePath}: ${status}${note}${skippedNote} [${entry.selectedActions.length} action(s) applied]`; }); return textResult([header, "", ...sections].join("\n"), { root, write: params.write ?? false, kind: actionKind, changedFiles: changedCount, files: perFile.map((entry) => entry.ok ? { path: entry.relativePath, uri: entry.uri, changed: entry.changed, actions: entry.resolvedActions.map(({ title, kind }) => ({ title, kind, })), appliedActions: entry.selectedActions.map( ({ title, kind }) => ({ title, kind, }), ), edits: entry.edits, otherDocumentUris: entry.otherDocumentUris, } : { path: entry.relativePath, failed: true as const, error: entry.error, }, ), }); }, ); return noteAutoInstalled(result, autoInstalled); } /** * Per-file fix outcome. A failed file never aborts the batch (unless the * caller aborted); its error is surfaced in the report and details.files. * A single-file call keeps its all-or-nothing contract instead. */ type FileFixEntry = | { ok: true; file: string; uri: string; relativePath: string; text: string; newText: string; changed: boolean; resolvedActions: CodeAction[]; selectedActions: CodeAction[]; edits: LspTextEdit[]; otherDocumentUris: string[]; skippedResourceOperations: string[]; } | { ok: false; relativePath: string; requestedPath: string; error: string; }; /** Wall-clock budget for one lsp_fix call across all of its files. */ const FIX_OVERALL_BUDGET_MS = 300_000; const FIX_BUDGET_EXHAUSTED_MESSAGE = "skipped: overall fix budget exhausted; re-run lsp_fix on this file"; /** * Write the fixed text only when the file is still the copy the LSP analyzed: * the mtime and size captured before the read must be unchanged at write * time. Size catches writes that land within the same mtime tick (coarse * clocks on network shares); mtime catches same-size overwrites. * Returns the failure reason, or undefined when the write succeeded. */ function writeIfUnchanged( file: string, mtimeBefore: number, sizeBefore: number, newText: string, ): string | undefined { let stat: Stats | undefined; try { stat = statSync(file); } catch { return "file was removed after it was read; fix not written"; } if (stat.mtimeMs !== mtimeBefore || stat.size !== sizeBefore) { return "file changed on disk after it was read; fix not written — re-run lsp_fix to work from the current content"; } try { writeFileSync(file, newText); } catch (error) { return `write failed: ${error instanceof Error ? error.message : String(error)}`; } return undefined; } /** withLspClient 的执行体:安装(可选)→ 起服务器 → 跑 operation → 收尾。 * * 状态栏的清除交给调用方统一做(安装在 try 之外失败也要清),这里只负责在 * 真正开始跑的时候把文案从「installing」换成活动名。 */ async function runWithClient( adapter: LspServerAdapter, root: string, timeoutMs: number, signal: AbortSignal | undefined, ctx: StatusContext, statusKey: string, activity: "diagnostics" | "fix", autoInstall: boolean | undefined, operation: (client: LspClient) => Promise, ): Promise<{ result: T; autoInstalled: boolean }> { let autoInstalled = false; if ( (adapter.installRecipes?.length || adapter.customInstaller) && adapter.autoInstall ) { const install = await ensureLspInstalled( adapter, root, signal, autoInstall !== false, ); if (!install.ok) { throw new Error( `${adapter.name} LSP command not found: ${adapter.defaultCommand.command}. ${adapter.missingCommandHint}` + `${install.detail ? ` Install attempts: ${install.detail}` : ""}`, ); } autoInstalled = install.autoInstalled ?? false; } const client = new LspClient( adapter, adapter.defaultCommand, root, adapter.timeoutMs ?? timeoutMs, ); const abort = () => client.close(); signal?.addEventListener("abort", abort, { once: true }); let cleanupFailure: { error: unknown } | undefined; let result: T; try { ctx.ui.setStatus(statusKey, `${adapter.name} ${activity}`); throwIfAborted(signal, adapter); await client.start(); throwIfAborted(signal, adapter); await client.initialize(root); throwIfAborted(signal, adapter); result = await operation(client); } finally { try { await client.shutdown(); } catch (error) { cleanupFailure = { error }; } finally { signal?.removeEventListener("abort", abort); } } // An operation rejection already propagates through finally and remains primary. if (cleanupFailure) throw cleanupFailure.error; throwIfAborted(signal, adapter); return { result, autoInstalled }; } /** withLspClient 起一次服务器并把状态栏从头报到尾。 * * 状态栏从第一件事就开始报,而不是等服务器起来:自动安装要下载几十 MB * (jdtls、rust-analyzer 尤其),以前这段完全是沉默的,界面上看不出在下载 * 还是卡死了。安装与运行用两种文案(installing / diagnostics|fix),卡在哪 * 一步一眼看得出来;清状态放在最外层 finally,安装失败、被取消、运行报错 * 都不会留下一条挂着的状态。 */ export async function withLspClient( adapter: LspServerAdapter, root: string, timeoutMs: number, signal: AbortSignal | undefined, ctx: StatusContext, statusKey: string, activity: "diagnostics" | "fix", autoInstall: boolean | undefined, operation: (client: LspClient) => Promise, ): Promise<{ result: T; autoInstalled: boolean }> { throwIfAborted(signal, adapter); const mayInstall = (adapter.installRecipes?.length || adapter.customInstaller) && adapter.autoInstall; if (mayInstall) { ctx.ui.setStatus(statusKey, `${adapter.name} installing`); } try { return await runWithClient( adapter, root, timeoutMs, signal, ctx, statusKey, activity, autoInstall, operation, ); } finally { clearStatus(ctx, statusKey); } } export function clearStatus(ctx: StatusContext, statusKey: string) { try { ctx.ui.setStatus(statusKey, undefined); } catch { // UI may be unavailable during teardown; it must never bypass resource cleanup. } } function selectCodeActions(actions: CodeAction[], requestedKind: string) { return actions.filter( (action) => action.kind === requestedKind || action.kind?.startsWith(`${requestedKind}.`), ); } function formatDiagnostics( adapter: LspServerAdapter, entries: DiagnosticEntry[], maxDiagnostics?: number, ) { const cap = Math.max( 1, Math.floor(maxDiagnostics ?? DEFAULT_MAX_DIAGNOSTICS), ); const lines: string[] = []; let shown = 0; let truncated = 0; for (const entry of entries) { if (entry.error) { lines.push(`${entry.path}: failed (${entry.error})`); continue; } if (entry.diagnostics.length === 0) { lines.push(`${entry.path}: no diagnostics`); continue; } for (const diagnostic of entry.diagnostics) { if (shown >= cap) { truncated++; continue; } shown++; lines.push(formatDiagnosticLine(adapter, entry, diagnostic)); } } if (truncated > 0) { lines.push( `… ${truncated} more diagnostics truncated (maxDiagnostics=${cap}).`, ); } const summary = summarize(entries); return [ `${adapter.name} LSP diagnostics: ${summary.diagnostics} diagnostic(s) across ${summary.files} file(s)${summary.failed > 0 ? `, ${summary.failed} file(s) failed` : ""}.`, "", ...lines, ].join("\n"); } function formatDiagnosticLine( adapter: LspServerAdapter, entry: DiagnosticEntry, diagnostic: DiagnosticEntry["diagnostics"][number], ) { const line = diagnostic.range.start.line + 1; const column = diagnostic.range.start.character + 1; const severity = severityName(diagnostic.severity); const source = diagnostic.source ?? adapter.name; const code = diagnostic.code === undefined ? "" : ` ${diagnostic.code}`; return `${entry.path}:${line}:${column}: ${severity} ${source}${code}: ${diagnostic.message}`; } function formatEditSummary( adapter: LspServerAdapter, action: "fix", root: string, file: string, changed: boolean, write: boolean | undefined, text: string, ) { const relativePath = path.relative(root, file) || file; const status = changed ? write ? "updated" : "computed changes for" : "left unchanged"; const summary = `${adapter.name} LSP ${action} ${status} ${relativePath}.`; if (write || !changed) return summary; return `${summary}\n\n${text}`; } function summarize(entries: DiagnosticEntry[]) { return { files: entries.length, diagnostics: entries.reduce( (total, entry) => total + entry.diagnostics.length, 0, ), failed: entries.filter((entry) => entry.error).length, }; } function skippedChangesNote(entry: { otherDocumentUris: string[]; skippedResourceOperations: string[]; }) { const parts: string[] = []; if (entry.otherDocumentUris.length > 0) { parts.push( `${entry.otherDocumentUris.length} edit(s) target other document(s) and were not applied: ${entry.otherDocumentUris.join(", ")}`, ); } if (entry.skippedResourceOperations.length > 0) { parts.push( `resource operation(s) not applied: ${entry.skippedResourceOperations.join(", ")}`, ); } return parts.length > 0 ? `\n\nNote: ${parts.join("; ")}.` : ""; } function severityName(severity: number | undefined) { if (severity === 1) return "error"; if (severity === 2) return "warning"; if (severity === 3) return "info"; if (severity === 4) return "hint"; return "diagnostic"; } function throwIfAborted( signal: AbortSignal | undefined, adapter: LspServerAdapter, ) { if (signal?.aborted) throw new Error(`${adapter.name} LSP request aborted.`); } export function textResult(text: string, details: unknown) { return { content: [{ type: "text" as const, text }], details, }; } /** Extract the rendered text section from a tool result (shared by the tools). */ export function textFromResult(result: { content?: Array<{ type?: string; text?: string }>; }) { return result.content?.find((item) => item.type === "text")?.text ?? ""; } /** Append the pi-lens-style "[auto-installed]" marker when this run installed the server. */ function noteAutoInstalled< T extends { content: Array<{ type: string; text?: string }>; details: unknown; }, >(result: T, autoInstalled: boolean): T { if (!autoInstalled) return result; const text = result.content[0]?.text; return { ...result, content: [ { type: "text", text: text ? `${text}\n\n[auto-installed]` : text }, ], details: { ...(result.details as object), autoInstalled: true }, }; }