Skip to content

A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.

TypeScript

fix(computer): send only the last screenshot in each model call

Alan Buscagliad9f0fa854ad2
diff --git a/packages/daemon/src/extensions/approval-guard.ts b/packages/daemon/src/extensions/approval-guard.ts
index e2c651b..df3ce18 100644
--- a/packages/daemon/src/extensions/approval-guard.ts
+++ b/packages/daemon/src/extensions/approval-guard.ts
@@ -31,6 +31,7 @@
import { realpathSync, statSync } from "node:fs";
import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
+import { pruneScreenshots } from "./screenshot-context.ts";
export const POLICY_ENV = "GENTLE_DOT_CONNECTOR_POLICY";
/** The status key of a connector draft; the daemon reads it, nothing shows it. */
@@ -385,6 +386,9 @@ export default function approvalGuard(pi: ExtensionAPI): void {
},
});
+ // Each model call carries only the last computer screenshot (S24.10).
+ pi.on("context", (event) => ({ messages: pruneScreenshots(event.messages) }));
+
pi.on("tool_call", async (event, ctx) => {
const annotations = event.toolName.startsWith("mcp__")
? pi.getAllTools().find((tool) => tool.name === event.toolName)?.annotations
diff --git a/packages/daemon/src/extensions/screenshot-context.ts b/packages/daemon/src/extensions/screenshot-context.ts
new file mode 100644
index 0000000..3b37093
--- /dev/null
+++ b/packages/daemon/src/extensions/screenshot-context.ts
@@ -0,0 +1,77 @@
+/**
+ * Keeps computer-control screenshots from piling up in every model call (S24.10).
+ *
+ * The engine resends the whole history on each call, so a long control session carried every
+ * screenshot it ever took. Only the last one is sent as an image; each earlier one becomes a
+ * one-line entry in its place, built from what the tool already returned (no extra model calls).
+ * The saved session keeps every image: this only shapes what one request carries.
+ */
+
+const COMPUTER_TOOL = "mcp__computer__";
+
+interface Block {
+ type: string;
+ text?: string;
+}
+
+interface Message {
+ role?: string;
+ toolName?: string;
+ content?: unknown;
+}
+
+function isScreenshotResult(message: Message): boolean {
+ return (
+ message.role === "toolResult" &&
+ typeof message.toolName === "string" &&
+ message.toolName.startsWith(COMPUTER_TOOL) &&
+ Array.isArray(message.content) &&
+ message.content.some((block: Block) => block?.type === "image")
+ );
+}
+
+/** The front app from the helper's metadata block, when there is one. */
+function frontApp(content: Block[]): string | undefined {
+ for (const block of content) {
+ if (block.type !== "text" || !block.text?.startsWith("{")) continue;
+ try {
+ const app = JSON.parse(block.text).frontApp;
+ if (typeof app === "string" && app) return app;
+ } catch {
+ // Not the metadata block.
+ }
+ }
+ return undefined;
+}
+
+function isMetadata(block: Block): boolean {
+ return block.type === "text" && frontApp([block]) !== undefined;
+}
+
+function logLine(message: Message, content: Block[]): Block {
+ const tool = (message.toolName ?? "").slice(COMPUTER_TOOL.length) || "action";
+ const app = frontApp(content);
+ return { type: "text", text: `[earlier screenshot omitted: ${tool}${app ? ` in ${app}` : ""}]` };
+}
+
+/**
+ * The messages for one model call: every computer screenshot but the last is replaced by a log
+ * line, keeping the action's own text. Returns the input array itself when nothing changes.
+ */
+export function pruneScreenshots<T extends Message>(messages: T[]): T[] {
+ let last = -1;
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const message = messages[i];
+ if (message && isScreenshotResult(message)) {
+ last = i;
+ break;
+ }
+ }
+ if (last < 0 || !messages.slice(0, last).some(isScreenshotResult)) return messages;
+ return messages.map((message, i) => {
+ if (i === last || !isScreenshotResult(message)) return message;
+ const content = message.content as Block[];
+ const kept = content.filter((block) => block.type !== "image" && !isMetadata(block));
+ return { ...message, content: [...kept, logLine(message, content)] };
+ });
+}
diff --git a/packages/daemon/src/runtime-build.ts b/packages/daemon/src/runtime-build.ts
index 3e4126b..fb9de89 100644
--- a/packages/daemon/src/runtime-build.ts
+++ b/packages/daemon/src/runtime-build.ts
@@ -88,10 +88,10 @@ export async function buildRuntime(outDir: string): Promise<void> {
chmodSync(join(daemon, "cli.mjs"), 0o755);
// The bundle finds these through `import.meta.url`, as the sources do in `src/`.
copyFileSync(join(PACKAGE, "src", "identity.md"), join(daemon, "identity.md"));
- copyFileSync(
- join(PACKAGE, "src", "extensions", "approval-guard.ts"),
- join(daemon, "extensions", "approval-guard.ts"),
- );
+ // The engine loads the guard with -e, and the guard imports its siblings.
+ for (const name of ["approval-guard.ts", "screenshot-context.ts"]) {
+ copyFileSync(join(PACKAGE, "src", "extensions", name), join(daemon, "extensions", name));
+ }
const manifest = { name: "gentle-dot-runtime", private: true, type: "module", dependencies };
writeFileSync(join(daemon, "package.json"), `${JSON.stringify(manifest, null, "\t")}\n`);
writeFileSync(join(outDir, "bin", "pi"), piWrapper(engineEntry()), { mode: 0o755 });
diff --git a/packages/daemon/test/approval-guard.test.ts b/packages/daemon/test/approval-guard.test.ts
index a316ec4..9d0034a 100644
--- a/packages/daemon/test/approval-guard.test.ts
+++ b/packages/daemon/test/approval-guard.test.ts
@@ -426,3 +426,32 @@ describe("approval guard extension", () => {
expect(result).toEqual({ block: true, reason: expect.stringContaining("Connectors screen") });
});
});
+
+describe("screenshots in the model's context (S24.10)", () => {
+ it("hooks the context event so each model call carries only the last screenshot", async () => {
+ const context: ((event: { messages: unknown[] }) => unknown)[] = [];
+ const pi = {
+ on(event: string, handler: (event: { messages: unknown[] }) => unknown) {
+ if (event === "context") context.push(handler);
+ },
+ getAllTools: () => [],
+ registerTool: () => {},
+ };
+ approvalGuard(pi as never);
+ const shot = (data: string) => ({
+ role: "toolResult",
+ toolCallId: data,
+ toolName: "mcp__computer__screenshot",
+ content: [{ type: "image", data, mimeType: "image/jpeg" }],
+ isError: false,
+ });
+ const [hook] = context;
+ expect(context).toHaveLength(1);
+ if (!hook) return;
+ const result = (await hook({ messages: [shot("OLD"), shot("NEW")] })) as {
+ messages: { content: { type: string }[] }[];
+ };
+ const types = result.messages.map((message) => message.content.map((block) => block.type));
+ expect(types).toEqual([["text"], ["image"]]);
+ });
+});
diff --git a/packages/daemon/test/runtime-build.test.ts b/packages/daemon/test/runtime-build.test.ts
index abf2c38..0916c93 100644
--- a/packages/daemon/test/runtime-build.test.ts
+++ b/packages/daemon/test/runtime-build.test.ts
@@ -42,6 +42,7 @@ describe("build:runtime", () => {
"bin/pi",
"daemon/cli.mjs",
"daemon/extensions/approval-guard.ts",
+ "daemon/extensions/screenshot-context.ts",
"daemon/identity.md",
"daemon/package.json",
]);
diff --git a/packages/daemon/test/screenshot-context.test.ts b/packages/daemon/test/screenshot-context.test.ts
new file mode 100644
index 0000000..9234836
--- /dev/null
+++ b/packages/daemon/test/screenshot-context.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it } from "vitest";
+import { pruneScreenshots } from "../src/extensions/screenshot-context.ts";
+
+const image = (data: string) => ({ type: "image", data, mimeType: "image/jpeg" });
+const meta = (frontApp: string) => ({
+ type: "text",
+ text: JSON.stringify({ frontApp, imageHeight: 720, imageWidth: 1280, scale: 0.5 }),
+});
+const result = (tool: string, content: object[]) => ({
+ role: "toolResult",
+ toolCallId: `${tool}-${content.length}`,
+ toolName: `mcp__computer__${tool}`,
+ content,
+ isError: false,
+});
+
+describe("pruneScreenshots (S24.10)", () => {
+ it("keeps only the last screenshot as an image and logs each earlier one as a line", () => {
+ const messages = [
+ { role: "user", content: [{ type: "text", text: "open Safari" }] },
+ result("screenshot", [image("AAA"), meta("Finder")]),
+ result("click", [
+ { type: "text", text: "Click at (412, 230) in Safari: done." },
+ image("BBB"),
+ meta("Safari"),
+ ]),
+ result("screenshot", [image("CCC"), meta("Safari")]),
+ ];
+ const pruned = pruneScreenshots(messages);
+
+ expect(pruned[1]).toEqual({
+ ...messages[1],
+ content: [{ type: "text", text: "[earlier screenshot omitted: screenshot in Finder]" }],
+ });
+ expect(pruned[2]).toEqual({
+ ...messages[2],
+ content: [
+ { type: "text", text: "Click at (412, 230) in Safari: done." },
+ { type: "text", text: "[earlier screenshot omitted: click in Safari]" },
+ ],
+ });
+ expect(pruned[3]).toBe(messages[3]);
+ expect(pruned[0]).toBe(messages[0]);
+ });
+
+ it("leaves the history it was given untouched", () => {
+ const first = result("screenshot", [image("AAA"), meta("Finder")]);
+ const messages = [first, result("screenshot", [image("BBB"), meta("Mail")])];
+ const before = JSON.stringify(messages);
+ pruneScreenshots(messages);
+ expect(JSON.stringify(messages)).toBe(before);
+ });
+
+ it("never touches images that are not computer screenshots", () => {
+ const pasted = { role: "user", content: [{ type: "text", text: "look" }, image("USER")] };
+ const other = {
+ role: "toolResult",
+ toolName: "read",
+ toolCallId: "r",
+ content: [image("FILE")],
+ isError: false,
+ };
+ const messages = [pasted, other, result("screenshot", [image("AAA"), meta("Finder")])];
+ const pruned = pruneScreenshots(messages);
+ expect(pruned[0]).toBe(pasted);
+ expect(pruned[1]).toBe(other);
+ expect(pruned[2]).toBe(messages[2]);
+ });
+
+ it("returns the same array when there is at most one screenshot", () => {
+ const messages = [{ role: "user", content: "hi" }, result("screenshot", [image("AAA"), meta("Finder")])];
+ expect(pruneScreenshots(messages)).toBe(messages);
+ });
+});