Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Chat: only a line the server marked automated becomes a wait note
luishron123cfee0e703533
diff --git a/src/components/AutomationNoteRow.tsx b/src/components/AutomationNoteRow.tsxindex 15472bbcea..3e527f11e1 100644--- a/src/components/AutomationNoteRow.tsx+++ b/src/components/AutomationNoteRow.tsx@@ -1,10 +1,16 @@import { useId, useState } from "react";import { ChevronRight, Clock3 } from "lucide-react";-import { automationNoteTitle, resumedText, type AutomationNote } from "@/lib/automation-note";+import { automationNote, automationNoteTitle, knownWaits, 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 note for a line an automation started a turn with, or null for every other line. `transcript` holds the wait's own card. */+export function automationNoteRow(message: Message, transcript: readonly Message[]) {+ const note = automationNote(message, knownWaits(transcript));+ return note ? <AutomationNoteRow message={message} note={note} /> : null;+}+/** 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);@@ -19,12 +25,13 @@ export function AutomationNoteRow({ message, note }: { message: Message; note: A<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 && (+ // On touch the 40px target overhangs the line instead of making the note taller.<buttontype="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"+ className="flex shrink-0 items-center gap-1 rounded text-ink transition-colors touch:-my-3 touch:min-h-10 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")}diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsxindex db147fa92e..8e925af7f1 100644--- a/src/components/ChatView.tsx+++ b/src/components/ChatView.tsx@@ -51,7 +51,8 @@ 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 { automationNote } from "@/lib/automation-note"; import { AutomationNoteRow } from "./AutomationNoteRow";+import { peerLine, peerPreview, peerRequest } from "@/lib/peer-message"; import { PeerCompactRow, PeerLabel, PeerMessagesContext, PeerOpenedActions } from "./PeerExchange";+import { lastRequests } 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 +700,9 @@ 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} />; const note = automationNote(m); if (note) return <AutomationNoteRow message={m} note={note} />;+ if (m.publishedPage || m.template) return m.template ? <TemplateChatCard message={m} botId={botId} threadId={threadId} /> : <PublishedPageCard message={m} />;+ const note = automationNoteRow(m, transcript);+ if (note) return note;const peer = peerLine(m) ?? peerRequest(m, botId);const user = m.role === "user" && !peer;if (!user && isPureLeakedSystemHarnessMessage(m.text) && !m.attachments?.length) return null;@@ -841,10 +844,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) && !automationNote(m));- return [said.at(-1), said.findLast((m) => !m.reaction)];- }, [messages]);+ const { answered: lastUserMessage, typed: lastTypedMessage } = useMemo(() => lastRequests(messages), [messages]);const lastTypedMessageHasAttachments = useMemo(() => {if (!lastTypedMessage?.text) return false;const cited = splitTranscriptCitations(lastTypedMessage.text);diff --git a/src/components/sidebar-preview.ts b/src/components/sidebar-preview.tsindex 043a5b6e72..c31ea6cef9 100644--- a/src/components/sidebar-preview.ts+++ b/src/components/sidebar-preview.ts@@ -1,7 +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 { automationNote, automationNoteTitle, knownWaits } 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";@@ -66,7 +66,7 @@ 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);+ const note = automationNote(last, knownWaits(visible));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/lib/automation-note.test.ts b/src/lib/automation-note.test.tsindex 03a95573a8..f0e5552d36 100644--- a/src/lib/automation-note.test.ts+++ b/src/lib/automation-note.test.ts@@ -5,7 +5,7 @@ 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 { automationNote, automationNoteTitle, knownWaits, lastRequests } from "./automation-note";import { setLocale } from "./i18n";import { unreadContextMessage } from "./unread-context";import { firstUnreadMessageId } from "./unread-divider";@@ -24,7 +24,10 @@ function followUpLine(label: string, followUp: string, retried?: "restarted" | "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;+const typed = (text: string, extra: Partial<Message> = {}): Message => ({ id: "m", role: "user", kind: "text", at: 1, text, ...extra }) as Message;+/** As the server stores a line an automation started a turn with. */+const line = (text: string, extra: Partial<Message> = {}): Message => typed(text, { automated: true, ...extra });+const waitCard = (label: string, followUp: string): Message => ({ id: `card-${label}`, role: "bot", kind: "options", at: 1, card: { title: "", options: [], waitRequest: { waitId: label, label, followUp } } }) as unknown as Message;describe("automationNote", () => {it("reads a wait's follow-up as the app's line, not the person's", () => {@@ -44,10 +47,39 @@ describe("automationNote", () => {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();+ it("leaves what a person or a bot wrote alone, even in the app's own words", () => {+ expect(automationNote(typed("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();+ const pasted = typed("[Wait finished: teste] minhas palavras", { id: "pasted" });+ expect(automationNote(pasted)).toBeNull();+ expect(automationNote(pasted, [{ label: "teste", followUp: "minhas palavras" }])).toBeNull();+ expect(automationNote(typed(continueNote("restarted")))).toBeNull();+ expect(automationNote(typed(followUpLine("the build", "Ship it.", "restarted")))).toBeNull();+ expect(bubbleGroup(pasted, "bot")).toBe("user");+ expect(firstUnreadMessageId([pasted, { id: "answer", role: "bot", kind: "text", at: 2, text: "ok" } as Message])).toBe("answer");+ expect(lastLine({} as Bot, [pasted], [], false)).toBe("[Wait finished: teste] minhas palavras");+ expect(lastRequests([pasted]).typed).toBe(pasted);+ });++ it("takes a label that holds \"] \" whole from the wait's own card", () => {+ const text = followUpLine("release [QA] aprovada", "Publish [the] notes.");+ const card = waitCard("release [QA] aprovada", "Publish [the] notes.");+ expect(automationNote(line(text), knownWaits([card]))).toEqual({ wait: "release [QA] aprovada", instructions: "Publish [the] notes." });+ expect(automationNote(line(text), knownWaits([waitCard("release [QA", "Something else."), card]))?.wait).toBe("release [QA] aprovada");+ expect(lastLine({} as Bot, [card, line(text)], [], false)).toBe("Following up on the wait: release [QA] aprovada");+ expect(automationNote(line(text))?.wait).toBe("release [QA");+ });++ it("sends again the line a reply answers, and offers for editing only what the person typed", () => {+ const asked = typed("Tell me when the report is ready", { id: "asked" });+ const wait = line(followUpLine("the report", "Say it is ready."), { id: "wait" });+ const reply = { id: "reply", role: "bot", kind: "text", at: 3, text: "It is ready." } as Message;+ expect(lastRequests([asked, reply])).toEqual({ answered: asked, typed: asked });+ expect(lastRequests([asked, reply, wait, reply])).toEqual({ answered: wait, typed: asked });+ const later = typed("Thanks", { id: "later" }), liked = typed("👍", { id: "liked", reaction: "👍" } as Partial<Message>);+ expect(lastRequests([asked, wait, reply, later, liked])).toEqual({ answered: liked, typed: later });+ expect(lastRequests([reply])).toEqual({ answered: undefined, typed: undefined });});it("is no bubble of the person's, no line they wrote, and previews in the app's words", () => {@@ -58,9 +90,9 @@ describe("automationNote", () => {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");+ expect(lastLine({} as Bot, [asked, wait], [], false)).toBe("Following up on the wait: the report");setLocale("pt-br");- expect(automationNoteTitle(automationNote(wait)!)).toBe("Espera concluída: the report");+ expect(automationNoteTitle(automationNote(wait)!)).toBe("Continuação da espera: 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.tsindex b4bfc3fb80..f10a53addd 100644--- a/src/lib/automation-note.ts+++ b/src/lib/automation-note.ts@@ -1,5 +1,6 @@// 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 { peerLine } from "@/lib/peer-message";import type { WireMessage as Message } from "../../shared/wire.ts";export interface AutomationNote {@@ -11,27 +12,51 @@ export interface AutomationNote {resumed?: "restart" | "interrupted";}+const PREFIX = "[Wait finished: ";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;+/** The waits a transcript's own cards record: what each was called and what it was to do afterwards. */+export type KnownWait = { label: string; followUp: string };+const known = new WeakMap<object, KnownWait[]>();+export function knownWaits(messages: readonly Pick<Message, "card">[]): KnownWait[] {+ let waits = known.get(messages);+ if (!waits) known.set(messages, (waits = messages.flatMap((message) => (message.card?.waitRequest ? [message.card.waitRequest] : []))));+ return waits;+}++// A label may itself hold "] ", where the text alone cannot tell it from the instructions: the wait's card can.+function waitLabel(text: string, waits: readonly KnownWait[]): string | undefined {+ if (!text.startsWith(PREFIX)) return undefined;+ const named = waits.filter((wait) => text.startsWith(`${PREFIX}${wait.label}] `)).sort((a, b) => b.label.length - a.label.length);+ return (named.find((wait) => text.startsWith(`${PREFIX}${wait.label}] ${wait.followUp}`)) ?? named[0])?.label ?? WAIT_FINISHED.exec(text)?.[1];+}++/** Only a line the server marked as started by an automation: the same words typed by a person stay theirs. */+export function automationNote(message: Pick<Message, "role" | "kind" | "text" | "automated">, waits: readonly KnownWait[] = []): AutomationNote | null {+ if (message.role !== "user" || message.automated !== true || (message.kind && message.kind !== "text")) return null;const text = message.text ?? "";- const wait = WAIT_FINISHED.exec(text);+ const wait = waitLabel(text, waits);const second = SECOND_START.exec(text);- if (!wait && second?.index !== 0) return null;+ if (wait === undefined && 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(),+ ...(wait === undefined ? {} : { wait }),+ instructions: text.slice(wait === undefined ? 0 : PREFIX.length + wait.length + 2, second?.index ?? text.length).trim(),...(resumed ? { resumed } : {}),};}+/** The line a reply answers, which Regenerate and Try again send again, and the last one the person typed, which they may edit. */+export function lastRequests<Line extends Pick<Message, "role" | "kind" | "text" | "automated" | "peerAsk" | "reaction">>(messages: readonly Line[]): { answered?: Line; typed?: Line } {+ const said = messages.filter((message) => message.role === "user" && message.kind === "text" && !peerLine(message));+ return { answered: said.at(-1), typed: said.findLast((message) => !message.reaction && !automationNote(message)) };+}+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 });+ note.wait === undefined ? resumedText(note) ?? "" : t("chat.automationNote.followUp", { label: note.wait });diff --git a/src/lib/unread-divider.ts b/src/lib/unread-divider.tsindex d74484cafd..7320ee82a6 100644--- a/src/lib/unread-divider.ts+++ b/src/lib/unread-divider.ts@@ -2,7 +2,7 @@ import { automationNote } from "@/lib/automation-note";import { peerLine } from "@/lib/peer-message";import type { Message } from "@/state/store";-type Line = Pick<Message, "id" | "role" | "kind" | "text" | "peerAsk">;+type Line = Pick<Message, "id" | "role" | "kind" | "text" | "peerAsk" | "automated">;export const fromPerson = (message: Line) => message.role === "user" && !peerLine(message) && !automationNote(message);diff --git a/src/locales/en.json b/src/locales/en.jsonindex 4c2aab435c..3a7913d3bb 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -2698,7 +2698,7 @@"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.followUp": "Following up on the wait: {label}","chat.automationNote.show": "Show instructions","chat.automationNote.hide": "Hide instructions","chat.automationNote.resumedAfterRestart": "Picked up again after OpenMausBot restarted",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 5372573be1..fb4a732f6a 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -2512,7 +2512,7 @@"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.followUp": "Continuação da espera: {label}","chat.automationNote.show": "Mostrar instruções","chat.automationNote.hide": "Ocultar instruções","chat.automationNote.resumedAfterRestart": "Retomada depois que o OpenMausBot reiniciou",diff --git a/src/state/store.tsx b/src/state/store.tsxindex c025413e49..665a6ab8b2 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -115,7 +115,7 @@ export type SecretRequestCardData = Omit<import("../../shared/wire").SecretRequeexport type ComputerControlState = { held: boolean; helpReason: string | null; help?: import("../../shared/wire").ComputerHelpRef | null };-export interface Message extends Pick<import("../../shared/wire").WireMessage, "widget" | "app" | "fromApp" | "pointed" | "routedBy" | "quickModel" | "automation" | "publishedPage" | "template" | "sender" | "setupSuggestion" | "settingsCard" | "helperIntro" | "helperFollowup" | "setupOffer" | "savedSteps" | "setupChoices" | "setupChoicesPending" | "setupChoicesUpdating" | "setupRequest" | "relay" | "inbox" | "sentDirectly" | "doneWhen" | "checkBack" | "handoff" | "bugReport" | "engineCompaction" | "stoppedBy"> {+export interface Message extends Pick<import("../../shared/wire").WireMessage, "widget" | "app" | "automated" | "fromApp" | "pointed" | "routedBy" | "quickModel" | "automation" | "publishedPage" | "template" | "sender" | "setupSuggestion" | "settingsCard" | "helperIntro" | "helperFollowup" | "setupOffer" | "savedSteps" | "setupChoices" | "setupChoicesPending" | "setupChoicesUpdating" | "setupRequest" | "relay" | "inbox" | "sentDirectly" | "doneWhen" | "checkBack" | "handoff" | "bugReport" | "engineCompaction" | "stoppedBy"> {id: string;role: "bot" | "user";kind: "text" | "options" | "activity" | "screen" | "connector" | "secret" | "signin" | "routine.run" | "goal.run" | "burst" | "digest" | "compaction" | "call" | "widget" | "app";