Skip to content

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

47.2 KB
Raw Blame
// @vitest-environment happy-dom
import { createElement } from "react";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import { saveWebhookCredential } from "@/lib/webhook-credentials";
import type { Bot } from "@/state/store";

const fixture = vi.hoisted(() => ({
  state: {} as Record<string, unknown>,
  dispatch: vi.fn(),
  api: vi.fn(async (..._args: unknown[]) => ({}) as unknown),
}));
vi.mock("@/state/store", async (importOriginal) => ({
  ...await importOriginal<typeof import("@/state/store")>(),
  useStore: () => ({ state: fixture.state, dispatch: fixture.dispatch }),
  api: (...args: unknown[]) => fixture.api(...args),
}));
vi.mock("@/lib/thread-preferences", () => ({ useShowThreads: () => false }));
const copied = vi.hoisted(() => ({ texts: [] as string[] }));
const credentials = vi.hoisted(() => {
  const items = new Map<string, string>();
  return { items, store: { getItem: (key: string) => items.get(key) ?? null, setItem: (key: string, value: string) => { items.set(key, value); }, removeItem: (key: string) => { items.delete(key); } } };
});
vi.mock("@/lib/webhook-credentials", async (importOriginal) => ({
  ...await importOriginal<typeof import("@/lib/webhook-credentials")>(),
  webhookCredentialStore: () => credentials.store,
}));
vi.mock("@/lib/copy-text", async (importOriginal) => ({
  ...await importOriginal<typeof import("@/lib/copy-text")>(),
  copyText: async (text: string) => { copied.texts.push(text); return "copied"; },
}));

const { NewAutomation, defaultBot } = await import("./NewAutomation");
const { AutomationPanel } = await import("./AutomationPanel");
const { TriggersPage } = await import("../TriggersPage");
const { AutomationsCalendar } = await import("./AutomationsCalendar");
const { automationsFrom } = await import("@/lib/automations");

const now = Date.now();
const botA = { id: "bot-a", name: "Scout", threadId: "thread-a", hidden: false, messages: [{ id: "m1", at: now - 5_000 }] } as unknown as Bot;
const botB = { id: "bot-b", name: "Ledger", threadId: "thread-b", hidden: false, messages: [{ id: "m2", at: now - 50_000 }] } as unknown as Bot;
const webhook = { id: "hook-1", endpointId: "wh_abc", name: "Sales form leads", prompt: "Draft a follow-up for the lead.", botId: "bot-a", runOn: "maus", enabled: true, createdAt: now, updatedAt: now, deliveryCount: 1 };

let root: Root | null = null;
function mount(element: ReturnType<typeof createElement>) {
  const container = document.createElement("div");
  document.body.append(container);
  root = createRoot(container);
  flushSync(() => root!.render(element));
  return container;
}
const button = (container: HTMLElement, label: string) => {
  const found = [...container.querySelectorAll("button")].find((candidate) => candidate.textContent?.trim() === label);
  if (!found) throw new Error(`no ${label} button in ${container.innerHTML}`);
  return found;
};
beforeEach(() => {
  fixture.dispatch.mockReset();
  fixture.api.mockReset();
  fixture.api.mockResolvedValue({});
  fixture.state = { hydrated: true, bots: [botA, botB], selectedId: "", routines: [], webhooks: [webhook], routineRuns: [], webhookAttempts: [], routinesLoadState: "ready", webhookIngress: { available: true, baseUrl: "http://127.0.0.1:8800" } };
});
afterEach(() => { root?.unmount(); root = null; document.body.innerHTML = ""; });

describe("+ New", () => {
  it("talks to the bot open now, else the one most recently talked to", () => {
    expect(defaultBot([botA, botB], "bot-b")?.id).toBe("bot-b");
    expect(defaultBot([botB, botA], "")?.id).toBe("bot-a");
  });

  it("sends what should happen to that bot as a normal chat message and opens the conversation", () => {
    const onClose = vi.fn();
    const container = mount(createElement(NewAutomation, { initialText: "every morning at 9, send me a summary of my inbox", onClose, onSetUpYourself: vi.fn() }));
    expect(container.querySelector("textarea")!.getAttribute("placeholder")).toBe("e.g. every morning at 9, send me a summary of my inbox");
    expect(container.querySelector('select[aria-label="Who should do it?"]')).not.toBeNull();
    flushSync(() => button(container, "Set it up").click());
    expect(fixture.dispatch).toHaveBeenNthCalledWith(1, { type: "select", id: "bot-a" });
    expect(fixture.dispatch).toHaveBeenNthCalledWith(2, { type: "send", botId: "bot-a", text: "every morning at 9, send me a summary of my inbox", threadId: "thread-a" });
    expect(onClose).toHaveBeenCalled();
  });

  it("asks no bot question with one bot, and does nothing until something is written", () => {
    fixture.state.bots = [botA];
    const container = mount(createElement(NewAutomation, { onClose: vi.fn(), onSetUpYourself: vi.fn() }));
    expect(container.querySelector("select")).toBeNull();
    expect(button(container, "Set it up").hasAttribute("disabled")).toBe(true);
  });

  it("lets a person set it up themselves: a schedule, or when another app sends something", () => {
    const onSetUpYourself = vi.fn();
    const container = mount(createElement(NewAutomation, { onClose: vi.fn(), onSetUpYourself }));
    flushSync(() => button(container, "Set it up yourself").click());
    flushSync(() => button(container, "When another app sends something").click());
    flushSync(() => button(container, "Continue").click());
    expect(onSetUpYourself).toHaveBeenCalledWith("webhook", "bot-a");
  });
});

describe("the automation panel", () => {
  it("explains an unread failure older than the recent runs and keeps it visible after marking it seen", () => {
    const runs = Array.from({ length: 6 }, (_, index) => ({ id: `success-${index}`, routineId: webhook.id, botId: botA.id, status: "completed", createdAt: now - index * 1_000, scheduledFor: now - index * 1_000, output: "Nothing new." }));
    const failure = { id: "old-failure", routineId: webhook.id, botId: botA.id, status: "failed", createdAt: now - 60_000, scheduledFor: now - 60_000, error: "Provider disconnected." };
    const [automation] = automationsFrom({ routines: [], webhooks: [webhook] as never, runs: [...runs, failure] as never });
    const props = { automation: automation!, sentence: "s", onClose: vi.fn(), onEdit: vi.fn(), onDeleted: vi.fn() };
    const container = mount(createElement(AutomationPanel, props));
    expect(container.textContent).toContain("Provider disconnected.");
    expect(container.querySelectorAll("section ul li")).toHaveLength(6);
    expect(fixture.dispatch).toHaveBeenCalledExactlyOnceWith({ type: "markRoutineRunSeen", runId: failure.id });
    const seen = { ...automation!, runs: automation!.runs.map((run) => ({ ...run, seenAt: now })) };
    flushSync(() => root!.render(createElement(AutomationPanel, { ...props, automation: seen })));
    expect(container.textContent).toContain("Provider disconnected.");
    expect(fixture.dispatch).toHaveBeenCalledTimes(1);
  });

  it("shows the sentence, the status, an address to paste with Copy address, the recent runs and the four actions, in plain words", () => {
    fixture.state.routineRuns = [{ id: "run-1", routineId: "hook-1", botId: "bot-a", status: "completed", scheduledFor: now - 60_000, startedAt: now - 60_000, createdAt: now - 60_000, output: "Drafted a follow-up for Ada.", threadId: "exec-1" }];
    const [automation] = automationsFrom({ routines: [], webhooks: [webhook] as never, runs: fixture.state.routineRuns as never });
    const container = mount(createElement(AutomationPanel, { automation: automation!, sentence: "When your sales form sends something, Scout drafts a follow-up for the lead", onClose: vi.fn(), onEdit: vi.fn(), onDeleted: vi.fn() }));
    const text = container.textContent ?? "";
    expect(container.querySelector("h2")!.textContent).toBe("Sales form leads");
    expect(container.querySelector("h2 + p")!.textContent).toBe("When your sales form sends something, Scout drafts a follow-up for the lead");
    expect(container.querySelector("[data-automation-status]")!.textContent).toContain("On");
    expect(text).not.toContain("Working");
    expect(text).toContain("Paste this address into the other app");
    expect(text).toContain("Recent runs");
    expect(text).toMatch(/Today [^✓]*✓Drafted a follow-up for Ada\./);
    for (const label of ["Copy address", "Run now", "Pause", "Edit", "Delete"]) expect(button(container, label)).toBeTruthy();
    expect(container.querySelector("details summary")!.textContent).toBe("More");
    expect(container.querySelector("details")!.textContent).toContain("Show secret / settings");
    const visible = text.replace(container.querySelector("details")!.textContent ?? "", "");
    expect(visible).not.toMatch(/webhook|endpoint|payload|fired|trigger/i);
  });

  it("runs now through the test route, and pauses through its own API", async () => {
    const [automation] = automationsFrom({ routines: [], webhooks: [webhook] as never, runs: [] });
    const container = mount(createElement(AutomationPanel, { automation: automation!, sentence: "s", onClose: vi.fn(), onEdit: vi.fn(), onDeleted: vi.fn() }));
    flushSync(() => button(container, "Run now").click());
    await vi.waitFor(() => expect(fixture.api).toHaveBeenCalledWith("/api/webhooks/hook-1/test", expect.objectContaining({ method: "POST" })));
    expect(container.textContent).toContain("It hasn't run yet.");
  });
});

describe("a routine's panel", () => {
  it("is titled with the routine's name, says when it runs and who runs it, and shows its whole instructions", () => {
    const prompt = "Every weekday at 9 AM, search for the latest AI news from the last 24 hours (new models, funding, research) and send a 5-bullet brief, each with a source link.";
    const routine = { id: "routine-1", name: "Daily AI News Brief", prompt, botId: "bot-a", runOn: "maus", enabled: true, createdAt: now, updatedAt: now,
      schedule: { type: "daily", time: "09:00", weekdays: [1, 2, 3, 4, 5] }, nextRunAt: now + 86_400_000, durationMinutes: 30 };
    const [automation] = automationsFrom({ routines: [routine] as never, webhooks: [], runs: [] });
    const container = mount(createElement(AutomationPanel, { automation: automation!, sentence: "Every weekday at 9 AM, Scout searches for the latest AI news from the last 24 hours (new…", onClose: vi.fn(), onEdit: vi.fn(), onDeleted: vi.fn() }));
    expect(container.querySelector("h2")!.textContent).toBe("Daily AI News Brief");
    expect(container.querySelector("h2 + p")!.textContent).toBe("Every weekday at 9 AM · Scout");
    expect(container.querySelector("[data-testid=automation-instructions]")!.textContent).toBe(prompt);
    expect(container.textContent).not.toContain("(new…");
    expect(container.querySelector("[data-automation-status]")!.textContent).toBe("On");
  });

  it("falls back to its sentence when it has no name", () => {
    const [automation] = automationsFrom({ routines: [], webhooks: [{ ...webhook, name: " " }] as never, runs: [] });
    const container = mount(createElement(AutomationPanel, { automation: automation!, sentence: "When another app sends something, Scout drafts a follow-up", onClose: vi.fn(), onEdit: vi.fn(), onDeleted: vi.fn() }));
    expect(container.querySelector("h2")!.textContent).toBe("When another app sends something, Scout drafts a follow-up");
    expect(container.querySelector("h2 + p")).toBeNull();
    expect(container.querySelector("[data-testid=automation-instructions]")).toBeNull();
  });
});

describe("Copy address", () => {
  const kept = { endpointUrl: "http://127.0.0.1:8800/hooks/wh_abc", url: "http://127.0.0.1:8800/hooks/wh_abc/whsec_kept-fixture", secret: "whsec_kept-fixture" };
  const fresh = { endpointUrl: kept.endpointUrl, url: "http://127.0.0.1:8800/hooks/wh_abc/whsec_new-fixture", secret: "whsec_new-fixture" };
  const panel = () => {
    const [automation] = automationsFrom({ routines: [], webhooks: [webhook] as never, runs: [] });
    return mount(createElement(AutomationPanel, { automation: automation!, sentence: "s", onClose: vi.fn(), onEdit: vi.fn(), onDeleted: vi.fn() }));
  };
  beforeEach(() => { copied.texts = []; credentials.items.clear(); });

  it("copies the address the server keeps, which the bot that owns it may already have given an app, and never replaces it", async () => {
    fixture.api.mockImplementation(async (path: unknown) => path === "/api/webhooks/hook-1/address" ? { credential: kept } : { webhook, credential: fresh });
    const container = panel();
    flushSync(() => button(container, "Copy address").click());
    await vi.waitFor(() => expect(copied.texts).toEqual([kept.url]));
    expect(fixture.api.mock.calls.map(([path]) => path)).not.toContain("/api/webhooks/hook-1/rotate");
    expect(credentials.items.get("omb-webhook-credentials")).toContain(kept.url);
  });

  it("makes a new one only for an address from before addresses were kept that nothing here holds", async () => {
    fixture.api.mockImplementation(async (path: unknown) => {
      if (path === "/api/webhooks/hook-1/address") throw Object.assign(new Error("this address was made before addresses were kept"), { status: 404 });
      return { webhook, credential: fresh };
    });
    const container = panel();
    flushSync(() => button(container, "Copy address").click());
    await vi.waitFor(() => expect(copied.texts).toEqual([fresh.url]));
    expect(fixture.api).toHaveBeenCalledWith("/api/webhooks/hook-1/rotate", expect.objectContaining({ method: "POST" }));
  });
});

describe("the Automations list switch", () => {
  const routine = { id: "routine-1", name: "Morning summary", prompt: "Send me a summary of my inbox.", target: "bot", botId: "bot-a", runOn: "maus", enabled: true,
    schedule: { type: "daily", time: "09:00", weekdays: [0, 1, 2, 3, 4, 5, 6] }, durationMinutes: 30, nextRunAt: now + 3_600_000, createdAt: now, updatedAt: now };
  let container: HTMLElement;
  /** The page, re-rendered from the store each time it changes, as the app's provider would. */
  function mountPage() {
    container = mount(createElement(TriggersPage, { onBack: vi.fn(), onOpenRoom: vi.fn() }));
    fixture.dispatch.mockImplementation((action: { type: string; routine?: { id: string }; webhook?: { id: string } }) => {
      if (action.type === "routinePatched") fixture.state.routines = (fixture.state.routines as Array<{ id: string }>).map((item) => item.id === action.routine!.id ? action.routine : item);
      if (action.type === "webhookPatched") fixture.state.webhooks = (fixture.state.webhooks as Array<{ id: string }>).map((item) => item.id === action.webhook!.id ? action.webhook : item);
      flushSync(() => root!.render(createElement(TriggersPage, { onBack: vi.fn(), onOpenRoom: vi.fn() })));
    });
  }
  const toggle = (name: string) => container.querySelector<HTMLButtonElement>(`[role=switch][aria-label="Turn “${name}” on or off"]`)!;
  const row = (id: string) => container.querySelector<HTMLElement>(`[data-automation="${id}"]`)!;

  beforeEach(() => { fixture.state.routines = [routine]; });

  it.each([
    ["a schedule", "Morning summary", "routine-1", "/api/routines/routine-1", (enabled: boolean) => ({ enabled }), (enabled: boolean) => ({ routine: { ...routine, enabled, nextRunAt: enabled ? now + 3_600_000 : null, updatedAt: now + (enabled ? 2 : 1) } })],
    ["another app's", "Sales form leads", "hook-1", "/api/webhooks/hook-1", (enabled: boolean) => ({ enabled, verificationPending: false }), (enabled: boolean) => ({ webhook: { ...webhook, enabled } })],
  ])("turns %s automation off and back on, showing each answer at once", async (_kind, name, id, path, body, answer) => {
    mountPage();
    // Only the switch's writes answer; the page's own reads (its app events) get an empty answer.
    fixture.api.mockImplementation(async (_path: unknown, init: unknown) => (init as { body?: string } | undefined)?.body ? answer(JSON.parse((init as { body: string }).body).enabled) : {});
    expect(toggle(name).getAttribute("aria-checked")).toBe("true");
    flushSync(() => toggle(name).click());
    await vi.waitFor(() => expect(toggle(name).getAttribute("aria-checked")).toBe("false"));
    expect(row(id).dataset.automationStatus).toBe("paused");
    expect(row(id).textContent).toContain("Paused");
    await vi.waitFor(() => expect(toggle(name).disabled).toBe(false));
    flushSync(() => toggle(name).click());
    await vi.waitFor(() => expect(toggle(name).getAttribute("aria-checked")).toBe("true"));
    expect(row(id).dataset.automationStatus).toBe("working");
    const writes = fixture.api.mock.calls.filter(([, init]) => (init as { body?: string } | undefined)?.body);
    expect(writes.map(([calledPath, init]) => [calledPath, JSON.parse((init as { body: string }).body)])).toEqual([[path, body(false)], [path, body(true)]]);
  });

  it("says why beside the automation when turning it back on is refused, and keeps it off", async () => {
    fixture.state.routines = [{ ...routine, enabled: false, nextRunAt: null }];
    mountPage();
    fixture.api.mockRejectedValue(new Error("The assigned bot no longer exists"));
    flushSync(() => toggle("Morning summary").click());
    await vi.waitFor(() => expect(row("routine-1").querySelector("[role=alert]")?.textContent).toBe("The assigned bot no longer exists"));
    expect(toggle("Morning summary").getAttribute("aria-checked")).toBe("false");
  });

  it("labels each automation by its name, with what it does beneath, and by what it does when it has no name", () => {
    fixture.state.routines = [routine, { ...routine, id: "unnamed", name: " " }];
    mountPage();
    expect(row("routine-1").querySelector("button")!.textContent).toBe("Morning summary");
    expect(row("routine-1").textContent).toContain("sends you a summary of your inbox");
    expect(row("unnamed").querySelector("button")!.textContent).toContain("sends you a summary of your inbox");
  });

  it("explains an old unread failure on its automation and acknowledges it only when the panel opens", () => {
    fixture.state.routines = [routine];
    fixture.state.routineRuns = [
      ...Array.from({ length: 6 }, (_, index) => ({ id: `success-${index}`, routineId: routine.id, botId: botA.id, status: "completed", createdAt: now - index * 1_000, scheduledFor: now - index * 1_000 })),
      { id: "old-failure", routineId: routine.id, botId: botA.id, status: "failed", createdAt: now - 60_000, scheduledFor: now - 60_000, error: "Provider disconnected." },
    ];
    mountPage();
    expect(row(routine.id).textContent).toContain("Provider disconnected.");
    expect(fixture.dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: "markRoutineRunSeen" }));
    flushSync(() => row(routine.id).querySelector("button")!.click());
    expect(container.querySelector('aside[aria-label="Automation"]')!.textContent).toContain("Provider disconnected.");
    expect(fixture.dispatch).toHaveBeenCalledWith({ type: "markRoutineRunSeen", runId: "old-failure" });
  });

  it("offers no switch for a one-time automation that already happened, and lists no automation whose bot is gone", () => {
    fixture.state.routines = [{ ...routine, enabled: false, nextRunAt: null, schedule: { type: "once", at: now - 60_000 } }, { ...routine, id: "orphan", name: "Orphan", botId: "deleted-bot" }];
    fixture.state.webhooks = [webhook, { ...webhook, id: "orphan-hook", name: "Orphan hook", botId: "deleted-bot" }];
    mountPage();
    expect(row("routine-1").dataset.automationStatus).toBe("done");
    expect(row("routine-1").querySelector("[role=switch]")).toBeNull();
    expect(container.querySelector('[data-automation="orphan"]')).toBeNull();
    expect(container.querySelector('[data-automation="orphan-hook"]')).toBeNull();
  });

  describe("Pause all / Resume all", () => {
    const setAll = () => container.querySelector<HTMLButtonElement>("[data-automations-set-all]");
    const undo = () => [...document.querySelectorAll<HTMLButtonElement>("[role=status] button")].find((candidate) => candidate.textContent === "Undo");
    const writes = () => fixture.api.mock.calls.filter(([, init]) => (init as { body?: string } | undefined)?.body)
      .map(([calledPath, init]) => [calledPath, JSON.parse((init as { body: string }).body).enabled] as [string, boolean]);
    const sorted = (list: Array<[string, boolean]>) => [...list].sort(([left], [right]) => left.localeCompare(right));
    /** Each write answers with the automation as now saved, as the server does. */
    function answerWrites() {
      fixture.api.mockImplementation(async (path: unknown, init: unknown) => {
        const body = (init as { body?: string } | undefined)?.body;
        if (!body) return {};
        const { enabled } = JSON.parse(body) as { enabled: boolean };
        const id = String(path).split("/").pop();
        if (String(path).startsWith("/api/routines/")) return { routine: { ...(fixture.state.routines as Array<{ id: string }>).find((item) => item.id === id), enabled } };
        return { webhook: { ...(fixture.state.webhooks as Array<{ id: string }>).find((item) => item.id === id), enabled } };
      });
    }
    const evening = { ...routine, id: "routine-2", name: "Evening digest" };
    const statuses = () => Object.fromEntries([...container.querySelectorAll<HTMLElement>("[data-automation]")].map((item) => [item.dataset.automation, item.dataset.automationStatus]));
    afterEach(() => { sessionStorage.clear(); vi.unstubAllGlobals(); });

    it("pauses every automation listed without asking, offers Undo, and Undo turns them back on", async () => {
      fixture.state.routines = [routine, evening];
      const confirm = vi.fn(() => true);
      vi.stubGlobal("confirm", confirm);
      mountPage();
      answerWrites();
      expect(setAll()!.textContent).toBe("Pause all");
      expect(setAll()!.className).toBe("ui-button ui-button-sm");
      flushSync(() => setAll()!.click());
      await vi.waitFor(() => expect(setAll()!.textContent).toBe("Resume all"));
      expect(confirm).not.toHaveBeenCalled();
      expect(sorted(writes())).toEqual([["/api/routines/routine-1", false], ["/api/routines/routine-2", false], ["/api/webhooks/hook-1", false]]);
      expect(statuses()).toEqual({ "routine-1": "paused", "routine-2": "paused", "hook-1": "paused" });
      await vi.waitFor(() => expect(document.querySelector("[role=status]")?.textContent).toContain("Paused 3 automations."));
      flushSync(() => undo()!.click());
      await vi.waitFor(() => expect(setAll()!.textContent).toBe("Pause all"));
      expect(sorted(writes().slice(3))).toEqual([["/api/routines/routine-1", true], ["/api/routines/routine-2", true], ["/api/webhooks/hook-1", true]]);
      expect(statuses()).toEqual({ "routine-1": "working", "routine-2": "working", "hook-1": "working" });
    });

    it("resumes only what it paused: one already paused stays off", async () => {
      fixture.state.routines = [routine, { ...evening, enabled: false, nextRunAt: null }];
      mountPage();
      answerWrites();
      flushSync(() => setAll()!.click());
      await vi.waitFor(() => expect(setAll()!.textContent).toBe("Resume all"));
      expect(sorted(writes())).toEqual([["/api/routines/routine-1", false], ["/api/webhooks/hook-1", false]]);
      await vi.waitFor(() => expect(setAll()!.disabled).toBe(false));
      flushSync(() => setAll()!.click());
      await vi.waitFor(() => expect(setAll()!.textContent).toBe("Pause all"));
      expect(sorted(writes().slice(2))).toEqual([["/api/routines/routine-1", true], ["/api/webhooks/hook-1", true]]);
      expect(statuses()["routine-2"]).toBe("paused");
    });

    it("leaves one the person switched by hand in between, and skips one deleted since", async () => {
      fixture.state.routines = [routine, evening, { ...routine, id: "routine-3", name: "Weekly report" }];
      mountPage();
      answerWrites();
      flushSync(() => setAll()!.click());
      await vi.waitFor(() => expect(setAll()!.textContent).toBe("Resume all"));
      await vi.waitFor(() => expect(setAll()!.disabled).toBe(false));
      flushSync(() => toggle("Morning summary").click());
      await vi.waitFor(() => expect(row("routine-1").dataset.automationStatus).toBe("working"));
      await vi.waitFor(() => expect(toggle("Morning summary").disabled).toBe(false));
      flushSync(() => toggle("Morning summary").click());
      await vi.waitFor(() => expect(row("routine-1").dataset.automationStatus).toBe("paused"));
      fixture.state.webhooks = [];
      flushSync(() => root!.render(createElement(TriggersPage, { onBack: vi.fn(), onOpenRoom: vi.fn() })));
      const before = writes().length;
      await vi.waitFor(() => expect(setAll()!.disabled).toBe(false));
      expect(setAll()!.textContent).toBe("Resume all");
      flushSync(() => setAll()!.click());
      await vi.waitFor(() => expect(setAll()!.textContent).toBe("Pause all"));
      expect(sorted(writes().slice(before))).toEqual([["/api/routines/routine-2", true], ["/api/routines/routine-3", true]]);
      expect(statuses()["routine-1"]).toBe("paused");
    });

    it("keeps Resume all after leaving the page and coming back, and never resumes what it did not pause once that is gone", async () => {
      fixture.state.routines = [routine, evening];
      mountPage();
      answerWrites();
      flushSync(() => setAll()!.click());
      await vi.waitFor(() => expect(setAll()!.textContent).toBe("Resume all"));
      root!.unmount();
      mountPage();
      answerWrites();
      expect(setAll()!.textContent).toBe("Resume all");
      root!.unmount();
      sessionStorage.clear();
      mountPage();
      expect(setAll()).toBeNull();
    });

    it("keeps one set per list shown: a department's Pause all is not resumed from another", async () => {
      fixture.state.bots = [{ ...botA, section: "Social" }, { ...botB, section: "Dev" }] as unknown as Bot[];
      fixture.state.sections = ["Dev", "Social"];
      fixture.state.webhooks = [];
      fixture.state.routines = [routine, evening, { ...routine, id: "dev-1", name: "Dev check", botId: "bot-b" }, { ...routine, id: "dev-2", name: "Dev deploy", botId: "bot-b" }];
      mountPage();
      answerWrites();
      const department = container.querySelector<HTMLSelectElement>('select[aria-label="All departments"]')!;
      const pick = (value: string) => { department.value = value; department.dispatchEvent(new Event("change", { bubbles: true })); };
      flushSync(() => pick("Dev"));
      flushSync(() => setAll()!.click());
      await vi.waitFor(() => expect(setAll()!.textContent).toBe("Resume all"));
      expect(sorted(writes())).toEqual([["/api/routines/dev-1", false], ["/api/routines/dev-2", false]]);
      flushSync(() => pick("Social"));
      expect(setAll()!.textContent).toBe("Pause all");
      flushSync(() => pick("all"));
      expect(setAll()!.textContent).toBe("Pause all");
      flushSync(() => pick("Dev"));
      expect(setAll()!.textContent).toBe("Resume all");
    });

    it("says a refusal below the list and keeps in the set only what it did turn off", async () => {
      fixture.state.routines = [routine, evening];
      mountPage();
      let written = 0;
      fixture.api.mockImplementation(async (path: unknown, init: unknown) => {
        const body = (init as { body?: string } | undefined)?.body;
        if (!body) return {};
        if (++written === 2) throw new Error("The server is restarting");
        const id = String(path).split("/").pop();
        if (String(path).startsWith("/api/routines/")) return { routine: { ...(fixture.state.routines as Array<{ id: string }>).find((item) => item.id === id), enabled: false } };
        return { webhook: { ...webhook, enabled: false } };
      });
      flushSync(() => setAll()!.click());
      await vi.waitFor(() => expect(container.querySelector("[role=alert]")?.textContent).toBe("The server is restarting"));
      const pausedIds = Object.entries(statuses()).filter(([, status]) => status === "paused").map(([id]) => id);
      expect(pausedIds).toHaveLength(1);
      expect(setAll()!.textContent).toBe("Resume all");
      await vi.waitFor(() => expect(document.querySelector("[role=status]")?.textContent).toContain("Paused 1 automation."));
      answerWrites();
      await vi.waitFor(() => expect(setAll()!.disabled).toBe(false));
      const before = writes().length;
      flushSync(() => setAll()!.click());
      await vi.waitFor(() => expect(setAll()!.textContent).toBe("Pause all"));
      expect(writes().slice(before).map(([calledPath]) => calledPath.split("/").pop())).toEqual(pausedIds);
    });

    it("keeps every switch waiting while it writes, so a click cannot be undone by it", async () => {
      fixture.state.routines = [routine, evening];
      mountPage();
      let release = () => {};
      fixture.api.mockImplementation(async (path: unknown, init: unknown) => {
        const body = (init as { body?: string } | undefined)?.body;
        if (!body) return {};
        await new Promise<void>((resolve) => { release = resolve; });
        const id = String(path).split("/").pop();
        return String(path).startsWith("/api/routines/")
          ? { routine: { ...(fixture.state.routines as Array<{ id: string }>).find((item) => item.id === id), enabled: false } }
          : { webhook: { ...webhook, enabled: false } };
      });
      flushSync(() => setAll()!.click());
      await vi.waitFor(() => expect(writes()).toHaveLength(1));
      expect(toggle("Morning summary").disabled).toBe(true);
      expect(toggle("Sales form leads").disabled).toBe(true);
      expect(setAll()!.disabled).toBe(true);
      flushSync(() => toggle("Morning summary").click());
      expect(writes()).toHaveLength(1);
      for (let count = 1; count <= 3; count++) {
        await vi.waitFor(() => expect(writes()).toHaveLength(count));
        release();
      }
      await vi.waitFor(() => expect(toggle("Morning summary").disabled).toBe(false));
      expect(writes().map(([, enabled]) => enabled)).toEqual([false, false, false]);
    });

    it("offers nothing when fewer than two automations have a switch, or in the calendar", () => {
      fixture.state.routines = [{ ...routine, enabled: false, nextRunAt: null, schedule: { type: "once", at: now - 60_000 } }];
      mountPage();
      expect(setAll()).toBeNull();
      root!.unmount();
      fixture.state.routines = [routine, evening];
      fixture.state.routinesFocus = { view: "calendar", nonce: 1 };
      mountPage();
      expect(setAll()).toBeNull();
    });
  });

  describe("by department", () => {
    const sectioned = [{ ...botA, section: "Social" }, { ...botB, section: "Dev" }, { ...botB, id: "bot-c", name: "Atlas", threadId: "thread-c" }] as unknown as Bot[];
    const department = () => container.querySelector<HTMLSelectElement>('select[aria-label="All departments"]');
    const pick = (value: string) => { department()!.value = value; department()!.dispatchEvent(new Event("change", { bubbles: true })); };

    it("offers no department question when no bot sits in a department", () => {
      fixture.state.routines = [routine];
      mountPage();
      expect(department()).toBeNull();
    });

    it("lists only the chosen department's automations, and the General ones for bots outside any", () => {
      fixture.state.bots = sectioned;
      fixture.state.sections = ["Dev", "Social"];
      fixture.state.routines = [routine, { ...routine, id: "dev-routine", name: "Dev check", botId: "bot-b" }, { ...routine, id: "general-routine", name: "General check", botId: "bot-c" }];
      fixture.state.webhooks = [];
      mountPage();
      expect([...department()!.options].map((option) => option.textContent)).toEqual(["All departments", "Dev", "Social", "General"]);
      expect(["routine-1", "dev-routine", "general-routine"].every((id) => row(id))).toBe(true);
      flushSync(() => pick("Dev"));
      expect(row("dev-routine")).not.toBeNull();
      expect(container.querySelector('[data-automation="routine-1"]')).toBeNull();
      expect(container.querySelector('[data-automation="general-routine"]')).toBeNull();
      flushSync(() => pick([...department()!.options].find((option) => option.textContent === "General")!.value));
      expect(row("general-routine")).not.toBeNull();
      expect(container.querySelector('[data-automation="dev-routine"]')).toBeNull();
    });

    it("falls back to everyone when the chosen department no longer holds a bot", () => {
      fixture.state.bots = sectioned;
      fixture.state.sections = ["Dev", "Social"];
      fixture.state.routines = [routine, { ...routine, id: "dev-routine", name: "Dev check", botId: "bot-b" }, { ...routine, id: "general-routine", name: "General check", botId: "bot-c" }];
      fixture.state.webhooks = [];
      mountPage();
      const rerender = () => flushSync(() => root!.render(createElement(TriggersPage, { onBack: vi.fn(), onOpenRoom: vi.fn() })));
      flushSync(() => pick("Dev"));
      expect(container.querySelector('[data-automation="routine-1"]')).toBeNull();
      fixture.state.bots = sectioned.map((bot) => bot.id === "bot-b" ? { ...bot, section: "Social" } : bot);
      rerender();
      expect(department()!.value).toBe("all");
      expect([...department()!.options].map((option) => option.textContent)).toEqual(["All departments", "Social", "General"]);
      expect(["routine-1", "dev-routine", "general-routine"].every((id) => row(id))).toBe(true);
      flushSync(() => pick([...department()!.options].find((option) => option.textContent === "General")!.value));
      fixture.state.bots = sectioned.map((bot) => ({ ...bot, section: "Social" }));
      rerender();
      // One department left and no General: nothing to choose between, so the filter hides.
      expect(department()).toBeNull();
      expect(row("general-routine")).not.toBeNull();
    });

    it("narrows the bot question to that department's bots and clears a bot picked before", () => {
      fixture.state.bots = sectioned;
      fixture.state.sections = ["Dev", "Social"];
      fixture.state.webhooks = [];
      fixture.state.routines = Array.from({ length: 9 }, (_, index) => ({ ...routine, id: `r-${index}`, name: `Check ${index}`, botId: index < 5 ? "bot-a" : "bot-b" }));
      mountPage();
      const bots = () => container.querySelector<HTMLSelectElement>('select[aria-label="All bots"]')!;
      const change = (select: HTMLSelectElement, value: string) => { select.value = value; select.dispatchEvent(new Event("change", { bubbles: true })); };
      expect([...bots().options].map((option) => option.textContent)).toEqual(["All bots", "Scout", "Ledger", "Atlas"]);
      flushSync(() => change(bots(), "bot-a"));
      expect(container.querySelectorAll("[data-automation]")).toHaveLength(5);
      flushSync(() => pick("Dev"));
      expect(bots().value).toBe("all");
      expect([...bots().options].map((option) => option.textContent)).toEqual(["All bots", "Ledger"]);
      expect(container.querySelectorAll("[data-automation]")).toHaveLength(4);
    });

    it("clears a bot picked in a department that then disappears, so nothing stays filtered under All departments", async () => {
      fixture.state.bots = sectioned;
      fixture.state.sections = ["Dev", "Social"];
      fixture.state.webhooks = [];
      fixture.state.routines = Array.from({ length: 9 }, (_, index) => ({ ...routine, id: `r-${index}`, name: `Check ${index}`, botId: index < 5 ? "bot-a" : "bot-b" }));
      mountPage();
      const bots = () => container.querySelector<HTMLSelectElement>('select[aria-label="All bots"]')!;
      flushSync(() => pick("Dev"));
      flushSync(() => { bots().value = "bot-b"; bots().dispatchEvent(new Event("change", { bubbles: true })); });
      expect(container.querySelectorAll("[data-automation]")).toHaveLength(4);
      fixture.state.bots = sectioned.map((bot) => bot.id === "bot-b" ? { ...bot, section: "Social" } : bot);
      flushSync(() => root!.render(createElement(TriggersPage, { onBack: vi.fn(), onOpenRoom: vi.fn() })));
      await vi.waitFor(() => expect(container.querySelectorAll("[data-automation]")).toHaveLength(9));
      expect(department()!.value).toBe("all");
      expect(bots().value).toBe("all");
    });
  });
});

describe("More, for another app's automation", () => {
  it("lists recent calls with ✓ or ✗ and a plain reason, shows a call's payload on click, and the last thing it received", () => {
    fixture.state.webhookAttempts = [
      { id: "a1", webhookId: "hook-1", receivedAt: now - 120_000, outcome: "accepted", statusCode: 202, preview: '{ "lead": "Ada", "email": "[email protected]" }', runId: "run-1" },
      { id: "a2", webhookId: "hook-1", receivedAt: now - 60_000, outcome: "rejected", statusCode: 401, reason: "Invalid webhook URL or secret" },
    ];
    const [automation] = automationsFrom({ routines: [], webhooks: [webhook] as never, runs: [] });
    const container = mount(createElement(AutomationPanel, { automation: automation!, sentence: "s", onClose: vi.fn(), onEdit: vi.fn(), onDeleted: vi.fn() }));
    const more = container.querySelector("details")!;
    expect(more.textContent).toContain("Last thing it received");
    expect(more.querySelector("pre")!.textContent).toBe('{ "lead": "Ada", "email": "[email protected]" }');
    const calls = [...more.querySelectorAll("[data-call]")];
    expect(calls.map((call) => call.textContent)).toEqual([expect.stringMatching(/✗Wrong secret$/), expect.stringMatching(/✓Received$/)]);
    flushSync(() => calls[1]!.querySelector("button")!.click());
    expect(calls[1]!.querySelector("pre")!.textContent).toBe('{ "lead": "Ada", "email": "[email protected]" }');
    flushSync(() => calls[0]!.querySelector("button")!.click());
    expect(calls[0]!.querySelector("pre")!.textContent).toBe("Nothing to show.");
    const visible = (container.textContent ?? "").replace(more.textContent ?? "", "");
    expect(visible).not.toContain("Recent calls");
  });
});

describe("on a Cloud", () => {
  it("never asks the person to keep the app open for another app's automation", () => {
    const [automation] = automationsFrom({ routines: [], webhooks: [webhook] as never, runs: [] });
    const props = { automation: automation!, sentence: "s", onClose: vi.fn(), onEdit: vi.fn(), onDeleted: vi.fn() };
    expect(mount(createElement(AutomationPanel, props)).textContent).toContain("Keep MausBot open so it can receive.");
    root!.unmount();
    fixture.state.config = { cloudHome: true };
    expect(mount(createElement(AutomationPanel, props)).textContent).not.toContain("Keep MausBot open");
  });
});

describe("the calendar", () => {
  afterEach(() => { vi.useRealTimers(); });
  it("shows a future event of an automation that needs you in its status colour, and none of a deleted bot", () => {
    vi.useFakeTimers({ toFake: ["Date"] });
    vi.setSystemTime(new Date(2026, 9, 14, 8, 0));
    const at = new Date(2026, 9, 14, 17, 0).getTime();
    const daily = (id: string, name: string, botId = "bot-a") => ({ id, name, prompt: `${name}.`, target: "bot", botId, runOn: "maus", enabled: true,
      schedule: { type: "daily", time: "17:00", weekdays: [0, 1, 2, 3, 4, 5, 6] }, durationMinutes: 30, nextRunAt: at, createdAt: 0, updatedAt: 0 });
    fixture.state.routines = [daily("failing", "Sales inbox check"), daily("fine", "Morning summary"), daily("orphan", "Orphan check", "deleted-bot")];
    // Last week's failure: its own receipt is off this week's grid, so only the future event can say Needs you.
    const failedAt = at - 8 * 86_400_000;
    fixture.state.routineRuns = [{ id: "run-1", routineId: "failing", botId: "bot-a", status: "failed", error: "Claude is signed out", scheduledFor: failedAt, startedAt: failedAt, createdAt: failedAt }];
    fixture.state.groups = [];
    const container = mount(createElement(AutomationsCalendar, { botFilter: "all", onOpenAutomation: vi.fn(), onOpenRoom: vi.fn() }));
    const dots = (name: string) => [...container.querySelectorAll(`[data-event-card][aria-label^="${name}"] [data-event-status]`)].map((dot) => (dot as HTMLElement).dataset.eventStatus);
    expect(dots("Sales inbox check")).toContain("needs-you");
    expect(dots("Morning summary").length).toBeGreaterThan(0);
    expect(dots("Morning summary").every((status) => status === "working")).toBe(true);
    expect(container.querySelector('[data-event-card][aria-label^="Orphan check"]')).toBeNull();
  });

  it("shows only the chosen department's events", () => {
    vi.useFakeTimers({ toFake: ["Date"] });
    vi.setSystemTime(new Date(2026, 9, 14, 8, 0));
    const at = new Date(2026, 9, 14, 17, 0).getTime();
    const daily = (id: string, name: string, botId: string) => ({ id, name, prompt: `${name}.`, target: "bot", botId, runOn: "maus", enabled: true,
      schedule: { type: "daily", time: "17:00", weekdays: [0, 1, 2, 3, 4, 5, 6] }, durationMinutes: 30, nextRunAt: at, createdAt: 0, updatedAt: 0 });
    fixture.state.bots = [{ ...botA, section: "Social" }, { ...botB, section: "Dev" }] as unknown as Bot[];
    fixture.state.routines = [daily("social", "Social post", "bot-a"), daily("dev", "Dev check", "bot-b")];
    fixture.state.groups = [];
    const cards = (department: string) => {
      const container = mount(createElement(AutomationsCalendar, { botFilter: "all", department, onOpenAutomation: vi.fn(), onOpenRoom: vi.fn() }));
      const count = (name: string) => container.querySelectorAll(`[data-event-card][aria-label^="${name}"]`).length;
      const counts = { social: count("Social post"), dev: count("Dev check") };
      root!.unmount();
      container.remove();
      return counts;
    };
    const everyone = cards("all");
    expect(everyone.social).toBeGreaterThan(0);
    expect(everyone.dev).toBeGreaterThan(0);
    expect(cards("Dev")).toEqual({ social: 0, dev: everyone.dev });
    expect(cards("Social")).toEqual({ social: everyone.social, dev: 0 });
  });

  it("keeps a call when any of its bots is in the chosen department", async () => {
    vi.useFakeTimers({ toFake: ["Date"] });
    vi.setSystemTime(new Date(2026, 9, 14, 8, 0));
    const at = new Date(2026, 9, 14, 17, 0).getTime();
    const call = (id: string, name: string, botIds: string[]) => ({ id, name, description: "", botIds, schedule: { type: "once", at }, durationMinutes: 30, attachments: [], nextRunAt: at, createdAt: 0, updatedAt: 0 });
    fixture.state.bots = [{ ...botA, section: "Social" }, { ...botB, section: "Dev" }] as unknown as Bot[];
    fixture.state.routines = [];
    fixture.state.groups = [];
    fixture.api.mockImplementation(async (path: unknown) => path === "/api/calendar-calls" ? { calls: [call("social", "Social sync", ["bot-a"]), call("dev", "Dev sync", ["bot-b"]), call("both", "All hands", ["bot-a", "bot-b"])] } : {});
    const container = mount(createElement(AutomationsCalendar, { botFilter: "all", department: "Dev", onOpenAutomation: vi.fn(), onOpenRoom: vi.fn() }));
    const shown = (name: string) => container.querySelectorAll(`[data-event-card][aria-label^="${name}"]`).length;
    await vi.waitFor(() => expect(shown("Dev sync")).toBeGreaterThan(0));
    expect(shown("All hands")).toBeGreaterThan(0);
    expect(shown("Social sync")).toBe(0);
  });
});

describe("the secret, under More", () => {
  const secret = "whsec_fixture-secret-value";
  beforeEach(() => {
    copied.texts = [];
    credentials.items.clear();
    saveWebhookCredential(credentials.store as never, "hook-1", { endpointUrl: "http://127.0.0.1:8800/hooks/wh_abc", url: `http://127.0.0.1:8800/hooks/wh_abc/${secret}`, secret });
  });
  afterEach(() => { credentials.items.clear(); });

  it("is masked when More opens, copies without showing, and shows only on Show, for that panel", async () => {
    const [automation] = automationsFrom({ routines: [], webhooks: [webhook] as never, runs: [] });
    const props = { automation: automation!, sentence: "s", onClose: vi.fn(), onEdit: vi.fn(), onDeleted: vi.fn() };
    let container = mount(createElement(AutomationPanel, props));
    const more = () => container.querySelector("details")!;
    expect(more().textContent).toContain("Recent calls");
    expect(more().textContent).toContain("Secret: ••••••••");
    expect(container.innerHTML).not.toContain(secret);
    flushSync(() => container.querySelector<HTMLButtonElement>('button[aria-label="Copy the secret"]')!.click());
    await vi.waitFor(() => expect(copied.texts).toEqual([secret]));
    await vi.waitFor(() => expect(container.querySelector('button[aria-label="Copy the secret"]')!.textContent).toBe("Copied"));
    expect(container.innerHTML).not.toContain(secret);
    flushSync(() => container.querySelector<HTMLButtonElement>('button[aria-label="Show the secret"]')!.click());
    expect(more().textContent).toContain(`Secret: ${secret}`);
    flushSync(() => container.querySelector<HTMLButtonElement>('button[aria-label="Hide the secret"]')!.click());
    expect(container.innerHTML).not.toContain(secret);
    flushSync(() => container.querySelector<HTMLButtonElement>('button[aria-label="Show the secret"]')!.click());
    root!.unmount();
    container = mount(createElement(AutomationPanel, props));
    expect(container.innerHTML).not.toContain(secret);
  });
});

describe("a run that waits on the person", () => {
  const routine = { id: "routine-1", name: "Morning summary", prompt: "Send me a summary of my inbox.", target: "bot", botId: "bot-a", runOn: "maus", enabled: true,
    schedule: { type: "daily", time: "09:00", weekdays: [0, 1, 2, 3, 4, 5, 6] }, durationMinutes: 30, nextRunAt: now + 3_600_000, createdAt: now, updatedAt: now };
  const run = (status: string) => ({ id: "run-1", routineId: "routine-1", botId: "bot-a", status, scheduledFor: now - 60_000, startedAt: now - 60_000, createdAt: now - 60_000, threadId: "exec-1" });
  const panel = (status: string) => {
    const [automation] = automationsFrom({ routines: [routine] as never, webhooks: [], runs: [run(status)] as never });
    return mount(createElement(AutomationPanel, { automation: automation!, sentence: "s", onClose: vi.fn(), onEdit: vi.fn(), onDeleted: vi.fn() }));
  };
  const cancel = (container: HTMLElement) => container.querySelector<HTMLButtonElement>("[data-automation-cancel-run]");

  it("can be cancelled beside Answer, when its question was settled somewhere else", async () => {
    const cancelled = { ...run("cancelled"), finishedAt: now };
    fixture.api.mockResolvedValue({ run: cancelled });
    const container = panel("waiting");
    expect(button(container, "Answer")).toBeTruthy();
    expect(cancel(container)!.textContent).toBe("Cancel run");
    flushSync(() => cancel(container)!.click());
    await vi.waitFor(() => expect(fixture.api).toHaveBeenCalledWith("/api/routine-runs/run-1/cancel", { method: "POST" }));
    await vi.waitFor(() => expect(fixture.dispatch).toHaveBeenCalledWith({ type: "routineRunPatched", run: cancelled }));
  });

  it("opens and cancels the same waiting run when a newer run was cancelled", async () => {
    const newer = { ...run("cancelled"), id: "run-2", threadId: "exec-2", scheduledFor: now - 30_000, startedAt: now - 30_000, createdAt: now - 30_000, finishedAt: now };
    const [automation] = automationsFrom({ routines: [routine] as never, webhooks: [], runs: [newer, run("waiting")] as never });
    const container = mount(createElement(AutomationPanel, { automation: automation!, sentence: "s", onClose: vi.fn(), onEdit: vi.fn(), onDeleted: vi.fn() }));
    flushSync(() => button(container, "Answer")!.click());
    expect(fixture.dispatch).toHaveBeenCalledWith({ type: "switchTask", botId: "bot-a", threadId: "exec-1" });
    expect(fixture.dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ threadId: "exec-2" }));
    fixture.api.mockResolvedValue({ run: { ...run("cancelled"), finishedAt: now } });
    flushSync(() => cancel(container)!.click());
    await vi.waitFor(() => expect(fixture.api).toHaveBeenCalledWith("/api/routine-runs/run-1/cancel", { method: "POST" }));
  });

  it("offers no Cancel run when nothing waits", () => {
    expect(cancel(panel("failed"))).toBeNull();
    root?.unmount(); root = null; document.body.innerHTML = "";
    expect(cancel(panel("completed"))).toBeNull();
  });
});