Compare commits

...
Author SHA1 Message Date
l0ng-ai 61f811434c Merge remote-tracking branch 'origin/main' into fix/debugger-variable-row-layout 2026-11-20 05:41:44 +08:00
Mr0Bread 4e1cec5233 refactor(ipc): enforce typed error-kind comparisons (#4612)
IPC error kinds were compared as untyped strings (`(e as { kind?: string }).kind === "notFound"`), so a misspelt kind compiled and silently never matched. A typed `isErrorKind(error, kind)` helper, taking a kind from the generated `IdeError["kind"]`, now handles wrapped and raw IPC errors in document sync, editor session restore, Spring service identity, plugin commands and recent projects.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 05:41:29 +08:00
l0ng-ai 150eacc3de fix(editor): keep parameter info readable in narrow panes (#4599)
Parameter Info had a fixed 640px cap and a 12-signature window, so in narrow panes it overflowed the editor and long signatures were clipped. The popup now fits the editor's tooltip bounds and height, uses the editor's current font size, wraps long signatures with a hanging indent, scrolls when needed and keeps the current parameter in view.
2026-11-20 05:40:20 +08:00
l0ng-ai f8257b88b4 Keep the full variable label available on hover 2026-11-20 03:54:34 +08:00
l0ng-ai 63b88bedc9 fix(debugger): keep values visible in narrow variables panes 2026-11-20 03:50:55 +08:00
14 changed files with 318 additions and 67 deletions

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
import { expect, stubDesktop, test } from "./fixtures";
const amountName = "regionalSettlementAmountFromExternalProcessorBeforeRounding";
const routingName = "settlementRoutingReferenceForCrossBorderReconciliation";
const routingValue = "'APR-2026 / eu-west / batch-701 / settlement complete'";
test("keeps values and their full-value action readable in a narrow debugger", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1220, height: 760 });
await stubDesktop(page);
await page.evaluate(
async ({ amountName, routingName, routingValue }) => {
const debugModule = "/src/features/debugger/state.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const servicesModule = "/src/workbench/contributions.ts";
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
const { toolWindowService } = await import(/* @vite-ignore */ servicesModule);
const h = window.__ipc.handlers;
h.debug_scopes = () => [{ name: "Locals", variablesReference: 100, expensive: false }];
h.debug_variables = () => [
{ name: amountName, value: "47.74", typeName: "float", variablesReference: 0, evaluateName: amountName },
{ name: routingName, value: routingValue, typeName: "str", variablesReference: 0, evaluateName: routingName },
];
adoptSession(91, {
name: "Checkout",
adapter: "debugpy",
status: "paused",
selectedFrame: 11,
frames: [{ id: 11, name: "checkout", path: null, line: 0, column: 0, presentationHint: null }],
});
moveToolWindow("debug", "right");
setToolWindowSize("right", 390);
toolWindowService().show("debug", true);
},
{ amountName, routingName, routingValue },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
const amount = debug.getByText("47.74", { exact: true });
await expect
.poll(() => amount.evaluate((el) => el.clientWidth > 0 && el.scrollWidth <= el.clientWidth + 1))
.toBe(true);
const routing = debug.getByRole("treeitem").filter({ hasText: routingName });
const show = routing.getByTitle("Show", { exact: true });
await expect(show).toBeInViewport({ ratio: 1 });
await show.click();
const dialog = page.getByRole("dialog", { name: `Value of ${routingName}` });
await expect(dialog.getByText(routingValue, { exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
await page.setViewportSize({ width: 1640, height: 760 });
await page.evaluate(async () => {
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { moveToolWindow } = await import(/* @vite-ignore */ layoutModule);
moveToolWindow("debug", "bottom");
});
await expect(show).toBeHidden();
await expect
.poll(() => routing.getByText(routingValue, { exact: true }).evaluate((el) => el.scrollWidth <= el.clientWidth + 1))
.toBe(true);
});
+76
View File
@@ -0,0 +1,76 @@
import type { Page } from "@playwright/test";
import type { SignatureHelp } from "../src/bindings";
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
function signature(name: string, parameters: string[]) {
let offset = name.length + 1;
const ranges: [number, number][] = parameters.map((parameter) => {
const range: [number, number] = [offset, offset + parameter.length];
offset = range[1] + 2;
return range;
});
return { label: `${name}(${parameters.join(", ")}): Invoice`, parameters: ranges, documentation: null };
}
async function openParameterInfo(page: Page, help: SignatureHelp) {
const editor = await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate((help) => {
window.__ipc.handlers.lsp_signature_help = () => help;
}, help);
await editor.locator(".cm-line", { hasText: "return order.toDto()" }).click();
await page.keyboard.press("End");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("Meta+p");
const popup = page.locator(".cm-lsp-signature");
await expect(popup).toBeVisible();
return { editor, popup };
}
test("parameter info wraps long parameters and follows the editor width", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 700 });
const parameter = "roundingPolicyForThirdPartyPaymentsWithMultipleSettlementCurrencies: RoundingPolicy";
const { editor, popup } = await openParameterInfo(page, {
signatures: [signature("formatInvoice", ["order: Cart", parameter, "currency: string"])],
activeSignature: 0,
activeParameter: 1,
});
await page.setViewportSize({ width: 560, height: 650 });
await expect
.poll(async () => {
const [pane, hint] = await Promise.all([editor.boundingBox(), popup.boundingBox()]);
return !!pane && !!hint && hint.x >= pane.x - 1 && hint.x + hint.width <= pane.x + pane.width + 1;
})
.toBe(true);
await expect.poll(() => popup.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(popup.locator("b")).toHaveText(parameter);
const fontSize = await editor.locator(".cm-content").evaluate((el) => getComputedStyle(el).fontSize);
await expect(popup).toHaveCSS("font-size", fontSize);
await page.keyboard.press("Escape");
await expect(popup).toBeHidden();
});
test("parameter info keeps the active overload visible and scrolls to the others", async ({ workbench: page }) => {
const signatures = Array.from({ length: 20 }, (_, i) =>
signature("formatInvoice", [`order: Cart${i}`, "currency: string"]),
);
const { popup } = await openParameterInfo(page, { signatures, activeSignature: 16, activeParameter: 1 });
await expect(popup.locator(".cm-lsp-signature-row")).toHaveCount(signatures.length);
const active = popup.locator(".cm-lsp-signature-active b");
await expect(active).toHaveText("currency: string");
await expect
.poll(async () => {
const [frame, parameter] = await Promise.all([popup.boundingBox(), active.boundingBox()]);
return (
!!frame && !!parameter && parameter.y >= frame.y && parameter.y + parameter.height <= frame.y + frame.height
);
})
.toBe(true);
expect(await popup.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
await popup.hover();
await page.mouse.wheel(0, -1200);
await expect.poll(() => popup.evaluate((el) => el.scrollTop)).toBe(0);
await expect(
popup.getByText("formatInvoice(order: Cart0, currency: string): Invoice", { exact: true }),
).toBeInViewport();
});
+2 -2
View File
@@ -47,7 +47,7 @@ import { useDistractionFree } from "@/workbench/distractionFree";
import { restoreMaximizedToolWindow } from "@/workbench/toolwindows/store";
import { ask, confirm } from "@/workbench/messages";
import { t, tx } from "@/platform/i18n";
import { call, commands, isTauri } from "@/platform/ipc";
import { call, commands, isErrorKind, isTauri } from "@/platform/ipc";
import { openLightweightEditor } from "./openLightweightEditor";
import { windowBackgroundHex } from "@/workbench/theme";
import { hoverActionsAt } from "@/platform/hoverActions";
@@ -736,7 +736,7 @@ export class EditorController implements SlotHost {
return this.slots.get(tabId) ?? this.createSlot(tabId, m, init);
})
.catch((e: unknown) => {
if (this.restoredTabs.has(tabId) && (e as { kind?: string } | null)?.kind === "notFound") {
if (this.restoredTabs.has(tabId) && isErrorKind(e, "notFound")) {
// A file from the saved session no longer exists: drop its tab quietly.
this.restoredTabs.delete(tabId);
this.restoredViews.delete(path);
+2 -2
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { ChangeSet, Text } from "@codemirror/state";
import type { TextChange } from "@/platform/ipc";
import type { IdeError, TextChange } from "@/platform/ipc";
import { DocSync, toTextChanges } from "./DocSync";
import { minimalChanges } from "./diff";
@@ -19,7 +19,7 @@ function numberedLines(count: number) {
}
class OutOfSync extends Error {
kind = "outOfSync";
readonly kind: IdeError["kind"] = "outOfSync";
}
/** Backend double: requests are queued and processed explicitly, in order. */
+2 -6
View File
@@ -25,7 +25,7 @@
* the snapshot, selections mapped).
*/
import { ChangeSet, Text } from "@codemirror/state";
import type { TextChange } from "@/platform/ipc";
import { isErrorKind, type TextChange } from "@/platform/ipc";
import { minimalChanges } from "./diff";
export interface SyncTransport {
@@ -64,10 +64,6 @@ export const frameScheduler: Scheduler = (fn) => {
setTimeout(once, 50);
};
function isOutOfSync(e: unknown): boolean {
return typeof e === "object" && e !== null && (e as { kind?: string }).kind === "outOfSync";
}
export function toTextChanges(cs: ChangeSet): TextChange[] {
const out: TextChange[] = [];
cs.iterChanges((fromA, toA, _fromB, _toB, inserted) => {
@@ -210,7 +206,7 @@ export class DocSync {
}
private onReject(error: unknown) {
if (!isOutOfSync(error)) {
if (!isErrorKind(error, "outOfSync")) {
this.host.onError?.(error);
this.hardResync(error);
return;
+51 -10
View File
@@ -6,8 +6,17 @@
*/
import { EditorSelection, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
import { completionStatus, hasNextSnippetField, hasPrevSnippetField } from "@codemirror/autocomplete";
import { EditorView, ViewPlugin, keymap, showTooltip, type Tooltip, type ViewUpdate } from "@codemirror/view";
import {
EditorView,
ViewPlugin,
keymap,
repositionTooltips,
showTooltip,
type Tooltip,
type ViewUpdate,
} from "@codemirror/view";
import { commands, type SignatureHelp } from "@/platform/ipc";
import { tooltipBounds } from "@/editor/core/cm/setup";
import { docOf, lspRequest, reportLspError, debounce } from "./lsp";
import { offsetToPos } from "./positions";
import { showHint } from "./hint";
@@ -40,8 +49,6 @@ export function splitSignature(label: string, params: ReadonlyArray<[number, num
return { before: label.slice(0, s), param: label.slice(s, e), after: label.slice(e) };
}
const MAX_ROWS = 12;
/** Whether an overload can take an argument at `index` (varargs take any number). */
export function acceptsParameter(sig: { label: string; parameters: ReadonlyArray<[number, number]> }, index: number) {
if (index < sig.parameters.length) return true;
@@ -54,23 +61,27 @@ function signatureTooltip(s: SigState): Tooltip {
pos: s.pos,
above: true,
strictSide: false,
create: () => {
create: (view) => {
const dom = document.createElement("div");
dom.className = "cm-lsp-signature";
dom.setAttribute("role", "tooltip");
const { signatures, activeSignature, activeParameter } = s.help;
const start = Math.max(0, Math.min(activeSignature - 6, signatures.length - MAX_ROWS));
signatures.slice(start, start + MAX_ROWS).forEach((sig, j) => {
const i = start + j;
let active: HTMLElement | null = null;
signatures.forEach((sig, i) => {
const row = document.createElement("div");
row.className = "cm-lsp-signature-row";
if (i === activeSignature) row.classList.add("cm-lsp-signature-active");
else if (!acceptsParameter(sig, activeParameter)) row.classList.add("cm-lsp-signature-disabled");
if (i === activeSignature) {
row.classList.add("cm-lsp-signature-active");
row.setAttribute("aria-current", "true");
active = row;
} else if (!acceptsParameter(sig, activeParameter)) row.classList.add("cm-lsp-signature-disabled");
const parts = splitSignature(sig.label, sig.parameters, activeParameter);
row.append(parts.before);
if (parts.param) {
const b = document.createElement("b");
b.textContent = parts.param;
row.appendChild(b);
if (i === activeSignature) active = b;
}
row.append(parts.after);
dom.appendChild(row);
@@ -81,7 +92,37 @@ function signatureTooltip(s: SigState): Tooltip {
d.classList.add("cm-lsp-signature-doc");
dom.appendChild(d);
}
return { dom };
const fit = ({ left, right }: { left: number; right: number }) => {
const width = `${Math.max(0, Math.floor(right - left))}px`;
const fontSize = getComputedStyle(view.contentDOM).fontSize;
const changed = dom.style.getPropertyValue("--cm-signature-width") !== width || dom.style.fontSize !== fontSize;
if (changed) {
dom.style.setProperty("--cm-signature-width", width);
dom.style.fontSize = fontSize;
}
return changed;
};
// Reveal the current parameter after wrapping or a vertical clamp. Leave manual scrolling alone.
let fittedWidth = 0;
let fittedHeight = 0;
return {
dom,
mount: () => void fit(tooltipBounds(view)),
positioned: (space) => {
if (fit(space)) {
repositionTooltips(view);
return;
}
if (!active || (fittedWidth === dom.clientWidth && fittedHeight === dom.clientHeight)) return;
fittedWidth = dom.clientWidth;
fittedHeight = dom.clientHeight;
const top = dom.getBoundingClientRect().top + dom.clientTop;
const parameter = active.getBoundingClientRect();
const below = parameter.bottom - (top + fittedHeight);
if (parameter.top < top || parameter.height >= fittedHeight) dom.scrollTop += parameter.top - top;
else if (below > 0) dom.scrollTop += below;
},
};
},
};
}
+17 -10
View File
@@ -270,28 +270,35 @@ export const lspTheme = EditorView.theme({
cursor: "pointer",
},
".cm-lsp-link-button:hover": { color: "var(--link-hover)", textDecoration: "underline" },
".cm-lsp-signature": {
".cm-tooltip.cm-lsp-signature": {
fontFamily: "var(--openidea-editor-font, var(--font-mono))",
fontWeight: "var(--fw-code, 400)",
fontSize: "var(--openidea-editor-font-size, var(--fs-code))",
padding: "6px 10px",
maxWidth: "640px",
maxWidth: "min(640px, var(--cm-signature-width, 100%))",
maxHeight: "min(380px, 65vh)",
paddingBlock: "var(--space-0-5)",
overflow: "auto",
overscrollBehavior: "contain",
},
".cm-lsp-signature-row": {
color: "var(--fg-secondary)",
whiteSpace: "pre-wrap",
overflowWrap: "anywhere",
lineHeight: "1.5",
padding: "var(--space-0-5) var(--space-2)",
paddingInlineStart: "calc(var(--space-2) + 2ch)",
textIndent: "-2ch",
},
".cm-lsp-signature-row": { color: "var(--fg-subtle)", whiteSpace: "pre-wrap", lineHeight: "max(20px, 1.5em)" },
".cm-lsp-signature-active": {
color: "var(--fg-strong)",
backgroundColor: "var(--bg-identifier-under-caret, color-mix(in srgb, var(--accent) 14%, transparent))",
margin: "0 -10px",
padding: "0 10px",
},
".cm-lsp-signature-disabled": { opacity: "0.55" },
".cm-lsp-signature b": { fontWeight: "var(--fw-code-bold, 700)", color: "var(--fg-strong)" },
".cm-lsp-signature-doc": {
borderTop: "1px solid var(--border-popup)",
marginTop: "6px",
paddingTop: "6px",
maxHeight: "160px",
overflow: "auto",
marginTop: "var(--space-1)",
padding: "var(--space-2)",
},
".cm-tooltip:has(> .cm-lsp-hint)": { background: "none", border: "none", boxShadow: "none" },
".cm-lsp-hint": {
@@ -10,12 +10,12 @@
.row {
display: flex;
align-items: center;
gap: 5px;
gap: var(--space-1);
min-width: 0;
width: 100%;
max-width: 100%;
box-sizing: border-box;
font-family: var(--font-mono);
font-family: var(--font-ui);
font-size: var(--fs-ui);
white-space: pre;
color: var(--fg);
@@ -23,7 +23,10 @@
}
.name {
flex: none;
min-width: 0;
max-width: 45%;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg);
}
@@ -41,7 +44,6 @@
.nodeIcon {
flex: none;
margin-right: 1px;
}
.eq {
@@ -49,15 +51,28 @@
color: var(--fg-subtle);
}
.valueGroup {
display: flex;
align-items: center;
gap: var(--space-1);
min-width: min(8ch, 45%);
flex: 1 1 0;
}
.value {
min-width: 0;
flex: 1 1 0;
overflow: hidden;
text-overflow: ellipsis;
font-family: var(--font-mono);
}
.showValue {
flex: none;
flex: 0 0 auto;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding: 0;
border: 0;
background: none;
@@ -112,6 +127,7 @@
.type {
min-width: 0;
max-width: 25%;
flex: 0 1 auto;
overflow: hidden;
text-overflow: ellipsis;
@@ -136,7 +152,7 @@
.editInput {
flex: 1;
min-width: 80px;
min-width: min(80px, 40%);
height: 18px;
padding: 0 4px;
font: inherit;
+34 -23
View File
@@ -415,7 +415,9 @@ function VarEditRow({
useEffect(() => acquirePopup(), []);
return (
<span className={styles.row}>
<span className={styles.name}>{node.name}</span>
<span className={styles.name} title={node.name}>
{node.name}
</span>
<span className={styles.eq}>=</span>
<input
className={clsx(styles.editInput, error && styles.editInvalid)}
@@ -465,18 +467,21 @@ function VarRow({
const valueRef = useRef<HTMLSpanElement>(null);
const [overflow, setOverflow] = useState(false);
useLayoutEffect(() => {
const el = valueRef.current;
if (!el) {
const text = valueRef.current;
const group = text?.parentElement;
if (!text || !group) {
setOverflow(false);
return;
}
const update = () => setOverflow(el.scrollWidth > el.clientWidth + 1);
// The group measures the space available before the Show button takes any of it.
const update = () => setOverflow(text.scrollWidth > group.clientWidth + 1);
update();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(update);
observer.observe(el);
observer.observe(group);
observer.observe(text);
return () => observer.disconnect();
}, [node.value]);
}, [node.value, node.typeName, node.error]);
if (node.kind === "message") return <span className={styles.message}>{node.name}</span>;
if (node.kind === "scope")
return (
@@ -489,7 +494,7 @@ function VarRow({
const shown = shownValue(node.value, node.typeName);
const evaluation = node.kind === "eval";
return (
<span className={styles.row}>
<span className={styles.row} title={node.name}>
<Icon name={nodeIcon(node)} size={16} className={styles.nodeIcon} />
{!shown.entry && (
<>
@@ -511,23 +516,29 @@ function VarRow({
<span className={styles.error}>{oneLine(node.error)}</span>
) : (
<>
{shown.label && <span className={styles.type}>{shown.label}</span>}
<span ref={valueRef} className={clsx(styles.value, kind && styles[kind])} title={node.value}>
{oneLine(shown.text)}
</span>
{overflow && (
<button
type="button"
className={styles.showValue}
title={tx("Show")}
onClick={(e) => {
e.stopPropagation();
onShowValue(node);
}}
>
…{tx("Show")}
</button>
{shown.label && (
<span className={styles.type} title={shown.label}>
{shown.label}
</span>
)}
<span className={styles.valueGroup}>
<span ref={valueRef} className={clsx(styles.value, kind && styles[kind])} title={node.value}>
{oneLine(shown.text)}
</span>
{overflow && (
<button
type="button"
className={styles.showValue}
title={tx("Show")}
onClick={(e) => {
e.stopPropagation();
onShowValue(node);
}}
>
…{tx("Show")}
</button>
)}
</span>
</>
)}
</span>
@@ -1,5 +1,5 @@
/** Bounded local configuration evidence, never an effective runtime identity. */
import type { FileEntry } from "@/platform/ipc";
import { isErrorKind, type FileEntry } from "@/platform/ipc";
import { ipcPath } from "@/platform/paths";
export interface ServiceReader {
@@ -90,7 +90,7 @@ export async function loadServiceName(module: string, reader: ServiceReader): Pr
try {
entries = await reader.directory(directory);
} catch (error) {
if ((error as { kind?: string }).kind === "notFound") continue;
if (isErrorKind(error, "notFound")) continue;
return null;
}
for (const file of entries) {
+2 -1
View File
@@ -1,6 +1,7 @@
/** Installed plugins, their UI contributions, the selected plugin theme, and the operations on them. */
import { create } from "zustand";
import { tx } from "@/platform/i18n";
import { isErrorKind } from "@/platform/ipc";
import type {
ActiveTheme,
CapabilityInfo,
@@ -412,7 +413,7 @@ export async function runPluginCommand(
const status = usePlugins.getState().plugins.find((p) => p.id === pluginId)?.status;
// A trap disables the plugin and the backend already announced why; a
// consent request opens its own dialog.
const permission = (e as { kind?: string }).kind === "permissionDenied";
const permission = isErrorKind(e, "permissionDenied");
if (status !== "failed" && !permission)
notifications().notify({ group: "plugins", level: "error", title: `${title} failed`, body: errorText(e) });
return null;
+6 -4
View File
@@ -5,6 +5,7 @@ import {
commands,
IpcError,
isCancelled,
isErrorKind,
isTauri,
type RecentProject,
type RecentProjectGroup,
@@ -117,10 +118,10 @@ export async function removeRecent(path: string) {
}
/** An open failure's kind and message, whether it is an `IpcError` or a raw rejected invoke. */
function failure(e: unknown): { kind?: string; message: string } {
function failure(e: unknown): { kind?: unknown; message: string } {
if (e instanceof IpcError) return { kind: e.kind, message: e.message };
if (e && typeof e === "object" && "message" in e)
return { kind: (e as { kind?: string }).kind, message: String((e as { message: unknown }).message) };
return { kind: "kind" in e ? e.kind : undefined, message: String(e.message) };
return { message: e instanceof Error ? e.message : String(e) };
}
@@ -149,8 +150,9 @@ export async function openRecent(project: Pick<RecentProject, "path" | "name">):
return true;
} catch (e) {
if (isCancelled(e)) return false;
const { kind, message } = failure(e);
if (kind === "notFound" || (!kind && /not found|no such/i.test(message))) {
const error = failure(e);
const { message } = error;
if (isErrorKind(error, "notFound") || (!error.kind && /not found|no such/i.test(message))) {
// A balloon can be switched off for this group and the welcome screen has no log to open.
const remove = await confirm({
title: tx`Project folder not found: ${project.name}`,
+29 -1
View File
@@ -1,6 +1,6 @@
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import type { IdeEvent } from "@/bindings";
import { emitLocalIdeEvent, ideEventsReady, onIdeEvent } from "./ipc";
import { emitLocalIdeEvent, ideEventsReady, IpcError, isErrorKind, onIdeEvent, type IdeError } from "./ipc";
type Listener = (e: { payload: IdeEvent }) => void;
const backend = vi.hoisted(() => ({ listener: null as Listener | null }));
@@ -60,3 +60,31 @@ describe("IDE event dispatch", () => {
expect(handler).toHaveBeenCalledTimes(1);
});
});
describe("isErrorKind", () => {
const versionMismatch: IdeError = { kind: "outOfSync", message: "document version changed" };
it.each([
["a wrapped IPC error", new IpcError(versionMismatch), true],
["a raw IPC rejection", versionMismatch, true],
["a different IPC kind", new IpcError({ kind: "notFound", message: "file missing" }), false],
["null", null, false],
["undefined", undefined, false],
["a string", "outOfSync", false],
["a number", 1, false],
["an object without a kind", { message: "version changed" }, false],
["a non-string kind", { kind: 1 }, false],
["an unknown kind", { kind: "unknown" }, false],
])("classifies %s", (_name, error, matches) => {
expect(isErrorKind(error, "outOfSync")).toBe(matches);
});
it("treats an unreadable kind as a non-match", () => {
const error = {
get kind() {
throw new Error("unreadable");
},
};
expect(isErrorKind(error, "outOfSync")).toBe(false);
});
});
+10
View File
@@ -24,6 +24,16 @@ export class IpcError extends Error {
}
}
/** Matches both wrapped IPC errors and raw invoke rejections by kind. */
export function isErrorKind(e: unknown, kind: IdeError["kind"]): boolean {
if (typeof e !== "object" || e === null) return false;
try {
return "kind" in e && e.kind === kind;
} catch {
return false;
}
}
type Result<T> = { status: "ok"; data: T } | { status: "error"; error: IdeError };
/** Unwraps a fallible command result: `await call(commands.docOpen(path))`. */