Skip to content

Commit 0278c7d

Browse files
committed
fix(browser): satisfy page-share CI gates
1 parent f57f21d commit 0278c7d

8 files changed

Lines changed: 138 additions & 104 deletions

File tree

‎docs/docs_map.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9738,6 +9738,7 @@ Do not edit it by hand; run `pnpm docs:map:gen`.
97389738
- H2: Install and pair
97399739
- H2: Use it
97409740
- H3: Tab copilot side panel
9741+
- H2: Send a page to OpenClaw
97419742
- H2: Remote / cross-machine
97429743
- H2: Diagnostics
97439744
- H2: Security model

‎extensions/browser/chrome-extension/background.js‎

Lines changed: 1 addition & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
import { createCopilotController } from "./modules/copilot-background.js";
22
import {
33
buildPageSharePayload,
4-
capturePageContent,
5-
fetchGoogleDocExportInTab,
6-
googleDocIdFromUrl,
4+
capturePageShare,
75
waitForCondition,
86
} from "./modules/page-share-core.js";
97
// OpenClaw extension service worker.
@@ -483,62 +481,6 @@ async function connectRelay() {
483481
// onclose follows onerror and drives the reconnect, so no error handler needed.
484482
}
485483

486-
async function capturePageShare(tab) {
487-
const tabId = tab.id;
488-
if (typeof tabId !== "number") {
489-
throw new Error("No tab.");
490-
}
491-
const docId = googleDocIdFromUrl(tab.url);
492-
if (docId) {
493-
// Selection wins over the export: never send a whole private document
494-
// when the user asked for a highlighted passage.
495-
const selection = await captureDomSelection(tabId);
496-
if (selection) {
497-
return { url: tab.url ?? "", title: tab.title ?? "", selection, content: "" };
498-
}
499-
const [injection] = await chrome.scripting.executeScript({
500-
target: { tabId },
501-
func: fetchGoogleDocExportInTab,
502-
args: [docId],
503-
});
504-
const result = injection?.result;
505-
if (!result || result.error) {
506-
throw new Error(result?.error || "Google Docs export failed.");
507-
}
508-
return {
509-
url: tab.url ?? "",
510-
title: tab.title ?? "",
511-
selection: "",
512-
content: result.text,
513-
};
514-
}
515-
516-
const [injection] = await chrome.scripting.executeScript({
517-
target: { tabId },
518-
func: capturePageContent,
519-
});
520-
if (!injection?.result) {
521-
throw new Error("Could not read this page.");
522-
}
523-
return injection.result;
524-
}
525-
526-
async function captureDomSelection(tabId) {
527-
// Main frame only, deliberately: all-frame probes reject wholesale on one
528-
// inaccessible frame and return child frames in nondeterministic order.
529-
// Child-frame selections are served by the context menu's selectionText;
530-
// toolbar/shortcut on a child-frame selection sends the full page instead.
531-
try {
532-
const [injection] = await chrome.scripting.executeScript({
533-
target: { tabId },
534-
func: () => window.getSelection()?.toString().trim() ?? "",
535-
});
536-
return typeof injection?.result === "string" ? injection.result : "";
537-
} catch {
538-
return "";
539-
}
540-
}
541-
542484
async function sendPageShareRequest(payload) {
543485
if (!relayWs || relayWs.readyState !== WebSocket.OPEN) {
544486
throw new Error("Relay not connected.");
Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,3 @@
1-
export const PAGE_SHARE_MAX_CONTENT_CHARS: 120000;
2-
export const PAGE_SHARE_MAX_NOTE_CHARS: 2000;
3-
export const PAGE_SHARE_MAX_TITLE_CHARS: 500;
4-
export const PAGE_SHARE_MAX_URL_CHARS: 2000;
5-
61
export type PageSharePayload = {
72
url: string;
83
title: string;
@@ -18,8 +13,6 @@ export type PageCapture = {
1813
content: string;
1914
};
2015

21-
export function googleDocIdFromUrl(url: unknown): string | null;
22-
export function truncateShareText(text: unknown, maxChars: number): string;
2316
export function waitForCondition(condition: () => boolean, timeoutMs: number): Promise<boolean>;
2417
export function buildPageSharePayload(params: {
2518
url: string;
@@ -28,7 +21,8 @@ export function buildPageSharePayload(params: {
2821
selection?: string;
2922
note?: string;
3023
}): PageSharePayload;
31-
export function capturePageContent(): PageCapture;
32-
export function fetchGoogleDocExportInTab(
33-
docId: string,
34-
): Promise<{ text: string; error?: never } | { error: string; text?: never }>;
24+
export function capturePageShare(tab: {
25+
id?: number;
26+
url?: string;
27+
title?: string;
28+
}): Promise<PageCapture>;

‎extensions/browser/chrome-extension/modules/page-share-core.js‎

Lines changed: 64 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
// Keep these limits in sync with browser/extension-relay/relay-protocol.ts.
2-
export const PAGE_SHARE_MAX_CONTENT_CHARS = 120_000;
3-
export const PAGE_SHARE_MAX_NOTE_CHARS = 2_000;
4-
export const PAGE_SHARE_MAX_TITLE_CHARS = 500;
5-
export const PAGE_SHARE_MAX_URL_CHARS = 2_000;
2+
const PAGE_SHARE_MAX_CONTENT_CHARS = 120_000;
3+
const PAGE_SHARE_MAX_NOTE_CHARS = 2_000;
4+
const PAGE_SHARE_MAX_TITLE_CHARS = 500;
5+
const PAGE_SHARE_MAX_URL_CHARS = 2_000;
66

7-
export function googleDocIdFromUrl(url) {
7+
function googleDocIdFromUrl(url) {
88
let parsed;
99
try {
1010
parsed = new URL(String(url ?? ""));
@@ -17,7 +17,7 @@ export function googleDocIdFromUrl(url) {
1717
return /^\/document\/d\/([^/]+)/u.exec(parsed.pathname)?.[1] ?? null;
1818
}
1919

20-
export function truncateShareText(text, maxChars) {
20+
function truncateShareText(text, maxChars) {
2121
const value = String(text ?? "");
2222
if (value.length <= maxChars) {
2323
return value;
@@ -57,8 +57,64 @@ export function buildPageSharePayload({ url, title, content, selection, note })
5757
};
5858
}
5959

60+
export async function capturePageShare(tab) {
61+
const tabId = tab.id;
62+
if (typeof tabId !== "number") {
63+
throw new Error("No tab.");
64+
}
65+
const docId = googleDocIdFromUrl(tab.url);
66+
if (docId) {
67+
// Selection wins over the export: never send a whole private document
68+
// when the user asked for a highlighted passage.
69+
const selection = await captureDomSelection(tabId);
70+
if (selection) {
71+
return { url: tab.url ?? "", title: tab.title ?? "", selection, content: "" };
72+
}
73+
const [injection] = await chrome.scripting.executeScript({
74+
target: { tabId },
75+
func: fetchGoogleDocExportInTab,
76+
args: [docId],
77+
});
78+
const result = injection?.result;
79+
if (!result || result.error) {
80+
throw new Error(result?.error || "Google Docs export failed.");
81+
}
82+
return {
83+
url: tab.url ?? "",
84+
title: tab.title ?? "",
85+
selection: "",
86+
content: result.text,
87+
};
88+
}
89+
90+
const [injection] = await chrome.scripting.executeScript({
91+
target: { tabId },
92+
func: capturePageContent,
93+
});
94+
if (!injection?.result) {
95+
throw new Error("Could not read this page.");
96+
}
97+
return injection.result;
98+
}
99+
100+
async function captureDomSelection(tabId) {
101+
// Main frame only, deliberately: all-frame probes reject wholesale on one
102+
// inaccessible frame and return child frames in nondeterministic order.
103+
// Child-frame selections are served by the context menu's selectionText;
104+
// toolbar/shortcut on a child-frame selection sends the full page instead.
105+
try {
106+
const [injection] = await chrome.scripting.executeScript({
107+
target: { tabId },
108+
func: () => window.getSelection()?.toString().trim() ?? "",
109+
});
110+
return typeof injection?.result === "string" ? injection.result : "";
111+
} catch {
112+
return "";
113+
}
114+
}
115+
60116
/** Self-contained because chrome.scripting serializes this function source. */
61-
export function capturePageContent() {
117+
function capturePageContent() {
62118
const selection = window.getSelection()?.toString().trim() ?? "";
63119
const textOf = (node) =>
64120
String(Reflect.get(node ?? {}, "innerText") || node?.textContent || "").trim();
@@ -163,7 +219,7 @@ export function capturePageContent() {
163219
}
164220

165221
/** Self-contained so the request runs in the tab with the user's Google cookies. */
166-
export async function fetchGoogleDocExportInTab(docId) {
222+
async function fetchGoogleDocExportInTab(docId) {
167223
try {
168224
const response = await fetch(
169225
`https://docs.google.com/document/d/${encodeURIComponent(docId)}/export?format=txt`,
Lines changed: 65 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,58 @@
1-
import { describe, expect, it } from "vitest";
2-
import {
3-
PAGE_SHARE_MAX_CONTENT_CHARS,
4-
PAGE_SHARE_MAX_NOTE_CHARS,
5-
PAGE_SHARE_MAX_TITLE_CHARS,
6-
PAGE_SHARE_MAX_URL_CHARS,
7-
buildPageSharePayload,
8-
capturePageContent,
9-
googleDocIdFromUrl,
10-
truncateShareText,
11-
} from "./page-share-core.js";
1+
import { afterEach, describe, expect, it, vi } from "vitest";
2+
import { buildPageSharePayload, capturePageShare } from "./page-share-core.js";
3+
4+
const PAGE_SHARE_MAX_CONTENT_CHARS = 120_000;
5+
const PAGE_SHARE_MAX_NOTE_CHARS = 2_000;
6+
const PAGE_SHARE_MAX_TITLE_CHARS = 500;
7+
const PAGE_SHARE_MAX_URL_CHARS = 2_000;
128

139
describe("page share core", () => {
14-
it("extracts Google document ids from document URLs only", () => {
15-
expect(
16-
googleDocIdFromUrl("https://docs.google.com/document/d/document-id_123/edit?tab=t.0"),
17-
).toBe("document-id_123");
18-
expect(googleDocIdFromUrl("https://docs.google.com/spreadsheets/d/sheet-id/edit")).toBeNull();
19-
expect(googleDocIdFromUrl("https://example.com/document/d/not-google/edit")).toBeNull();
20-
expect(googleDocIdFromUrl("not a URL")).toBeNull();
10+
afterEach(() => {
11+
vi.unstubAllGlobals();
12+
});
13+
14+
it("exports Google documents in the tab using the document id", async () => {
15+
const executeScript = vi
16+
.fn()
17+
.mockResolvedValueOnce([{ result: "" }])
18+
.mockResolvedValueOnce([{ result: { text: "Document body" } }]);
19+
vi.stubGlobal("chrome", { scripting: { executeScript } });
20+
21+
await expect(
22+
capturePageShare({
23+
id: 17,
24+
url: "https://docs.google.com/document/d/document-id_123/edit?tab=t.0",
25+
title: "Document",
26+
}),
27+
).resolves.toEqual({
28+
url: "https://docs.google.com/document/d/document-id_123/edit?tab=t.0",
29+
title: "Document",
30+
selection: "",
31+
content: "Document body",
32+
});
33+
expect(executeScript.mock.calls[1]?.[0]).toMatchObject({
34+
target: { tabId: 17 },
35+
args: ["document-id_123"],
36+
});
2137
});
2238

2339
it("keeps text at the boundary and marks truncation beyond it", () => {
24-
expect(truncateShareText("12345", 5)).toBe("12345");
25-
expect(truncateShareText("123456", 5)).toBe("12345\n\n[Truncated: original was 6 characters]");
40+
const atBoundary = buildPageSharePayload({
41+
url: "https://example.com",
42+
title: "Example",
43+
content: "x".repeat(PAGE_SHARE_MAX_CONTENT_CHARS),
44+
});
45+
const beyondBoundary = buildPageSharePayload({
46+
url: "https://example.com",
47+
title: "Example",
48+
content: "x".repeat(PAGE_SHARE_MAX_CONTENT_CHARS + 1),
49+
});
50+
expect(atBoundary.content).toHaveLength(PAGE_SHARE_MAX_CONTENT_CHARS);
51+
expect(
52+
beyondBoundary.content.endsWith(
53+
`[Truncated: original was ${PAGE_SHARE_MAX_CONTENT_CHARS + 1} characters]`,
54+
),
55+
).toBe(true);
2656
});
2757

2858
it("trims fields, preserves newlines, applies caps, and drops empty optionals", () => {
@@ -42,8 +72,21 @@ describe("page share core", () => {
4272
expect(payload).not.toHaveProperty("selection");
4373
});
4474

45-
it("keeps the injected capture function self-contained", () => {
46-
const source = String(capturePageContent);
75+
it("keeps the injected capture function self-contained", async () => {
76+
const executeScript = vi.fn().mockResolvedValue([
77+
{
78+
result: {
79+
url: "https://example.com",
80+
title: "Example",
81+
selection: "",
82+
content: "Body",
83+
},
84+
},
85+
]);
86+
vi.stubGlobal("chrome", { scripting: { executeScript } });
87+
88+
await capturePageShare({ id: 9, url: "https://example.com", title: "Example" });
89+
const source = String(executeScript.mock.calls[0]?.[0].func);
4790
expect(source).not.toMatch(/\b(?:import|require)\b/u);
4891
});
4992
});

‎extensions/browser/src/browser/extension-relay/page-share.test.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,12 @@ import {
33
PAGE_SHARE_GATEWAY_REQUIRED_ERROR,
44
deliverPageShare,
55
setPageShareSink,
6-
type PageShareSink,
76
} from "./page-share.js";
87

98
function createSink() {
109
const enqueueSystemEvent = vi.fn();
1110
const requestHeartbeat = vi.fn();
12-
const sink: PageShareSink = {
11+
const sink = {
1312
enqueueSystemEvent,
1413
requestHeartbeat,
1514
resolveMainSessionKey: () => "agent:main:main",

‎extensions/browser/src/browser/extension-relay/page-share.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import type { PageSharePayload } from "./relay-protocol.js";
99
export const PAGE_SHARE_GATEWAY_REQUIRED_ERROR =
1010
"Send to OpenClaw needs the extension relay hosted by the Gateway (pair on the Gateway host or use direct Gateway pairing). Node-hosted relays are not supported yet.";
1111

12-
export type PageShareSink = {
12+
type PageShareSink = {
1313
enqueueSystemEvent(text: string, opts: { sessionKey: string }): unknown;
1414
requestHeartbeat(opts: { source: "other"; intent: "immediate"; reason: string }): unknown;
1515
resolveMainSessionKey(): string;

‎extensions/browser/src/browser/extension-relay/relay-protocol.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ export type RelayTabInfo = {
1313
active: boolean;
1414
};
1515

16-
export const PAGE_SHARE_MAX_CONTENT_CHARS = 120_000;
1716
export const PAGE_SHARE_MAX_NOTE_CHARS = 2_000;
1817
export const PAGE_SHARE_MAX_TITLE_CHARS = 500;
1918
export const PAGE_SHARE_MAX_URL_CHARS = 2_000;

0 commit comments

Comments
 (0)