Skip to content

Open source CapCut alternative.

TypeScript
13.0 KB
Raw Blame
import { useCallback, useEffect, useRef, useState } from "react";
import { App } from "@modelcontextprotocol/ext-apps";
import { useTranslations } from "use-intl";
import type { Messages } from "@/i18n/namespaces";
import { useSetWidgetLocale } from "./intl";
import { editorSchema, playbackSchema, viewSchema, type Editor, type Playback, type ProjectView } from "../contracts";

type ToolResult = { isError?: boolean; structuredContent?: unknown; _meta?: Record<string, unknown>; content?: unknown[] };
/** Where a result came from. The card's own result can be old, its editor
 * link long spent, when ChatGPT shows the card again after a reload; a call
 * the card makes gets a link minted for it. */
type Origin = "card" | "call";

/** What went wrong, named by its message in the widget's catalog so the card
 * draws it in whatever language the host speaks. */
export type CardProblem = { key: keyof Messages["chatgpt"]["widget"]["problems"]; name?: string };

/** A failure `receive` raises, carrying its problem to the caller's catch. */
class CardError extends Error {
  constructor(readonly problem: CardProblem["key"]) {
    super(problem);
  }
}

/** The host's theme, which the card and the editor it frames both wear. */
export type HostTheme = "light" | "dark";

/** The bands of the card the host draws over: its rail, its header, its
 * composer. The card keeps the editor out of the side and top bands and hands
 * the bottom one to the editor, which keeps its controls above it. */
export type HostEdges = { top: number; right: number; left: number };
const NO_EDGES: HostEdges = { top: 0, right: 0, left: 0 };

/** The page the frame shows after moving on its own: a project, or null on
 * the projects home. */
export type FramePage = { projectId: string | null; name: string | null };

/** What a frame link opens: a project id, or HOME for the projects home. No
 * project id is empty, so the two never collide. */
const HOME = "";
const openArgs = (target: string): Record<string, string> => (target === HOME ? {} : { projectId: target });

/** The host carries authentication; the iframe only calls the MCP Apps bridge. */
export function useProjectApp() {
  const appRef = useRef<App | null>(null);
  const epoch = useRef(0);
  const [ready, setReady] = useState(false);
  const [view, setView] = useState<ProjectView | null>(null);
  const [playback, setPlayback] = useState<Playback | null>(null);
  const [editor, setEditor] = useState<Editor | null>(null);
  const [fullscreen, setFullscreen] = useState(false);
  const [hostInset, setHostInset] = useState(0);
  const [edges, setEdges] = useState<HostEdges>(NO_EDGES);
  const [theme, setTheme] = useState<HostTheme>("light");
  const [editorRequest, setEditorRequest] = useState<string | null>(null);
  // Tied to the frame that reported it, so a new frame starts from its link.
  const [page, setPage] = useState<{ url: string } & FramePage | null>(null);
  const requested = useRef<string | null>(null);
  const reconnecting = useRef(false);
  const [error, setError] = useState<CardProblem | null>(null);
  const t = useTranslations("chatgpt.widget");
  const setLocale = useSetWidgetLocale();
  const [busy, setBusy] = useState(false);
  const [visible, setVisible] = useState(!document.hidden);
  const [pollMs, setPollMs] = useState(2000);
  const recoveries = useRef(0);

  const receive = useCallback((result: ToolResult, origin: Origin) => {
    if (result.isError) throw new CardError("requestFailed");
    const parsed = viewSchema.safeParse(result.structuredContent);
    if (!parsed.success) throw new CardError("unreadable");
    // An editable project is the editor and an editable projects view is the
    // projects home. A link is good for one minute, so the card's own result
    // counts it only inside that minute.
    const home = parsed.data.view === "projects" ? HOME : null;
    const editable = parsed.data.canEdit ? parsed.data.project?.id ?? home : null;
    const embed = editorSchema.safeParse(result._meta?.editor);
    const link = embed.success && (origin !== "card" || embed.data.expiresAt > Date.now()) ? embed.data : null;
    if (origin === "call" && editable !== null && !link) {
      throw new CardError("editorFailed");
    }
    const media = playbackSchema.safeParse(result._meta?.playback);
    const interval = result._meta?.pollMs;
    if (typeof interval === "number" && interval >= 1000 && interval <= 30000) setPollMs(interval);
    setView(parsed.data);
    setPlayback(media.success ? media.data : null);
    if (editable !== null && link) {
      setEditor((current) => current ?? link);
    }
    setEditorRequest(editable !== null && !link ? editable : null);
    setError(null);
  }, []);

  useEffect(() => {
    const app = new App({ name: "Donkey Cut preview", version: "1.0.0" }, {}, { strict: true });
    appRef.current = app;
    let live = true;
    app.ontoolresult = (result) => {
      if (!live) return;
      epoch.current++;
      recoveries.current = 0;
      setBusy(false);
      try { receive(result, "card"); } catch (e) { setError({ key: e instanceof CardError ? e.problem : "generic" }); }
    };
    // ChatGPT overlays its composer on the bottom of a fullscreen card and
    // reports the covered band as a safe-area inset; the editor frame gets
    // the number and keeps its own bottom controls above the band.
    const applyContext = (context: ReturnType<App["getHostContext"]>) => {
      if (!context) return;
      if (context.theme) {
        document.documentElement.dataset.theme = context.theme;
        setTheme(context.theme);
      }
      if (context.locale) setLocale(context.locale);
      const full = context.displayMode === "fullscreen";
      if (context.displayMode) setFullscreen(full);
      // Measured from ChatGPT's desktop fullscreen when the host reports no inset.
      setHostInset(full ? (context.safeAreaInsets?.bottom ?? 120) : 0);
      const insets = context.safeAreaInsets;
      setEdges(insets ? { top: insets.top, right: insets.right, left: insets.left } : NO_EDGES);
    };
    app.onhostcontextchanged = (context) => { applyContext({ ...app.getHostContext(), ...context }); };
    void app.connect().then(() => {
      if (!live) return;
      const context = app.getHostContext();
      console.debug("[donkeycut] host context", context);
      applyContext(context ?? { theme: "light" });
      setReady(true);
    }).catch(() => { if (live) setError({ key: "connect" }); });
    const visibility = () => setVisible(!document.hidden);
    document.addEventListener("visibilitychange", visibility);
    return () => {
      live = false;
      appRef.current = null;
      document.removeEventListener("visibilitychange", visibility);
      void app.close().catch(() => {});
    };
  }, [receive, setLocale]);

  const run = useCallback(async (name: string, args: Record<string, string>, manual = true, origin: Origin = "call") => {
    const app = appRef.current;
    if (!app || !ready) return;
    const current = ++epoch.current;
    if (manual) { recoveries.current = 0; setBusy(true); setError(null); }
    try {
      // The host rejects a failed call with its own error text; the card
      // shows its one sentence for that.
      const result = await app.callServerTool({ name, arguments: args }).catch((): ToolResult => ({ isError: true }));
      if (current === epoch.current && appRef.current === app) receive(result, origin);
    } catch (e) {
      if (current === epoch.current && appRef.current === app) setError({ key: e instanceof CardError ? e.problem : "generic" });
    } finally { if (current === epoch.current && appRef.current === app) setBusy(false); }
  }, [ready, receive]);

  // Only the preview card polls. An editable project is the editor, which
  // plays and exports on its own; a poll there would also drop the answer
  // to the editor's link request.
  const framed = Boolean(view?.canEdit && view.project);
  const projectId = view?.project?.id;
  const jobId = view?.preview?.id;
  const status = view?.preview?.status;
  useEffect(() => {
    if (!ready || !visible || busy || error || framed || !projectId || !jobId) return;
    const waiting = status === "queued" || status === "running";
    if (!waiting && !playback) return;
    const delay = waiting ? pollMs : Math.max(1000, playback!.expiresAt - Date.now() - 60000);
    const timeout = window.setTimeout(() => { void run("get_preview_status", { projectId, jobId }, false); }, delay);
    return () => window.clearTimeout(timeout);
  }, [ready, visible, busy, error, framed, projectId, jobId, status, playback, pollMs, run, view]);

  // The model sees the tool calls it made, never a project opened inside the
  // card, so the card tells it what the frame shows. "Make this square" then
  // edits the project on screen, e.g. one opened from the projects home.
  const reported = page && page.url === editor?.url ? page : null;
  const shownId = reported ? reported.projectId : projectId ?? null;
  const shownName = reported ? reported.name ?? (shownId === projectId ? view?.project?.name : null) : view?.project?.name;
  const framePage = useCallback((url: string, next: FramePage) => { setPage({ url, ...next }); }, []);
  useEffect(() => {
    const app = appRef.current;
    if (!app || !ready || !view || !app.getHostCapabilities()?.updateModelContext) {
      return;
    }
    // The projects home clears what the card said, so the composer carries no
    // chip until a project opens.
    if (!shownId) {
      void app.updateModelContext({ content: [] }).catch(() => {});
      return;
    }
    const named = shownName ? `"${shownName}" ` : "";
    const text = `The Donkey Cut card shows the project ${named}(projectId ${shownId}). Requests about this project or video mean this one.`;
    void app.updateModelContext({ content: [{ type: "text", text }], structuredContent: { projectId: shownId, name: shownName ?? null } }).catch(() => {});
  }, [ready, view, shownId, shownName]);

  const playbackFailed = useCallback(() => {
    if (!projectId || !jobId) return;
    if (recoveries.current++ >= 1) { setError({ key: "videoFailed" }); return; }
    setPlayback(null);
    void run("get_preview_status", { projectId, jobId }, false);
  }, [projectId, jobId, run]);

  const openLink = async (url: string) => {
    if (!appRef.current) return;
    try { const result = await appRef.current.openLink({ url }); if (result.isError) setError({ key: "openFailed" }); }
    catch { setError({ key: "openFailed" }); }
  };
  const openDonkey = () => { if (view?.project) void openLink(view.project.url); };
  /** The framed editor asking for a tab: opening the project on donkeycut.com,
   * and saving an export, which the card's sandbox blocks in the frame. */
  const openFromFrame = useCallback((url: string) => {
    void openLink(url);
  }, []);
  /** A captions file made inside the frame: its bytes go with the request, so
   * the host needs nothing from this origin to save it. */
  const saveFromFrame = useCallback(async (text: string, name: string, mimeType: string) => {
    const app = appRef.current;
    if (!app) return;
    try {
      const result = await app.downloadFile({
        contents: [{ type: "resource", resource: { uri: `file:///${name}`, mimeType, text } }],
      });
      if (result.isError) setError({ key: "saveFailed", name });
    } catch { setError({ key: "saveFailed", name }); }
  }, []);

  useEffect(() => {
    if (!ready || editorRequest === null || editor || requested.current === editorRequest) {
      return;
    }
    requested.current = editorRequest;
    void run("open_project", openArgs(editorRequest), false);
  }, [ready, editorRequest, editor, run]);
  /** A fresh one-use link replaces the frame and renews its session cookie,
   * on the page the frame was showing. */
  const retryEditor = () => {
    const target = reported ? reported.projectId ?? HOME : projectId ?? (view?.view === "projects" ? HOME : null);
    if (!ready || busy || reconnecting.current || target === null) {
      return;
    }
    reconnecting.current = true;
    requested.current = target;
    setEditorRequest(null);
    setEditor(null);
    void run("open_project", openArgs(target)).finally(() => { reconnecting.current = false; });
  };

  /** The way forward from a project the account no longer has: a new cloud
   * project, opened here in its place. Its result carries the editor link,
   * so it opens like any other. */
  const createProject = () => { void run("create_project", { name: t("untitled") }); };

  // The editor's own button asks for the whole window; the host grants what it supports.
  const requestFullscreen = useCallback(async () => {
    const app = appRef.current;
    if (!app) return;
    try {
      const result = await app.requestDisplayMode({ mode: "fullscreen" });
      const full = result.mode === "fullscreen";
      setFullscreen(full);
      setHostInset(full ? (app.getHostContext()?.safeAreaInsets?.bottom ?? 120) : 0);
    } catch { /* the inline card still works */ }
  }, []);
  return { ready, view, playback, editor, fullscreen, hostInset, edges, theme, error, busy, visible, run, playbackFailed, openDonkey, openFromFrame, saveFromFrame, requestFullscreen, retryEditor, createProject, framePage };
}