Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(ok): copy image writes screenshot-shape clipboard (PRD-7877) (#3366)

Abraham9e6680380144
diff --git a/.changeset/copy-image-portable.md b/.changeset/copy-image-portable.md
new file mode 100644
index 000000000..7b9c28169
--- /dev/null
+++ b/.changeset/copy-image-portable.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Copying an image from a doc (Cmd+C after selecting the image) now pastes as an actual image everywhere. Before, most destinations either pasted the image's alt text as plain text (Slack chat, plain textareas), showed a gray box that never loaded (Google Docs), or a broken-attachment placeholder (Apple Notes). The Electron desktop app now writes the same 9-flavor raster set a macOS screenshot puts on the clipboard, so Notes, Docs, Slack, Notion, iMessage, and every other rich-text destination render the pixels inline first-try.
diff --git a/knip.config.ts b/knip.config.ts
index f9179f2d4..78162ec09 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/editor/clipboard/copy-image.ts b/packages/app/src/editor/clipboard/copy-image.ts
new file mode 100644
index 000000000..93197e04c
--- /dev/null
+++ b/packages/app/src/editor/clipboard/copy-image.ts
@@ -0,0 +1,165 @@
+/**
+ * Cmd+C on an image inside the editor — replace PM's default copy
+ * output (HTML `<img>` + alt-text as plain) with what a macOS system
+ * screenshot writes: the 9-flavor raster set that every rich receiver
+ * (Notes, Docs, Slack chat, Notion inline, iMessage) picks up first-
+ * try.
+ *
+ * The intercept runs in a document-level `copy` capture-phase listener,
+ * NOT the natural PM `handleDOMEvents.copy` plugin surface. That surface
+ * never received events for image node selections in Electron — the copy
+ * bubbled from the `<img>` up through the editor DOM but PM's plugin
+ * chain didn't see it (the failure is opaque; suspect
+ * react-medium-image-zoom's Zoom wrapper interacting with PM's synthetic
+ * `document.execCommand('copy')` dispatch for NodeSelections). A doc-
+ * level capture-phase listener catches every copy regardless of the
+ * plugin chain's state.
+ *
+ * The clipboard write itself runs in Electron main via
+ * `window.okDesktop.clipboard.copyImage`, because renderer's
+ * `navigator.clipboard.write` cannot produce the 9-flavor raster set —
+ * Chromium's Async Clipboard API only accepts a single `image/png`
+ * blob. Main's `nativeImage`-backed write goes through NSImage, which
+ * macOS's pasteboard writer expands into every raster flavor a receiver
+ * might read.
+ */
+
+/**
+ * Local duck type for the desktop-bridge copy surface. Structurally
+ * matches `OkDesktopBridge['clipboard']['copyImage']` in
+ * `packages/core/src/desktop-bridge.ts` — kept local instead of
+ * importing the full bridge type so this module stays testable without
+ * dragging the whole bridge surface into the test env. Adding a reason
+ * to the union here + in the bridge/IPC types is the sync contract.
+ */
+interface DesktopClipboardBridge {
+ copyImage(params: { readonly src: string; readonly alt: string }): Promise<
+ | { ok: true }
+ | {
+ ok: false;
+ reason: 'fetch-failed' | 'path-escape' | 'empty-image' | 'read-error' | 'write-error';
+ detail?: string;
+ }
+ >;
+}
+
+/** Read the desktop-bridge copy surface off `window.okDesktop.clipboard`, or null on web. */
+function getDesktopClipboard(): DesktopClipboardBridge | null {
+ if (typeof window === 'undefined') return null;
+ const bridge = (window as unknown as { okDesktop?: { clipboard?: unknown } }).okDesktop;
+ const c = bridge?.clipboard as { copyImage?: unknown } | undefined;
+ if (!c || typeof c.copyImage !== 'function') return null;
+ return c as DesktopClipboardBridge;
+}
+
+let installed = false;
+if (typeof window !== 'undefined' && !installed) {
+ installed = true;
+ document.addEventListener('copy', onDocCopy, true);
+}
+
+function onDocCopy(ev: ClipboardEvent): void {
+ const target = ev.target;
+ // Strict IMG-target match. PM dispatches copy events on the selected
+ // node's DOM element — for a NodeSelection on an image, that IS the
+ // `<img>`. A container target (paragraph, ProseMirror root) means a
+ // broader selection (multi-block, select-all, text-with-inline-img)
+ // that we must NOT hijack — otherwise the intercept below replaces
+ // the user's rich copy with just image bytes.
+ if (!(target instanceof HTMLImageElement)) return;
+ if (!target.closest('.ProseMirror')) return;
+ const resolvedSrc = target.currentSrc || target.src;
+ if (!resolvedSrc) return;
+ const alt = target.getAttribute('alt') ?? '';
+ // `stopImmediatePropagation` prevents PM's own copy handler on
+ // `view.dom` from running after ours. `preventDefault` alone only
+ // cancels the browser's default action; PM's listener still fires
+ // during the bubble phase and would `data.setData('text/html', …)` +
+ // `data.setData('text/plain', …)` synchronously, committing at end
+ // of event dispatch and racing with our async main-process write.
+ ev.preventDefault();
+ ev.stopImmediatePropagation();
+ const bridge = getDesktopClipboard();
+ if (bridge) {
+ void bridge
+ .copyImage({ src: resolvedSrc, alt })
+ .then((res) => {
+ if (res.ok) return;
+ // Main returned a classifiable failure (`empty-image` for a
+ // WebP/GIF/AVIF nativeImage can't decode; `fetch-failed` for
+ // an unreachable external URL; `path-escape` / `read-error`
+ // for same-origin misses). Fall back to the web write so the
+ // clipboard isn't left empty — Chromium's single-blob
+ // limitation still leaves the receiver with something.
+ console.warn('[copy-image] desktop write declined, falling back', res.reason, res.detail);
+ void webCopyFromImgEl(alt, resolvedSrc);
+ })
+ .catch((err) => {
+ console.warn('[copy-image] desktop bridge threw, falling back', err);
+ void webCopyFromImgEl(alt, resolvedSrc);
+ });
+ return;
+ }
+ // Pure-browser hosts (no desktop bridge). Chromium's Async Clipboard
+ // API only accepts one image flavor at a time, so this write is
+ // strictly less rich than the Electron path (single `image/png` vs
+ // main's 9-flavor raster set). Kept so browser hosts still get
+ // *some* raster on the clipboard instead of PM's alt-text default.
+ void webCopyFromImgEl(alt, resolvedSrc);
+}
+
+async function webCopyFromImgEl(alt: string, resolvedSrc: string): Promise<void> {
+ if (typeof navigator === 'undefined' || !navigator.clipboard?.write) {
+ // Every other failure path in this module logs — the doc-level
+ // listener has already preventDefaulted + stopImmediatePropagation-ed
+ // by the time we're here, so a silent early return leaves Cmd+C as
+ // a no-op with zero diagnostic trail. Electron always ships this
+ // API, so the branch only fires on pure-browser hosts where the
+ // Async Clipboard API is missing or restricted.
+ console.warn('[copy-image] navigator.clipboard.write unavailable — skipping web fallback');
+ return;
+ }
+ const html = `<img src="${escapeAttr(resolvedSrc)}" alt="${escapeAttr(alt)}">`;
+ // CommonMark image syntax: `[` / `]` in alt closes the label early,
+ // and `(` / `)` in the URL closes the destination — escape both so
+ // a paste into a markdown editor round-trips as a single image.
+ const escapedAlt = alt.replaceAll('\\', '\\\\').replaceAll('[', '\\[').replaceAll(']', '\\]');
+ const escapedSrc = resolvedSrc.replaceAll('(', '%28').replaceAll(')', '%29');
+ const markdown = `![${escapedAlt}](${escapedSrc})`;
+ try {
+ // Match the main-process fetch timeout (10s in
+ // copy-image-clipboard.ts). Otherwise a slow external image
+ // hangs the clipboard write indefinitely — and when the desktop
+ // path times out first and we fall through here, the user waits
+ // another 10s+ on the same slow URL.
+ const blob = await fetch(resolvedSrc, { signal: AbortSignal.timeout(10_000) }).then(
+ async (res) => {
+ if (!res.ok) throw new Error(`copy-image fetch failed: ${res.status}`);
+ const b = await res.blob();
+ // Chromium's Async Clipboard API only accepts `image/png` on
+ // write — a `ClipboardItem({ 'image/jpeg': blob })` throws
+ // `DOMException: Type image/jpeg not supported`. Always coerce
+ // to `image/png` here; most receivers sniff the bytes and
+ // ignore the declared MIME anyway.
+ return b.type === 'image/png' ? b : new Blob([b], { type: 'image/png' });
+ },
+ );
+ await navigator.clipboard.write([
+ new ClipboardItem({
+ 'image/png': blob,
+ 'text/plain': new Blob([markdown], { type: 'text/plain' }),
+ 'text/html': new Blob([html], { type: 'text/html' }),
+ }),
+ ]);
+ } catch (err) {
+ console.warn('[copy-image] web clipboard write failed', err);
+ }
+}
+
+function escapeAttr(s: string): string {
+ return s
+ .replaceAll('&', '&amp;')
+ .replaceAll('"', '&quot;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;');
+}
diff --git a/packages/app/src/editor/clipboard/index.ts b/packages/app/src/editor/clipboard/index.ts
index 120355e30..4746df85a 100644
--- a/packages/app/src/editor/clipboard/index.ts
+++ b/packages/app/src/editor/clipboard/index.ts
@@ -14,6 +14,12 @@
* (`source-polish/index.ts`, `image-upload/index.ts`).
*/
+// Side-effect import: `copy-image.ts` registers a document-level `copy`
+// capture-phase listener at module load — no exports. TipTapEditor imports
+// this barrel, which drags copy-image in so the listener arms whenever an
+// editor mounts.
+import './copy-image.ts';
+
export { OPT_OUT_ATTR } from './clipboard-sanitize.ts';
export { createCopyCutHandler } from './handle-copy.ts';
export { createHandleDrop, createHandlePaste } from './handle-paste.ts';
diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.ts
index 0e0c11e7a..7f83557ef 100644
--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts
+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts
@@ -392,6 +392,7 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
shell: shellStub,
clipboard: {
writeText: async () => {},
+ copyImage: async (): Promise<{ ok: true }> => ({ ok: true }),
},
project: {
listRecent: async () => [],
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 01ef76a9f..8fb428b90 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';
import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';
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 dcc5b0690..01ac80099 100644
--- a/packages/core/src/bridge/normalize.ts
+++ b/packages/core/src/bridge/normalize.ts
@@ -1,4 +1,3 @@
-
import { stripFrontmatter } from '../extensions/frontmatter.ts';
import { bodyEdgeEmpties } from './doc-boundary-space.ts';
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/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index 14f0ca958..39d0b5d90 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -1409,6 +1409,31 @@ export interface OkDesktopBridge {
/** IPC-relayed clipboard writer (sandboxed renderer cannot call clipboard directly). */
clipboard: {
writeText(text: string): Promise<void>;
+ /**
+ * Copy an image to the clipboard as raster bytes via `nativeImage`,
+ * which macOS's pasteboard writer expands into the 9-flavor raster
+ * set (`«class PNGf»`, `TIFF picture`, `JPEG picture`, `GIF
+ * picture`, `«class jp2»`, `«class BMP»`, `«class TPIC»`,
+ * `«class 8BPS»`, `«class AVIF»`) — the same shape a macOS
+ * screenshot writes. Every rich receiver (Notes, Docs, Slack chat,
+ * Notion inline, iMessage) picks a compatible flavor and renders
+ * inline first-try.
+ *
+ * Renderer's own `navigator.clipboard.write` can't produce that
+ * 9-flavor set (Chromium's Async Clipboard API only accepts one
+ * blob per MIME key), which is why the copy has to run in main.
+ * `nativeImage.createFromBuffer` decodes PNG + JPEG only; other
+ * formats resolve `empty-image` and the renderer is expected to
+ * fall back to its own best-effort `navigator.clipboard.write`.
+ */
+ copyImage(params: { readonly src: string; readonly alt: string }): Promise<
+ | { ok: true }
+ | {
+ ok: false;
+ reason: 'fetch-failed' | 'path-escape' | 'empty-image' | 'read-error' | 'write-error';
+ detail?: string;
+ }
+ >;
};
/**
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 69221627d..9075aa7f1 100644
--- a/packages/core/src/markdown/index.ts
+++ b/packages/core/src/markdown/index.ts
@@ -1,4 +1,3 @@
-
import {
type FromProseMirrorOptions,
fromPmMark,
@@ -207,7 +206,6 @@ export class MarkdownManager {
}
}
-
const registry = createRegistry();
function destructureAttrs(
@@ -256,7 +254,6 @@ function destructureAttrs(
return result;
}
-
function hasDirtyDescendant(node: PmNode): boolean {
let found = false;
node.descendants((child) => {
@@ -279,7 +276,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 ?? [];
@@ -348,7 +344,6 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {
return out;
}
-
import {
AUDIO_EXTENSIONS,
FILE_ATTACHMENT_EXTENSIONS,
@@ -601,7 +596,6 @@ function buildMdastToPmHandlers(
}));
}
-
if (m.emphasis) {
handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({
sourceDelimiter: node.data?.sourceDelimiter ?? '*',
@@ -682,7 +676,6 @@ function buildMdastToPmHandlers(
}));
}
-
if (m.link) {
const sourceLiteralMark = m.sourceLiteral;
handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {
@@ -980,7 +973,6 @@ function buildMdastToPmHandlers(
};
}
-
const blockUnknownHandler = (node: {
type: string;
position?: { start: { offset: number }; end: { offset: number } };
@@ -1106,7 +1098,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 e413367ef..0ba33b7d8 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 b96d19182..0d4c9a0df 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 833c3a727..3918e657c 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];
@@ -72,7 +71,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 4aa0490c4..d988f4b8b 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 5af2f05f5..449e6f12f 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 93798cf83..7cac5b042 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,
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 959cc0bd2..3e79f8cb6 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/copy-image-clipboard.test.ts b/packages/desktop/src/main/copy-image-clipboard.test.ts
new file mode 100644
index 000000000..057b4d924
--- /dev/null
+++ b/packages/desktop/src/main/copy-image-clipboard.test.ts
@@ -0,0 +1,242 @@
+/**
+ * Unit tests for the copy-image main-process pipeline. Every FS + network
+ * + Electron dep is injected, so no Electron / real fs / real network is
+ * exercised. Coverage priorities (from the PR review):
+ * 1. Path containment — %-encoded traversal, absolute paths.
+ * 2. Cross-origin fetch failure paths.
+ * 3. `nativeImage` empty-decode surfaces `empty-image`.
+ * 4. Happy path — `clipboard.writeImage` is called and result is ok.
+ * 5. Realpath before containment — a symlink escape is refused.
+ */
+
+import { describe, expect, test, vi } from 'vitest';
+import { type CopyImageToClipboardDeps, copyImageToClipboard } from './copy-image-clipboard.ts';
+
+/**
+ * Base deps with sensible stubs. Individual tests override what they
+ * need. Real-`Buffer` returns from nativeImage.toPNG are not asserted
+ * because we only need `isEmpty` for the branch coverage below.
+ */
+function baseDeps(overrides: Partial<CopyImageToClipboardDeps> = {}): CopyImageToClipboardDeps {
+ return {
+ projectPath: '/proj',
+ platform: 'darwin',
+ assetOrigin: 'http://localhost:5173',
+ clipboard: { writeImage: vi.fn() },
+ nativeImage: {
+ createFromBuffer: () => ({ isEmpty: () => false }),
+ },
+ fetch: vi.fn(async () => new Response(new Uint8Array([1, 2, 3]), { status: 200 })),
+ resolveCanonical: (p) => p,
+ ...overrides,
+ };
+}
+
+describe('copyImageToClipboard — same-origin path handling', () => {
+ test('refuses %-encoded ../ traversal with path-escape', async () => {
+ const writeImage = vi.fn();
+ const result = await copyImageToClipboard(
+ baseDeps({
+ clipboard: { writeImage },
+ // Force the realpath step to canonicalize outside the project so
+ // the containment check has real work to do — %2E%2E doesn't
+ // survive as ".." after decode+resolve alone.
+ resolveCanonical: () => '/etc/passwd',
+ }),
+ { src: 'http://localhost:5173/%2E%2E/%2E%2E/etc/passwd', alt: 'x' },
+ );
+ expect(result).toEqual({
+ ok: false,
+ reason: 'path-escape',
+ detail: expect.stringContaining('outside project'),
+ });
+ expect(writeImage).not.toHaveBeenCalled();
+ });
+
+ test('windows drive-letter after decode triggers the isAbsolute guard', async () => {
+ // On Windows, `http://localhost/C:/Windows/…` decodes to `/C:/…`;
+ // leading-slash strip leaves `C:/…`, which `pathWin32.isAbsolute`
+ // classifies as absolute. The guard fires BEFORE realpath, so the
+ // injected `resolveCanonical` never runs — asserts the guard's
+ // reachability from a real URL shape (from POSIX URL input the
+ // strip always leaves a relative path, so the guard is a
+ // Windows-specific defense).
+ const writeImage = vi.fn();
+ const resolveCanonical = vi.fn((p: string) => p);
+ const result = await copyImageToClipboard(
+ baseDeps({
+ platform: 'win32',
+ clipboard: { writeImage },
+ resolveCanonical,
+ }),
+ { src: 'http://localhost:5173/C:/Windows/System32/passwd', alt: 'x' },
+ );
+ expect(result).toEqual({
+ ok: false,
+ reason: 'path-escape',
+ detail: expect.stringContaining('absolute rel path'),
+ });
+ expect(resolveCanonical).not.toHaveBeenCalled();
+ expect(writeImage).not.toHaveBeenCalled();
+ });
+
+ test('realpath ENOENT surfaces as read-error (missing file along the chain)', async () => {
+ const writeImage = vi.fn();
+ const result = await copyImageToClipboard(
+ baseDeps({
+ clipboard: { writeImage },
+ resolveCanonical: () => {
+ throw Object.assign(new Error('no such file'), { code: 'ENOENT' });
+ },
+ }),
+ { src: 'http://localhost:5173/assets/missing.png', alt: 'x' },
+ );
+ expect(result).toEqual({
+ ok: false,
+ reason: 'read-error',
+ detail: expect.stringContaining('no such file'),
+ });
+ expect(writeImage).not.toHaveBeenCalled();
+ });
+
+ test('readFile EACCES surfaces as read-error (permission denied)', async () => {
+ const writeImage = vi.fn();
+ const result = await copyImageToClipboard(
+ baseDeps({
+ clipboard: { writeImage },
+ readFile: async () => {
+ throw Object.assign(new Error('permission denied'), { code: 'EACCES' });
+ },
+ }),
+ { src: 'http://localhost:5173/assets/logo.png', alt: 'x' },
+ );
+ expect(result).toEqual({
+ ok: false,
+ reason: 'read-error',
+ detail: expect.stringContaining('permission denied'),
+ });
+ expect(writeImage).not.toHaveBeenCalled();
+ });
+
+ test('non-image extension is refused at the disk-read gate (extension whitelist)', async () => {
+ const writeImage = vi.fn();
+ const readFile = vi.fn();
+ const result = await copyImageToClipboard(
+ baseDeps({
+ clipboard: { writeImage },
+ readFile,
+ }),
+ { src: 'http://localhost:5173/.ok/config.yml', alt: 'x' },
+ );
+ expect(result).toEqual({
+ ok: false,
+ reason: 'path-escape',
+ detail: expect.stringContaining('unsupported ext'),
+ });
+ expect(readFile).not.toHaveBeenCalled();
+ expect(writeImage).not.toHaveBeenCalled();
+ });
+
+ test('realpath refuses a symlink escape (containment on canonical path, not lexical)', async () => {
+ const writeImage = vi.fn();
+ const result = await copyImageToClipboard(
+ baseDeps({
+ clipboard: { writeImage },
+ // `assets/logo.png` lexically stays in project, but realpath
+ // resolves it to `/etc/passwd` — a symlink escape that a
+ // lexical containment check would miss.
+ resolveCanonical: () => '/etc/passwd',
+ }),
+ { src: 'http://localhost:5173/assets/logo.png', alt: 'x' },
+ );
+ expect(result).toEqual({
+ ok: false,
+ reason: 'path-escape',
+ detail: expect.stringContaining('outside project'),
+ });
+ expect(writeImage).not.toHaveBeenCalled();
+ });
+});
+
+describe('copyImageToClipboard — cross-origin fetch', () => {
+ test('4xx / 5xx response resolves fetch-failed with HTTP status', async () => {
+ const writeImage = vi.fn();
+ const result = await copyImageToClipboard(
+ baseDeps({
+ clipboard: { writeImage },
+ fetch: vi.fn(async () => new Response('', { status: 404 })),
+ }),
+ { src: 'https://cdn.example.com/missing.png', alt: 'x' },
+ );
+ expect(result).toEqual({
+ ok: false,
+ reason: 'fetch-failed',
+ detail: 'HTTP 404',
+ });
+ expect(writeImage).not.toHaveBeenCalled();
+ });
+
+ test('fetch throw (network error, timeout) surfaces as fetch-failed', async () => {
+ const writeImage = vi.fn();
+ const result = await copyImageToClipboard(
+ baseDeps({
+ clipboard: { writeImage },
+ fetch: vi.fn(async () => {
+ throw new Error('boom');
+ }),
+ }),
+ { src: 'https://cdn.example.com/foo.png', alt: 'x' },
+ );
+ expect(result).toEqual({
+ ok: false,
+ reason: 'fetch-failed',
+ detail: 'boom',
+ });
+ expect(writeImage).not.toHaveBeenCalled();
+ });
+});
+
+describe('copyImageToClipboard — decode + write', () => {
+ test('empty-image branch when nativeImage.createFromBuffer decodes empty (SVG / AVIF / WebP)', async () => {
+ const writeImage = vi.fn();
+ const result = await copyImageToClipboard(
+ baseDeps({
+ clipboard: { writeImage },
+ nativeImage: {
+ createFromBuffer: () => ({ isEmpty: () => true }),
+ },
+ }),
+ { src: 'https://cdn.example.com/x.svg', alt: 'x' },
+ );
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.reason).toBe('empty-image');
+ }
+ expect(writeImage).not.toHaveBeenCalled();
+ });
+
+ test('happy path: writeImage called, ok:true returned', async () => {
+ const writeImage = vi.fn();
+ const result = await copyImageToClipboard(baseDeps({ clipboard: { writeImage } }), {
+ src: 'https://cdn.example.com/pic.png',
+ alt: 'x',
+ });
+ expect(result).toEqual({ ok: true });
+ expect(writeImage).toHaveBeenCalledTimes(1);
+ });
+
+ test('writeImage throw surfaces as write-error (defends against NSPasteboard flakes)', async () => {
+ const writeImage = vi.fn(() => {
+ throw new Error('NSPasteboard write failed');
+ });
+ const result = await copyImageToClipboard(baseDeps({ clipboard: { writeImage } }), {
+ src: 'https://cdn.example.com/pic.png',
+ alt: 'x',
+ });
+ expect(result).toEqual({
+ ok: false,
+ reason: 'write-error',
+ detail: 'NSPasteboard write failed',
+ });
+ });
+});
diff --git a/packages/desktop/src/main/copy-image-clipboard.ts b/packages/desktop/src/main/copy-image-clipboard.ts
new file mode 100644
index 000000000..2ad114cf3
--- /dev/null
+++ b/packages/desktop/src/main/copy-image-clipboard.ts
@@ -0,0 +1,270 @@
+/**
+ * Main-process helper that puts an image on the OS clipboard the same
+ * shape a macOS system screenshot / CleanShot writes: the 9-flavor
+ * raster set macOS's pasteboard writer expands an NSImage into
+ * (`«class PNGf»`, `TIFF picture`, `JPEG picture`, `GIF picture`,
+ * `«class jp2»`, `«class BMP»`, `«class TPIC»`, `«class 8BPS»`,
+ * `«class AVIF»`). Every rich receiver we tested (Notes, Docs, Slack
+ * chat, Notion inline, iMessage) picks a compatible raster and renders
+ * inline first-try.
+ *
+ * Renderer's own `navigator.clipboard.write` can't produce that 9-flavor
+ * set — Chromium's Async Clipboard API only accepts one blob per MIME
+ * key — which is why the copy has to run in main. `nativeImage` is the
+ * transport into NSImage.
+ *
+ * The bytes come from disk when the src is same-origin as the asset
+ * serve (path resolved + canonicalized against the project root — same
+ * `realpath` + containment gate as `openAssetSafely`), and from a
+ * network `fetch` otherwise.
+ */
+
+import { realpathSync } from 'node:fs';
+import { readFile } from 'node:fs/promises';
+import { resolve as resolvePath } from 'node:path';
+import * as pathPosix from 'node:path/posix';
+import * as pathWin32 from 'node:path/win32';
+import type { Clipboard, NativeImage } from 'electron';
+import { isPathWithinProject } from './ipc-handlers.ts';
+
+/**
+ * Extensions `nativeImage.createFromBuffer` decodes on macOS. Electron's
+ * `AddImageSkiaRepFromBuffer` tries PNG then JPEG then a raw bitmap
+ * shape that needs explicit `width`/`height` (which this call site
+ * doesn't have). WebP / GIF / BMP land in the empty-image branch and
+ * fall back to the renderer's `navigator.clipboard.write` path — kept
+ * off this list so the fallback fires without the confusing detour
+ * through a decode we already know will fail.
+ */
+const CLIPBOARD_IMAGE_EXTS: ReadonlySet<string> = new Set(['png', 'jpg', 'jpeg']);
+
+type CopyImageResult =
+ | { ok: true }
+ | {
+ ok: false;
+ reason: 'fetch-failed' | 'path-escape' | 'empty-image' | 'read-error' | 'write-error';
+ detail?: string;
+ };
+
+export interface CopyImageToClipboardDeps {
+ readonly projectPath: string;
+ readonly platform: NodeJS.Platform;
+ /** Full origin (`http://localhost:<port>`) the OK asset serve is bound to for
+ * this window — same-origin URLs resolve to on-disk paths under project. */
+ readonly assetOrigin: string;
+ /**
+ * Electron `clipboard` + `nativeImage`. Injected so tests can stub.
+ * `clear` is intentionally not in the Pick — `writeImage` on macOS
+ * clears+writes atomically at the NSPasteboard level, and calling
+ * `clear` explicitly would open a wipe-then-throw window where the
+ * user's prior clipboard is gone with nothing to replace it.
+ */
+ readonly clipboard: Pick<Clipboard, 'writeImage'>;
+ readonly nativeImage: {
+ createFromBuffer(buffer: Buffer): Pick<NativeImage, 'isEmpty'>;
+ };
+ /** Optional network fetch — defaults to `globalThis.fetch`. */
+ readonly fetch?: typeof fetch;
+ /** Test seams — default to `realpathSync`. Failures map to `read-error`. */
+ readonly resolveCanonical?: (path: string) => string;
+ /** Test seam — defaults to `fs/promises` `readFile`. Failures map to `read-error`. */
+ readonly readFile?: (path: string) => Promise<Buffer>;
+}
+
+export interface CopyImageInput {
+ /** Absolute URL the renderer resolved off the live img (currentSrc / src). */
+ readonly src: string;
+ /** Alt attribute — currently unused, kept in the payload so a future
+ * human-readable filename step can seed on it without a shape change. */
+ readonly alt: string;
+}
+
+/**
+ * Fetch the image bytes for `src`, decode via nativeImage, and write to
+ * the OS clipboard via `writeImage`. `{ok: false, reason}` on every
+ * classifiable failure so the renderer's `navigator.clipboard.write`
+ * fallback can fire.
+ */
+export async function copyImageToClipboard(
+ deps: CopyImageToClipboardDeps,
+ input: CopyImageInput,
+): Promise<CopyImageResult> {
+ const fetchImpl = deps.fetch ?? globalThis.fetch;
+ const bytesResult = await loadImageBytes(deps, input.src, fetchImpl);
+ if (!bytesResult.ok) return bytesResult;
+ const { bytes, ext } = bytesResult;
+
+ const img = deps.nativeImage.createFromBuffer(bytes);
+ if (img.isEmpty()) {
+ return { ok: false, reason: 'empty-image', detail: `nativeImage empty for .${ext}` };
+ }
+
+ // Raster-only clipboard write. `clipboard.writeImage` on macOS routes
+ // through NSImage; the pasteboard writer expands that into the
+ // 9-flavor raster set every rich receiver reads (see header). We do
+ // NOT chain a `writeBuffer('public.file-url', …)` — Electron's
+ // `writeBuffer` on macOS calls `[NSPasteboard clearContents]`, which
+ // wipes the raster from the prior `writeImage` and leaves file-url
+ // as the only flavor (sandboxed receivers like Notes then show a
+ // broken-attachment placeholder). Truly-atomic multi-flavor writes
+ // need a native module (`-writeObjects:` with an NSImage + NSURL),
+ // which we don't ship today.
+ //
+ // `writeImage` on macOS is `[NSPasteboard writeObjects:@[image]]`,
+ // which clears + writes atomically at the OS level — no explicit
+ // `clipboard.clear()` needed, and skipping it avoids the "clipboard
+ // wiped, then writeImage threw" window where the user's old
+ // clipboard is gone and nothing replaced it. The try/catch below is
+ // defense against a synchronous NativeImage / NSPasteboard failure
+ // (memory pressure, malformed image, native-layer bug) so the IPC
+ // returns a classified result instead of a raw rejection.
+ try {
+ // biome-ignore lint/suspicious/noExplicitAny: nativeImage.createFromBuffer returns Pick<>, writeImage wants full NativeImage — safe at runtime because Electron only reads the surface Pick<> covers.
+ deps.clipboard.writeImage(img as any);
+ } catch (err) {
+ return {
+ ok: false,
+ reason: 'write-error',
+ detail: (err as Error)?.message ?? 'writeImage failed',
+ };
+ }
+ return { ok: true };
+}
+
+/**
+ * Read the image bytes for `src`. Same-origin URLs (matching
+ * `assetOrigin`) resolve to an on-disk path under `projectPath` and
+ * read from FS — the path is canonicalized via `realpathSync` before
+ * the containment check (`openAssetSafely` parity), so a symlink whose
+ * lexical join stays inside the project but whose real target escapes
+ * gets refused with `path-escape` rather than followed. External URLs
+ * go through `fetch`.
+ */
+async function loadImageBytes(
+ deps: CopyImageToClipboardDeps,
+ src: string,
+ fetchImpl: typeof fetch,
+): Promise<
+ | { ok: true; bytes: Buffer; ext: string }
+ | { ok: false; reason: 'fetch-failed' | 'path-escape' | 'read-error'; detail?: string }
+> {
+ let url: URL;
+ try {
+ url = new URL(src);
+ } catch (err) {
+ return { ok: false, reason: 'fetch-failed', detail: `invalid URL: ${(err as Error).message}` };
+ }
+ if (url.origin === deps.assetOrigin) {
+ const relPath = decodeURIComponent(url.pathname).replace(/^\/+/, '');
+ const p = deps.platform === 'win32' ? pathWin32 : pathPosix;
+ if (p.isAbsolute(relPath)) {
+ return { ok: false, reason: 'path-escape', detail: `absolute rel path: ${relPath}` };
+ }
+ const joined = resolvePath(deps.projectPath, relPath);
+ // realpath before containment — matches `resolveAndContain` in
+ // asset-allowlist.ts. `isPathWithinProject` is lexical-only; a
+ // symlink inside the project pointing outside it would otherwise
+ // pass the containment check and `readFile` would follow it.
+ const resolveCanonical = deps.resolveCanonical ?? realpathSync;
+ let canonical: string;
+ try {
+ canonical = resolveCanonical(joined);
+ } catch (err) {
+ // Every `realpathSync` failure — ENOENT (path missing along the
+ // chain), EACCES (permission), ELOOP (symlink cycle), or other —
+ // collapses to `read-error`. The caller can distinguish causes
+ // via `detail` if needed but the branch outcome (fall back to
+ // renderer's own write) is the same for all of them.
+ return {
+ ok: false,
+ reason: 'read-error',
+ detail: `realpath: ${(err as Error)?.message ?? 'unknown'}`,
+ };
+ }
+ if (!isPathWithinProject(canonical, deps.projectPath, deps.platform)) {
+ return { ok: false, reason: 'path-escape', detail: `outside project: ${relPath}` };
+ }
+ // Extension gate — the feature is copying IMAGES; a DOM-supplied src
+ // that resolves to `.ok/config.yml` or `.env` inside the project
+ // should never reach `readFile`. `nativeImage.createFromBuffer` on
+ // a non-image body would land on `empty-image` anyway (no raw
+ // bytes escape to the clipboard), but refusing at the disk-read
+ // gate is the tighter capability match and matches
+ // `openAssetSafely`'s extension gate.
+ //
+ // Read the RAW extension here, not via `extractExt` — that helper
+ // normalizes unknown extensions to `'png'` for logging + fallback
+ // purposes, which would silently defeat this gate.
+ const rawExt = rawExtension(canonical);
+ if (!CLIPBOARD_IMAGE_EXTS.has(rawExt)) {
+ return { ok: false, reason: 'path-escape', detail: `unsupported ext: .${rawExt}` };
+ }
+ const readFileImpl = deps.readFile ?? readFile;
+ try {
+ const bytes = await readFileImpl(canonical);
+ return { ok: true, bytes, ext: rawExt };
+ } catch (err) {
+ return { ok: false, reason: 'read-error', detail: (err as Error)?.message ?? 'unknown' };
+ }
+ }
+ // Cross-origin: fetch via the network. Node's fetch respects proxies
+ // and TLS trust roots. Bounded by `AbortSignal.timeout` because the
+ // renderer fire-and-forgets the call — a hanging fetch would leave
+ // the user staring at a stale clipboard with no way to tell the copy
+ // wedged. 10s matches the sibling `AbortSignal.timeout` pattern in
+ // main/index.ts (npm-registry / cli-probe callers).
+ try {
+ // `redirect: 'manual'` closes the SSRF redirect-amplification
+ // window — a benign external URL 3xx'ing into `169.254.169.254`
+ // (cloud metadata) or `localhost:<internal-port>` would otherwise
+ // follow the redirect and return the internal body. `src` is
+ // DOM-supplied via authored document content, so it's
+ // attacker-influenceable. `nativeImage.createFromBuffer` already
+ // bounds what the bytes CAN do (only decodable rasters reach the
+ // clipboard), but blocking redirects at the fetch layer is
+ // zero-cost hardening on top.
+ const res = await fetchImpl(src, {
+ redirect: 'manual',
+ signal: AbortSignal.timeout(10_000),
+ });
+ if (!res.ok) {
+ return { ok: false, reason: 'fetch-failed', detail: `HTTP ${res.status}` };
+ }
+ const buf = Buffer.from(await res.arrayBuffer());
+ return { ok: true, bytes: buf, ext: extractExtFromResponse(res, src) };
+ } catch (err) {
+ return { ok: false, reason: 'fetch-failed', detail: (err as Error)?.message ?? 'unknown' };
+ }
+}
+
+/**
+ * Lowercased extension of a filesystem path with no allowlist coercion —
+ * `foo.YML` → `yml`, `foo` → `''`. Callers that want an image-only
+ * fallback (`.txt` → `.png` for logging) can wrap this; the extension
+ * gate above must NOT wrap it or it silently accepts everything.
+ */
+function rawExtension(path: string): string {
+ const lastDot = path.lastIndexOf('.');
+ if (lastDot < 0) return '';
+ return path.slice(lastDot + 1).toLowerCase();
+}
+
+function extractExt(path: string): string {
+ const raw = rawExtension(path);
+ return raw.length > 0 && CLIPBOARD_IMAGE_EXTS.has(raw) ? raw : 'png';
+}
+
+function extractExtFromResponse(res: Response, url: string): string {
+ const ct = res.headers.get('content-type') ?? '';
+ const match = ct.match(/image\/([a-z0-9]+)/i);
+ if (match) {
+ const raw = match[1].toLowerCase();
+ if (CLIPBOARD_IMAGE_EXTS.has(raw)) return raw;
+ if (raw === 'jpg') return 'jpeg';
+ }
+ try {
+ return extractExt(new URL(url).pathname);
+ } catch {
+ return 'png';
+ }
+}
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 68f74b87b..161d92a6f 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -208,6 +208,7 @@ import {
runLoginShellProbe,
} from './claude-readiness.ts';
import { requestUserConsent, walkExceedsCap } from './consent-dialog.ts';
+import { copyImageToClipboard } from './copy-image-clipboard.ts';
import {
type CrashDetection,
createCrashDetection,
@@ -5027,6 +5028,27 @@ function registerIpcHandlers() {
return undefined;
});
+ handle('ok:clipboard:copy-image', async (event, { src, alt }) => {
+ const callerWin = BrowserWindow.fromWebContents(event.sender);
+ if (!callerWin || !wm) {
+ return { ok: false as const, reason: 'read-error' as const, detail: 'no window context' };
+ }
+ const ctx = wm.getContextForBrowserWindow(callerWin as unknown as BrowserWindowLike);
+ if (!ctx?.projectPath || !ctx.apiOrigin) {
+ return { ok: false as const, reason: 'read-error' as const, detail: 'no project context' };
+ }
+ return copyImageToClipboard(
+ {
+ projectPath: ctx.projectPath,
+ platform: process.platform,
+ assetOrigin: ctx.apiOrigin,
+ clipboard,
+ nativeImage,
+ },
+ { src, alt },
+ );
+ });
+
handle('ok:locale:set-preference', async (_event, { preference }) => {
// The payload is user intent, stored and transported unresolved; resolution
// happens inside `currentMenuTranslator` at the point of activation, so a
diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.ts
index fa98b0f44..767d8e121 100644
--- a/packages/desktop/src/preload/index.ts
+++ b/packages/desktop/src/preload/index.ts
@@ -459,6 +459,7 @@ const bridge: OkDesktopBridge = {
clipboard: {
writeText: (text: string) => invoke('ok:clipboard:write-text', text),
+ copyImage: (params) => invoke('ok:clipboard:copy-image', params),
},
project: {
diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.ts
index 3501f368c..9c9f11e30 100644
--- a/packages/desktop/src/shared/ipc-channels.ts
+++ b/packages/desktop/src/shared/ipc-channels.ts
@@ -30,7 +30,7 @@
* existing channels is preferred over net-new hand-rolled channels until
* that migration lands.
*
- * Count is 91 (ratchet cap 91). The 74→75 bump reconciled a merge collision:
+ * Count is 93 (ratchet cap 93). The 74→75 bump reconciled a merge collision:
* the worktree selector (`ok:worktree:dispatch`) and the terminal-controls PR
* (`ok:terminal:cli-installed-map`) each landed in the base tree's single free
* slot concurrently. The 75→76 bump then unioned in the desktop
@@ -804,6 +804,27 @@ export interface RequestChannels {
};
/** Clipboard text write (IPC-relay — renderer is sandboxed). */
'ok:clipboard:write-text': { args: [text: string]; result: undefined };
+ /**
+ * Copy an image to the OS clipboard as raster bytes via `nativeImage`,
+ * which macOS's pasteboard writer expands into the 9-flavor raster
+ * set every rich receiver reads (Notes, Docs, Slack chat, Notion
+ * inline, iMessage). Renderer sends the resolved img URL + alt; main
+ * fetches the bytes (from disk when same-origin as the asset serve —
+ * realpath + containment gate; via `fetch` otherwise), decodes via
+ * nativeImage, and calls `clipboard.writeImage`. Renderer's own
+ * `navigator.clipboard.write` cannot produce the 9-flavor set —
+ * Chromium's Async Clipboard API only accepts one blob per MIME key.
+ */
+ 'ok:clipboard:copy-image': {
+ args: [params: { readonly src: string; readonly alt: string }];
+ result:
+ | { ok: true }
+ | {
+ ok: false;
+ reason: 'fetch-failed' | 'path-escape' | 'empty-image' | 'read-error' | 'write-error';
+ detail?: string;
+ };
+ };
/** Read the current window's config (projectPath, collabUrl, etc.). */
'ok:project:get-info': { args: []; result: OkDesktopConfig };
diff --git a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
index 0019a74ec..090138d49 100644
--- a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
+++ b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
@@ -411,10 +411,29 @@ const CHANNELS_SRC = readFileSync(SRC_PATH, 'utf-8');
* appearance surface exists: `ok:menu-action` and `ok:theme:applied` both push
* the other direction.
*
+ * Bumped from 92 to 93 for the Cmd+C-on-image clipboard write
+ * (`ok:clipboard:copy-image`): renderer sends a resolved img URL + alt
+ * off the DOM, main fetches bytes (from disk when same-origin as the
+ * asset serve; via network fetch otherwise) and calls
+ * `clipboard.writeImage` — the only path that produces the 9-flavor
+ * raster set macOS's pasteboard writer expands NSImage into, which is
+ * what every rich receiver (Notes, Docs, Slack chat, Notion inline,
+ * iMessage) reads. Chromium's Async Clipboard API in the renderer only
+ * accepts one blob per MIME key, so the write cannot fold there.
+ *
+ * Could not fold onto `ok:clipboard:write-text` (the only sibling
+ * clipboard channel): the two have incompatible payload shapes —
+ * `write-text` takes a plain `string` and returns `undefined`, while
+ * `copy-image` takes a `{src, alt}` params object and returns a
+ * discriminated `CopyImageResult` with five failure reasons the
+ * renderer branches on for the web-fallback path. Widening
+ * `write-text`'s payload to carry both would erase the type safety
+ * of both channels' callers.
+ *
* The typed-ipc migration remains the committed end state, with the
* `ipc-channels.ts` header updated in lock-step.
*/
-const REQUEST_CHANNEL_CAP = 92;
+const REQUEST_CHANNEL_CAP = 93;
/**
* Extract the body of an interface block by name. Returns the substring