Skip to content

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

Automations: Pause all / Resume all for the list shown, with Undo

milind-sonie27a81dbe7c5
diff --git a/src/components/TriggersPage.tsx b/src/components/TriggersPage.tsx
index f29e389983..c9fadb75ef 100644
--- a/src/components/TriggersPage.tsx
+++ b/src/components/TriggersPage.tsx
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useRef, useState } from "react";
-import { Plus, Zap } from "lucide-react";
+import { Pause, Play, Plus, Zap } from "lucide-react";
import { automationsFrom, automationSentence, automationStatus, orderAutomations, runLine, statusLine, type Automation } from "@/lib/automations";
import { cn } from "@/lib/cn";
@@ -13,16 +13,18 @@ import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-se
import { useAppTriggers } from "@/lib/app-triggers";
import { useMinuteTick } from "@/lib/minute-tick";
import { AppEventEditor } from "./automations/AppEventEditor";
-import { useAllAutomationActions } from "./automations/app-actions";
+import { type AutomationActions, SET_ALL_BUSY, useAllAutomationActions } from "./automations/app-actions";
import { AutomationPanel } from "./automations/AutomationPanel";
import { AutomationsCalendar } from "./automations/AutomationsCalendar";
import { LimitWarnings } from "./automations/LimitWarnings";
import { NewAutomation, type SetUpKind } from "./automations/NewAutomation";
import { FixButton, StatusMark } from "./automations/parts";
+import { usePausedByAll } from "./automations/paused-by-all";
import { RoutineEditor } from "./RoutineCalendarPage";
import { Select } from "./Select";
import { Switch } from "./SettingsPrimitives";
import { TOOL_PAGE_TITLE, ToolPage, ToolPageActions, ToolPageHeader } from "./ToolPageShell";
+import { UndoToast, useUndoToast } from "./UndoToast";
import { WebhookEditor } from "./WebhookTrigger";
import { schedulableBots, useTeamPeople } from "@/state/team-people";
@@ -77,6 +79,7 @@ export function TriggersPage({ onBack, onOpenRoom }: { onBack: () => void; onOpe
const listed = orderAutomations(all.filter((automation) => inDepartment(automation.botId) && (!showFilter || botFilter === "all" || automation.botId === botFilter)));
const open = all.find((automation) => automation.id === openId) ?? null;
const sentenceOf = (automation: Automation) => automationSentence(automation, botName(automation.botId));
+ const setAll = usePauseAll(view === "list" ? listed : [], JSON.stringify([activeDepartment, showFilter ? botFilter : "all"]), actions);
const editRoutine = editing?.kind === "schedule" ? state.routines.find((routine) => routine.id === editing.id) : undefined;
const editWebhook = editing?.kind === "webhook" ? state.webhooks.find((webhook) => webhook.id === editing.id) : undefined;
@@ -100,6 +103,12 @@ export function TriggersPage({ onBack, onOpenRoom }: { onBack: () => void; onOpe
{departmentBots.map((bot) => <option key={bot.id} value={bot.id}>{bot.name}</option>)}
</Select>
)}
+ {setAll.offer && (
+ <button type="button" className="ui-button ui-button-sm" data-automations-set-all="" disabled={actions.busy !== null} onClick={() => void setAll.run()}>
+ {setAll.offer === "pause" ? <Pause size={14} aria-hidden="true" /> : <Play size={14} aria-hidden="true" />}
+ {t(setAll.offer === "pause" ? "automations.pauseAll" : "automations.resumeAll")}
+ </button>
+ )}
<div role="group" aria-label={t("automations.view")} className="flex items-center rounded-lg border border-hairline/50 bg-panel p-0.5">
{(["list", "calendar"] as const).map((option) => (
<button key={option} type="button" aria-pressed={view === option} onClick={() => dispatch({ type: "showRoutines", view: option, botId: botFilter === "all" ? undefined : botFilter })}
@@ -146,22 +155,22 @@ export function TriggersPage({ onBack, onOpenRoom }: { onBack: () => void; onOpe
<span>{problemLine.when} {problemLine.mark} {problemLine.text}</span>
</button>}
{!!automation.noStartStreak && <div className="mt-1 text-[13px] text-warning" data-automation-no-start="">{t("routines.noStartStreak", { count: automation.noStartStreak })}</div>}
- {actions.error && actions.errorFor?.endsWith(`:${automation.id}`) && <p role="alert" className="mt-1 text-[12px] text-danger">{actions.error}</p>}
+ {!open && actions.error && actions.errorFor?.endsWith(`:${automation.id}`) && <p role="alert" className="mt-1 text-[12px] text-danger">{actions.error}</p>}
</div>
- {status.state !== "done" && <Switch checked={automation.enabled} disabled={actions.busy === `toggle:${automation.id}`} aria-label={t("automations.toggle", { name: automation.name })} onClick={() => void actions.toggle(automation)} className="relative z-10 mt-0.5 shrink-0" />}
+ {status.state !== "done" && <Switch checked={automation.enabled} disabled={actions.busy === `toggle:${automation.id}` || actions.busy === SET_ALL_BUSY} aria-label={t("automations.toggle", { name: automation.name })} onClick={() => { setAll.forget(automation.id); void actions.toggle(automation); }} className="relative z-10 mt-0.5 shrink-0" />}
</li>
);
})}
</ul>
)}
- {actions.error && !listed.some((automation) => actions.errorFor?.endsWith(`:${automation.id}`)) && <p role="alert" className="mt-3 text-[12px] text-danger">{actions.error}</p>}
+ {!open && actions.error && !listed.some((automation) => actions.errorFor?.endsWith(`:${automation.id}`)) && <p role="alert" className="mt-3 text-[12px] text-danger">{actions.error}</p>}
<RoutineWakeBar />
</div>
</div>
)}
{open && (
<div className="absolute inset-y-0 right-0 z-30 flex shadow-2xl lg:static lg:shadow-none">
- <AutomationPanel key={open.id} automation={open} sentence={sentenceOf(open)} onClose={() => setOpenId(null)} onDeleted={() => setOpenId(null)} onEdit={() => setEditing({ kind: open.kind, id: open.id })} />
+ <AutomationPanel key={open.id} automation={open} sentence={sentenceOf(open)} actions={actions} onClose={() => setOpenId(null)} onDeleted={() => setOpenId(null)} onEdit={() => setEditing({ kind: open.kind, id: open.id })} />
</div>
)}
</div>
@@ -174,10 +183,48 @@ export function TriggersPage({ onBack, onOpenRoom }: { onBack: () => void; onOpe
<WebhookEditor webhook={editWebhook} bots={editorBots} initialBotId={editing.botId} onClose={() => setEditing(null)} onCredential={(credential, id) => { saveWebhookCredential(webhookCredentialStore(), id, credential); setOpenId(id); }} />
)}
{editing?.kind === "app" && (editApp || !editing.id) && <AppEventEditor trigger={editApp} bots={editorBots} initialBotId={editing.botId} onClose={() => setEditing(null)} onSaved={(trigger) => setOpenId(trigger.id)} />}
+ <UndoToast toast={setAll.toast} onDone={setAll.hideToast} />
</ToolPage>
);
}
+/** "Pause all" turns off every automation on in the list shown, with Undo; "Resume all" then turns back on only the
+ * ones it turned off and that are still off. One the person switches by hand is theirs again. Shown for two or more
+ * automations with a switch. */
+function usePauseAll(listed: readonly Automation[], list: string, actions: AutomationActions) {
+ const [pausedByAll, remember] = usePausedByAll(list);
+ const [toast, showToast] = useUndoToast();
+ const latest = useRef({ listed, actions });
+ latest.current = { listed, actions };
+ const switchable = listed.filter((automation) => automationStatus(automation).state !== "done");
+ const toResume = switchable.filter((automation) => !automation.enabled && pausedByAll.includes(automation.id));
+ const toPause = switchable.filter((automation) => automation.enabled);
+ const offer = switchable.length < 2 ? null : toResume.length ? "resume" : toPause.length ? "pause" : null;
+
+ /** Turns back on those of `ids` still off, and keeps in the list's set only the ones that could not be. */
+ const resume = async (ids: readonly string[]) => {
+ const off = latest.current.listed.filter((automation) => !automation.enabled && ids.includes(automation.id) && automationStatus(automation).state !== "done");
+ const resumed = await latest.current.actions.setAllEnabled(off, true);
+ remember(off.map((automation) => automation.id).filter((id) => !resumed.includes(id)));
+ };
+ const pause = async () => {
+ const paused = await actions.setAllEnabled(toPause, false);
+ if (!paused.length) return;
+ remember(paused);
+ showToast({
+ text: paused.length === 1 ? t("automations.pausedAll.one") : t("automations.pausedAll.other", { count: paused.length }),
+ undo: () => void resume(paused),
+ });
+ };
+ return {
+ offer,
+ run: () => offer === "resume" ? resume(toResume.map((automation) => automation.id)) : pause(),
+ forget: (id: string) => { if (pausedByAll.includes(id)) remember(pausedByAll.filter((kept) => kept !== id)); },
+ toast,
+ hideToast: () => showToast(null),
+ };
+}
+
/** While a Mac sleeps no schedule runs: the shell can hold it awake the hour before one is due, plugged in only. */
function RoutineWakeBar() {
const bridge = typeof window !== "undefined" ? window.ogb?.routines : undefined;
diff --git a/src/components/automations/AutomationPanel.tsx b/src/components/automations/AutomationPanel.tsx
index 50bcc2e213..cba43b8dd1 100644
--- a/src/components/automations/AutomationPanel.tsx
+++ b/src/components/automations/AutomationPanel.tsx
@@ -8,7 +8,7 @@ import { t } from "@/lib/i18n";
import { isRoutineProblemRun } from "@/lib/routines";
import { loadWebhookCredentials, webhookCredentialStore } from "@/lib/webhook-credentials";
import { AppEventsSection } from "./AppEventsSection";
-import { useAllAutomationActions } from "./app-actions";
+import { type AutomationActions, useAllAutomationActions } from "./app-actions";
import { FixButton, StatusMark } from "./parts";
import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";
import { useMinuteTick } from "@/lib/minute-tick";
@@ -17,12 +17,14 @@ const RECENT = 5;
const BUTTON = "flex items-center justify-center gap-1.5 rounded-lg px-3 py-2 text-[13px] font-medium disabled:opacity-50";
/** One automation, simply: its sentence, its status, the last five runs plus any failure not yet seen, and what can be done to it. */
-export function AutomationPanel({ automation, sentence, onClose, onEdit, onDeleted }: {
+export function AutomationPanel({ automation, sentence, onClose, onEdit, onDeleted, actions: listActions }: {
automation: Automation;
sentence: string;
onClose: () => void;
onEdit: () => void;
onDeleted: () => void;
+ /** The Automations list's actions, so the list and this panel show one latest refusal between them. */
+ actions?: AutomationActions;
}) {
useMinuteTick();
const state = useStoreSelector((s) => ({ bots: s.bots, config: s.config, webhookAttempts: s.webhookAttempts, webhookIngress: s.webhookIngress, webhooks: s.webhooks }), sameFields), dispatch = useStoreDispatch();
@@ -31,7 +33,8 @@ export function AutomationPanel({ automation, sentence, onClose, onEdit, onDelet
useEffect(() => {
for (const run of automation.runs) if (isRoutineProblemRun(run) && !run.seenAt) dispatch({ type: "markRoutineRunSeen", runId: run.id });
}, [automation.runs, dispatch]);
- const actions = useAllAutomationActions();
+ const ownActions = useAllAutomationActions();
+ const actions = listActions ?? ownActions;
const status = automationStatus(automation);
const webhook = automation.kind === "webhook" ? state.webhooks.find((candidate) => candidate.id === automation.id) : undefined;
const credential = webhook ? loadWebhookCredentials(webhookCredentialStore())[webhook.id] : undefined;
diff --git a/src/components/automations/actions.ts b/src/components/automations/actions.ts
index afcd3b2fab..aa2adfd5be 100644
--- a/src/components/automations/actions.ts
+++ b/src/components/automations/actions.ts
@@ -20,45 +20,54 @@ export function useAutomationActions() {
const [errorFor, setErrorFor] = useState<string | null>(null);
const [copied, setCopied] = useState<string | null>(null);
+ /** Runs one action unless another is running; true when it ran and was not refused. */
const attempt = async (key: string, work: () => Promise<unknown>) => {
- if (busy) return;
+ if (busy) return false;
setBusy(key);
setError("");
setErrorFor(null);
- try { await work(); }
- catch (failure) { setError(failure instanceof Error ? failure.message : String(failure)); setErrorFor(key); }
+ try { await work(); return true; }
+ catch (failure) { setError(failure instanceof Error ? failure.message : String(failure)); setErrorFor(key); return false; }
finally { setBusy(null); }
};
- const toggle = (automation: Automation) => attempt(`toggle:${automation.id}`, async () => {
+ /** Turns a schedule or another app's automation on or off: what its switch does, and "Pause all" does for each. */
+ const setEnabled = async (automation: Automation, enabled: boolean) => {
if (automation.kind === "schedule") {
- const response = await api(`/api/routines/${automation.id}`, { method: "PATCH", body: JSON.stringify({ enabled: !automation.enabled }) });
+ const response = await api(`/api/routines/${automation.id}`, { method: "PATCH", body: JSON.stringify({ enabled }) });
dispatch({ type: "routinePatched", routine: response.routine });
return;
}
- const response = await api(`/api/webhooks/${automation.id}`, { method: "PATCH", body: JSON.stringify({ enabled: !automation.enabled, verificationPending: false }) });
+ const response = await api(`/api/webhooks/${automation.id}`, { method: "PATCH", body: JSON.stringify({ enabled, verificationPending: false }) });
dispatch({ type: "webhookPatched", webhook: response.webhook });
- });
+ };
+
+ const toggle = (automation: Automation) => attempt(`toggle:${automation.id}`, () => setEnabled(automation, !automation.enabled));
+
+ /** Forgets the last refusal and what it was about, so it no longer shows beside that automation. */
+ const clearError = () => { setError(""); setErrorFor(null); };
const runNow = (automation: Automation) => attempt(`run:${automation.id}`, () => automation.kind === "schedule"
? new Promise<void>((resolve, reject) => dispatch({ type: "runRoutine", routineId: automation.id, onStarted: () => resolve(), onError: reject }))
: api(`/api/webhooks/${automation.id}/test`, { method: "POST", body: JSON.stringify({ event: "openmaus.test", message: "A test run from Automations" }) }));
- /** Asks once (a person deleting their own automation), then deletes it. */
- const remove = async (automation: Automation, question: string): Promise<boolean> => {
- if (!window.confirm(question)) return false;
+ /** Deletes it once the person said yes to the question; false when it is kept, so a refusal stays in view. */
+ const removeConfirmed = async (automation: Automation): Promise<boolean> => {
if (automation.kind === "schedule") {
+ clearError();
dispatch({ type: "deleteRoutine", routineId: automation.id });
return true;
}
- await attempt(`delete:${automation.id}`, async () => {
+ return attempt(`delete:${automation.id}`, async () => {
await api(`/api/webhooks/${automation.id}`, { method: "DELETE" });
dispatch({ type: "webhookDeleted", webhookId: automation.id });
removeWebhookCredential(webhookCredentialStore(), automation.id);
});
- return true;
};
+ /** Asks once (a person deleting their own automation), then deletes it. */
+ const remove = async (automation: Automation, question: string) => window.confirm(question) && removeConfirmed(automation);
+
/** The address another app sends to, as the server keeps it: the owning bot may already have given it to an app, so
* copying never replaces it. Only one from before addresses were kept, and not copied here before, gets a new one. */
const copyAddress = (webhookId: string, replace = false) => attempt(`copy:${webhookId}`, async () => {
@@ -90,5 +99,5 @@ export function useAutomationActions() {
if (response.run) dispatch({ type: "routineRunPatched", run: response.run });
});
- return { busy, error, errorFor, setError, copied, toggle, runNow, remove, copyAddress, openRun, cancelRun };
+ return { busy, error, errorFor, setError, clearError, copied, setEnabled, toggle, runNow, remove, removeConfirmed, copyAddress, openRun, cancelRun };
}
diff --git a/src/components/automations/app-actions.test.ts b/src/components/automations/app-actions.test.ts
new file mode 100644
index 0000000000..4cd4402ca6
--- /dev/null
+++ b/src/components/automations/app-actions.test.ts
@@ -0,0 +1,100 @@
+// @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 type { Automation } from "@/lib/automations";
+
+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 { useAllAutomationActions } = await import("./app-actions");
+
+const schedule = { kind: "schedule", id: "routine-1", enabled: true } as Automation;
+const hook = { kind: "webhook", id: "hook-1", enabled: true } as Automation;
+const app = { kind: "app", id: "acme", enabled: true } as Automation;
+
+let root: Root | null = null;
+let actions: ReturnType<typeof useAllAutomationActions>;
+function Probe() {
+ actions = useAllAutomationActions();
+ return null;
+}
+/** Waits until the last action finished, then gives the refusal shown and what it is about. */
+async function shown() {
+ await vi.waitFor(() => expect(actions.busy).toBeNull());
+ return { error: actions.error, errorFor: actions.errorFor };
+}
+const refuseWith = (message: string) => fixture.api.mockRejectedValueOnce(new Error(message));
+
+beforeEach(() => {
+ fixture.dispatch.mockReset();
+ fixture.api.mockReset();
+ fixture.api.mockResolvedValue({ trigger: { id: "acme", enabled: false }, routine: { id: "routine-1" }, webhook: { id: "hook-1" } });
+ fixture.state = { bots: [], routines: [], webhooks: [] };
+ const container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ flushSync(() => root!.render(createElement(Probe)));
+});
+afterEach(() => { root?.unmount(); root = null; document.body.innerHTML = ""; vi.unstubAllGlobals(); });
+
+describe("the automation actions with app events added", () => {
+ it("lets an app's action replace a schedule switch's refusal, and its own refusal is not shown beside the schedule", async () => {
+ refuseWith("The assigned bot no longer exists");
+ flushSync(() => { void actions.toggle(schedule); });
+ expect(await shown()).toEqual({ error: "The assigned bot no longer exists", errorFor: "toggle:routine-1" });
+ flushSync(() => { void actions.toggle(app); });
+ expect(await shown()).toEqual({ error: "", errorFor: null });
+ refuseWith("The assigned bot no longer exists");
+ flushSync(() => { void actions.toggle(schedule); });
+ expect((await shown()).errorFor).toBe("toggle:routine-1");
+ refuseWith("Gmail needs reconnecting");
+ flushSync(() => { void actions.runNow(app); });
+ expect(await shown()).toEqual({ error: "Gmail needs reconnecting", errorFor: null });
+ });
+
+ it("lets a webhook delete replace a Pause all refusal once the person confirms it, and keeps it when they cancel", async () => {
+ refuseWith("The server is restarting");
+ flushSync(() => { void actions.setAllEnabled([schedule, hook], false); });
+ expect((await shown()).error).toBe("The server is restarting");
+ vi.stubGlobal("confirm", vi.fn(() => false));
+ flushSync(() => { void actions.remove(hook, "Delete it?"); });
+ expect((await shown()).error).toBe("The server is restarting");
+ expect(fixture.api).not.toHaveBeenCalledWith("/api/webhooks/hook-1", expect.anything());
+ vi.stubGlobal("confirm", vi.fn(() => true));
+ refuseWith("The webhook is still in use");
+ flushSync(() => { void actions.remove(hook, "Delete it?"); });
+ await vi.waitFor(() => expect(fixture.api).toHaveBeenCalledWith("/api/webhooks/hook-1", { method: "DELETE" }));
+ expect(await shown()).toEqual({ error: "The webhook is still in use", errorFor: "delete:hook-1" });
+ });
+
+ it("lets a refused Copy address replace a Pause all refusal", async () => {
+ refuseWith("The server is restarting");
+ flushSync(() => { void actions.setAllEnabled([schedule, hook], false); });
+ expect((await shown()).error).toBe("The server is restarting");
+ fixture.api.mockRejectedValue(new Error("The webhook is gone"));
+ flushSync(() => { void actions.copyAddress("hook-1"); });
+ expect(await shown()).toEqual({ error: "The webhook is gone", errorFor: "copy:hook-1" });
+ });
+
+ it("drops a refused switch's refusal once the person confirms deleting a schedule", async () => {
+ refuseWith("The assigned bot no longer exists");
+ flushSync(() => { void actions.toggle(schedule); });
+ expect(await shown()).toEqual({ error: "The assigned bot no longer exists", errorFor: "toggle:routine-1" });
+ vi.stubGlobal("confirm", vi.fn(() => true));
+ flushSync(() => { void actions.remove(schedule, "Delete it?"); });
+ await vi.waitFor(() => expect(fixture.dispatch).toHaveBeenCalledWith({ type: "deleteRoutine", routineId: "routine-1" }));
+ expect(await shown()).toEqual({ error: "", errorFor: null });
+ });
+});
diff --git a/src/components/automations/app-actions.ts b/src/components/automations/app-actions.ts
index 2dbdb544d5..e53a2b5b66 100644
--- a/src/components/automations/app-actions.ts
+++ b/src/components/automations/app-actions.ts
@@ -5,34 +5,63 @@ import { appTriggerApi } from "@/lib/app-triggers";
import type { Automation } from "@/lib/automations";
import { useAutomationActions } from "./actions";
+/** What `busy` is while "Pause all" / "Resume all" writes: every switch waits for it. */
+export const SET_ALL_BUSY = "toggle:all";
+
+export type AutomationActions = ReturnType<typeof useAllAutomationActions>;
+
export function useAllAutomationActions() {
const base = useAutomationActions();
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState("");
const attempt = async (key: string, work: () => Promise<unknown>) => {
- if (busy || base.busy) return;
+ if (busy || base.busy) return false;
setBusy(key);
setError("");
- try { await work(); }
- catch (failure) { setError(failure instanceof Error ? failure.message : String(failure)); }
+ base.clearError();
+ try { await work(); return true; }
+ catch (failure) { setError(failure instanceof Error ? failure.message : String(failure)); return false; }
finally { setBusy(null); }
};
+ /** Runs a schedule's or another app's own action: an earlier "Pause all" refusal is no longer the latest word. */
+ const handOn = <T>(action: () => T): T => {
+ if (!base.busy) setError("");
+ return action();
+ };
return {
...base,
busy: busy ?? base.busy,
error: error || base.error,
setError: (message: string) => { setError(message); base.setError(message); },
+ /** "Pause all" / "Resume all": turns each of `automations` on or off in turn, stopping at the first refusal.
+ * Gives the ids it changed, so a refusal partway still says which ones it turned. */
+ setAllEnabled: async (automations: readonly Automation[], enabled: boolean): Promise<string[]> => {
+ const changed: string[] = [];
+ await attempt(SET_ALL_BUSY, async () => {
+ for (const automation of automations) {
+ if (automation.kind === "app") await appTriggerApi.update(automation.id, { enabled });
+ else await base.setEnabled(automation, enabled);
+ changed.push(automation.id);
+ }
+ });
+ return changed;
+ },
toggle: (automation: Automation) => automation.kind === "app"
? void attempt(`toggle:${automation.id}`, () => appTriggerApi.update(automation.id, { enabled: !automation.enabled }))
- : base.toggle(automation),
+ : busy ? undefined : handOn(() => base.toggle(automation)),
runNow: (automation: Automation) => automation.kind === "app"
? attempt(`run:${automation.id}`, () => appTriggerApi.test(automation.id))
- : base.runNow(automation),
+ : handOn(() => base.runNow(automation)),
+ copyAddress: (webhookId: string, replace?: boolean) => handOn(() => base.copyAddress(webhookId, replace)),
+ cancelRun: (...args: Parameters<typeof base.cancelRun>) => handOn(() => base.cancelRun(...args)),
remove: async (automation: Automation, question: string): Promise<boolean> => {
- if (automation.kind !== "app") return base.remove(automation, question);
if (!window.confirm(question)) return false;
- await attempt(`delete:${automation.id}`, () => appTriggerApi.remove(automation.id));
- return true;
+ if (automation.kind !== "app") {
+ const removed = await handOn(() => base.removeConfirmed(automation));
+ if (removed) setError("");
+ return removed;
+ }
+ return attempt(`delete:${automation.id}`, () => appTriggerApi.remove(automation.id));
},
};
}
diff --git a/src/components/automations/automations.test.ts b/src/components/automations/automations.test.ts
index ddc05e0b21..90628043f9 100644
--- a/src/components/automations/automations.test.ts
+++ b/src/components/automations/automations.test.ts
@@ -274,6 +274,187 @@ describe("the Automations list switch", () => {
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"]');
diff --git a/src/components/automations/paused-by-all.ts b/src/components/automations/paused-by-all.ts
new file mode 100644
index 0000000000..5638961ca8
--- /dev/null
+++ b/src/components/automations/paused-by-all.ts
@@ -0,0 +1,35 @@
+import { useState } from "react";
+
+const storageKey = (list: string) => `openmausbot.automations.paused-by-all.${list}`;
+
+function read(list: string): readonly string[] {
+ try {
+ const ids: unknown = JSON.parse(sessionStorage.getItem(storageKey(list)) ?? "[]");
+ return Array.isArray(ids) ? ids.filter((id): id is string => typeof id === "string") : [];
+ } catch {
+ return [];
+ }
+}
+
+function write(list: string, ids: readonly string[]) {
+ try {
+ if (ids.length) sessionStorage.setItem(storageKey(list), JSON.stringify(ids));
+ else sessionStorage.removeItem(storageKey(list));
+ } catch { /* no storage: kept while the page is open */ }
+}
+
+/** The automations "Pause all" turned off in one list, so "Resume all" turns back on only those. Each list shown
+ * (a department, a bot) keeps its own; it lasts while this window is open and is empty when none is kept. */
+export function usePausedByAll(list: string): [ids: readonly string[], remember: (ids: readonly string[]) => void] {
+ const [held, setHeld] = useState(() => ({ list, ids: read(list) }));
+ let current = held;
+ if (held.list !== list) {
+ current = { list, ids: read(list) };
+ setHeld(current);
+ }
+ const remember = (ids: readonly string[]) => {
+ write(list, ids);
+ setHeld({ list, ids });
+ };
+ return [current.ids, remember];
+}
diff --git a/src/locales/de.json b/src/locales/de.json
index 8096d929eb..12abaac458 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -4567,5 +4567,9 @@
"githubSignIn.tokenPlaceholder": "github_pat_…",
"approval.status.teammateSkills": "Team-Skills geändert",
"approval.applied.skill.teammates": "{name} hat Skills im Team geändert: {title}",
- "skills.request.reviewTeammates": "Prüfe jede Änderung, bevor du sie anwendest"
+ "skills.request.reviewTeammates": "Prüfe jede Änderung, bevor du sie anwendest",
+ "automations.pauseAll": "Alle pausieren",
+ "automations.resumeAll": "Alle fortsetzen",
+ "automations.pausedAll.one": "1 Automatisierung pausiert.",
+ "automations.pausedAll.other": "{count} Automatisierungen pausiert."
}
diff --git a/src/locales/en.json b/src/locales/en.json
index 0eceb2f2dc..9cb8d9642f 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -5667,6 +5667,10 @@
"routines.title": "Routines",
"automations.title": "Automations",
"automations.new": "New",
+ "automations.pauseAll": "Pause all",
+ "automations.resumeAll": "Resume all",
+ "automations.pausedAll.one": "Paused 1 automation.",
+ "automations.pausedAll.other": "Paused {count} automations.",
"automations.view": "Show as",
"automations.list": "List",
"automations.calendar": "Calendar",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index ccc22fb8ca..e571c672f3 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -5304,6 +5304,10 @@
"routines.title": "Rotinas",
"automations.title": "Automações",
"automations.new": "Nova",
+ "automations.pauseAll": "Pausar todas",
+ "automations.resumeAll": "Retomar todas",
+ "automations.pausedAll.one": "1 automação pausada.",
+ "automations.pausedAll.other": "{count} automações pausadas.",
"automations.view": "Mostrar como",
"automations.list": "Lista",
"automations.calendar": "Calendário",