Skip to content

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

One "needs you" state for every card a bot leaves open

milind-sonid28c36336225
diff --git a/server/ask-routing.ts b/server/ask-routing.ts
index b4e4e6569a..fda04568c0 100644
--- a/server/ask-routing.ts
+++ b/server/ask-routing.ts
@@ -10,7 +10,7 @@ import { audienceMember, type Audience } from "./audience.ts";
/** The notifications that are a bot asking a person for something; "done", "mention" and the rest reach whoever sees
* the conversation, unless one names its person (`forPerson`). */
export const ASK_NOTIFICATIONS: ReadonlySet<NotifyKind> = new Set([
- "approval", "question", "sign-in", "routine-failed", "routine-deferred", "turn-failed", "incident",
+ "approval", "question", "sign-in", "secret", "routine-failed", "routine-deferred", "turn-failed", "incident",
]);
export interface AskViewer {
diff --git a/server/computer-asks.ts b/server/computer-asks.ts
index 64bc081fea..361b11df87 100644
--- a/server/computer-asks.ts
+++ b/server/computer-asks.ts
@@ -11,6 +11,7 @@ import { optionCardsForTools } from "./message-db.ts";
import { buildNotification, type Notification } from "./notify.ts";
import type { BotRecord, Store } from "./store.ts";
import type { CardAnswerer } from "../shared/wire.ts";
+import { turnWaitedOnPerson } from "./waiting-on-person.ts";
import {
ASK_FOR_COMPUTER_TOOL, cleanAskWhy, COMPUTER_ASK_TOOL, computerAskHeadline, computerAskReasonLine, computerAskText, needsTheApp, turnsOnFromHere,
type ComputerAskCard, type ComputerAskReason, type ComputerAskState, type ComputerDevice, type ComputerNeed,
@@ -362,7 +363,7 @@ export class ComputerAsks {
private idle(ask: Ask): void {
const task = this.deps.store.projectBotForTask(ask.botId, ask.threadId);
- if (task?.activity === "waiting-on-you") this.deps.store.setTaskActivity(task.id, ask.threadId, "working");
+ if (turnWaitedOnPerson(task)) this.deps.store.setTaskActivity(task.id, ask.threadId, "working");
}
private patch(ask: Ask, fields: { answered?: string; answeredBy?: Answerer; dismissed?: boolean }): void {
diff --git a/server/drivers/agents-call.ts b/server/drivers/agents-call.ts
index 956b7ea26f..7d92cffb02 100644
--- a/server/drivers/agents-call.ts
+++ b/server/drivers/agents-call.ts
@@ -566,7 +566,7 @@ export async function callTool(called: string, input: Json, context: ToolCallCon
return { text: `A secure ${r.label ?? CREDENTIAL_TARGETS[credentialId].label} request is ready: the person pastes it into its card in OpenMausBot, on their computer or in My Cloud, and OpenMausBot checks it with 1Password before keeping it. End this turn; OpenMausBot will resume the task after they save or decline. Never ask them to paste the token into chat, and never pass it to a command line.` };
}
return {
- text: `A secure ${r.label ?? CREDENTIAL_TARGETS[credentialId].label} request is ready. The desktop app and a freshly QR-paired mobile app show its secure entry card; older mobile pairings explain how to pair again or finish on the computer. End this turn; OpenMausBot will resume the task after the user saves or declines. Never ask them to paste the key into chat.`,
+ text: `A secure ${r.label ?? CREDENTIAL_TARGETS[credentialId].label} request is now in this conversation, and the person was notified. The desktop app and a freshly QR-paired mobile app show its secure entry card; older mobile pairings explain how to pair again or finish on the computer. End this turn; OpenMausBot will resume the task after the user saves or declines. Never ask them to paste the key into chat.`,
};
}
if (name === "request_sign_in") {
@@ -891,6 +891,6 @@ async function requestCustomSecret(args: Json, context: ToolCallContext): Promis
? ` ${label} was saved earlier for OpenMausBot's tools only, not as a file for your commands (not a file request), so this card asks for it again.`
: r.body.savedAs === "file" ? ` ${label} was saved earlier as a file for your commands, not as a secretRef, so this card asks for it again.` : "";
return {
- text: `A secure card for ${label} is ready in OpenMausBot, on the computer and on a freshly QR-paired phone.${asked} End this turn now and say in one line that you are waiting for it; OpenMausBot resumes you when the person saves or declines, and tells you how to use it. Never ask for it in chat.`,
+ text: `A secure card for ${label} is now in this conversation, in the app and on a QR-paired phone, and the person was notified. If they can't find it, tell them it is in this conversation, and the notification opens it.${asked} End this turn now and say in one line that you are waiting for it; OpenMausBot resumes you when the person saves or declines, and tells you how to use it. Never ask for it in chat.`,
};
}
diff --git a/server/drivers/agents-proxy.test.ts b/server/drivers/agents-proxy.test.ts
index 4ab807b526..31b42fba24 100644
--- a/server/drivers/agents-proxy.test.ts
+++ b/server/drivers/agents-proxy.test.ts
@@ -1165,7 +1165,7 @@ describe("agents-proxy MCP surface", () => {
it("asks for any other secret by its name, reason and delivery, never its value", async () => {
const res = await callTool("request_credential", { label: "Stripe secret key", reason: "To create test charges.", placeholder: "sk_test_…", delivery: "file" });
expect(res.result.isError).toBeFalsy();
- expect(res.result.content[0].text).toMatch(/^A secure card for OpenCode API key is ready in OpenMausBot, on the computer and on a freshly QR-paired phone\. End this turn now/u);
+ expect(res.result.content[0].text).toMatch(/^A secure card for OpenCode API key is now in this conversation, in the app and on a QR-paired phone, and the person was notified\. If they can't find it, tell them it is in this conversation, and the notification opens it\. End this turn now/u);
expect(lastCredentialBody).toEqual({
fromBotId: "bot-asker",
fromThreadId: "thread-asker-routine",
diff --git a/server/host/ask-cards.test.ts b/server/host/ask-cards.test.ts
index 9e9865dbbb..cc4af0a589 100644
--- a/server/host/ask-cards.test.ts
+++ b/server/host/ask-cards.test.ts
@@ -151,11 +151,11 @@ describe("a teammate's NEEDS INPUT question", () => {
expect(room.cards.answerParked("work", "needs-input-as_1-1", "once more")).toBe(false);
});
- it("keeps a parked card's wait as it was: a chip and the work's notice", () => {
+ it("keeps a parked card's chip, and leaves telling the person to the card itself", () => {
const card = world({ inboxThread: "inbox" });
card.cards.park(card.node({ cards: ["m9"] }), "Waiting on the person: connect Gmail");
expect(card.rows("inbox").map((row) => row.tool?.name)).toEqual(["Ledger needs your input: Waiting on the person: connect Gmail"]);
- expect(card.notified.map((notification) => notification.kind)).toEqual(["delegation-settled"]);
+ expect(card.notified).toEqual([]);
});
});
@@ -212,7 +212,7 @@ describe("nothing stale waits on the person", () => {
w.say("inbox", "Scout: something else");
w.cards.park(node, "Waiting on the person: sign in to notion.so", true);
expect(w.rows("inbox").filter((row) => row.tool?.name.includes("needs your input"))).toHaveLength(1);
- expect(w.notified).toHaveLength(1);
+ expect(w.notified).toEqual([]);
});
it("a newer question closes the bot's older one that no turn waits on any more, but not one a turn still waits on", () => {
diff --git a/server/host/ask-cards.ts b/server/host/ask-cards.ts
index 0dc1bfaab4..9a388c8ade 100644
--- a/server/host/ask-cards.ts
+++ b/server/host/ask-cards.ts
@@ -164,6 +164,7 @@ export function createAskCards(deps: AskCardsDeps) {
}
if (node.groupId) store.patchGroup(node.groupId, { unread: true });
else store.patchTask(bot.id, node.threadId, { unread: true });
+ if (node.cards?.length) return;
const room = node.groupId ? store.group(node.groupId) : undefined;
notify(buildNotification(asksWithCard ? "question" : "delegation-settled", bot, node.threadId, withDefault(question).question,
{ avatarUrl: bot.avatarUrl, ...(room ? { group: { id: room.id, name: room.name } } : {}) }));
diff --git a/server/host/first-hour.ts b/server/host/first-hour.ts
index f5e6f7f050..4ad045ab23 100644
--- a/server/host/first-hour.ts
+++ b/server/host/first-hour.ts
@@ -15,6 +15,7 @@ import { createAgentCard } from "../chat-widgets.ts";
import { connectorCardText } from "../connector-card-text.ts";
import type { DraftReply } from "../read-and-draft.ts";
import { localDate, validZone } from "./check-plan.ts";
+import { FIRST_HOUR_OFFER_KEY } from "../../shared/person-wait.ts";
import { firstHourWords, type FirstHourWords } from "./first-hour-words.ts";
import { anyValue, minutesSaved, type ValueLedger, type ValueTally } from "./value-ledger.ts";
@@ -242,7 +243,7 @@ export function createFirstHour(deps: FirstHourDeps) {
}
const cards = await Promise.all(missing.map(async (slug) => ({ slug, ...(await deps.apps.card(slug).catch(() => ({ label: APP_NAME[slug], description: "" }))) })));
if (!state || state.offeredAt || deps.threadBusy(place.bot.id, place.threadId)) return;
- const key = `first-hour-${randomUUID()}`;
+ const key = `${FIRST_HOUR_OFFER_KEY}${randomUUID()}`;
say(place.bot, place.threadId, words().connect);
for (const card of cards) {
deps.store.appendMessage(place.threadId, {
diff --git a/server/host/person-waits.test.ts b/server/host/person-waits.test.ts
new file mode 100644
index 0000000000..29cdff06b9
--- /dev/null
+++ b/server/host/person-waits.test.ts
@@ -0,0 +1,211 @@
+import { rmSync } from "node:fs";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { CUSTOM_SECRET_TARGET } from "../../shared/credential-request.ts";
+import type { Notification } from "../../shared/notification.ts";
+import type { SecretRequestCardData } from "../../shared/wire.ts";
+import { DATA_DIR } from "../config.ts";
+import { Store, type BotRecord } from "../store.ts";
+import { createPersonWaits } from "./person-waits.ts";
+
+const SECRET: SecretRequestCardData = { target: CUSTOM_SECRET_TARGET, label: "Mailbox password", description: "desc", reason: "To read the mail.", placeholder: "", helpUrl: "", requestKey: "k", delivery: "ref" };
+const SIGN_IN = { url: "https://example.com", site: "example.com", place: "browser", reason: "The dashboard is behind a login." } as const;
+const flush = () => new Promise((resolve) => setImmediate(resolve));
+
+function fixture() {
+ const store = new Store(() => ({ instanceId: "claude", model: "claude-sonnet-5" }));
+ const sent: Notification[] = [];
+ const known = new Set<string>();
+ const waits = createPersonWaits({ store, notify: (notification) => { if (notification) sent.push(notification); }, threadsWithCards: () => [...known] });
+ const bot = store.createBot({ name: "Postie" });
+ const thread = store.createTask(bot.id, "Work", false)!.threadId;
+ const task = () => store.taskByThread(bot.id, thread)!;
+ const card = (patch: Record<string, unknown> = {}) => store.appendMessage(thread, { role: "bot", kind: "secret", text: "enter it", secret: { ...SECRET, ...patch } });
+ return { store, waits, sent, known, bot, thread, task, card };
+}
+
+describe("a conversation resting on the person", () => {
+ beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));
+
+ it("waits on the person with no turn running, while the card is open", () => {
+ const { store, bot, thread, task, card } = fixture();
+ const asked = card();
+ expect(task()).toMatchObject({ activity: "waiting-on-you", busy: false });
+ expect(store.bot(bot.id)).toMatchObject({ activity: "waiting-on-you", busy: false });
+ store.patchMessage(thread, asked.id, { secret: { ...SECRET, provided: true } });
+ expect(task()).toMatchObject({ activity: "idle", busy: false });
+ expect(store.bot(bot.id)).toMatchObject({ activity: "idle", busy: false });
+ });
+
+ it.each([
+ ["saved", { provided: true }],
+ ["declined", { dismissed: true }],
+ ["replaced", { superseded: true }],
+ ["stopped", { stopped: true }],
+ ])("stops counting a card that was %s", (_name, settled) => {
+ const { store, thread, task, card } = fixture();
+ const asked = card();
+ store.patchMessage(thread, asked.id, { secret: { ...SECRET, ...settled } });
+ expect(task().activity).toBe("idle");
+ });
+
+ it("keeps a running turn's own state, and comes back to waiting when it ends", () => {
+ const { store, bot, thread, task, card } = fixture();
+ store.setTaskActivity(bot.id, thread, "working");
+ card();
+ expect(task()).toMatchObject({ activity: "working", busy: true });
+ store.setTaskActivity(bot.id, thread, "idle");
+ expect(task()).toMatchObject({ activity: "waiting-on-you", busy: false });
+ store.setTaskActivity(bot.id, thread, "working");
+ expect(task()).toMatchObject({ activity: "working", busy: true });
+ store.setTaskActivity(bot.id, thread, "idle");
+ expect(task()).toMatchObject({ activity: "waiting-on-you", busy: false });
+ });
+
+ it("leaves a card saved during a running turn idle at the turn's end", () => {
+ const { store, bot, thread, task, card } = fixture();
+ store.setTaskActivity(bot.id, thread, "working");
+ const asked = card();
+ store.patchMessage(thread, asked.id, { secret: { ...SECRET, provided: true } });
+ store.setTaskActivity(bot.id, thread, "idle");
+ expect(task()).toMatchObject({ activity: "idle", busy: false });
+ });
+
+ it("reads a running turn's approval but does not rest on it", () => {
+ const { store, waits, thread, task } = fixture();
+ store.appendMessage(thread, { role: "bot", kind: "options", card: { title: "Allow", options: ["Allow"], requestId: "r", tool: "Bash" } as never });
+ expect(waits.open(thread)).toMatchObject({ kind: "approval" });
+ expect(task().activity).toBe("idle");
+ });
+
+ it("lists every conversation resting on the person by its card's kind, newest first, for an inbox", () => {
+ const { store, waits, bot, thread, card } = fixture();
+ const room = store.createGroup("Launch", [bot.id]);
+ const password = card();
+ const signIn = store.appendMessage(room.threadId, { role: "bot", kind: "signin", text: "sign in", at: password.at + 1, from: { botId: bot.id, name: bot.name, color: bot.color }, signIn: { ...SIGN_IN } });
+ expect(waits.waiting()).toEqual([
+ expect.objectContaining({ kind: "sign-in", label: "example.com", threadId: room.threadId, botId: bot.id, messageId: signIn.id }),
+ expect.objectContaining({ kind: "password", label: "Mailbox password", threadId: thread, botId: bot.id, messageId: password.id }),
+ ]);
+ store.patchMessage(thread, password.id, { secret: { ...SECRET, provided: true } });
+ expect(waits.waiting().map((wait) => wait.kind)).toEqual(["sign-in"]);
+ });
+
+ it("shows a card asked in a room on the room's thread", () => {
+ const { store, bot } = fixture();
+ const room = store.createGroup("Launch", [bot.id]);
+ const asked = store.appendMessage(room.threadId, { role: "bot", kind: "secret", text: "enter it", from: { botId: bot.id, name: bot.name, color: bot.color }, secret: { ...SECRET } });
+ expect(store.groupTaskByThread(room.id, room.threadId)?.activity).toBe("waiting-on-you");
+ expect(Boolean(store.bot(bot.id)?.busy)).toBe(false);
+ store.patchMessage(room.threadId, asked.id, { secret: { ...SECRET, provided: true } });
+ expect(store.groupTaskByThread(room.id, room.threadId)?.activity).toBeUndefined();
+ });
+
+ it("follows the branch the person is on", () => {
+ const { store, thread, task, card } = fixture();
+ const before = store.appendMessage(thread, { role: "user", kind: "text", text: "start" });
+ const asked = card();
+ expect(task().activity).toBe("waiting-on-you");
+ const other = store.appendMessage(thread, { role: "user", kind: "text", text: "another way", parentId: before.id });
+ store.setActiveLeaf(thread, other.id);
+ expect(task().activity).toBe("idle");
+ store.setActiveLeaf(thread, asked.id);
+ expect(task().activity).toBe("waiting-on-you");
+ });
+
+ it("restores what rested on the person after a restart, and leaves a card nobody answered for a week", () => {
+ const { store, waits, known, thread, task, bot } = fixture();
+ const left = store.createTask(bot.id, "Old work", false)!.threadId;
+ store.appendMessage(thread, { role: "bot", kind: "secret", text: "x", secret: { ...SECRET } });
+ store.appendMessage(left, { role: "bot", kind: "secret", text: "x", at: Date.now() - 8 * 24 * 60 * 60_000, secret: { ...SECRET } });
+ (store.bots as BotRecord[]).forEach((one) => one.tasks?.forEach((row) => { row.activity = "idle"; }));
+ known.add(thread).add(left);
+ waits.boot();
+ expect(task()).toMatchObject({ activity: "waiting-on-you", busy: false });
+ expect(store.bot(bot.id)?.busy).toBe(false);
+ expect(store.taskByThread(bot.id, left)?.activity).toBe("idle");
+ });
+});
+
+describe("telling the person", () => {
+ beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));
+
+ it("says what is needed for a password, once, from the bot that asked", async () => {
+ const { sent, card, thread, bot } = fixture();
+ card();
+ await flush();
+ expect(sent).toEqual([expect.objectContaining({ kind: "secret", botId: bot.id, threadId: thread, title: "Postie needs your Mailbox password", body: "To read the mail." })]);
+ });
+
+ it("says who and where for a sign-in and an app to connect", async () => {
+ const { store, sent, thread } = fixture();
+ store.appendMessage(thread, { role: "bot", kind: "signin", text: "sign in", signIn: { ...SIGN_IN } });
+ store.appendMessage(thread, { role: "bot", kind: "connector", text: "connect", connector: { slug: "gmail", label: "Gmail", description: "Read mail.", status: "required", resumeKey: "k" } });
+ await flush();
+ expect(sent.map(({ kind, title, body }) => ({ kind, title, body }))).toEqual([
+ { kind: "sign-in", title: "Postie needs you to sign in to example.com", body: "The dashboard is behind a login." },
+ { kind: "sign-in", title: "Postie needs you to connect Gmail", body: "Read mail." },
+ ]);
+ });
+
+ it("asks once for a proposal left open, and not for one applied at once", async () => {
+ const { store, sent, thread } = fixture();
+ const applied = store.appendMessage(thread, { role: "bot", kind: "options", card: { title: "New routine", options: ["Allow"], requestId: "a", mcpRequest: {} } as never });
+ store.patchMessage(thread, applied.id, { card: { ...applied.card!, autoApplied: true } });
+ store.appendMessage(thread, { role: "bot", kind: "options", card: { title: "New skill", options: ["Allow"], requestId: "b", mcpRequest: {} } as never });
+ await flush();
+ expect(sent).toEqual([expect.objectContaining({ kind: "approval", title: "Postie needs approval", body: "New skill" })]);
+ });
+
+ it("leaves a provider's question and approval to the path that already announces them", async () => {
+ const { store, sent, thread } = fixture();
+ store.appendMessage(thread, { role: "bot", kind: "options", card: { title: "Which?", options: ["A"], requestId: "q", requestType: "question" } as never });
+ store.appendMessage(thread, { role: "bot", kind: "options", card: { title: "Allow", options: ["Allow"], requestId: "p", tool: "Bash" } as never });
+ await flush();
+ expect(sent).toEqual([]);
+ });
+
+ it("does not ask for a card settled before anyone could hear of it", async () => {
+ const { store, sent, thread, card } = fixture();
+ const asked = card();
+ store.patchMessage(thread, asked.id, { secret: { ...SECRET, superseded: true } });
+ await flush();
+ expect(sent).toEqual([]);
+ });
+
+ it("stays quiet for the first hour's offer to connect an app", async () => {
+ const { store, sent, thread, task } = fixture();
+ store.appendMessage(thread, { role: "bot", kind: "connector", text: "connect", connector: { slug: "gmail", label: "Gmail", description: "", status: "required", resumeKey: "first-hour-1" } });
+ await flush();
+ expect(sent).toEqual([]);
+ expect(task().activity).toBe("idle");
+ });
+
+ it("does not call a turn finished when it rests on the person, and reminds them when they spoke since the card", async () => {
+ const { store, waits, sent, thread, card } = fixture();
+ expect(waits.atTurnEnd(thread, "Hello")).toBe(false);
+ card();
+ await flush();
+ sent.length = 0;
+ expect(waits.atTurnEnd(thread, "I asked for the password.")).toBe(true);
+ expect(sent).toEqual([]);
+ store.appendMessage(thread, { role: "user", kind: "text", text: "where is the card?" });
+ expect(waits.atTurnEnd(thread, "It is in this conversation.")).toBe(true);
+ expect(sent).toEqual([expect.objectContaining({ kind: "secret", title: "Postie needs your Mailbox password", body: "It is in this conversation." })]);
+ });
+
+ it("calls a turn finished once the card has settled", () => {
+ const { store, waits, thread, card } = fixture();
+ const asked = card();
+ store.patchMessage(thread, asked.id, { secret: { ...SECRET, provided: true } });
+ expect(waits.atTurnEnd(thread, "Read the mail.")).toBe(false);
+ });
+
+ it("honours a bot whose notifications are off", async () => {
+ const { store, sent, bot, card } = fixture();
+ store.patchBot(bot.id, { notifications: false } as never);
+ card();
+ await flush();
+ expect(sent).toEqual([]);
+ });
+});
diff --git a/server/host/person-waits.ts b/server/host/person-waits.ts
new file mode 100644
index 0000000000..116b0da2e2
--- /dev/null
+++ b/server/host/person-waits.ts
@@ -0,0 +1,133 @@
+// A conversation's turn ended with a card still open: it rests on the person, on every surface, until the card settles.
+// The state follows the card rows, so every way a card opens or closes (saved, declined, replaced, stopped, answered in
+// the chat, a restart, another branch) reads the same. A card a person isn't looking at reaches them by notification,
+// and a turn that ends resting on them says so instead of "finished".
+import { openPersonWait, personWait, restingOnPerson, type PersonWait } from "../../shared/person-wait.ts";
+import type { Notification } from "../../shared/notification.ts";
+import { NEEDS_YOU_WINDOW_MS } from "../../shared/today.ts";
+import { buildNotification } from "../notify.ts";
+import { conversationLanguage, serverLine } from "../server-lines.ts";
+import type { BotRecord, Message, Store } from "../store.ts";
+
+export interface PersonWaitsDeps {
+ store: Pick<Store, "activePath" | "bot" | "botByThread" | "groups" | "groupByThread" | "groupTaskByThread" | "patchGroupTask" | "setTaskActivity" | "taskByThread" | "onChange">;
+ notify(notification: Notification | null): void;
+ /** The conversations that may hold an open card asked since then. */
+ threadsWithCards(since: number): readonly string[];
+ now?: () => number;
+}
+
+const NOTIFIED_ELSEWHERE: ReadonlySet<PersonWait["kind"]> = new Set(["question", "approval"]);
+const CARD_ROWS: ReadonlySet<Message["kind"]> = new Set(["secret", "signin", "connector", "options"]);
+
+export function createPersonWaits(deps: PersonWaitsDeps) {
+ const { store } = deps;
+ const now = deps.now ?? Date.now;
+ const resting = new Map<string, PersonWait>();
+ const withCards = new Set<string>();
+
+ const askerOf = (threadId: string, wait: Pick<PersonWait, "botId">): BotRecord | null => (wait.botId ? store.bot(wait.botId) : null) ?? store.botByThread(threadId);
+
+ /** What this conversation rests on: a card older than the Needs you window has been left, and no longer asks. */
+ const restsOn = (threadId: string): PersonWait | undefined => {
+ const wait = restingOnPerson(store.activePath(threadId));
+ return wait && now() - wait.at < NEEDS_YOU_WINDOW_MS ? wait : undefined;
+ };
+
+ function show(threadId: string, wait: PersonWait | undefined): void {
+ const group = store.groupByThread(threadId);
+ if (group) {
+ const task = store.groupTaskByThread(group.id, threadId);
+ if (task && Boolean(task.activity) !== Boolean(wait)) store.patchGroupTask(group.id, threadId, { activity: wait ? "waiting-on-you" : null });
+ return;
+ }
+ const bot = store.botByThread(threadId);
+ const task = bot ? store.taskByThread(bot.id, threadId) : null;
+ if (!bot || !task || task.busy) return;
+ if (wait && (task.activity ?? "idle") === "idle") store.setTaskActivity(bot.id, threadId, "waiting-on-you", true);
+ else if (!wait && task.activity === "waiting-on-you") store.setTaskActivity(bot.id, threadId, "idle");
+ }
+
+ function refresh(threadId: string): void {
+ const wait = restsOn(threadId);
+ if (wait) resting.set(threadId, wait);
+ else resting.delete(threadId);
+ show(threadId, wait);
+ }
+
+ function announce(threadId: string, messageId: string): void {
+ const message = store.activePath(threadId).find((row) => row.id === messageId);
+ const wait = message && personWait(message);
+ if (!wait || NOTIFIED_ELSEWHERE.has(wait.kind)) return;
+ const detail = message.secret ? message.secret.reason ?? message.secret.description
+ : message.signIn ? message.signIn.reason ?? serverLine(conversationLanguage(threadId), "server.notify.openToSignIn", { site: wait.label })
+ : message.connector?.description ?? wait.label;
+ deps.notify(cardNotification(threadId, wait, detail));
+ }
+
+ function cardNotification(threadId: string, wait: PersonWait, detail: string): Notification | null {
+ const bot = askerOf(threadId, wait);
+ if (!bot) return null;
+ const group = store.groupByThread(threadId);
+ const extra = { avatarUrl: bot.avatarUrl, ...(group ? { group: { id: group.id, name: group.name } } : {}) };
+ const target = { ...bot, threadId };
+ switch (wait.kind) {
+ case "password": return buildNotification("secret", target, threadId, detail, { ...extra, label: wait.label });
+ case "sign-in": return buildNotification("sign-in", target, threadId, detail, { ...extra, site: wait.label });
+ case "connect": return buildNotification("sign-in", target, threadId, detail, { ...extra, app: wait.label });
+ case "question": return buildNotification("question", target, threadId, detail, extra);
+ default: return buildNotification("approval", target, threadId, detail, extra);
+ }
+ }
+
+ store.onChange((change) => {
+ if (change.type === "message" || change.type === "message.patch") {
+ if (!CARD_ROWS.has(change.message.kind)) return;
+ withCards.add(change.threadId);
+ refresh(change.threadId);
+ // A proposal applied at once (Full access) settles in the same tick it is added: only one left open asks.
+ if (change.type === "message") setImmediate(() => announce(change.threadId, change.message.id));
+ } else if (change.type === "thread") {
+ if (withCards.has(change.threadId)) refresh(change.threadId);
+ } else if (change.type === "thread.deleted") {
+ withCards.delete(change.threadId);
+ resting.delete(change.threadId);
+ } else if (change.type === "bot") {
+ for (const [threadId, wait] of resting) if (store.taskByThread(change.botId, threadId)) show(threadId, wait);
+ }
+ });
+
+ return {
+ /** Nothing is running after a restart: what rested on the person still does. */
+ boot(): void {
+ for (const group of store.groups) for (const task of group.tasks ?? []) if (task.activity) store.patchGroupTask(group.id, task.threadId, { activity: null });
+ for (const threadId of deps.threadsWithCards(now() - NEEDS_YOU_WINDOW_MS)) {
+ withCards.add(threadId);
+ refresh(threadId);
+ }
+ },
+ /** Every conversation resting on the person, newest first, by its card's kind: what an inbox lists beside the questions
+ * and approvals a running turn waits on. */
+ waiting(): Array<PersonWait & { threadId: string; botId: string }> {
+ return [...resting].flatMap(([threadId, wait]) => {
+ const bot = askerOf(threadId, wait);
+ return bot ? [{ ...wait, threadId, botId: bot.id }] : [];
+ }).sort((a, b) => b.at - a.at);
+ },
+ /** What this conversation waits on the person for, a running turn's approval included. */
+ open: (threadId: string): PersonWait | undefined => openPersonWait(store.activePath(threadId)),
+ /** At a turn's end: whether it rests on the person, so it isn't news that it finished. Asked again in a turn the person
+ * spoke into, the reminder carries the bot's reply. */
+ atTurnEnd(threadId: string, reply: string): boolean {
+ const wait = restsOn(threadId);
+ if (!wait) return false;
+ const path = store.activePath(threadId);
+ const card = path.findIndex((row) => row.id === wait.messageId);
+ const spokenSince = path.slice(card + 1).some((row) => row.role === "user" && !row.peerAsk && !row.relayed);
+ if (spokenSince) deps.notify(cardNotification(threadId, wait, reply || wait.label));
+ return true;
+ },
+ };
+}
+
+export type PersonWaits = ReturnType<typeof createPersonWaits>;
diff --git a/server/host/queued-reason.ts b/server/host/queued-reason.ts
index 10fca2e1ec..57365a7732 100644
--- a/server/host/queued-reason.ts
+++ b/server/host/queued-reason.ts
@@ -1,3 +1,4 @@
+import type { PersonWaitKind } from "../../shared/person-wait.ts";
import type { HandoffView } from "../coordinator.ts";
export interface QueuedReasonDeps {
@@ -8,7 +9,7 @@ export interface QueuedReasonDeps {
/** The bot's threads that hold a slot now, and how many it may run at once when a bot starts the work. */
slots(botId: string): { busy: { threadId: string; title: string }[]; limit: number };
groupTurn(botId: string): boolean;
- behindPerson(node: HandoffView): { kind: "approval" | "question" | "review"; title: string } | undefined;
+ behindPerson(node: HandoffView): { kind: PersonWaitKind; title: string } | undefined;
}
/** `showTitle`: name the busy threads it allows; only for the receiver itself, whose own threads they are. Otherwise just the count. */
diff --git a/server/host/teammate-prompts.ts b/server/host/teammate-prompts.ts
index 72db0fbd77..462185b647 100644
--- a/server/host/teammate-prompts.ts
+++ b/server/host/teammate-prompts.ts
@@ -1,5 +1,6 @@
// What a bot's turn is told about its teammates' open work: the assignments it still waits on, and, for a Chief, the
// questions teammates it manages wait on the person for.
+import type { PersonWait } from "../../shared/person-wait.ts";
import { chiefLevel } from "../chief-level.ts";
import type { HandoffView } from "../coordinator.ts";
import { escapeNotes } from "../peer-provenance.ts";
@@ -12,7 +13,7 @@ type WaitingQuestion = { bot: string; threadId: string; thread: string; question
export interface TeammatePromptDeps {
store: Pick<Store, "bots" | "bot">;
outstandingDirect(threadId: string): readonly HandoffView[];
- openPersonCard(threadId: string): { kind: "approval" | "question" | "review"; question?: string } | undefined;
+ openPersonCard(threadId: string): Pick<PersonWait, "kind" | "label"> | undefined;
queuedStatus(node: HandoffView): string;
isUnattended(botId: string, threadId: string): boolean;
fullAccess(botId: string, threadId: string): boolean;
@@ -36,8 +37,8 @@ export function createTeammatePrompts(deps: TeammatePromptDeps) {
return { requestId: node.id, bot: store.bot(node.botId)?.name ?? "Teammate", threadId: node.threadId, assignment: node.text.slice(0, 1_000),
status: node.status === "queued" ? deps.queuedStatus(node)
: card?.kind === "question" ? "stopped on its question in that teammate's thread; once you have the answer, send it there with coordinate_bots, or tell the person to open it"
- : card ? "stopped on a card waiting for the person's approval in that teammate's thread; tell the person to open it" : "working on it now",
- ...(card?.kind === "question" && card.question ? { question: escapeNotes(card.question).slice(0, 400) } : {}) };
+ : card ? "stopped on a card waiting for the person in that teammate's thread; tell the person to open it" : "working on it now",
+ ...(card?.kind === "question" && card.label ? { question: escapeNotes(card.label).slice(0, 400) } : {}) };
});
return ` Assignments you already sent are still outstanding, and nothing in this conversation cancelled them: ${JSON.stringify(listed)}. Do not resend them, do not poll or wait for them, and do not tell the user they were lost. Each result returns to this conversation on its own and resumes you then. To change or add to one, send the change to the same teammate with coordinate_bots, with its threadId as thread: it goes into that work, answering the question it waits on or reaching the turn running it. Answer the message above with that work still in flight.`;
}
diff --git a/server/index.ts b/server/index.ts
index 8104d276fa..1dca1cc291 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -23,8 +23,8 @@ import { cloudHomeLendingRefusal, createCloudRoutineAuthors, ownerOnlyConversati
import { botMemoryFiles, createLendingMemory } from "./lending-memory.ts";
import { SharedComputerControl } from "./shared-computer-control.ts";
import { createCoordinator, type ComposedTurn, type CoordinateBotsCall, type Coordinator, type HandoffOpener, type HandoffOptions, type HandoffView, type HostTurnResult } from "./coordinator.ts";
-import { queuedBehindPersonText, UnansweredApprovals } from "./waiting-on-person.ts";
-import { askToolName, createAskCards } from "./host/ask-cards.ts"; import { createQuestionRouting } from "./host/question-routing.ts"; import { workThreadFor } from "./host/work-thread.ts"; import { closedByStop, resumableCards as cardsWaitedOn } from "./host/resumable-cards.ts"; import { createMcpChat } from "./host/mcp-chat.ts"; import { isCardOwnerLive, isMcpSignInCard } from "./host/mcp-sign-in-cards.ts";
+import { queuedBehindPersonText, turnWaitedOnPerson, UnansweredApprovals } from "./waiting-on-person.ts";
+import { createPersonWaits } from "./host/person-waits.ts"; import { askToolName, createAskCards } from "./host/ask-cards.ts"; import { createQuestionRouting } from "./host/question-routing.ts"; import { workThreadFor } from "./host/work-thread.ts"; import { closedByStop, resumableCards as cardsWaitedOn } from "./host/resumable-cards.ts"; import { createMcpChat } from "./host/mcp-chat.ts"; import { isCardOwnerLive, isMcpSignInCard } from "./host/mcp-sign-in-cards.ts";
import { assertRequestTarget, guardedRequestPath, requestConflict, requestNeedsInput } from "./guarded-requests.ts";
import { botAvatarUrlFromStoredPath } from "../shared/bot-avatar.ts";
import { BOT_PROFILE_LIMITS } from "../shared/bot-profile.ts";
@@ -105,7 +105,7 @@ import { parseToolScope } from "../shared/tool-scope.ts";
import type { TeamComputersPayload } from "../shared/team-computer.ts";
import { boatCreateRecoverySnapshot } from "./boat-create-idempotency.ts";
import { boatDeletionSnapshot } from "./boat-delete-journal.ts";
-import { liveCardKind, liveDecisionRefusal } from "../shared/live-approval.ts";
+import { liveDecisionRefusal } from "../shared/live-approval.ts"; import type { PersonWaitKind } from "../shared/person-wait.ts";
import { vpsLeftBehindNotice } from "./cloud-backend.ts";
import * as composio from "./composio.ts";
import { connectorCallFromFrame, connectorRefusalText, connectorScopeRefusalText, connectorUnrecognizedText, evaluateConnectorTools } from "./connector-verdict.ts";
@@ -228,7 +228,7 @@ import { createOneOnOneGoals } from "./host/one-on-one-goals.ts";
import { BUILT_IN_DRIVERS } from "./drivers/builtIn.ts";
import { openCodeProviderKeysAllowed, setOpenCodeProviderKeyPolicy } from "./drivers/acp/opencode-go.ts";
-import { readMessageText, recallMessages, recentMessages, closeMessageSearch, closeMessageDb, chatFollowups, cancelledChatFollowup, settleChatFollowups, threadsReferencing, logNotification, lastRowAt } from "./message-db.ts";
+import { readMessageText, recallMessages, recentMessages, closeMessageSearch, closeMessageDb, chatFollowups, cancelledChatFollowup, settleChatFollowups, threadsReferencing, logNotification, lastRowAt, threadsWithCardsSince } from "./message-db.ts";
import { briefCrossingLabel, claimRecallCrossings, recallCrossingLabel } from "./recall-disclosure.ts";
import { parseSince, parseUntil, recentWork, recentWorkPrompt, turnOutcomeLine } from "./recent-work.ts";
import { chiefEscalationsEnabled, NEEDS_INPUT_GATE, peerApprovalGate, RAISED_GATE } from "./escalations.ts";
@@ -3845,10 +3845,10 @@ const queuedStatus = createQueuedReason({ botName: (id) => store.bot(id)?.name,
slots: (id) => ({ busy: store.tasks(id).filter((task) => threadBusy(id, task.threadId)).map(({ threadId, title }) => ({ threadId, title })), limit: maxConcurrentChildThreads(cfg, botThreadsHost(cloudPlanTier.starter())) }) });
const teammatePrompts = createTeammatePrompts({ store, outstandingDirect: (threadId) => coordinator.outstandingDirect(threadId), openPersonCard, queuedStatus, isUnattended, fullAccess: fullAccessForSource, startedOutside: (threadId) => directRequestOwners.get(threadId)?.origin?.kind === "outside" || coordinator.active().some((node) => node.threadId === threadId && node.origin?.kind === "outside"), guestDriven: cloudGuestDriven, confined: (threadId) => proactive.fence.confines(threadId), readableFrom: threadReadableFrom, waitingForPerson: (chief, teammates, readable) => questionRouting.waitingForPerson(chief, teammates, readable) });
-function queuedBehindPerson(node: HandoffView): { threadId: string; kind: "approval" | "question" | "review"; title: string } | undefined {
+function queuedBehindPerson(node: HandoffView): { threadId: string; kind: PersonWaitKind; title: string } | undefined {
if (node.groupId || node.status !== "queued" || threadBusy(node.botId, node.threadId) || !botAtThreadCapacity(node.botId, undefined, true)) return undefined;
for (const task of store.tasks(node.botId)) {
- if (task.threadId === node.threadId || task.activity !== "waiting-on-you") continue;
+ if (task.threadId === node.threadId || task.activity !== "waiting-on-you" || !task.busy) continue;
const card = openPersonCard(task.threadId);
if (card) return { threadId: task.threadId, kind: card.kind, title: task.title };
}
@@ -5028,7 +5028,7 @@ const providerLabel = (provider: string): string => {
};
// Rewritten by every dispatch, so a quiet turn never silences the next one.
-const quietTurnThreads = new Set<string>(); const doneNotice = createDoneNotice({ awaitingTeammates: (threadId) => coordinator.awaitingTeammateThreads().has(threadId), queuedFollowUp: hasQueuedPersonMessage });
+const quietTurnThreads = new Set<string>(); const doneNotice = createDoneNotice({ awaitingTeammates: (threadId) => coordinator.awaitingTeammateThreads().has(threadId), queuedFollowUp: hasQueuedPersonMessage }); const personWaits = createPersonWaits({ store, notify, threadsWithCards: threadsWithCardsSince });
const QUIET_TURN_NEWS: ReadonlySet<Notification["kind"]> = new Set(["done", "turn-failed", "incident"]);
function notify(notification: Notification | null, how?: { routine?: boolean }) {
@@ -6716,9 +6716,9 @@ bus.subscribe((event: RuntimeEvent) => {
if (event.requestId) pendingCommandRules.delete(`${event.threadId}:${event.requestId}`);
if (event.requestId) askCards.settleWaitingOnPersonChips(event.threadId, event);
const waiting = bot ?? (speaker ? store.bot(speaker.botId) : undefined);
- if (bot && store.taskByThread(bot.id, event.threadId)?.activity === "waiting-on-you") {
+ if (bot && turnWaitedOnPerson(store.taskByThread(bot.id, event.threadId))) {
store.setTaskActivity(bot.id, event.threadId, "working");
- } else if (!bot && waiting?.activity === "waiting-on-you") store.setActivity(waiting.id, "working");
+ } else if (!bot && turnWaitedOnPerson(waiting)) store.setActivity(waiting.id, "working");
const messageId = event.requestId ? askMessageByRequest.get(`${event.threadId}:${event.requestId}`) : null;
if (messageId) {
const existing = store.messagesFor(event.threadId).find((m) => m.id === messageId);
@@ -6940,7 +6940,7 @@ bus.subscribe((event: RuntimeEvent) => {
const routineReportThread = routineRun ? routineSourceThread(routineRun) : null;
if (!routineReportThread && (!internal || reviewAnswer)) store.patchTask(bot.id, event.threadId, { unread: true });
if (routineRun && routineReportThread !== event.threadId) automationReports.runSettled(routineRun, completedTurnId);
- else if ((!routineRun || routineRun.status === "completed") && (!internal || reviewAnswer) && !computerSelectionTurns.get(event.threadId)?.selected && doneNotice.atTurnEnd({ botId: bot.id, threadId: event.threadId, review: reviewAnswer, ok: event.ok, routine: Boolean(routineRun) }) === "notify") {
+ else if ((!routineRun || routineRun.status === "completed") && (!internal || reviewAnswer) && !computerSelectionTurns.get(event.threadId)?.selected && doneNotice.atTurnEnd({ botId: bot.id, threadId: event.threadId, review: reviewAnswer, ok: event.ok, routine: Boolean(routineRun) }) === "notify" && !personWaits.atTurnEnd(event.threadId, reply)) {
notify(buildNotification("done", bot, event.threadId, routineRun ? reply || routineRun.output || routineRun.routineName : reply, { avatarUrl: bot.avatarUrl }), routineRun ? { routine: true } : undefined);
}
if (screenPollers.has(event.threadId)) {
@@ -7015,15 +7015,7 @@ bus.subscribe((event: RuntimeEvent) => {
}
});
-function openPersonCard(threadId: string): { kind: "approval" | "question" | "review"; tool?: string; question?: string } | undefined {
- const messages = store.messagesFor(threadId);
- for (let i = messages.length - 1; i >= 0; i--) {
- const card = messages[i]!.kind === "options" ? messages[i]!.card : undefined;
- const kind = liveCardKind(card);
- if (kind) return { kind, tool: card?.tool, question: card?.subtitle };
- }
- return undefined;
-}
+function openPersonCard(threadId: string) { return personWaits.open(threadId); }
function delegatorOf(threadId: string): { threadId: string; botId?: string } | undefined {
const parent = coordinator.assignerOf(threadId);
@@ -11716,11 +11708,6 @@ function requestSignIn(from: BotRecord, threadId: string, rawSite: unknown, rawR
}
computerControl.requestHelp(signInControlKey(from, threadId, place), `sign in to ${target.site}`,
{ botId: from.id, threadId, messageId: message.id, site: target.site, place });
- notify(buildNotification("sign-in", { ...from, threadId }, threadId, reason || serverLine(threadLanguage(threadId), "server.notify.openToSignIn", { site: target.site }), {
- avatarUrl: from.avatarUrl,
- ...(owner.group ? { group: { id: owner.group.id, name: owner.group.name } } : {}),
- site: target.site,
- }));
return { messageId: message.id, site: target.site, place };
}
@@ -15667,7 +15654,7 @@ if (CLOUD_HOME) registerCloudPower(cloudPower = createCloudPower({ dataDir: DATA
server.listen(PORT, "127.0.0.1", async () => {
companyRuntimeReady();
console.log(`openmausbot server on http://127.0.0.1:${PORT}`);
- browserSweep.start(); startCloudTeamPolicy({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, managed: managedPolicy, sessions }); moveFreeze.hold(() => appTriggers.start(), () => void appTriggers.stop()); startCloudHomeConnectedApps({ cloudHome: CLOUD_HOME !== null, dataDir: DATA_DIR, cloudGrant: CLOUD_ENV.OMB_CLOUD_CONNECTED_APPS_GRANT, apply: (access) => { composio.setManagedBrokerAccess(access); broadcast({ kind: "config", ...configStatus() }); } });
+ personWaits.boot(); browserSweep.start(); startCloudTeamPolicy({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, managed: managedPolicy, sessions }); moveFreeze.hold(() => appTriggers.start(), () => void appTriggers.stop()); startCloudHomeConnectedApps({ cloudHome: CLOUD_HOME !== null, dataDir: DATA_DIR, cloudGrant: CLOUD_ENV.OMB_CLOUD_CONNECTED_APPS_GRANT, apply: (access) => { composio.setManagedBrokerAccess(access); broadcast({ kind: "config", ...configStatus() }); } });
void afterFirstEngineRead().then(() => { if (builtInBrowserEnabled(cfg)) chromeLauncher.start(); });
followupsReady = true;
drainQueuedSends();
diff --git a/server/mausbot-notifications.ts b/server/mausbot-notifications.ts
index 9842399e72..bd6f82f34f 100644
--- a/server/mausbot-notifications.ts
+++ b/server/mausbot-notifications.ts
@@ -23,6 +23,7 @@ const LEAN: Record<NotifyKind, Lean> = {
approval: "needs-you",
question: "needs-you",
"sign-in": "needs-you",
+ secret: "needs-you",
incident: "needs-you",
"turn-failed": "needs-you",
"routine-failed": "needs-you",
diff --git a/server/message-db.ts b/server/message-db.ts
index cc4f71d3ce..8f812f2485 100644
--- a/server/message-db.ts
+++ b/server/message-db.ts
@@ -18,6 +18,7 @@ const DB_FILE = () => join(DATA_DIR, "messages.db");
/** The rows the Today page reads, and among them the failed tool calls. JSON.stringify escapes every quote inside a
* string value, so a stored row holds the bare text "ok":false only as a real key. */
const WORK_KINDS = "kind IN ('activity', 'digest', 'options')";
+const CARD_KINDS = "kind IN ('secret', 'signin', 'connector')";
const FAILED_CALL = "kind = 'activity' AND instr(json, '\"ok\":false') > 0";
let handle: DatabaseSync | null = null;
@@ -58,6 +59,7 @@ function open(): DatabaseSync {
CREATE INDEX IF NOT EXISTS messages_thread_at ON messages(thread_id, at);
-- Partial, so no other query's plan can move onto them: only a statement that repeats the WHERE may use one.
CREATE INDEX IF NOT EXISTS messages_work_at ON messages(kind, at) WHERE ${WORK_KINDS};
+ CREATE INDEX IF NOT EXISTS messages_cards_at ON messages(kind, at) WHERE ${CARD_KINDS};
CREATE INDEX IF NOT EXISTS messages_failed_at ON messages(at) WHERE ${FAILED_CALL};
CREATE TABLE IF NOT EXISTS thread_state (
thread_id TEXT PRIMARY KEY,
@@ -559,6 +561,16 @@ export function attentionRows(since: number): AttentionRow[] {
).all(since, since, since) as unknown as AttentionRow[];
}
+/** The conversations with a card asked since `since` that has not been answered, oldest first; the caller reads each card. */
+export function threadsWithCardsSince(since: number): string[] {
+ const rows = db().prepare(
+ `SELECT DISTINCT thread_id AS threadId FROM messages INDEXED BY messages_cards_at WHERE ${CARD_KINDS} AND at >= ? ` +
+ `UNION SELECT DISTINCT thread_id AS threadId FROM messages INDEXED BY messages_work_at WHERE ${WORK_KINDS} AND kind = 'options' AND at >= ? ` +
+ "AND json_extract(json, '$.card.requestId') IS NOT NULL AND json_extract(json, '$.card.answered') IS NULL AND coalesce(json_extract(json, '$.card.dismissed'), 0) = 0",
+ ).all(since, since) as Array<{ threadId: string }>;
+ return rows.map((row) => row.threadId);
+}
+
/** Successful tool calls after a time whose row mentions `word` (case-insensitive), newest last. */
export function successfulCallsMentioning(since: number, word: string): Array<{ at: number; name: string; input: string | null }> {
return db().prepare(
diff --git a/server/notify.ts b/server/notify.ts
index 03f97d75df..c521ea91b8 100644
--- a/server/notify.ts
+++ b/server/notify.ts
@@ -47,16 +47,18 @@ export function buildNotification(
bot: Omit<NotifyBot, "threadId"> & { threadId?: string },
threadId: string,
detail: string,
- extra?: { avatarUrl?: string; group?: { id: string; name: string }; site?: string },
+ extra?: { avatarUrl?: string; group?: { id: string; name: string }; site?: string; label?: string; app?: string },
): Notification | null {
if (bot.notifications === false) return null;
const body = summarize(detail);
const language = conversationLanguage(threadId);
const who = extra?.group ? serverLine(language, "server.notify.inRoom", { bot: bot.name, room: extra.group.name }) : bot.name;
- const title = kind === "sign-in"
- ? extra?.site ? serverLine(language, "server.notify.signIn", { who, site: extra.site }) : serverLine(language, "server.notify.signInWebsite", { who })
- : serverLine(language, TITLE[kind] ?? "server.notify.done", { who });
+ const title = kind === "secret" ? serverLine(language, "server.notify.secret", { who, label: extra?.label ?? "" })
+ : kind === "sign-in"
+ ? extra?.app ? serverLine(language, "server.notify.connect", { who, app: extra.app })
+ : extra?.site ? serverLine(language, "server.notify.signIn", { who, site: extra.site }) : serverLine(language, "server.notify.signInWebsite", { who })
+ : serverLine(language, TITLE[kind] ?? "server.notify.done", { who });
if ((kind === "done" || kind === "mention") && !body) return null;
diff --git a/server/outbound-hold.ts b/server/outbound-hold.ts
index e0d24d9c7b..234bb87056 100644
--- a/server/outbound-hold.ts
+++ b/server/outbound-hold.ts
@@ -8,6 +8,7 @@ import type { OutboundCounts } from "./outbound-counts.ts";
import type { OutboundRequestService } from "./outbound-requests.ts";
import { outboundCard } from "./outbound-requests.ts";
import type { BotRecord, GroupRecord, Store } from "./store.ts";
+import { turnWaitedOnPerson } from "./waiting-on-person.ts";
/** How long a "Send on your behalf?" card waits on the person before it times out. */
export const OUTBOUND_HOLD_MS = 9 * 60_000;
@@ -88,8 +89,8 @@ export function createOutboundHold(deps: OutboundHoldDeps): OutboundHold {
if (active()) {
const waiting = store.bot(currentSender.id);
if (owner?.group) {
- if (activeGroupTurnForBot(currentSender.id)?.threadId === threadId && waiting?.activity === "waiting-on-you") store.setActivity(waiting.id, "working");
- } else if (store.taskByThread(currentSender.id, threadId)?.activity === "waiting-on-you") {
+ if (activeGroupTurnForBot(currentSender.id)?.threadId === threadId && turnWaitedOnPerson(waiting)) store.setActivity(waiting.id, "working");
+ } else if (turnWaitedOnPerson(store.taskByThread(currentSender.id, threadId))) {
store.setTaskActivity(currentSender.id, threadId, "working");
}
}
diff --git a/server/peer-approval.ts b/server/peer-approval.ts
index acc11d7522..cd5485dec0 100644
--- a/server/peer-approval.ts
+++ b/server/peer-approval.ts
@@ -5,6 +5,7 @@ import { optionCardsForTools } from "./message-db.ts";
import { buildNotification, type Notification } from "./notify.ts";
import { peerAllowKey, type PeerAction } from "./peer-approval-key.ts";
import type { BotRecord, Message, Store } from "./store.ts";
+import { turnWaitedOnPerson } from "./waiting-on-person.ts";
export { peerAllowKey } from "./peer-approval-key.ts";
@@ -54,10 +55,10 @@ function settleCard(pending: Pending, behavior: string, source: "user" | "system
const store = pending.bus.store;
const task = store.projectBotForTask(pending.fromBotId, pending.threadId);
if (task) {
- if (task.activity === "waiting-on-you") store.setTaskActivity(task.id, pending.threadId, "working");
+ if (turnWaitedOnPerson(task)) store.setTaskActivity(task.id, pending.threadId, "working");
} else if (store.groupByThread(pending.threadId)) {
const waiting = store.bot(pending.fromBotId);
- if (waiting?.activity === "waiting-on-you") store.setActivity(waiting.id, "working");
+ if (turnWaitedOnPerson(waiting)) store.setActivity(waiting.id, "working");
}
}
diff --git a/server/person-waits.e2e.test.ts b/server/person-waits.e2e.test.ts
new file mode 100644
index 0000000000..b0fadbc96d
--- /dev/null
+++ b/server/person-waits.e2e.test.ts
@@ -0,0 +1,181 @@
+// A bot asks for a password and ends its turn. Real server and agents tools on the fake engine: the person hears about
+// it, every surface says the conversation waits on them, and only settling the card ends that. Nothing here reaches the
+// user's data or port 8799.
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+import { hostTimeout } from "./testing/host-timeout.ts";
+import { launchRestartableServer, type RestartableServer } from "./testing/restartable-server.ts";
+
+const ASK = { tool: "request_credential", arguments: { label: "Mailbox password", reason: "To read the mail.", delivery: "ref" } };
+
+async function scenario(test: (f: Awaited<ReturnType<typeof fixture>>) => Promise<void>): Promise<void> {
+ const server = await launchRestartableServer({ scripted: true });
+ try {
+ await test(await fixture(server));
+ } finally {
+ await server.close();
+ }
+}
+
+async function fixture(server: RestartableServer) {
+ const { url, planPath } = server;
+ const api = async (path: string, body?: unknown, method = body === undefined ? "GET" : "POST") => {
+ const response = await fetch(url + path, { method, headers: { "content-type": "application/json", origin: url }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
+ const parsed = await response.json() as any;
+ expect(response.status, `${method} ${path}: ${JSON.stringify(parsed)}`).toBeLessThan(300);
+ return parsed;
+ };
+ const bot = (await api("/api/bots", { name: "Postie" })).bot;
+ const chief = (await api("/api/bots", { name: "Clive" })).bot;
+ const task = async (threadId: string, botId = bot.id) => (await api("/api/bots?messages=0")).bots.find((one: any) => one.id === botId).tasks.find((row: any) => row.threadId === threadId);
+ const owner = async (botId = bot.id) => (await api("/api/bots?messages=0")).bots.find((one: any) => one.id === botId);
+ const notes = async () => (await api("/api/notifications")).notifications as any[];
+ const notesOf = async (kind: string, botId = bot.id) => (await notes()).filter((note) => note.kind === kind && note.botId === botId);
+ const messages = async (threadId: string) => (await api(`/api/threads/${threadId}/messages`)).messages as any[];
+ const card = async (threadId: string, label = "Mailbox password") => (await messages(threadId)).findLast((message) => message.secret?.label === label);
+ const say = (threadId: string, text: string, botId = bot.id) => api(`/api/bots/${botId}/messages`, { text, threadId, sendId: crypto.randomUUID() });
+ const turns = () => existsSync(`${planPath}.evidence.jsonl`) ? readFileSync(`${planPath}.evidence.jsonl`, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)) : [];
+ const said = async (threadId: string, text: string) => expect.poll(async () => (await messages(threadId)).some((message) => message.text === text && message.turnTerminal), { timeout: 20_000 }).toBe(true);
+ const settled = (threadId: string) => expect.poll(async () => (await task(threadId))?.busy, { timeout: 20_000 }).toBe(false);
+ return { server, api, bot, chief, task, owner, notes, notesOf, messages, card, say, turns, said, settled, plan: (plan: unknown) => writeFileSync(planPath, JSON.stringify(plan)) };
+}
+
+it("a card in the person's own conversation: they are told, it waits on them, and no \"finished\" says otherwise", () => scenario(async (f) => {
+ f.plan({ [f.bot.id]: { script: [
+ { key: "ask", match: ["READ-MAIL"], steps: [ASK], reply: "ASKED: waiting for the password." },
+ { key: "where", match: ["WHERE"], reply: "STILL: the card is in this conversation." },
+ { key: "resume", match: ["secret update"], reply: "RESUMED: no password, so no mail." },
+ ] } });
+ const thread = f.bot.threadId;
+ await f.say(thread, "READ-MAIL please");
+ await f.said(thread, "ASKED: waiting for the password.");
+ await f.settled(thread);
+
+ await expect.poll(() => f.task(thread), { timeout: 10_000 }).toMatchObject({ activity: "waiting-on-you", busy: false });
+ expect(await f.owner()).toMatchObject({ activity: "waiting-on-you", busy: false });
+ await expect.poll(() => f.notesOf("secret"), { timeout: 10_000 }).toHaveLength(1);
+ expect((await f.notesOf("secret"))[0]).toMatchObject({ threadId: thread, title: "Postie needs your Mailbox password", body: "To read the mail." });
+ expect(await f.notesOf("done")).toEqual([]);
+ expect((await f.api("/api/needs-you")).items).toEqual([expect.objectContaining({ kind: "question", threadId: thread, botId: f.bot.id, text: expect.stringContaining("Mailbox password") })]);
+
+ // Their next line still runs a turn, and the reply reaches them as the card it waits on, never as "finished".
+ await f.say(thread, "WHERE is the card?");
+ await f.said(thread, "STILL: the card is in this conversation.");
+ await f.settled(thread);
+ await expect.poll(() => f.task(thread), { timeout: 10_000 }).toMatchObject({ activity: "waiting-on-you", busy: false });
+ await expect.poll(() => f.notesOf("secret"), { timeout: 10_000 }).toHaveLength(2);
+ expect((await f.notesOf("secret"))[0]).toMatchObject({ title: "Postie needs your Mailbox password", body: "STILL: the card is in this conversation." });
+ expect(await f.notesOf("done")).toEqual([]);
+ expect((await f.api("/api/needs-you")).items).toEqual([expect.objectContaining({ threadId: thread, text: expect.stringContaining("Mailbox password") })]);
+
+ // Declining settles it: nothing waits on them, and the bot's next word is ordinary news again.
+ const asked = await f.card(thread);
+ await f.api(`/api/bots/${f.bot.id}/secret-cards/${asked.id}/dismiss`, { threadId: thread });
+ await f.said(thread, "RESUMED: no password, so no mail.");
+ await f.settled(thread);
+ await expect.poll(() => f.task(thread), { timeout: 10_000 }).toMatchObject({ activity: "idle", busy: false });
+ expect((await f.owner()).busy).toBe(false);
+ expect((await f.api("/api/needs-you")).items).toEqual([]);
+ await expect.poll(() => f.notesOf("done"), { timeout: 10_000 }).toHaveLength(1);
+}), hostTimeout(90_000));
+
+it("a card in work a bot handed on reaches the person, and saving it carries the work on", () => scenario(async (f) => {
+ f.plan({
+ [f.chief.id]: { script: [
+ { key: "hand", match: ["GET-MAIL"], steps: [{ arguments: { bot_ids: [f.bot.id], message: "WORK: read the mail", thread: "new" } }], reply: "HANDED: Postie is on it." },
+ { key: "any", match: [], repeat: true, reply: "BACK: noted." },
+ ] },
+ [f.bot.id]: { script: [
+ { key: "ask", match: ["WORK"], steps: [ASK], reply: "ASKED: waiting for the password." },
+ { key: "resume", match: ["secret update"], reply: "DONE: the mail is read." },
+ { key: "any", match: [], repeat: true, reply: "OK" },
+ ] },
+ });
+ await f.say(f.chief.threadId, "GET-MAIL please", f.chief.id);
+ let work: any;
+ await expect.poll(async () => {
+ work = (await f.owner()).tasks.find((row: any) => row.openedBy?.botId === f.chief.id);
+ return work?.threadId && (await f.card(work.threadId)) !== undefined;
+ }, { timeout: 20_000 }).toBe(true);
+ await f.said(work.threadId, "ASKED: waiting for the password.");
+ await f.settled(work.threadId);
+
+ await expect.poll(() => f.task(work.threadId), { timeout: 10_000 }).toMatchObject({ activity: "waiting-on-you", busy: false });
+ await expect.poll(() => f.notesOf("secret"), { timeout: 10_000 }).toHaveLength(1);
+ expect((await f.notesOf("secret"))[0]).toMatchObject({ threadId: work.threadId, title: "Postie needs your Mailbox password" });
+ expect(await f.notesOf("done")).toEqual([]);
+ expect(await f.notesOf("delegation-settled"), "work resting on a person has no results to announce").toEqual([]);
+
+ const asked = await f.card(work.threadId);
+ await f.api(`/api/bots/${f.bot.id}/secret-cards/${asked.id}/save`, { threadId: work.threadId, value: "not-a-real-password" });
+ await f.said(work.threadId, "DONE: the mail is read.");
+ await f.settled(work.threadId);
+ await expect.poll(() => f.task(work.threadId), { timeout: 10_000 }).toMatchObject({ activity: "idle", busy: false });
+}), hostTimeout(90_000));
+
+it("what rested on the person still does after a restart, with no second notification", () => scenario(async (f) => {
+ f.plan({ [f.bot.id]: { script: [
+ { key: "ask", match: ["READ-MAIL"], steps: [ASK], reply: "ASKED: waiting for the password." },
+ { key: "any", match: [], repeat: true, reply: "OK" },
+ ] } });
+ const thread = f.bot.threadId;
+ await f.say(thread, "READ-MAIL please");
+ await f.said(thread, "ASKED: waiting for the password.");
+ await f.settled(thread);
+ await expect.poll(() => f.notesOf("secret"), { timeout: 10_000 }).toHaveLength(1);
+
+ await f.server.stop();
+ await f.server.start();
+ await expect.poll(() => f.task(thread), { timeout: 20_000 }).toMatchObject({ activity: "waiting-on-you", busy: false });
+ expect(await f.notesOf("secret")).toHaveLength(1);
+ const asked = await f.card(thread);
+ await f.api(`/api/bots/${f.bot.id}/secret-cards/${asked.id}/dismiss`, { threadId: thread });
+ await expect.poll(async () => (await f.task(thread)).activity, { timeout: 20_000 }).not.toBe("waiting-on-you");
+}), hostTimeout(90_000));
+
+it("a card a webhook's run asks for reaches the person, and its report is not called finished", () => scenario(async (f) => {
+ f.plan({ [f.bot.id]: { script: [
+ { key: "hook", match: ["new-mail-signal"], repeat: true, steps: [ASK], reply: "ASKED: waiting for the password." },
+ { key: "any", match: [], repeat: true, reply: "OK" },
+ ] } });
+ const hook = await f.api("/api/webhooks", { name: "New mail", prompt: "new-mail-signal: check the mailbox", botId: f.bot.id });
+ const fired = await fetch(hook.credential.url, { method: "POST", headers: { authorization: `Bearer ${hook.credential.secret}`, "content-type": "application/json" }, body: "{}" });
+ expect(fired.status).toBe(202);
+ await expect.poll(() => f.notesOf("secret"), { timeout: 20_000 }).toHaveLength(1);
+ const thread = (await f.notesOf("secret"))[0].threadId;
+ expect((await f.card(thread))).toBeDefined();
+ await f.settled(thread);
+ await expect.poll(() => f.task(thread), { timeout: 10_000 }).toMatchObject({ activity: "waiting-on-you", busy: false });
+ expect(await f.notesOf("done")).toEqual([]);
+}), hostTimeout(90_000));
+
+it("work queued for a bot busy elsewhere does not blame a card that holds no slot", () => scenario(async (f) => {
+ const gate = join(f.server.dataDir, "free-the-slot");
+ f.plan({
+ [f.chief.id]: { script: [
+ { key: "hand", match: ["GET-MAIL"], steps: [{ arguments: { bot_ids: [f.bot.id], message: "WORK: read the mail", thread: "new" } }], reply: "HANDED: Postie is on it." },
+ { key: "any", match: [], repeat: true, reply: "BACK: noted." },
+ ] },
+ [f.bot.id]: { script: [
+ { key: "ask", match: ["READ-MAIL"], steps: [ASK], reply: "ASKED: waiting for the password." },
+ { key: "busy", match: ["BUSY"], gateFile: gate, timeoutMs: 60_000, reply: "FREE: the other job is done." },
+ { key: "any", match: [], repeat: true, reply: "OK" },
+ ] },
+ });
+ const thread = f.bot.threadId;
+ await f.say(thread, "READ-MAIL please");
+ await f.said(thread, "ASKED: waiting for the password.");
+ await expect.poll(() => f.task(thread), { timeout: 10_000 }).toMatchObject({ activity: "waiting-on-you", busy: false });
+ await f.api("/api/config", { threads: { maxConcurrentPerBot: 1 } }, "PATCH");
+ const { task } = await f.api(`/api/bots/${f.bot.id}/tasks`, { title: "Other job", select: false });
+ await f.say(task.threadId, "BUSY for a while");
+ await expect.poll(async () => (await f.task(task.threadId))?.busy, { timeout: 15_000 }).toBe(true);
+
+ await f.say(f.chief.threadId, "GET-MAIL please", f.chief.id);
+ await f.said(f.chief.threadId, "HANDED: Postie is on it.");
+ await new Promise((resolve) => setTimeout(resolve, 1_500));
+ expect((await f.messages(f.chief.threadId)).filter((message) => String(message.tool?.name ?? "").includes("behind your"))).toEqual([]);
+ writeFileSync(gate, "go");
+ await f.said(task.threadId, "FREE: the other job is done.");
+}), hostTimeout(90_000));
diff --git a/server/runtime-roots.e2e.test.ts b/server/runtime-roots.e2e.test.ts
index cc4c9d45d5..3f6edd556d 100644
--- a/server/runtime-roots.e2e.test.ts
+++ b/server/runtime-roots.e2e.test.ts
@@ -254,7 +254,7 @@ it("T2 parks the root on a credential card and runs it again with the provided l
expect(f.eventsOf(parked.id)).toContain("parked");
await f.settle(500);
expect(f.turns(f.clive.id).map((record: any) => record.planKey)).toEqual(["C0"]);
- expect(await f.task(f.clive.id, job)).toMatchObject({ busy: false, activity: "idle" });
+ expect(await f.task(f.clive.id, job)).toMatchObject({ busy: false, activity: "waiting-on-you" });
f.script(f.clive.id, { key: "C-TYPED", match: ["T2-TYPED"], reply: "T2-TYPED-DONE: hello back." });
await f.say(f.clive.id, job, "T2-TYPED: hello while the card waits.");
await f.final(job, "T2-TYPED-DONE");
@@ -300,7 +300,7 @@ it("T3 parks the root on connector cards and runs it again once when both connec
await expect.poll(() => f.roots()[0]?.status, { timeout: 15_000 }).toBe("needs_input");
const parked = f.roots()[0];
expect(parked.cards).toEqual([gmail, slack]);
- expect(await f.task(f.clive.id, job)).toMatchObject({ busy: false, activity: "idle" });
+ expect(await f.task(f.clive.id, job)).toMatchObject({ busy: false, activity: "waiting-on-you" });
composio.connect("gmail");
const first = await f.api("GET", `/api/bots/${f.clive.id}/connector-cards/${gmail}/status?threadId=${job}`);
expect(first.body).toMatchObject({ connected: true });
@@ -635,7 +635,7 @@ it("T9 parks the root on a sign-in card and runs it again with the signed-in lin
const parked = f.roots()[0];
expect(parked).toMatchObject({ status: "needs_input", cards: [card.id], executions: 1, question: expect.stringContaining("sign in to example.com") });
expect(card.signIn.resumed).toBeUndefined();
- expect(await f.task(f.clive.id, job)).toMatchObject({ busy: false, activity: "idle" });
+ expect(await f.task(f.clive.id, job)).toMatchObject({ busy: false, activity: "waiting-on-you" });
const done = await f.api("POST", `/api/bots/${f.clive.id}/sign-in-cards/${card.id}/done`, { threadId: job });
expect(done.status, JSON.stringify(done.body)).toBe(200);
expect(done.body).toEqual({ done: true, resumed: true });
diff --git a/server/secret-requests.e2e.test.ts b/server/secret-requests.e2e.test.ts
index 329e769567..66f90738aa 100644
--- a/server/secret-requests.e2e.test.ts
+++ b/server/secret-requests.e2e.test.ts
@@ -159,7 +159,7 @@ it("keeps a file secret and a ref secret out of every record, and the bot uses e
// A file for the bot's own commands.
expect((await tools.call("request_credential", { label: "Stripe secret key", reason: "To create test charges." })).text).toMatch(/needs delivery/u);
const askedFile = await tools.call("request_credential", { label: "Stripe secret key", reason: "To create test charges.", placeholder: "sk_test_…", delivery: "file" });
- expect(askedFile).toEqual({ isError: false, text: expect.stringMatching(/^A secure card for Stripe secret key is ready/u) });
+ expect(askedFile).toEqual({ isError: false, text: expect.stringMatching(/^A secure card for Stripe secret key is now in this conversation/u) });
const fileCard = (await cards()).at(-1);
expect(fileCard.secret).toMatchObject({ target: "customSecret", label: "Stripe secret key", placeholder: "sk_test_…", helpUrl: "", delivery: "file", reason: "To create test charges." });
expect(fileCard.secret.description).toBe("To create test charges. Ledger's commands can read it from a private file for 24 hours; it is never added to chat.");
diff --git a/server/store.ts b/server/store.ts
index 9cde89b0b6..67d1ba5ec5 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -108,7 +108,7 @@ const TASK_PATCH_FIELDS = [
] as const satisfies readonly (keyof TaskRecord)[];
export type TaskPatch = Partial<Pick<TaskRecord, typeof TASK_PATCH_FIELDS[number]>>;
-export type GroupTaskPatch = Partial<Pick<GroupTaskRecord, "title" | "pinned">> & { turnTimeoutMinutes?: number | null; archivedAt?: number | null };
+export type GroupTaskPatch = Partial<Pick<GroupTaskRecord, "title" | "pinned">> & { turnTimeoutMinutes?: number | null; archivedAt?: number | null; activity?: "waiting-on-you" | null };
function mirrorActiveGroupTask(group: GroupRecord, task: GroupTaskRecord): void {
Object.assign(group, { threadId: task.threadId, pinnedCwd: task.pinnedCwd, pinnedMessageId: task.pinnedMessageId });
@@ -1049,8 +1049,8 @@ export class Store {
if (!group || !task) return null;
this.commitGroupChange(group, "the thread change", () => {
if (patch.title !== undefined) task.title = patch.title.trim().slice(0, 80) || UNTITLED_TASK;
- if (patch.pinned) task.pinned = true;
- else if (patch.pinned === false) delete task.pinned;
+ if (patch.pinned) task.pinned = true; else if (patch.pinned === false) delete task.pinned;
+ if (patch.activity) task.activity = patch.activity; else if (patch.activity === null) delete task.activity;
for (const key of ["turnTimeoutMinutes", "archivedAt"] as const) if (patch[key] === null) delete task[key]; else if (patch[key] !== undefined) task[key] = patch[key];
});
this.emit({ type: "group", groupId });
@@ -1670,11 +1670,11 @@ export class Store {
return bot;
}
- setTaskActivity(botId: string, threadId: string, activity: BotActivity): BotRecord | null {
+ setTaskActivity(botId: string, threadId: string, activity: BotActivity, noTurnRunning = false): BotRecord | null {
const bot = this.bot(botId);
const task = this.taskByThread(botId, threadId);
if (!bot || !task) return null;
- const busy = ACTIVITY_BUSY.has(activity);
+ const busy = ACTIVITY_BUSY.has(activity) && !noTurnRunning;
if ((task.activity ?? "idle") === activity && Boolean(task.busy) === busy) return bot;
const wasBusy = Boolean(task.busy);
task.activity = activity;
@@ -1694,7 +1694,7 @@ export class Store {
const activities = [this.legacyActivities.get(bot.id), ...(bot.tasks ?? []).map((task) => task.activity)];
bot.activity = (["waiting-on-you", "no-signal", "working", "dead"] as const)
.find((activity) => activities.includes(activity)) ?? "idle";
- bot.busy = ACTIVITY_BUSY.has(bot.activity);
+ bot.busy = ACTIVITY_BUSY.has(this.legacyActivities.get(bot.id) ?? "idle") || (bot.tasks ?? []).some((task) => task.busy);
}
/** Makes `id` its scope's one Chief (its owner's on a Team Cloud, else its department's), or with no `id` leaves
diff --git a/server/waiting-on-person.test.ts b/server/waiting-on-person.test.ts
index 66ba3b8786..920d5721a9 100644
--- a/server/waiting-on-person.test.ts
+++ b/server/waiting-on-person.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { queuedBehindPersonText, settledWaitingChip, UnansweredApprovals } from "./waiting-on-person.ts";
+import { queuedBehindPersonText, settledWaitingChip, turnWaitedOnPerson, UnansweredApprovals } from "./waiting-on-person.ts";
describe("the waiting-on-you chip once its card settles", () => {
it.each([
@@ -20,6 +20,15 @@ describe("the waiting-on-you chip once its card settles", () => {
});
});
+describe("an answer the person gives", () => {
+ it("sets a running turn that waited on them working again, and leaves a conversation resting on a card waiting", () => {
+ expect(turnWaitedOnPerson({ activity: "waiting-on-you", busy: true })).toBe(true);
+ expect(turnWaitedOnPerson({ activity: "waiting-on-you", busy: false })).toBe(false);
+ expect(turnWaitedOnPerson({ activity: "idle", busy: false })).toBe(false);
+ expect(turnWaitedOnPerson(undefined)).toBe(false);
+ });
+});
+
describe("work queued behind the person's card", () => {
it("names whose card and where, in words that stay true once it is answered", () => {
expect(queuedBehindPersonText("Mira", "approval", "@Clive · work")).toBe("Queued for @Mira behind your approval in “@Clive · work”");
diff --git a/server/waiting-on-person.ts b/server/waiting-on-person.ts
index 3049968ad0..6cf7ebaab1 100644
--- a/server/waiting-on-person.ts
+++ b/server/waiting-on-person.ts
@@ -1,4 +1,5 @@
// The engines' own prompts stay the only gates: nothing here answers, holds or grants anything.
+import type { PersonWaitKind } from "../shared/person-wait.ts";
import type { RuntimeEvent } from "./contracts.ts";
import { redactSecretsInText } from "./redact.ts";
import { serverLine } from "./server-lines.ts";
@@ -23,7 +24,12 @@ export function settledWaitingChip(name: string, kind: string, behavior: Resolve
: { name: line(question ? "server.teammates.questionAnswered" : "server.teammates.requestApproved"), ok: true };
}
-export function queuedBehindPersonText(name: string, kind: "approval" | "question" | "review", title: string, language?: string): string {
+/** A running turn waited on the person; once they answer it works again. A conversation resting on a card runs no turn
+ * and keeps waiting. */
+export const turnWaitedOnPerson = <T extends { activity?: string; busy?: boolean }>(waiting: T | null | undefined): waiting is T =>
+ waiting?.activity === "waiting-on-you" && waiting.busy === true;
+
+export function queuedBehindPersonText(name: string, kind: PersonWaitKind, title: string, language?: string): string {
return serverLine(language, kind === "question" ? "server.teammates.queuedBehind.answer" : kind === "approval" ? "server.teammates.queuedBehind.approval"
: "server.teammates.queuedBehind.review", { bot: name, title });
}
diff --git a/server/your-computer-consent.ts b/server/your-computer-consent.ts
index 5d64d858db..d4fcc1d2e9 100644
--- a/server/your-computer-consent.ts
+++ b/server/your-computer-consent.ts
@@ -6,6 +6,7 @@ import { newId } from "./contracts.ts";
import { optionCardsForTools } from "./message-db.ts";
import { buildNotification, type Notification } from "./notify.ts";
import type { BotRecord, Store } from "./store.ts";
+import { turnWaitedOnPerson } from "./waiting-on-person.ts";
import {
cleanAppName,
cleanSiteName,
@@ -64,7 +65,7 @@ function settle(entry: Pending, answer: "allow" | "deny", source: "user" | "syst
entry.store.patchMessage(entry.threadId, entry.messageId, { card: { ...card, answered: answer, dismissed: source !== "user" } });
}
const task = entry.botId ? entry.store.projectBotForTask(entry.botId, entry.threadId) : null;
- if (task?.activity === "waiting-on-you") entry.store.setTaskActivity(task.id, entry.threadId, "working");
+ if (turnWaitedOnPerson(task)) entry.store.setTaskActivity(task.id, entry.threadId, "working");
}
/** Resolves when the person allows; rejects with YourComputerDeclined when they deny or the request ends first. */
diff --git a/shared/notification.ts b/shared/notification.ts
index d8d6917b6c..fe52d6b596 100644
--- a/shared/notification.ts
+++ b/shared/notification.ts
@@ -13,6 +13,9 @@ export type NotifyKind =
/** A bot asked the person to sign in to a website themselves
* (request_sign_in): it waits on their hands, at the place it works. */
| "sign-in"
+ /** A bot asked the person for a password or key on a secure card (request_credential): its work rests on them until
+ * they save it or say no. */
+ | "secret"
/** A delegated room request settled and the coordinator auto-resumed with
* the results; both are internal, so without this the parent conversation
* sits silent until the resume's first token. */
diff --git a/shared/person-wait.test.ts b/shared/person-wait.test.ts
new file mode 100644
index 0000000000..4feeeefe33
--- /dev/null
+++ b/shared/person-wait.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from "vitest";
+
+import { openPersonWait, personWait, restingOnPerson } from "./person-wait.ts";
+import type { WireMessage } from "./wire.ts";
+
+const row = (fields: Partial<WireMessage>): WireMessage => ({ id: "m", role: "bot", kind: "text", at: 5, ...fields }) as WireMessage;
+const secret = (fields = {}) => row({ kind: "secret", secret: { target: "customSecret", label: "Mailbox password", description: "", placeholder: "", helpUrl: "", requestKey: "k", ...fields } as WireMessage["secret"] });
+const signIn = (fields = {}) => row({ kind: "signin", signIn: { url: "https://example.com", site: "example.com", place: "browser", ...fields } as WireMessage["signIn"] });
+const connector = (fields = {}) => row({ kind: "connector", connector: { slug: "gmail", label: "Gmail", description: "", status: "required", resumeKey: "k", ...fields } as WireMessage["connector"] });
+const options = (fields = {}) => row({ kind: "options", card: { title: "t", options: ["a"], requestId: "r", ...fields } as WireMessage["card"] });
+
+describe("what a row waits on the person for", () => {
+ it("names the password, sign-in, connection, question, approval and proposal it waits on", () => {
+ expect(personWait(secret())).toMatchObject({ kind: "password", label: "Mailbox password", messageId: "m", at: 5 });
+ expect(personWait(signIn())).toMatchObject({ kind: "sign-in", label: "example.com" });
+ expect(personWait(connector())).toMatchObject({ kind: "connect", label: "Gmail" });
+ expect(personWait(options({ subtitle: "Which day?" }))).toMatchObject({ kind: "question", label: "Which day?" });
+ expect(personWait(options({ tool: "Bash", subtitle: "rm" }))).toMatchObject({ kind: "approval", tool: "Bash" });
+ expect(personWait(options({ skillRequest: {} }))).toMatchObject({ kind: "review" });
+ });
+
+ it.each([
+ ["a saved password", secret({ provided: true })],
+ ["a declined password", secret({ dismissed: true })],
+ ["a superseded password", secret({ superseded: true })],
+ ["a resumed password", secret({ resumed: true })],
+ ["a stopped password", secret({ stopped: true })],
+ ["a finished sign-in", signIn({ done: true })],
+ ["a cancelled sign-in", signIn({ cancelled: true })],
+ ["a superseded sign-in", signIn({ superseded: true })],
+ ["a sign-in answered in the chat", signIn({ answeredInChat: true })],
+ ["a stopped sign-in", signIn({ stopped: true })],
+ ["a connected app", connector({ status: "connected" })],
+ ["a dismissed connection", connector({ dismissed: true })],
+ ["a superseded connection", connector({ superseded: true })],
+ ["a stopped connection", connector({ stopped: true })],
+ ["the first hour's offer to connect", connector({ resumeKey: "first-hour-1" })],
+ ["an answered question", options({ answered: "answer" })],
+ ["a dismissed question", options({ dismissed: true })],
+ ["an expired proposal", options({ skillRequest: {}, expired: true })],
+ ["an offer to switch engines", options({ quotaSwitch: {} })],
+ ["a receipt", options({ autoApplied: true })],
+ ["an inbox's copy of a card asked elsewhere", { ...options(), inbox: { kind: "ask", from: { name: "Mira" } } } as WireMessage],
+ ["plain text", row({ text: "hello" })],
+ ])("%s waits on nobody", (_name, message) => {
+ expect(personWait(message)).toBeNull();
+ });
+});
+
+describe("a conversation's visible branch", () => {
+ it("reads the newest open wait, past settled cards", () => {
+ const older = { ...secret(), id: "older" };
+ const newer = { ...signIn(), id: "newer" };
+ const settled = { ...secret({ superseded: true }), id: "settled" };
+ expect(openPersonWait([older, newer, settled, row({ id: "said" })])?.messageId).toBe("newer");
+ expect(openPersonWait([settled])).toBeUndefined();
+ });
+
+ it("rests on the person only for a card that outlives its turn", () => {
+ const approval = { ...options({ tool: "Bash" }), id: "approval" };
+ const password = { ...secret(), id: "password" };
+ expect(openPersonWait([password, approval])?.messageId).toBe("approval");
+ expect(restingOnPerson([password, approval])?.messageId).toBe("password");
+ expect(restingOnPerson([approval])).toBeUndefined();
+ });
+});
diff --git a/shared/person-wait.ts b/shared/person-wait.ts
new file mode 100644
index 0000000000..73ecc80c3a
--- /dev/null
+++ b/shared/person-wait.ts
@@ -0,0 +1,67 @@
+// What a conversation waits on the person for: the one reading behind the sidebar's Waiting, the inbox, the phone's
+// Updates, what a "done" notification may say and what other bots are told.
+import { liveCardKind } from "./live-approval.ts";
+import { signInWaits } from "./sign-in-request.ts";
+import type { WireMessage } from "./wire.ts";
+
+export type PersonWaitKind = "approval" | "question" | "review" | "password" | "sign-in" | "connect";
+
+export interface PersonWait {
+ kind: PersonWaitKind;
+ messageId: string;
+ at: number;
+ /** The person's words for what is needed: a question, a proposal's title, a key's name, a site or an app. */
+ label: string;
+ /** In a room, the bot that asked. */
+ botId?: string;
+ tool?: string;
+}
+
+/** A first-hour offer to connect an app is the product suggesting something; no work waits on it. */
+export const FIRST_HOUR_OFFER_KEY = "first-hour-";
+
+type WaitRow = Pick<WireMessage, "id" | "at" | "kind" | "card" | "secret" | "signIn" | "connector" | "from" | "inbox">;
+
+/** What this row waits on the person for, or null: anything superseded, cancelled, declined, stopped, answered or expired
+ * waits on nobody. */
+export function personWait(row: WaitRow): PersonWait | null {
+ const own = { messageId: row.id, at: row.at, ...(row.from?.botId ? { botId: row.from.botId } : {}) };
+ const { secret, signIn, connector, card } = row;
+ if (row.kind === "secret") {
+ if (!secret || secret.provided || secret.dismissed || secret.superseded || secret.resumed || secret.stopped) return null;
+ return { ...own, kind: "password", label: secret.label };
+ }
+ if (row.kind === "signin") {
+ if (!signIn || !signInWaits(signIn) || signIn.resumed || signIn.stopped) return null;
+ return { ...own, kind: "sign-in", label: signIn.site };
+ }
+ if (row.kind === "connector") {
+ if (!connector || connector.status === "connected" || connector.dismissed || connector.superseded || connector.resumed || connector.stopped) return null;
+ return connector.resumeKey.startsWith(FIRST_HOUR_OFFER_KEY) ? null : { ...own, kind: "connect", label: connector.label };
+ }
+ if (row.kind !== "options" || row.inbox || card?.quotaSwitch || card?.teamMemoryRequest || card?.autoApplied) return null;
+ const kind = liveCardKind(card);
+ if (!kind) return null;
+ return { ...own, kind, label: card?.subtitle || card?.title || "", ...(card?.tool ? { tool: card.tool } : {}) };
+}
+
+/** The newest thing this conversation's visible branch waits on the person for. */
+export function openPersonWait(path: readonly WaitRow[]): PersonWait | undefined {
+ for (let index = path.length - 1; index >= 0; index -= 1) {
+ const wait = personWait(path[index]!);
+ if (wait) return wait;
+ }
+ return undefined;
+}
+
+/** An approval lives and ends with the running turn it paused; every other card still waits once its turn has ended. */
+export const outlivesTurn = (wait: Pick<PersonWait, "kind">): boolean => wait.kind !== "approval";
+
+/** The newest wait still open once no turn is running, so the conversation rests on the person. */
+export function restingOnPerson(path: readonly WaitRow[]): PersonWait | undefined {
+ for (let index = path.length - 1; index >= 0; index -= 1) {
+ const wait = personWait(path[index]!);
+ if (wait && outlivesTurn(wait)) return wait;
+ }
+ return undefined;
+}
diff --git a/shared/wire.ts b/shared/wire.ts
index d72e1629e1..6c5e8ec7d4 100644
--- a/shared/wire.ts
+++ b/shared/wire.ts
@@ -821,6 +821,8 @@ export interface GroupTask {
turnTimeoutMinutes?: number;
/** Epoch ms when the person archived this thread; absent while it is in the list. */
archivedAt?: number;
+ /** A card in this thread waits on the person, with no turn running. */
+ activity?: "waiting-on-you";
/** Epoch ms of the newest message, or createdAt when the thread has none. */
updatedAt?: number;
lastThreadOrderAt?: number;
diff --git a/src/components/AskCard.tsx b/src/components/AskCard.tsx
index 6c270c7cbe..bb8e834527 100644
--- a/src/components/AskCard.tsx
+++ b/src/components/AskCard.tsx
@@ -6,7 +6,7 @@ import { t } from "@/lib/i18n";
import type { MausColor } from "@/lib/mascot";
import type { Bot } from "@/state/store";
import { BotAvatar } from "./Avatar";
-import { ELEVATED_CARD } from "./elevated";
+import { ELEVATED_CARD, ELEVATED_FLOAT } from "./elevated";
/** The bot a card asks for: its face and name lead the card. */
export type Asker = Pick<Bot, "name" | "color"> & Partial<Pick<Bot, "avatarUrl" | "avatarCrop" | "avatarZoom" | "avatarFocusX" | "avatarFocusY" | "mascotBody" | "mascotFaceColor">>;
@@ -39,6 +39,7 @@ export function AskCard({
children,
footer,
onKeyDown,
+ stays = false,
}: {
/** An AskHeader: who asks, above the question. */
header?: ReactNode;
@@ -53,6 +54,8 @@ export function AskCard({
children?: ReactNode;
footer?: ReactNode;
onKeyDown?: (event: KeyboardEvent<HTMLDivElement>) => void;
+ /** Work rests on this card and the person's answer alone moves it: it stays in view however far the chat scrolls. */
+ stays?: boolean;
}) {
return (
<div
@@ -61,7 +64,7 @@ export function AskCard({
data-tour={tour}
data-ask-card="pending"
onKeyDown={onKeyDown}
- className={cn("w-full max-w-[560px] rounded-[24px] px-4 pb-3.5 pt-3 text-start", ELEVATED_CARD)}
+ className={cn("w-full max-w-[560px] rounded-[24px] px-4 pb-3.5 pt-3 text-start", stays ? `sticky top-[60px] bottom-[72px] z-10 ${ELEVATED_FLOAT}` : ELEVATED_CARD)}
>
{header && <div className="mb-1.5 pe-6">{header}</div>}
<div className="flex min-w-0 items-start gap-2">
diff --git a/src/components/ConnectorCard.tsx b/src/components/ConnectorCard.tsx
index 5e76b49228..a618ae18fc 100644
--- a/src/components/ConnectorCard.tsx
+++ b/src/components/ConnectorCard.tsx
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { Loader2, PlugZap, RefreshCw, X } from "lucide-react";
+import { FIRST_HOUR_OFFER_KEY } from "../../shared/person-wait";
import { api, type Bot, type Message } from "@/state/store";
import { ApiError } from "@/state/api";
import { t } from "@/lib/i18n";
@@ -177,6 +178,7 @@ export function ConnectorCard({ botId, color, threadId, message }: { botId: stri
<AskCard
tour="connector"
ariaLabel={connector.label}
+ stays={!connector.resumeKey.startsWith(FIRST_HOUR_OFFER_KEY)}
icon={<PlugZap size={15} />}
title={isMcp ? t("connectors.card.signInTo", { label: connector.label }) : connector.label}
explanation={connector.description}
diff --git a/src/components/NotificationsPanel.tsx b/src/components/NotificationsPanel.tsx
index 6d8958605d..1e7d35940c 100644
--- a/src/components/NotificationsPanel.tsx
+++ b/src/components/NotificationsPanel.tsx
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react";
-import { AlertTriangle, AtSign, Bell, CheckCircle2, CircleHelp, HandHelping, Info, LogIn, Newspaper, Pin, RotateCcw, Wallet, X, type LucideIcon } from "lucide-react";
+import { AlertTriangle, AtSign, Bell, CheckCircle2, CircleHelp, HandHelping, Info, KeyRound, LogIn, Newspaper, Pin, RotateCcw, Wallet, X, type LucideIcon } from "lucide-react";
import { api, useStore, openNotificationTarget, type Action } from "@/state/store";
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
@@ -16,6 +16,7 @@ const KIND_LOOK: Record<NotifyKind, { Icon: LucideIcon; className: string; statu
approval: { Icon: HandHelping, className: "text-warning", status: "notifications.status.approval" },
question: { Icon: CircleHelp, className: "text-warning", status: "notifications.status.question" },
"sign-in": { Icon: LogIn, className: "text-warning", status: "notifications.status.signIn" },
+ secret: { Icon: KeyRound, className: "text-warning", status: "notifications.status.secret" },
mention: { Icon: AtSign, className: "text-accent", status: "notifications.status.mention" },
incident: { Icon: AlertTriangle, className: "text-danger", status: "notifications.status.problem" },
"turn-failed": { Icon: AlertTriangle, className: "text-danger", status: "notifications.status.failed" },
diff --git a/src/components/SecretRequestCard.test.ts b/src/components/SecretRequestCard.test.ts
index 2ec687a936..c80ba9992e 100644
--- a/src/components/SecretRequestCard.test.ts
+++ b/src/components/SecretRequestCard.test.ts
@@ -82,6 +82,12 @@ describe("SecretRequestCard ask card", () => {
expect(html).toContain('autoComplete="new-password"');
});
+ it("stays in view while it waits, however far the chat scrolls, and lets go once it is settled", () => {
+ expect(view({})).toMatch(/data-ask-card="pending"[^>]*class="[^"]*\bsticky\b/);
+ expect(view({ provided: true, resumed: true })).not.toContain("sticky");
+ expect(view({ superseded: true })).not.toContain("sticky");
+ });
+
it("folds into one line that names the key once it is saved and the bot resumed", () => {
const html = view({ provided: true, resumed: true });
expect(html).toContain('data-ask-card="settled"');
diff --git a/src/components/SecretRequestCard.tsx b/src/components/SecretRequestCard.tsx
index d8d1814bca..e4d607ad97 100644
--- a/src/components/SecretRequestCard.tsx
+++ b/src/components/SecretRequestCard.tsx
@@ -195,6 +195,7 @@ export function SecretRequestCard({
explanation={description}
onDismiss={dismiss}
dismissLabel="Not now"
+ stays
>
{remoteClient ? (
<div className="text-[13px] leading-relaxed text-ink-secondary">
diff --git a/src/components/SidebarBotActivity.test.ts b/src/components/SidebarBotActivity.test.ts
index 18d84b8c87..5c0c32d978 100644
--- a/src/components/SidebarBotActivity.test.ts
+++ b/src/components/SidebarBotActivity.test.ts
@@ -128,6 +128,8 @@ describe("group attention", () => {
const idle = group("g", "Crew", "g0");
const dm = group("d", "Bot DM", "d0", { working: true, dm: true });
expect(sidebarGroupActivityTasks(idle, [], {})).toEqual([]);
+ const resting = { ...idle, tasks: [{ threadId: "card", title: "Rests on a card", createdAt: 1, activity: "waiting-on-you" as const }] };
+ expect(sidebarGroupActivityTasks(resting, [], {})).toEqual([expect.objectContaining({ threadId: "card", activity: "waiting-on-you", busy: false })]);
expect(sidebarGroupActivityTasks(dm, [], {})).toEqual([]);
});
diff --git a/src/components/SidebarBotActivity.tsx b/src/components/SidebarBotActivity.tsx
index 11fed5b1d1..7032596cc5 100644
--- a/src/components/SidebarBotActivity.tsx
+++ b/src/components/SidebarBotActivity.tsx
@@ -61,7 +61,7 @@ export function sidebarGroupActivityTasks(group: Group, bots: Bot[], queued: Rec
const waiting = Boolean(speakerId) && bots.find((bot) => bot.id === speakerId)?.activity === "waiting-on-you";
return {
...task, busy: roomThreadWorking(group, task.threadId), unread: task.threadId === group.threadId && Boolean(group.unread),
- activity: waiting ? "waiting-on-you" as const : undefined,
+ activity: waiting || task.activity === "waiting-on-you" ? "waiting-on-you" as const : undefined,
};
});
return tasks.map((task) => ({ ...task, queued: Boolean(queued[task.threadId]?.length) }))
diff --git a/src/components/SidebarGroupThreadList.tsx b/src/components/SidebarGroupThreadList.tsx
index 59846b8f6a..3b8c4baf39 100644
--- a/src/components/SidebarGroupThreadList.tsx
+++ b/src/components/SidebarGroupThreadList.tsx
@@ -14,7 +14,7 @@ export function GroupThreadList({ group, selected, query = "" }: { group: Group;
const waiting = Boolean(speakerId) && state.bots.find((bot) => bot.id === speakerId)?.activity === "waiting-on-you";
return {
...task, busy: roomThreadWorking(group, task.threadId), unread: task.threadId === group.threadId && group.unread,
- activity: waiting ? "waiting-on-you" as const : undefined,
+ activity: waiting || task.activity === "waiting-on-you" ? "waiting-on-you" as const : undefined,
};
});
const bulk = useBulkSelect();
diff --git a/src/components/SignInRequestCard.tsx b/src/components/SignInRequestCard.tsx
index 60a72bf4a6..16b096b5fd 100644
--- a/src/components/SignInRequestCard.tsx
+++ b/src/components/SignInRequestCard.tsx
@@ -127,6 +127,7 @@ export function SignInRequestCard({
ariaLabel={t("signIn.cardLabel", { name: botName, site: card.site })}
icon={<LogIn size={15} />}
title={t("signIn.title")}
+ stays
footer={saving ? undefined : <>
<button type="button" onClick={() => void answer("cancel")} disabled={pending !== null} className={cn(ASK_CHIP, ASK_CHIP_IDLE)}>
{pending === "cancel" ? <Loader2 size={14} className="animate-spin" /> : <X size={14} />}
diff --git a/src/locales/de.json b/src/locales/de.json
index 69ff67dbcc..17ad7bd65e 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -150,6 +150,8 @@
"server.notify.approval": "{who} braucht eine Freigabe",
"server.notify.question": "{who} hat eine Frage",
"server.notify.signIn": "{who} braucht deine Anmeldung bei {site}",
+ "server.notify.secret": "{who} braucht von dir: {label}",
+ "server.notify.connect": "{who} möchte, dass du {app} verbindest",
"server.notify.signInWebsite": "{who} braucht deine Anmeldung bei einer Website",
"server.notify.routineFailed": "Routine von {who} ist fehlgeschlagen",
"server.notify.routineDeferred": "Routine von {who} wartet",
diff --git a/src/locales/en.json b/src/locales/en.json
index 7686f3f943..0e2681c970 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -247,6 +247,8 @@
"server.notify.question": "{who} has a question",
"server.notify.signIn": "{who} needs you to sign in to {site}",
"server.notify.signInWebsite": "{who} needs you to sign in to a website",
+ "server.notify.secret": "{who} needs your {label}",
+ "server.notify.connect": "{who} needs you to connect {app}",
"server.notify.routineFailed": "{who}'s routine failed",
"server.notify.routineDeferred": "{who}'s routine is waiting",
"server.notify.turnFailed": "{who} couldn't start",
@@ -1616,6 +1618,7 @@
"notifications.status.approval": "Approval",
"notifications.status.question": "Question",
"notifications.status.signIn": "Sign-in",
+ "notifications.status.secret": "Password or key",
"notifications.status.mention": "Mention",
"notifications.status.failed": "Failed",
"notifications.status.deferred": "Deferred",
diff --git a/src/state/store.tsx b/src/state/store.tsx
index c977bf6ff9..e6b4fd3c93 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -201,7 +201,7 @@ export interface GroupTask {
pinned?: boolean;
updatedAt?: number;
turnTimeoutMinutes?: number;
- archivedAt?: number;
+ archivedAt?: number; activity?: "waiting-on-you";
lastThreadOrderAt?: number;
working?: boolean;
busyBotId?: string | null;