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 resolved request settles its card at once; a close that won rewrites its own refusal
luishron123b22ed813f984
diff --git a/server/host/ask-cards.test.ts b/server/host/ask-cards.test.tsindex 65962ba9a5..716384ad31 100644--- a/server/host/ask-cards.test.ts+++ b/server/host/ask-cards.test.ts@@ -5,7 +5,7 @@ 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, settleRequestCard, type AskCardsDeps, type Closing } from "./ask-cards.ts";+import { askToolName, closeCard, createAskCards, settleRequestCard, 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?";@@ -567,10 +567,10 @@ describe("the chip in the conversation that handed the work on", () => {describe("closing a card the person moved past", () => {type Resolved = Extract<RuntimeEvent, { type: "request.resolved" }>;- /** Question cards in one chat, the live link of each, and an engine that takes a decline only once released. The- * request.resolved handler's own lookup of the link stays here: it finds the card and drops the link, then hands over. */+ /** Question cards in one chat, the live link of each, and an engine that takes a decline only once released. `resolve`+ * stands in for the request.resolved handler: it settles the card through the link, then drops the link. */const server = () => {- const rows: Message[] = [], live = new Map<string, string>(), closing = new Map<string, Closing>(), pending = new Set<string>();+ const rows: Message[] = [], live = new Map<string, string>(), closing = new Map<string, Promise<RequestOutcome>>(), pending = new Set<string>();const store = {messagesFor: () => rows,patchMessage: (_threadId: string, id: string, patch: Partial<Message>) => {@@ -590,7 +590,7 @@ describe("closing a card the person moved past", () => {pending.delete(requestId);const messageId = live.get(`chat:${requestId}`);if (!messageId) return;- settleRequestCard(store, closing, { type: "request.resolved", eventId: `e-${requestId}`, provider: "claude", createdAt: "0", threadId: "chat", requestId, behavior, source }, messageId);+ settleRequestCard(store, { type: "request.resolved", eventId: `e-${requestId}`, provider: "claude", createdAt: "0", threadId: "chat", requestId, behavior, source }, messageId);live.delete(`chat:${requestId}`);};let release!: () => void;@@ -606,7 +606,15 @@ describe("closing a card the person moved past", () => {};const close = (requestId: string, take: () => Promise<RequestOutcome>) =>closeCard({ store, threadId: "chat", requestId, live, closing, decline: take });- return { live, closing, declines, ask, card, resolve, release, decline, close };+ // A newer question closes the older cards no turn waits on and nobody answered, as askedAgain does.+ const askedAgain = (requestId: string) => {+ for (const row of rows) {+ if (row.card?.requestId && row.card.requestId !== requestId && !row.card.answered && !live.has(`chat:${row.card.requestId}`)) {+ row.card = { ...row.card, answered: "unavailable", dismissed: true };+ }+ }+ };+ return { live, closing, declines, ask, askedAgain, card, resolve, release, decline, close };};it("reads closed without an answer once the engine took the decline, whatever source the engine reported", async () => {@@ -632,12 +640,26 @@ describe("closing a card the person moved past", () => {expect(s.closing.size).toBe(0);});- it("keeps an explicit refusal that wins while the decline is on its way", async () => {+ it("keeps an explicit refusal that wins while the decline is on its way, even when a newer question opens meanwhile", async () => {+ const s = server();+ s.ask("req-1");+ const closing = s.close("req-1", s.decline("req-1", { hold: true }));+ await Promise.resolve();+ s.resolve("req-1", "deny", "user");+ s.ask("req-2");+ s.askedAgain("req-2");+ s.release();+ expect(await closing).toBe("unavailable");+ expect(s.card("req-1")).toMatchObject({ answered: "deny", dismissed: false });+ });++ it("takes no second answer for a question refused while the decline is on its way", async () => {const s = server();s.ask("req-1");const closing = s.close("req-1", s.decline("req-1", { hold: true }));await Promise.resolve();s.resolve("req-1", "deny", "user");+ expect(s.card("req-1"), "settled before the close returns").toMatchObject({ answered: "deny", dismissed: false });s.release();expect(await closing).toBe("unavailable");expect(s.card("req-1")).toMatchObject({ answered: "deny", dismissed: false });diff --git a/server/host/ask-cards.ts b/server/host/ask-cards.tsindex 0175ff9f8e..e54355ee68 100644--- a/server/host/ask-cards.ts+++ b/server/host/ask-cards.ts@@ -73,38 +73,29 @@ const typedAnswer = (card: OptionCardData, text: string): string => {type Resolved = Extract<RuntimeEvent, { type: "request.resolved" }>;type CardStore = Pick<Store, "messagesFor" | "patchMessage">;-/** A close on its way to one request: the outcome every send closing it shares, and a decline the engine settled meanwhile. */-export interface Closing { outcome: Promise<RequestOutcome>; deferred?: Resolved }-/** The card a request settled into. */export function resolvedCard(card: OptionCardData, resolved: Resolved): OptionCardData {const persistent = isPersistentQuestionCard(card);return { ...card, answered: resolved.behavior, dismissed: persistent ? false : resolved.source !== "user", ...(resolved.source === "timeout" && !persistent ? { expired: true } : {}) };}-function patchOpenCard(store: CardStore, threadId: string, messageId: string, next: (card: OptionCardData) => OptionCardData | null): void {- const card = store.messagesFor(threadId).find((message) => message.id === messageId)?.card;- const settled = card && !card.answered ? next(card) : null;- if (settled) store.patchMessage(threadId, messageId, { card: settled });-}--/** Settles a card as its request resolved. A decline that lands while a close is on its way waits for the close's own- * outcome, which alone tells whether that decline was the close's. */-export function settleRequestCard(store: CardStore, closing: Map<string, Closing>, resolved: Resolved, messageId: string): void {- const inFlight = closing.get(`${resolved.threadId}:${resolved.requestId}`);- if (inFlight && resolved.behavior === "deny") inFlight.deferred = resolved;- else patchOpenCard(store, resolved.threadId, messageId, (card) => shouldSettleRequestCard(card, resolved.source) ? resolvedCard(card, resolved) : null);+/** Settles a card as its request resolved, the moment it resolves: a decline a close sent included, which the close's+ * own outcome then turns into closed without an answer. */+export function settleRequestCard(store: CardStore, resolved: Resolved, messageId: string): void {+ const card = store.messagesFor(resolved.threadId).find((message) => message.id === messageId)?.card;+ if (card && !card.answered && shouldSettleRequestCard(card, resolved.source)) store.patchMessage(resolved.threadId, messageId, { card: resolvedCard(card, resolved) });}/** Declines a question the person moved past without an answer, once per request however many sends close it. An- * outcome other than `unavailable` means the engine took this decline: the card reads closed without an answer, whatever- * source the engine reported. Otherwise a tap, an explicit decline, Stop or the turn ending came first, and the card- * settles as that resolution would have settled it; a decline that never landed leaves the card and the request alone. */+ * outcome other than `unavailable` means the engine took this decline, so the refusal the card may already show was the+ * close's: it reads closed without an answer, whatever source the engine reported. Otherwise a tap, an explicit decline,+ * Stop or the turn ending came first and settled the card as usual; a decline that never landed leaves the card and the+ * request alone. */export function closeCard(input: { store: CardStore; threadId: string; requestId: string; live: ReadonlyMap<string, string>;- closing: Map<string, Closing>; decline: () => Promise<RequestOutcome> }): Promise<RequestOutcome> {+ closing: Map<string, Promise<RequestOutcome>>; decline: () => Promise<RequestOutcome> }): Promise<RequestOutcome> {const key = `${input.threadId}:${input.requestId}`;const running = input.closing.get(key);- if (running) return running.outcome;+ if (running) return running;const messageId = input.live.get(key);if (!messageId) return Promise.resolve("unavailable");const close = async (): Promise<RequestOutcome> => {@@ -116,13 +107,16 @@ export function closeCard(input: { store: CardStore; threadId: string; requestId} finally {input.closing.delete(key);}- if (outcome !== "unavailable") patchOpenCard(input.store, input.threadId, messageId, (card) => ({ ...card, answered: "unavailable", dismissed: true }));- else if (entry.deferred) settleRequestCard(input.store, input.closing, entry.deferred, messageId);+ const card = input.store.messagesFor(input.threadId).find((message) => message.id === messageId)?.card;+ if (outcome !== "unavailable" && card && (!card.answered || card.answered === "deny")) {+ const { answeredBy: _refuser, ...open } = card;+ input.store.patchMessage(input.threadId, messageId, { card: { ...open, answered: "unavailable", dismissed: true } });+ }return outcome;};- const entry: Closing = { outcome: Promise.resolve().then(close) };- input.closing.set(key, entry);- return entry.outcome;+ const outcome = Promise.resolve().then(close);+ input.closing.set(key, outcome);+ return outcome;}/** 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 64fd804199..a73ff1868b 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, settleRequestCard, type Closing } 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, settleRequestCard } 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>(), closingRequests = new Map<string, Closing>();+const askMessageByRequest = new Map<string, string>(), closingRequests = new Map<string, Promise<RequestOutcome>>();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 }>();@@ -6599,7 +6599,7 @@ bus.subscribe((event: RuntimeEvent) => {if (event.source === "timeout") unansweredApprovals.record(event.threadId, event.turnId, existing.card.tool, existing.card.subtitle);else if (event.source !== "system" && event.source !== "unavailable") unansweredApprovals.answered(event.threadId, event.turnId, existing.card.tool, existing.card.subtitle);}- settleRequestCard(store, closingRequests, event, messageId);+ settleRequestCard(store, event, messageId);if (event.requestId) askMessageByRequest.delete(`${event.threadId}:${event.requestId}`);}break;