Skip to content

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

Land every file a thread parked when its turn settles, and log where voice notes park (#4711)

Milind Soni24dfaeca67a3
diff --git a/server/host/turn-attachments.test.ts b/server/host/turn-attachments.test.ts
index 403283e6cf..723de392d2 100644
--- a/server/host/turn-attachments.test.ts
+++ b/server/host/turn-attachments.test.ts
@@ -2,7 +2,7 @@ import { expect, it, vi } from "vitest";
import { PERSON_STOPPED_TURN_NAME } from "../../shared/client-cancel.ts";
import { failedTurnTool } from "../../shared/failed-turn.ts";
import type { Message } from "../store.ts";
-import { landTurnFiles, settleParkedFiles } from "./turn-attachments.ts";
+import { landTurnFiles, parkedFilesKey, settleParkedFiles, takeParkedFiles } from "./turn-attachments.ts";
const image = { kind: "image" as const, path: "/a/one.png", mime: "image/png" };
const note = { kind: "audio" as const, path: "/a/two.mp3", mime: "audio/mpeg", text: " the token is sk-live-abc " };
@@ -71,3 +71,19 @@ it("appends that line when the turn ended without an error line, and does nothin
landTurnFiles(store, { threadId: "th", turnId: "t1", from: { botId: "b", name: "B", color: "#fff" } }, [audio], append);
expect(append).toHaveBeenCalledWith({ role: "bot", kind: "text", text: "", attachments: [audio], turnId: "t1", from: { botId: "b", name: "B", color: "#fff" } });
});
+
+it("takes a settling turn's own files and any the thread parked under another turn, and leaves other threads' alone", () => {
+ const one = { kind: "audio" as const, path: "/a/1.mp3", mime: "audio/mpeg" };
+ const two = { kind: "image" as const, path: "/a/2.png", mime: "image/png" };
+ const three = { kind: "audio" as const, path: "/a/3.mp3", mime: "audio/mpeg" };
+ const other = { kind: "audio" as const, path: "/a/4.mp3", mime: "audio/mpeg" };
+ const parked = new Map([
+ [parkedFilesKey("th", "t2"), [one]],
+ [parkedFilesKey("th"), [two]],
+ [parkedFilesKey("th", "t1"), [three]],
+ [parkedFilesKey("th-2", "t9"), [other]],
+ ]);
+ expect(takeParkedFiles(parked, "th", "t2")).toEqual({ files: [one, two, three], strays: ["active", "t1"] });
+ expect([...parked.keys()]).toEqual([parkedFilesKey("th-2", "t9")]);
+ expect(takeParkedFiles(parked, "th", "t3")).toEqual({ files: [], strays: [] });
+});
diff --git a/server/host/turn-attachments.ts b/server/host/turn-attachments.ts
index 73de2af9ef..f500ea73aa 100644
--- a/server/host/turn-attachments.ts
+++ b/server/host/turn-attachments.ts
@@ -23,6 +23,31 @@ export function settleParkedFiles(
return { land, discard };
}
+/** Where a thread's turn parks its files until it settles. */
+export function parkedFilesKey(threadId: string, turnId?: string): string {
+ return `${threadId}:${turnId ?? "active"}`;
+}
+
+/** Takes what a settling turn parked, and with it anything parked on the thread under another turn: a thread runs one
+ * turn at a time, so a file parked under any other key would otherwise never reach the person. */
+export function takeParkedFiles(
+ parked: Map<string, ParkedTurnAttachment[]>,
+ threadId: string,
+ turnId: string | undefined,
+): { files: ParkedTurnAttachment[]; strays: string[] } {
+ const own = parkedFilesKey(threadId, turnId);
+ const files = [...parked.get(own) ?? []];
+ parked.delete(own);
+ const strays: string[] = [];
+ for (const [key, more] of parked) {
+ if (!key.startsWith(`${threadId}:`)) continue;
+ parked.delete(key);
+ files.push(...more);
+ strays.push(key.slice(threadId.length + 1));
+ }
+ return { files, strays };
+}
+
const endsTurn = (message: Message) => message.kind === "activity" && message.tool !== undefined
&& (failedTurnCause(message.tool.name) !== null || isStoppedTurnName(message.tool.name));
diff --git a/server/index.ts b/server/index.ts
index 4b7a78afc8..8114148379 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -10,7 +10,7 @@ import { homedir } from "node:os";
import { rm as removeDirectory } from "node:fs/promises";
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { ToolResults, TOOL_RESULT_MAX_CHARS } from "./tool-results.ts";
-import { join } from "node:path";
+import { basename, join } from "node:path";
import { authorizeExternalRuntime, externalRuntimeIsActive, type ExternalRuntimeGrant } from "./external-runtime.ts";
import { z } from "zod";
import { selectReplay, replayToolCalls, DEFAULT_REBUILD_BYTES, MAX_SUMMARY_BYTES } from "./context-rebuild.ts";
@@ -87,7 +87,7 @@ import { emailSignInRoute } from "./routes/email-sign-in.ts";
import { createPersonStop } from "./host/person-stop.ts";
import { createTurnOrder } from "./host/turn-order.ts";
import { createQueuedNotes, createWaitWords } from "./host/wait-words.ts";
-import { landTurnFiles, settleParkedFiles, type ParkedTurnAttachment } from "./host/turn-attachments.ts";
+import { landTurnFiles, parkedFilesKey, settleParkedFiles, takeParkedFiles, type ParkedTurnAttachment } from "./host/turn-attachments.ts";
import { createReplyVoiceNotes } from "./host/reply-voice-notes.ts";
import { runtimeRequestCardFields } from "./request-card.ts";
import type { DirectSendInput, DirectSendReceipt } from "./direct-send.ts";
@@ -2310,9 +2310,7 @@ const pendingCancelledProviderHandshakes = new PendingTurnCancellations();
const turnAttachmentsByTurn = new Map<string, Array<ParkedTurnAttachment>>();
-function turnAttachmentKey(threadId: string, turnId?: string): string {
- return `${threadId}:${turnId ?? "active"}`;
-}
+const turnAttachmentKey = parkedFilesKey;
function purgeTurnAttachmentsForThread(threadId: string): void {
for (const [key, attachments] of turnAttachmentsByTurn) {
@@ -6422,9 +6420,9 @@ bus.subscribe((event: RuntimeEvent) => {
lastReply.set(event.threadId, spoken.text);
};
const landParkedFiles = () => {
- const key = turnAttachmentKey(event.threadId, event.turnId);
- const { land, discard } = settleParkedFiles(turnAttachmentsByTurn.get(key) ?? [], redactSecretsInText, Boolean(goalCoordinatorTurn || ambiguousCoordinatorText));
- turnAttachmentsByTurn.delete(key);
+ const { files, strays } = takeParkedFiles(turnAttachmentsByTurn, event.threadId, event.turnId);
+ if (strays.length) console.warn(`[turn-files] thread=${event.threadId} turn=${event.turnId ?? "none"} took files parked under ${strays.join(", ")}`);
+ const { land, discard } = settleParkedFiles(files, redactSecretsInText, Boolean(goalCoordinatorTurn || ambiguousCoordinatorText));
for (const file of discard) deleteAttachment(file.path);
landTurnFiles(store, { threadId: event.threadId, turnId: completedTurnId, ...(speaker ? { from: speaker } : {}) }, land, pushMessage);
};
@@ -14434,7 +14432,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
const key = turnAttachmentKey(internalCapability.threadId, turnId);
const current = turnAttachmentsByTurn.get(key) ?? [];
current.push({ kind: "audio", path: saved.path, mime: saved.mime, text });
- turnAttachmentsByTurn.set(key, current);
+ turnAttachmentsByTurn.set(key, current); console.info(`[voice-note] parked thread=${internalCapability.threadId} turn=${turnId} file=${basename(saved.path)}`);
return json(res, 201, { attached: true });
} catch (error) {
const failure = voiceNoteFailure(error);
diff --git a/server/voice-notes-chat.e2e.test.ts b/server/voice-notes-chat.e2e.test.ts
index ea39a5f6a1..17c7122922 100644
--- a/server/voice-notes-chat.e2e.test.ts
+++ b/server/voice-notes-chat.e2e.test.ts
@@ -229,3 +229,31 @@ it("with a voice note on every reply, says by voice how a failed turn ended", as
await f.settle(bot, "Again.");
await expect.poll(async () => audioOf(await f.messages(bot.activeTaskId)).map((note) => note.file.text).at(-1), { timeout: 30_000 }).toBe("All good now.");
}), 90_000);
+
+it("attaches the note to the final reply of a long turn: folded first, said in between, two failed calls", async () => withChatVoice(async (f) => {
+ const bot = await f.newBot("Long turn voice bot");
+ await f.api("PATCH", `/api/bots/${bot.id}`, { voiceNoteEveryReply: true });
+ await f.api("PATCH", "/api/config", { context: { compactAt: 1 } });
+ f.script(() => say("Noted."));
+ for (const line of ["First older request.", "Second older request.", "Third older request."]) await f.settle(bot, line);
+ const step = (id: string, text: string, name: string, args: unknown) =>
+ frame({ content: text, tool_calls: [{ index: 0, id, type: "function", function: { name, arguments: JSON.stringify(args) } }] }, "tool_calls") + "data: [DONE]\n\n";
+ f.script((request) => {
+ const done = toolResults(request).length;
+ if (done === 0) return step("c1", "Voice note on its way…", "agents_send_voice_note", { text: "Here is the weekly summary." });
+ if (done === 1) return step("c2", "Looking at the numbers.", "agents_send_voice_note", { text: "" });
+ if (done === 2) return step("c3", "Trying another way.", "agents_list_bots", { unexpected: true });
+ if (done === 3) return step("c4", "Almost there.", "agents_list_bots", {});
+ return say("Voice note is attached to this reply.");
+ });
+ await f.settle(bot, "Summarise the week and send it as a voice note.");
+ const messages = await f.messages(bot.activeTaskId);
+ expect(messages.filter((message) => message.kind === "compaction").length).toBeGreaterThan(0);
+ const turn = messages.find((message) => message.text === "Voice note is attached to this reply.")?.turnId;
+ expect(turn).toBeTruthy();
+ const lines = messages.filter((message) => message.kind === "text" && message.turnId === turn);
+ expect(lines.length).toBeGreaterThan(1);
+ const failed = messages.filter((message) => message.kind === "activity" && message.turnId === turn && message.tool?.ok === false);
+ expect(failed.length).toBeGreaterThanOrEqual(1);
+ expect(audioOf(messages).filter((note) => note.message.turnId === turn).map((note) => [note.message.text, note.file.text])).toEqual([["Voice note is attached to this reply.", "Here is the weekly summary."]]);
+}), 120_000);