Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(documents): preserve Markdown image reference semantics

Afloat57536552854f
diff --git a/packages/document-files/README.md b/packages/document-files/README.md
index 6abe00df..14a8465e 100644
--- a/packages/document-files/README.md
+++ b/packages/document-files/README.md
@@ -2,6 +2,8 @@
Document Files holds shared helpers for Room Document files: media type detection and Markdown processing built on unified/remark.
+Markdown image references use the first matching definition in document order, including definitions inside lists and block quotes. Preparing or extracting images removes unused data-URI definitions from those containers while retaining definitions still used by ordinary links.
+
There is one table from extension to representation format and media type, in the `@linger/document-files/media-type` subpath, which has no Node dependency. The CLI, Agent tools and Web all read it; Web keeps its own preview allowlist and file categories. `.m4v` is recorded as `video/mp4`. TeamHub's Go code does not use this table, so `agentsendmessage/atomic.go` and the inline playback allowlist must stay consistent with it.
The package has no AGENTS.md of its own; commands are the `scripts` in `package.json`, and general conventions are in the root [AGENTS.md](../../AGENTS.md).
diff --git a/packages/document-files/src/index.test.ts b/packages/document-files/src/index.test.ts
index 7c1cd555..450c2839 100644
--- a/packages/document-files/src/index.test.ts
+++ b/packages/document-files/src/index.test.ts
@@ -1,5 +1,90 @@
import { expect, it } from "vitest";
-import { extractDocumentImages, bundleDocumentImages } from "./index.js";
+import {
+ extractDocumentImages,
+ bundleDocumentImages,
+ prepareDocumentSource,
+} from "./index.js";
+
+it.each([
+ [
+ "root definitions",
+ "[chart]: data:image/gif;base64,R0lGODlh\n\n[CHART]: data:image/gif;base64,R0lGODdh",
+ ],
+ [
+ "a definition in a quote",
+ "> [chart]: data:image/gif;base64,R0lGODlh\n\n[chart]: data:image/gif;base64,R0lGODdh",
+ ],
+ [
+ "a definition in a list",
+ "- Notes\n\n [chart]: data:image/gif;base64,R0lGODlh",
+ ],
+])(
+ "resolves the first document-wide image definition with %s",
+ (_name, definitions) => {
+ const content = Buffer.from(`![chart][ChArT]\n\n${definitions}\n`);
+ const snapshot = {
+ filePath: "report.md",
+ content,
+ sizeBytes: content.length,
+ sha256: "",
+ };
+ const extracted = extractDocumentImages(snapshot);
+ expect([...extracted.files.values()]).toEqual([Buffer.from("GIF89a")]);
+ expect(Buffer.from(extracted.content).toString()).not.toContain(
+ "data:image",
+ );
+ const prepared = prepareDocumentSource(snapshot);
+ expect(prepared.image_count).toBe(1);
+ expect(prepared.markdown).toContain("document-image:");
+ expect(prepared.markdown).not.toContain("data:image");
+ },
+);
+
+it("keeps definitions that ordinary links still use after extracting images", () => {
+ const content = Buffer.from(
+ "![chart][asset]\n\n[Download][asset]\n\n> [asset]: data:image/gif;base64,R0lGODlh\n\n[Website][site]\n\n[site]: https://example.test/\n\n`![not an image][asset]`\n",
+ );
+ const snapshot = {
+ filePath: "report.md",
+ content,
+ sizeBytes: content.length,
+ sha256: "",
+ };
+ const extracted = extractDocumentImages(snapshot);
+ expect([...extracted.files.values()]).toEqual([Buffer.from("GIF89a")]);
+ for (const markdown of [
+ Buffer.from(extracted.content).toString(),
+ prepareDocumentSource(snapshot).markdown,
+ ]) {
+ expect(markdown).toContain("[Download][asset]");
+ expect(markdown).toContain("[asset]: data:image/gif;base64,R0lGODlh");
+ expect(markdown).toContain("[Website][site]");
+ expect(markdown).toContain("[site]: https://example.test/");
+ expect(markdown).toContain("`![not an image][asset]`");
+ }
+});
+
+it("bundles the first nested local definition without reading a later duplicate", async () => {
+ const content = Buffer.from(
+ "![chart][chart]\n\n> [chart]: first.gif\n\n[chart]: second.gif\n",
+ );
+ const reads: string[] = [];
+ const bundled = await bundleDocumentImages(
+ { filePath: "report.md", content, sizeBytes: content.length, sha256: "" },
+ async (filePath) => {
+ reads.push(filePath);
+ const bytes = Buffer.from(
+ filePath.endsWith("first.gif") ? "GIF89a" : "GIF87a",
+ );
+ return { filePath, content: bytes, sizeBytes: bytes.length, sha256: "" };
+ },
+ new AbortController().signal,
+ );
+ expect(reads).toEqual(["./playground/first.gif"]);
+ expect(Buffer.from(bundled.content).toString()).toContain(
+ "![chart](data:image/gif;base64,R0lGODlh)",
+ );
+});
it("extracts duplicate reference-style images once, preserves code, and restores image bytes", async () => {
const encoded = "R0lGODlh";
diff --git a/packages/document-files/src/index.ts b/packages/document-files/src/index.ts
index 092c9511..a3f3baa4 100644
--- a/packages/document-files/src/index.ts
+++ b/packages/document-files/src/index.ts
@@ -59,6 +59,22 @@ interface ImageNode {
alt?: string | null;
title?: string | null;
}
+interface MarkdownNode {
+ type: string;
+ children?: MarkdownNode[];
+ identifier?: string;
+ url?: string;
+ title?: string | null;
+}
+function* markdownNodes(tree: Tree): Generator<MarkdownNode> {
+ const pending: MarkdownNode[] = [tree];
+ while (pending.length) {
+ const node = pending.pop()!;
+ yield node;
+ const children = node.children ?? [];
+ for (let i = children.length - 1; i >= 0; i--) pending.push(children[i]!);
+ }
+}
function parse(snapshot: DocumentFileSnapshot) {
if (snapshot.content.length > MAX_BYTES) throw invalid();
return processor.parse(
@@ -68,18 +84,14 @@ function parse(snapshot: DocumentFileSnapshot) {
// Resolve reference-style images before changing URLs. Preserve ordinary links and code.
function images(tree: Tree): ImageNode[] {
const definitions = new Map<string, { url: string; title?: string | null }>();
- for (const node of tree.children)
- if (node.type === "definition")
- definitions.set(node.identifier.toUpperCase(), node);
+ for (const node of markdownNodes(tree)) {
+ if (node.type !== "definition") continue;
+ const key = node.identifier!.toUpperCase();
+ if (!definitions.has(key))
+ definitions.set(key, { url: node.url!, title: node.title });
+ }
const result: ImageNode[] = [];
- const stack: unknown[] = [tree];
- while (stack.length) {
- const node = stack.pop() as {
- type: string;
- children?: unknown[];
- identifier?: string;
- url?: string;
- };
+ for (const node of markdownNodes(tree)) {
if (node.type === "imageReference") {
const definition = definitions.get(node.identifier!.toUpperCase());
if (definition)
@@ -91,10 +103,24 @@ function images(tree: Tree): ImageNode[] {
}
if (node.type === "image") result.push(node as ImageNode);
if (result.length > 4096) throw invalid();
- if (node.children) for (const child of node.children) stack.push(child);
}
return result;
}
+function removeImageDefinitions(tree: Tree): void {
+ const linked = new Set<string>();
+ for (const node of markdownNodes(tree))
+ if (node.type === "linkReference")
+ linked.add(node.identifier!.toUpperCase());
+ for (const node of markdownNodes(tree)) {
+ if (!node.children) continue;
+ node.children = node.children.filter(
+ (child) =>
+ child.type !== "definition" ||
+ !/^data:/iu.test(child.url!) ||
+ linked.has(child.identifier!.toUpperCase()),
+ );
+ }
+}
function imageType(bytes: Uint8Array): string {
const b = Buffer.from(bytes);
if (b.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
@@ -140,10 +166,8 @@ export function prepareDocumentSource(snapshot: DocumentFileSnapshot) {
node.url = `document-image:${hash(bytes)}?source=${encodeURIComponent(source)}&sha256=${sourceHash}`;
imageCount++;
}
- // Definitions are no longer needed for converted images. Do not return large payloads to the model.
- tree.children = tree.children.filter(
- (node) => node.type !== "definition" || !/^data:/iu.test(node.url),
- );
+ // Drop payloads used only by converted images, but preserve ordinary links.
+ removeImageDefinitions(tree);
const markdown = processor.stringify(tree);
const textBytes = Buffer.byteLength(markdown);
if (textBytes > MAX_TEXT_BYTES)
@@ -174,9 +198,7 @@ export function extractDocumentImages(snapshot: DocumentFileSnapshot) {
node.url = filename;
}
if (!files.size) return { content: snapshot.content, files };
- tree.children = tree.children.filter(
- (node) => node.type !== "definition" || !/^data:/iu.test(node.url),
- );
+ removeImageDefinitions(tree);
const content = Buffer.from(processor.stringify(tree));
if (content.length > MAX_TEXT_BYTES)
throw new DocumentImageError(