Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep a failed turn's voice note, as its images are kept
milind-soni5fd31f92b0e1
diff --git a/server/host/turn-attachments.test.ts b/server/host/turn-attachments.test.tsnew file mode 100644index 0000000000..d15f88cb69--- /dev/null+++ b/server/host/turn-attachments.test.ts@@ -0,0 +1,21 @@+import { expect, it } from "vitest";+import { settleParkedFiles } 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 " };+const redact = (text: string) => text.replace(/sk-live-\w+/, "[redacted]");++it("lands a failed turn's voice note with its images, its words kept as a redacted transcript", () => {+ expect(settleParkedFiles([image, note], false, redact)).toEqual({+ land: [image, { kind: "audio", path: "/a/two.mp3", mime: "audio/mpeg", text: "the token is [redacted]" }],+ discard: [],+ });+});++it("discards only the voice notes of a stopped turn", () => {+ expect(settleParkedFiles([image, note], true, redact)).toEqual({ land: [image], discard: [note] });+});++it("leaves no transcript on a note recorded without words", () => {+ expect(settleParkedFiles([{ ...note, text: " " }], false, redact).land).toEqual([{ kind: "audio", path: "/a/two.mp3", mime: "audio/mpeg" }]);+});diff --git a/server/host/turn-attachments.ts b/server/host/turn-attachments.tsnew file mode 100644index 0000000000..2172aebb4b--- /dev/null+++ b/server/host/turn-attachments.ts@@ -0,0 +1,21 @@+// The files a turn parked while it ran (generated images, recorded voice notes), and what becomes of them when it settles.+import type { Message } from "../store.ts";++export type ParkedTurnAttachment = NonNullable<Message["attachments"]>[number];++/** A turn the person stopped loses the voice notes it recorded; every other turn, a failed one included, keeps all its+ * files. A note's words stay on it as its transcript, redacted. */+export function settleParkedFiles(+ parked: readonly ParkedTurnAttachment[],+ stopped: boolean,+ redact: (text: string) => string,+): { land: ParkedTurnAttachment[]; discard: ParkedTurnAttachment[] } {+ const land: ParkedTurnAttachment[] = [];+ const discard: ParkedTurnAttachment[] = [];+ for (const file of parked) {+ if (file.kind !== "audio") land.push(file);+ else if (stopped) discard.push(file);+ else land.push({ kind: "audio", path: file.path, mime: file.mime, ...(file.text?.trim() ? { text: redact(file.text.trim()) } : {}) });+ }+ return { land, discard };+}diff --git a/server/index.ts b/server/index.tsindex 8d66da0e6f..99326222f3 100644--- a/server/index.ts+++ b/server/index.ts@@ -80,7 +80,7 @@ import { groupTurnCwd } from "./room-cwd.ts";import { RoomTurnDeadline, RoomTurnStallRegistry, effectiveRoomTurnTimeoutMinutes, parseConversationTurnTimeout, roomTurnTimeoutMessage } from "./room-turn-timeout.ts";import { roomTurnEnd, type RoomClaimEnd } from "./room-turn-end.ts";import { applyHoldDirective, classifyHoldDirective, heldMemberLine, rememberHeldMessage, stopWordPlacement } from "./room-holds.ts";-import { createPersonStop } from "./host/person-stop.ts"; import type { DirectSendInput, DirectSendReceipt } from "./direct-send.ts";+import { createPersonStop } from "./host/person-stop.ts"; import { settleParkedFiles, type ParkedTurnAttachment } from "./host/turn-attachments.ts"; import type { DirectSendInput, DirectSendReceipt } from "./direct-send.ts";import { finishedWithoutSummaryLine, ROOM_SUMMARY_REASK, roomTurnNarrationIds, roomTurnReply } from "./room-reply.ts";import { pickComputer } from "./computer-selection.ts";import * as boat from "./boat.ts"; import { keyHint, keyStatus, nestedKeyStatus, withoutKeyHints } from "./key-hint.ts";@@ -2338,7 +2338,6 @@ async function interruptAllDirectThreads(botId: string): Promise<void> {}const retiredProviderTurns = new RetiredTurnRegistry();const pendingCancelledProviderHandshakes = new PendingTurnCancellations();-type ParkedTurnAttachment = NonNullable<Message["attachments"]>[number];const turnAttachmentsByTurn = new Map<string, Array<ParkedTurnAttachment>>();@@ -6452,6 +6451,16 @@ bus.subscribe((event: RuntimeEvent) => {pushMessage({ role: "bot", kind: "text", text: spoken.text, turnId });lastReply.set(event.threadId, spoken.text);};+ const landParkedFiles = (stopped: boolean) => {+ const key = turnAttachmentKey(event.threadId, event.turnId);+ const { land, discard } = settleParkedFiles(turnAttachmentsByTurn.get(key) ?? [], stopped, redactSecretsInText);+ turnAttachmentsByTurn.delete(key);+ for (const file of discard) deleteAttachment(file.path);+ if (!land.length) return;+ const response = store.messagesFor(event.threadId).findLast((message) => message.role === "bot" && message.kind === "text" && message.turnId === completedTurnId);+ if (response) store.patchMessage(event.threadId, response.id, { attachments: [...(response.attachments ?? []), ...land] });+ else pushMessage({ role: "bot", kind: "text", text: "", attachments: land, turnId: completedTurnId });+ };if (coordinatorVisibleText) pushAssistantText(coordinatorVisibleText, completedTurnId);if (bot) handoffs.onEvent(event); else roomSessions.onEvent(event);@@ -6736,11 +6745,8 @@ bus.subscribe((event: RuntimeEvent) => {pushStoppedTurn(event.turnId);break;}- pushMessage({- role: "bot",- kind: "activity",- tool: failedTurnTool(event.message, event),- });+ landParkedFiles(false); // above the failure row, which stays the last, retryable line+ pushMessage({ role: "bot", kind: "activity", tool: failedTurnTool(event.message, event) });if (event.setup && bot) store.setTaskActivity(bot.id, event.threadId, "dead");break;case "thread.token-usage.updated":@@ -6754,49 +6760,11 @@ bus.subscribe((event: RuntimeEvent) => {const internal = isInternalTurn(event.threadId);clearInternalTurn(event.threadId);const reviewAnswer = reviewAnswerThreads.delete(event.threadId);- const generatedKey = turnAttachmentKey(event.threadId, event.turnId);- const generated = turnAttachmentsByTurn.get(generatedKey) ?? [];- turnAttachmentsByTurn.delete(generatedKey);- for (const attachment of generated) {- if (event.ok || attachment.kind !== "audio") continue;- deleteAttachment(attachment.path);- }- const settled = event.ok || !generated.length- ? generated- : generated.filter((attachment) => attachment.kind !== "audio");- if (settled.length) {- const response = [...store.messagesFor(event.threadId)].reverse().find(- (message) =>- message.role === "bot" &&- message.kind === "text" &&- message.turnId === completedTurnId,- );- // A note's words stay on its attachment as the transcript, never appended to the reply: every client- // would otherwise read the reply twice. The model still sees them after the text (contextText).- const staged = settled.map((attachment) =>- attachment.kind === "audio"- ? {- kind: "audio" as const,- path: attachment.path,- mime: attachment.mime,- ...(attachment.text?.trim() ? { text: redactSecretsInText(attachment.text.trim()) } : {}),- }- : attachment,- );- if (response) {- store.patchMessage(event.threadId, response.id, {- attachments: [...(response.attachments ?? []), ...staged],- });- } else {- pushMessage({- role: "bot",- kind: "text",- text: "",- attachments: staged,- turnId: completedTurnId,- });- }- }+ const stoppedTurnId = stoppedTurns.get(event.threadId);+ const clientStopped = personStops.stopped(event.threadId, completedTurnId) || (stoppedTurns.has(event.threadId)+ && (stoppedTurnId === undefined || completedTurnId === undefined || stoppedTurnId === completedTurnId));+ const stopped = event.stopReason === "interrupted" || clientStopped;+ landParkedFiles(!event.ok && stopped);if (completedTurnId) {const terminal = store.markTerminalAssistantMessage(event.threadId, completedTurnId);if (terminal) store.patchMessage(event.threadId, terminal.id, { turnSucceeded: event.ok });@@ -6808,11 +6776,7 @@ bus.subscribe((event: RuntimeEvent) => {if (personStops.stopped(event.threadId, completedTurnId)) pushStoppedTurn(completedTurnId);personStops.turnEnded(event.threadId, completedTurnId);lastReply.delete(event.threadId);- const stoppedTurnId = stoppedTurns.get(event.threadId);- const clientStopped = stoppedTurns.has(event.threadId)- && (stoppedTurnId === undefined || completedTurnId === undefined || stoppedTurnId === completedTurnId);stoppedTurns.delete(event.threadId);- const stopped = event.stopReason === "interrupted" || clientStopped;// Claude settles a lazy-claim interrupt as exit_before_result, not "interrupted": this generation's marker keeps it from reporting a second incident.const lazyClaimAlreadyReported = event.stopReason === "exit_before_result" &&turnResourceOwners.get(event.threadId)?.lazyClaimFailureReported === true;diff --git a/server/voice-notes.e2e.test.ts b/server/voice-notes.e2e.test.tsindex ccecf0e4ce..9e3bd4bf1e 100644--- a/server/voice-notes.e2e.test.ts+++ b/server/voice-notes.e2e.test.ts@@ -340,6 +340,52 @@ it("keeps the parked note when the room-post append fails, so a retry can attachexpect(audio.path.endsWith(f.mp3Files()[0])).toBe(true);}, { failFirstAudioAppend: true }), 60_000);+it("keeps a failed turn's voice note above its failure row, and still deletes a stopped turn's", async () => withVoiceFixture(async (f) => {+ const baseUrl = await f.serveTts();+ await f.api("/api/config", { tts: { provider: "chatterbox", baseUrl, voice: "voice-a" } }, "PUT");+ const replying = (await f.cli("new-bot", "--name", "Failing reply bot")).bot;+ const quiet = (await f.cli("new-bot", "--name", "Failing quiet bot")).bot;+ const stopped = (await f.cli("new-bot", "--name", "Stopped note bot")).bot;+ const gate = join(f.dataDir, "stopped-note-gate");+ const replyNote = "Status: the first half of the export is done.";+ const quietNote = "Status: nothing is exported yet.";+ f.savePlan({+ // The second turn is the harness's one automatic retry after a failure.+ [replying.id]: { turns: [{ steps: [{ tool: "send_voice_note", arguments: { text: replyNote } }], progress: "Half the export is done.", failWith: "the export step crashed" }, { steps: [], reply: "Retried." }] },+ [quiet.id]: { turns: [{ steps: [{ tool: "send_voice_note", arguments: { text: quietNote } }], failWith: "the export step crashed" }, { steps: [], reply: "Retried." }] },+ [stopped.id]: { steps: [{ tool: "send_voice_note", arguments: { text: "This note is stopped." } }], gateFile: gate, reply: "Never reached." },+ });+ const failure = (m: any) => m.kind === "activity" && String(m.tool?.name ?? "").startsWith("error:");+ const settledFailure = async (bot: any, note: string) => {+ await f.cli("send", "--bot", bot.id, "--task", bot.activeTaskId, "--text", "Export it, and tell me by voice.");+ await expect.poll(async () => (await f.messages(bot.activeTaskId)).some(failure), { timeout: 30_000 }).toBe(true);+ await f.cli("wait", "--bot", bot.id, "--task", bot.activeTaskId, "--timeout", "30");+ const messages = await f.messages(bot.activeTaskId);+ const voiced = messages.findIndex((m: any) => (m.attachments ?? []).some((a: any) => a.kind === "audio"));+ expect(voiced).toBeGreaterThanOrEqual(0);+ const audio = messages[voiced].attachments.find((a: any) => a.kind === "audio");+ expect(audio.text).toBe(note);+ const failed = messages.findIndex(failure);+ expect(failed).toBeGreaterThan(voiced);+ expect(messages.slice(failed + 1).some((m: any) => m.role === "bot" && m.kind === "text" && m.turnId === messages[voiced].turnId)).toBe(false);+ return messages[voiced];+ };++ const withReply = await settledFailure(replying, replyNote);+ expect(withReply.text).toBe("Half the export is done.");+ const alone = await settledFailure(quiet, quietNote);+ expect(alone.role).toBe("bot");+ expect(alone.text).toBe("");+ expect(f.mp3Files()).toHaveLength(2);++ await f.cli("send", "--bot", stopped.id, "--task", stopped.activeTaskId, "--text", "Send a note, then hold.");+ await expect.poll(() => f.mp3Files().length, { timeout: 20_000 }).toBe(3);+ await f.api("/api/bots/" + stopped.id + "/interrupt", { threadId: stopped.activeTaskId });+ await expect.poll(() => f.mp3Files().length, { timeout: 20_000 }).toBe(2);+ await f.cli("wait", "--bot", stopped.id, "--task", stopped.activeTaskId, "--timeout", "30");+ expect((await f.messages(stopped.activeTaskId)).some((m: any) => (m.attachments ?? []).some((a: any) => a.kind === "audio"))).toBe(false);+}), 120_000);+it("deletes a parked voice note when the turn is cancelled mid-flight", async () => withVoiceFixture(async (f) => {const baseUrl = await f.serveTts();await f.api("/api/config", { tts: { provider: "chatterbox", baseUrl, voice: "voice-a" } }, "PUT");