-
Notifications
You must be signed in to change notification settings - Fork 289
Expand file tree
/
Copy pathpdf-annotations.spec.ts
More file actions
406 lines (350 loc) · 12.6 KB
/
pdf-annotations.spec.ts
File metadata and controls
406 lines (350 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
import { test, expect, type Page } from "@playwright/test";
// Increase timeout for these tests — PDF loading from arxiv can be slow
test.setTimeout(120000);
/**
* PDF Annotation E2E Tests
*
* Tests the annotation capabilities of the PDF server through the basic-host UI.
* Verifies that annotations can be added, rendered, and interacted with.
*/
/** Wait for the MCP App to load inside nested iframes. */
async function waitForAppLoad(page: Page) {
const outerFrame = page.frameLocator("iframe").first();
await expect(outerFrame.locator("iframe")).toBeVisible({ timeout: 30000 });
}
/** Get the app frame locator (nested: sandbox > app) */
function getAppFrame(page: Page) {
return page.frameLocator("iframe").first().frameLocator("iframe").first();
}
/** Load the PDF server and call display_pdf with the default PDF. */
async function loadPdfServer(page: Page) {
await page.goto("/?theme=hide");
await expect(page.locator("select").first()).toBeEnabled({ timeout: 30000 });
await page.locator("select").first().selectOption({ label: "PDF Server" });
await page.click('button:has-text("Call Tool")');
await waitForAppLoad(page);
}
/**
* Extract the viewUUID from the display_pdf result panel.
* The tool result is displayed as JSON in a collapsible panel.
*/
async function extractViewUUID(page: Page): Promise<string> {
// Wait for the Tool Result panel to appear — it contains "📤 Tool Result"
const resultPanel = page.locator('text="📤 Tool Result"').first();
await expect(resultPanel).toBeVisible({ timeout: 30000 });
// The result preview shows the first 100 chars including "viewUUID: ..."
// Click to expand the result panel to see the full JSON
await resultPanel.click();
// Wait for the expanded result content to appear
const resultContent = page.locator("pre").last();
await expect(resultContent).toBeVisible({ timeout: 5000 });
const resultText = (await resultContent.textContent()) ?? "";
// Extract viewUUID from the JSON result
// The text content includes: "PDF opened. viewUUID: <uuid>"
const match = resultText.match(/viewUUID["\s:]+([a-f0-9-]{36})/);
if (!match) {
throw new Error(
`Could not extract viewUUID from result: ${resultText.slice(0, 200)}`,
);
}
return match[1];
}
/**
* Call the interact tool with the given input JSON.
* Selects the interact tool from the dropdown, fills the input, and clicks Call Tool.
*/
async function callInteract(page: Page, input: Record<string, unknown>) {
// Select "interact" in the tool dropdown (second select on the page)
const toolSelect = page.locator("select").nth(1);
await toolSelect.selectOption("interact");
// Fill the input textarea with the JSON
const inputTextarea = page.locator("textarea");
await inputTextarea.fill(JSON.stringify(input));
// Click "Call Tool"
await page.click('button:has-text("Call Tool")');
}
/** Wait for the PDF canvas to render (ensures the page is ready for annotations). */
async function waitForPdfCanvas(page: Page) {
const appFrame = getAppFrame(page);
await expect(appFrame.locator("canvas").first()).toBeVisible({
timeout: 30000,
});
// Wait a bit for fonts and text layer to stabilize
await page.waitForTimeout(2000);
}
test.describe("PDF Server - Annotations", () => {
test("display_pdf result includes viewUUID and interactEnabled meta", async ({
page,
}) => {
await loadPdfServer(page);
// Wait for result to appear
const resultPanel = page.locator('text="📤 Tool Result"').first();
await expect(resultPanel).toBeVisible({ timeout: 30000 });
// Expand the result panel
await resultPanel.click();
const resultContent = page.locator("pre").last();
await expect(resultContent).toBeVisible({ timeout: 5000 });
const resultText = (await resultContent.textContent()) ?? "";
// The result should carry the viewUUID and interact flag in _meta / structuredContent
// (interact action list lives in the tool description, not the runtime result).
expect(resultText).toContain("viewUUID");
expect(resultText).toContain("interactEnabled");
expect(resultText).toContain("PDF opened");
});
test("interact tool is available in tool dropdown", async ({ page }) => {
await loadPdfServer(page);
// Verify the interact tool is available in the tool dropdown
const toolSelect = page.locator("select").nth(1);
const options = await toolSelect.locator("option").allTextContents();
expect(options).toContain("interact");
});
test("add_annotations renders highlight on the page", async ({ page }) => {
await loadPdfServer(page);
await waitForPdfCanvas(page);
const viewUUID = await extractViewUUID(page);
// Add a highlight annotation on page 1
await callInteract(page, {
viewUUID,
action: "add_annotations",
annotations: [
{
id: "test-highlight-1",
type: "highlight",
page: 1,
rects: [{ x: 72, y: 700, width: 300, height: 14 }],
color: "rgba(255, 255, 0, 0.4)",
},
],
});
// Wait for the interact result
await page.waitForTimeout(1000);
// Verify the annotation appears in the annotation layer inside the app frame
const appFrame = getAppFrame(page);
const annotationLayer = appFrame.locator("#annotation-layer");
await expect(annotationLayer).toBeVisible({ timeout: 5000 });
// Check that a highlight annotation element was rendered
const highlightEl = appFrame.locator(".annotation-highlight");
await expect(highlightEl.first()).toBeVisible({ timeout: 5000 });
// Regression: highlight must be translucent (not opaque hex), so text
// underneath remains readable.
await expect(highlightEl.first()).toHaveCSS(
"background-color",
/rgba\(255, 255, 0, 0\.35\)/,
);
});
test("add_annotations renders multiple annotation types", async ({
page,
}) => {
await loadPdfServer(page);
await waitForPdfCanvas(page);
const viewUUID = await extractViewUUID(page);
// Add multiple annotation types at once
await callInteract(page, {
viewUUID,
action: "add_annotations",
annotations: [
{
id: "test-highlight",
type: "highlight",
page: 1,
rects: [{ x: 72, y: 700, width: 300, height: 14 }],
color: "rgba(255, 255, 0, 0.4)",
},
{
id: "test-note",
type: "note",
page: 1,
x: 400,
y: 600,
content: "Important finding!",
color: "#ffeb3b",
},
{
id: "test-stamp",
type: "stamp",
page: 1,
x: 300,
y: 400,
label: "APPROVED",
color: "#4caf50",
rotation: -15,
},
{
id: "test-freetext",
type: "freetext",
page: 1,
x: 100,
y: 300,
content: "See section 3.2",
fontSize: 14,
color: "#1976d2",
},
{
id: "test-rect",
type: "rectangle",
page: 1,
x: 50,
y: 200,
width: 500,
height: 100,
color: "#f44336",
},
],
});
await page.waitForTimeout(1500);
const appFrame = getAppFrame(page);
// Verify each annotation type is rendered
await expect(appFrame.locator(".annotation-highlight").first()).toBeVisible(
{
timeout: 5000,
},
);
await expect(appFrame.locator(".annotation-note").first()).toBeVisible({
timeout: 5000,
});
await expect(appFrame.locator(".annotation-stamp").first()).toBeVisible({
timeout: 5000,
});
await expect(appFrame.locator(".annotation-freetext").first()).toBeVisible({
timeout: 5000,
});
await expect(appFrame.locator(".annotation-rectangle").first()).toBeVisible(
{ timeout: 5000 },
);
});
test("remove_annotations removes annotation from DOM", async ({ page }) => {
await loadPdfServer(page);
await waitForPdfCanvas(page);
const viewUUID = await extractViewUUID(page);
// Add an annotation
await callInteract(page, {
viewUUID,
action: "add_annotations",
annotations: [
{
id: "to-remove",
type: "highlight",
page: 1,
rects: [{ x: 72, y: 700, width: 300, height: 14 }],
},
],
});
await page.waitForTimeout(1000);
const appFrame = getAppFrame(page);
await expect(appFrame.locator(".annotation-highlight").first()).toBeVisible(
{
timeout: 5000,
},
);
// Remove the annotation
await callInteract(page, {
viewUUID,
action: "remove_annotations",
ids: ["to-remove"],
});
await page.waitForTimeout(1000);
// Verify the annotation is gone
await expect(appFrame.locator(".annotation-highlight")).toHaveCount(0, {
timeout: 5000,
});
});
test("highlight_text finds and highlights text", async ({ page }) => {
await loadPdfServer(page);
await waitForPdfCanvas(page);
const viewUUID = await extractViewUUID(page);
// Use highlight_text to find and highlight "Attention" in the PDF
await callInteract(page, {
viewUUID,
action: "highlight_text",
query: "Attention",
color: "rgba(0, 200, 255, 0.4)",
});
await page.waitForTimeout(2000);
const appFrame = getAppFrame(page);
// highlight_text creates highlight annotations, so we should see at least one
await expect(appFrame.locator(".annotation-highlight").first()).toBeVisible(
{
timeout: 10000,
},
);
});
});
/**
* Read the most recent interact result text from the basic-host UI.
* Waits for the result-panel count to reach `expectedCount` first —
* `callInteract` doesn't block, so `.last()` would otherwise race to the
* previous (display_pdf) panel.
*/
async function readLastToolResult(
page: Page,
expectedCount: number,
): Promise<string> {
const panels = page.locator('text="📤 Tool Result"');
await expect(panels).toHaveCount(expectedCount, { timeout: 30000 });
await panels.last().click();
const pre = page.locator("pre").last();
await expect(pre).toBeVisible({ timeout: 5000 });
return (await pre.textContent()) ?? "";
}
/** Unwrap basic-host's `CallToolResult` JSON to the first text block. */
function unwrapTextResult(raw: string): string {
const parsed = JSON.parse(raw) as {
content?: { type: string; text?: string }[];
};
const block = parsed.content?.find((c) => c.type === "text");
if (!block?.text) throw new Error(`No text block in: ${raw.slice(0, 200)}`);
return block.text;
}
test.describe("PDF Server - get_viewer_state", () => {
test("returns page/zoom/mode and selection:null when nothing is selected", async ({
page,
}) => {
await loadPdfServer(page);
await waitForPdfCanvas(page);
const viewUUID = await extractViewUUID(page);
await callInteract(page, { viewUUID, action: "get_viewer_state" });
const raw = await readLastToolResult(page, 2);
const state = JSON.parse(unwrapTextResult(raw));
expect(state.currentPage).toBe(1);
expect(state.pageCount).toBeGreaterThan(1);
expect(typeof state.zoom).toBe("number");
expect(state.displayMode).toBe("inline");
expect(state.selection).toBeNull();
expect(Array.isArray(state.selectedAnnotationIds)).toBe(true);
});
test("returns selected text and bounding rect when text-layer text is selected", async ({
page,
}) => {
await loadPdfServer(page);
await waitForPdfCanvas(page);
const viewUUID = await extractViewUUID(page);
const app = getAppFrame(page);
// Programmatically select the contents of the first text-layer span.
const selectedText = await app
.locator("#text-layer span")
.first()
.evaluate((span) => {
const range = span.ownerDocument.createRange();
range.selectNodeContents(span);
const sel = span.ownerDocument.defaultView!.getSelection()!;
sel.removeAllRanges();
sel.addRange(range);
return sel.toString().replace(/\s+/g, " ").trim();
});
expect(selectedText.length).toBeGreaterThan(0);
await callInteract(page, { viewUUID, action: "get_viewer_state" });
const raw = await readLastToolResult(page, 2);
const state = JSON.parse(unwrapTextResult(raw));
expect(state.currentPage).toBe(1);
expect(state.selection).not.toBeNull();
expect(state.selection.text).toContain(selectedText);
expect(state.selection.boundingRect).toEqual(
expect.objectContaining({
x: expect.any(Number),
y: expect.any(Number),
width: expect.any(Number),
height: expect.any(Number),
}),
);
});
});