Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

7.7 KB
Raw Blame
import { Predicate } from "effect";
import { BookmarkIcon, CircleAlertIcon } from "lucide-react";
import { useState } from "react";

import {
  botInboxItemCopy,
  botInboxRowAction,
  selectOpenBotInboxItems,
  type BotInboxItem,
  type BotInboxRowAction,
} from "@akeru/client-runtime/bot-inbox";
import {
  describeDurableFactFailure,
  memoryApprovalMutation,
  type MemoryApprovalIntent,
} from "@akeru/client-runtime/durable-memory";
import { squashAtomCommandFailure } from "@akeru/client-runtime/state/runtime";
import { openPlugins } from "../../pluginsDialogStore";
import { openSettings } from "../../settingsDialogStore";
import { useSettingsEnvironmentId } from "../../settingsDialogStore";
import { useI18n } from "../../i18n";
import { botInboxEnvironment } from "../../state/botInbox";
import { memoryEnvironment } from "../../state/memory";
import { formatEnvironmentQueryError, useEnvironmentQuery } from "../../state/query";
import { useAtomCommand } from "../../state/use-atom-command";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { SettingsRow, SettingsSection } from "./settingsLayout";

/** Open bot errors and approval requests for surfaces that still use the inbox. */
export function InboxSection() {
  const { t } = useI18n();
  const environmentId = useSettingsEnvironmentId();

  const inboxQuery = useEnvironmentQuery(
    environmentId === null ? null : botInboxEnvironment.list({ environmentId, input: {} }),
  );

  const resolveIncident = useAtomCommand(botInboxEnvironment.resolve);
  const mutateFact = useAtomCommand(memoryEnvironment.mutateFact, { reportFailure: false });
  const openItems = selectOpenBotInboxItems(inboxQuery.data ?? []);

  return (
    <SettingsSection
      id="errors"
      title={t("Bot inbox")}
      headerAction={
        openItems.length > 0 ? (
          <Badge variant="error">{t("{count} open", { count: openItems.length })}</Badge>
        ) : null
      }
    >
      {inboxQuery.isPending ? (
        <SettingsRow title={t("Loading inbox")} />
      ) : inboxQuery.error ? (
        <SettingsRow title={t("Could not load the inbox")} description={inboxQuery.error} />
      ) : openItems.length === 0 ? (
        <SettingsRow
          title={t("Nothing open")}
          description={t("Bot failures and memory approvals appear here.")}
        />
      ) : (
        openItems.map((item) => {
          const approval = item.memoryApproval;

          return (
            <InboxIncidentRow
              key={item.id}
              item={item}
              environmentId={environmentId}
              onResolve={
                environmentId === null
                  ? null
                  : async () => {
                      const result = await resolveIncident({
                        environmentId,
                        input: { id: item.id },
                      });

                      return Predicate.isTagged(result, "Failure")
                        ? formatEnvironmentQueryError(result.cause)
                        : null;
                    }
              }
              onDecideMemory={
                environmentId === null || approval === undefined
                  ? null
                  : async (intent) => {
                      const result = await mutateFact({
                        environmentId,
                        input: {
                          threadId: approval.sourceThreadId,
                          mutation: memoryApprovalMutation(approval, intent),
                        },
                      });

                      if (Predicate.isTagged(result, "Failure")) {
                        return t(
                          describeDurableFactFailure(squashAtomCommandFailure(result)).message,
                        );
                      }

                      // The server closes the inbox item when it records the decision.
                      inboxQuery.refresh();

                      return null;
                    }
              }
            />
          );
        })
      )}
    </SettingsSection>
  );
}

export function InboxIncidentRow({
  item,
  environmentId,
  onResolve,
  onDecideMemory,
}: {
  readonly item: BotInboxItem;
  readonly environmentId: ReturnType<typeof useSettingsEnvironmentId>;
  readonly onResolve: (() => Promise<string | null>) | null;
  readonly onDecideMemory: ((intent: MemoryApprovalIntent) => Promise<string | null>) | null;
}) {
  const { t } = useI18n();
  const action = botInboxRowAction(item);
  const copy = botInboxItemCopy(item, t);
  const [isResolving, setIsResolving] = useState(false);
  const [resolveError, setResolveError] = useState<string | null>(null);

  const openRepair = () => {
    if (action === "plugins") {
      openPlugins();

      return;
    }

    if (action === "providers") openSettings("providers", null, environmentId);
  };

  const handleResolve = async () => {
    if (onResolve === null || isResolving) return;
    setIsResolving(true);
    setResolveError(null);

    try {
      setResolveError(await onResolve());
    } finally {
      setIsResolving(false);
    }
  };

  const handleDecideMemory = async (intent: MemoryApprovalIntent) => {
    if (onDecideMemory === null || isResolving) return;
    setIsResolving(true);
    setResolveError(null);

    try {
      setResolveError(await onDecideMemory(intent));
    } finally {
      setIsResolving(false);
    }
  };

  return (
    <SettingsRow
      title={
        <span className="flex items-center gap-2">
          {action === "memory-approval" ? (
            <BookmarkIcon className="size-4 text-muted-foreground" />
          ) : (
            <CircleAlertIcon className="size-4 text-destructive" />
          )}
          <span>
            {item.botName} · {item.taskOrRoutine} · {copy.kind}
          </span>
          {copy.sensitive ? (
            <span className="text-xs font-normal text-muted-foreground">· {copy.sensitive}</span>
          ) : null}
        </span>
      }
      description={copy.detail}
      status={resolveError ?? copy.nextAction}
      control={
        <InboxRowControl
          action={action}
          isResolving={isResolving}
          canResolve={onResolve !== null}
          canDecideMemory={onDecideMemory !== null}
          onResolve={() => void handleResolve()}
          onDecideMemory={(intent) => void handleDecideMemory(intent)}
          onOpenRepair={openRepair}
        />
      }
    />
  );
}

function InboxRowControl({
  action,
  isResolving,
  canResolve,
  canDecideMemory,
  onResolve,
  onDecideMemory,
  onOpenRepair,
}: {
  readonly action: BotInboxRowAction;
  readonly isResolving: boolean;
  readonly canResolve: boolean;
  readonly canDecideMemory: boolean;
  readonly onResolve: () => void;
  readonly onDecideMemory: (intent: MemoryApprovalIntent) => void;
  readonly onOpenRepair: () => void;
}) {
  const { t } = useI18n();

  if (action === "memory-approval") {
    return (
      <span className="flex items-center gap-1.5">
        <Button
          size="xs"
          variant="ghost-muted"
          disabled={isResolving || !canDecideMemory}
          onClick={() => onDecideMemory({ action: "reject" })}
        >
          {t("Reject")}
        </Button>
        <Button
          size="xs"
          disabled={isResolving || !canDecideMemory}
          onClick={() => onDecideMemory({ action: "approve" })}
        >
          {t("Approve")}
        </Button>
      </span>
    );
  }

  if (action === "resolve") {
    return (
      <Button size="xs" variant="outline" disabled={isResolving || !canResolve} onClick={onResolve}>
        {isResolving ? t("Resolving…") : t("Resolve")}
      </Button>
    );
  }

  return (
    <Button size="xs" variant="outline" onClick={onOpenRepair}>
      {action === "plugins" ? t("Open Plugins") : t("Open Providers")}
    </Button>
  );
}