Skip to content

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

app_settings: Stop settles a waiting Change card at once

aivsomkarc52f8cb554b2
diff --git a/server/app-settings.e2e.test.ts b/server/app-settings.e2e.test.ts
index 3c0e4e3f75..d07564ee1f 100644
--- a/server/app-settings.e2e.test.ts
+++ b/server/app-settings.e2e.test.ts
@@ -141,6 +141,24 @@ it("a Full-access owner turn changing a provider address waits on a Change/Cance
expect(decisions.map((row: any) => row.decision).sort()).toEqual(["card-shown", "card-shown", "user-approved", "user-denied"]);
}, 90_000);
+it("Stop settles a waiting Change card at once: the card shows as unavailable, a later Change applies nothing, and the next turn can ask again", async () => {
+ await start("CONFIRM-STOP", [step({ action: "set", id: "providers.groq.url", value: XAI_URL }, true)], 60_000);
+ let waiting: any;
+ await expect.poll(async () => (waiting = (await settingCards(bot.threadId)).find((one) => one.card.appSettingRequest.settingId === "providers.groq.url" && !one.card.answered)) !== undefined, { timeout: 20_000 }).toBe(true);
+ await api("POST", `/api/bots/${bot.id}/interrupt`, { threadId: bot.threadId });
+ await expect.poll(async () => (await settingCards(bot.threadId)).find((one) => one.id === waiting.id)?.card, { timeout: 10_000 }).toMatchObject({ answered: "unavailable", dismissed: true });
+ expect(await api("POST", `/api/threads/${bot.threadId}/respond`, { requestId: waiting.card.requestId, behavior: "allow" }, 200, ownerDevice)).toMatchObject({ outcome: "unavailable" });
+ expect(config().groq?.url).toBeUndefined();
+ await idle();
+
+ // The stopped card no longer holds the bot's one open slot, so the next turn's change gets its own card.
+ await start("CONFIRM-AFTER-STOP", [step({ action: "set", id: "providers.groq.url", value: XAI_URL }, true)], 60_000);
+ let next: any;
+ await expect.poll(async () => (next = (await settingCards(bot.threadId)).find((one) => one.card.appSettingRequest.settingId === "providers.groq.url" && !one.card.answered)) !== undefined, { timeout: 20_000 }).toBe(true);
+ await api("POST", `/api/threads/${bot.threadId}/respond`, { requestId: next.card.requestId, behavior: "deny" });
+ expect(results(await finished("CONFIRM-AFTER-STOP"))[0]?.text).toMatch(/^The user cancelled the change to Groq address\./);
+}, 90_000);
+
it("a key is never taken as a value: set with a value is refused, set without one posts the secure card, and the key appears nowhere", async () => {
const before = (await messages(bot.threadId)).length;
await start("SECRET", [
diff --git a/server/app-settings/host.test.ts b/server/app-settings/host.test.ts
index a9081890e4..d342362b00 100644
--- a/server/app-settings/host.test.ts
+++ b/server/app-settings/host.test.ts
@@ -78,7 +78,7 @@ function fixture(options: { owner?: boolean; guest?: boolean; group?: boolean; w
language: () => undefined,
});
const turn = { botId: "kiwi", threadId: "t-kiwi", generation: "gen-1" };
- const set = (id: string, value?: unknown, generation = turn.generation) => host.handle({ action: "set", id, ...(value === undefined ? {} : { value }) }, { ...turn, generation });
+ const set = (id: string, value?: unknown, generation = turn.generation, ended?: AbortSignal) => host.handle({ action: "set", id, ...(value === undefined ? {} : { value }) }, { ...turn, generation }, ended);
const answer = (requestId: string, behavior: "allow" | "deny", ownerReview = true) => {
let sent: { status: number; body: unknown } | null = null;
const res = { writeHead: (status: number) => { sent = { status, body: null }; }, end: (text: string) => { sent = { status: sent?.status ?? 0, body: JSON.parse(text) }; } } as unknown as ServerResponse;
@@ -258,6 +258,23 @@ describe("confirm tier", () => {
});
});
+describe("a stopped turn", () => {
+ it("closes the waiting card at once as unavailable, tells the bot nothing changed, and a later tap changes nothing", async () => {
+ const { set, cards, answer, saved, turn } = fixture();
+ const stop = new AbortController();
+ const pending = set("providers.anthropic.url", "https://proxy.example/v1", turn.generation, stop.signal);
+ await vi.waitFor(() => expect(cards()).toHaveLength(1));
+ stop.abort();
+ const result = await pending;
+ expect(result).toMatchObject({ status: 409, body: { error: expect.stringMatching(/^This turn was stopped, so the "Anthropic address" card was closed and nothing changed\./) } });
+ expect(cards()[0]!.card).toMatchObject({ answered: "unavailable", dismissed: true });
+ expect(answer(String(cards()[0]!.card.requestId), "allow").sent).toMatchObject({ status: 200, body: { outcome: "unavailable" } });
+ expect(saved).toEqual([]);
+ expect((await set("providers.anthropic.url", "https://proxy.example/v1", turn.generation, stop.signal)).status).toBe(409);
+ expect(cards()).toHaveLength(1);
+ });
+});
+
describe("secret tier", () => {
it("never takes a value, posts the secret card instead, and shows keys only as set or not set", async () => {
const { host, set, credentialCards, messages, turn, dataDir } = fixture();
diff --git a/server/app-settings/host.ts b/server/app-settings/host.ts
index c41e6e1cdf..9c99e5957e 100644
--- a/server/app-settings/host.ts
+++ b/server/app-settings/host.ts
@@ -43,7 +43,7 @@ export interface Turn {
generation: string;
}
-type Outcome = { kind: "applied"; text: string } | { kind: "failed"; error: string } | { kind: "denied" } | { kind: "timeout" };
+type Outcome = { kind: "applied"; text: string } | { kind: "failed"; error: string } | { kind: "denied" } | { kind: "timeout" } | { kind: "stopped" };
interface Held {
botId: string;
threadId: string;
@@ -133,7 +133,8 @@ export function createAppSettings(deps: AppSettingsDeps) {
return reply(200, { text: `${outcome.text} The user can undo it from the card in the conversation.` });
}
- async function setConfirm(turn: Turn, bot: BotRecord, entry: WritableEntry, value: unknown, before: string) {
+ async function setConfirm(turn: Turn, bot: BotRecord, entry: WritableEntry, value: unknown, before: string, ended?: AbortSignal) {
+ if (ended?.aborted) return refuse(409, `This turn was stopped, so nothing changed. ${NOT_RETRY}`);
if (openByBot.has(bot.id)) return refuse(409, "A settings change is already waiting on the user. End your turn and wait for the answer.");
const requestId = randomUUID();
const after = display(value);
@@ -141,6 +142,7 @@ export function createAppSettings(deps: AppSettingsDeps) {
const answer = new Promise<Outcome>((resolve) => { settle = resolve; });
const timer = setTimeout(() => settleHold(requestId, { kind: "timeout" }), holdMs);
timer.unref?.();
+ ended?.addEventListener("abort", () => settleHold(requestId, { kind: "stopped" }), { once: true });
held.set(requestId, { botId: bot.id, threadId: turn.threadId, entry, value, before, earlier: entry.current(), settle, timer });
openByBot.set(bot.id, requestId);
const message = card(bot, turn.threadId, entry, before, after, requestId, ["Change", "Cancel"], {});
@@ -151,10 +153,11 @@ export function createAppSettings(deps: AppSettingsDeps) {
held.delete(requestId);
if (openByBot.get(bot.id) === requestId) openByBot.delete(bot.id);
waiting(bot, turn.threadId, false);
- if (outcome.kind === "timeout") {
+ if (outcome.kind === "timeout" || outcome.kind === "stopped") {
const stale = store.messagesFor(turn.threadId).find((candidate) => candidate.id === message.id);
if (stale?.card && !stale.card.answered) store.patchMessage(turn.threadId, stale.id, { card: { ...stale.card, answered: "unavailable", dismissed: true } });
- return refuse(409, `Nobody answered the "${entry.label}" card in time, so nothing changed. ${NOT_RETRY}`);
+ return refuse(409, outcome.kind === "timeout" ? `Nobody answered the "${entry.label}" card in time, so nothing changed. ${NOT_RETRY}`
+ : `This turn was stopped, so the "${entry.label}" card was closed and nothing changed. ${NOT_RETRY}`);
}
if (outcome.kind === "denied") return refuse(409, `The user cancelled the change to ${entry.label}. ${NOT_RETRY}`);
if (outcome.kind === "failed") return refuse(409, `The user allowed it, but the change failed: ${outcome.error}`);
@@ -178,7 +181,7 @@ export function createAppSettings(deps: AppSettingsDeps) {
entry.settle(outcome);
}
- async function set(turn: Turn, body: Record<string, unknown>) {
+ async function set(turn: Turn, body: Record<string, unknown>, ended?: AbortSignal) {
const entry = typeof body.id === "string" ? byId.get(body.id) : undefined;
if (!entry) return refuse(404, `No setting with id ${JSON.stringify(body.id ?? null)}. Use action find first.`);
const bot = store.bot(turn.botId);
@@ -199,11 +202,12 @@ export function createAppSettings(deps: AppSettingsDeps) {
const budget = spendWrite(turn);
if (budget) return refuse(429, budget);
const before = entry.read();
- return entry.tier === "safe" ? setSafe(turn, bot, entry, parsed.data, before) : setConfirm(turn, bot, entry, parsed.data, before);
+ return entry.tier === "safe" ? setSafe(turn, bot, entry, parsed.data, before) : setConfirm(turn, bot, entry, parsed.data, before, ended);
}
return {
- async handle(body: Record<string, unknown>, turn: Turn): Promise<{ status: number; body: Record<string, unknown> }> {
+ /** `ended` aborts once the turn is stopped or revoked, or its call is gone: a waiting card then closes at once. */
+ async handle(body: Record<string, unknown>, turn: Turn, ended?: AbortSignal): Promise<{ status: number; body: Record<string, unknown> }> {
if (body.action === "find") {
const query = typeof body.query === "string" ? body.query : "";
const hits = findSettings(entries, query, FIND_LIMIT).map(describe);
@@ -215,7 +219,7 @@ export function createAppSettings(deps: AppSettingsDeps) {
return reply(200, { text: JSON.stringify({ ...describe(entry), help: entry.help, ...("allowed" in entry ? { allowed: entry.allowed } : {}),
change: entry.tier === "owner-only" ? `only the owner, in ${entry.where}` : entry.tier === "secret" ? "set with no value opens a secure card" : entry.tier === "confirm" ? "set shows the user a Change/Cancel card and waits" : "set applies at once, with Undo on the card" }) });
}
- if (body.action === "set") return set(turn, body);
+ if (body.action === "set") return set(turn, body, ended);
return refuse(400, "action must be find, get or set.");
},
diff --git a/server/index.ts b/server/index.ts
index 1ad03aad3e..743f41df27 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -14297,7 +14297,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
}
if (await dispatchRoutes([createInternalMcpRoutes({
...mcpServerDeps(internalSender, internalCapability.threadId, internalCapability.generation), readBody: readInternalBody,
- }), createInternalAppSettingsRoutes({ readBody: readInternalBody, handle: (body) => appSettings.handle(body, internalCapability) })], { req, res, url, path, method, auth, json, readBody })) return;
+ }), createInternalAppSettingsRoutes({ readBody: readInternalBody, handle: (body) => appSettings.handle(body, internalCapability, turnCallSignals.signal(internalCapability, res)) })], { req, res, url, path, method, auth, json, readBody })) return;
if (await dispatchRoutes([createInternalCredentialRequestRoutes({ readBody: readInternalBody, request: (body) => secretCards.requestCredential(internalSender, internalCapability.threadId, body) })], { req, res, url, path, method, auth, json, readBody })) return;
if (await dispatchRoutes([createInternalSignInRoutes({
readBody: readInternalBody,