Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

6.0 KB
Raw Blame
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.

import { Toast } from "@base-ui/react/toast";
import { CheckIcon, CircleAlertIcon, CircleCheckIcon, CopyIcon, InfoIcon, XIcon } from "lucide-react";
import { useState, type ReactNode } from "react";

import { CuaKey } from "@/components/cua-key";

export const toastManager = Toast.createToastManager();

type ToastType = "info" | "success" | "error";

/** How long an info or success toast stays. */
export const TOAST_MS = 5000;
/**
 * How long an error stays: longer, to read it, but it goes by itself too.
 * What failed stays where it happened (a failed create keeps its row and
 * reason, as in the SwiftUI app), so the toast need not.
 */
export const ERROR_TOAST_MS = 15000;

/** A button on a toast (an error's Upgrade). */
export interface ToastAction {
  label: string;
  onClick: () => void;
}

let errorAction: ((text: string, group?: string) => ToastAction | null) | null = null;

/** Offers an action on a failed action's toast, from the error's text (the
 * plan-limit refusal's Upgrade) and the toast's group (`create` for a
 * Space create). Set by the shell, which has the core. */
export function setErrorAction(fn: ((text: string, group?: string) => ToastAction | null) | null) {
  errorAction = fn;
}

/** The open toasts of each group (`toast`'s `group`). */
const groups = new Map<string, Set<string>>();

/**
 * Shows a toast. One with a `group` replaces that group's earlier ones: a
 * create that worked closes the failure of the try before it. `fromCua` marks
 * one of Cua's own notifications: it shows the Cua key instead of the info icon.
 */
export function toast(title: string, options: { description?: string; type?: ToastType; group?: string; fromCua?: boolean; action?: ToastAction } = {}) {
  const type = options.type ?? "info";
  const group = options.group;
  if (group) {
    for (const old of groups.get(group) ?? []) toastManager.close(old);
    groups.delete(group);
  }
  // Base UI's own timer pauses while the window is unfocused and resumes on
  // focus, which a webview in a native window may never report (an
  // "Opening…" toast stayed 10+ min). A plain timer closes it either way.
  const id = toastManager.add({ title, description: options.description, type, timeout: 0, data: { fromCua: options.fromCua === true, action: options.action } });
  if (group) groups.set(group, new Set([id]));
  setTimeout(() => {
    toastManager.close(id);
    if (group) groups.get(group)?.delete(id);
  }, type === "error" ? ERROR_TOAST_MS : TOAST_MS);
  return id;
}

/** A failed action: `title` says what didn't happen, the error says why. */
export const toastError = (title: string, group?: string) => (e: unknown) => {
  const description = e instanceof Error ? e.message : String(e);
  toast(title, { description, type: "error", group, action: errorAction?.(description, group) ?? undefined });
};

const ICONS = { info: InfoIcon, success: CircleCheckIcon, error: CircleAlertIcon } as const;

export function ToastProvider({ children }: { children: ReactNode }) {
  return (
    <Toast.Provider toastManager={toastManager} limit={3}>
      {children}
      <Toast.Portal>
        <Toast.Viewport className="fixed right-4 bottom-4 z-[60] flex w-80 flex-col-reverse gap-2 outline-none">
          <ToastList />
        </Toast.Viewport>
      </Toast.Portal>
    </Toast.Provider>
  );
}

/** Copies an error toast's complete text. */
function CopyError({ text }: { text: string }) {
  const [copied, setCopied] = useState(false);
  return (
    <button
      type="button"
      data-toast-copy=""
      className="mt-1.5 -ml-1 flex items-center gap-1 rounded-lg px-1 py-0.5 text-xs text-muted-foreground hover:text-foreground"
      onClick={() => {
        void navigator.clipboard?.writeText(text).catch(() => undefined);
        setCopied(true);
        setTimeout(() => setCopied(false), 1200);
      }}
    >
      {copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />} {copied ? "Copied" : "Copy"}
    </button>
  );
}

function ToastList() {
  const { toasts } = Toast.useToastManager();
  return toasts.map((t) => {
    const Icon = ICONS[(t.type as ToastType | undefined) ?? "info"] ?? InfoIcon;
    return (
      <Toast.Root
        key={t.id}
        toast={t}
        data-video-occluder=""
        className="glass flex items-start gap-2.5 rounded-lg border p-3 pr-2 shadow-float transition-[opacity,translate] duration-200 ease-out-soft data-ending-style:translate-y-2 data-ending-style:opacity-0 data-starting-style:translate-y-2 data-starting-style:opacity-0"
      >
        {(t.data as { fromCua?: boolean } | undefined)?.fromCua && t.type !== "error" ? (
          <CuaKey size={20} className="-my-0.5" />
        ) : (
          <Icon className={t.type === "error" ? "mt-px size-4 text-destructive" : t.type === "success" ? "mt-px size-4 text-success" : "mt-px size-4 text-brand-strong"} />
        )}
        <Toast.Content className="min-w-0 flex-1">
          <Toast.Title className="text-[13px] font-medium" />
          {/* An error is never cut: the whole text wraps (scrolls when very long), selects and copies. */}
          <Toast.Description className="max-h-40 overflow-y-auto text-xs break-words whitespace-pre-wrap text-muted-foreground select-text" />
          {t.type === "error" && typeof t.description === "string" && t.description ? <CopyError text={t.description} /> : null}
          {(t.data as { action?: ToastAction } | undefined)?.action ? (
            <button
              type="button"
              data-toast-action=""
              className="mt-2 rounded-lg border px-2 py-1 text-xs font-medium hover:bg-accent"
              onClick={() => (t.data as { action: ToastAction }).action.onClick()}
            >
              {(t.data as { action: ToastAction }).action.label}
            </button>
          ) : null}
        </Toast.Content>
        <Toast.Close aria-label="Dismiss" className="rounded-lg p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground">
          <XIcon className="size-3.5" />
        </Toast.Close>
      </Toast.Root>
    );
  });
}