/** * Project-wide diagnostics for the Problems tool window, status bar and file * decorations. The backend sends full replacements per (file, producer), so * the store keeps one list per source and merges them per file. */ import { create } from "zustand"; import type { Diagnostic, Severity } from "@/bindings"; import { isLibraryPath } from "@/editor/api"; import { onIdeEvent } from "@/platform/ipc"; import { onLocalDiagnostics } from "@/platform/localDiagnostics"; import { applyProfile, inspectionProfile, subscribeInspectionProfile, type ProfileOverrides, } from "@/platform/inspections"; export type FileDiagnostics = ReadonlyMap; /** path → source → diagnostics. */ export type ProblemsMap = ReadonlyMap; export interface SeverityCounts { error: number; warning: number; info: number; hint: number; } /** * `prev` (one file's sources) with `source`'s diagnostics replaced; undefined when nothing * changes. An empty result means the file has no problems left. */ function replaceSource(prev: FileDiagnostics | undefined, source: string, items: readonly Diagnostic[]) { if (!items.length && !prev?.has(source)) return undefined; const sources = new Map(prev ?? []); if (items.length) sources.set( source, items.map((d) => (d.source ? d : { ...d, source })), ); else sources.delete(source); return sources; } function putSources(map: Map, path: string, sources: FileDiagnostics) { if (sources.size) map.set(path, sources); else map.delete(path); } /** Replaces `source`'s diagnostics for `path`; returns the same map when nothing changed. */ export function mergeDiagnostics( map: ProblemsMap, path: string, source: string, items: readonly Diagnostic[], ): ProblemsMap { const sources = replaceSource(map.get(path), source, items); if (!sources) return map; const next = new Map(map); putSources(next, path, sources); return next; } const SEVERITY_ORDER: Record = { error: 0, warning: 1, info: 2, hint: 3 }; // A file's sources map is replaced whenever its diagnostics change, so it keys the merged list. const merged = new WeakMap(); const sameProblem = (d: Diagnostic) => `${d.range.start.line}:${d.range.start.col}-${d.range.end.line}:${d.range.end.col} ${d.severity} ${d.message}`; /** * All diagnostics of a file across sources, ordered by position then severity. An error both * Build and the tsc watcher report is listed once. */ export function fileDiagnostics(map: ProblemsMap, path: string): readonly Diagnostic[] { return mergedSources(map.get(path)); } function mergedSources(sources: FileDiagnostics | undefined): readonly Diagnostic[] { if (!sources) return []; let items = merged.get(sources); if (!items) { // Build's tsc step and the tsc watcher (Problems › TypeScript Project Errors) print the same errors. const build = sources.get("build"); const built = build && sources.has("tsc") ? new Set(build.map(sameProblem)) : null; items = [...sources] .flatMap(([source, list]) => (built && source === "tsc" ? list.filter((d) => !built.has(sameProblem(d))) : list)) .sort( (a, b) => a.range.start.line - b.range.start.line || a.range.start.col - b.range.start.col || SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity], ); merged.set(sources, items); } return items; } /** The producer (inspection) that reported `d`, one of `path`'s problems in `map`. */ /** * The file the Problems "File" tab shows: the active text editor's, or the active tab's * own path when it is another editor kind (a notebook keeps its cells' diagnostics there). */ export function currentProblemsPath( textPath: string | null, activeInput: { kind: string; path?: string | null } | null, ): string | null { if (activeInput && activeInput.kind !== "file" && activeInput.kind !== "virtual" && activeInput.path) return activeInput.path; return textPath; } const CELL_SCHEME = "vscode-notebook-cell:"; /** The notebook a cell's diagnostics key (`vscode-notebook-cell:#`) belongs to. */ function cellNotebook(key: string): string | null { if (!key.startsWith(CELL_SCHEME)) return null; const rest = key.slice(CELL_SCHEME.length); const hash = rest.indexOf("#"); const path = decodeURIComponent(hash < 0 ? rest : rest.slice(0, hash)); return /^\/[A-Za-z]:\//.test(path) ? path.slice(1) : path; } /** The diagnostics keys of one file: the file itself and, for a notebook, its cells. */ export function filePaths(map: ProblemsMap, path: string): string[] { const out = map.has(path) ? [path] : []; for (const key of map.keys()) if (cellNotebook(key) === path) out.push(key); return out; } export function producerFor(map: ProblemsMap, path: string, d: Diagnostic): string | null { for (const [source, items] of map.get(path) ?? []) if (items.includes(d)) return source; return null; } export interface ProblemOrder { /** Errors before warnings before infos (IDEA's default). */ bySeverity: boolean; /** By message text, then position; otherwise by position, then text. */ byName: boolean; } export const DEFAULT_PROBLEM_ORDER: ProblemOrder = { bySeverity: true, byName: false }; const natural = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }); /** A file's problems in the Problems view order (Sort by Severity / Name). */ export function sortProblems(items: readonly Diagnostic[], order: ProblemOrder): Diagnostic[] { const position = (a: Diagnostic, b: Diagnostic) => a.range.start.line - b.range.start.line || a.range.start.col - b.range.start.col; return [...items].sort( (a, b) => (order.bySeverity ? SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity] : 0) || (order.byName ? natural.compare(a.message, b.message) || position(a, b) : position(a, b) || natural.compare(a.message, b.message)), ); } export function countSeverities(diags: Iterable): SeverityCounts { const c: SeverityCounts = { error: 0, warning: 0, info: 0, hint: 0 }; for (const d of diags) c[d.severity]++; return c; } export function projectCounts(map: ProblemsMap): SeverityCounts { const c: SeverityCounts = { error: 0, warning: 0, info: 0, hint: 0 }; for (const sources of map.values()) for (const d of mergedSources(sources)) c[d.severity]++; return c; } export function worstSeverity(diags: Iterable): Severity | null { let best: Severity | null = null; for (const d of diags) if (best === null || SEVERITY_ORDER[d.severity] < SEVERITY_ORDER[best]) best = d.severity; return best; } /** `raw` under the inspection profile: disabled inspections dropped, severities remapped. */ export function profiledProblems(raw: ProblemsMap, profile: ProfileOverrides): Map { const out = new Map(); for (const [path, sources] of raw) { for (const [source, items] of sources) { const next = replaceSource(out.get(path), source, applyProfile(profile, source, items)); if (next) putSources(out, path, next); } } return out; } /** * A problems map the store updates in place, so applying an event costs the size of the event, * not the number of files. Each change publishes a new facade object: subscribers still see a new * `map`/`raw` identity exactly when the content changed, but an older facade reads the current * content, so keep a copy (`new Map(map)`) to compare against later, never the facade itself. */ class ProblemsSnapshot implements ProblemsMap { constructor(readonly data: Map) {} get size() { return this.data.size; } get(path: string) { return this.data.get(path); } has(path: string) { return this.data.has(path); } keys() { return this.data.keys(); } values() { return this.data.values(); } entries() { return this.data.entries(); } forEach(fn: (value: FileDiagnostics, path: string, map: ProblemsMap) => void) { for (const [path, sources] of this.data) fn(sources, path, this); } [Symbol.iterator]() { return this.data[Symbol.iterator](); } } interface ProblemsState { /** As reported, before the inspection profile. */ raw: ProblemsSnapshot; /** What the views show. */ map: ProblemsSnapshot; /** `projectCounts(map)`, kept up to date per event. */ counts: SeverityCounts; } const NO_COUNTS: SeverityCounts = { error: 0, warning: 0, info: 0, hint: 0 }; const emptyProblems = (): ProblemsState => ({ raw: new ProblemsSnapshot(new Map()), map: new ProblemsSnapshot(new Map()), counts: NO_COUNTS, }); export const useProblems = create(emptyProblems); function recount(counts: SeverityCounts, removed: readonly Diagnostic[], added: readonly Diagnostic[]) { const c = { ...counts }; for (const d of removed) c[d.severity]--; for (const d of added) c[d.severity]++; return c; } /** Replaces `source`'s diagnostics for `path` in `snapshot`'s data; the new facade, or null when nothing changed. */ function applyTo(snapshot: ProblemsSnapshot, path: string, source: string, items: readonly Diagnostic[]) { const sources = replaceSource(snapshot.data.get(path), source, items); if (!sources) return null; putSources(snapshot.data, path, sources); return new ProblemsSnapshot(snapshot.data); } export function applyDiagnosticsEvent(path: string, source: string, items: readonly Diagnostic[]) { // Library sources (an SDK interface, a dependency's code) are not the project's problems. if (isLibraryPath(path)) items = []; useProblems.setState((s) => { // The file's sources map is replaced, not changed, so this is the list before the event. const before = mergedSources(s.map.get(path)); const raw = applyTo(s.raw, path, source, items); if (!raw) return s; const map = applyTo(s.map, path, source, applyProfile(inspectionProfile(), source, items)); if (!map) return { raw }; return { raw, map, counts: recount(s.counts, before, mergedSources(map.get(path))) }; }); } export function clearProblems() { useProblems.setState(emptyProblems()); } export function installProblemsEvents(): () => void { const off = onIdeEvent("diagnostics", (e) => applyDiagnosticsEvent(e.path, e.source, e.items)); // Typo, file references, SQL: inspections the editor runs itself. const offLocal = onLocalDiagnostics(applyDiagnosticsEvent); const offProfile = subscribeInspectionProfile(() => useProblems.setState((s) => { const map = new ProblemsSnapshot(profiledProblems(s.raw, inspectionProfile())); return { map, counts: projectCounts(map) }; }), ); return () => { off(); offLocal(); offProfile(); }; } /** * Errors and warnings as `rel:line:col: severity: message (source)` lines, errors first, at most * `max`; null when there are none. For an agent's context. */ export function problemsReport(map: ProblemsMap, root: string, max = 60): string | null { const rows: { severity: Severity; text: string }[] = []; for (const path of map.keys()) { const rel = path.startsWith(`${root}/`) ? path.slice(root.length + 1) : path; for (const d of fileDiagnostics(map, path)) { if (d.severity !== "error" && d.severity !== "warning") continue; const at = `${rel}:${d.range.start.line + 1}:${d.range.start.col + 1}`; const source = d.source ? ` (${d.source})` : ""; rows.push({ severity: d.severity, text: `${at}: ${d.severity}: ${d.message.split("\n")[0]}${source}` }); } } if (!rows.length) return null; rows.sort((a, b) => Number(a.severity !== "error") - Number(b.severity !== "error")); const shown = rows.slice(0, max).map((r) => r.text); if (rows.length > max) shown.push(`… ${rows.length - max} more`); return shown.join("\n"); }