Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Bring the files a routine sent into its report, without the images its tools returned

Xiaolei Shi973564c1a4d8
diff --git a/server/automation-reports.e2e.test.ts b/server/automation-reports.e2e.test.ts
index 6fa87b5706..1ae818228a 100644
--- a/server/automation-reports.e2e.test.ts
+++ b/server/automation-reports.e2e.test.ts
@@ -1,6 +1,6 @@
// Automations report into the bot's chat, end to end: the real server and Claude driver, the scripted fake engine
// answering each turn by what it was sent, and the permission broker reached the way the CLI's proxy reaches it.
-import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { connect, type Socket } from "node:net";
import { join } from "node:path";
import { afterEach, expect, it } from "vitest";
@@ -417,3 +417,20 @@ it("tells the main chat about a run missed while the computer was off, which has
await restartable.close();
}
}, 120_000);
+
+it("brings the files a run sent with attach_file into its report", async () => {
+ const s = await server();
+ const folder = join(s.dataDir, "workspaces", s.bot.id);
+ mkdirSync(folder, { recursive: true });
+ writeFileSync(join(folder, "brief.pdf"), "%PDF-brief");
+ s.script([{
+ key: "run", match: [s.header("Daily brief")], steps: [{ tool: "attach_file", arguments: { path: join(folder, "brief.pdf") } }],
+ reply: "Today's brief is attached.",
+ }]);
+ const id = await s.runNow(await s.routine("Daily brief"));
+ await s.settled(id);
+ await s.reported(id, "posted");
+ expect(await s.lines()).toEqual([expect.objectContaining({
+ text: "Today's brief is attached.", attachments: [expect.objectContaining({ kind: "file", name: "brief.pdf" })],
+ })]);
+}, 120_000);
diff --git a/server/automation-reports.test.ts b/server/automation-reports.test.ts
index b53260144c..0fe0fedc57 100644
--- a/server/automation-reports.test.ts
+++ b/server/automation-reports.test.ts
@@ -441,6 +441,35 @@ describe("automation reports", () => {
expect(f.lines()).toEqual([expect.objectContaining({ text: "Here is this week's report.", attachments })]);
});
+ it("carries the files the run's last turn sent, in order, and not the images its tools returned", () => {
+ const f = fixture();
+ const run = f.finished(null);
+ const thread = run.threadId!;
+ const earlier = { kind: "file" as const, path: "old.pdf", mime: "application/pdf", name: "Old.pdf" };
+ const pdf = { kind: "file" as const, path: "brief-1.pdf", mime: "application/pdf", name: "Brief.pdf" };
+ const mp3 = { kind: "file" as const, path: "brief-1.mp3", mime: "audio/mpeg", name: "Brief.mp3" };
+ const page = { kind: "image" as const, path: "page-1.png", mime: "image/png", fromTool: true as const };
+ const drawn = { kind: "image" as const, path: "chart-1.png", mime: "image/png" };
+ const note = { kind: "audio" as const, path: "note-1.ogg", mime: "audio/ogg", text: "Today's brief." };
+ f.store.appendMessage(thread, { role: "bot", kind: "text", text: "", attachments: [earlier] });
+ f.store.appendMessage(thread, { role: "user", kind: "text", text: "Go on." });
+ f.store.appendMessage(thread, { role: "bot", kind: "text", text: "", attachments: [pdf] });
+ f.store.appendMessage(thread, { role: "bot", kind: "text", text: "", attachments: [mp3] });
+ f.store.appendMessage(thread, { role: "bot", kind: "text", text: "Your brief.", attachments: [page, drawn, note], turnId: `turn-${run.id}`, turnTerminal: true });
+ f.reports.runSettled(run, `turn-${run.id}`);
+ expect(f.lines()).toEqual([expect.objectContaining({ text: "Your brief.", attachments: [pdf, mp3, drawn, note] })]);
+ });
+
+ it("keeps a run quiet that said nothing and sent nothing, though its tools returned images", () => {
+ const f = fixture();
+ const run = f.finished(null);
+ const page = { kind: "image" as const, path: "page-1.png", mime: "image/png", fromTool: true as const };
+ f.store.appendMessage(run.threadId!, { role: "bot", kind: "text", text: "", attachments: [page], turnId: `turn-${run.id}`, turnTerminal: true });
+ f.reports.runSettled(run, `turn-${run.id}`);
+ expect(f.added()).toEqual([]);
+ expect(f.runs.get(run.id)!.report).toEqual({ state: "quiet" });
+ });
+
it("reads a report still waiting after a restart again, and writes nothing if the run's last reply had nothing new", () => {
const f = fixture();
const run = f.finished("Checked again.\nNOTHING NEW");
diff --git a/server/automation-reports.ts b/server/automation-reports.ts
index 209b40dc71..8d1e9f62a4 100644
--- a/server/automation-reports.ts
+++ b/server/automation-reports.ts
@@ -122,7 +122,18 @@ export function createAutomationReports(deps: AutomationReportDeps) {
return messageId ? path.find((message) => message.id === messageId) : path.findLast((message) => said(message) && message.turnTerminal) ?? path.findLast(said);
};
- const read = (message: Message | undefined) => readRunReply(message?.text ?? "", Boolean(message?.attachments?.length));
+ /** The files the reply's turn sent the person, in order: its attach_file lines' and the reply's own, without the
+ * images its tools returned. */
+ const sentWith = (run: RoutineRun, reply: Message | undefined): NonNullable<Message["attachments"]> => {
+ if (!reply) return [];
+ const path = store.activePath(run.threadId!);
+ const end = path.findIndex((message) => message.id === reply.id);
+ const turn = path.slice(path.findLastIndex((message, at) => at < end && message.role === "user") + 1, end + 1);
+ return turn.flatMap((message) => message.role === "bot" && message.kind === "text" ? message.attachments ?? [] : [])
+ .filter((file) => file.kind !== "image" || !file.fromTool);
+ };
+
+ const read = (run: RoutineRun, message: Message | undefined) => readRunReply(message?.text ?? "", sentWith(run, message).length > 0);
/** The automation's line before this run's in the chat, written or still waiting ahead of it, says a run failed. */
const lastSaidFailed = (run: RoutineRun, threadId: string): boolean => {
@@ -171,7 +182,7 @@ export function createAutomationReports(deps: AutomationReportDeps) {
}
const source = line.kind === "reply" ? replyOf(run, line.messageId) : undefined;
const language = deps.threadLanguage?.(target.threadId);
- const said: RunReply = line.kind === "reply" ? read(source)
+ const said: RunReply = line.kind === "reply" ? read(run, source)
: { quiet: false, text: line.detail ? serverLine(language, run.partial ? "server.runs.partlyDoneWhy" : "server.runs.didNotFinishWhy", { detail: line.detail }) : serverLine(language, "server.runs.didNotFinish") };
const recovered = said.quiet && lastSaidFailed(run, target.threadId);
if (said.quiet && !recovered) {
@@ -179,9 +190,10 @@ export function createAutomationReports(deps: AutomationReportDeps) {
return true;
}
const reply: Extract<RunReply, { quiet: false }> = said.quiet ? { quiet: false, text: recoveredText(run.routineName, run.finishedAt ?? Date.now(), language) } : said;
+ const files = recovered ? [] : sentWith(run, source);
const posted = store.appendMessage(target.threadId, {
role: "bot", kind: "text", text: reply.text,
- ...(source?.attachments?.length && !recovered ? { attachments: source.attachments } : {}),
+ ...(files.length ? { attachments: files } : {}),
automation: lineOf(run, line.kind === "failure" ? { failed: true, ...(run.partial ? { partial: true as const } : {}) } : recovered ? { recovered: true } : reply.question ? { needsYou: true } : {}),
});
deps.routines()?.noteReport(run.id, { state: "posted", threadId: target.threadId, messageId: posted.id });
@@ -245,7 +257,7 @@ export function createAutomationReports(deps: AutomationReportDeps) {
if (run.target !== "bot" || run.status !== "completed" || !run.threadId) return;
if (run.deliver === "brief") return deps.brief?.(run, turnId);
const said = turnId ? store.activePath(run.threadId).findLast((message) => message.role === "bot" && message.kind === "text" && message.turnId === turnId) : replyOf(run);
- const reply = read(said);
+ const reply = read(run, said);
const bot = store.bot(run.botId);
const target = destination(run);
if (target && (!reply.quiet || lastSaidFailed(run, target.threadId))) hold(run.id, { kind: "reply", run, ...(said ? { messageId: said.id } : {}) });
diff --git a/server/drivers/acp/acp.test.ts b/server/drivers/acp/acp.test.ts
index b97d061aff..3f586c6ae2 100644
--- a/server/drivers/acp/acp.test.ts
+++ b/server/drivers/acp/acp.test.ts
@@ -385,6 +385,7 @@ describe("ACP turns (fake CLI)", () => {
const failedEnd = recorder.events.findIndex((e) => e.type === "item.completed" && e.itemType === "tool" && e.itemId === started[4]);
const image = recorder.events.findIndex((e) => e.type === "item.completed" && e.itemType === "assistant_image");
expect(image).toBe(failedEnd + 1);
+ expect(recorder.events[image]).toMatchObject({ fromTool: true });
// The stall watchdog sees no tool left running, so the turn's own silence limit applies.
let now = 0;
const limits: number[] = [];
@@ -1014,6 +1015,7 @@ describe("ACP turns (fake CLI)", () => {
itemType: "assistant_image",
alt: "Generated image",
});
+ expect(image).not.toHaveProperty("fromTool");
expect(image && "data" in image ? image.data : "").toMatch(/^iVBOR/);
expect(
recorder.events.some(
diff --git a/server/drivers/acp/tool-items.ts b/server/drivers/acp/tool-items.ts
index 149a2520ef..706a156fb2 100644
--- a/server/drivers/acp/tool-items.ts
+++ b/server/drivers/acp/tool-items.ts
@@ -3,7 +3,7 @@ import { toolDetailPreview } from "../../tool-summary.ts";
export type AcpToolEndEvent = { type: "item.completed" } & (
| { itemType: "tool"; itemId: string | undefined; ok: boolean; output?: string }
- | { itemType: "assistant_image"; data: string }
+ | { itemType: "assistant_image"; data: string; fromTool: true }
);
/**
@@ -21,6 +21,6 @@ export function acpToolEndEvents(
}
return [
{ type: "item.completed", itemType: "tool", itemId, ok: update.status !== "failed", output: toolDetailPreview(update.rawOutput ?? update.content) },
- ...extractMcpImages(update.content ?? update.rawOutput).map((img): AcpToolEndEvent => ({ type: "item.completed", itemType: "assistant_image", data: img.data })),
+ ...extractMcpImages(update.content ?? update.rawOutput).map((img): AcpToolEndEvent => ({ type: "item.completed", itemType: "assistant_image", data: img.data, fromTool: true })),
];
}
diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.ts
index 5ad142ec01..d762cfa4a5 100644
--- a/server/drivers/claude.test.ts
+++ b/server/drivers/claude.test.ts
@@ -592,6 +592,18 @@ describe("ClaudeDriver turns (fake CLI)", () => {
expect(beat).toBeLessThan(types.lastIndexOf("item.completed"));
});
+ it("marks an image a tool's result returned as the tool's", async () => {
+ const data = Buffer.from([0x89, 0x50, 0x4e, 0x47, 1, 2, 3]).toString("base64");
+ await create(undefined, {
+ FAKE_CLAUDE_TOOL_CALLS: JSON.stringify([{ name: "Read", input: { file_path: "brief.pdf" }, output: [{ type: "image", source: { type: "base64", media_type: "image/png", data } }] }]),
+ });
+ await instance.adapter.sendTurn({ threadId: "t-tool-image", text: "check the brief" });
+ await recorder.until((e) => e.type === "turn.completed");
+ expect(recorder.events.filter((e) => e.type === "item.completed" && e.itemType === "assistant_image")).toEqual([
+ expect.objectContaining({ data, fromTool: true }),
+ ]);
+ });
+
it("names the CLI process while a long tool runs, and no process once the turn is over", async () => {
const release = join(scratch, "release");
await create(undefined, {
diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts
index cd6e014fb6..a26b6a7e40 100644
--- a/server/drivers/claude.ts
+++ b/server/drivers/claude.ts
@@ -1571,7 +1571,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
if (b.type === "tool_result") {
emit({ ...base(threadId, currentTurnId()), type: "item.completed", itemType: "tool", itemId: b.tool_use_id, ok: !b.is_error, output: toolDetailPreview(b.content) });
for (const img of extractMcpImages(b.content)) {
- emit({ ...base(threadId, currentTurnId()), type: "item.completed", itemType: "assistant_image", data: img.data });
+ emit({ ...base(threadId, currentTurnId()), type: "item.completed", itemType: "assistant_image", data: img.data, fromTool: true });
}
}
}
diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.ts
index 776702f291..8006512150 100644
--- a/server/drivers/codex.test.ts
+++ b/server/drivers/codex.test.ts
@@ -1086,6 +1086,17 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
});
expect(image && "data" in image ? image.data : "").toMatch(/^iVBOR/);
expect(JSON.stringify(image)).not.toContain("provider-owned-path");
+ expect(image).not.toHaveProperty("fromTool");
+ });
+
+ it("marks an image an MCP tool's result returned as the tool's", async () => {
+ process.env.FAKE_CODEX_MODE = "mcp-image";
+ await create();
+ await instance.adapter.sendTurn({ threadId: "t-mcp-image", text: "take a screenshot" });
+ await recorder.until((event) => event.type === "turn.completed");
+ expect(recorder.events.filter((event) => event.type === "item.completed" && event.itemType === "assistant_image")).toEqual([
+ expect.objectContaining({ data: "iVBORw0KGgo=", fromTool: true }),
+ ]);
});
it("keeps the full command when a Windows interpreter prefix is long", async () => {
diff --git a/server/drivers/codex.ts b/server/drivers/codex.ts
index dd2ef41497..6cfe22b906 100644
--- a/server/drivers/codex.ts
+++ b/server/drivers/codex.ts
@@ -1172,7 +1172,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
});
if (item.type === "mcpToolCall") {
for (const img of extractMcpImages(item.result)) {
- emit({ ...base(threadId, turnId), type: "item.completed", itemType: "assistant_image", data: img.data });
+ emit({ ...base(threadId, turnId), type: "item.completed", itemType: "assistant_image", data: img.data, fromTool: true });
}
}
} else if (item.type === "reasoning") {
diff --git a/server/index.ts b/server/index.ts
index 3424b19329..70822f0903 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -6449,7 +6449,7 @@ bus.subscribe((event: RuntimeEvent) => {
const saved = saveImage(decoded.bytes, decoded.mime);
const key = turnAttachmentKey(event.threadId, event.turnId);
const current = turnAttachmentsByTurn.get(key) ?? [];
- current.push({ kind: "image", path: saved.path, mime: saved.mime });
+ current.push({ kind: "image", path: saved.path, mime: saved.mime, ...(event.fromTool ? { fromTool: true as const } : {}) });
turnAttachmentsByTurn.set(key, current);
} catch (error) {
pushMessage({
diff --git a/server/testing/fake-codex-app-server.ts b/server/testing/fake-codex-app-server.ts
index 963353cea8..3b57a6323c 100755
--- a/server/testing/fake-codex-app-server.ts
+++ b/server/testing/fake-codex-app-server.ts
@@ -5,7 +5,7 @@
// mcp-app-approval | mcp-form | permissions-approval | question | multi-question | mixed-question |
// empty-question | malformed-question | config-profile | config-profile-unsupported | config-read-error |
// image | logged-in-stdout | logged-out | unauthorized | late-request | retry-then-complete | signin-refused |
-// auth-recovery | mcp-401 | legacy-error | key-401 | recovered-403 | recovered-401 | recovering-403 | usage-limit
+// auth-recovery | mcp-401 | mcp-image | legacy-error | key-401 | recovered-403 | recovered-401 | recovering-403 | usage-limit
// | async-question (an agentMessage with delivery async and questions, as codex 0.160 sends request_user_input_async)
// FAKE_CODEX_MISSING_BEARER the first N launches fail their turn as codex-cli 0.160.1 holding no login does (count in FAKE_CODEX_STATE)
// FAKE_CODEX_LAUNCH_CRASHES the first N launches die pre-ack at turn/start, transient stderr, exit 1 (count in FAKE_CODEX_STATE)
@@ -747,6 +747,12 @@ process.stdin.on("data", (chunk) => {
finishTurn();
break;
}
+ if (mode === "mcp-image") {
+ out({ jsonrpc: "2.0", id: msg.id, result: { turn: { id: nativeTurnId } } });
+ notify("item/completed", { item: { id: "t1", type: "mcpToolCall", tool: "screenshot", status: "completed", result: { content: [{ type: "image", data: "iVBORw0KGgo=", mimeType: "image/png" }] } } });
+ finishTurn();
+ break;
+ }
if (mode === "legacy-error") {
out({ jsonrpc: "2.0", id: msg.id, result: { turn: { id: nativeTurnId } } });
notify("error", { message: "stream disconnected before completion" });
diff --git a/shared/runtime-events.ts b/shared/runtime-events.ts
index 5cd6c866a1..5a088164c9 100644
--- a/shared/runtime-events.ts
+++ b/shared/runtime-events.ts
@@ -122,8 +122,9 @@ export type RuntimeEvent = RuntimeEventBase &
| { type: "item.completed"; itemType: "tool"; ok: boolean; output?: string }
| { type: "item.completed"; itemType: "assistant_text"; text: string }
/** Provider-generated raster bytes, folded into the private attachment
- * store and never forwarded to renderer SSE. */
- | { type: "item.completed"; itemType: "assistant_image"; data: string; alt?: string }
+ * store and never forwarded to renderer SSE. `fromTool`: a tool's result
+ * returned the image to the engine; the bot did not make or send it. */
+ | { type: "item.completed"; itemType: "assistant_image"; data: string; alt?: string; fromTool?: true }
| { type: "content.delta"; streamKind: "assistant_text" | "reasoning_text"; delta: string }
| {
type: "request.opened";
diff --git a/shared/wire.ts b/shared/wire.ts
index 89cd8e4dd5..31fa481ee2 100644
--- a/shared/wire.ts
+++ b/shared/wire.ts
@@ -466,9 +466,10 @@ export interface WireMessage extends ServerTextLine, HelperIntroField, SetupCard
by: "person" | "harness";
};
/** Renderers receive only the allowlisted /api/attachments URL. `file` entries are opened through the message-scoped
- * file route, never by path. `source`: a bot attach-file copy's original path on the server, for Show in folder. */
+ * file route, never by path. `source`: a bot attach-file copy's original path on the server, for Show in folder.
+ * `fromTool`: an image a tool's result returned while the bot worked, which it did not make or send. */
attachments?: Array<
- | { kind: "image"; path: string; mime: string; name?: string; source?: string }
+ | { kind: "image"; path: string; mime: string; name?: string; source?: string; fromTool?: true }
| { kind: "file"; path: string; mime: string; name: string; source?: string }
/** `text` is the words the note speaks (secret-redacted when stored): clients show it behind a
* collapsed transcript, never as message body, and the model's replay folds it back after `text`. */