Skip to content

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

feat(server): add a new-turn-only option to plain bot message sends

erywim6b7ca34a312a
diff --git a/server/routes/bot-messages.test.ts b/server/routes/bot-messages.test.ts
index 6b9e3554eb..3c24ac1a78 100644
--- a/server/routes/bot-messages.test.ts
+++ b/server/routes/bot-messages.test.ts
@@ -670,6 +670,117 @@ describe("a typed answer to a card the server refuses", () => {
});
});
+describe('a plain send with answer: "never"', () => {
+ const question = (store: Store, threadId: string) => store.appendMessage(threadId, {
+ role: "bot", kind: "options", text: "Which color?", card: {
+ title: "A question", subtitle: "Which color?", options: ["Blue", "Green"], requestId: "req-question", requestType: "question",
+ },
+ });
+ const approval = (store: Store, threadId: string) => store.appendMessage(threadId, {
+ role: "bot", kind: "options", text: "Run the command?", card: {
+ title: "An approval", subtitle: "Run the command?", options: [], requestId: "req-approval", requestType: "permission", tool: "Bash",
+ },
+ });
+ const credential = (store: Store, threadId: string) => store.appendMessage(threadId, {
+ role: "bot", kind: "secret", text: "Enter the key", secret: {
+ target: "xaiApiKey", label: "xAI API key", description: "", placeholder: "", helpUrl: "", requestKey: "secret-1",
+ },
+ });
+ const signIn = (store: Store, threadId: string) => store.appendMessage(threadId, {
+ role: "bot", kind: "signin", text: "Sign in to example.test", signIn: {
+ url: "https://example.test/", site: "example.test", place: "browser",
+ },
+ });
+ const REFUSED = {
+ error: "a question, approval, sign-in or credential request is waiting in this conversation, so nothing was sent; answer it, then send again",
+ code: "card_waiting",
+ };
+
+ it("still answers a waiting card when the option is omitted", async () => {
+ let store!: Store;
+ let cardId = "";
+ const typedCardAnswer = vi.fn(async (_auth: RequestAuth, threadId: string, text: string) => ({
+ status: 202, message: store.appendMessage(threadId, { role: "user", kind: "text", text, replyToId: cardId }),
+ }));
+ const { threadId, state, post, sent, store: opened } = await fixture({ typedCardAnswer });
+ store = opened;
+ cardId = question(store, threadId).id;
+
+ const answered = await post({ threadId, sendId: SEND, text: "Blue" });
+ expect(answered.status, JSON.stringify(answered.body)).toBe(202);
+ expect(typedCardAnswer).toHaveBeenCalledOnce();
+ expect(sent()).toMatchObject([{ text: "Blue", replyToId: cardId }]);
+ expect(state.accepted).toEqual([]);
+ });
+
+ it.each([
+ ["question", question],
+ ["approval", approval],
+ ["credential", credential],
+ ["sign-in", signIn],
+ ])("refuses the send while a %s is waiting, and appends nothing", async (_kind, append) => {
+ const typedCardAnswer = vi.fn(async () => null);
+ const { store, threadId, state, post, sent } = await fixture({ typedCardAnswer });
+ append(store, threadId);
+
+ const refused = await post({ threadId, sendId: SEND, text: "Start the next task", answer: "never" });
+ expect(refused).toEqual({ status: 409, body: REFUSED });
+ expect(typedCardAnswer).not.toHaveBeenCalled();
+ expect(state.accepted).toEqual([]);
+ expect(sent()).toEqual([]);
+ });
+
+ it("sends normally when no card waits, and never reaches the typed-answer path", async () => {
+ const typedCardAnswer = vi.fn(async () => null);
+ const { threadId, post, sent } = await fixture({ typedCardAnswer });
+
+ const sentMessage = await post({ threadId, sendId: SEND, text: "Start the next task", answer: "never" });
+ expect(sentMessage.status, JSON.stringify(sentMessage.body)).toBe(202);
+ expect(sent()).toMatchObject([{ text: "Start the next task", sendId: SEND }]);
+ expect(typedCardAnswer).not.toHaveBeenCalled();
+ });
+
+ it("does not refuse for a waiting card left on an abandoned branch", async () => {
+ const { store, threadId, post, sent } = await fixture();
+ const asked = question(store, threadId);
+ // A new line under the question's parent makes its own branch the active one; the question stays on the old branch.
+ store.branchMessage(threadId, asked.id, "Start the next task");
+
+ const send = await post({ threadId, sendId: SEND, text: "Start the next task", answer: "never" });
+ expect(send.status, JSON.stringify(send.body)).toBe(202);
+ expect(sent().filter((message) => message.sendId === SEND)).toMatchObject([{ text: "Start the next task", sendId: SEND }]);
+ });
+
+ it("keeps a sendId retry idempotent when a card starts waiting after the first send", async () => {
+ const { store, threadId, post, sent } = await fixture();
+ const first = await post({ threadId, sendId: SEND, text: "Start the next task", answer: "never" });
+ expect(first.status, JSON.stringify(first.body)).toBe(202);
+ question(store, threadId);
+
+ const again = await post({ threadId, sendId: SEND, text: "Start the next task", answer: "never" });
+ expect(again.status, JSON.stringify(again.body)).toBe(202);
+ expect(again.body.message.id).toBe(first.body.message.id);
+ expect(sent()).toHaveLength(1);
+ });
+
+ it("rejects any other answer value", async () => {
+ const { threadId, post } = await fixture();
+ for (const answer of ["auto", "always", null, 1]) {
+ expect(await post({ threadId, text: "Start", answer }), JSON.stringify(answer))
+ .toEqual({ status: 400, body: { error: 'answer must be "never" when set' } });
+ }
+ expect((await post({ threadId, text: "Start" })).status).toBe(202);
+ });
+
+ it("applies only to a typed message", async () => {
+ const { threadId, post, show } = await fixture();
+ const widgetId = show("pullRequests");
+ const refusal = { status: 400, body: { error: 'answer: "never" applies only to a typed message' } };
+ expect(await post({ threadId, sendId: SEND, text: "Hi", answer: "never" }, "/guarded")).toEqual(refusal);
+ expect(await post({ threadId, sendId: SEND, widgetAction: { messageId: widgetId, ref: "confirm" }, answer: "never" })).toEqual(refusal);
+ });
+});
+
describe("POST /api/bots/:id/messages/guarded with a reaction another app relayed", () => {
const relay = (threadId: string, replyToId: string | undefined, leaf: string | null, patch: Record<string, unknown> = {}) => ({
threadId, sendId: SEND, reaction: "+1", replyToId, expectedActiveLeafId: leaf, expectedApprovalMode: "ask",
diff --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.ts
index 69a2e54eff..4ad196417a 100644
--- a/server/routes/bot-messages.ts
+++ b/server/routes/bot-messages.ts
@@ -8,6 +8,7 @@ import { isPersistentQuestionCard } from "../../shared/ask-question.ts";
import { normalizeReaction, reactionAnswer } from "../../shared/reactions.ts";
import type { WidgetAction } from "../../shared/widget.ts";
import { parseFollowUp } from "../../shared/follow-up.ts";
+import { personWait } from "../../shared/person-wait.ts";
import type { ResolvedSender } from "../../shared/wire.ts";
import { admit } from "../admission.ts";
import { dismissQuestionCard } from "../card-dismissal.ts";
@@ -168,6 +169,22 @@ const guardedSendSchema = z.object({
}).strict().refine((who) => Boolean(who.email || who.name)).optional(),
}).strict().refine((send) => (send.text === undefined) !== (send.reaction === undefined));
+/** Plain-send option: `answer: "never"` keeps the line from answering a card, and refuses while one waits. */
+const ANSWER_NEVER = "never";
+const WAITING_CARD_KINDS: ReadonlySet<string> = new Set(["question", "approval", "password", "sign-in"]);
+
+/** A question, approval, sign-in or credential request still open in this conversation. */
+const waitsOnCard = (messages: readonly Message[]): boolean =>
+ messages.some((message) => {
+ const wait = personWait(message);
+ return wait !== null && WAITING_CARD_KINDS.has(wait.kind);
+ });
+
+const CARD_WAITING_BODY = {
+ error: "a question, approval, sign-in or credential request is waiting in this conversation, so nothing was sent; answer it, then send again",
+ code: "card_waiting",
+};
+
const CONTEXT_BREAKDOWN_WAIT_MS = 5_000;
export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler {
@@ -208,6 +225,13 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler
const fromAnApp = body.appMessage !== undefined && body.appMessage !== null;
if (guarded && fromAnApp) return json(res, 400, { error: "guarded sends cannot speak for an app" });
if (pressed && fromAnApp) return json(res, 400, { error: "send widgetAction or appMessage, not both" });
+ if (body.answer !== undefined && body.answer !== ANSWER_NEVER) {
+ return json(res, 400, { error: `answer must be "${ANSWER_NEVER}" when set` });
+ }
+ const answerNever = body.answer === ANSWER_NEVER;
+ if (answerNever && (guarded || pressed || fromAnApp)) {
+ return json(res, 400, { error: `answer: "${ANSWER_NEVER}" applies only to a typed message` });
+ }
const pointing = body.pointed !== undefined && body.pointed !== null;
if (pointing && (guarded || pressed || fromAnApp)) return json(res, 400, { error: "only a typed message can carry what the person pointed at" });
const pageOpen = body.openPage !== undefined && body.openPage !== null;
@@ -253,6 +277,7 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler
const accepted = goalSendId ? acceptedSendMatch(store.messagesFor(threadId), goalSendId, typed, undefined, "goal") : null;
if (accepted?.kind === "conflict") return json(res, 409, { error: "sendId already belongs to another message" });
if (accepted?.kind === "match") return json(res, 202, { ok: true, threadId, message: accepted.message });
+ if (answerNever && waitsOnCard(store.activePath(threadId))) return json(res, 409, CARD_WAITING_BODY);
const message = goals.start(bot.id, threadId, typed, { sendId: goalSendId, sender: messageSender(auth) });
return json(res, 202, { ok: true, threadId, message });
}
@@ -275,6 +300,8 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler
// acceptDirectSend checks these again; nothing awaits between.
const refused = directSendRefusal(bot.id, threadId);
if (refused) return json(res, refused.status, refused.body);
+ const alreadySent = Boolean(sendId && (store.messagesFor(threadId).some((message) => message.sendId === sendId) || queuedSteeredMessage(bot.id, threadId, sendId)));
+ if (answerNever && !alreadySent && waitsOnCard(store.activePath(threadId))) return json(res, 409, CARD_WAITING_BODY);
const appSent = fromAnApp ? prepareAppMessage(store, threadId, body.appMessage) : null;
if (appSent && !appSent.ok) return json(res, appSent.status, { error: appSent.error });
const pointed = pointing ? preparePointed(store, threadId, body.pointed) : null;
@@ -286,7 +313,7 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler
if (relayed && target?.role !== "bot") return json(res, 400, { error: "a relayed reaction answers a bot's message" });
const passedBack = !guarded && !press && !appSent && !pointed && target ? deps.inboxReply?.(auth, threadId, target.id, text, { sendId, sender: messageSender(auth) }) : null;
const queuedAgain = Boolean(sendId && queuedSteeredMessage(bot.id, threadId, sendId));
- const typedAnswer = passedBack || guarded || press || appSent || pointed || queuedAgain ? null : await deps.typedCardAnswer?.(auth, threadId, text, target, { sendId, sender: messageSender(auth) });
+ const typedAnswer = answerNever || passedBack || guarded || press || appSent || pointed || queuedAgain ? null : await deps.typedCardAnswer?.(auth, threadId, text, target, { sendId, sender: messageSender(auth) });
const answeredBack = passedBack ?? typedAnswer;
if (answeredBack) return json(res, answeredBack.status, answeredBack.message ? { ok: true, threadId, message: answeredBack.message } : refusalText(answeredBack.error ?? ""));
// Only a real press or reaction, or an app's own words, marks the reply; a typed reply to the same row never does, whatever its words.