Skip to content

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

5.8 KB
Raw Blame
// What a person can do to an automation, the same from the page, its panel and the chat card.
import { useState } from "react";

import type { Automation } from "@/lib/automations";
import { copyText } from "@/lib/copy-text";
import { t } from "@/lib/i18n";
import type { RoutineRun } from "@/lib/routines";
import { useShowThreads } from "@/lib/thread-preferences";
import { loadWebhookCredentials, removeWebhookCredential, saveWebhookCredential, webhookCredentialStore } from "@/lib/webhook-credentials";
import type { WebhookCredential } from "@/lib/webhooks";
import { api, openBotThread } from "@/state/store";
import { useStoreRef } from "@/state/store-ref";

export function useAutomationActions() {
  const store = useStoreRef(), dispatch = store.dispatch;
  const showThreads = useShowThreads();
  const [busy, setBusy] = useState<string | null>(null);
  const [error, setError] = useState("");
  /** What the error is about, e.g. "toggle:<id>", so it shows beside the thing that was clicked. */
  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 false;
    setBusy(key);
    setError("");
    setErrorFor(null);
    try { await work(); return true; }
    catch (failure) { setError(failure instanceof Error ? failure.message : String(failure)); setErrorFor(key); return false; }
    finally { setBusy(null); }
  };

  /** 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 }) });
      dispatch({ type: "routinePatched", routine: response.routine });
      return;
    }
    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" }) }));

  /** 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;
    }
    return attempt(`delete:${automation.id}`, async () => {
      await api(`/api/webhooks/${automation.id}`, { method: "DELETE" });
      dispatch({ type: "webhookDeleted", webhookId: automation.id });
      removeWebhookCredential(webhookCredentialStore(), automation.id);
    });
  };

  /** 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 () => {
    let credential: WebhookCredential | undefined;
    if (!replace) {
      credential = await api(`/api/webhooks/${webhookId}/address`).then((response) => response.credential as WebhookCredential, () => undefined)
        ?? loadWebhookCredentials(webhookCredentialStore())[webhookId];
      if (credential) saveWebhookCredential(webhookCredentialStore(), webhookId, credential);
    }
    if (!credential) {
      const response = await api(`/api/webhooks/${webhookId}/rotate`, { method: "POST" });
      credential = response.credential as WebhookCredential;
      dispatch({ type: "webhookPatched", webhook: response.webhook });
      saveWebhookCredential(webhookCredentialStore(), webhookId, credential);
    }
    if (await copyText(credential.url) !== "copied") throw new Error(t("automations.address.copyAddressFailed"));
    setCopied(webhookId);
    setTimeout(() => setCopied((current) => (current === webhookId ? null : current)), 1_800);
  });

  const openRun = (automation: Automation, run: RoutineRun | undefined) => {
    const bot = store.state().bots.find((candidate) => candidate.id === automation.botId);
    if (bot && run?.threadId) openBotThread(dispatch, bot, run.threadId, showThreads);
  };

  /** Stops a run that waits on the person, for when the question it waits on was settled somewhere else. */
  const cancelRun = (automation: Automation, run: RoutineRun) => attempt(`cancel:${automation.id}`, async () => {
    const response = await api(`/api/routine-runs/${run.id}/cancel`, { method: "POST" });
    if (response.run) dispatch({ type: "routineRunPatched", run: response.run });
  });

  return { busy, error, errorFor, setError, clearError, copied, setEnabled, toggle, runNow, remove, removeConfirmed, copyAddress, openRun, cancelRun };
}