Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(viewer): open the file, not the API URL that failed (PRD-7674) (#2999)

Andrew Mikofalvy9e8a00e24c6e
diff --git a/.changeset/viewer-open-file-handoff.md b/.changeset/viewer-open-file-handoff.md
new file mode 100644
index 000000000..148aaa295
--- /dev/null
+++ b/.changeset/viewer-open-file-handoff.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Fix "Open file" wiping out the app when a file preview fails to load. Opening a file the built-in viewer could not show — a text file over the 1 MB limit, a binary one, or one it declined for any other reason — offered an "Open file" button that pointed straight back at the request that had just failed. Clicking it navigated the whole window there, so the editor disappeared and left an empty window with nothing but the traffic-light buttons and no way back.
+
+"Open file" now hands the actual file to your Mac to open in whatever app it belongs to, the same way it already works elsewhere in the preview pane, and the editor stays put. In the browser it opens in a new tab instead. When the file simply is not there, the button no longer appears at all, since there is nothing to open. The desktop app also refuses outright to navigate the window to an internal address like that, so a stray link cannot blank the app again.
diff --git a/knip.config.ts b/knip.config.ts
index f004e6bc3..13582ee18 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -123,9 +123,7 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],
project: 'src/**',
- ignoreDependencies: [
- '@types/shell-quote',
- ],
+ ignoreDependencies: ['@types/shell-quote'],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],
diff --git a/packages/app/src/components/AssetPreview.tsx b/packages/app/src/components/AssetPreview.tsx
index 7542940bc..8e614e442 100644
--- a/packages/app/src/components/AssetPreview.tsx
+++ b/packages/app/src/components/AssetPreview.tsx
@@ -101,6 +101,7 @@ function AssetPreviewBody({ assetPath, mediaKind }: AssetPreviewProps) {
<TextViewer
key={assetPath}
src={assetTextUrl(assetPath)}
+ assetPath={assetPath}
fileName={fileName}
extension={rawExtension.toLowerCase()}
/>
@@ -119,6 +120,7 @@ function AssetPreviewBody({ assetPath, mediaKind }: AssetPreviewProps) {
<MermaidFileViewer
key={assetPath}
src={assetTextUrl(assetPath)}
+ assetPath={assetPath}
fileName={fileName}
extension={rawExtension.toLowerCase()}
/>
diff --git a/packages/app/src/components/LintConfigEditor.tsx b/packages/app/src/components/LintConfigEditor.tsx
index b7707300e..c17b65dce 100644
--- a/packages/app/src/components/LintConfigEditor.tsx
+++ b/packages/app/src/components/LintConfigEditor.tsx
@@ -80,6 +80,7 @@ export function LintConfigEditor({ assetPath }: LintConfigEditorProps) {
<TextViewer
key={assetPath}
src={assetTextUrl(assetPath)}
+ assetPath={assetPath}
fileName={fileName}
extension={extension}
/>
diff --git a/packages/app/src/components/MermaidFileViewer.tsx b/packages/app/src/components/MermaidFileViewer.tsx
index 586919f80..cfbba8068 100644
--- a/packages/app/src/components/MermaidFileViewer.tsx
+++ b/packages/app/src/components/MermaidFileViewer.tsx
@@ -29,6 +29,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip
import { MermaidView } from '@/editor/components/Mermaid';
import { useViewerText, type ViewerTextSource } from './use-viewer-text';
import { ViewerErrorPane, ViewerLoadingPane } from './ViewerStatusPane';
+import { resolveViewerOpenFile } from './viewer-open-file';
type MermaidFileViewerProps = ViewerTextSource & {
fileName: string;
@@ -62,7 +63,12 @@ export function MermaidFileViewer({ fileName, extension, ...source }: MermaidFil
dataAttr="data-mermaid-file-viewer"
extraAttrs={extraAttrs}
message={fetchState.message}
- openHref={source.src}
+ openFile={resolveViewerOpenFile({
+ assetPath: source.assetPath,
+ fileName,
+ extension,
+ httpStatus: fetchState.httpStatus,
+ })}
/>
);
}
diff --git a/packages/app/src/components/SchemaConfigEditor.tsx b/packages/app/src/components/SchemaConfigEditor.tsx
index fe31e2cac..97747559c 100644
--- a/packages/app/src/components/SchemaConfigEditor.tsx
+++ b/packages/app/src/components/SchemaConfigEditor.tsx
@@ -111,6 +111,7 @@ export function SchemaConfigEditor({ assetPath }: SchemaConfigEditorProps) {
<TextViewer
key={assetPath}
src={assetTextUrl(assetPath)}
+ assetPath={assetPath}
fileName={fileName}
extension={extension}
/>
diff --git a/packages/app/src/components/SkillMarkdownLoader.tsx b/packages/app/src/components/SkillMarkdownLoader.tsx
index fa45eb440..8925d1eb1 100644
--- a/packages/app/src/components/SkillMarkdownLoader.tsx
+++ b/packages/app/src/components/SkillMarkdownLoader.tsx
@@ -41,7 +41,8 @@ export function SkillMarkdownLoader({
return <ViewerLoadingPane fileName={fileName} dataAttr={DATA_ATTR} />;
}
if (fetchState.status === 'error') {
- // No "Open file" handoff — a skill bundle file has no asset-server URL.
+ // No "Open file" handoff — a skill bundle file lives outside the content
+ // dir, so there is no project-relative path to hand to the OS.
return (
<ViewerErrorPane fileName={fileName} dataAttr={DATA_ATTR} message={fetchState.message} />
);
diff --git a/packages/app/src/components/TextViewer.error-message.dom.test.tsx b/packages/app/src/components/TextViewer.error-message.dom.test.tsx
index 6ecf2f276..f0eb0b9a1 100644
--- a/packages/app/src/components/TextViewer.error-message.dom.test.tsx
+++ b/packages/app/src/components/TextViewer.error-message.dom.test.tsx
@@ -41,6 +41,7 @@ describe('TextViewer — human-readable load errors', () => {
const { container } = render(
<TextViewer
src="/api/asset-text?path=fishing-log/Morning_Activity.gpx"
+ assetPath="fishing-log/Morning_Activity.gpx"
fileName="Morning_Activity.gpx"
extension="gpx"
/>,
@@ -58,7 +59,12 @@ describe('TextViewer — human-readable load errors', () => {
test('404 renders a not-found explanation', async () => {
globalThis.fetch = mockFetchStatus(404);
const { container } = render(
- <TextViewer src="/api/asset-text?path=gone.csv" fileName="gone.csv" extension="csv" />,
+ <TextViewer
+ src="/api/asset-text?path=gone.csv"
+ assetPath="gone.csv"
+ fileName="gone.csv"
+ extension="csv"
+ />,
);
await waitFor(() => {
expect(container.querySelector('[data-text-viewer-state="error"]')).not.toBeNull();
@@ -69,7 +75,12 @@ describe('TextViewer — human-readable load errors', () => {
test('an unmapped status keeps the diagnostic code for debuggability', async () => {
globalThis.fetch = mockFetchStatus(503);
const { container } = render(
- <TextViewer src="/api/asset-text?path=weird.bin" fileName="weird.bin" extension="bin" />,
+ <TextViewer
+ src="/api/asset-text?path=weird.bin"
+ assetPath="weird.bin"
+ fileName="weird.bin"
+ extension="bin"
+ />,
);
await waitFor(() => {
expect(container.querySelector('[data-text-viewer-state="error"]')).not.toBeNull();
diff --git a/packages/app/src/components/TextViewer.tsx b/packages/app/src/components/TextViewer.tsx
index 6ae6e034f..9491e3123 100644
--- a/packages/app/src/components/TextViewer.tsx
+++ b/packages/app/src/components/TextViewer.tsx
@@ -31,6 +31,7 @@ import { okCmTheme } from '@/editor/extensions/cm-theme';
import { loadCodeMirrorLanguageForExtension } from './text-viewer-languages';
import { useViewerText, type ViewerTextSource } from './use-viewer-text';
import { ViewerErrorPane, ViewerLoadingPane } from './ViewerStatusPane';
+import { resolveViewerOpenFile } from './viewer-open-file';
const darkTheme = okCmTheme({
dark: true,
@@ -47,7 +48,8 @@ const lightTheme = okCmTheme({
* Exactly one text source (`src` for a content-dir asset, or `loadText` for a
* scope-aware skill-bundle read) plus the display coordinates. The source half
* is the `ViewerTextSource` discriminated union, so "both" / "neither" can't be
- * passed. `src` (when present) also targets the "Open file" fallback link.
+ * passed. The `src` variant also carries the project-relative `assetPath`, which
+ * is what the error pane's "Open file" handoff targets.
*/
type TextViewerProps = ViewerTextSource & {
fileName: string;
@@ -143,9 +145,12 @@ export function TextViewer({ fileName, extension, ...source }: TextViewerProps)
dataAttr="data-text-viewer"
extraAttrs={extraAttrs}
message={fetchState.message}
- // Skill bundle files (`loadText` mode) have no asset-server URL, so the
- // "Open file" handoff only applies to the content-dir `src` path.
- openHref={source.src}
+ openFile={resolveViewerOpenFile({
+ assetPath: source.assetPath,
+ fileName,
+ extension,
+ httpStatus: fetchState.httpStatus,
+ })}
/>
);
}
diff --git a/packages/app/src/components/ViewerStatusPane.open-file.dom.test.tsx b/packages/app/src/components/ViewerStatusPane.open-file.dom.test.tsx
new file mode 100644
index 000000000..8486d89eb
--- /dev/null
+++ b/packages/app/src/components/ViewerStatusPane.open-file.dom.test.tsx
@@ -0,0 +1,261 @@
+/**
+ * Pin the read-only viewers' "Open file" handoff.
+ *
+ * The failure this guards: the affordance used to be a bare `<a href>` pointing
+ * at the very `/api/asset-text` URL whose failure produced the pane. Clicking it
+ * was a top-level navigation, so the browser (and, in the desktop shell, the
+ * whole BrowserWindow) left the single-page app and rendered the raw API
+ * response — for a 404 or 413 that is an empty body, i.e. a window with nothing
+ * in it and no in-app way back.
+ *
+ * Two properties are asserted here, both behavioral:
+ * 1. The control is not a same-origin `<a>` into `/api/*`, and activating it
+ * reaches the desktop asset bridge with the project-relative FILE path.
+ * 2. A 404 renders no affordance at all — there is no file to hand over.
+ *
+ * Runs under the jsdom DOM tier.
+ */
+
+import { cleanup, fireEvent, render, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+
+const { TextViewer } = await import('./TextViewer.tsx');
+const { MermaidFileViewer } = await import('./MermaidFileViewer.tsx');
+
+/** Non-OK response of the given status; the viewer throws before reading a body. */
+function mockFetchStatus(status: number): typeof globalThis.fetch {
+ return (() =>
+ Promise.resolve({
+ ok: false,
+ status,
+ text: async () => '',
+ } as Response)) as typeof globalThis.fetch;
+}
+
+type OpenAssetSpy = ReturnType<typeof vi.fn>;
+
+/**
+ * Install a minimal desktop bridge so the real `dispatchAssetClick` takes its
+ * Electron branch. Exercising the shipped dispatcher (rather than stubbing it)
+ * is what makes this a proof that the click reaches `shell.openAsset`.
+ */
+function installDesktopBridge(): OpenAssetSpy {
+ const openAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ (window as unknown as { okDesktop: unknown }).okDesktop = {
+ shell: { openAsset, revealAsset: vi.fn(async (_: string) => ({ ok: true }) as const) },
+ };
+ return openAsset;
+}
+
+async function findErrorPane(container: HTMLElement, attr: string): Promise<void> {
+ await waitFor(() => {
+ expect(container.querySelector(`[${attr}-state="error"]`)).not.toBeNull();
+ });
+}
+
+function openFileControl(container: HTMLElement): HTMLElement | null {
+ return container.querySelector('[data-testid="viewer-open-file"]');
+}
+
+describe('viewer error pane — "Open file" handoff', () => {
+ const originalFetch = globalThis.fetch;
+
+ beforeEach(() => {
+ globalThis.fetch = mockFetchStatus(413);
+ });
+
+ afterEach(() => {
+ cleanup();
+ globalThis.fetch = originalFetch;
+ delete (window as unknown as { okDesktop?: unknown }).okDesktop;
+ });
+
+ test('413 offers the handoff, and it is not an anchor into /api/*', async () => {
+ installDesktopBridge();
+ const { container } = render(
+ <TextViewer
+ src="/api/asset-text?path=logs/huge.csv"
+ assetPath="logs/huge.csv"
+ fileName="huge.csv"
+ extension="csv"
+ />,
+ );
+ await findErrorPane(container, 'data-text-viewer');
+
+ const control = openFileControl(container);
+ expect(control).not.toBeNull();
+ // The defect shape: a same-frame navigation to the API surface.
+ expect(container.querySelector('a[href*="/api/"]')).toBeNull();
+ expect(control?.closest('a')).toBeNull();
+ });
+
+ test('activating the handoff opens the FILE through the desktop bridge', async () => {
+ const openAsset = installDesktopBridge();
+ const { container } = render(
+ <TextViewer
+ src="/api/asset-text?path=logs/huge.csv"
+ assetPath="logs/huge.csv"
+ fileName="huge.csv"
+ extension="csv"
+ />,
+ );
+ await findErrorPane(container, 'data-text-viewer');
+
+ fireEvent.click(openFileControl(container) as HTMLElement);
+
+ await waitFor(() => {
+ expect(openAsset).toHaveBeenCalledTimes(1);
+ });
+ // The project-relative path, NOT the /api/asset-text URL that just failed.
+ expect(openAsset).toHaveBeenCalledWith('logs/huge.csv');
+ });
+
+ test('web host (no desktop bridge) opens a new tab instead of navigating', async () => {
+ const openSpy = vi.fn(() => null);
+ const originalOpen = window.open;
+ window.open = openSpy as unknown as typeof window.open;
+ try {
+ const { container } = render(
+ <TextViewer
+ src="/api/asset-text?path=logs/huge.csv"
+ assetPath="logs/huge.csv"
+ fileName="huge.csv"
+ extension="csv"
+ />,
+ );
+ await findErrorPane(container, 'data-text-viewer');
+ fireEvent.click(openFileControl(container) as HTMLElement);
+ await waitFor(() => {
+ expect(openSpy).toHaveBeenCalledTimes(1);
+ });
+ expect(openSpy.mock.calls[0]?.[1]).toBe('_blank');
+ // The regression was the URL, not the mechanism: the old anchor pointed at
+ // the `/api/asset-text` request that had just failed. Pin the byte-serving
+ // endpoint and the file it addresses, so re-wiring the target back to the
+ // failed URL cannot pass on `_blank` alone.
+ const openedUrl = String(openSpy.mock.calls[0]?.[0] ?? '');
+ expect(openedUrl).toContain('/api/asset?');
+ expect(openedUrl).not.toContain('/api/asset-text');
+ expect(openedUrl).toContain(encodeURIComponent('logs/huge.csv'));
+ } finally {
+ window.open = originalOpen;
+ }
+ });
+
+ test('404 renders no handoff — the file does not exist', async () => {
+ installDesktopBridge();
+ globalThis.fetch = mockFetchStatus(404);
+ const { container } = render(
+ <TextViewer
+ src="/api/asset-text?path=logs/gone.csv"
+ assetPath="logs/gone.csv"
+ fileName="gone.csv"
+ extension="csv"
+ />,
+ );
+ await findErrorPane(container, 'data-text-viewer');
+
+ expect(openFileControl(container)).toBeNull();
+ expect(container.textContent ?? '').toContain('could not be found');
+ });
+
+ test('415 (binary) keeps the handoff — a real file is on disk', async () => {
+ installDesktopBridge();
+ globalThis.fetch = mockFetchStatus(415);
+ const { container } = render(
+ <TextViewer
+ src="/api/asset-text?path=logs/blob.bin"
+ assetPath="logs/blob.bin"
+ fileName="blob.bin"
+ extension="bin"
+ />,
+ );
+ await findErrorPane(container, 'data-text-viewer');
+
+ expect(openFileControl(container)).not.toBeNull();
+ });
+
+ test('a transport failure keeps the handoff - nothing refuted the file', async () => {
+ installDesktopBridge();
+ globalThis.fetch = (() =>
+ Promise.reject(new Error('Network error'))) as typeof globalThis.fetch;
+ const { container } = render(
+ <TextViewer
+ src="/api/asset-text?path=logs/huge.csv"
+ assetPath="logs/huge.csv"
+ fileName="huge.csv"
+ extension="csv"
+ />,
+ );
+ await findErrorPane(container, 'data-text-viewer');
+
+ // The request never completed, so no status reached the hook and nothing
+ // proved the file absent. Only a confirmed 404 suppresses the affordance.
+ expect(openFileControl(container)).not.toBeNull();
+ });
+
+ test('loader-backed sources (skill bundles) never offer the handoff', async () => {
+ installDesktopBridge();
+ const { container } = render(
+ <TextViewer
+ loadText={async () => ({ ok: false, status: 413 })}
+ fileName="script.py"
+ extension="py"
+ />,
+ );
+ await findErrorPane(container, 'data-text-viewer');
+
+ // No content-dir path exists for a skill bundle file, so there is nothing
+ // the OS handoff could address.
+ expect(openFileControl(container)).toBeNull();
+ });
+
+ test('web fallback for a .mmd targets the endpoint that actually serves it', async () => {
+ // `.mmd` is deliberately absent from ASSET_EXTENSIONS: the serve allowlist
+ // does not admit it, so `/api/asset` answers 404 and only the ungated
+ // byte path returns the file. Pointing the web handoff at an endpoint that
+ // provably cannot serve the file makes it a guaranteed dead end.
+ const openSpy = vi.fn(() => null);
+ const originalOpen = window.open;
+ window.open = openSpy as unknown as typeof window.open;
+ try {
+ const { container } = render(
+ <MermaidFileViewer
+ src="/api/asset-text?path=diagrams/huge.mmd"
+ assetPath="diagrams/huge.mmd"
+ fileName="huge.mmd"
+ extension="mmd"
+ />,
+ );
+ await findErrorPane(container, 'data-mermaid-file-viewer');
+ fireEvent.click(openFileControl(container) as HTMLElement);
+ await waitFor(() => {
+ expect(openSpy).toHaveBeenCalledTimes(1);
+ });
+ const openedUrl = String(openSpy.mock.calls[0]?.[0] ?? '');
+ expect(openedUrl).toContain('/api/asset-text?');
+ expect(openedUrl).toContain(encodeURIComponent('diagrams/huge.mmd'));
+ } finally {
+ window.open = originalOpen;
+ }
+ });
+
+ test('the mermaid file viewer shares the same handoff behavior', async () => {
+ const openAsset = installDesktopBridge();
+ const { container } = render(
+ <MermaidFileViewer
+ src="/api/asset-text?path=diagrams/flow.mmd"
+ assetPath="diagrams/flow.mmd"
+ fileName="flow.mmd"
+ extension="mmd"
+ />,
+ );
+ await findErrorPane(container, 'data-mermaid-file-viewer');
+
+ expect(container.querySelector('a[href*="/api/"]')).toBeNull();
+ fireEvent.click(openFileControl(container) as HTMLElement);
+ await waitFor(() => {
+ expect(openAsset).toHaveBeenCalledWith('diagrams/flow.mmd');
+ });
+ });
+});
diff --git a/packages/app/src/components/ViewerStatusPane.tsx b/packages/app/src/components/ViewerStatusPane.tsx
index 5d90e32ba..c830493a5 100644
--- a/packages/app/src/components/ViewerStatusPane.tsx
+++ b/packages/app/src/components/ViewerStatusPane.tsx
@@ -11,6 +11,9 @@
* `data-text-viewer-extension`).
*/
import { Trans } from '@lingui/react/macro';
+import { Button } from '@/components/ui/button';
+import { dispatchAssetClick } from '@/editor/asset-dispatch';
+import type { ViewerOpenFileTarget } from './viewer-open-file';
interface ViewerStatusPaneBaseProps {
fileName: string;
@@ -40,11 +43,15 @@ export function ViewerErrorPane({
dataAttr,
extraAttrs,
message,
- openHref,
+ openFile,
}: ViewerStatusPaneBaseProps & {
message: string;
- /** "Open file" handoff target. Only the content-dir asset path has one. */
- openHref?: string;
+ /**
+ * OS-handoff target for the "Open file" affordance, or `undefined` to render
+ * no affordance at all. Resolved by `resolveViewerOpenFile` — see there for
+ * why this is a dispatch context and not an href.
+ */
+ openFile?: ViewerOpenFileTarget;
}) {
return (
<main
@@ -57,13 +64,30 @@ export function ViewerErrorPane({
<Trans>Couldn't load {fileName}</Trans>
</div>
<div className="text-muted-foreground text-xs">{message}</div>
- {openHref ? (
- <a
- href={openHref}
- className="mt-2 rounded-md border px-3 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground"
+ {openFile ? (
+ // Deliberately not an `<a href>`: a same-frame navigation here unloads
+ // the whole single-page app and strands the user on a raw API response
+ // with no way back. The dispatcher hands the file to the OS on desktop
+ // and opens a new tab on web, either way leaving the app mounted.
+ // `forceOsDelegation` skips the in-app viewer registry — an in-app
+ // viewer is precisely what just failed on this file.
+ <Button
+ variant="outline"
+ size="sm"
+ className="mt-2"
+ data-testid="viewer-open-file"
+ onClick={() => {
+ void dispatchAssetClick({
+ url: openFile.url,
+ projectRelPath: openFile.projectRelPath,
+ ext: openFile.ext,
+ title: openFile.title,
+ forceOsDelegation: true,
+ });
+ }}
>
<Trans>Open file</Trans>
- </a>
+ </Button>
) : null}
</main>
);
diff --git a/packages/app/src/components/use-viewer-text.ts b/packages/app/src/components/use-viewer-text.ts
index 403990796..ff76a5c92 100644
--- a/packages/app/src/components/use-viewer-text.ts
+++ b/packages/app/src/components/use-viewer-text.ts
@@ -32,10 +32,19 @@ export type ViewerTextSource =
* (`/api/asset-text?path=…`). Used for content-dir assets.
*/
src: string;
+ /**
+ * Project-relative path of the file `src` reads. Carried alongside the
+ * URL because the failure path has to hand the FILE to the OS: the
+ * endpoint that just refused the read is not a usable "open this
+ * elsewhere" target, and the desktop bridge addresses assets by path,
+ * not by URL.
+ */
+ assetPath: string;
loadText?: never;
}
| {
src?: never;
+ assetPath?: never;
/**
* Scope-aware loader override. The hook calls this instead of fetching
* `src` — used for skill bundle files (global refs + scripts) that live
@@ -47,9 +56,33 @@ export type ViewerTextSource =
export type FetchState =
| { status: 'loading' }
- | { status: 'error'; message: string }
+ | {
+ status: 'error';
+ message: string;
+ /**
+ * HTTP status behind the failure, when the load got far enough to have
+ * one. Render branches key the "open this elsewhere" affordance off it —
+ * a 404 means there is no file to hand anywhere. Absent for transport
+ * failures, where the file may well exist.
+ */
+ httpStatus?: number;
+ }
| { status: 'loaded'; content: string };
+/**
+ * Carries the HTTP status across the promise-chain `throw` in the `src` branch
+ * so the catch can distinguish "server said the file is gone" from "the request
+ * never completed", which the message string alone can't express.
+ */
+class ViewerTextLoadError extends Error {
+ readonly httpStatus: number;
+ constructor(message: string, httpStatus: number) {
+ super(message);
+ this.name = 'ViewerTextLoadError';
+ this.httpStatus = httpStatus;
+ }
+}
+
/**
* Network state for the file load. Kept as a single discriminated union so the
* render-branch logic stays exhaustive. `AbortController` cancels the in-flight
@@ -116,6 +149,7 @@ export function useViewerText(props: ViewerTextSource): FetchState {
setState({
status: 'error',
message: result.message ?? messageForStatusRef.current(result.status),
+ httpStatus: result.status,
});
})
.catch((err: unknown) => {
@@ -139,7 +173,7 @@ export function useViewerText(props: ViewerTextSource): FetchState {
// wording aligned with that constant if it ever changes. Unmapped
// statuses keep the code appended so unexpected failures stay
// diagnosable.
- throw new Error(messageForStatusRef.current(resp.status));
+ throw new ViewerTextLoadError(messageForStatusRef.current(resp.status), resp.status);
}
return resp.text();
})
@@ -155,7 +189,11 @@ export function useViewerText(props: ViewerTextSource): FetchState {
// unrelated "Couldn't load …" message during sidebar nav.
if (err instanceof Error && err.name === 'AbortError') return;
const message = err instanceof Error ? err.message : t`Failed to load file`;
- setState({ status: 'error', message });
+ setState({
+ status: 'error',
+ message,
+ httpStatus: err instanceof ViewerTextLoadError ? err.httpStatus : undefined,
+ });
});
return () => {
cancelled = true;
diff --git a/packages/app/src/components/viewer-open-file.ts b/packages/app/src/components/viewer-open-file.ts
new file mode 100644
index 000000000..1528f0af3
--- /dev/null
+++ b/packages/app/src/components/viewer-open-file.ts
@@ -0,0 +1,71 @@
+/**
+ * Decides whether a failed read-only viewer should offer to hand the file to
+ * another application, and builds the dispatch context when it should.
+ *
+ * Two things this exists to keep straight, both of which the naive "link to the
+ * URL we just fetched" shape got wrong:
+ *
+ * - The handoff target is the FILE, addressed by its project-relative path,
+ * not the `/api/asset-text` URL whose failure produced the pane. That URL
+ * answers the same way a second time.
+ * - A 404 is the one status that CONFIRMS there is nothing to hand over, so
+ * it is the one that suppresses the affordance: the caller gets `undefined`
+ * and renders no control. No other failure refutes the file's existence -
+ * too large and binary both prove it exists, and a transport failure says
+ * nothing either way - so those keep the affordance rather than hide a
+ * working handoff behind an unprovable guess.
+ */
+
+import { ASSET_EXTENSIONS, toDesktopAssetHref } from '@inkeep/open-knowledge-core';
+
+/** Everything `dispatchAssetClick` needs, resolved at the error-pane boundary. */
+export interface ViewerOpenFileTarget {
+ /** Project-relative path — what the desktop bridge resolves and contains. */
+ readonly projectRelPath: string;
+ /** Lowercased, dot-stripped extension. */
+ readonly ext: string;
+ /** Basename, for menus and logs. */
+ readonly title: string;
+ /** Web fallback target: the byte-serving asset endpoint, opened in a new tab. */
+ readonly url: string;
+}
+
+interface ResolveViewerOpenFileArgs {
+ /** Absent for loader-backed sources (skill bundles) that have no content-dir path. */
+ readonly assetPath: string | undefined;
+ readonly fileName: string;
+ readonly extension: string;
+ readonly httpStatus: number | undefined;
+}
+
+export function resolveViewerOpenFile({
+ assetPath,
+ fileName,
+ extension,
+ httpStatus,
+}: ResolveViewerOpenFileArgs): ViewerOpenFileTarget | undefined {
+ if (!assetPath) return undefined;
+ if (httpStatus === 404) return undefined;
+ const ext = extension.toLowerCase();
+ // Only the web fallback reads the URL: the dispatcher's Electron branch hands
+ // `projectRelPath` to the bridge and returns without touching it. The origin
+ // wrap is therefore inert here - it no-ops precisely when `window.okDesktop`
+ // is absent, which is the only case that gets this far - and is kept so the
+ // field stays a complete, self-contained target if a future dispatch path
+ // does open it.
+ //
+ // `/api/asset` serves bytes uncapped, which is what the common too-large
+ // failure needs, but its serve allowlist admits only `ASSET_EXTENSIONS`. The
+ // few types the viewer reaches through the ungated byte path instead
+ // (`.mmd`, `.canvas`, ...) are absent from it and would answer 404 there, so
+ // they get the endpoint that does serve them. That one is size-capped, so
+ // this only recovers failures that were not about size - but an endpoint
+ // that provably cannot serve the file is never the better target.
+ const endpoint = ASSET_EXTENSIONS.has(ext) ? '/api/asset' : '/api/asset-text';
+ return {
+ projectRelPath: assetPath,
+ ext,
+ title: fileName,
+ url: toDesktopAssetHref(`${endpoint}?path=${encodeURIComponent(assetPath)}`),
+ };
+}
diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.ts
index dfd95ef49..d7a845280 100644
--- a/packages/core/src/bridge/bind-frontmatter-doc.ts
+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts
@@ -1,4 +1,3 @@
-
import type * as Y from 'yjs';
import type { Err, Ok, Result } from '../config/result.ts';
import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';
diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.ts
index 8bfdb40cd..005627195 100644
--- a/packages/core/src/bridge/bridge-invariant.ts
+++ b/packages/core/src/bridge/bridge-invariant.ts
@@ -1,4 +1,3 @@
-
import { fnv1aDigest } from './hash-util.ts';
export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';
diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.ts
index 2a597ec3d..f4cc8a286 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,4 +1,3 @@
-
import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';
export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index c18c086d5..8890f6739 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,4 +1,3 @@
-
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
const LEADING_BOUNDARY_RE = /^(?:\r?\n)+/;
diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.ts
index 463e89595..9d9c244b0 100644
--- a/packages/core/src/bridge/growth-detect.ts
+++ b/packages/core/src/bridge/growth-detect.ts
@@ -1,4 +1,3 @@
-
const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;
export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;
diff --git a/packages/core/src/bridge/intraline-predicate.ts b/packages/core/src/bridge/intraline-predicate.ts
index 0939885bb..c43fdd7e7 100644
--- a/packages/core/src/bridge/intraline-predicate.ts
+++ b/packages/core/src/bridge/intraline-predicate.ts
@@ -1,4 +1,3 @@
-
export function rawLineCounts(doc: string): Map<string, number> {
const counts = new Map<string, number>();
for (const line of doc.split('\n')) {
diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.ts
index c0dc65705..251560a35 100644
--- a/packages/core/src/bridge/merge-three-way.ts
+++ b/packages/core/src/bridge/merge-three-way.ts
@@ -65,7 +65,6 @@ export function tryLineLevelCombine(
return { clean: true, merged };
}
-
export type BridgeMergeContentLossSide = 'user' | 'agent';
export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';
diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.ts
index d35f6b455..da41900cd 100644
--- a/packages/core/src/bridge/normalize.ts
+++ b/packages/core/src/bridge/normalize.ts
@@ -1,4 +1,3 @@
-
const COMMONMARK_ESCAPE_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~])/g;
const TABLE_ALIGN_ROW_RE = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/;
diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.ts
index 0be5203e4..754dc5cc2 100644
--- a/packages/core/src/bridge/pm-structural-equivalence.ts
+++ b/packages/core/src/bridge/pm-structural-equivalence.ts
@@ -32,7 +32,6 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };
const BR_LITERAL_RE = /^<br\s*\/?>$/i;
-
interface DegradeEntry {
readonly label: string;
readonly severity: ToleranceClassSeverity;
@@ -128,7 +127,6 @@ export interface ComparePmStructuralOptions {
ignoreAttrs?: (attrKey: string) => boolean;
}
-
/** Rebuild a node with `fn` applied to each child; identity when childless.
* Shared by the degrade canonicalizers so none re-implements the walk. */
function mapChildren(
@@ -250,7 +248,6 @@ function applyDegrades(tree: PmStructuralNode): {
return { normalized: current, fired };
}
-
export function comparePmStructural(
expected: PmStructuralNode,
actual: PmStructuralNode,
diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.ts
index dca644141..af20de1e2 100644
--- a/packages/core/src/bridge/subsequence.ts
+++ b/packages/core/src/bridge/subsequence.ts
@@ -1,4 +1,3 @@
-
/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):
* insertions in `haystack` are free; any dropped or substituted `needle` byte
* fails. */
diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.ts
index a363dfd54..83d47404a 100644
--- a/packages/core/src/markdown/callout-transformer.ts
+++ b/packages/core/src/markdown/callout-transformer.ts
@@ -1,4 +1,3 @@
-
import type { Blockquote, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.ts
index 4499dbc92..9807a7e82 100644
--- a/packages/core/src/markdown/code-fence.ts
+++ b/packages/core/src/markdown/code-fence.ts
@@ -1,4 +1,3 @@
-
export function selectFenceChar(info: string): '`' | '~' {
return info.includes('`') ? '~' : '`';
}
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index 34704165b..7415c474a 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.ts
index b6299a948..ece5c02a1 100644
--- a/packages/core/src/markdown/dedent-block-jsx-close.ts
+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts
@@ -1,4 +1,3 @@
-
import { findFencedRegions, isInsideFence } from './fence-regions.ts';
const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;
diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.ts
index acd398aa6..54774764a 100644
--- a/packages/core/src/markdown/details-accordion-promoter.ts
+++ b/packages/core/src/markdown/details-accordion-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.ts
index ba9b56384..43ecdc709 100644
--- a/packages/core/src/markdown/div-align-promoter.ts
+++ b/packages/core/src/markdown/div-align-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.ts
index 4513da9bb..6d3f3643e 100644
--- a/packages/core/src/markdown/fence-regions.ts
+++ b/packages/core/src/markdown/fence-regions.ts
@@ -1,4 +1,3 @@
-
const FENCE_RE = /^(`{3,}|~{3,})/gm;
export function findFencedRegions(src: string): Array<[number, number]> {
diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.ts
index 6931623c7..00f5771ee 100644
--- a/packages/core/src/markdown/fixtures/index.ts
+++ b/packages/core/src/markdown/fixtures/index.ts
@@ -1,4 +1,3 @@
-
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -9,7 +8,6 @@ function fixturePath(...segments: string[]): string {
return resolve(FIXTURES_DIR, ...segments);
}
-
interface GfmExample {
section: string;
markdown: string;
@@ -19,7 +17,6 @@ export function loadGfmExamples(): GfmExample[] {
return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];
}
-
interface MdxCrashEntry {
id: string;
input: string;
@@ -71,7 +68,6 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {
) as LargeEmbedFixture[];
}
-
export function loadPrd6955Before(): string {
return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');
}
@@ -80,7 +76,6 @@ export function loadPrd6955CorruptedTriplicated(): string {
return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');
}
-
export interface NgPinnedCase {
id: string;
name: string;
@@ -97,7 +92,6 @@ export function loadNgPinnedCases(): NgPinnedCase[] {
) as NgPinnedCase[];
}
-
export function loadLargeRealistic(): string {
return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');
}
diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.ts
index daa3ef82b..8b1eb8519 100644
--- a/packages/core/src/markdown/fixtures/perf/generate.ts
+++ b/packages/core/src/markdown/fixtures/perf/generate.ts
@@ -1,4 +1,3 @@
-
import { writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -11,7 +10,6 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;
const SEED = 0xf1de1117;
-
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
@@ -38,7 +36,6 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {
return items[items.length - 1][0];
}
-
const WORDS = [
'lorem',
'ipsum',
@@ -156,7 +153,6 @@ function mdxBlock(rand: () => number): string {
return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;
}
-
type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';
const MIX: readonly [BlockKind, number][] = [
@@ -195,7 +191,6 @@ function generateDocument(blockCount: number, seed: number): string {
return `${blocks.join('\n\n')}\n`;
}
-
function main(): void {
for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {
const doc = generateDocument(count, SEED);
diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.ts
index 32c055c5b..420dc0fe5 100644
--- a/packages/core/src/markdown/guard-flanking-matrix.ts
+++ b/packages/core/src/markdown/guard-flanking-matrix.ts
@@ -7,7 +7,6 @@ import {
import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';
import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';
-
export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;
export type FlankClass = 'whitespace' | 'punctuation' | 'other';
diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.ts
index 283913255..2653473da 100644
--- a/packages/core/src/markdown/handler-shadow-audit.ts
+++ b/packages/core/src/markdown/handler-shadow-audit.ts
@@ -1,4 +1,3 @@
-
export interface HandlerShadowWitness {
input: string;
expect: 'byte' | 'byte-and-reparse-type';
diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.ts
index 5d1000cc4..da0a81d23 100644
--- a/packages/core/src/markdown/highlight-promoter.ts
+++ b/packages/core/src/markdown/highlight-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.ts
index 9681c0056..787315157 100644
--- a/packages/core/src/markdown/html-to-mdast.ts
+++ b/packages/core/src/markdown/html-to-mdast.ts
@@ -1,4 +1,3 @@
-
import type { Element as HastElement, Root as HastRoot } from 'hast';
import type { List, Nodes as MdastNodes, Root as MdastRoot } from 'mdast';
import rehypeParse from 'rehype-parse';
@@ -129,8 +128,7 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRo
throw new HtmlPayloadTooLargeError(html.length, maxBytes);
}
- const processor = unified()
- .use(rehypeParse, { fragment: true });
+ const processor = unified().use(rehypeParse, { fragment: true });
for (const plugin of cleanupPlugins) {
processor.use(plugin);
diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.ts
index 994eb6917..706fa9afb 100644
--- a/packages/core/src/markdown/image-promoter.ts
+++ b/packages/core/src/markdown/image-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Image, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.ts
index 25bc43422..f49f4b64e 100644
--- a/packages/core/src/markdown/index.ts
+++ b/packages/core/src/markdown/index.ts
@@ -1,4 +1,3 @@
-
import {
type FromProseMirrorOptions,
fromPmMark,
@@ -206,7 +205,6 @@ export class MarkdownManager {
}
}
-
const registry = createRegistry();
function destructureAttrs(
@@ -255,7 +253,6 @@ function destructureAttrs(
return result;
}
-
function hasDirtyDescendant(node: PmNode): boolean {
let found = false;
node.descendants((child) => {
@@ -275,7 +272,6 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChec
return freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;
}
-
function isEmptyMdastParagraph(node: MdastNodes): boolean {
if (node.type !== 'paragraph') return false;
const children = node.children ?? [];
@@ -344,7 +340,6 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {
return out;
}
-
import {
AUDIO_EXTENSIONS,
FILE_ATTACHMENT_EXTENSIONS,
@@ -597,7 +592,6 @@ function buildMdastToPmHandlers(
}));
}
-
if (m.emphasis) {
handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({
sourceDelimiter: node.data?.sourceDelimiter ?? '*',
@@ -678,7 +672,6 @@ function buildMdastToPmHandlers(
}));
}
-
if (m.link) {
const sourceLiteralMark = m.sourceLiteral;
handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {
@@ -957,7 +950,6 @@ function buildMdastToPmHandlers(
};
}
-
const blockUnknownHandler = (node: {
type: string;
position?: { start: { offset: number }; end: { offset: number } };
@@ -1083,7 +1075,6 @@ function buildMdastToPmHandlers(
return handlers as RemarkProseMirrorOptions['handlers'];
}
-
function buildPmToMdastHandlers(
schema: Schema,
freshness: FreshnessCheckerHolder,
diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.ts
index b79e9aef7..fa0be9e86 100644
--- a/packages/core/src/markdown/lint/applies-to.ts
+++ b/packages/core/src/markdown/lint/applies-to.ts
@@ -1,4 +1,3 @@
-
import picomatch from 'picomatch';
import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';
diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.ts
index 94b34dee1..312c9c74b 100644
--- a/packages/core/src/markdown/lint/config-files.ts
+++ b/packages/core/src/markdown/lint/config-files.ts
@@ -1,4 +1,3 @@
-
const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set([
'.markdownlint.json',
'.markdownlint.jsonc',
diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.ts
index a1dab6426..c94bfce20 100644
--- a/packages/core/src/markdown/lint/config-schemas.ts
+++ b/packages/core/src/markdown/lint/config-schemas.ts
@@ -38,7 +38,6 @@ const fullPluginShape = Object.fromEntries(
LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),
) as z.ZodRawShape;
-
export const LinterConfigSchema = z.object({
enabled: z.boolean(),
plugins: z.object(fullPluginShape),
diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.ts
index a51f2ffb0..d48eea5e4 100644
--- a/packages/core/src/markdown/lint/default-config.ts
+++ b/packages/core/src/markdown/lint/default-config.ts
@@ -6,7 +6,6 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSetting
MD013: false,
};
-
export function resolveMarkdownlintConfig(
rules: Record<string, MarkdownlintRuleSetting> | undefined,
): Configuration {
diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
index 9c9542661..ef478e268 100644
--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
@@ -1,4 +1,3 @@
-
import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';
export interface FrontmatterFieldConstraint {
diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.ts
index 997f71794..3871ccada 100644
--- a/packages/core/src/markdown/lint/frontmatter-validate.ts
+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts
@@ -1,4 +1,3 @@
-
import Ajv, { type ValidateFunction } from 'ajv';
import Ajv2019 from 'ajv/dist/2019.js';
import Ajv2020 from 'ajv/dist/2020.js';
diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.ts
index 48d260ed6..00d08265a 100644
--- a/packages/core/src/markdown/lint/index.ts
+++ b/packages/core/src/markdown/lint/index.ts
@@ -1,4 +1,3 @@
-
import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';
import type { LintDiagnostic } from './types.ts';
diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.ts
index be5871ed9..5e832aa19 100644
--- a/packages/core/src/markdown/lint/plugins.ts
+++ b/packages/core/src/markdown/lint/plugins.ts
@@ -1,4 +1,3 @@
-
import { z } from 'zod';
import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';
import {
@@ -14,7 +13,6 @@ import {
type MarkdownlintSlice,
} from './types.ts';
-
const MarkdownlintRuleSettingSchema = z.union([
z.boolean(),
z.enum(MARKDOWNLINT_RULE_SEVERITIES),
diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.ts
index 772183427..da6c477e9 100644
--- a/packages/core/src/markdown/lint/types.ts
+++ b/packages/core/src/markdown/lint/types.ts
@@ -1,4 +1,3 @@
-
export const LINT_PLUGIN_IDS = ['markdownlint', 'frontmatter'] as const;
export type LintPluginId = (typeof LINT_PLUGIN_IDS)[number];
@@ -70,7 +69,6 @@ export interface FrontmatterSlice {
schemas: ResolvedFrontmatterSchemaEntry[];
}
-
interface RuleOptionSpecBase {
key: string;
description: string;
diff --git a/packages/core/src/markdown/lint/validation-counts.ts b/packages/core/src/markdown/lint/validation-counts.ts
index 437cc539a..98238656e 100644
--- a/packages/core/src/markdown/lint/validation-counts.ts
+++ b/packages/core/src/markdown/lint/validation-counts.ts
@@ -1,4 +1,3 @@
-
export interface ValidationSourceCounts {
errorCount: number;
warningCount: number;
diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.ts
index bd79424c7..a5b511f25 100644
--- a/packages/core/src/markdown/math-promoter.ts
+++ b/packages/core/src/markdown/math-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Code, Root } from 'mdast';
import type { Math as MdastMath } from 'mdast-util-math';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.ts
index 00fbc0035..ed89371d0 100644
--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts
+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, ElementContent, Properties } from 'hast';
import type { FootnoteDefinition, FootnoteReference } from 'mdast';
import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.ts
index df788a80d..8ce2b2492 100644
--- a/packages/core/src/markdown/mdast-to-html.ts
+++ b/packages/core/src/markdown/mdast-to-html.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root as HastRoot, Text as HastText } from 'hast';
import type { Root as MdastRoot, Text as MdastText } from 'mdast';
import type { Handler } from 'mdast-util-to-hast';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index fa3cfcd86..bfd7e3109 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.ts
index 17ed2b829..1a897fca8 100644
--- a/packages/core/src/markdown/mermaid-promoter.ts
+++ b/packages/core/src/markdown/mermaid-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Code, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.ts
index 7e4a9a48b..9864b3b60 100644
--- a/packages/core/src/markdown/parse-with-fallback.ts
+++ b/packages/core/src/markdown/parse-with-fallback.ts
@@ -168,7 +168,6 @@ export function parseRecursive(
}
}
-
interface VFilePlace {
offset?: number;
start?: { offset?: number };
@@ -187,7 +186,6 @@ function extractErrorOffset(err: unknown): number | undefined {
return undefined;
}
-
interface Region {
start: number;
end: number;
@@ -211,7 +209,6 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {
return null;
}
-
export interface TagEvent {
kind: 'open' | 'close' | 'self-close';
name: string;
@@ -358,7 +355,6 @@ function findFallbackRegion(src: string, errorOffset: number): Region {
return { start: blockStart, end: blockEnd };
}
-
interface SourceBlock {
src: string;
start: number;
@@ -456,7 +452,6 @@ function tryPerBlockFallback(
};
}
-
function wholeDocRawText(source: string): JSONContent {
return {
type: 'doc',
diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.ts
index 43d420187..e6ab4fd57 100644
--- a/packages/core/src/markdown/parser-drop-closure.ts
+++ b/packages/core/src/markdown/parser-drop-closure.ts
@@ -1,4 +1,3 @@
-
export type DroppedTokenAdjudication =
| {
kind: 'format-dof-axis';
diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.ts
index c21e1fdf1..4426ab46e 100644
--- a/packages/core/src/markdown/pipeline.ts
+++ b/packages/core/src/markdown/pipeline.ts
@@ -1,4 +1,3 @@
-
import {
type FromProseMirrorOptions,
fromProseMirror,
diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.ts
index ccf06e94d..91cdf658f 100644
--- a/packages/core/src/markdown/position-aware-join.ts
+++ b/packages/core/src/markdown/position-aware-join.ts
@@ -1,4 +1,3 @@
-
import type { Join } from 'mdast-util-to-markdown';
import type { Position } from 'unist';
import { isBlankLineParagraph } from './zero-emission-blocks.ts';
diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.ts
index e5b4c9eba..0f399d34c 100644
--- a/packages/core/src/markdown/position-slice.ts
+++ b/packages/core/src/markdown/position-slice.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Root } from 'mdast';
import { visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
@@ -477,8 +476,7 @@ export function applyPositionSliceToNode(
const first = source[startOff];
if (first !== '[' && first !== '<' && !node.title) {
node.data.sourceStyle = 'gfm-autolink';
- }
- else if (first === '[') {
+ } else if (first === '[') {
const slice = source.slice(startOff, endOff);
const closeBracketIdx = slice.lastIndexOf('](');
if (closeBracketIdx !== -1) {
diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
index ca225ce9b..db10fa54b 100644
--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, Root, Text } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
index 3a2524a9a..34068d103 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
index 2279a0189..93151d43b 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
index a0f467c42..188f02d83 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
index 4e8542a21..4ba2c3418 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
index a3c96b24a..1a74b1272 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
index e95cf43d6..de35e7b79 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
index ffdb4d5b5..b4be1b2ea 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
index e2a96d1a7..3c8d88b7c 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.ts
index 0389575ac..cf2c9da8e 100644
--- a/packages/core/src/markdown/resolve-image-url.ts
+++ b/packages/core/src/markdown/resolve-image-url.ts
@@ -1,4 +1,3 @@
-
import { isRelativeUrl } from './safe-url.ts';
function isDevDiagnosticContext(): boolean {
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 8be632ba4..4d3250d3a 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,4 +1,3 @@
-
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/core/src/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
index 96304e7a5..0dd54070e 100644
--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts
+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
@@ -1,4 +1,3 @@
-
import type { JSONContent } from '@tiptap/core';
import type { Nodes } from 'mdast';
import { expect } from 'vitest';
diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.ts
index 542204403..46cc6a074 100644
--- a/packages/core/src/markdown/serialize-helpers.ts
+++ b/packages/core/src/markdown/serialize-helpers.ts
@@ -1,4 +1,3 @@
-
import type { Node as PmNode } from '@tiptap/pm/model';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { PropDef, SerializeContext } from '../registry/types.ts';
diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.ts
index 8c08b7a04..b012a5aff 100644
--- a/packages/core/src/markdown/single-dollar-math-promoter.ts
+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts
@@ -1,4 +1,3 @@
-
import type { PhrasingContent, Root, Text } from 'mdast';
import type { InlineMath } from 'mdast-util-math';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.ts
index 20ce25dbe..a41534404 100644
--- a/packages/core/src/markdown/to-markdown-handlers.ts
+++ b/packages/core/src/markdown/to-markdown-handlers.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parents } from 'mdast';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { Handle, Info, State } from 'mdast-util-to-markdown';
diff --git a/packages/core/src/markdown/underline-promoter.ts b/packages/core/src/markdown/underline-promoter.ts
index 6e6d73400..0f1b0f27d 100644
--- a/packages/core/src/markdown/underline-promoter.ts
+++ b/packages/core/src/markdown/underline-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, Root } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.ts
index 932d7d2a8..1a082bda7 100644
--- a/packages/core/src/markdown/unknown-mdast-guard.ts
+++ b/packages/core/src/markdown/unknown-mdast-guard.ts
@@ -1,4 +1,3 @@
-
import type { Root as MdastRoot } from 'mdast';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.ts
index ac9f5239b..d578476a7 100644
--- a/packages/core/src/markdown/whitespace-char-ref.ts
+++ b/packages/core/src/markdown/whitespace-char-ref.ts
@@ -1,4 +1,3 @@
-
const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([
[0x20, ' '],
[0x09, '\t'],
diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.ts
index afd9936fe..6dad26200 100644
--- a/packages/core/src/markdown/wiki-link-micromark.ts
+++ b/packages/core/src/markdown/wiki-link-micromark.ts
@@ -17,7 +17,6 @@ declare module 'micromark-util-types' {
}
}
-
const CODE_BANG = 33; // !
const CODE_LBRACKET = 91; // [
const CODE_RBRACKET = 93; // ]
@@ -261,7 +260,6 @@ export function wikiLinkSyntax(): Extension {
};
}
-
function enterWikiLink(this: CompileContext, token: Token) {
this.enter(
{
@@ -387,7 +385,6 @@ export const wikiLinkToMarkdown: {
unsafe: [{ character: '[', inConstruct: ['phrasing'] }],
};
-
const MICROMARK_EXT = wikiLinkSyntax();
export function remarkWikiLink(this: Processor) {
diff --git a/packages/desktop/src/main/asset-safety-net.ts b/packages/desktop/src/main/asset-safety-net.ts
index 5f3021da0..0cc7734f9 100644
--- a/packages/desktop/src/main/asset-safety-net.ts
+++ b/packages/desktop/src/main/asset-safety-net.ts
@@ -22,6 +22,11 @@
* canonical defense; Standard Notes + AFFiNE + VSCode all implement
* both.
*
+ * `will-navigate` additionally REFUSES same-origin top-level navigations into
+ * `/api/*` (see `matchInAppApiNavigation`). Those are never legitimate SPA
+ * navigation and unloading the renderer for a raw API response leaves a window
+ * with no UI and no way back.
+ *
* Pure-ish: takes a narrow `WebContentsLike` so tests can exercise the
* dispatch logic without standing up Electron. `openAssetSafely` is
* injected — the real wiring in `index.ts` passes the main-process gate
@@ -163,6 +168,35 @@ export function matchAssetUrl(url: string, editorOrigin: string): string | null
return path;
}
+/**
+ * True when `url` is a same-origin (renderer or editor/API) navigation into the
+ * HTTP API surface. Such a URL is never a legitimate top-level navigation: the
+ * app shell is the bundle entry, in-app routes live in the hash, and asset URLs
+ * are claimed earlier by `matchAssetUrl`. What DOES produce one is a stray
+ * `<a href="/api/…">` in renderer markup — and letting it through replaces the
+ * whole single-page app with a raw API response, leaving a chrome-only window
+ * the user cannot navigate back from.
+ *
+ * Deliberately narrow: only the `/api` path prefix, only on origins we already
+ * treat as in-app. The bundle entry, `/@vite/*` HMR endpoints, hash routes, and
+ * every cross-origin URL fall through untouched.
+ *
+ * Exported for test coverage of the matching logic without mounting the net.
+ */
+export function matchInAppApiNavigation(
+ url: string,
+ inAppOrigins: readonly (string | null | undefined)[],
+): boolean {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return false;
+ }
+ if (!inAppOrigins.includes(parsed.origin)) return false;
+ return parsed.pathname === '/api' || parsed.pathname.startsWith('/api/');
+}
+
/**
* Origin of `url`, or null if absent/unparseable. Used to read the renderer's
* own origin from `webContents.getURL()`.
@@ -296,6 +330,19 @@ export function attachAssetSafetyNet(
});
return;
}
+ // A top-level navigate into the HTTP API would unload the app shell for a
+ // raw API response — refuse before the same-origin allowance below, which
+ // exists for the app bundle and hash routes, not for API endpoints.
+ const rendererOrigin = safeOrigin(webContents.getURL?.());
+ if (matchInAppApiNavigation(url, [deps.editorOrigin, rendererOrigin])) {
+ event.preventDefault();
+ log({
+ level: 'warn',
+ message: 'refused top-level navigation into the HTTP API',
+ data: { url },
+ });
+ return;
+ }
// Same-origin navigation (Vite HMR full-reload, an in-app link that
// somehow turned into a top-level navigate, the editor itself
// reloading) — leave Electron's default handling alone.
@@ -310,10 +357,7 @@ export function attachAssetSafetyNet(
// `matchInAppRoute`). Leaving Electron's default handling keeps a same-page
// navigation in-app rather than leaking a `localhost:5173/#/doc` URL to the
// OS browser via the `openExternal` fall-through below.
- if (
- parsed.origin === deps.editorOrigin ||
- parsed.origin === safeOrigin(webContents.getURL?.())
- ) {
+ if (parsed.origin === deps.editorOrigin || parsed.origin === rendererOrigin) {
return;
}
// Cross-origin navigation that would otherwise replace the editor's
diff --git a/packages/desktop/tests/main/asset-safety-net.test.ts b/packages/desktop/tests/main/asset-safety-net.test.ts
index 8bd726e86..d338d8e12 100644
--- a/packages/desktop/tests/main/asset-safety-net.test.ts
+++ b/packages/desktop/tests/main/asset-safety-net.test.ts
@@ -9,6 +9,7 @@ import { describe, expect, test, vi } from 'vitest';
import {
attachAssetSafetyNet,
matchAssetUrl,
+ matchInAppApiNavigation,
matchInAppRoute,
} from '../../src/main/asset-safety-net.ts';
@@ -103,6 +104,70 @@ describe('matchAssetUrl', () => {
});
});
+describe('matchInAppApiNavigation', () => {
+ const IN_APP = [ORIGIN, 'http://localhost:8765'];
+
+ test('same-origin /api/* path → true', () => {
+ expect(
+ matchInAppApiNavigation('http://localhost:5173/api/asset-text?path=logs/huge.csv', IN_APP),
+ ).toBe(true);
+ expect(matchInAppApiNavigation('http://localhost:8765/api/asset?path=a.pdf', IN_APP)).toBe(
+ true,
+ );
+ });
+
+ test('bare /api → true (no trailing segment needed)', () => {
+ expect(matchInAppApiNavigation('http://localhost:5173/api', IN_APP)).toBe(true);
+ });
+
+ test('app bundle entry and root → false (reload path must stay open)', () => {
+ expect(matchInAppApiNavigation('http://localhost:5173/index.html', IN_APP)).toBe(false);
+ expect(matchInAppApiNavigation('http://localhost:5173/', IN_APP)).toBe(false);
+ });
+
+ test('Vite dev endpoints → false', () => {
+ expect(matchInAppApiNavigation('http://localhost:5173/@vite/client', IN_APP)).toBe(false);
+ expect(matchInAppApiNavigation('http://localhost:5173/@react-refresh', IN_APP)).toBe(false);
+ });
+
+ test('in-app hash route → false', () => {
+ expect(matchInAppApiNavigation('http://localhost:5173/#/people/ray', IN_APP)).toBe(false);
+ });
+
+ test('a path that merely starts with the letters "api" → false', () => {
+ expect(matchInAppApiNavigation('http://localhost:5173/apiary/notes.md', IN_APP)).toBe(false);
+ });
+
+ test('cross-origin /api/* → false (openExternal owns that branch)', () => {
+ expect(matchInAppApiNavigation('https://example.com/api/thing', IN_APP)).toBe(false);
+ });
+
+ test('null / undefined in-app origins are ignored, not matched', () => {
+ expect(matchInAppApiNavigation('http://localhost:5173/api/asset', [null, undefined])).toBe(
+ false,
+ );
+ });
+
+ test('packaged renderer: a root-relative /api href resolves to file:///api/... and matches', () => {
+ // In a packaged build the renderer is a `file://` page, so `<a href="/api/…">`
+ // resolves to `file:///api/…` and both origins are the opaque string 'null'.
+ // That is the production shape of the blank-window navigation.
+ const packagedRendererOrigin = new URL(
+ 'file:///Applications/OK.app/Contents/Resources/app/dist/index.html',
+ ).origin;
+ expect(
+ matchInAppApiNavigation('file:///api/asset-text?path=logs/huge.csv', [
+ 'http://127.0.0.1:8765',
+ packagedRendererOrigin,
+ ]),
+ ).toBe(true);
+ });
+
+ test('bogus URL → false (no throw)', () => {
+ expect(matchInAppApiNavigation('not a url', IN_APP)).toBe(false);
+ });
+});
+
describe('matchInAppRoute', () => {
test('same-renderer-origin hash route → returns the hash', () => {
expect(
@@ -408,6 +473,178 @@ describe('attachAssetSafetyNet — will-navigate', () => {
expect(openExternal).not.toHaveBeenCalled();
});
+ test('same-origin /api/* navigation → refused, app shell stays mounted', async () => {
+ // A stray `<a href="/api/asset-text?…">` would otherwise replace the whole
+ // renderer with the raw API response, leaving a window with no UI.
+ const openAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ const openExternal = vi.fn(noopOpenExternal);
+ const logEvents: unknown[] = [];
+
+ let installedHandler: ((event: { preventDefault: () => void }, url: string) => void) | null =
+ null;
+ const webContents = {
+ setWindowOpenHandler: () => {},
+ on(
+ event: 'will-navigate',
+ handler: (event: { preventDefault: () => void }, url: string) => void,
+ ) {
+ if (event === 'will-navigate') installedHandler = handler;
+ },
+ getURL: () => 'http://localhost:5173/#/home',
+ };
+
+ attachAssetSafetyNet(webContents, {
+ openAsset,
+ openExternal,
+ editorOrigin: 'http://localhost:8765',
+ log: (evt) => logEvents.push(evt),
+ });
+
+ const preventDefault = vi.fn(() => {});
+ installedHandler?.(
+ { preventDefault },
+ 'http://localhost:5173/api/asset-text?path=logs/huge.csv',
+ );
+ expect(preventDefault).toHaveBeenCalledTimes(1);
+ await Promise.resolve();
+ // Refused outright: not delegated to the OS browser, not opened as an asset.
+ expect(openExternal).not.toHaveBeenCalled();
+ expect(openAsset).not.toHaveBeenCalled();
+ expect(logEvents).toHaveLength(1);
+ expect(logEvents[0]).toMatchObject({
+ level: 'warn',
+ message: 'refused top-level navigation into the HTTP API',
+ });
+ });
+
+ test('editor-origin /api/* navigation → also refused', async () => {
+ const openAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ const openExternal = vi.fn(noopOpenExternal);
+
+ let installedHandler: ((event: { preventDefault: () => void }, url: string) => void) | null =
+ null;
+ const webContents = {
+ setWindowOpenHandler: () => {},
+ on(
+ event: 'will-navigate',
+ handler: (event: { preventDefault: () => void }, url: string) => void,
+ ) {
+ if (event === 'will-navigate') installedHandler = handler;
+ },
+ };
+
+ attachAssetSafetyNet(webContents, { openAsset, openExternal, editorOrigin: ORIGIN });
+
+ const preventDefault = vi.fn(() => {});
+ installedHandler?.({ preventDefault }, 'http://localhost:5173/api/asset?path=notes/a.zip');
+ expect(preventDefault).toHaveBeenCalledTimes(1);
+ await Promise.resolve();
+ expect(openExternal).not.toHaveBeenCalled();
+ expect(openAsset).not.toHaveBeenCalled();
+ });
+
+ test('packaged file:// renderer: /api/* navigation → refused', async () => {
+ // The production shape of the reported blank window: a root-relative
+ // `/api/…` href on a `file://` page resolves to `file:///api/…`, which does
+ // not exist, so the window ends up showing nothing at all.
+ const openAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ const openExternal = vi.fn(noopOpenExternal);
+
+ let installedHandler: ((event: { preventDefault: () => void }, url: string) => void) | null =
+ null;
+ const webContents = {
+ setWindowOpenHandler: () => {},
+ on(
+ event: 'will-navigate',
+ handler: (event: { preventDefault: () => void }, url: string) => void,
+ ) {
+ if (event === 'will-navigate') installedHandler = handler;
+ },
+ getURL: () => 'file:///Applications/OK.app/Contents/Resources/app/dist/index.html',
+ };
+
+ attachAssetSafetyNet(webContents, {
+ openAsset,
+ openExternal,
+ editorOrigin: 'http://127.0.0.1:8765',
+ });
+
+ const preventDefault = vi.fn(() => {});
+ installedHandler?.({ preventDefault }, 'file:///api/asset-text?path=logs/huge.csv');
+ expect(preventDefault).toHaveBeenCalledTimes(1);
+ await Promise.resolve();
+ expect(openExternal).not.toHaveBeenCalled();
+ expect(openAsset).not.toHaveBeenCalled();
+ });
+
+ test('the API refusal does not claim the bundle entry or an in-app hash route', async () => {
+ // Regression fence for the dev reload flow: `/index.html` (Vite HMR full
+ // reload) and `#/…` routes must still fall through to Electron's default
+ // handling after the API branch was added.
+ const openAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ const openExternal = vi.fn(noopOpenExternal);
+
+ let installedHandler: ((event: { preventDefault: () => void }, url: string) => void) | null =
+ null;
+ const webContents = {
+ setWindowOpenHandler: () => {},
+ on(
+ event: 'will-navigate',
+ handler: (event: { preventDefault: () => void }, url: string) => void,
+ ) {
+ if (event === 'will-navigate') installedHandler = handler;
+ },
+ getURL: () => 'http://localhost:5173/#/home',
+ };
+
+ attachAssetSafetyNet(webContents, {
+ openAsset,
+ openExternal,
+ editorOrigin: 'http://localhost:8765',
+ });
+
+ for (const url of [
+ 'http://localhost:5173/index.html',
+ 'http://localhost:5173/',
+ 'http://localhost:5173/@vite/client',
+ 'http://localhost:5173/#/people/ray-zaragoza',
+ ]) {
+ const preventDefault = vi.fn(() => {});
+ installedHandler?.({ preventDefault }, url);
+ expect(preventDefault, `should not refuse ${url}`).not.toHaveBeenCalled();
+ }
+ await Promise.resolve();
+ expect(openExternal).not.toHaveBeenCalled();
+ expect(openAsset).not.toHaveBeenCalled();
+ });
+
+ test('asset URL still wins over the API refusal', async () => {
+ // The asset branch runs first; a served asset path must keep delegating to
+ // openAsset rather than being swallowed by the new refusal.
+ const openAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ const openExternal = vi.fn(noopOpenExternal);
+
+ let installedHandler: ((event: { preventDefault: () => void }, url: string) => void) | null =
+ null;
+ const webContents = {
+ setWindowOpenHandler: () => {},
+ on(
+ event: 'will-navigate',
+ handler: (event: { preventDefault: () => void }, url: string) => void,
+ ) {
+ if (event === 'will-navigate') installedHandler = handler;
+ },
+ };
+
+ attachAssetSafetyNet(webContents, { openAsset, openExternal, editorOrigin: ORIGIN });
+
+ const preventDefault = vi.fn(() => {});
+ installedHandler?.({ preventDefault }, 'http://localhost:5173/notes/meeting.pdf');
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(openAsset).toHaveBeenCalledWith('notes/meeting.pdf');
+ });
+
test('malformed URL → silent drop (no preventDefault, no delegation, no crash)', async () => {
// Trust-boundary pin: `will-navigate` can fire with URLs Chromium's parser
// accepts but WHATWG `new URL()` rejects. Both parse attempts in the