Skip to content

Computer use for the Pi coding agent — Windows apps, browsers and desktops through native UI trees, screenshots and real input.

fix: quiet captures keep the agent's image as the space of its points; viewport OCR reads enlarged; live check of viewports (LPT-931)

alexshpunt-clanker[bot]d60339c51edf
diff --git a/src/computer-resources.ts b/src/computer-resources.ts
index 70e3db7..c12ae21 100644
--- a/src/computer-resources.ts
+++ b/src/computer-resources.ts
@@ -955,7 +955,8 @@ export class ComputerResources {
if (!view.ocr) return result;
const image = result.content.find(block => block.type === "image")!;
let lines;
- try { lines = await session.recognizeText(image, undefined, signal); }
+ // The whole image as a region: Windows OCR then reads it enlarged, so small text of a small viewport reads too.
+ try { lines = await session.recognizeText(image, { x: 0, y: 0, ...result.details.viewport!.image }, signal); }
catch (error) { throw new ComputerRequestError(`Text recognition failed: ${error instanceof Error ? error.message : error}`); }
return { ...result, details: { ...result.details, text_lines: lines } };
}
@@ -1086,11 +1087,13 @@ export class ComputerResources {
const pixels = plan.point !== undefined || plan.end !== undefined || command.unit === "wheel_detents" || action === "timeline";
if (hint) this.hinted(view, hint);
else if (!view.native || pixels && view.native.width === undefined || viewport && !view.native.full) {
- // A viewport maps its points into a full-resolution capture of its window; the image the agent saw stays its latest.
- if (viewport) this.retireWindow(window, "native");
- const captured = viewport ? this.remember({ window_ref: window }, await session.observeFull(window, signal))
- : await this.read({ kind: "window", ref: window, source: computerSource("window", window) }, cwd, ["image"], signal);
- if (!captured || captured.details.status !== "observed") return captured ?? { content: [{ type: "text", text: "The window could not be captured; nothing was sent." }], details: { status: "refused", mode: this.getMode(), window_ref: window }, isError: true };
+ // A quiet capture: the image the agent saw stays the space of its points. A viewport maps its points into a
+ // full-resolution capture; other points go to a capture the size of the agent's latest image.
+ const seen = view.seen ? Math.max(64, view.seen.width, view.seen.height) : undefined;
+ this.retireWindow(window, "native");
+ const captured = this.remember({ window_ref: window }, await (viewport ? session.observeFull(window, signal)
+ : session.observeQuiet(window, signal, { granularity: "image", ...(seen && seen <= FULL_RESOLUTION ? { maxLongEdge: seen, scale: 1 } : {}) })));
+ if (captured.details.status !== "observed") return captured;
view = session.inputView(window);
}
const native = view.native!;
diff --git a/src/provider.ts b/src/provider.ts
index 0cdaa27..a2cc331 100644
--- a/src/provider.ts
+++ b/src/provider.ts
@@ -173,7 +173,7 @@ export function presentComputerResult(result: ComputerResult, full = false): str
for (const r of d.visual_regions) lines.push(`${r.kind}${r.text || r.label ? ` "${label(r.text ?? r.label)}"` : ""} | x=${r.x} y=${r.y} w=${r.width} h=${r.height} | center ${Math.round(r.x + r.width / 2)},${Math.round(r.y + r.height / 2)} | confidence ${r.confidence}`);
}
if (d.text_lines) {
- lines.push(`OCR: ${d.text_lines.length} lines; boxes in this observation's overview pixels. Recognised text can be wrong; confirm with pixels or UI before acting on it.`);
+ lines.push(`OCR: ${d.text_lines.length} lines; boxes in ${d.viewport ? "pixels of the viewport's image" : "this observation's overview pixels"}. Recognised text can be wrong; confirm with pixels or UI before acting on it.`);
for (const line of d.text_lines) lines.push(`"${label(line.text)}" | x=${line.x} y=${line.y} w=${line.width} h=${line.height}`);
}
if (d.successor) {
diff --git a/src/session.ts b/src/session.ts
index f4aa82f..ef87de5 100644
--- a/src/session.ts
+++ b/src/session.ts
@@ -1030,7 +1030,8 @@ export class ComputerSession {
const full = [element.label, element.value].filter((item): item is string => typeof item === "string" && item.length > 1024);
if (full.length && ui.elements[index]) texts.set(ui.elements[index].hint, full.join("\n").slice(0, ELEMENT_TEXT_LIMIT));
});
- if (hasImage && typeof state.screenshot_width === "number" && typeof state.screenshot_height === "number") entry.seen = { width: state.screenshot_width, height: state.screenshot_height };
+ // Only an image the agent is shown sets the space of its points; successors and other quiet captures keep it.
+ if (hasImage && !quiet && typeof state.screenshot_width === "number" && typeof state.screenshot_height === "number") entry.seen = { width: state.screenshot_width, height: state.screenshot_height };
entry.observation = { id, ui, settings, ...(texts.size ? { texts } : {}),
width: hasImage && typeof state.screenshot_width === "number" ? state.screenshot_width : undefined,
height: hasImage && typeof state.screenshot_height === "number" ? state.screenshot_height : undefined,
@@ -1288,8 +1289,7 @@ export class ComputerSession {
/**
* A full-resolution capture of a window for input in one of its viewports: it becomes the window's current
- * observation, but the size of the image the agent last saw stays, so points of the window's latest image keep
- * their meaning. Quiet, like a successor.
+ * observation. Quiet, like a successor, so points of the window's latest image keep their meaning.
*/
observeFull(ref: string, signal?: AbortSignal, granularity: "image" | "full" = "full"): Promise<ComputerResult> {
return this.queue(async () => {
@@ -1298,9 +1298,7 @@ export class ComputerSession {
const entry = await this.current(ref, signal);
if (!entry) return this.entries.has(ref) ? this.denied(ref) : this.result("refused", "Unknown or closed window_ref. Discover again.");
if (!this.allowed(entry)) return this.denied(entry.ref);
- const seen = entry.seen;
- try { return await this.capture(entry, signal, undefined, { granularity, maxLongEdge: FULL_RESOLUTION, scale: 1, hints: false }, true); }
- finally { entry.seen = seen; }
+ return await this.capture(entry, signal, undefined, { granularity, maxLongEdge: FULL_RESOLUTION, scale: 1, hints: false }, true);
} catch (error) { return this.failed(error, false); }
});
}
diff --git a/test/live/viewports.live.ts b/test/live/viewports.live.ts
new file mode 100644
index 0000000..6cd37f6
--- /dev/null
+++ b/test/live/viewports.live.ts
@@ -0,0 +1,93 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import { afterAll, expect, test } from "vitest";
+import { requireComputerAddress } from "../../src/computer-resources.ts";
+import { clickPlan, waitCommand, windowCommand } from "../../src/computer-tools.ts";
+import { presentComputerResult } from "../../src/provider.ts";
+import type { ComputerResult } from "../../src/session.ts";
+import { connectLive, nativeForm, openWindow, WINDOWS_POWERSHELL_PATH } from "./remote.ts";
+
+// LPT-931: a named viewport of a native window on the configured machine: its image at the window's own resolution,
+// clicks at points of that image, a change list of only its pixels, and a rectangle that follows the window.
+const live = await connectLive();
+afterAll(async () => { await live.close(); });
+const report: string[] = [];
+afterAll(async () => { await mkdir(".tmp/lpt931", { recursive: true }); await writeFile(".tmp/lpt931/report.txt", report.join("\n\n")); });
+const image = (result: ComputerResult, index = 0) => Buffer.from((result.content.filter(block => block.type === "image")[index] as { data: string }).data, "base64");
+const holds = async (window: string, name: string) => {
+ const result = await live.insert(window, waitCommand({ window, timeout_ms: 3000, conditions: [{ target: `getByRole('button', { name: '${name}' })`, is: "exists" }] }));
+ return (result.details.verification as { verdict?: string } | undefined)?.verdict;
+};
+
+test("a viewport shows its part of the window at full resolution, takes clicks in its pixels and follows the window", async () => {
+ const title = `pi-viewport-${Date.now()}`;
+ const window = await openWindow(live, live.machine, WINDOWS_POWERSHELL_PATH, nativeForm(title), title);
+ try {
+ // The agent's overview is smaller than the window, so its pixels and the window's differ.
+ const overview = await live.read(window, ["full", 'capture:{"maxLongEdge":300}']);
+ const button = overview.details.ui!.elements.find(e => /^Count 0/.test(e.name ?? ""))!;
+ const box = button.bounds.window_image!;
+ const pad = requireComputerAddress(`${window}/pad`);
+ const requested = { x: 0, y: 0, width: box.x + box.width + 20, height: box.y + box.height + 20 };
+ let started = performance.now();
+ const made = await live.resources.view(pad, live.cwd, requested);
+ report.push(`view ${Math.round(performance.now() - started)} ms\n${presentComputerResult(made)}`);
+ expect(made.details.status, presentComputerResult(made)).toBe("observed");
+ const viewport = made.details.viewport!;
+ // Full resolution: more image pixels than the overview gave the same rectangle.
+ const scale = viewport.rect.width / requested.width;
+ expect(scale).toBeGreaterThan(1.2);
+ expect(viewport.image).toEqual({ width: viewport.rect.width, height: viewport.rect.height });
+ await mkdir(".tmp/lpt931", { recursive: true });
+ await writeFile(".tmp/lpt931/pad.png", image(made));
+
+ // The hidden console of the form's PowerShell opens through Windows Terminal, which can take the foreground a moment
+ // after the form appears; the first real click needs the form in front, so focus it until it stays there.
+ for (let attempt = 0; attempt < 10; attempt++) {
+ await live.resources.manageWindow(requireComputerAddress(window), live.cwd, windowCommand({ window, action: "focus" }));
+ await new Promise(resolve => setTimeout(resolve, 500));
+ const state = (await live.read(window, ["state"])).details.state as { foreground_at_target?: boolean } | undefined;
+ if (state?.foreground_at_target) break;
+ }
+ // The button's centre in the viewport's own pixels.
+ const local = { x: Math.round((box.x + box.width / 2) * scale), y: Math.round((box.y + box.height / 2) * scale) };
+ started = performance.now();
+ const first = await live.resources.input(pad, live.cwd, clickPlan({ window: pad.source, x: local.x, y: local.y }));
+ report.push(`click in viewport ${Math.round(performance.now() - started)} ms\n${presentComputerResult(first)}`);
+ expect(first.details.status, presentComputerResult(first)).toBe("delivered");
+ expect(await holds(window, "Count 1")).toBe("satisfied");
+ expect(first.details.viewport?.source).toBe(viewport.source);
+ expect(first.details.successor?.diff?.pixels?.space).toBe("viewport");
+ if (first.content.some(block => block.type === "image")) await writeFile(".tmp/lpt931/first-change.png", image(first));
+
+ // Move the window: the viewport goes with it, so the same local point still hits the button.
+ const moved = await live.resources.manageWindow(requireComputerAddress(window), live.cwd, windowCommand({ window, action: "move", x: 333, y: 222 }));
+ report.push(`move\n${presentComputerResult(moved)}`);
+ expect(moved.details.status, presentComputerResult(moved)).not.toBe("refused");
+ const second = await live.resources.input(pad, live.cwd, clickPlan({ window: pad.source, x: local.x, y: local.y }));
+ report.push(`click after move\n${presentComputerResult(second)}`);
+ expect(await holds(window, "Count 2")).toBe("satisfied");
+
+ // A Read of the viewport shows the new label; ocr finds it.
+ const read = await live.read(pad.source, ["ocr"]);
+ report.push(`read with ocr\n${presentComputerResult(read)}`);
+ expect(JSON.stringify(read.details.text_lines)).toContain("Count 2");
+ await writeFile(".tmp/lpt931/pad-after.png", image(read));
+
+ // A point of the agent's overview keeps its meaning after input in the viewport.
+ const centre = { x: Math.round(box.x + box.width / 2), y: Math.round(box.y + box.height / 2) };
+ const third = await live.resources.input(requireComputerAddress(window), live.cwd, clickPlan({ window, x: centre.x, y: centre.y }));
+ report.push(`window click\n${presentComputerResult(third)}`);
+ expect(await holds(window, "Count 3")).toBe("satisfied");
+
+ // A viewport Read only looks: a ref of the window's latest Read still acts.
+ const fresh = await live.read(window, ["full"]);
+ const hint = fresh.details.ui!.elements.find(e => /^Count 3/.test(e.name ?? ""))!.hint;
+ await live.read(pad.source, []);
+ const fourth = await live.resources.input(requireComputerAddress(window), live.cwd, clickPlan({ window, target: hint }));
+ report.push(`ref click after a viewport Read\n${presentComputerResult(fourth)}`);
+ expect(fourth.details.status, presentComputerResult(fourth)).toBe("delivered");
+ expect(await holds(window, "Count 4")).toBe("satisfied");
+ } finally {
+ await live.resources.delete(window, live.cwd).catch(() => undefined);
+ }
+});
diff --git a/test/viewport.test.ts b/test/viewport.test.ts
index d50d735..dc3cf10 100644
--- a/test/viewport.test.ts
+++ b/test/viewport.test.ts
@@ -141,6 +141,15 @@ describe("viewports of a window", () => {
expect(f.dots.at(-1)).toEqual({ x: 500, y: 320 });
});
+ test("a capture the agent is not shown keeps the agent's latest image as the space of its points", async () => {
+ const f = await fixture();
+ await f.overview();
+ // A UI-only Read leaves no pixels, so the click captures the window first; that capture is not the agent's image.
+ await f.resources.read(requireComputerAddress(f.window), cwd, ["ui"]);
+ await f.resources.input(requireComputerAddress(f.window), cwd, { label: "click", point: { x: 250, y: 160 }, native: { action: "click" }, web: "" });
+ expect(f.dots).toEqual([{ x: 500, y: 320 }]);
+ });
+
test("a point outside the viewport's image and space refuse before anything is sent", async () => {
const f = await fixture();
await f.overview();