Skip to content

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

A new bot's setup answers follow its name (#3743)

Milind Sonib355c661208b
diff --git a/docs/verification/evidence/name-suggestions/new-card-dark.jpg b/docs/verification/evidence/name-suggestions/new-card-dark.jpg
new file mode 100644
index 0000000000..f6bb0a2c80
Binary files /dev/null and b/docs/verification/evidence/name-suggestions/new-card-dark.jpg differ
diff --git a/docs/verification/evidence/name-suggestions/new-card-light.jpg b/docs/verification/evidence/name-suggestions/new-card-light.jpg
new file mode 100644
index 0000000000..6bfc13f853
Binary files /dev/null and b/docs/verification/evidence/name-suggestions/new-card-light.jpg differ
diff --git a/docs/verification/evidence/name-suggestions/refreshed-dark.jpg b/docs/verification/evidence/name-suggestions/refreshed-dark.jpg
new file mode 100644
index 0000000000..e9ffcae48f
Binary files /dev/null and b/docs/verification/evidence/name-suggestions/refreshed-dark.jpg differ
diff --git a/docs/verification/evidence/name-suggestions/refreshed-light.jpg b/docs/verification/evidence/name-suggestions/refreshed-light.jpg
new file mode 100644
index 0000000000..a7b8111567
Binary files /dev/null and b/docs/verification/evidence/name-suggestions/refreshed-light.jpg differ
diff --git a/docs/verification/evidence/name-suggestions/renamed-updating-dark.jpg b/docs/verification/evidence/name-suggestions/renamed-updating-dark.jpg
new file mode 100644
index 0000000000..a37cb0cfec
Binary files /dev/null and b/docs/verification/evidence/name-suggestions/renamed-updating-dark.jpg differ
diff --git a/docs/verification/evidence/name-suggestions/renamed-updating-light.jpg b/docs/verification/evidence/name-suggestions/renamed-updating-light.jpg
new file mode 100644
index 0000000000..39f703975b
Binary files /dev/null and b/docs/verification/evidence/name-suggestions/renamed-updating-light.jpg differ
diff --git a/server/index.test.ts b/server/index.test.ts
index 3fdc15389d..c64e19bc3b 100644
--- a/server/index.test.ts
+++ b/server/index.test.ts
@@ -460,7 +460,7 @@ beforeAll(async () => {
writeFileSync(
join(home, ".openmausbot", "config.json"),
JSON.stringify({
- // generated titles are opt-in; this suite owns the one-shot's reply file (FAKE_CLAUDE_TEXT_FILE below); one test turns the setup card's answers on
+ // generated titles are opt-in; this suite owns the one-shot's reply file (FAKE_CLAUDE_TEXT_FILE below); the setup card's tests turn its answers on
features: { llmThreadTitles: true, browser: false, smartSetupChoices: false },
instances: {
ghost: { driver: "not-a-real-driver", displayName: "Ghost" },
@@ -7814,6 +7814,45 @@ describe("harness HTTP API", () => {
}
});
+ it("writes a new bot's setup answers again when it is renamed before anyone answers, and without the name for a picked one", async () => {
+ const hiring = ["Screen my new candidates", "Draft a job post", "Schedule my interviews", "Find candidates on job sites", "Remind me to follow up"];
+ const everyday = ["Find cheap flights", "Sort my inbox", "Check my calendar", "Draft a cover letter", "Remind me to pay bills"];
+ const greeting = async (threadId: string) => (await api("GET", `/api/threads/${threadId}/messages?limit=50`)).body.messages[0];
+ const settled = async (threadId: string) => {
+ await expect.poll(async () => { const line = await greeting(threadId); return line.setupChoicesPending ?? line.setupChoicesUpdating ?? null; }, { timeout: 10_000 }).toBeNull();
+ return greeting(threadId);
+ };
+ const answer = (choices: string[]) => { writeFileSync(setupAnswersFile, `${JSON.stringify(choices)}\n`); rmSync(setupAnswersDump, { force: true }); };
+ let id = "";
+ expect((await api("PUT", "/api/config", { features: { smartSetupChoices: true } })).status).toBe(200);
+ try {
+ rmSync(setupAnswersFile, { force: true });
+ const created = await api("POST", "/api/bots", { name: "Pepper", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" }, requireAvailableModel: true });
+ expect(created.status).toBe(201);
+ id = created.body.bot.id;
+ const { threadId } = created.body.bot;
+ const fixed = created.body.bot.messages[0].setupChoices;
+ expect((await settled(threadId)).setupChoices).toEqual(fixed);
+
+ answer(hiring);
+ expect((await api("PATCH", `/api/bots/${id}`, { name: "Recruiter" })).status).toBe(200);
+ expect((await greeting(threadId)).setupChoicesUpdating).toEqual(expect.any(Number));
+ expect((await settled(threadId)).setupChoices).toEqual(hiring);
+ expect((await readJsonFileWhenReady<{ prompt: string }>(setupAnswersDump)).prompt).toContain("Bot name: Recruiter");
+
+ answer(everyday);
+ expect((await api("PATCH", `/api/bots/${id}`, { name: "Pesto" })).status).toBe(200);
+ const unnamed = await settled(threadId);
+ const rewritten = existsSync(setupAnswersDump) ? await readJsonFileWhenReady<{ prompt: string }>(setupAnswersDump) : null;
+ expect(unnamed.setupChoices).toEqual(rewritten ? everyday : fixed);
+ expect(rewritten?.prompt ?? "").not.toContain("Bot name:");
+ } finally {
+ rmSync(setupAnswersFile, { force: true });
+ if (id) await api("DELETE", `/api/bots/${id}`);
+ await api("PUT", "/api/config", { features: { smartSetupChoices: false } });
+ }
+ });
+
it("validates approval decisions and reports a request that is no longer open", async () => {
const { body } = await api("GET", "/api/bots");
const bot = body.bots[0];
diff --git a/server/setup-suggestions.test.ts b/server/setup-suggestions.test.ts
index 90f6c082c5..c06096272d 100644
--- a/server/setup-suggestions.test.ts
+++ b/server/setup-suggestions.test.ts
@@ -3,10 +3,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DATA_DIR } from "./config.ts";
import { isPickedBotName } from "./names.ts";
-import { hasSetupChoices } from "./initial-greeting.ts";
-import { aboutMeExcerpt, createSetupSuggestions, parseSetupSuggestions, setupSuggestionPrompt, suggestionBasis, worthAsking, type SuggestionApps,
- type SuggestionBasis } from "./setup-suggestions.ts";
-import type { BotRecord } from "./store.ts";
+import { hasSetupChoices, setupChoices } from "./initial-greeting.ts";
+import { aboutMeExcerpt, createSetupSuggestions, parseSetupSuggestions, RENAME_SETTLE_MS, SETUP_SUGGESTIONS_DEADLINE_MS, setupSuggestionPrompt,
+ suggestionBasis, worthAsking, type SuggestionApps, type SuggestionBasis } from "./setup-suggestions.ts";
+import type { BotRecord, Message } from "./store.ts";
import { cancelSetupRequest } from "./setup-request.ts";
import type { SideJobText } from "./side-jobs.ts";
import { Store } from "./store.ts";
@@ -229,3 +229,217 @@ describe("the card's answers", () => {
expect(empty.greeting().setupChoicesPending).toBeUndefined();
});
});
+
+describe("renaming a new bot before its card is answered", () => {
+ beforeEach(() => {
+ rmSync(DATA_DIR, { recursive: true, force: true });
+ vi.useFakeTimers();
+ });
+ afterEach(() => vi.useRealTimers());
+
+ const FIXED = setupChoices("en");
+ const RECRUITER = ["Screen my new candidates", "Draft a job post", "Schedule my interviews", "Find candidates on job sites", "Remind me to follow up"];
+ const GARDENER = ["Find plants for my balcony", "Remind me to water plants", "Check the weekly frost forecast", "Draft a planting plan", "Compare garden tools"];
+ const PLANNER = ["Find a party venue", "Draft my guest invitations", "Compare catering options", "Remind me to send invites", "Plan a party menu"];
+ type Reply = () => Promise<string>;
+ const replying = (choices: readonly string[]): Reply => async () => JSON.stringify(choices);
+ const later = () => {
+ let answer!: (text: string) => void;
+ const reply = new Promise<string>((resolve) => { answer = resolve; });
+ return { reply: () => reply, answer };
+ };
+
+ function setup(options: { name?: string; replies?: Record<string, Reply>; withinBudget?: () => boolean; canSetUp?: () => boolean } = {}) {
+ const store = new Store(() => ({ instanceId: "claude", model: "claude-sonnet-5" }), undefined, undefined, "en");
+ const bot = store.createBot({ name: options.name ?? "Pepper" });
+ const replies: Record<string, Reply> = { Recruiter: replying(RECRUITER), Gardener: replying(GARDENER), "Party Planner": replying(PLANNER), ...options.replies };
+ const calls: Array<{ name: string; signal?: AbortSignal }> = [];
+ const writer: SideJobText = { via: "engine", generateText: (prompt, callOptions) => {
+ const name = /^Bot name: (.*)$/m.exec(prompt)?.[1] ?? "";
+ calls.push({ name, ...(callOptions?.signal ? { signal: callOptions.signal } : {}) });
+ return (replies[name] ?? (async () => "[]"))();
+ } };
+ const patches: Array<Partial<Message>> = [];
+ const patchMessage = store.patchMessage.bind(store);
+ store.patchMessage = (threadId, id, patch) => { patches.push(patch); return patchMessage(threadId, id, patch); };
+ const suggestions = createSetupSuggestions({
+ store, enabled: () => true, canSetUp: () => options.canSetUp?.() ?? true, withinBudget: () => options.withinBudget?.() ?? true,
+ writer: () => writer, apps: () => null,
+ facts: (of) => suggestionBasis(of, { bots: store.bots, shared: false, languageCode: "en", canBrowse: true }),
+ });
+ suggestions.personalise(bot.id);
+ const greeting = () => store.messagesFor(bot.threadId)[0]!;
+ const rename = (name: string) => store.patchBotProfile(bot.id, { name });
+ const settle = () => vi.advanceTimersByTimeAsync(RENAME_SETTLE_MS);
+ return { store, bot, calls, patches, greeting, rename, settle, named: () => calls.map((call) => call.name) };
+ }
+
+ it("marks the card busy at once, writes it once the rename settles, and swaps the new answers in with the end of the wait", async () => {
+ const s = setup();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(s.calls).toHaveLength(0);
+ expect(s.greeting().setupChoices).toEqual(FIXED);
+ s.rename("Recruiter");
+ expect(s.greeting().setupChoicesUpdating).toBeTypeOf("number");
+ expect(s.greeting().setupChoices).toEqual(FIXED);
+ await vi.advanceTimersByTimeAsync(RENAME_SETTLE_MS - 1);
+ expect(s.calls).toHaveLength(0);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(s.named()).toEqual(["Recruiter"]);
+ expect(s.greeting().setupChoices).toEqual(RECRUITER);
+ expect(s.greeting().setupChoicesUpdating).toBeUndefined();
+ expect(s.patches).toStrictEqual([
+ { setupChoicesPending: undefined, setupChoicesUpdating: expect.any(Number) },
+ { setupChoicesPending: undefined, setupChoicesUpdating: undefined, setupChoices: RECRUITER },
+ ]);
+ });
+
+ it("follows a rename by any path, and a new title or department too", async () => {
+ const s = setup();
+ s.store.patchBot(s.bot.id, { name: "Gardener" });
+ await s.settle();
+ expect(s.greeting().setupChoices).toEqual(GARDENER);
+ s.store.patchBotProfile(s.bot.id, { name: "Pepper", title: "Party Planner" });
+ await s.settle();
+ expect(s.calls.at(-1)!.name).toBe("");
+ s.store.patchBot(s.bot.id, { section: "Hiring" });
+ await s.settle();
+ expect(s.calls).toHaveLength(3);
+ s.store.patchBotProfile(s.bot.id, { notifications: false });
+ s.store.patchTask(s.bot.id, s.bot.threadId, { unread: true });
+ await s.settle();
+ expect(s.calls).toHaveLength(3);
+ expect(s.greeting().setupChoicesUpdating).toBeUndefined();
+ });
+
+ it("goes back to the fixed answers for a picked or blank name without asking, and does nothing between two picked names", async () => {
+ const s = setup({ name: "Recruiter" });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(s.greeting().setupChoices).toEqual(RECRUITER);
+ s.rename("Pesto");
+ await s.settle();
+ expect(s.named()).toEqual(["Recruiter"]);
+ expect(s.greeting().setupChoices).toEqual(FIXED);
+ expect(s.greeting().setupChoicesUpdating).toBeUndefined();
+ const seen = s.patches.length;
+ s.rename("Pepper 2");
+ await s.settle();
+ expect(s.patches).toHaveLength(seen);
+ s.rename("Gardener");
+ await s.settle();
+ expect(s.greeting().setupChoices).toEqual(GARDENER);
+ s.store.patchBot(s.bot.id, { name: " " });
+ await s.settle();
+ expect(s.named()).toEqual(["Recruiter", "Gardener"]);
+ expect(s.greeting().setupChoices).toEqual(FIXED);
+ });
+
+ it("never writes again once the person has written, picked or closed the card, or the bot has instructions", async () => {
+ const acts: Array<(s: ReturnType<typeof setup>) => void> = [
+ (s) => s.store.appendMessage(s.bot.threadId, { role: "user", kind: "text", text: "hello" }),
+ (s) => s.store.patchTask(s.bot.id, s.bot.threadId, { setupRequest: { at: Date.now() } }),
+ (s) => cancelSetupRequest(s.store, s.bot.id, s.bot.threadId),
+ (s) => s.store.patchBot(s.bot.id, { description: "Hires people." }),
+ ];
+ for (const act of acts) {
+ const s = setup();
+ act(s);
+ const seen = s.patches.length;
+ s.rename("Recruiter");
+ await s.settle();
+ expect(s.calls).toHaveLength(0);
+ expect(s.patches).toHaveLength(seen);
+ }
+ });
+
+ it("stops a rewrite the person answers while it is on its way, and keeps the answers they saw", async () => {
+ const waiting = setup();
+ waiting.rename("Recruiter");
+ waiting.store.appendMessage(waiting.bot.threadId, { role: "user", kind: "text", text: "find me a dentist" });
+ expect(waiting.greeting().setupChoicesUpdating).toBeUndefined();
+ await waiting.settle();
+ expect(waiting.calls).toHaveLength(0);
+
+ const reply = later();
+ const asked = setup({ replies: { Recruiter: reply.reply } });
+ asked.rename("Recruiter");
+ await asked.settle();
+ expect(asked.named()).toEqual(["Recruiter"]);
+ asked.store.patchTask(asked.bot.id, asked.bot.threadId, { setupRequest: { at: Date.now() } });
+ expect(asked.calls[0]!.signal?.aborted).toBe(true);
+ expect(asked.greeting().setupChoicesUpdating).toBeUndefined();
+ reply.answer(JSON.stringify(RECRUITER));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(asked.greeting().setupChoices).toEqual(FIXED);
+ });
+
+ it("waits for rapid renames to settle and cancels a stale writing, so the latest name wins", async () => {
+ const s = setup();
+ s.rename("Recruiter");
+ await vi.advanceTimersByTimeAsync(RENAME_SETTLE_MS / 2);
+ s.rename("Gardener");
+ await vi.advanceTimersByTimeAsync(RENAME_SETTLE_MS / 2);
+ expect(s.calls).toHaveLength(0);
+ await vi.advanceTimersByTimeAsync(RENAME_SETTLE_MS / 2);
+ expect(s.named()).toEqual(["Gardener"]);
+ expect(s.greeting().setupChoices).toEqual(GARDENER);
+
+ const stale = later();
+ const t = setup({ replies: { Recruiter: stale.reply } });
+ t.rename("Recruiter");
+ await t.settle();
+ t.rename("Party Planner");
+ expect(t.calls[0]!.signal?.aborted).toBe(true);
+ expect(t.greeting().setupChoicesUpdating).toBeTypeOf("number");
+ await t.settle();
+ expect(t.named()).toEqual(["Recruiter", "Party Planner"]);
+ expect(t.greeting().setupChoices).toEqual(PLANNER);
+ stale.answer(JSON.stringify(RECRUITER));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(t.greeting().setupChoices).toEqual(PLANNER);
+ expect(t.patches.filter((patch) => patch.setupChoices)).toHaveLength(1);
+ });
+
+ it("replaces the first answers' writing when the bot is renamed while the card still waits for them", async () => {
+ const first = later();
+ const s = setup({ name: "Max", replies: { Max: first.reply } });
+ expect(s.greeting().setupChoicesPending).toBe(true);
+ s.rename("Recruiter");
+ expect(s.calls[0]!.signal?.aborted).toBe(true);
+ expect(s.greeting().setupChoicesPending).toBeUndefined();
+ expect(s.greeting().setupChoicesUpdating).toBeTypeOf("number");
+ first.answer(JSON.stringify(GARDENER));
+ await s.settle();
+ expect(s.named()).toEqual(["Max", "Recruiter"]);
+ expect(s.greeting().setupChoices).toEqual(RECRUITER);
+ expect(s.greeting().setupChoicesUpdating).toBeUndefined();
+ });
+
+ it("keeps the answers it shows, and takes picks again, when the writing fails, is unusable, is late or cannot start", async () => {
+ const replies: Reply[] = [async () => { throw new Error("offline"); }, async () => "I cannot help with that.", () => new Promise<string>(() => {})];
+ for (const reply of replies) {
+ const s = setup({ name: "Recruiter", replies: { Gardener: reply } });
+ await vi.advanceTimersByTimeAsync(0);
+ s.rename("Gardener");
+ await s.settle();
+ await vi.advanceTimersByTimeAsync(SETUP_SUGGESTIONS_DEADLINE_MS);
+ expect(s.named()).toEqual(["Recruiter", "Gardener"]);
+ expect(s.greeting().setupChoices).toEqual(RECRUITER);
+ expect(s.greeting().setupChoicesUpdating).toBeUndefined();
+ }
+ let budget = true;
+ const broke = setup({ name: "Recruiter", withinBudget: () => budget });
+ await vi.advanceTimersByTimeAsync(0);
+ budget = false;
+ broke.rename("Gardener");
+ await broke.settle();
+ expect(broke.named()).toEqual(["Recruiter"]);
+ expect(broke.greeting().setupChoices).toEqual(RECRUITER);
+ expect(broke.greeting().setupChoicesUpdating).toBeUndefined();
+ const plain = setup({ canSetUp: () => false });
+ plain.rename("Recruiter");
+ await plain.settle();
+ expect(plain.calls).toHaveLength(0);
+ expect(plain.greeting().setupChoicesUpdating).toBeUndefined();
+ });
+});
diff --git a/server/setup-suggestions.ts b/server/setup-suggestions.ts
index bc34ac3a7f..7c9fbb448f 100644
--- a/server/setup-suggestions.ts
+++ b/server/setup-suggestions.ts
@@ -1,20 +1,21 @@
-// Personal answers for a new bot's setup card, written by the bot's own engine (or the helper) as a side job. The card
-// waits for them, for at most 6 s, and is filled once: the answers never change under the person's eyes, so a letter
-// key always picks the job it shows. Without anything to go on, or when no one can write them, the fixed answers
-// (initial-greeting.ts) show at once.
+// Personal answers for a new bot's setup card, written by the bot's own engine (or the helper) as a side job. A new
+// card waits for them for at most 6 s, and renaming the bot while its card is unanswered writes them again for the new
+// name. While they are written the card takes no pick, and they change only in the change that ends that wait, so a
+// letter key always picks a job the person could read. Without anything to go on the fixed answers (initial-greeting.ts)
+// show; when no one can write them, the card keeps what it shows.
import { redactSecretsInText } from "../shared/redact.ts";
import { appLabel } from "./app-event-catalog.ts";
import type { AppConfig } from "./config.ts";
import type { ProviderAdapter } from "./contracts.ts";
-import { hasSetupChoices } from "./initial-greeting.ts";
+import { hasSetupChoices, setupChoices } from "./initial-greeting.ts";
import { isPickedBotName } from "./names.ts";
import { LEARNED_LINE } from "./profile-learned.ts";
import { openSetupOffer, type SetupRequestStore } from "./setup-request.ts";
import type { SideJobText } from "./side-jobs.ts";
-import type { BotRecord } from "./store.ts";
+import type { BotRecord, Message, Store } from "./store.ts";
export interface SuggestionFacts {
- /** As typed; absent when the server picked the name (isPickedBotName). */
+ /** As typed; absent when it is blank or the server picked it (isPickedBotName). */
name?: string;
title?: string;
department?: string;
@@ -170,10 +171,12 @@ export function worthAsking(facts: SuggestionBasis, apps: SuggestionApps): boole
}
export const SETUP_SUGGESTIONS_DEADLINE_MS = 6_000;
+/** Renames closer together than this are written for once, with the latest name. */
+export const RENAME_SETTLE_MS = 600;
const APPS_WAIT_MS = 700;
export interface SetupSuggestionsDeps {
- store: SetupRequestStore;
+ store: SetupRequestStore & Pick<Store, "onChange">;
/** config.json features.smartSetupChoices, on unless false. */
enabled(): boolean;
/** The bot's engine can set a bot up, as a pick needs. */
@@ -188,59 +191,166 @@ export interface SetupSuggestionsDeps {
const sleep = (ms: number) => new Promise<void>((resolve) => { setTimeout(resolve, ms).unref?.(); });
+const typedName = (name: string): string | undefined => (name.trim() && !isPickedBotName(name) ? name : undefined);
+
+/** What the prompt reads first: the typed name, the title and the department. */
+const calledKey = (bot: Pick<BotRecord, "name" | "title" | "section">): string =>
+ JSON.stringify([factLine(typedName(bot.name), 80), factLine(bot.title, 120), factLine(bot.section, 60)]);
+
+/** One writing of a bot's card; a newer one for the same bot supersedes it. */
+interface CardJob {
+ threadId: string;
+ greetingId: string;
+ stop: AbortController;
+ timer?: ReturnType<typeof setTimeout>;
+}
+
+type Outcome = "shown" | "nothing to go on" | "unusable reply" | "failed" | "late" | "stopped";
+
export function createSetupSuggestions(deps: SetupSuggestionsDeps) {
- async function write(bot: BotRecord, greetingId: string, writer: SideJobText, basis: SuggestionBasis, apps: SuggestionApps): Promise<void> {
+ const jobs = new Map<string, CardJob>();
+ const called = new Map(deps.store.bots.map((bot) => [bot.id, calledKey(bot)]));
+
+ const unanswered = (bot: BotRecord): Message | null => {
+ const greeting = openSetupOffer(deps.store, bot.id, bot.threadId);
+ return greeting && !deps.store.taskByThread(bot.id, bot.threadId)?.setupRequest ? greeting : null;
+ };
+
+ function drop(botId: string): void {
+ const job = jobs.get(botId);
+ if (!job) return;
+ jobs.delete(botId);
+ clearTimeout(job.timer);
+ job.stop.abort();
+ }
+
+ function begin(bot: BotRecord, greetingId: string): CardJob {
+ drop(bot.id);
+ const job: CardJob = { threadId: bot.threadId, greetingId, stop: new AbortController() };
+ jobs.set(bot.id, job);
+ return job;
+ }
+
+ /** Ends the job, so the card takes picks again: with `choices` while it is unanswered, else with what it shows. Null
+ * when a newer job owns the card. */
+ function settle(botId: string, job: CardJob, choices: readonly string[] | null): boolean | null {
+ if (jobs.get(botId) !== job) return null;
+ drop(botId);
+ const greeting = deps.store.messagesFor(job.threadId).find((message) => message.id === job.greetingId);
+ if (!greeting?.setupChoicesPending && greeting?.setupChoicesUpdating === undefined) return false;
+ const bot = deps.store.bot(botId);
+ const shown = choices !== null && bot !== null && unanswered(bot)?.id === job.greetingId;
+ deps.store.patchMessage(job.threadId, job.greetingId, { setupChoicesPending: undefined, setupChoicesUpdating: undefined, ...(shown ? { setupChoices: [...choices] } : {}) });
+ return shown;
+ }
+
+ async function ask(writer: SideJobText, basis: SuggestionBasis, apps: SuggestionApps, stop: AbortSignal): Promise<{ choices: string[] | null; outcome: Outcome }> {
const started = Date.now();
const expiry = new AbortController();
const timer = setTimeout(() => expiry.abort(), SETUP_SUGGESTIONS_DEADLINE_MS);
timer.unref?.();
- const expired = new Promise<never>((_, reject) => expiry.signal.addEventListener("abort", () => reject(new Error("late")), { once: true }));
- expired.catch(() => undefined);
- let choices: string[] | null = null;
- let outcome = "failed";
+ const signal = AbortSignal.any([expiry.signal, stop]);
+ const ended = new Promise<never>((_, reject) => signal.addEventListener("abort", () => reject(new Error("ended")), { once: true }));
+ ended.catch(() => undefined);
try {
- const named = apps && "later" in apps ? await Promise.race([apps.later, sleep(APPS_WAIT_MS).then(() => [])]) : apps?.known ?? [];
- if (!worthAsking(basis, { known: named })) {
- outcome = "nothing to go on";
- return;
- }
+ const named = apps && "later" in apps ? await Promise.race([apps.later, sleep(APPS_WAIT_MS).then(() => []), ended]) : apps?.known ?? [];
+ if (!worthAsking(basis, { known: named })) return { choices: null, outcome: "nothing to go on" };
const prompt = setupSuggestionPrompt({ ...basis, apps: named });
const remaining = Math.max(1, SETUP_SUGGESTIONS_DEADLINE_MS - (Date.now() - started));
- const reply = await Promise.race([writer.generateText(prompt, { signal: expiry.signal, timeoutMs: remaining }), expired]);
- choices = parseSetupSuggestions(reply, basis.languageCode);
- outcome = choices ? "shown" : "unusable reply";
+ const reply = await Promise.race([writer.generateText(prompt, { signal, timeoutMs: remaining }), ended]);
+ const choices = parseSetupSuggestions(reply, basis.languageCode);
+ return { choices, outcome: choices ? "shown" : "unusable reply" };
} catch {
- outcome = expiry.signal.aborted ? "late" : "failed";
+ return { choices: null, outcome: stop.aborted ? "stopped" : expiry.signal.aborted ? "late" : "failed" };
} finally {
clearTimeout(timer);
- try {
- const greeting = deps.store.messagesFor(bot.threadId).find((message) => message.id === greetingId);
- if (greeting?.setupChoicesPending) {
- const open = openSetupOffer(deps.store, bot.id, bot.threadId)?.id === greetingId && !deps.store.taskByThread(bot.id, bot.threadId)?.setupRequest;
- const shown = choices !== null && open && !expiry.signal.aborted;
- deps.store.patchMessage(bot.threadId, greetingId, { setupChoicesPending: undefined, ...(shown ? { setupChoices: choices! } : {}) });
- deps.log?.(`setup card answers for ${bot.id}: ${shown ? "shown" : outcome === "shown" ? "late" : outcome} after ${Date.now() - started} ms (${bot.modelSelection.instanceId}, ${writer.via})`);
- }
- } catch {
- deps.log?.(`setup card answers for ${bot.id}: could not be saved`);
- }
}
}
+ /** `renamed`: the card already shows answers, and nothing to go on means the fixed ones. */
+ async function write(bot: BotRecord, job: CardJob, writer: SideJobText, basis: SuggestionBasis, apps: SuggestionApps, renamed: boolean): Promise<void> {
+ const started = Date.now();
+ const { choices, outcome } = await ask(writer, basis, apps, job.stop.signal);
+ try {
+ const shown = settle(bot.id, job, choices ?? (renamed && outcome === "nothing to go on" ? setupChoices(basis.languageCode) : null));
+ if (shown === null) return;
+ deps.log?.(`setup card answers for ${bot.id}${renamed ? " after a rename" : ""}: ${!shown && outcome === "shown" ? "late" : outcome} after ${Date.now() - started} ms (${bot.modelSelection.instanceId}, ${writer.via})`);
+ } catch {
+ deps.log?.(`setup card answers for ${bot.id}: could not be saved`);
+ }
+ }
+
+ /** Ends a rename's job without asking anyone. */
+ function end(botId: string, job: CardJob, why: string, choices: readonly string[] | null = null): void {
+ try {
+ if (settle(botId, job, choices) !== null) deps.log?.(`setup card answers for ${botId} after a rename: ${why}`);
+ } catch {
+ deps.log?.(`setup card answers for ${botId}: could not be saved`);
+ }
+ }
+
+ function rewrite(botId: string, job: CardJob): void {
+ const bot = deps.store.bot(botId);
+ if (!bot || jobs.get(botId) !== job) return;
+ try {
+ if (!unanswered(bot)) return end(botId, job, "answered first");
+ const basis = deps.facts(bot);
+ const apps = deps.apps(bot);
+ if (!worthAsking(basis, apps)) return end(botId, job, "nothing to go on", setupChoices(basis.languageCode));
+ const writer = deps.withinBudget() ? deps.writer(bot.id) : null;
+ if (!writer) return end(botId, job, "no one can write them");
+ void write(bot, job, writer, basis, apps, true);
+ } catch {
+ end(botId, job, "not asked");
+ }
+ }
+
+ /** The card takes no pick from now on, so a letter key never picks an answer written for the old name. */
+ function renamed(bot: BotRecord): void {
+ const greeting = deps.enabled() && deps.canSetUp(bot) ? unanswered(bot) : null;
+ const current = jobs.get(bot.id);
+ if (!greeting) {
+ if (current) settle(bot.id, current, null);
+ return;
+ }
+ const job = begin(bot, greeting.id);
+ deps.store.patchMessage(bot.threadId, greeting.id, { setupChoicesPending: undefined, setupChoicesUpdating: Date.now() });
+ job.timer = setTimeout(() => rewrite(bot.id, job), RENAME_SETTLE_MS);
+ job.timer.unref?.();
+ }
+
+ deps.store.onChange((change) => {
+ if (change.type === "bot.deleted") {
+ called.delete(change.botId);
+ drop(change.botId);
+ } else if (change.type === "message" && change.message.role === "user") {
+ for (const [botId, job] of jobs) if (job.threadId === change.threadId) settle(botId, job, null);
+ } else if (change.type === "bot") {
+ const bot = deps.store.bot(change.botId);
+ if (!bot) return;
+ const key = calledKey(bot);
+ const before = called.get(bot.id);
+ called.set(bot.id, key);
+ const current = jobs.get(bot.id);
+ if (before !== undefined && before !== key) renamed(bot);
+ else if (current && !unanswered(bot)) settle(bot.id, current, null);
+ }
+ });
+
return {
/** Marks the card as waiting before it returns, so the new bot's first transcript carries the mark. */
personalise(botId: string): void {
try {
const bot = deps.store.bot(botId);
const greeting = bot && deps.enabled() ? openSetupOffer(deps.store, bot.id, bot.threadId) : null;
- if (!bot || !greeting || greeting.setupChoicesPending || !deps.canSetUp(bot) || !deps.withinBudget()) return;
+ if (!bot || !greeting || jobs.has(bot.id) || greeting.setupChoicesPending || !deps.canSetUp(bot) || !deps.withinBudget()) return;
const writer = deps.writer(bot.id);
if (!writer) return;
const basis = deps.facts(bot);
const apps = deps.apps(bot);
if (!worthAsking(basis, apps)) return;
deps.store.patchMessage(bot.threadId, greeting.id, { setupChoicesPending: true });
- void write(bot, greeting.id, writer, basis, apps);
+ void write(bot, begin(bot, greeting.id), writer, basis, apps, false);
} catch {
deps.log?.(`setup card answers for ${botId}: not asked`);
}
@@ -256,7 +366,7 @@ export function suggestionBasis(bot: BotRecord, place: { bots: readonly BotRecor
try { language = new Intl.DisplayNames(["en"], { type: "language" }).of(place.languageCode) ?? "English"; } catch { language = "English"; }
const aboutMe = place.shared ? undefined : aboutMeExcerpt(place.aboutMe, redactSecretsInText);
return {
- ...(isPickedBotName(bot.name) ? {} : { name: bot.name }),
+ ...(typedName(bot.name) ? { name: bot.name } : {}),
...(bot.title ? { title: bot.title } : {}),
...(bot.section ? { department: bot.section } : {}),
...(aboutMe ? { aboutMe } : {}),
@@ -271,7 +381,7 @@ type EngineCapabilities = Partial<Pick<ProviderAdapter["capabilities"], "agentsM
/** The server's side of the card's writer, read as each bot is made. */
export interface SetupSuggestionsHost extends Pick<SetupSuggestionsDeps, "withinBudget" | "writer" | "log"> {
- store: SetupRequestStore & { readonly bots: readonly BotRecord[] };
+ store: SetupSuggestionsDeps["store"] & { readonly bots: readonly BotRecord[] };
config(): Pick<AppConfig, "features" | "profile">;
/** Several people share this place. */
shared(): boolean;
diff --git a/server/testing/fake-claude-cli.ts b/server/testing/fake-claude-cli.ts
index 5d15ff7c3e..1296771fea 100755
--- a/server/testing/fake-claude-cli.ts
+++ b/server/testing/fake-claude-cli.ts
@@ -386,8 +386,11 @@ if (["text", "json"].includes(argAfter("--output-format") ?? "")) {
}
// Every new bot asks for its setup card's answers (server/setup-suggestions.ts), so that call stays out of the captures
// below too: FAKE_CLAUDE_SETUP_DUMP records it, FAKE_CLAUDE_SETUP_FILE holds its reply, and without one it fails at once.
+ // FAKE_CLAUDE_SETUP_DELAY_MS holds the reply back, so a recipe can see the card while it waits.
if (prompt.startsWith("You write the answer options for the first message of a new bot")) {
if (process.env.FAKE_CLAUDE_SETUP_DUMP) writeDumpAtomic(process.env.FAKE_CLAUDE_SETUP_DUMP, JSON.stringify({ argv, env: process.env, prompt }, null, 2));
+ const delay = Number(process.env.FAKE_CLAUDE_SETUP_DELAY_MS);
+ if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));
const file = process.env.FAKE_CLAUDE_SETUP_FILE;
if (file && existsSync(file)) replyText(readFileSync(file, "utf8"));
process.stderr.write("fake setup answers failed\n");
diff --git a/server/testing/fake-claude-dump.test.ts b/server/testing/fake-claude-dump.test.ts
index 6c407c80e8..89cb6296c8 100644
--- a/server/testing/fake-claude-dump.test.ts
+++ b/server/testing/fake-claude-dump.test.ts
@@ -102,7 +102,7 @@ it("keeps the server's connection check out of every turn and one-shot capture,
}
});
-it("keeps a new bot's setup answers out of every turn and one-shot capture, failing at once without a reply file", async () => {
+it("keeps a new bot's setup answers out of every turn and one-shot capture, failing at once without a reply file, and holds the reply back on request", async () => {
const home = mkdtempSync(join(tmpdir(), "omb-claude-dump-"));
const dump = join(home, "capture.json");
const textDump = join(home, "text.json");
@@ -110,11 +110,11 @@ it("keeps a new bot's setup answers out of every turn and one-shot capture, fail
const setupDump = join(home, "setup.json");
const setupFile = join(home, "setup.txt");
const prompt = "You write the answer options for the first message of a new bot in OpenMausBot.";
- const ask = async () => {
+ const ask = async (extra: Record<string, string> = {}) => {
const child = spawn(process.execPath, [fileURLToPath(new URL("fake-claude-cli.ts", import.meta.url)), "-p", "--output-format", "text"], {
cwd: home,
env: { ...process.env, HOME: home, USERPROFILE: home, FAKE_CLAUDE_MODE: "happy", FAKE_CLAUDE_DUMP: dump, FAKE_CLAUDE_TEXT_DUMP: textDump,
- FAKE_CLAUDE_TEXT_LOG: textLog, FAKE_CLAUDE_TEXT_FILE: join(home, "missing"), FAKE_CLAUDE_SETUP_DUMP: setupDump, FAKE_CLAUDE_SETUP_FILE: setupFile },
+ FAKE_CLAUDE_TEXT_LOG: textLog, FAKE_CLAUDE_TEXT_FILE: join(home, "missing"), FAKE_CLAUDE_SETUP_DUMP: setupDump, FAKE_CLAUDE_SETUP_FILE: setupFile, ...extra },
stdio: ["pipe", "pipe", "pipe"],
});
let stdout = "";
@@ -129,6 +129,9 @@ it("keeps a new bot's setup answers out of every turn and one-shot capture, fail
expect(await ask()).toEqual({ code: 0, stdout: '["Sort my receipts"]' });
for (const file of [dump, textDump, textLog]) expect(existsSync(file), file).toBe(false);
expect(JSON.parse(readFileSync(setupDump, "utf8")).prompt).toBe(prompt);
+ const started = Date.now();
+ expect(await ask({ FAKE_CLAUDE_SETUP_DELAY_MS: "1500" })).toEqual({ code: 0, stdout: '["Sort my receipts"]' });
+ expect(Date.now() - started).toBeGreaterThanOrEqual(1500);
} finally {
await removeTempDir(home);
}
diff --git a/shared/setup-card.ts b/shared/setup-card.ts
new file mode 100644
index 0000000000..3ca89c250b
--- /dev/null
+++ b/shared/setup-card.ts
@@ -0,0 +1,19 @@
+/** What clients draw the setup card under a new bot's greeting from. */
+export interface SetupCardFields {
+ /** A new bot's greeting while it has no role or instructions: clients that know it draw the setup card under the
+ * text; `text` reads on its own for older ones. It stays once the card is answered, so the card can show the answer;
+ * closing the card clears it. */
+ setupOffer?: true;
+ /** The setup card's answers, in the app's language. Picking one sends its words; absent on older greetings, where a
+ * client offers its own. Replaced only in the change that clears setupChoicesPending or setupChoicesUpdating. */
+ setupChoices?: string[];
+ /** Personal answers for this card are being written: clients show the card without answers until it clears. The
+ * server clears it within 6 s, in the same change that sets setupChoices if they came in time; a client still seeing
+ * it 8 s after showing the card, or on a greeting older than 20 s, shows setupChoices. */
+ setupChoicesPending?: true;
+ /** Epoch ms the bot's latest rename started rewriting setupChoices, while the card was unanswered: clients keep
+ * showing them but take no pick until it clears. The server clears it within 7 s of the stamp, in the same change
+ * that sets the new setupChoices if they came in time; a client still seeing a stamp 8 s after it first saw it, or
+ * one older than 20 s, takes picks again. */
+ setupChoicesUpdating?: number;
+}
diff --git a/shared/wire.ts b/shared/wire.ts
index a870b47c93..cf74349c9c 100644
--- a/shared/wire.ts
+++ b/shared/wire.ts
@@ -11,6 +11,7 @@ import type { BotBodyId } from "./bot-body.ts";
import type { ReplyStyle } from "./reply-style.ts";
import type { CredentialTargetId } from "./credential-request.ts";
import type { TeamSetupRequest } from "./team-setup.ts"; import type { DefaultBotFields, HelperIntroField } from "./default-bot.ts";
+import type { SetupCardFields } from "./setup-card.ts";
import type { RoutineRequestCardData } from "./routine-request.ts";
import type { WebhookRequestCardData } from "./webhook-request.ts";
import type { AppEventAttempt, AppTrigger, AppTriggerRequestCardData, AppTriggerService } from "./app-triggers.ts";
@@ -444,7 +445,7 @@ export type CardAnswerer = (
export const EXCERPT_SUMMARY_HEADER = "Historical excerpts in chronological order; newer corrections override older requests. These excerpts may omit earlier details.";
/** One transcript line, serialized as stored. */
-export interface WireMessage extends HelperIntroField {
+export interface WireMessage extends HelperIntroField, SetupCardFields {
roomRequest?: { id: string; phase: "request" | "result" };
id: string;
role: "bot" | "user";
@@ -477,17 +478,6 @@ export interface WireMessage extends HelperIntroField {
serverCard?: true;
/** A setup suggestion the device renders in its own words (server/host/helper-suggestion.ts); `text` is the English. */
setupSuggestion?: { kind: "helperKey"; answer?: "notNow" };
- /** A new bot's greeting while it has no role or instructions: clients that know it draw the setup card under the
- * text (server/setup-request.ts); `text` reads on its own for older ones. It stays once the card is answered, so the
- * card can show the answer; closing the card clears it. */
- setupOffer?: true;
- /** The setup card's answers, in the app's language. Picking one sends its words; absent on older greetings, where a
- * client offers its own. Replaced at most once, by personal answers, in the change that clears setupChoicesPending. */
- setupChoices?: string[];
- /** Personal answers for this card are being written (server/setup-suggestions.ts): clients show the card without
- * answers until it clears. The server clears it within 6 s, in the same change that sets setupChoices if they came in
- * time; a client still seeing it 8 s after showing the card, or on a greeting older than 20 s, shows setupChoices. */
- setupChoicesPending?: true;
/** A person's line Set me up turned into a setup request: the bot reads it as `/setup <text>`; the chat shows `text`. */
setupRequest?: true;
/** app rows (kind "app"): bot HTML or an MCP server's UI. `text` is always the readable fallback. */
diff --git a/src/components/SetupOffer.tsx b/src/components/SetupOffer.tsx
index 7c43bfeaf1..7bd2ef64c4 100644
--- a/src/components/SetupOffer.tsx
+++ b/src/components/SetupOffer.tsx
@@ -2,6 +2,7 @@
// answers, then Something else. A pick sends its words, which the server runs as setup at once; Something else is
// answered by the bot's own line, and the next thing the person types is what the bot sets itself up for. While it
// waits, a chip above the message box says so and its x stops it. Once answered, the card stays, quiet, with the answer.
+// While its answers are written, at first or after the bot is renamed, it takes no pick.
import { useEffect, useRef, useState, type KeyboardEvent } from "react";
import { Sparkles, X } from "lucide-react";
@@ -17,8 +18,8 @@ const LETTERS = "ABCDEFGH";
const FALLBACK_CHOICES: LocaleKey[] = [
"chat.setupCard.research", "chat.setupCard.watch", "chat.setupCard.inbox", "chat.setupCard.errands", "chat.setupCard.data",
];
-/** How long the card waits for personal answers after it is first shown, and how old a greeting can be before a wait on
- * it is one a restart left behind: the server clears the wait within 6 s. */
+/** How long the card waits for answers being written after it first sees the wait, and how old a wait can be before it
+ * is one a restart left behind: the server ends a wait within 7 s. */
const PENDING_GRACE_MS = 8_000;
const STALE_WAIT_MS = 20_000;
const PLACEHOLDER_WIDTHS = ["62%", "48%", "56%", "44%", "58%", "30%"];
@@ -32,17 +33,26 @@ export function SetupOffer({ botId, threadId, message, transcript }: { botId: st
const [closed, setClosed] = useState(false);
const [error, setError] = useState<string | null>(null);
const [waitedOut, setWaitedOut] = useState(false);
+ const [rewriteWaitedOut, setRewriteWaitedOut] = useState<number | null>(null);
// A double click lands before the disabled buttons are drawn.
const sending = useRef(false);
- // The first list the card shows stays, so a letter key always picks the job on screen.
+ // The list on screen changes only when a wait the card showed ends, so a letter key always picks a job on screen.
const shown = useRef<{ id: string; choices: string[] } | null>(null);
+ const showedWait = useRef(false);
const waitedOnce = useRef(false);
const waiting = message.setupChoicesPending === true && !waitedOut && Date.now() - message.at < STALE_WAIT_MS;
+ const stamp = message.setupChoicesUpdating;
+ const rewriting = stamp !== undefined && rewriteWaitedOut !== stamp && Date.now() - stamp < STALE_WAIT_MS;
useEffect(() => {
if (!waiting) return;
const timer = setTimeout(() => setWaitedOut(true), PENDING_GRACE_MS);
return () => clearTimeout(timer);
}, [waiting]);
+ useEffect(() => {
+ if (!rewriting) return;
+ const timer = setTimeout(() => setRewriteWaitedOut(stamp), PENDING_GRACE_MS);
+ return () => clearTimeout(timer);
+ }, [rewriting, stamp]);
const bot = state.bots.find((candidate) => candidate.id === botId);
if (closed || message.setupOffer !== true || !bot) return null;
const selection = bot.tasks?.find((task) => task.threadId === threadId)?.modelSelection ?? bot.modelSelection;
@@ -53,10 +63,13 @@ export function SetupOffer({ botId, threadId, message, transcript }: { botId: st
const settled = first !== undefined;
const answer = first?.setupRequest ? first : undefined;
const pending = waiting && !settled;
- if (pending) waitedOnce.current = true;
- else if (shown.current?.id !== message.id) {
+ const updating = rewriting && !settled;
+ if (pending || updating) waitedOnce.current = true;
+ if (shown.current?.id !== message.id || (showedWait.current && !pending && !updating)) {
shown.current = { id: message.id, choices: message.setupChoices?.length ? message.setupChoices : FALLBACK_CHOICES.map((key) => t(key)) };
}
+ showedWait.current = pending || updating;
+ const quiet = settled || updating;
const choices = pending ? [] : shown.current!.choices;
const title = t("chat.setupCard.title");
@@ -93,7 +106,7 @@ export function SetupOffer({ botId, threadId, message, transcript }: { botId: st
};
return (
- <section data-setup-card={message.id} aria-label={title} aria-busy={busy || pending || undefined} onKeyDown={settled || pending ? undefined : byLetter}
+ <section data-setup-card={message.id} aria-label={title} aria-busy={busy || pending || updating || undefined} onKeyDown={quiet || pending ? undefined : byLetter}
className="w-full max-w-[min(var(--chat-bubble-max),var(--chat-bubble-pct))] rounded-[24px] bg-composer px-2 pb-2 pt-3 ring-[0.5px] ring-ink/10">
<div className="flex items-start justify-between gap-2 ps-3 pe-1">
<h3 dir="auto" className="py-px text-[16px] font-semibold leading-[22px] text-ink-secondary">{title}</h3>
@@ -108,16 +121,17 @@ export function SetupOffer({ botId, threadId, message, transcript }: { botId: st
<span className="h-4 rounded-md bg-ink/[0.06] motion-safe:animate-pulse" style={{ width }} />
</div>
))}
- </div> : <div className={cn("mt-1.5 flex flex-col", waitedOnce.current && "motion-safe:animate-msg-in")}>
+ </div> : <div key={choices.join("\n")} data-setup-updating={updating ? "" : undefined}
+ className={cn("mt-1.5 flex flex-col", updating ? "motion-safe:animate-pulse" : waitedOnce.current && "motion-safe:animate-msg-in")}>
{options.map((option, index) => (
- <button key={option.label} type="button" data-ask-choice="" disabled={settled || busy} onClick={option.pick}
+ <button key={option.label} type="button" data-ask-choice="" disabled={quiet || busy} onClick={option.pick}
className={cn("group flex min-h-10 items-center gap-3 rounded-xl px-3 py-2 text-start",
- settled ? "cursor-default" : "hover:bg-ink/[0.05] disabled:cursor-default")}>
+ quiet ? "cursor-default" : "hover:bg-ink/[0.05] disabled:cursor-default")}>
<kbd className={cn("flex size-6 shrink-0 items-center justify-center rounded-md font-sans text-[12px] font-medium",
- settled ? "bg-ink/[0.04] text-ink-tertiary" : "bg-ink/[0.07] text-ink-secondary group-hover:bg-ink/[0.1]")}>
+ quiet ? "bg-ink/[0.04] text-ink-tertiary" : "bg-ink/[0.07] text-ink-secondary group-hover:bg-ink/[0.1]")}>
{LETTERS[index]}
</kbd>
- <span dir="auto" className={cn("min-w-0 break-words text-[14px] leading-5", settled ? "text-ink-tertiary" : "text-ink")}>{option.label}</span>
+ <span dir="auto" className={cn("min-w-0 break-words text-[14px] leading-5", quiet ? "text-ink-tertiary" : "text-ink")}>{option.label}</span>
</button>
))}
</div>}
diff --git a/src/components/SetupOffer.waiting.test.ts b/src/components/SetupOffer.waiting.test.ts
index 0a0a958814..b011285955 100644
--- a/src/components/SetupOffer.waiting.test.ts
+++ b/src/components/SetupOffer.waiting.test.ts
@@ -101,3 +101,67 @@ describe("the setup card while its answers are written", () => {
expect(fixture.api).toHaveBeenCalledWith("/api/bots/b1/setup-request", { method: "POST", body: JSON.stringify({ threadId: "t1", text: FIXED[2] }) });
});
});
+
+describe("the setup card while a rename rewrites its answers", () => {
+ const buttons = () => [...container.querySelectorAll<HTMLButtonElement>("[data-ask-choice]")];
+ const rewriting = () => container.querySelector("[data-setup-updating]") !== null;
+ const picked = (text: string) => ["/api/bots/b1/setup-request", { method: "POST", body: JSON.stringify({ threadId: "t1", text }) }];
+
+ it("keeps the answers on screen, quiet, takes no letter or click, then swaps the new ones in at once", () => {
+ show(greeting());
+ show(greeting({ setupChoicesUpdating: Date.now() }));
+ expect(rewriting()).toBe(true);
+ expect(card()!.getAttribute("aria-busy")).toBe("true");
+ expect(labels()).toEqual([...FIXED, "Something else"]);
+ expect(buttons().every((button) => button.disabled)).toBe(true);
+ press("a");
+ press("f");
+ act(() => buttons()[1]!.click());
+ expect(fixture.api).not.toHaveBeenCalled();
+ show(greeting({ setupChoices: PERSONAL }));
+ expect(rewriting()).toBe(false);
+ expect(card()!.getAttribute("aria-busy")).toBeNull();
+ expect(labels()).toEqual([...PERSONAL, "Something else"]);
+ press("b");
+ expect(fixture.api).toHaveBeenCalledWith(...picked(PERSONAL[1]!));
+ });
+
+ it("keeps its answers and takes picks again when the rewrite ends without new ones, also when first drawn mid-rewrite", () => {
+ show(greeting({ setupChoices: PERSONAL, setupChoicesUpdating: Date.now() }));
+ expect(rewriting()).toBe(true);
+ expect(labels()).toEqual([...PERSONAL, "Something else"]);
+ show(greeting({ setupChoices: PERSONAL }));
+ expect(rewriting()).toBe(false);
+ expect(buttons().some((button) => button.disabled)).toBe(false);
+ press("c");
+ expect(fixture.api).toHaveBeenCalledWith(...picked(PERSONAL[2]!));
+ });
+
+ it("takes picks again 8 s after it first saw a rewrite, never swaps answers in after that, and ignores one older than 20 s", () => {
+ const stamp = Date.now();
+ show(greeting());
+ show(greeting({ setupChoicesUpdating: stamp }));
+ act(() => void vi.advanceTimersByTime(7_999));
+ expect(rewriting()).toBe(true);
+ act(() => void vi.advanceTimersByTime(1));
+ expect(rewriting()).toBe(false);
+ show(greeting({ setupChoices: PERSONAL }));
+ expect(labels()).toEqual([...FIXED, "Something else"]);
+ show(greeting({ setupChoicesUpdating: Date.now() }));
+ expect(rewriting(), "a later rename waits again").toBe(true);
+ act(() => root!.unmount());
+ root = createRoot(container);
+ show(greeting({ setupChoicesUpdating: Date.now() - 20_000 }));
+ expect(rewriting()).toBe(false);
+ press("a");
+ expect(fixture.api).toHaveBeenCalledWith(...picked(FIXED[0]!));
+ });
+
+ it("never shows a rewrite on a settled card", () => {
+ const message = greeting({ setupChoicesUpdating: Date.now() });
+ show(message, [message, { id: "u1", role: "user", kind: "text", at: Date.now(), text: "help me hire" } as Message]);
+ expect(rewriting()).toBe(false);
+ expect(card()!.getAttribute("aria-busy")).toBeNull();
+ expect(buttons().every((button) => button.disabled)).toBe(true);
+ });
+});
diff --git a/src/state/store.tsx b/src/state/store.tsx
index 5689806293..28aa9483b6 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -136,7 +136,7 @@ export interface SecretRequestCardData {
export type ComputerControlState = { held: boolean; helpReason: string | null; help?: import("../../shared/wire").ComputerHelpRef | null };
-export interface Message extends Pick<import("../../shared/wire").WireMessage, "widget" | "app" | "fromApp" | "pointed" | "routedBy" | "quickModel" | "automation" | "publishedPage" | "sender" | "setupSuggestion" | "helperIntro" | "helperFollowup" | "setupOffer" | "setupChoices" | "setupChoicesPending" | "setupRequest" | "relay" | "inbox" | "sentDirectly" | "doneWhen"> {
+export interface Message extends Pick<import("../../shared/wire").WireMessage, "widget" | "app" | "fromApp" | "pointed" | "routedBy" | "quickModel" | "automation" | "publishedPage" | "sender" | "setupSuggestion" | "helperIntro" | "helperFollowup" | "setupOffer" | "setupChoices" | "setupChoicesPending" | "setupChoicesUpdating" | "setupRequest" | "relay" | "inbox" | "sentDirectly" | "doneWhen"> {
id: string;
role: "bot" | "user";
kind: "text" | "options" | "activity" | "screen" | "connector" | "secret" | "signin" | "routine.run" | "goal.run" | "digest" | "compaction" | "call" | "widget" | "app";