Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Chat: a wait's follow-up is drawn as a note, not as the person's message
luishron12388a3f7c6b24d
diff --git a/src/components/AutomationNoteRow.tsx b/src/components/AutomationNoteRow.tsxnew file mode 100644index 0000000000..15472bbcea--- /dev/null+++ b/src/components/AutomationNoteRow.tsx@@ -0,0 +1,45 @@+import { useId, useState } from "react";+import { ChevronRight, Clock3 } from "lucide-react";+import { automationNoteTitle, resumedText, type AutomationNote } from "@/lib/automation-note";+import { cn } from "@/lib/cn";+import { intlLocale, t } from "@/lib/i18n";+import type { Message } from "@/state/store";++/** The line an automation started a turn with, in the app's words; what it told the bot stays behind a disclosure. */+export function AutomationNoteRow({ message, note }: { message: Message; note: AutomationNote }) {+ const [open, setOpen] = useState(false);+ const instructionsId = useId();+ const resumed = resumedText(note);+ return (+ <div data-look="automation-note" data-testid="automation-note" className="flex w-full justify-start" title={new Date(message.at).toLocaleString(intlLocale())}>+ <div className="w-fit max-w-[min(var(--chat-bubble-max),var(--chat-bubble-pct))] rounded-xl border border-hairline/40 bg-panel px-3 py-2 text-[13px] leading-[18px] text-ink-secondary">+ <div className="flex min-w-0 gap-2">+ <Clock3 size={14} aria-hidden="true" className="mt-0.5 shrink-0" />+ <div className="min-w-0">+ <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1">+ <span dir="auto" className="min-w-0 [overflow-wrap:anywhere]">{automationNoteTitle(note)}</span>+ {note.instructions && (+ <button+ type="button"+ aria-expanded={open}+ aria-controls={instructionsId}+ onClick={() => setOpen((shown) => !shown)}+ className="flex shrink-0 items-center gap-1 rounded text-ink transition-colors duration-[120ms] hover:text-ink-secondary motion-reduce:transition-none"+ >+ <ChevronRight size={12} aria-hidden="true" className={cn("shrink-0", open ? "rotate-90" : "rtl:-scale-x-100")} />+ {t(open ? "chat.automationNote.hide" : "chat.automationNote.show")}+ </button>+ )}+ </div>+ {note.wait !== undefined && resumed && <p className="mt-0.5 text-[12px] leading-4 text-ink-tertiary">{resumed}</p>}+ </div>+ </div>+ {note.instructions && (+ <div id={instructionsId} hidden={!open} dir="auto" className="mt-2 border-t border-hairline/40 pt-2 whitespace-pre-wrap [overflow-wrap:anywhere]">+ {note.instructions}+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsxindex a35aed55c0..db147fa92e 100644--- a/src/components/ChatView.tsx+++ b/src/components/ChatView.tsx@@ -51,7 +51,7 @@ import { BotAvatar } from "./Avatar";import { TurnPresence } from "./TurnPresence";import { showToolCallsEnabled } from "@/lib/feature-flags";import { stateForBot } from "@/lib/mascot";-import { peerLine, peerPreview, peerRequest } from "@/lib/peer-message"; import { PeerCompactRow, PeerLabel, PeerMessagesContext, PeerOpenedActions } from "./PeerExchange";+import { peerLine, peerPreview, peerRequest } from "@/lib/peer-message"; import { PeerCompactRow, PeerLabel, PeerMessagesContext, PeerOpenedActions } from "./PeerExchange"; import { automationNote } from "@/lib/automation-note"; import { AutomationNoteRow } from "./AutomationNoteRow";import { showWorkingDots } from "@/lib/turn-tail";import { lastNonReceipt } from "@/lib/receipts";import { useTurnLive } from "@/state/turn-status"; import { isLiveReply, StreamingReplyContext, streamedReply, useHasLiveReply, useLiveRow, useLiveTranscriptLayout } from "@/state/live-reply"; import { useTurnNow } from "./NowCard"; import { useThreadRoutineRun } from "@/state/older-routine-runs";@@ -699,7 +699,7 @@ const MessagesList = memo(function MessagesList({case "screen":return <ScreenFrame threadId={threadId} message={m} />;default: {- if (m.publishedPage || m.template) return m.template ? <TemplateChatCard message={m} botId={botId} threadId={threadId} /> : <PublishedPageCard message={m} />;+ if (m.publishedPage || m.template) return m.template ? <TemplateChatCard message={m} botId={botId} threadId={threadId} /> : <PublishedPageCard message={m} />; const note = automationNote(m); if (note) return <AutomationNoteRow message={m} note={note} />;const peer = peerLine(m) ?? peerRequest(m, botId);const user = m.role === "user" && !peer;if (!user && isPureLeakedSystemHarnessMessage(m.text) && !m.attachments?.length) return null;@@ -842,7 +842,7 @@ export const ChatView = memo(function ChatView({ bot: profile, inForkPanel = fal[bot.id, bot.threadId, dispatch],);const [lastUserMessage, lastTypedMessage] = useMemo(() => {- const said = messages.filter((m) => m.role === "user" && m.kind === "text" && !peerLine(m));+ const said = messages.filter((m) => m.role === "user" && m.kind === "text" && !peerLine(m) && !automationNote(m));return [said.at(-1), said.findLast((m) => !m.reaction)];}, [messages]);const lastTypedMessageHasAttachments = useMemo(() => {diff --git a/src/components/chat-bubble.ts b/src/components/chat-bubble.tsindex 3ef6dbdfe9..9e176222b8 100644--- a/src/components/chat-bubble.ts+++ b/src/components/chat-bubble.ts@@ -1,6 +1,7 @@import { cn } from "@/lib/cn";import { failedTurnCause } from "@/lib/failed-turn";import { isStatusActivity } from "@/lib/activity-runs";+import { automationNote } from "@/lib/automation-note";import { peerLine, peerRequest } from "@/lib/peer-message";import { localDay } from "@/lib/transcript-derivations";import type { TranscriptItem } from "@/lib/activity-runs";@@ -50,7 +51,7 @@ export function joinedCorners(side: "start" | "end", join: BubbleJoin): string {/** Which bubble group a transcript row belongs to in Simple mode: this bot's words, the person's own words, or none. */export function bubbleGroup(message: Message, botId: string): "bot" | "user" | null {if (message.kind !== "text" || message.publishedPage || message.template || message.automation || message.helperFollowup) return null;- if (message.role === "user") return peerLine(message) ? null : "user";+ if (message.role === "user") return peerLine(message) || automationNote(message) ? null : "user";if (message.role !== "bot" || peerRequest(message, botId)) return null;return isPureLeakedSystemHarnessMessage(message.text) && !message.attachments?.length ? null : "bot";}diff --git a/src/components/sidebar-preview.ts b/src/components/sidebar-preview.tsindex e4b3e422d5..043a5b6e72 100644--- a/src/components/sidebar-preview.ts+++ b/src/components/sidebar-preview.ts@@ -1,6 +1,7 @@import { approvalCardOutcome } from "./ApprovalCard";import type { Bot, Group, InstanceInfo, Message } from "@/state/store";import type { RoutineRunCardData } from "../../shared/routine-run";+import { automationNote, automationNoteTitle } from "@/lib/automation-note";import { peerLine } from "@/lib/peer-message";import { isReceipt } from "@/lib/receipts";import { activityPreview, botEngine, failedTurnCause, STATUS_MARKER } from "@/lib/failed-turn";@@ -65,6 +66,8 @@ export function lastLine(bot: Bot, visible: Message[], instances: InstanceInfo[]if (last.kind === "routine.run" && last.routineRun) return automationRunPreview(last.routineRun);const peer = peerLine(last);if (peer) return `${peer.name}: ${plainPreviewText(peer.body)}`;+ const note = automationNote(last);+ if (note) return automationNoteTitle(note);if (last.role !== "user" && isClientCancellation(last.text ?? "")) return t("chat.turnStopped");return plainPreviewText(citationPreviewText(serverCardText(last) ?? last.text ?? ""));}diff --git a/src/hooks/use-unread-divider.ts b/src/hooks/use-unread-divider.tsindex 2f1c61df60..459c804f7f 100644--- a/src/hooks/use-unread-divider.ts+++ b/src/hooks/use-unread-divider.ts@@ -1,6 +1,5 @@import { useEffect, useMemo, useRef, useState } from "react";-import { peerLine } from "@/lib/peer-message";-import { UNREAD_DIVIDER_FADE_MS, UNREAD_DIVIDER_LINGER_MS } from "@/lib/unread-divider";+import { fromPerson, UNREAD_DIVIDER_FADE_MS, UNREAD_DIVIDER_LINGER_MS } from "@/lib/unread-divider";import type { Message } from "@/state/store";import { useStoreDispatch, useStoreSelector } from "@/state/store-select";@@ -13,7 +12,7 @@ export function useUnreadDivider({ threadId, messages, following }: {const messageId = divider && divider.threadId === threadId ? divider.messageId : null;const newestOwnId = useMemo(() => {for (let i = messages.length - 1; i >= 0; i--) {- if (messages[i]!.role === "user" && !peerLine(messages[i]!)) return messages[i]!.id;+ if (fromPerson(messages[i]!)) return messages[i]!.id;}return null;}, [messages]);diff --git a/src/lib/automation-note.test.ts b/src/lib/automation-note.test.tsnew file mode 100644index 0000000000..03a95573a8--- /dev/null+++ b/src/lib/automation-note.test.ts@@ -0,0 +1,66 @@+import { afterEach, describe, expect, it } from "vitest";+import { bubbleGroup } from "@/components/chat-bubble";+import { lastLine } from "@/components/sidebar-preview";+import type { Bot, Message } from "@/state/store";+import { continueNote, retryNote, startPrompt } from "../../server/routine-recovery";+import { composeExecutionPrompt } from "../../server/routine-execution";+import { createWaitHost } from "../../server/wait-host";+import { automationNote, automationNoteTitle } from "./automation-note";+import { setLocale } from "./i18n";+import { unreadContextMessage } from "./unread-context";+import { firstUnreadMessageId } from "./unread-divider";++afterEach(() => setLocale("en"));++/** The line a wait's follow-up run starts its turn with, built by the server's own code. */+function followUpLine(label: string, followUp: string, retried?: "restarted" | "stalled", said = false): string {+ let queued = "";+ const host = createWaitHost({+ store: {} as never, directChat: () => true, threadBusy: () => false, wrote: () => {}, notify: () => {}, cloudHome: false,+ enqueue: (input) => { queued = input.prompt ?? ""; return { id: "run" }; },+ });+ host.followUp!({ id: "wait-1", botId: "bot", threadId: "thread", label, followUp } as never);+ const first = composeExecutionPrompt({ id: "wait:wait-1", name: label, trigger: "webhook", runOn: "maus" }, queued, undefined);+ return startPrompt({ retried }, queued, first, () => said);+}++const line = (text: string, extra: Partial<Message> = {}): Message => ({ id: "m", role: "user", kind: "text", at: 1, text, ...extra }) as Message;++describe("automationNote", () => {+ it("reads a wait's follow-up as the app's line, not the person's", () => {+ const text = followUpLine("the report", "Read /tmp/report.txt\nand say what changed.");+ expect(text).toBe("[Wait finished: the report] Read /tmp/report.txt\nand say what changed.");+ expect(automationNote(line(text))).toEqual({ wait: "the report", instructions: "Read /tmp/report.txt\nand say what changed." });+ });++ it("keeps the app's second-start line out of the instructions and names what cut the first start off", () => {+ expect(automationNote(line(followUpLine("the build", "Ship it.", "restarted")))).toEqual({ wait: "the build", instructions: "Ship it.", resumed: "restart" });+ expect(automationNote(line(followUpLine("the build", "Ship it.", "stalled")))).toEqual({ wait: "the build", instructions: "Ship it.", resumed: "interrupted" });+ });++ it("reads a second start that only carries the app's line", () => {+ const text = followUpLine("the build", "Ship it.", "restarted", true);+ expect(text).toBe(continueNote("restarted"));+ expect(automationNote(line(text))).toEqual({ instructions: "", resumed: "restart" });+ });++ it("leaves what a person or a bot wrote alone", () => {+ expect(automationNote(line("Tell me when the report is ready"))).toBeNull();+ expect(automationNote(line(`I saw this:\n\n${retryNote("restarted")}`))).toBeNull();+ expect(automationNote(line("[Wait finished: x] y", { role: "bot" }))).toBeNull();+ });++ it("is no bubble of the person's, no line they wrote, and previews in the app's words", () => {+ const wait = line(followUpLine("the report", "Say it is ready."), { id: "wait" });+ const asked = line("Tell me when the report is ready", { id: "asked" });+ const answer = { id: "answer", role: "bot", kind: "text", at: 3, text: "It is ready." } as Message;+ expect(bubbleGroup(asked, "bot")).toBe("user");+ expect(bubbleGroup(wait, "bot")).toBeNull();+ expect(firstUnreadMessageId([asked, wait, answer])).toBe("wait");+ expect(unreadContextMessage([asked, wait, answer], "answer")?.id).toBe("asked");+ expect(lastLine({} as Bot, [asked, wait], [], false)).toBe("Wait over: the report");+ setLocale("pt-br");+ expect(automationNoteTitle(automationNote(wait)!)).toBe("Espera concluída: the report");+ expect(automationNoteTitle(automationNote(line(continueNote("restarted")))!)).toBe("Retomada depois que o OpenMausBot reiniciou");+ });+});diff --git a/src/lib/automation-note.ts b/src/lib/automation-note.tsnew file mode 100644index 0000000000..b4bfc3fb80--- /dev/null+++ b/src/lib/automation-note.ts@@ -0,0 +1,37 @@+// A wait's follow-up starts its turn with a user-role line the app wrote; keyed on role alone it would read as the person's own.+import { t } from "@/lib/i18n";+import type { WireMessage as Message } from "../../shared/wire.ts";++export interface AutomationNote {+ /** The person's words for what the wait was for. Absent on a second start that only carries the app's own line. */+ wait?: string;+ /** What the bot was asked to do then. Empty when the line holds none. */+ instructions: string;+ /** The run's second start: what cut the first one off. */+ resumed?: "restart" | "interrupted";+}++const WAIT_FINISHED = /^\[Wait finished: ([^\n]*?)\] /;+const SECOND_START = /(?:^|\n\n)\[OpenMausBot: this run's first start ([^\]]*?) before it finished\. [^\]]*\]$/;++export function automationNote(message: Pick<Message, "role" | "kind" | "text">): AutomationNote | null {+ if (message.role !== "user" || (message.kind && message.kind !== "text")) return null;+ const text = message.text ?? "";+ const wait = WAIT_FINISHED.exec(text);+ const second = SECOND_START.exec(text);+ if (!wait && second?.index !== 0) return null;+ const resumed = second ? (second[1]!.includes("restarted") ? "restart" : "interrupted") : undefined;+ return {+ ...(wait ? { wait: wait[1]! } : {}),+ instructions: text.slice(wait?.[0].length ?? 0, second?.index ?? text.length).trim(),+ ...(resumed ? { resumed } : {}),+ };+}++const RESUMED = { restart: "chat.automationNote.resumedAfterRestart", interrupted: "chat.automationNote.resumed" } as const;++export const resumedText = (note: AutomationNote): string | null => (note.resumed ? t(RESUMED[note.resumed]) : null);++/** The note's one line: the wait it follows, or on a second start with nothing else to name, why it started again. */+export const automationNoteTitle = (note: AutomationNote): string =>+ note.wait === undefined ? resumedText(note) ?? "" : t("chat.automationNote.waitOver", { label: note.wait });diff --git a/src/lib/unread-context.ts b/src/lib/unread-context.tsindex 966ad78da2..2eeb0a850f 100644--- a/src/lib/unread-context.ts+++ b/src/lib/unread-context.ts@@ -1,3 +1,4 @@+import { automationNote } from "@/lib/automation-note";import { splitTranscriptCitations, type CitationAttachment } from "@/lib/citations";import { splitTranscriptAttachments } from "@/lib/composer-attachments";import { peerLine } from "@/lib/peer-message";@@ -13,7 +14,7 @@ export function unreadContextMessage(messages: readonly Message[], unreadMessageif (at < 0) return null;for (let i = at - 1; i >= 0; i--) {const message = messages[i]!;- if (message.role === "user" && message.kind === "text" && !peerLine(message)) return message;+ if (message.role === "user" && message.kind === "text" && !peerLine(message) && !automationNote(message)) return message;}return null;}diff --git a/src/lib/unread-divider.ts b/src/lib/unread-divider.tsindex 7659275bdc..d74484cafd 100644--- a/src/lib/unread-divider.ts+++ b/src/lib/unread-divider.ts@@ -1,9 +1,10 @@+import { automationNote } from "@/lib/automation-note";import { peerLine } from "@/lib/peer-message";import type { Message } from "@/state/store";-type Line = Pick<Message, "id" | "role" | "text" | "peerAsk">;+type Line = Pick<Message, "id" | "role" | "kind" | "text" | "peerAsk">;-const fromPerson = (message: Line) => message.role === "user" && !peerLine(message);+export const fromPerson = (message: Line) => message.role === "user" && !peerLine(message) && !automationNote(message);export function firstUnreadMessageId(messages: readonly Line[], lastReadMessageId?: string): string | null {let seen = -1;diff --git a/src/locales/en.json b/src/locales/en.jsonindex 350b00b653..4c2aab435c 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -2698,6 +2698,11 @@"chat.callSheet.keptSpoken": "Your requests, and what {name} said, did and answered. Nothing else you said on the call is kept.","chat.showFull": "Show full message","chat.showLess": "Show less",+ "chat.automationNote.waitOver": "Wait over: {label}",+ "chat.automationNote.show": "Show instructions",+ "chat.automationNote.hide": "Hide instructions",+ "chat.automationNote.resumedAfterRestart": "Picked up again after OpenMausBot restarted",+ "chat.automationNote.resumed": "Picked up again after an interruption","chat.generatedImage": "Generated image","chat.regenerate": "Regenerate response","chat.messageActions": "Message actions",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex e060f07de9..5372573be1 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -2512,6 +2512,11 @@"chat.callSheet.keptSpoken": "Seus pedidos e o que {name} disse, fez e respondeu. Nada mais do que você disse na chamada fica salvo.","chat.showFull": "Ver a mensagem inteira","chat.showLess": "Mostrar menos",+ "chat.automationNote.waitOver": "Espera concluída: {label}",+ "chat.automationNote.show": "Mostrar instruções",+ "chat.automationNote.hide": "Ocultar instruções",+ "chat.automationNote.resumedAfterRestart": "Retomada depois que o OpenMausBot reiniciou",+ "chat.automationNote.resumed": "Retomada depois de uma interrupção","chat.generatedImage": "Imagem gerada","chat.regenerate": "Gerar a resposta novamente","chat.messageActions": "Ações da mensagem",