惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

小众软件
小众软件
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
WordPress大学
WordPress大学
月光博客
月光博客
Hugging Face - Blog
Hugging Face - Blog
博客园 - 聂微东
博客园 - 【当耐特】
博客园_首页
The Cloudflare Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Apple Machine Learning Research
Apple Machine Learning Research
Last Week in AI
Last Week in AI
酷 壳 – CoolShell
酷 壳 – CoolShell
大猫的无限游戏
大猫的无限游戏
雷峰网
雷峰网
量子位
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tailwind CSS Blog
IT之家
IT之家
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
GbyAI
GbyAI
V
Visual Studio Blog
F
Fortinet All Blogs
Martin Fowler
Martin Fowler

Recent Commits to openclaw:main

test: merge chat side-result checks · openclaw/openclaw@ddd2c2a test: merge cron history checks · openclaw/openclaw@f7eb746 test: merge responsive navigation shell checks · openclaw/openclaw@c2e4b47 docs(changelog): add codex oauth fixes · openclaw/openclaw@628e6cd test: merge navigation routing cases · openclaw/openclaw@5d8cecb Tests: mock channel registry bundled fallback · openclaw/openclaw@2b08233 Secrets: avoid broad web search discovery for single plugin config · openclaw/openclaw@a464f59 test: merge config view browser checks · openclaw/openclaw@20cf511 fix(status): align oauth health with runtime · openclaw/openclaw@eed7116 feat: add macOS screen snapshots for monitor preview (#67954) thanks … · openclaw/openclaw@f377db1 fix: report shared auth scopes in hello-ok (#67810) thanks @BunsDev · openclaw/openclaw@0b6c39b Auto-reply: avoid eager bundled route fallback · openclaw/openclaw@3ea1bf4 Tests: narrow session binding contract setup · openclaw/openclaw@54e4e16 fix(macOS): enable undo/redo in webchat composer text input (#34962) · openclaw/openclaw@00951dc Tests: speed up channel setup promotion · openclaw/openclaw@82b529a Docs: refresh agent instructions · openclaw/openclaw@5775fe2 fix(auth): serialize OAuth refresh across agents to fix #26322 (#67876) · openclaw/openclaw@8e79080 test: allow ollama public surface boundary test · openclaw/openclaw@7d4f1a6 Docs: add test performance guardrails · openclaw/openclaw@89706d3 Tests: restore context-engine usage proof · openclaw/openclaw@e4c4f95 Tests: slim context engine runtime coverage · openclaw/openclaw@74c198f ci: retry failed custom checkouts · openclaw/openclaw@0ee5baf test: trim duplicate provider auth onboarding cases · openclaw/openclaw@1ffc02e matrix: fix sessions_spawn --thread subagent session spawning (#67643) · openclaw/openclaw@1ce2596 test: reduce auth choice fixture churn · openclaw/openclaw@857b9cd test: mock health status config boundaries · openclaw/openclaw@9d5ab4a test: mock onboard config io boundary · openclaw/openclaw@299694d test: mock legacy state plugin boundaries · openclaw/openclaw@2713089 test: mock channel install boundaries · openclaw/openclaw@b945248 test: mock doctor preview channel boundaries · openclaw/openclaw@b1a3ad4
[codex] Use clawpdf for PDF extraction (#87670) · opencla...
steipete · 2026-05-29 · via Recent Commits to openclaw:main
1-

import { existsSync } from "node:fs";

2-

import { createRequire } from "node:module";

3-

import path from "node:path";

41

import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";

526-

const { canvasSizes, getDocumentMock, pdfDocument } = vi.hoisted(() => ({

7-

canvasSizes: [] as Array<{ width: number; height: number }>,

8-

getDocumentMock: vi.fn(),

3+

const { createEngineMock, openPdfMock, pdfDocument } = vi.hoisted(() => ({

4+

createEngineMock: vi.fn(),

5+

openPdfMock: vi.fn(),

96

pdfDocument: {

10-

numPages: 2,

11-

getPage: vi.fn(async () => ({

12-

getTextContent: vi.fn(async () => ({ items: [] })),

13-

getViewport: vi.fn(({ scale }: { scale: number }) => ({

14-

width: 1000 * scale,

15-

height: 1000 * scale,

16-

})),

17-

render: vi.fn(() => ({ promise: Promise.resolve() })),

18-

})),

7+

pageCount: 2,

8+

extract: vi.fn(),

9+

destroy: vi.fn(),

1910

},

2011

}));

211222-

vi.mock("pdfjs-dist/legacy/build/pdf.mjs", () => ({

23-

getDocument: getDocumentMock,

24-

}));

25-26-

vi.mock("@napi-rs/canvas", () => ({

27-

createCanvas: vi.fn((width: number, height: number) => {

28-

canvasSizes.push({ width, height });

29-

return {

30-

toBuffer: vi.fn(() => Buffer.from("png")),

31-

};

32-

}),

13+

vi.mock("clawpdf", () => ({

14+

createEngine: createEngineMock,

3315

}));

34163517

import { createPdfDocumentExtractor } from "./document-extractor.js";

361837-

const require = createRequire(import.meta.url);

38-39-

function requireFirstMockArg(mock: ReturnType<typeof vi.fn>, label: string) {

40-

const [call] = mock.mock.calls;

41-

if (!call) {

42-

throw new Error(`Expected ${label}`);

43-

}

44-

return call[0];

19+

function request(overrides = {}) {

20+

return {

21+

buffer: Buffer.from("%PDF-1.4"),

22+

mimeType: "application/pdf",

23+

maxPages: 2,

24+

maxPixels: 100,

25+

minTextChars: 10,

26+

...overrides,

27+

};

4528

}

46294730

describe("PDF document extractor", () => {

4831

afterAll(() => {

49-

vi.doUnmock("pdfjs-dist/legacy/build/pdf.mjs");

50-

vi.doUnmock("@napi-rs/canvas");

32+

vi.doUnmock("clawpdf");

5133

vi.resetModules();

5234

});

53355436

beforeEach(() => {

55-

canvasSizes.length = 0;

56-

getDocumentMock.mockReset();

57-

getDocumentMock.mockReturnValue({ promise: Promise.resolve(pdfDocument) });

58-

pdfDocument.getPage.mockClear();

37+

createEngineMock.mockResolvedValue({ open: openPdfMock });

38+

openPdfMock.mockReset();

39+

openPdfMock.mockResolvedValue(pdfDocument);

40+

pdfDocument.pageCount = 2;

41+

pdfDocument.extract.mockReset();

42+

pdfDocument.destroy.mockReset();

5943

});

60446145

it("declares PDF support", () => {

@@ -70,55 +54,90 @@ describe("PDF document extractor", () => {

7054

});

7155

});

725673-

it("treats maxPixels as a hard total image rendering budget", async () => {

57+

it("extracts text first and renders fallback images through clawpdf", async () => {

58+

pdfDocument.extract.mockResolvedValueOnce({ text: "", images: [] }).mockResolvedValueOnce({

59+

text: "",

60+

images: [

61+

{

62+

type: "image",

63+

bytes: Uint8Array.from(Buffer.from("png")),

64+

mimeType: "image/png",

65+

page: 1,

66+

width: 10,

67+

height: 10,

68+

},

69+

],

70+

});

7471

const extractor = createPdfDocumentExtractor();

757276-

const result = await extractor.extract({

77-

buffer: Buffer.from("%PDF-1.4"),

78-

mimeType: "application/pdf",

79-

maxPages: 2,

80-

maxPixels: 100,

81-

minTextChars: 10,

82-

});

73+

const result = await extractor.extract(request());

83748475

if (!result) {

8576

throw new Error("Expected PDF extraction result");

8677

}

87-

expect(result.images).toHaveLength(1);

88-

expect(canvasSizes).toEqual([{ width: 10, height: 10 }]);

78+

expect(openPdfMock).toHaveBeenCalledWith(expect.any(Uint8Array));

79+

expect(pdfDocument.extract).toHaveBeenNthCalledWith(1, {

80+

mode: "text",

81+

maxPages: 2,

82+

maxTextChars: 200_000,

83+

});

84+

expect(pdfDocument.extract).toHaveBeenNthCalledWith(2, {

85+

mode: "images",

86+

maxPages: 2,

87+

image: {

88+

maxDimension: 10_000,

89+

maxPixels: 100,

90+

forms: true,

91+

},

92+

});

93+

expect(result).toEqual({

94+

text: "",

95+

images: [{ type: "image", data: "cG5n", mimeType: "image/png" }],

96+

});

97+

expect(pdfDocument.destroy).toHaveBeenCalledTimes(1);

8998

});

909991-

it("passes standardFontDataUrl to pdfjs getDocument as a package-root filesystem path", async () => {

100+

it("skips image fallback when enough text is extracted", async () => {

101+

pdfDocument.extract.mockResolvedValueOnce({ text: "enough text", images: [] });

92102

const extractor = createPdfDocumentExtractor();

9310394-

await extractor.extract({

95-

buffer: Buffer.from("%PDF-1.4"),

96-

mimeType: "application/pdf",

97-

maxPages: 1,

98-

maxPixels: 4_000_000,

99-

minTextChars: 200,

100-

});

104+

const result = await extractor.extract(request({ minTextChars: 5 }));

101105102-

expect(getDocumentMock).toHaveBeenCalledTimes(1);

103-

const params = requireFirstMockArg(getDocumentMock, "pdfjs getDocument call");

104-

const { data, standardFontDataUrl, ...stableParams } = params as {

105-

data: Uint8Array;

106-

disableWorker: boolean;

107-

standardFontDataUrl: string;

108-

};

109-

expect(stableParams).toEqual({

110-

disableWorker: true,

111-

});

112-

expect(data).toBeInstanceOf(Uint8Array);

113-

expect(typeof standardFontDataUrl).toBe("string");

114-115-

const expectedStandardFontDataUrl =

116-

path.join(path.dirname(require.resolve("pdfjs-dist/package.json")), "standard_fonts") + "/";

117-

expect(standardFontDataUrl).toBe(expectedStandardFontDataUrl);

118-

expect(path.isAbsolute(standardFontDataUrl)).toBe(true);

119-

expect(standardFontDataUrl.endsWith("/")).toBe(true);

120-

expect(standardFontDataUrl.startsWith("file://")).toBe(false);

121-

expect(existsSync(standardFontDataUrl)).toBe(true);

122-

expect(existsSync(path.join(standardFontDataUrl, "LiberationSans-Regular.ttf"))).toBe(true);

106+

expect(result).toEqual({ text: "enough text", images: [] });

107+

expect(pdfDocument.extract).toHaveBeenCalledTimes(1);

108+

expect(pdfDocument.destroy).toHaveBeenCalledTimes(1);

109+

});

110+111+

it("filters selected pages before passing them to clawpdf", async () => {

112+

pdfDocument.extract

113+

.mockResolvedValueOnce({ text: "", images: [] })

114+

.mockResolvedValueOnce({ text: "", images: [] });

115+

const extractor = createPdfDocumentExtractor();

116+117+

await extractor.extract(request({ pageNumbers: [3, 2, 0, 1], maxPages: 2 }));

118+119+

expect(pdfDocument.extract).toHaveBeenNthCalledWith(

120+

1,

121+

expect.objectContaining({ pages: [2, 1] }),

122+

);

123+

expect(pdfDocument.extract).toHaveBeenNthCalledWith(

124+

2,

125+

expect.objectContaining({ pages: [2, 1] }),

126+

);

127+

});

128+129+

it("reports image fallback failures and returns extracted text", async () => {

130+

const onImageExtractionError = vi.fn();

131+

const failure = new Error("render failed");

132+

pdfDocument.extract

133+

.mockResolvedValueOnce({ text: "short", images: [] })

134+

.mockRejectedValueOnce(failure);

135+

const extractor = createPdfDocumentExtractor();

136+137+

const result = await extractor.extract(request({ onImageExtractionError }));

138+139+

expect(result).toEqual({ text: "short", images: [] });

140+

expect(onImageExtractionError).toHaveBeenCalledWith(failure);

141+

expect(pdfDocument.destroy).toHaveBeenCalledTimes(1);

123142

});

124143

});