Skip to content

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

8.4 KB
Raw Blame
import { ArrowRight, Loader2, Zap } from "lucide-react";

import { cn } from "@/lib/cn";
import { routineDateTime } from "@/lib/routine-display";
import { t } from "@/lib/i18n";
import type { LocaleKey } from "@/locales";
import { useShowThreads } from "@/lib/thread-preferences";
import { liveCardKind } from "../../shared/live-approval";
import type { AutomationLine, RoutineRunCardData } from "../../shared/routine-run";
import { formatTime, openThread, useStore, type Message } from "@/state/store";

const DETAIL_LIMIT = 280;

const COPY = {
  queued: { label: "routines.status.queued", tone: "text-ink-secondary" },
  running: { label: "routines.status.running", tone: "text-accent" },
  waiting: { label: "routines.status.waiting", tone: "text-warning" },
  completed: { label: "routines.status.completed", tone: "text-ink-secondary" },
  failed: { label: "routines.status.failed", tone: "text-danger" },
  cancelled: { label: "routines.status.cancelled", tone: "text-ink-secondary" },
  missed: { label: "routines.status.missed", tone: "text-danger" },
} satisfies Record<
  RoutineRunCardData["status"],
  { label: LocaleKey; tone: string }
>;

const GOAL_COPY = {
  completed: COPY.completed,
  "needs-input": { label: "routines.goal.needs-input", tone: "text-warning" },
  blocked: { label: "routines.goal.blocked", tone: "text-danger" },
  "limit-reached": { label: "routines.goal.limit-reached", tone: "text-warning" },
  paused: { label: "routines.goal.paused", tone: "text-warning" },
  stopped: { label: "routines.goal.stopped", tone: "text-ink-secondary" },
  failed: COPY.failed,
} satisfies Record<
  NonNullable<RoutineRunCardData["goalStatus"]>,
  { label: LocaleKey; tone: string }
>;

function compactDetail(value: string | undefined): string {
  const clean = value?.replace(/\s+/g, " ").trim() ?? "";
  return clean.length > DETAIL_LIMIT ? `${clean.slice(0, DETAIL_LIMIT - 1).trimEnd()}…` : clean;
}

export function hasRoutineExecutionTask(
  tasks: ReadonlyArray<{ threadId: string }> | undefined,
  executionThreadId: string | undefined,
): executionThreadId is string {
  return Boolean(
    executionThreadId && tasks?.some((task) => task.threadId === executionThreadId),
  );
}

export function RoutineRunCard({
  message,
  onOpen,
}: {
  message: Message;
  onOpen?: () => void;
}) {
  const run = message.routineRun;
  if (!run) {
    const fallback = compactDetail(message.text);
    return fallback ? (
      <div className="w-fit max-w-[min(var(--chat-bubble-max),var(--chat-card-pct))] rounded-2xl bg-card px-4 py-2.5 text-[14px] leading-relaxed text-ink">
        {fallback}
      </div>
    ) : null;
  }

  const copy = run.goalStatus
    ? GOAL_COPY[run.goalStatus]
    : run.status === "queued" && run.deferredAt != null
      ? { label: "routines.status.deferred" as const, tone: "text-warning" }
      : COPY[run.status];
  const detail = compactDetail(
    run.status === "failed" || run.status === "missed"
      ? (run.error ?? run.summary)
      : (run.summary ?? run.error),
  );
  const actionLabel = t(run.goalStatus === "needs-input" ? "routines.run.review" : "routines.run.open");

  return (
    <section
      aria-label={t("routines.run.cardLabel", { name: run.routineName, status: t(copy.label) })}
      className="w-full max-w-[680px] rounded-xl border border-hairline/45 bg-card px-4 py-3"
    >
      <div className="flex items-start gap-3">
        <div className="min-w-0 flex-1">
          <div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
            <h3 className="truncate text-[14px] font-semibold text-ink">{run.routineName}</h3>
            <span aria-live="polite" className={cn("inline-flex items-center gap-1 text-[12px] font-semibold", copy.tone)}>
              {run.status === "running" && !run.goalStatus && <Loader2 aria-hidden="true" className="size-3 animate-spin" />}
              {t(copy.label)}
            </span>
          </div>
          <time dateTime={new Date(run.scheduledFor ?? message.at).toISOString()} className="mt-0.5 block text-[12px] text-ink-secondary">
            {routineDateTime(run.scheduledFor ?? message.at)}
          </time>
          {detail && <p className="mt-1.5 text-[13px] leading-relaxed text-ink-secondary">{detail}</p>}
          {run.status === "completed" && run.summary && run.summary.length > DETAIL_LIMIT && <details className="mt-2 text-[12px] text-ink-secondary">
            <summary className="cursor-pointer font-medium text-ink-secondary hover:text-ink">{t("routines.results.showReport")}</summary>
            <p className="mt-2 whitespace-pre-wrap leading-relaxed">{run.summary}</p>
          </details>}
        </div>
        {onOpen && run.executionThreadId && (
          <button
            type="button"
            onClick={onOpen}
            aria-label={t("routines.run.actionFor", { action: actionLabel, name: run.routineName })}
            className={cn(
              "flex shrink-0 items-center gap-1 rounded-md px-2 py-1 text-[12px] font-semibold transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent",
              run.goalStatus === "needs-input"
                ? "bg-warning/15 text-warning hover:bg-warning/25"
                : "text-ink-secondary hover:bg-inset hover:text-ink",
            )}
          >
            {actionLabel}
            <ArrowRight aria-hidden="true" size={13} />
          </button>
        )}
      </div>
    </section>
  );
}

export function RoutineRunRow({ message, botId }: { message: Message; botId: string }) {
  const { state, dispatch } = useStore();
  const showThreads = useShowThreads();
  const executionThreadId = message.routineRun?.executionThreadId;
  const canOpen = executionThreadId && state.bots.some((candidate) =>
    candidate.threadId === executionThreadId || hasRoutineExecutionTask(candidate.tasks, executionThreadId)
  );
  return (
    <RoutineRunCard
      message={message}
      onOpen={canOpen && executionThreadId
        ? () => openThread(dispatch, { botId, threadId: executionThreadId }, state, showThreads)
        : undefined}
    />
  );
}

/** Above a line an automation run wrote in a chat: which automation, when, and the way to its full run. */
export function AutomationCaption({ message, line, botId }: { message: Message; line: AutomationLine; botId: string }) {
  const { state, dispatch } = useStore();
  const showThreads = useShowThreads();
  const canOpen = state.bots.some((bot) => bot.threadId === line.executionThreadId || hasRoutineExecutionTask(bot.tasks, line.executionThreadId));
  const asking = line.needsYou === true && (message.card ? liveCardKind(message.card) !== null : line.copyOf !== undefined ||
    !state.bots.find((bot) => bot.id === botId)?.messages.some((later) => later.role === "user" && later.at > message.at));
  const tone = line.partial ? "text-warning" : line.failed ? "text-danger" : asking ? "text-warning" : "text-accent";
  const chipBorder = line.partial || asking ? "border-warning/35" : line.failed ? "border-danger/35" : "border-hairline/60";
  return (
    <div data-automation-caption={line.runId} className="mt-2 -mb-1 flex w-full min-w-0 items-center gap-2 text-[12px] leading-4 text-ink-secondary">
      <span data-automation-badge className={cn("ui-chip gap-1.5 border bg-panel px-2.5 text-ink-secondary", chipBorder)}>
        <Zap aria-hidden="true" size={12} className={cn("shrink-0", tone)} />
        <span dir="auto" title={line.name} className="truncate font-medium text-ink">{line.name}</span>
        <time className="shrink-0 text-ink-secondary" dateTime={new Date(line.scheduledFor).toISOString()}>· {formatTime(line.scheduledFor)}</time>
        {(line.failed || asking) && <span className={cn("shrink-0", tone)}>· {t(line.partial ? "chat.automation.partial" : line.failed ? "chat.automation.failed" : "chat.automation.needsYou")}</span>}
        {canOpen && (
          <button
            type="button"
            onClick={() => openThread(dispatch, { botId, threadId: line.executionThreadId }, state, showThreads)}
            aria-label={t("chat.automation.openRunFor", { name: line.name })}
            className="ms-0.5 shrink-0 cursor-pointer rounded px-1 font-medium text-ink-secondary transition-colors motion-reduce:transition-none hover:bg-raised-hover hover:text-ink focus-visible:outline focus-visible:outline-2 focus-visible:outline-focus"
          >
            {t("chat.automation.openRun")}
          </button>
        )}
      </span>
      <span aria-hidden="true" data-automation-rule className="h-px min-w-4 flex-1 bg-hairline/60" />
    </div>
  );
}