Skip to content

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

Inbox: a question the person writes past stops waiting on them

Krishna Dobhalcd3803ca89a7
diff --git a/docs/verification/inbox.md b/docs/verification/inbox.md
index 3c48ad5e86..85ceeda954 100644
--- a/docs/verification/inbox.md
+++ b/docs/verification/inbox.md
@@ -7,6 +7,8 @@
3. An answer through the row's own conversation reaches the bot, its turn goes on and the count clears. A second answer to
the same card is refused.
4. `message_person` arrives as one line, one row and one notification, and a reply reaches the bot.
+5. A question left by `NEEDS INPUT:` that the person writes past leaves Needs you and stops marking the thread as
+ waiting on the person; its card stays open to answer.
On My Cloud it also checks that nobody connects as a guest, that a bot's shell reads nothing, and that a guest's conversation
left behind reaches the owner labelled, with its news kept away.
diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.ts
index 0a6b47f65c..c9baeb3916 100644
--- a/packages/phone-protocol/src/wire.ts
+++ b/packages/phone-protocol/src/wire.ts
@@ -514,6 +514,9 @@ export interface WireMessage extends ServerTextLine, HelperIntroField, SetupCard
* route (the Slack worker): nobody typed it in one of this workspace's
* clients. A Live call never reads it back as what the caller typed. */
relayed?: boolean;
+ /** A user line a routine, webhook, room coordination or another bot's
+ * message started a turn with: the person did not write it. */
+ automated?: boolean;
/** Which person sent this user message, when the workspace has more than
* one. Absent reads as the profile name. */
sender?: ResolvedSender;
diff --git a/server/host/person-waits.ts b/server/host/person-waits.ts
index 116b0da2e2..75178a4ff4 100644
--- a/server/host/person-waits.ts
+++ b/server/host/person-waits.ts
@@ -2,7 +2,7 @@
// 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 { openPersonWait, personWait, personWrote, 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";
@@ -30,7 +30,7 @@ export function createPersonWaits(deps: PersonWaitsDeps) {
/** 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));
+ const wait = restingOnPerson(store.activePath(threadId), Boolean(store.groupByThread(threadId)));
return wait && now() - wait.at < NEEDS_YOU_WINDOW_MS ? wait : undefined;
};
@@ -82,7 +82,10 @@ export function createPersonWaits(deps: PersonWaitsDeps) {
store.onChange((change) => {
if (change.type === "message" || change.type === "message.patch") {
- if (!CARD_ROWS.has(change.message.kind)) return;
+ if (!CARD_ROWS.has(change.message.kind)) {
+ if (change.type === "message" && withCards.has(change.threadId) && personWrote(change.message)) refresh(change.threadId);
+ 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.
diff --git a/server/host/place-inbox.test.ts b/server/host/place-inbox.test.ts
index 253304d04a..2281792f13 100644
--- a/server/host/place-inbox.test.ts
+++ b/server/host/place-inbox.test.ts
@@ -46,10 +46,12 @@ function setup(over: Partial<PlaceInboxDeps> = {}, dataDir = mkdtempSync(join(tm
},
patchTask: () => undefined, patchGroup: () => undefined,
messagesFor: (threadId: string) => said.get(threadId) ?? [],
+ activePath: (threadId: string) => said.get(threadId) ?? [],
onChange: (listener: (change: { type: string; threadId: string }) => void) => { listeners.push(listener); return () => undefined; },
};
const inbox = createPlaceInbox({
dataDir, store: store as unknown as PlaceInboxDeps["store"], openCards: () => cards,
+ live: () => false,
viewer: (auth) => viewers.get(auth)!,
sees: () => true,
mayAnswer: (auth) => auth === OWNER,
@@ -157,6 +159,16 @@ describe("the inbox of a place that is no team's", () => {
expect(f.inbox.view(OWNER).rows).toEqual([]);
});
+ it("drops a question the person wrote past, unless a running turn still waits on it", () => {
+ const live = new Set<string>();
+ const f = setup({ live: (_threadId, requestId) => live.has(requestId) });
+ const row = f.ask("eli-main", "q");
+ f.said.set("eli-main", [{ ...row, role: "bot", kind: "options", card: JSON.parse(row.card!) } as Said, { id: "said", at: 2_000, role: "user", text: "Do the report instead" }]);
+ expect(f.inbox.count(OWNER)).toBe(0);
+ live.add("q");
+ expect(f.inbox.view(OWNER).rows.map((one) => one.id)).toEqual(["card-q"]);
+ });
+
it("leaves out offers and receipts, and a card somebody already settled", () => {
const f = setup();
f.ask("eli-main", "offer", { quotaSwitch: {} as never });
diff --git a/server/host/place-inbox.ts b/server/host/place-inbox.ts
index f868f58a88..a9eb904bf0 100644
--- a/server/host/place-inbox.ts
+++ b/server/host/place-inbox.ts
@@ -11,7 +11,7 @@ import { z } from "zod";
import type { InboxItem, InboxRow, InboxView } from "../../shared/inbox.ts";
import type { Notification } from "../../shared/notification.ts";
-import { personWait, type PersonWait } from "../../shared/person-wait.ts";
+import { overtakenQuestions, personWait, type PersonWait } from "../../shared/person-wait.ts";
import type { OptionCardData } from "../../shared/wire.ts";
import { ASK_NOTIFICATIONS } from "../ask-routing.ts";
import { writeFileAtomic } from "../atomic.ts";
@@ -62,8 +62,10 @@ export function placeInboxViewer(auth: RequestAuth, cloud: { personal: boolean;
export interface PlaceInboxDeps {
dataDir: string;
- store: Pick<Store, "bot" | "botByThread" | "taskByThread" | "groupByThread" | "appendMessage" | "patchTask" | "patchGroup" | "messagesFor" | "onChange">;
+ store: Pick<Store, "bot" | "botByThread" | "taskByThread" | "groupByThread" | "appendMessage" | "patchTask" | "patchGroup" | "messagesFor" | "activePath" | "onChange">;
openCards(): OpenCardRow[];
+ /** A running turn waits on this card's answer. */
+ live(threadId: string, requestId: string): boolean;
viewer(auth: RequestAuth): InboxViewer;
sees(auth: RequestAuth, threadId: string): boolean;
/** Whose answer counts on this card; decided where cards are answered, so a row never offers what the answer would refuse. */
@@ -136,10 +138,17 @@ export function createPlaceInbox(deps: PlaceInboxDeps) {
function askRows(auth: RequestAuth): InboxRow[] {
if (deps.viewer(auth).kind === "nobody") return [];
const rows = new Map<string, InboxRow>();
+ const passed = new Map<string, Set<string>>();
+ const overtaken = (threadId: string, messageId: string): boolean => {
+ let questions = passed.get(threadId);
+ if (!questions) passed.set(threadId, questions = overtakenQuestions(store.activePath(threadId), Boolean(store.groupByThread(threadId))));
+ return questions.has(messageId);
+ };
for (const row of deps.openCards()) {
let card: OptionCardData | null = null;
try { card = row.card ? JSON.parse(row.card) as OptionCardData : null; } catch { continue; }
if (!card || !personWait({ id: row.id, at: row.at, kind: "options", card }) || !deps.sees(auth, row.threadId) || !deps.mayAnswer(auth, row.threadId, card.requestId!)) continue;
+ if (overtaken(row.threadId, row.id) && !deps.live(row.threadId, card.requestId!)) continue;
const bot = (row.fromBotId ? store.bot(row.fromBotId) : undefined) ?? store.botByThread(row.threadId);
if (!bot) continue;
const group = store.groupByThread(row.threadId);
diff --git a/server/index.ts b/server/index.ts
index 146108ead9..42077c4585 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -2826,7 +2826,7 @@ const computerAsks = CLOUD_PERSONAL ? createComputerAsksHost({ store, notify, le
const { stopThreadForPerson, stopOnTypedCommand, restartForPerson } = createPersonStop({
store, routines: () => routines, handoffs: () => handoffs, interruptDirectThread, stopping: (botId, threadId) => idleThreads.stopping(botId, threadId), clearUnattended,
stopGoal: (threadId) => oneOnOneGoals.stop(threadId), markStopped: (threadId, by) => personStops.stop(threadId, liveTurns.running(threadId), directTurnDispatchClaims.has(threadId), by), working: (botId, threadId) => threadBusy(botId, threadId) || coordinator.activeDirect(threadId), asking: (threadId) => coordinator.awaitingAnswer(threadId) || Boolean(openPersonCard(threadId)), language: threadLanguage, stopRefusal: (threadId, by) => runOwners.stopRefusal(threadId, by),
-}); const teamMessages = createTeamMessages({ place: CLOUD_TEAM ? null : createPlaceInbox({ dataDir: DATA_DIR, store, openCards: openCardRows, waiting: () => personWaits.waiting(), send: (notification) => { broadcast({ kind: "notify", notification: logNotification(notification) }); }, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), mayAnswer: (auth, threadId, requestId) => cardAnswerRefusal(auth, threadId, requestId, "allow") === null, viewer: (auth) => placeInboxViewer(auth, { personal: CLOUD_PERSONAL, owner: cloudOwnerSession, personOf: personKey }), guestOf: (threadId) => { if (!CLOUD_PERSONAL || !cloudGuestDriven(threadId)) return null; const person = [...cloudThreadStarters(threadId), threadPersonKey(threadId)].find((one) => one && one !== CLOUD_OUTSIDE_KEY && !cloudOwnerPerson(one)); return person ?? null; }, guestName: (threadId) => guestNameIn(store.messagesFor(threadId)), handedBy: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.botId ?? store.botByThread(from.threadId)?.id ?? null : null; } }), team: CLOUD_TEAM, dataDir: DATA_DIR, store, confined: (threadId) => cloudGuestDriven(threadId), people: teamOwners.people, personName: teamHost.personName, audienceOf: teamHost.audienceOf, starters: threadStarters, notify, sees: (person) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }), inbox: { askedPerson: teamOwners.routing.askedPerson, delivered: (item, delivery) => teamAway.delivered(item, delivery), changed: (threadId) => { const bot = store.botByThread(threadId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, ensureOwnBot: (email) => { ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM?.name ?? null, opened: (made) => void mausbotOwnChat.claim(made) }); }, handedFrom: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.threadId : null; }, continueTurn: relayedTurn({ store, startTurn, state: (botId, threadId) => ({ atCapacity: botAtThreadCapacity(botId, threadId), threadBusy: threadBusy(botId, threadId), groupTurn: roomTurnHolds(activeGroupTurnForBot(botId), threadId, false), parksBehindCoordination: parksBehindCoordination(botId, threadId) }) }), representative: { generate: async (botId, prompt) => (await sideJobs.text("representative", botId)?.generateText(prompt, { timeoutMs: 60_000 })) ?? null, busy: createPersonCalendar({ access: (person) => teamConnections.personApps().includes("googlecalendar") ? teamConnections.people.appsAccess(person) : null, connected: async (access) => (await composio.connectedServices(...teamConnections.via(access))).googlecalendar?.connected === true, relay: (payload, session, signal, access) => composio.relayMcp(teamConnections.via(access)[0], payload as never, session, undefined, signal, teamConnections.via(access)[1]) }).busy } } });
+}); const teamMessages = createTeamMessages({ place: CLOUD_TEAM ? null : createPlaceInbox({ dataDir: DATA_DIR, store, openCards: openCardRows, live: (threadId, requestId) => askMessageByRequest.has(`${threadId}:${requestId}`), waiting: () => personWaits.waiting(), send: (notification) => { broadcast({ kind: "notify", notification: logNotification(notification) }); }, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), mayAnswer: (auth, threadId, requestId) => cardAnswerRefusal(auth, threadId, requestId, "allow") === null, viewer: (auth) => placeInboxViewer(auth, { personal: CLOUD_PERSONAL, owner: cloudOwnerSession, personOf: personKey }), guestOf: (threadId) => { if (!CLOUD_PERSONAL || !cloudGuestDriven(threadId)) return null; const person = [...cloudThreadStarters(threadId), threadPersonKey(threadId)].find((one) => one && one !== CLOUD_OUTSIDE_KEY && !cloudOwnerPerson(one)); return person ?? null; }, guestName: (threadId) => guestNameIn(store.messagesFor(threadId)), handedBy: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.botId ?? store.botByThread(from.threadId)?.id ?? null : null; } }), team: CLOUD_TEAM, dataDir: DATA_DIR, store, confined: (threadId) => cloudGuestDriven(threadId), people: teamOwners.people, personName: teamHost.personName, audienceOf: teamHost.audienceOf, starters: threadStarters, notify, sees: (person) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }), inbox: { askedPerson: teamOwners.routing.askedPerson, delivered: (item, delivery) => teamAway.delivered(item, delivery), changed: (threadId) => { const bot = store.botByThread(threadId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, ensureOwnBot: (email) => { ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM?.name ?? null, opened: (made) => void mausbotOwnChat.claim(made) }); }, handedFrom: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.threadId : null; }, continueTurn: relayedTurn({ store, startTurn, state: (botId, threadId) => ({ atCapacity: botAtThreadCapacity(botId, threadId), threadBusy: threadBusy(botId, threadId), groupTurn: roomTurnHolds(activeGroupTurnForBot(botId), threadId, false), parksBehindCoordination: parksBehindCoordination(botId, threadId) }) }), representative: { generate: async (botId, prompt) => (await sideJobs.text("representative", botId)?.generateText(prompt, { timeoutMs: 60_000 })) ?? null, busy: createPersonCalendar({ access: (person) => teamConnections.personApps().includes("googlecalendar") ? teamConnections.people.appsAccess(person) : null, connected: async (access) => (await composio.connectedServices(...teamConnections.via(access))).googlecalendar?.connected === true, relay: (payload, session, signal, access) => composio.relayMcp(teamConnections.via(access)[0], payload as never, session, undefined, signal, teamConnections.via(access)[1]) }).busy } } });
const imageTools = createImageToolRoutes({ config: () => cfg, dataDir: DATA_DIR, liveTurn: (threadId) => liveTurnByThread.get(threadId), key: turnAttachmentKey, images: (key) => (turnAttachmentsByTurn.get(key) ?? []).filter((item) => item.kind === "image").length, park: (key, image) => { const saved = saveImage(image.bytes, image.mime); turnAttachmentsByTurn.set(key, [...turnAttachmentsByTurn.get(key) ?? [], { kind: "image", path: saved.path, mime: saved.mime }]); } });
const noAiNotice = createNoAiNotice({ team: CLOUD_TEAM, dataDir: DATA_DIR, people: () => teamOwners.people?.list() ?? [], personName: teamHost.personName, inbox: () => teamMessages.inbox, language: personLanguages.forLine, threadLanguage: conversationLanguage });
const botNameClash = createBotNameClash({ store, people: () => teamMessages.people(), profileName: () => cfg.profile?.name });
@@ -7690,6 +7690,7 @@ async function beginTurn(
sender: opts?.sender,
...spokenLineFields(opts?.via, opts?.callId),
...(opts?.relayed ? { relayed: true } : {}),
+ ...(automated ? { automated: true } : {}),
});
}
const personLine = !opts?.coordination && !opts?.cardContinuation && !opts?.automationSource && !opts?.compactOnly
diff --git a/server/place-inbox.e2e.test.ts b/server/place-inbox.e2e.test.ts
index 9ab0ff6a40..06f1441d5a 100644
--- a/server/place-inbox.e2e.test.ts
+++ b/server/place-inbox.e2e.test.ts
@@ -128,6 +128,27 @@ describe.each([
expect((await h.messages(launch)).some((line) => line.text?.includes("going with Home"))).toBe(false);
}, hostTimeout(180_000));
+ it("clears a question overtaken by the person's next message from the thread and inbox", async () => {
+ const h = here();
+ const bot = await h.bot(`Quinn ${role}`);
+ const thread = await h.thread(bot.id, "Question left behind");
+ h.script(bot.id,
+ { key: "STALE-ASK", match: ["STALE-ASK-GO"], reply: "NEEDS INPUT: Which page should I use?" },
+ { key: "STALE-NEXT", match: ["STALE-NEXT-GO"], reply: "I will work on the report instead." });
+ await h.say(bot.id, thread, "STALE-ASK-GO");
+ await until(async () => (await h.listed()).some((row) => row.origin?.threadId === thread), "the question in the inbox");
+ const question = (await h.listed()).find((row) => row.origin?.threadId === thread)!;
+ expect(question.tab).toBe("needs-you");
+ await h.say(bot.id, thread, "STALE-NEXT-GO");
+ await until(async () => (await h.messages(thread)).some((line) => line.text === "I will work on the report instead."), "the next turn to finish");
+ expect((await h.messages(thread)).find((line) => line.id === question.id)?.card).not.toHaveProperty("answered");
+ expect((await h.listed()).some((row) => row.id === question.id)).toBe(false);
+ const call = role === "desktop" ? fx.local : fx.onCloud;
+ const state = await call("GET", `/api/bots/${bot.id}`);
+ expect(state.status).toBe(200);
+ expect(state.body.bot.tasks.find((task: { threadId: string }) => task.threadId === thread).activity).not.toBe("waiting-on-you");
+ }, hostTimeout(120_000));
+
it("gets a bot's message_person to the person once, and their reply reaches the bot", async () => {
const h = here();
const eli = await h.bot(`Mel ${role}`);
diff --git a/shared/person-wait.test.ts b/shared/person-wait.test.ts
index 4feeeefe33..fbdc7aeb1c 100644
--- a/shared/person-wait.test.ts
+++ b/shared/person-wait.test.ts
@@ -64,3 +64,30 @@ describe("a conversation's visible branch", () => {
expect(restingOnPerson([approval])).toBeUndefined();
});
});
+
+describe("a question the person wrote past", () => {
+ const question = { ...options({ subtitle: "Which page?" }), id: "question" };
+ const password = { ...secret(), id: "password" };
+ const wrote = (fields: Partial<WireMessage> = {}) => row({ id: "said", role: "user", text: "Do the report instead", ...fields });
+
+ it("no longer waits once the person writes after it, while cards that are not questions still do", () => {
+ expect(restingOnPerson([question])?.messageId).toBe("question");
+ expect(restingOnPerson([question, wrote()])).toBeUndefined();
+ expect(restingOnPerson([password, question, wrote()])?.messageId).toBe("password");
+ expect(restingOnPerson([wrote(), question])?.messageId).toBe("question");
+ });
+
+ it.each([
+ ["another bot", { peerAsk: { botId: "scout", name: "Scout" } }],
+ ["a relay", { relayed: true }],
+ ["the API", { via: "api" as const }],
+ ["an automation", { automated: true }],
+ ])("still waits after a line %s wrote", (_name, fields) => {
+ expect(restingOnPerson([question, wrote(fields)])?.messageId).toBe("question");
+ });
+
+ it("in a room, waits until the person replies to the question itself", () => {
+ expect(restingOnPerson([question, wrote()], true)?.messageId).toBe("question");
+ expect(restingOnPerson([question, wrote({ replyToId: "question" })], true)).toBeUndefined();
+ });
+});
diff --git a/shared/person-wait.ts b/shared/person-wait.ts
index 73ecc80c3a..7311498e70 100644
--- a/shared/person-wait.ts
+++ b/shared/person-wait.ts
@@ -57,11 +57,35 @@ export function openPersonWait(path: readonly WaitRow[]): PersonWait | 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";
+type SpokenRow = Pick<WireMessage, "role" | "peerAsk" | "relayed" | "via" | "automated" | "replyToId">;
+type PathRow = WaitRow & SpokenRow;
+
+/** A line the person wrote themselves, not one another bot, a relay, the API or an automation put in the conversation. */
+export const personWrote = (row: SpokenRow): boolean =>
+ row.role === "user" && !row.peerAsk && !row.relayed && row.via !== "api" && !row.automated;
+
+/** The questions on this branch the person has written past: they no longer wait on them. In a room the person talks to
+ * the others too, so only a reply to the question itself passes it. */
+export function overtakenQuestions(path: readonly PathRow[], room: boolean): Set<string> {
+ const passed = new Set<string>();
+ const repliedTo = new Set<string>();
+ let spoke = false;
+ for (let index = path.length - 1; index >= 0; index -= 1) {
+ const row = path[index]!;
+ if (personWrote(row)) {
+ spoke = true;
+ if (row.replyToId) repliedTo.add(row.replyToId);
+ } else if (personWait(row)?.kind === "question" && (room ? repliedTo.has(row.id) : spoke)) passed.add(row.id);
+ }
+ return passed;
+}
+
/** 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 {
+export function restingOnPerson(path: readonly PathRow[], room = false): PersonWait | undefined {
+ const passed = overtakenQuestions(path, room);
for (let index = path.length - 1; index >= 0; index -= 1) {
const wait = personWait(path[index]!);
- if (wait && outlivesTurn(wait)) return wait;
+ if (wait && outlivesTurn(wait) && !passed.has(wait.messageId)) return wait;
}
return undefined;
}