Skip to content

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

Parked work follows the card that replaced the one it waited on

milind-soni9d682f6b36c1
diff --git a/server/coordinator.ts b/server/coordinator.ts
index 020e060d70..6f1e7c93df 100644
--- a/server/coordinator.ts
+++ b/server/coordinator.ts
@@ -178,6 +178,10 @@ export interface Coordinator {
/** Live nodes assigned to this bot that are parked on the person or on their requester. */
parkedFor(botId: string): HandoffView[];
parkedDirect(threadId: string): HandoffView | undefined;
+ /** A newer card replaced `from`: work parked on it in this conversation waits on `to`. */
+ followCard(threadId: string, from: string, to: string): void;
+ /** Nothing can answer what this parked work waits on any more: it ends, and whoever waits on it hears why. */
+ releaseParked(id: string, reason: string): void;
prune(before: number): number;
sharedRequest(node: HandoffView): { id: string; botIds: string[] };
cancelRoom(groupId: string, threadId?: string, reason?: string, status?: "failed" | "cancelled"): void;
diff --git a/server/host/mcp-chat.ts b/server/host/mcp-chat.ts
index 20f6b4792c..b119b262cb 100644
--- a/server/host/mcp-chat.ts
+++ b/server/host/mcp-chat.ts
@@ -35,6 +35,7 @@ export interface McpChatDeps {
teamCloud: boolean;
threadLanguage(threadId: string): string | undefined;
answerCardNode(threadId: string, messageId: string, text: string): boolean;
+ followCard(threadId: string, from: string, to: string): void;
fullAccessForSource(botId: string, threadId: string): boolean;
cloudGuestDriven(threadId: string): boolean;
liveTurnByThread: ReadonlyMap<string, string>;
@@ -66,6 +67,7 @@ export function createMcpChat(deps: McpChatDeps) {
publicOrigins: deps.publicOrigins,
language: threadLanguage,
answer: answerCardNode,
+ followCard: deps.followCard,
threadVisible: deps.threadVisible,
changed: () => broadcast({ kind: "mcp.changed" }),
});
diff --git a/server/host/mcp-sign-in-cards.ts b/server/host/mcp-sign-in-cards.ts
index fddfab2275..54914907d4 100644
--- a/server/host/mcp-sign-in-cards.ts
+++ b/server/host/mcp-sign-in-cards.ts
@@ -39,6 +39,8 @@ export interface McpSignInCardDeps {
language(threadId: string): string | undefined;
/** Answers the turn parked on this card; false while no turn waits on it. */
answer(threadId: string, messageId: string, text: string): boolean;
+ /** A newer card replaced `from`: a turn parked on it waits on `to`. */
+ followCard(threadId: string, from: string, to: string): void;
threadVisible(auth: RequestAuth, threadId: string): boolean;
/** A sign-in finished: whatever shows sign-in state refreshes. */
changed(): void;
@@ -235,14 +237,16 @@ export function createMcpSignInCards(deps: McpSignInCardDeps) {
if (!signer(name, at.threadId)) {
return { status: 409, error: `${name} is each person's own, and this chat isn't one person's alone, so nobody can sign in to it here. Each person signs in to their own on their team's page in MausBot Cloud.` };
}
+ const replaced: string[] = [];
for (const old of store.messagesFor(at.threadId)) {
if (!isMcpSignInCard(old) || old.connector.slug !== name || old.from?.botId !== at.from?.botId) continue;
if (old.connector.dismissed || old.connector.stopped || old.connector.status === "connected") continue;
patch(at.threadId, old.id, { dismissed: true, superseded: true });
cancel(name, at.threadId, old.id);
+ replaced.push(old.id);
}
const language = deps.language(at.threadId), label = appLabel(name);
- store.appendMessage(at.threadId, {
+ const card = store.appendMessage(at.threadId, {
role: "bot", kind: "connector", text: mcpSignInCardText(label, language),
...(at.from ? { from: at.from } : {}),
connector: {
@@ -250,6 +254,7 @@ export function createMcpSignInCards(deps: McpSignInCardDeps) {
description: mcpSignInCardDescription(at.bot.name, label, new URL(server.url).host, language),
},
});
+ for (const old of replaced) deps.followCard(at.threadId, old, card.id);
return { posted: true };
},
diff --git a/server/host/resumable-cards.test.ts b/server/host/resumable-cards.test.ts
index 30b42e026b..f25ba79815 100644
--- a/server/host/resumable-cards.test.ts
+++ b/server/host/resumable-cards.test.ts
@@ -4,7 +4,7 @@ import type { ConnectorCardData } from "../../shared/connector-card.ts";
import type { McpChangeRequest } from "../../shared/mcp-request.ts";
import type { OptionCardData } from "../../shared/wire.ts";
import type { Store } from "../store.ts";
-import { resumableCards } from "./resumable-cards.ts";
+import { anyCardLive, resumableCards } from "./resumable-cards.ts";
const request: McpChangeRequest = { requestId: "r1", botId: "kiwi", threadId: "t1", action: "enable", name: "linear", targetHash: "0".repeat(64) };
const card = (extra: Partial<OptionCardData> = {}, mcp: Partial<McpChangeRequest> = {}): OptionCardData => ({
@@ -34,4 +34,26 @@ describe("resumableCards", () => {
connector: { slug: "gmail", label: "Gmail", description: "", status: "required", resumeKey: "k-1", dismissed: true } }] } as unknown as Pick<Store, "activePath">, "t1", 0);
expect(app, "an app's card set aside waits on nothing, as before").toEqual([]);
});
+
+ const secret = (extra: Record<string, unknown>) => ({ id: "s1", at: 10, role: "bot", kind: "secret", secret: { label: "Mailbox password", ...extra } });
+ const signIn = (extra: Record<string, unknown>) => ({ id: "s2", at: 10, role: "bot", kind: "signin", signIn: { site: "example.com", ...extra } });
+ const oneRow = (row: unknown) => ({ activePath: () => [row], messagesFor: () => [row] }) as unknown as Pick<Store, "activePath" | "messagesFor">;
+
+ it("a stopped or replaced card waits on nobody, and a saved or declined one waits until the turn hears it", () => {
+ expect(resumableCards(oneRow(secret({})), "t1", 0)).toEqual([{ id: "s1", waits: "provide Mailbox password" }]);
+ expect(resumableCards(oneRow(secret({ provided: true })), "t1", 0), "saved, not yet heard").toHaveLength(1);
+ expect(resumableCards(oneRow(secret({ dismissed: true })), "t1", 0), "declined, not yet heard").toHaveLength(1);
+ expect(resumableCards(oneRow(secret({ provided: true, resumed: true })), "t1", 0)).toEqual([]);
+ expect(resumableCards(oneRow(secret({ superseded: true })), "t1", 0)).toEqual([]);
+ expect(resumableCards(oneRow(secret({ stopped: true })), "t1", 0)).toEqual([]);
+ expect(resumableCards(oneRow(signIn({ stopped: true })), "t1", 0)).toEqual([]);
+ expect(resumableCards(oneRow(signIn({ superseded: true })), "t1", 0)).toEqual([]);
+ });
+
+ it("tells a parked turn with a card left to wait on from one with none", () => {
+ expect(anyCardLive(oneRow(secret({})), "t1", ["s1"])).toBe(true);
+ expect(anyCardLive(oneRow(secret({ superseded: true })), "t1", ["s1"])).toBe(false);
+ expect(anyCardLive(oneRow(secret({ stopped: true })), "t1", ["s1"])).toBe(false);
+ expect(anyCardLive(oneRow(secret({})), "t1", ["gone"]), "a card that no longer exists").toBe(false);
+ });
});
diff --git a/server/host/resumable-cards.ts b/server/host/resumable-cards.ts
index da61944cc6..fb91a0e3b4 100644
--- a/server/host/resumable-cards.ts
+++ b/server/host/resumable-cards.ts
@@ -28,19 +28,25 @@ export function resumableCards(store: Pick<Store, "activePath">, threadId: strin
}
const connector = message.connector;
// An MCP Sign in card set aside before the turn parked is still answered ("didn't sign in"); an app's card is not.
- if (connector && !connector.resumed && !connector.superseded && (!connector.dismissed || connector.source === "mcp")) {
+ if (connector && !connector.resumed && !connector.superseded && !connector.stopped && (!connector.dismissed || connector.source === "mcp")) {
open.push({ id: message.id, waits: `connect ${connector.label}` });
continue;
}
const secret = message.secret;
- if (secret && !secret.resumed && !secret.superseded) {
+ if (secret && !secret.resumed && !secret.superseded && !secret.stopped) {
open.push({ id: message.id, waits: `provide ${secret.label}` });
continue;
}
const signIn = message.signIn;
- if (signIn && !signIn.resumed && !signIn.superseded && !signIn.answeredInChat) {
+ if (signIn && !signIn.resumed && !signIn.superseded && !signIn.answeredInChat && !signIn.stopped) {
open.push({ id: message.id, waits: `sign in to ${signIn.site}` });
}
}
return open;
}
+
+/** Whether any of these parked-on cards, on any branch, can still be answered or still has an answer for the turn to hear. */
+export function anyCardLive(store: Pick<Store, "messagesFor">, threadId: string, ids: readonly string[]): boolean {
+ const open = new Set(resumableCards({ activePath: (id) => store.messagesFor(id) as ReturnType<Store["activePath"]> }, threadId, 0).map((card) => card.id));
+ return ids.some((id) => open.has(id));
+}
diff --git a/server/host/secret-cards.test.ts b/server/host/secret-cards.test.ts
index 19ae78c0f1..ae8eca685c 100644
--- a/server/host/secret-cards.test.ts
+++ b/server/host/secret-cards.test.ts
@@ -32,7 +32,7 @@ function fixture(language?: string) {
const cards = createSecretCards({
store: store as never, cfg: {} as never, botLogins: { credentialConfig: (config) => ({ ...config, onePassword: { connected: false } }) },
phoneSecrets: { provide: async () => {}, open: () => {} } as never, phoneSecretSubmissions: {} as never,
- connectorThread: () => ({ bot, group: undefined }), answerCardNode: () => true, dataDir, providerKeysRefused: false,
+ connectorThread: () => ({ bot, group: undefined }), answerCardNode: () => true, followCard: () => {}, dataDir, providerKeysRefused: false,
layerFolder: () => dataDir, turnVm: () => undefined, ...(language ? { threadLanguage: () => language } : {}),
});
return { cards, lines, bot };
diff --git a/server/host/secret-cards.ts b/server/host/secret-cards.ts
index bccc476095..ee46f615e6 100644
--- a/server/host/secret-cards.ts
+++ b/server/host/secret-cards.ts
@@ -57,6 +57,8 @@ export interface SecretCardsDeps {
phoneSecretSubmissions: PhoneSecretSubmissionRegistry;
connectorThread(botId: string, threadId: string): { bot: BotRecord; group: GroupRecord | undefined } | null;
answerCardNode(threadId: string, messageId: string, text: string): boolean;
+ /** A newer card replaced `from`: a turn parked on it waits on `to`. */
+ followCard(threadId: string, from: string, to: string): void;
dataDir: string;
/** Admin manages this server's models: an AI provider key cannot be saved here. */
providerKeysRefused: boolean;
@@ -377,6 +379,7 @@ export function createSecretCards(deps: SecretCardsDeps) {
if (prior.id === message.id) continue;
if (!prior.secret || !isPendingCredentialRequest(prior, credentialId, from.id, Boolean(owner.group))) continue;
store.patchMessage(fromThreadId, prior.id, { secret: { ...prior.secret, superseded: true } });
+ deps.followCard(fromThreadId, prior.id, message.id);
}
return { status: 201, body: { messageId: message.id, label: target.label } };
}
@@ -415,6 +418,7 @@ export function createSecretCards(deps: SecretCardsDeps) {
for (const prior of path) {
if (!prior.secret || !isPendingCustomSecretRequest(prior, asked.label, from.id, room)) continue;
store.patchMessage(threadId, prior.id, { secret: { ...prior.secret, superseded: true } });
+ deps.followCard(threadId, prior.id, message.id);
}
return { status: 201, body: { messageId: message.id, label: asked.label, delivery: asked.delivery, ...(mismatch ? { savedAs: mismatch } : {}) } };
}
diff --git a/server/index.ts b/server/index.ts
index 8104d276fa..e556e406df 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -24,7 +24,7 @@ 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 { askToolName, createAskCards } from "./host/ask-cards.ts"; import { createQuestionRouting } from "./host/question-routing.ts"; import { workThreadFor } from "./host/work-thread.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 { assertRequestTarget, guardedRequestPath, requestConflict, requestNeedsInput } from "./guarded-requests.ts";
import { botAvatarUrlFromStoredPath } from "../shared/bot-avatar.ts";
import { BOT_PROFILE_LIMITS } from "../shared/bot-profile.ts";
@@ -2063,7 +2063,7 @@ function hostTurnResult(node: HandoffView | undefined, generation: string, outco
if (!node) return outcome;
const result: DirectTurnOutcome = { ...outcome, evidence: { ...outcome.evidence, ...turnEvidence(turnRows(node)) } };
if (outcome.ok && !node.groupId) signInSettle.verified(node.botId, node.threadId, node.startedAt ?? node.createdAt);
- const cards = resumableCards(node.threadId, node.startedAt ?? node.createdAt, node.groupId ? node.botId : undefined);
+ const cards = resumableCards(node.threadId, node.startedAt ?? node.createdAt, node.groupId ? node.botId : undefined).filter((card) => !coordinator.active().some((other) => other.id !== node.id && other.threadId === node.threadId && other.status === "waiting" && other.cards?.includes(card.id)));
if (result.stalled) stopCards(node.threadId, new Set(cards.map((card) => card.id)));
if (node.goalRunId) return result;
if (seat) {
@@ -9441,7 +9441,7 @@ async function resolveAndSendTeamSetup(res: ServerResponse, args: { botId: strin
}
const { mcpRequests, mcpSignInCards, mcpServerDeps, resolveAndSendMcp, mcpServerResponse, mcpPolicyRefusal } = createMcpChat({ store, cfg, mcpOAuth, teamConnections, mcpServersHost, managedPolicy,
- secretCards: () => secretCards, mcpConfig: () => mcpConfig, teamCloud: Boolean(CLOUD_TEAM), threadLanguage, answerCardNode, fullAccessForSource, cloudGuestDriven, liveTurnByThread, broadcast,
+ secretCards: () => secretCards, mcpConfig: () => mcpConfig, teamCloud: Boolean(CLOUD_TEAM), threadLanguage, answerCardNode, followCard: (threadId, from, to) => coordinator.followCard(threadId, from, to), fullAccessForSource, cloudGuestDriven, liveTurnByThread, broadcast,
publicOrigins: () => [CLOUD_HOME?.publicOrigin, hostedWorkspaceConfiguration()?.tenant.origin, savedCustomDomain(), FALLBACK_PUBLIC_URL], threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId) });
const routineTimeZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
function sendRoutineResolution(
@@ -9706,7 +9706,7 @@ handoffTicks.start({ pace: () => enginesRead || parkedNodesToReconcile.size > 0
} });
function reconcileParkedRoots(): void {
- for (const node of coordinator.active()) reconcileParkedNode(node);
+ for (const node of coordinator.active()) if (!reconcileParkedNode(node) && node.status === "waiting" && node.cards?.length && !anyCardLive(store, node.threadId, node.cards)) coordinator.releaseParked(node.id, "The card it waited on was replaced or closed");
}
const MAX_GROUP_HOPS = 1;
@@ -11670,7 +11670,7 @@ function claimPhoneSecretBotDeletion(botId: string): (() => void) | null {
};
}
-const secretCards = createSecretCards({ store, cfg, botLogins, phoneSecrets, phoneSecretSubmissions, connectorThread, answerCardNode, threadLanguage, dataDir: DATA_DIR, providerKeysRefused: Boolean(hostedModels), layerFolder: (botId, threadId) => workspaceDir(teamHost.layer(botId, threadId)), turnVm: (threadId) => localVmThreadTargets.get(threadId)?.key });
+const secretCards = createSecretCards({ store, cfg, botLogins, phoneSecrets, phoneSecretSubmissions, connectorThread, answerCardNode, followCard: (threadId, from, to) => coordinator.followCard(threadId, from, to), threadLanguage, dataDir: DATA_DIR, providerKeysRefused: Boolean(hostedModels), layerFolder: (botId, threadId) => workspaceDir(teamHost.layer(botId, threadId)), turnVm: (threadId) => localVmThreadTargets.get(threadId)?.key });
ROUTES.push(createSecretCardRoutes({ cards: secretCards, phoneSecretSubmissions, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), answerContext: (auth, botId, threadId) => ({ personalCloud: Boolean(CLOUD_PERSONAL), shared: sharedMembership(), owner: (CLOUD_TEAM ? teamOwners.routing.askedPerson(botId, threadId) : null) ?? threadStarters.get(threadId) ?? null, person: auth.kind === "session" ? personKey(auth.session) : null }) }));
// By design OpenMausBot never receives a website password: the person signs in where the bot works, and the bot uses that session.
@@ -11711,7 +11711,7 @@ function requestSignIn(from: BotRecord, threadId: string, rawSite: unknown, rawR
});
for (const prior of store.activePath(threadId)) {
if (prior.id === message.id || !prior.signIn || !isPendingSignInRequest(prior, target.site, from.id, Boolean(owner.group))) continue;
- store.patchMessage(threadId, prior.id, { signIn: { ...prior.signIn, superseded: true } });
+ store.patchMessage(threadId, prior.id, { signIn: { ...prior.signIn, superseded: true } }); coordinator.followCard(threadId, prior.id, message.id);
computerControl.settleHelp(prior.id);
}
computerControl.requestHelp(signInControlKey(from, threadId, place), `sign in to ${target.site}`,
diff --git a/server/mcp-sign-in-card.test.ts b/server/mcp-sign-in-card.test.ts
index fbf9531d05..93a8c616bf 100644
--- a/server/mcp-sign-in-card.test.ts
+++ b/server/mcp-sign-in-card.test.ts
@@ -94,7 +94,7 @@ async function setup(options: { team?: boolean; origins?: string[]; lifetimeMs?:
composio: { configured: () => false } as never,
});
const cards = createMcpSignInCards({
- store, cfg: () => cfg, mcpOAuth,
+ store, cfg: () => cfg, mcpOAuth, followCard: () => {},
personal: () => team.personMcp(),
turnPerson: (threadId) => team.turnPerson(threadId),
oauthFor: (person) => team.people.oauth(person),
diff --git a/server/parked-cards.e2e.test.ts b/server/parked-cards.e2e.test.ts
new file mode 100644
index 0000000000..7dd3977842
--- /dev/null
+++ b/server/parked-cards.e2e.test.ts
@@ -0,0 +1,121 @@
+// A turn parked on a card follows the card the bot replaced it with, and a card has one waiting turn. Real server and
+// agents tools on the fake engine; nothing here reaches the user's data or port 8799.
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { DatabaseSync } from "node:sqlite";
+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, dataDir } = 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 owner = async (botId = bot.id) => (await api("/api/bots?messages=0")).bots.find((one: any) => one.id === botId);
+ const task = async (threadId: string) => (await owner()).tasks.find((row: any) => row.threadId === threadId);
+ const messages = async (threadId: string) => (await api(`/api/threads/${threadId}/messages`)).messages as any[];
+ const cards = async (threadId: string) => (await messages(threadId)).filter((message) => message.kind === "secret");
+ const say = (threadId: string, text: string, botId = bot.id) => api(`/api/bots/${botId}/messages`, { text, threadId, sendId: crypto.randomUUID() });
+ const said = (threadId: string, text: string) => expect.poll(async () => (await messages(threadId)).some((message) => message.text === text), { timeout: 20_000 }).toBe(true);
+ const nodes = (): any[] => {
+ const path = join(dataDir, "runtime.db");
+ if (!existsSync(path)) return [];
+ const db = new DatabaseSync(path, { readOnly: true });
+ try {
+ return (db.prepare("SELECT json FROM assignments ORDER BY created_at, id").all() as Array<{ json: string }>).map((row) => JSON.parse(row.json));
+ } finally { db.close(); }
+ };
+ const turns = () => existsSync(`${planPath}.evidence.jsonl`) ? readFileSync(`${planPath}.evidence.jsonl`, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)) : [];
+ const handOff = async () => {
+ await say(chief.threadId, "GET-MAIL please", chief.id);
+ let work: any;
+ await expect.poll(async () => {
+ work = (await owner()).tasks.find((row: any) => row.openedBy?.botId === chief.id);
+ return Boolean(work) && (await cards(work.threadId)).length === 1;
+ }, { timeout: 20_000 }).toBe(true);
+ await expect.poll(() => nodes().find((node) => node.assignee.botId === bot.id)?.status, { timeout: 20_000 }).toBe("needs_input");
+ return work.threadId as string;
+ };
+ return { server, api, bot, chief, owner, task, messages, cards, say, said, nodes, turns, handOff, dataDir, plan: (plan: unknown) => writeFileSync(planPath, JSON.stringify(plan)) };
+}
+
+const plans = (f: Awaited<ReturnType<typeof fixture>>) => ({
+ [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: "again", match: ["AGAIN"], steps: [ASK], reply: "ASKED AGAIN: waiting for the password." },
+ { key: "resume", match: ["secret update"], reply: "DONE: the mail is read." },
+ { key: "any", match: [], repeat: true, reply: "OK" },
+ ] },
+});
+
+it("work parked on a card follows the newer card that replaced it, and saving that one carries the work on", () => scenario(async (f) => {
+ f.plan(plans(f));
+ const work = await f.handOff();
+ const first = (await f.cards(work))[0];
+ const parked = () => f.nodes().find((node) => node.assignee.botId === f.bot.id && node.parentId);
+ expect(parked()).toMatchObject({ status: "needs_input", cards: [first.id] });
+
+ // The person writes in the thread and the bot asks again: the first card is replaced while the hand-off stays parked.
+ await f.say(work, "AGAIN please");
+ await f.said(work, "ASKED AGAIN: waiting for the password.");
+ await expect.poll(() => f.cards(work).then((rows) => rows.length), { timeout: 20_000 }).toBe(2);
+ const [older, newer] = await f.cards(work);
+ expect(older.secret.superseded).toBe(true);
+ await expect.poll(() => parked()?.cards, { timeout: 15_000 }).toEqual([newer.id]);
+ await expect.poll(async () => (await f.task(work)).busy, { timeout: 15_000 }).toBe(false);
+
+ // A card has one waiting turn: the person's own turn ended when it asked, and doesn't park on the hand-off's card.
+ const others = f.nodes().filter((node) => node.status === "needs_input" && node.id !== parked()!.id);
+ expect(others).toEqual([]);
+
+ await f.api(`/api/bots/${f.bot.id}/secret-cards/${newer.id}/save`, { threadId: work, value: "not-a-real-password" });
+ await f.said(work, "DONE: the mail is read.");
+ await expect.poll(() => parked()?.status, { timeout: 20_000 }).toBe("completed");
+ expect((await f.messages(work)).filter((message) => message.text === "DONE: the mail is read.")).toHaveLength(1);
+ await expect.poll(() => f.nodes().filter((node) => node.status === "needs_input"), { timeout: 15_000 }).toEqual([]);
+}), hostTimeout(90_000));
+
+it("at start, work left parked on a card nothing can answer is let go, and work on an open card stays", () => scenario(async (f) => {
+ f.plan(plans(f));
+ const work = await f.handOff();
+ const card = (await f.cards(work))[0];
+ const parked = () => f.nodes().find((node) => node.assignee.botId === f.bot.id && node.parentId);
+ await f.server.stop();
+ await f.server.start();
+ await expect.poll(() => parked()?.status, { timeout: 20_000 }).toBe("needs_input");
+ expect(parked()!.cards).toEqual([card.id]);
+
+ // What an older build left behind: the card was replaced and the parked turn never heard.
+ await f.server.stop();
+ const db = new DatabaseSync(join(f.dataDir, "messages.db"));
+ try {
+ const row = db.prepare("SELECT json FROM messages WHERE id = ?").get(card.id) as { json: string };
+ const message = JSON.parse(row.json);
+ message.secret.superseded = true;
+ db.prepare("UPDATE messages SET json = ? WHERE id = ?").run(JSON.stringify(message), card.id);
+ } finally { db.close(); }
+ await f.server.start();
+ await expect.poll(() => parked()?.status, { timeout: 20_000 }).toBe("cancelled");
+ expect(f.nodes().filter((node) => node.status === "needs_input")).toEqual([]);
+}), hostTimeout(90_000));
diff --git a/server/runtime-coordinator.ts b/server/runtime-coordinator.ts
index f632d0fd96..e2a12a9359 100644
--- a/server/runtime-coordinator.ts
+++ b/server/runtime-coordinator.ts
@@ -333,6 +333,17 @@ export class RuntimeCoordinator implements Coordinator {
return this.runtime.answer(id, text, by);
}
+ followCard(threadId: string, from: string, to: string): void {
+ this.ready();
+ for (const n of this.live()) if (n.assignee.destination.threadId === threadId && n.cards?.includes(from)) this.runtime.followCard(n.id, from, to);
+ }
+
+ /** Nothing can answer what this parked turn waits on any more. */
+ releaseParked(id: string, reason: string): void {
+ this.ready();
+ if (this.store.get(id)?.status === "needs_input") this.runtime.cancel(id, reason, "stopped");
+ }
+
parkedFor(botId: string): HandoffView[] {
this.ready();
return this.live().filter(n => n.status === "needs_input" && n.assignee.botId === botId).map(n => this.project(n));
diff --git a/server/runtime/runtime.ts b/server/runtime/runtime.ts
index 6de12de1df..b4ecd50fee 100644
--- a/server/runtime/runtime.ts
+++ b/server/runtime/runtime.ts
@@ -544,6 +544,15 @@ export class Runtime {
return true;
}
+ /** A newer card replaced one this parked turn waits on: it waits on the newer one. */
+ followCard(id: string, from: string, to: string): void {
+ const n = this.store.get(id);
+ if (!n || n.status !== "needs_input" || !n.cards?.includes(from)) return;
+ n.cards = [...new Set(n.cards.map(card => card === from ? to : card))];
+ this.store.update(n);
+ this.touch(n);
+ }
+
/** Cancel this node and everything under it; abort running turns. */
cancel(id: string, reason = "Stopped by user", outcome: "stopped" | "failed" = "stopped"): void {
const n = this.store.get(id);