Skip to content

Commit 2e16be7

Browse files
committed
perf(browser): reuse snapshot refs and screenshot metadata
1 parent 7504a3b commit 2e16be7

10 files changed

Lines changed: 92 additions & 191 deletions

‎extensions/browser/src/browser/cdp.ts‎

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -823,8 +823,6 @@ async function buildCdpRoleSnapshot(params: {
823823
}
824824

825825
const counts = new Map<string, number>();
826-
const refsByKey = new Map<string, string[]>();
827-
const nodesByRef = new Map<string, RoleTreeNode>();
828826
const refs: Record<string, CdpRoleRef> = {};
829827
for (const node of tree) {
830828
const role = node.role.toLowerCase();
@@ -843,13 +841,6 @@ async function buildCdpRoleSnapshot(params: {
843841
params.nextRef.value += 1;
844842
node.ref = ref;
845843
node.nth = nth;
846-
const refsForKey = refsByKey.get(key);
847-
if (refsForKey) {
848-
refsForKey.push(ref);
849-
} else {
850-
refsByKey.set(key, [ref]);
851-
}
852-
nodesByRef.set(ref, node);
853844
refs[ref] = {
854845
role,
855846
...(node.name ? { name: node.name } : {}),
@@ -858,19 +849,6 @@ async function buildCdpRoleSnapshot(params: {
858849
...(params.frameId ? { frameId: params.frameId } : {}),
859850
};
860851
}
861-
for (const refList of refsByKey.values()) {
862-
if (refList.length > 1) {
863-
continue;
864-
}
865-
const ref = refList[0];
866-
if (ref) {
867-
delete refs[ref]?.nth;
868-
const node = nodesByRef.get(ref);
869-
if (node) {
870-
delete node.nth;
871-
}
872-
}
873-
}
874852

875853
const iframeFrameIds = await resolveIframeFrameIds(params.send, tree, params.sessionId);
876854
for (const node of tree) {

‎extensions/browser/src/browser/chrome-mcp.snapshot.ts‎

Lines changed: 4 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -50,37 +50,6 @@ function shouldCreateRef(role: string, name?: string): boolean {
5050
return INTERACTIVE_ROLES.has(role) || (CONTENT_ROLES.has(role) && Boolean(name));
5151
}
5252

53-
type DuplicateTracker = {
54-
counts: Map<string, number>;
55-
keysByRef: Map<string, string>;
56-
duplicates: Set<string>;
57-
};
58-
59-
function createDuplicateTracker(): DuplicateTracker {
60-
return {
61-
counts: new Map(),
62-
keysByRef: new Map(),
63-
duplicates: new Set(),
64-
};
65-
}
66-
67-
function registerRef(
68-
tracker: DuplicateTracker,
69-
ref: string,
70-
role: string,
71-
name?: string,
72-
): number | undefined {
73-
const key = `${role}:${name ?? ""}`;
74-
const count = tracker.counts.get(key) ?? 0;
75-
tracker.counts.set(key, count + 1);
76-
tracker.keysByRef.set(ref, key);
77-
if (count > 0) {
78-
tracker.duplicates.add(key);
79-
return count;
80-
}
81-
return undefined;
82-
}
83-
8453
/** Build ARIA nodes while preserving whether a traversal ceiling omitted input. */
8554
export function flattenChromeMcpSnapshotToAriaResult(
8655
root: ChromeMcpSnapshotNode,
@@ -134,7 +103,7 @@ export function buildAiSnapshotFromChromeMcpSnapshot(params: {
134103
truncated?: true;
135104
} {
136105
const refs: RoleRefMap = {};
137-
const tracker = createDuplicateTracker();
106+
const counts = new Map<string, number>();
138107
const lines: string[] = [];
139108
const maxDepth = Math.min(
140109
params.options?.maxDepth ?? ROLE_SNAPSHOT_MAX_DEPTH,
@@ -162,7 +131,9 @@ export function buildAiSnapshotFromChromeMcpSnapshot(params: {
162131
}
163132
const ref = normalizeSnapshotString(node.id);
164133
if (ref && shouldCreateRef(role, name)) {
165-
const nth = registerRef(tracker, ref, role, name);
134+
const key = `${role}:${name ?? ""}`;
135+
const nth = counts.get(key);
136+
counts.set(key, (nth ?? 0) + 1);
166137
refs[ref] = nth === undefined ? { role, name } : { role, name, nth };
167138
line += ` [ref=${ref}]`;
168139
}
@@ -182,13 +153,6 @@ export function buildAiSnapshotFromChromeMcpSnapshot(params: {
182153

183154
visit(params.root, 0);
184155

185-
for (const [ref, data] of Object.entries(refs)) {
186-
const key = tracker.keysByRef.get(ref);
187-
if (key && !tracker.duplicates.has(key)) {
188-
delete data.nth;
189-
}
190-
}
191-
192156
const result = { snapshot: lines.join("\n"), refs };
193157
return truncated ? { ...result, truncated: true } : result;
194158
}

‎extensions/browser/src/browser/pw-role-snapshot.ts‎

Lines changed: 55 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -68,13 +68,14 @@ export function getRoleSnapshotIdentityKeys<T extends RoleRef>(
6868
/** Mark ref-bearing lines that were absent from the previous compatible snapshot. */
6969
function annotateRoleSnapshotDelta<T extends RoleRef>(params: {
7070
lines: string[];
71+
lineRefs: readonly (string | undefined)[];
7172
refs: Record<string, T>;
7273
mode: RoleSnapshotIdentityMode;
7374
previousKeys: ReadonlySet<string>;
7475
}): boolean {
7576
const markedKeys = new Set<string>();
7677
for (const [index, line] of params.lines.entries()) {
77-
const ref = findRoleSnapshotLineRef(line);
78+
const ref = params.lineRefs[index];
7879
const value = ref && Object.hasOwn(params.refs, ref) ? params.refs[ref] : undefined;
7980
if (!ref || !value) {
8081
continue;
@@ -93,18 +94,20 @@ function annotateRoleSnapshotDelta<T extends RoleRef>(params: {
9394
return true;
9495
}
9596

96-
function truncateRoleSnapshot(lines: readonly string[], maxChars: number): string {
97+
function truncateRoleSnapshot(lines: readonly string[], maxChars: number) {
9798
const marker =
9899
maxChars >= ROLE_SNAPSHOT_TRUNCATION_MARKER.length ? ROLE_SNAPSHOT_TRUNCATION_MARKER : "…";
99100
let prefix = "";
101+
let lineCount = 0;
100102
for (const line of lines) {
101103
const candidate = prefix ? `${prefix}\n${line}` : line;
102104
if (candidate.length + 2 + marker.length > maxChars) {
103105
break;
104106
}
105107
prefix = candidate;
108+
lineCount += 1;
106109
}
107-
return prefix ? `${prefix}\n\n${marker}` : marker;
110+
return { snapshot: prefix ? `${prefix}\n\n${marker}` : marker, lineCount };
108111
}
109112

110113
/** Apply the final output budget, then keep only refs present on complete output lines. */
@@ -131,22 +134,28 @@ export function finalizeRoleSnapshot<T extends RoleRef>(params: {
131134
const delta = params.delta;
132135
const previousKeys = delta?.previousKeys;
133136
const sourceLines = params.snapshot.split("\n");
134-
const annotated =
135-
delta && previousKeys !== undefined
136-
? annotateRoleSnapshotDelta({
137-
lines: sourceLines,
138-
refs: params.refs,
139-
mode: delta.mode,
140-
previousKeys,
141-
})
142-
: false;
137+
let lineRefs: (string | undefined)[] | undefined;
138+
let annotated = false;
139+
if (delta && previousKeys !== undefined) {
140+
lineRefs = sourceLines.map(findRoleSnapshotLineRef);
141+
annotated = annotateRoleSnapshotDelta({
142+
lines: sourceLines,
143+
lineRefs,
144+
refs: params.refs,
145+
mode: delta.mode,
146+
previousKeys,
147+
});
148+
}
143149
const sourceSnapshot = annotated ? sourceLines.join("\n") : params.snapshot;
144150
const truncated = maxChars !== undefined && sourceSnapshot.length > maxChars;
145-
const snapshot = truncated ? truncateRoleSnapshot(sourceLines, maxChars) : sourceSnapshot;
151+
const bounded = truncated ? truncateRoleSnapshot(sourceLines, maxChars) : undefined;
152+
const snapshot = bounded?.snapshot ?? sourceSnapshot;
146153
const outputLines = truncated ? snapshot.split("\n") : sourceLines;
147154
const visibleRefs = new Set<string>();
148-
for (const line of outputLines) {
149-
const ref = findRoleSnapshotLineRef(line);
155+
// Delta suffixes and the truncation marker cannot introduce formatter-owned refs.
156+
const visibleLineCount = bounded?.lineCount ?? sourceLines.length;
157+
for (let index = 0; index < visibleLineCount; index += 1) {
158+
const ref = lineRefs ? lineRefs[index] : findRoleSnapshotLineRef(sourceLines[index]!);
150159
if (ref) {
151160
visibleRefs.add(ref);
152161
}
@@ -238,57 +247,27 @@ function decodeSnapshotName(nameToken: string | undefined): string | undefined {
238247
return nameToken?.startsWith('"') ? JSON.parse(nameToken) : nameToken;
239248
}
240249

241-
type RoleNameTracker = {
242-
counts: Map<string, number>;
243-
refsByKey: Map<string, string[]>;
244-
getKey: (role: string, name?: string) => string;
245-
getNextIndex: (role: string, name?: string) => number;
246-
trackRef: (role: string, name: string | undefined, ref: string) => void;
247-
getDuplicateKeys: () => Set<string>;
248-
};
249-
250-
function createRoleNameTracker(): RoleNameTracker {
251-
const counts = new Map<string, number>();
252-
const refsByKey = new Map<string, string[]>();
253-
return {
254-
counts,
255-
refsByKey,
256-
getKey(role: string, name?: string) {
257-
return `${role}:${name ?? ""}`;
258-
},
259-
getNextIndex(role: string, name?: string) {
260-
const key = this.getKey(role, name);
261-
const current = counts.get(key) ?? 0;
262-
counts.set(key, current + 1);
263-
return current;
264-
},
265-
trackRef(role: string, name: string | undefined, ref: string) {
266-
const key = this.getKey(role, name);
267-
const list = refsByKey.get(key) ?? [];
268-
list.push(ref);
269-
refsByKey.set(key, list);
270-
},
271-
getDuplicateKeys() {
272-
const out = new Set<string>();
273-
for (const [key, refs] of refsByKey) {
274-
if (refs.length > 1) {
275-
out.add(key);
276-
}
250+
function createRoleNameTracker() {
251+
const groups = new Map<string, { count: number; first: RoleRef }>();
252+
return (role: string, name?: string): RoleRef => {
253+
const key = `${role}:${name ?? ""}`;
254+
const group = groups.get(key);
255+
const data: RoleRef = { role, name };
256+
if (group) {
257+
// The first generated ref gains index zero only when a duplicate appears.
258+
if (group.count === 1) {
259+
group.first.nth = 0;
277260
}
278-
return out;
279-
},
261+
data.nth = group.count;
262+
group.count += 1;
263+
} else {
264+
groups.set(key, { count: 1, first: data });
265+
}
266+
return data;
280267
};
281268
}
282269

283-
function removeNthFromNonDuplicates(refs: RoleRefMap, tracker: RoleNameTracker) {
284-
const duplicates = tracker.getDuplicateKeys();
285-
for (const [ref, data] of Object.entries(refs)) {
286-
const key = tracker.getKey(data.role, data.name);
287-
if (!duplicates.has(key)) {
288-
delete refs[ref]?.nth;
289-
}
290-
}
291-
}
270+
type RoleNameTracker = ReturnType<typeof createRoleNameTracker>;
292271

293272
function compactTree(tree: string) {
294273
const lines = tree.split("\n");
@@ -374,13 +353,9 @@ function processLine(
374353
}
375354

376355
const ref = nextRef();
377-
const nth = tracker.getNextIndex(role, name);
378-
tracker.trackRef(role, name, ref);
379-
refs[ref] = {
380-
role,
381-
name,
382-
nth,
383-
};
356+
const data = tracker(role, name);
357+
refs[ref] = data;
358+
const nth = data.nth ?? 0;
384359

385360
let enhanced = `${prefix}${roleRaw}`;
386361
if (name) {
@@ -403,8 +378,8 @@ type InteractiveSnapshotLine = NonNullable<ReturnType<typeof parseSnapshotLine>>
403378
function buildInteractiveSnapshotLines(params: {
404379
lines: string[];
405380
options: RoleSnapshotOptions;
406-
resolveRef: (parsed: InteractiveSnapshotLine) => { ref: string; nth?: number } | null;
407-
recordRef: (parsed: InteractiveSnapshotLine, ref: string, nth?: number) => void;
381+
refs: RoleRefMap;
382+
resolveRef: (parsed: InteractiveSnapshotLine) => { ref: string; data: RoleRef } | null;
408383
formatSuffix: (suffix: string, ref: string) => string;
409384
}): string[] {
410385
const out: string[] = [];
@@ -424,15 +399,15 @@ function buildInteractiveSnapshotLines(params: {
424399
if (!resolved?.ref) {
425400
continue;
426401
}
427-
params.recordRef(parsed, resolved.ref, resolved.nth);
402+
params.refs[resolved.ref] = resolved.data;
428403

429404
let enhanced = `- ${parsed.roleRaw}`;
430405
if (parsed.name) {
431406
enhanced += ` ${JSON.stringify(parsed.name)}`;
432407
}
433408
enhanced += ` [ref=${resolved.ref}]`;
434-
if ((resolved.nth ?? 0) > 0) {
435-
enhanced += ` [nth=${resolved.nth}]`;
409+
if ((resolved.data.nth ?? 0) > 0) {
410+
enhanced += ` [nth=${resolved.data.nth}]`;
436411
}
437412
enhanced += params.formatSuffix(parsed.suffix, resolved.ref);
438413
out.push(enhanced);
@@ -479,24 +454,11 @@ export function buildRoleSnapshotFromAriaSnapshot(
479454
const result = buildInteractiveSnapshotLines({
480455
lines,
481456
options,
482-
resolveRef: ({ role, name }) => {
483-
const ref = nextRef();
484-
const nth = tracker.getNextIndex(role, name);
485-
tracker.trackRef(role, name, ref);
486-
return { ref, nth };
487-
},
488-
recordRef: ({ role, name }, ref, nth) => {
489-
refs[ref] = {
490-
role,
491-
name,
492-
nth,
493-
};
494-
},
457+
refs,
458+
resolveRef: ({ role, name }) => ({ ref: nextRef(), data: tracker(role, name) }),
495459
formatSuffix: (suffix) => (suffix.includes("[") ? suffix : ""),
496460
});
497461

498-
removeNthFromNonDuplicates(refs, tracker);
499-
500462
return {
501463
snapshot: result.join("\n") || "(no interactive elements)",
502464
refs,
@@ -511,8 +473,6 @@ export function buildRoleSnapshotFromAriaSnapshot(
511473
}
512474
}
513475

514-
removeNthFromNonDuplicates(refs, tracker);
515-
516476
const tree = result.join("\n") || "(empty)";
517477
return {
518478
snapshot: options.compact ? compactTree(tree) : tree,
@@ -541,12 +501,12 @@ export function buildRoleSnapshotFromAiSnapshot(
541501
const out = buildInteractiveSnapshotLines({
542502
lines,
543503
options,
504+
refs,
544505
resolveRef: (parsed) => {
545506
const ref = parseAiSnapshotRef(parsed.ref);
546-
return ref ? { ref } : null;
547-
},
548-
recordRef: ({ role, name }, ref) => {
549-
refs[ref] = { role, ...(name ? { name } : {}) };
507+
return ref
508+
? { ref, data: { role: parsed.role, ...(parsed.name ? { name: parsed.name } : {}) } }
509+
: null;
550510
},
551511
formatSuffix: (suffix, ref) => suffix.replace(` [ref=${ref}]`, ""),
552512
});

0 commit comments

Comments
 (0)