Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(ask-cards): a close never moves a question's live link; its own decline settles the card
luishron1238adc5d6e4fdf
diff --git a/server/host/ask-cards.test.ts b/server/host/ask-cards.test.tsindex 288f5c8b33..b3c698146c 100644--- a/server/host/ask-cards.test.ts+++ b/server/host/ask-cards.test.ts@@ -1,10 +1,13 @@import { describe, expect, it, vi } from "vitest";+import { shouldSettleRequestCard } from "../../shared/ask-question.ts";+import type { OptionCardData } from "../../shared/wire.ts";+import type { RequestOutcome, RuntimeEvent } from "../contracts.ts";import type { HandoffView } from "../coordinator.ts";import type { Notification } from "../notify.ts";import type { RequestAuth } from "../request-auth.ts";import type { BotRecord, Message } from "../store.ts";-import { askToolName, closeCard, createAskCards, type AskCardsDeps } from "./ask-cards.ts";+import { askToolName, closeCard, createAskCards, resolvedCard, type AskCardsDeps } from "./ask-cards.ts";const AUTH = { kind: "session", scopes: ["client"], session: { id: "s", email: "[email protected]" } } as unknown as RequestAuth;const QUESTION = "What wording should the new footer text use?";@@ -565,40 +568,91 @@ describe("the chip in the conversation that handed the work on", () => {});describe("closing a card the person moved past", () => {- const setup = () => {- const card = { id: "m1", at: 1, role: "bot", kind: "options", card: { requestId: "req-1", requestType: "question", options: [], fixedOptions: true } } as unknown as Message;- const patches: Array<Partial<Message>> = [];- const live = new Map([["chat:req-1", "m1"]]);- const store = { patchMessage: (_threadId: string, _id: string, patch: Partial<Message>) => { patches.push(patch); return { ...card, ...patch }; } };- return { card, patches, live, close: (decline: () => Promise<"rejected" | "unavailable">) =>- closeCard({ threadId: "chat", requestId: "req-1", card, live, store: store as never, decline }) };+ type Resolved = Extract<RuntimeEvent, { type: "request.resolved" }>;+ /** The server's side: question cards by request, the live link of each, and what the engine settling one writes. */+ const server = () => {+ const cards = new Map<string, OptionCardData>(), live = new Map<string, string>(), closing = new Set<string>();+ const ask = (requestId: string) => { cards.set(requestId, { title: "Which?", subtitle: "Which?", requestId, requestType: "question", options: [], fixedOptions: true }); live.set(`chat:${requestId}`, requestId); };+ // As the request.resolved handler: a live request's card settles, and the request is no longer live.+ const settle = (requestId: string, behavior: Resolved["behavior"], source: Resolved["source"] = "user") => {+ if (!live.has(`chat:${requestId}`)) return;+ const card = cards.get(requestId)!;+ if (shouldSettleRequestCard(card, source)) cards.set(requestId, resolvedCard(card, { type: "request.resolved", threadId: "chat", requestId, behavior, source } as Resolved, closing));+ live.delete(`chat:${requestId}`);+ };+ // As Stop or the turn ending: a question card stays for a late answer, and its request is no longer live.+ const turnEnds = () => live.clear();+ let release!: () => void;+ const held = new Promise<void>((resolve) => { release = resolve; });+ const close = (requestId: string, decline: () => Promise<RequestOutcome>) => closeCard({ key: `chat:${requestId}`, live, closing, decline });+ // An engine that takes a decline only once released, and settles the request then unless something already did.+ const slowDecline = (requestId: string) => async (): Promise<RequestOutcome> => {+ await held;+ if (!live.has(`chat:${requestId}`)) return "unavailable";+ settle(requestId, "deny");+ return "rejected";+ };+ return { cards, live, closing, ask, settle, turnEnds, release, close, slowDecline };};- it("reads closed without an answer once the engine took the decline, and is no longer live while it was on its way", async () => {- const w = setup();- let liveWhileDeclining = true;- expect(await w.close(async () => { liveWhileDeclining = w.live.has("chat:req-1"); return "rejected"; })).toBe("rejected");- expect(liveWhileDeclining, "the engine settling the request leaves the card to this close").toBe(false);- expect(w.patches).toEqual([{ card: { ...w.card.card, answered: "unavailable", dismissed: true } }]);- expect(w.live.has("chat:req-1")).toBe(false);+ it("reads closed without an answer once the engine took the decline, and records it as no answer", async () => {+ const s = server();+ s.ask("req-1");+ expect(await s.close("req-1", async () => { s.settle("req-1", "deny"); return "rejected"; })).toBe("rejected");+ expect(s.cards.get("req-1")).toMatchObject({ answered: "unavailable", dismissed: true });+ expect([...s.live.keys()]).toEqual([]);+ expect(s.closing.size).toBe(0);+ });++ it("keeps a tap that wins while the decline is on its way, and leaves no dead request live for the next card", async () => {+ const s = server();+ s.ask("req-1");+ const closing = s.close("req-1", s.slowDecline("req-1"));+ expect(s.live.has("chat:req-1"), "a tap still finds the card's request").toBe(true);+ s.settle("req-1", "answer");+ s.release();+ expect(await closing).toBe("unavailable");+ expect(s.cards.get("req-1")).toMatchObject({ answered: "answer", dismissed: false });+ expect([...s.live.keys()]).toEqual([]);+ s.ask("req-2");+ expect([...s.live.keys()], "the next card is the only one waiting").toEqual(["chat:req-2"]);+ expect(await s.close("req-2", async () => { s.settle("req-2", "deny"); return "rejected"; })).toBe("rejected");+ expect(s.cards.get("req-2")).toMatchObject({ answered: "unavailable", dismissed: true });+ });++ it("leaves no dead request live when Stop or the turn ending beats the decline", async () => {+ const s = server();+ s.ask("req-1");+ const closing = s.close("req-1", s.slowDecline("req-1"));+ s.turnEnds();+ s.release();+ expect(await closing).toBe("unavailable");+ expect(s.cards.get("req-1")?.answered, "open for a late answer, as after any Stop").toBeUndefined();+ expect([...s.live.keys()]).toEqual([]);+ s.ask("req-2");+ expect([...s.live.keys()]).toEqual(["chat:req-2"]);+ s.settle("req-2", "deny", "system");+ expect(s.cards.get("req-2")?.answered, "a decline that is not a close's own settles as before").toBeUndefined();});it("stays open and live for a tap when the engine did not take the decline, or delivering it failed", async () => {for (const decline of [async () => "unavailable" as const, async (): Promise<"rejected"> => { throw new Error("broker gone"); }]) {- const w = setup();- expect(await w.close(decline)).toBe("unavailable");- expect(w.patches).toEqual([]);- expect(w.live.get("chat:req-1")).toBe("m1");+ const s = server();+ s.ask("req-1");+ expect(await s.close("req-1", decline)).toBe("unavailable");+ expect(s.cards.get("req-1")?.answered).toBeUndefined();+ expect(s.live.get("chat:req-1")).toBe("req-1");+ expect(s.closing.size).toBe(0);+ s.settle("req-1", "answer");+ expect(s.cards.get("req-1")).toMatchObject({ answered: "answer" });}});it("delivers nothing for a card no turn waits on", async () => {- const w = setup();- w.live.clear();+ const s = server();const decline = vi.fn(async () => "rejected" as const);- expect(await w.close(decline)).toBe("unavailable");+ expect(await s.close("req-1", decline)).toBe("unavailable");expect(decline).not.toHaveBeenCalled();- expect(w.patches).toEqual([]);});});diff --git a/server/host/ask-cards.ts b/server/host/ask-cards.tsindex a811ae18cc..025f9785e8 100644--- a/server/host/ask-cards.ts+++ b/server/host/ask-cards.ts@@ -71,18 +71,25 @@ const typedAnswer = (card: OptionCardData, text: string): string => {return questions ? formatQuestionAnswers(questions, [[text]]) : text;};-/** Closes a question card the person moved past without an answer, once the engine takes the decline. While it is on- * its way the card is not live, so the engine settling the request leaves the card alone; one that did not land leaves- * the card open and live, for a tap. */-export async function closeCard(input: { threadId: string; requestId: string; card: Message | undefined; live: Map<string, string>;- store: Pick<Store, "patchMessage">; decline: () => Promise<RequestOutcome> }): Promise<RequestOutcome> {- const key = `${input.threadId}:${input.requestId}`, messageId = input.live.get(key);- if (!messageId || !input.card?.card) return "unavailable";- input.live.delete(key);- const outcome = await input.decline().catch((): RequestOutcome => "unavailable");- if (outcome === "unavailable") input.live.set(key, messageId);- else input.store.patchMessage(input.threadId, input.card.id, { card: { ...input.card.card, answered: "unavailable", dismissed: true } });- return outcome;+/** Declines a question the person moved past without an answer. While the decline is on its way the request is marked+ * closing, so the engine settling it with that decline reads closed without an answer; a tap, Stop or the turn ending+ * first settles it as they always do. A decline that did not land leaves the card and the request as they were. */+export async function closeCard(input: { key: string; live: ReadonlyMap<string, string>; closing: Set<string>;+ decline: () => Promise<RequestOutcome> }): Promise<RequestOutcome> {+ if (!input.live.has(input.key)) return "unavailable";+ input.closing.add(input.key);+ try {+ return await input.decline().catch((): RequestOutcome => "unavailable");+ } finally {+ input.closing.delete(input.key);+ }+}++/** The card a request settled into: closed without an answer when the decline was a close's own. */+export function resolvedCard(card: OptionCardData, resolved: Extract<RuntimeEvent, { type: "request.resolved" }>, closing: ReadonlySet<string>): OptionCardData {+ if (resolved.behavior === "deny" && closing.has(`${resolved.threadId}:${resolved.requestId}`)) return { ...card, answered: "unavailable", dismissed: true };+ const persistent = isPersistentQuestionCard(card);+ return { ...card, answered: resolved.behavior, dismissed: persistent ? false : resolved.source !== "user", ...(resolved.source === "timeout" && !persistent ? { expired: true } : {}) };}/** The reply up to its NEEDS INPUT line; empty when the line is the whole reply. */diff --git a/server/index.ts b/server/index.tsindex f2cf9a946f..ae65989d3b 100644--- a/server/index.ts+++ b/server/index.ts@@ -26,7 +26,7 @@ import { botMemoryFiles, createLendingMemory } from "./lending-memory.ts";import { SharedComputerControl } from "./shared-computer-control.ts";import { STATUS_REPLY_TIMEOUT_MS } from "./runtime/status-reply.ts"; import { createCoordinator, type ComposedTurn, type CoordinateBotsCall, type Coordinator, type HandoffOpener, type HandoffOptions, type HandoffView, type HostTurnResult } from "./coordinator.ts";import { queuedBehindPersonText, turnWaitedOnPerson, UnansweredApprovals } from "./waiting-on-person.ts";-import { createPersonWaits } from "./host/person-waits.ts"; import { askToolName, closeCard, createAskCards } from "./host/ask-cards.ts"; import { createQuestionRouting } from "./host/question-routing.ts"; import { workThreadFor } from "./host/work-thread.ts"; import { leaveThreadPost, postToThread, threadWaitsOn, unreadThreadPosts } from "./host/thread-posts.ts"; import { anyCardLive, 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 { createConnectCardSettle } from "./host/connect-card-settle.ts";+import { createPersonWaits } from "./host/person-waits.ts"; import { askToolName, closeCard, createAskCards, resolvedCard } from "./host/ask-cards.ts"; import { createQuestionRouting } from "./host/question-routing.ts"; import { workThreadFor } from "./host/work-thread.ts"; import { leaveThreadPost, postToThread, threadWaitsOn, unreadThreadPosts } from "./host/thread-posts.ts"; import { anyCardLive, 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 { createConnectCardSettle } from "./host/connect-card-settle.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";@@ -4725,7 +4725,7 @@ onSteeredQueueChange(() => broadcast({ kind: "bot.queued", queues: publicBotQueu// Keyed by threadId: provider item and request ids are unique only within a thread.const toolMessageByItem = new Map<string, string>();-const askMessageByRequest = new Map<string, string>();+const askMessageByRequest = new Map<string, string>(), closingRequests = new Set<string>();const unansweredApprovals = new UnansweredApprovals(); const approvalAsk = (botId: string | undefined, threadId: string, turnId: string | undefined): { approvalAsk?: string } => { const asked = botId ? unansweredApprovals.ask(threadId, turnId, store.bot(botId)?.name ?? "A teammate", threadLanguage(threadId)) : undefined; return asked ? { approvalAsk: asked } : {}; };// Only native, live permission metadata becomes a remembered grant, never an imported transcript or display summary.const pendingCommandRules = new Map<string, { botId: string; candidate: CommandAllowlistCandidate }>();@@ -4759,7 +4759,7 @@ async function answerRequest(const remembered = rememberCommand ? pendingCommandRules.get(`${threadId}:${requestId}`) : undefined;// The live turn owns this question, as it owns Stop and steer. A card closed without an answer records no denial.const instance = runningTurnEngines.get(threadId) ?? registry.get(instanceId);- if (behavior === "close") return closeCard({ threadId, requestId, card: cardMessage, live: askMessageByRequest, store,+ if (behavior === "close") return closeCard({ key: `${threadId}:${requestId}`, live: askMessageByRequest, closing: closingRequests,decline: async () => instance ? instance.adapter.respondToRequest(threadId, requestId, { behavior: "deny" }) : "unavailable" });let outcome: RequestOutcome = "unavailable";if (instance) {@@ -6601,14 +6601,7 @@ bus.subscribe((event: RuntimeEvent) => {else if (event.source !== "system" && event.source !== "unavailable") unansweredApprovals.answered(event.threadId, event.turnId, existing.card.tool, existing.card.subtitle);}if (shouldSettleRequestCard(existing.card, event.source)) {- store.patchMessage(event.threadId, messageId, {- card: {- ...existing.card,- answered: event.behavior,- dismissed: isPersistentQuestionCard(existing.card) ? false : event.source !== "user",- ...(event.source === "timeout" && !isPersistentQuestionCard(existing.card) ? { expired: true } : {}),- },- });+ store.patchMessage(event.threadId, messageId, { card: resolvedCard(existing.card, event, closingRequests) });}}if (event.requestId) askMessageByRequest.delete(`${event.threadId}:${event.requestId}`);