Skip to content

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

Chat: a wait's follow-up line records its wait, so two waits with the same words keep their own names

luishron123bd08d630aacd
diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.ts
index 26b5bb041e..e9eb98856f 100644
--- a/packages/phone-protocol/src/wire.ts
+++ b/packages/phone-protocol/src/wire.ts
@@ -520,7 +520,7 @@ export interface WireMessage extends ServerTextLine, HelperIntroField, SetupCard
relayed?: boolean;
/** A user line a routine, webhook, room coordination or another bot's
* message started a turn with: the person did not write it. */
- automated?: boolean;
+ automated?: boolean; /** On a wait follow-up's line: that wait's id, so the chat names it when two waits write the same words. */ waitId?: string;
/** Which person sent this user message, when the workspace has more than
* one. Absent reads as the profile name. */
sender?: ResolvedSender;
diff --git a/server/index.ts b/server/index.ts
index 1157980893..32a67c5b9c 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -483,7 +483,7 @@ import { listenWebhookIngress, type WebhookIngress } from "./webhook-ingress.ts"
import { addressFor } from "./webhook-address.ts";
import { assertModelVariantSupported, memberTurnSelection } from "./member-turn.ts";
import { WebhookManager } from "./webhooks.ts";
-import { tieAutomationsToBots } from "./bot-automations.ts"; import { WaitManager } from "./waits.ts"; import { cancelWaitFromCard, createWaitHost, waitContinuationCheck, waitRunChat, waitTurnRunId } from "./wait-host.ts"; import { continuedConversation } from "./routine-same-conversation.ts"; import { createWaitRoutes, findWaitPeer, handedAssignment, hostWaitRefusal, waitSourceRefusal, type WaitRouteContext } from "./routes/waits.ts";
+import { tieAutomationsToBots } from "./bot-automations.ts"; import { WaitManager } from "./waits.ts"; import { cancelWaitFromCard, createWaitHost, waitContinuationCheck, waitLineFields, waitRunChat, waitTurnRunId } from "./wait-host.ts"; import { continuedConversation } from "./routine-same-conversation.ts"; import { createWaitRoutes, findWaitPeer, handedAssignment, hostWaitRefusal, waitSourceRefusal, type WaitRouteContext } from "./routes/waits.ts";
import type { WebhookTrigger } from "../shared/webhooks.ts";
import { AGENTS_NODE_FLAG, SPAWNED_PROXIES } from "./proxy-paths.ts";
import { agentsProxyLaunch, agentsToolBridgeEnv, applyAgentsBridge, bridgedToolTitle, turnEngine } from "./agents-bridge-switch.ts"; import { serverTurnedOff } from "./drivers/agents-tool-groups.ts"; import { availableToolGroups, toolsOffPart } from "./tool-groups.ts"; import { agentsServerEnv, botDrivenConversation, COMPUTER_OFF_REFUSAL, computerPickRefusal, directTurnKind, roomSkillsRefusal, type TurnKind } from "./agents-turn.ts";
@@ -7591,7 +7591,7 @@ async function beginTurn(
peerAsk: opts?.peerAsk,
sender: opts?.sender,
...spokenLineFields(opts?.via, opts?.callId),
- ...(opts?.relayed ? { relayed: true } : {}), ...(automated ? { automated: true } : {}),
+ ...(opts?.relayed ? { relayed: true } : {}), ...(automated ? { automated: true, ...waitLineFields(routines?.runForThread(threadId) ?? null, opts?.automationRunId) } : {}),
});
}
const personLine = !opts?.coordination && !opts?.cardContinuation && !opts?.automationSource && !opts?.compactOnly
diff --git a/server/store.test.ts b/server/store.test.ts
index d9d86ee2ff..54378bf815 100644
--- a/server/store.test.ts
+++ b/server/store.test.ts
@@ -1804,7 +1804,7 @@ describe("Store", () => {
const store = new Store(selection);
const bot = store.createBot();
const followUp = "[Wait finished: the build] Tell me how it went.";
- const automatedLine = store.appendMessage(bot.threadId, { role: "user", kind: "text", text: `${followUp}\n`, automated: true });
+ const automatedLine = store.appendMessage(bot.threadId, { role: "user", kind: "text", text: `${followUp}\n`, automated: true, waitId: "w1" });
const typed = store.appendMessage(bot.threadId, { role: "user", kind: "text", text: "Thanks" });
const live: Message[] = [];
store.onChange((change) => { if (change.type === "message") live.push(change.message); });
@@ -1813,10 +1813,11 @@ describe("Store", () => {
const edited = store.branchMessage(bot.threadId, automatedLine.id, "Tell me tomorrow instead.")!;
const typedAgain = store.branchMessage(bot.threadId, typed.id, "Thanks")!;
- expect(live.map((message) => [message.id, message.automated])).toEqual([[again.id, true], [edited.id, undefined], [typedAgain.id, undefined]]);
+ expect(live.map((message) => [message.id, message.automated, message.waitId])).toEqual([[again.id, true, "w1"], [edited.id, undefined, undefined], [typedAgain.id, undefined, undefined]]);
const reread = new Store(selection).messagesFor(bot.threadId);
- expect(reread.find((message) => message.id === again.id)).toMatchObject({ text: followUp, automated: true });
+ expect(reread.find((message) => message.id === again.id)).toMatchObject({ text: followUp, automated: true, waitId: "w1" });
expect(reread.find((message) => message.id === edited.id)).not.toHaveProperty("automated");
+ expect(reread.find((message) => message.id === edited.id)).not.toHaveProperty("waitId");
expect(reread.find((message) => message.id === typedAgain.id)).not.toHaveProperty("automated");
});
diff --git a/server/store.ts b/server/store.ts
index 7d3697fc49..e245ab47c6 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -1208,7 +1208,7 @@ export class Store {
replyToId: source.replyToId,
...(source.reaction && source.text === text ? { reaction: source.reaction } : {}),
// Regenerate and Try again send the stored words back: an automation's line stays the automation's.
- ...(source.automated === true && source.text?.trim() === text.trim() ? { automated: true } : {}),
+ ...(source.automated === true && source.text?.trim() === text.trim() ? { automated: true, ...(source.waitId ? { waitId: source.waitId } : {}) } : {}),
...(sendId ? { sendId } : {}), ...(sender ? { sender } : {}),
...(dataContext ? { dataContext } : {}), ...from,
};
diff --git a/server/wait-host.test.ts b/server/wait-host.test.ts
index 79f4f08caf..421da22630 100644
--- a/server/wait-host.test.ts
+++ b/server/wait-host.test.ts
@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Notification } from "../shared/notification.ts";
import type { Message } from "./store.ts";
-import { cancelWaitFromCard, createWaitHost, waitContinuesHere, waitContinuationCheck, waitRunChat, waitTurnRunId, type WaitHostDeps } from "./wait-host.ts";
+import { cancelWaitFromCard, createWaitHost, waitContinuesHere, waitContinuationCheck, waitLineFields, waitRunChat, waitTurnRunId, type WaitHostDeps } from "./wait-host.ts";
import type { WaitRecord } from "./waits.ts";
const NOW = 1_700_000_000_000;
@@ -172,4 +172,13 @@ describe("the store side of waits", () => {
store.messages[0]!.wait!.status = "expired";
expect(waitContinuesHere(run, "bot-1", "t-1", store, "run-1")).toBe(false);
});
+
+ it("names the wait a follow-up's line starts, only for the turn that wait's own run started", () => {
+ const run = { id: "run-1", eventSource: "wait" as const, triggerSource: "webhook" as const, webhookId: "wait:w1", deliveryId: "w1" };
+ expect(waitLineFields(run, "run-1")).toEqual({ waitId: "w1" });
+ expect(waitLineFields(run, undefined)).toEqual({});
+ expect(waitLineFields(null, "run-1")).toEqual({});
+ for (const patch of [{ id: "other" }, { eventSource: "app" as const }, { triggerSource: "schedule" as const }, { webhookId: "wait:w2" }, { deliveryId: undefined }])
+ expect(waitLineFields({ ...run, ...patch }, "run-1")).toEqual({});
+ });
});
diff --git a/server/wait-host.ts b/server/wait-host.ts
index 58f5a9836e..3b6152bfa1 100644
--- a/server/wait-host.ts
+++ b/server/wait-host.ts
@@ -42,6 +42,15 @@ export function waitContinuesHere(
return store.messagesFor(threadId).some((message) => message.wait?.status === "fired" && message.wait.id === run.deliveryId);
}
+/** The wait a follow-up's line starts, recorded on that line: only for the turn its own run started. */
+export function waitLineFields(
+ run: Pick<RoutineRun, "id" | "eventSource" | "triggerSource" | "webhookId" | "deliveryId"> | null,
+ originatingRunId: string | undefined,
+): { waitId?: string } {
+ return run && originatingRunId && run.id === originatingRunId && run.eventSource === "wait" && run.triggerSource === "webhook"
+ && run.deliveryId && run.webhookId === `wait:${run.deliveryId}` ? { waitId: run.deliveryId } : {};
+}
+
interface WaitRunOwner {
automationRunId?: string;
messageId?: string;
diff --git a/server/waits.e2e.test.ts b/server/waits.e2e.test.ts
index 3bf7d11e73..2e8ec189a0 100644
--- a/server/waits.e2e.test.ts
+++ b/server/waits.e2e.test.ts
@@ -70,7 +70,8 @@ it("waits for a file with no AI, posts once in the asked chat, notifies, and con
await expect.poll(async () => (await transcript()).filter((m) => m.wait?.status === "fired").map((m) => ({ text: m.text, textCode: m.textCode, textParams: m.textParams })), { timeout: 30_000 })
.toEqual([{ text: `the report: done. ${report} is there now.`, textCode: "chat.notice.waitDone.fileExists", textParams: { label: "the report", path: report } }]);
expect(await api("POST", `/api/threads/${bot.threadId}/undo`, { requestId: cards[0].card.requestId }, 409)).toEqual({ error: "This wait has already ended.", errorKey: "serverError.wait.alreadyEnded" });
- await expect.poll(async () => (await transcript()).some((m) => m.role === "user" && m.text?.includes("[Wait finished: the report] Say the report is ready.")), { timeout: 40_000 }).toBe(true);
+ await expect.poll(async () => (await transcript()).find((m) => m.role === "user" && m.text?.includes("[Wait finished: the report] Say the report is ready.")), { timeout: 40_000 })
+ .toMatchObject({ automated: true, waitId: cards[0].card.waitRequest.waitId });
expect((await api("GET", "/api/notifications")).notifications.filter((n: any) => n.kind === "wait")).toMatchObject([{ title: "Scout's wait is over" }]);
await new Promise((resolve) => setTimeout(resolve, 7_000));
expect((await transcript()).filter((m) => m.wait).length).toBe(1);
diff --git a/src/components/AutomationNoteRow.tsx b/src/components/AutomationNoteRow.tsx
index 3e527f11e1..596f051bb6 100644
--- a/src/components/AutomationNoteRow.tsx
+++ b/src/components/AutomationNoteRow.tsx
@@ -38,7 +38,7 @@ export function AutomationNoteRow({ message, note }: { message: Message; note: A
</button>
)}
</div>
- {note.wait !== undefined && resumed && <p className="mt-0.5 text-[12px] leading-4 text-ink-tertiary">{resumed}</p>}
+ {(note.wait !== undefined || note.unnamed) && resumed && <p className="mt-0.5 text-[12px] leading-4 text-ink-tertiary">{resumed}</p>}
</div>
</div>
{note.instructions && (
diff --git a/src/components/sidebar-preview.test.ts b/src/components/sidebar-preview.test.ts
index 6cc059b893..d6e9a1cd44 100644
--- a/src/components/sidebar-preview.test.ts
+++ b/src/components/sidebar-preview.test.ts
@@ -49,6 +49,13 @@ describe("sidebar previews", () => {
expect(botPreview(bot, [message({ text: "Earlier reply" }), typed, step("Read")], [], false)).not.toBe("Following up on the wait: report");
});
+ it("shows a wait's note in a group chat as the line it is, a step after it included", () => {
+ const note = message({ role: "user", text: "[Wait finished: report] Summarize.", automated: true } as Partial<Message>);
+ const group = (messages: Message[]) => ({ id: "g", name: "Team", memberIds: ["ada"], messages }) as unknown as Group;
+ expect(groupPreview(group([note]), [bot], [], false)).toBe("You: [Wait finished: report] Summarize.");
+ expect(groupPreview(group([note, step("Read")]), [bot], [], false)).toBe("You: [Wait finished: report] Summarize.");
+ });
+
it("keeps a failed step's error line and a recovery or notice line as they are", () => {
const failed = [message({ role: "user", text: "Tidy my inbox" }), message({ text: "On it." }), message({ kind: "activity", tool: { name: "error: Gmail is not connected", ok: false } } as Partial<Message>)];
expect(botPreview(bot, failed, [], false)).toContain("Gmail is not connected");
diff --git a/src/lib/automation-note.test.ts b/src/lib/automation-note.test.ts
index f4365e391b..01014b1790 100644
--- a/src/lib/automation-note.test.ts
+++ b/src/lib/automation-note.test.ts
@@ -79,6 +79,21 @@ describe("automationNote", () => {
expect(automationNote(line(followUpLine("build", "prod] Check logs and notify.", "restarted")), waits)).toMatchObject({ wait: "build", instructions: "prod] Check logs and notify.", resumed: "restart" });
});
+ it("follows the wait the server recorded when two waits write the same line, and names neither when an older line has no id", () => {
+ const short = waitCard("build", "prod] Check logs"), long = waitCard("build] prod", "Check logs");
+ const waits = knownWaits([short, long]);
+ const text = followUpLine("build", "prod] Check logs");
+ expect(followUpLine("build] prod", "Check logs")).toBe(text);
+ expect(automationNote(line(text, { waitId: "build" }), waits)).toEqual({ wait: "build", instructions: "prod] Check logs" });
+ expect(automationNote(line(text, { waitId: "build] prod" }), waits)).toEqual({ wait: "build] prod", instructions: "Check logs" });
+ expect(automationNote(line(followUpLine("build", "prod] Check logs", "restarted"), { waitId: "build" }), waits)).toMatchObject({ wait: "build", instructions: "prod] Check logs", resumed: "restart" });
+ const unnamed = automationNote(line(text), waits)!;
+ expect(unnamed).toEqual({ unnamed: true, instructions: text });
+ expect(automationNoteTitle(unnamed)).toBe("Following up on a wait");
+ expect(lastLine({} as Bot, [short, long, line(text)], [], false)).toBe("Following up on a wait");
+ expect(automationNote(line(followUpLine("build", "prod] Check logs", "restarted")), waits)).toEqual({ unnamed: true, instructions: text, resumed: "restart" });
+ });
+
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" });
diff --git a/src/lib/automation-note.ts b/src/lib/automation-note.ts
index b9f396425e..7bd373ac00 100644
--- a/src/lib/automation-note.ts
+++ b/src/lib/automation-note.ts
@@ -6,6 +6,8 @@ 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;
+ /** A wait's follow-up whose wait the line cannot single out: an older line, with no id, that two waits' cards both match whole. */
+ unnamed?: true;
/** 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. */
@@ -17,7 +19,7 @@ const WAIT_FINISHED = /^\[Wait finished: ([^\n]*?)\] /;
const SECOND_START = /(?:^|\n\n)\[OpenMausBot: this run's first start ([^\]]*?) before it finished\. [^\]]*\]$/;
/** 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 };
+export type KnownWait = { waitId?: string; label: string; followUp: string };
const known = new WeakMap<object, KnownWait[]>();
export function knownWaits(messages: readonly Pick<Message, "card">[]): KnownWait[] {
let waits = known.get(messages);
@@ -26,23 +28,29 @@ export function knownWaits(messages: readonly Pick<Message, "card">[]): KnownWai
}
// A label may itself hold "] ", where the text alone cannot tell it from the instructions: the wait's card can.
-// The card that matches the whole line, second-start part aside, wins over one whose name and instructions only start it.
-function waitLabel(text: string, waits: readonly KnownWait[]): string | undefined {
+// The wait the server recorded on the line decides. A line without one takes the card that matches it whole, second-start part aside,
+// then one that starts it, then the longest name; null when two cards match it whole, rather than guess.
+function waitLabel(text: string, waitId: string | undefined, waits: readonly KnownWait[]): string | null | undefined {
if (!text.startsWith(PREFIX)) return undefined;
- const body = text.slice(0, SECOND_START.exec(text)?.index ?? text.length).trim();
const named = waits.filter((wait) => text.startsWith(`${PREFIX}${wait.label}] `)).sort((a, b) => b.label.length - a.label.length);
+ const own = waitId === undefined ? undefined : named.find((wait) => wait.waitId === waitId);
+ if (own) return own.label;
+ const body = text.slice(0, SECOND_START.exec(text)?.index ?? text.length).trim();
const said = (wait: KnownWait) => `${PREFIX}${wait.label}] ${wait.followUp}`;
- return (named.find((wait) => body === said(wait).trim()) ?? named.find((wait) => body.startsWith(said(wait))) ?? named[0])?.label ?? WAIT_FINISHED.exec(text)?.[1];
+ const whole = named.filter((wait) => body === said(wait).trim());
+ if (new Set(whole.map((wait) => wait.label)).size > 1) return null;
+ return (whole[0] ?? named.find((wait) => body.startsWith(said(wait))) ?? 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 {
+export function automationNote(message: Pick<Message, "role" | "kind" | "text" | "automated" | "waitId">, 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 = waitLabel(text, waits);
+ const wait = waitLabel(text, message.waitId, waits);
const second = SECOND_START.exec(text);
if (wait === undefined && second?.index !== 0) return null;
const resumed = second ? (second[1]!.includes("restarted") ? "restart" : "interrupted") : undefined;
+ if (wait === null) return { unnamed: true, instructions: text.slice(0, second?.index ?? text.length).trim(), ...(resumed ? { resumed } : {}) };
return {
...(wait === undefined ? {} : { wait }),
instructions: text.slice(wait === undefined ? 0 : PREFIX.length + wait.length + 2, second?.index ?? text.length).trim(),
@@ -62,4 +70,5 @@ export const resumedText = (note: AutomationNote): string | null => (note.resume
/** 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.followUp", { label: note.wait });
+ note.unnamed ? t("chat.automationNote.followUpUnnamed")
+ : note.wait === undefined ? resumedText(note) ?? "" : t("chat.automationNote.followUp", { label: note.wait });
diff --git a/src/locales/en.json b/src/locales/en.json
index 3a7913d3bb..e6d94e90b0 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -2699,6 +2699,7 @@
"chat.showFull": "Show full message",
"chat.showLess": "Show less",
"chat.automationNote.followUp": "Following up on the wait: {label}",
+ "chat.automationNote.followUpUnnamed": "Following up on a wait",
"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.json
index fb4a732f6a..d2d0c66da2 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -2513,6 +2513,7 @@
"chat.showFull": "Ver a mensagem inteira",
"chat.showLess": "Mostrar menos",
"chat.automationNote.followUp": "Continuação da espera: {label}",
+ "chat.automationNote.followUpUnnamed": "Continuação de uma espera",
"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.tsx
index 665a6ab8b2..00e690a0f9 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -115,7 +115,7 @@ export type SecretRequestCardData = Omit<import("../../shared/wire").SecretReque
export type ComputerControlState = { held: boolean; helpReason: string | null; help?: import("../../shared/wire").ComputerHelpRef | null };
-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"> {
+export interface Message extends Pick<import("../../shared/wire").WireMessage, "widget" | "app" | "automated" | "waitId" | "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";