Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Hosted runs: a guest attaches a photo before sign-up, and the whole draft and run come back after it

Adarsh2da4d920a681
diff --git a/src/components/studio/attachments.ts b/src/components/studio/attachments.ts
index f665a785..9a609027 100644
--- a/src/components/studio/attachments.ts
+++ b/src/components/studio/attachments.ts
@@ -4,10 +4,11 @@ import { nanoid } from "nanoid";
import { createContext, useCallback, useContext, useEffect, useMemo, useRef } from "react";
import { toast } from "sonner";
import { useAskBeforeUpload } from "@/lib/api";
+import { dropHeld } from "@/lib/held-files";
import { MAX_KEYFRAMES } from "@/lib/catalog/keyframes";
import { acceptedKinds, addFrame, fitAttachments, noRoomMessage, onImageChange, placeAttachment, removeFrame, replaceAttachment } from "@/lib/composer";
import type { InputSlot, MediaKind } from "@/lib/catalog/types";
-import { fileToSlot, kindOfFile, type SlotValue } from "./media-slot";
+import { fileToSlot, heldSlot, kindOfFile, type SlotValue } from "./media-slot";
import { useStudio, type Draft, type SlotKey } from "./studio-context";
/**
@@ -17,11 +18,22 @@ import { useStudio, type Draft, type SlotKey } from "./studio-context";
*/
const inflight = new Map<string, { ac: AbortController; seen: boolean }>();
+/** A guest's kept files the draft has held (src/lib/held-files.ts): one taken out of the draft is forgotten too. */
+const heldSeen = new Set<string>();
+
/** Abort uploads whose attachment is gone from the draft. Mount once, where the draft is read. */
export function useUploadReaper(draft: Pick<Draft, "slots" | "refs" | "frames">) {
useEffect(() => {
+ const values = [...Object.values(draft.slots), ...draft.refs, ...(draft.frames ?? []).map((f) => f.value)];
+ const held = new Set(values.map((v) => v?.held).filter((x): x is string => !!x));
+ for (const id of held) heldSeen.add(id);
+ for (const id of heldSeen) {
+ if (held.has(id)) continue;
+ heldSeen.delete(id);
+ void dropHeld(id);
+ }
if (!inflight.size) return;
- const ids = new Set([...Object.values(draft.slots), ...draft.refs, ...(draft.frames ?? []).map((f) => f.value)].map((v) => v?.id).filter(Boolean));
+ const ids = new Set(values.map((v) => v?.id).filter(Boolean));
for (const [id, e] of inflight) {
if (ids.has(id)) e.seen = true;
else if (e.seen) {
@@ -44,9 +56,10 @@ const MAX_AT_ONCE = 8;
* id (never re-added if it was removed meanwhile). A file with no room (references full, or a
* model that takes none) is never uploaded: the person is told why instead. Someone whose upload
* would be refused (a guest, an account with neither its own GPU nor its own key) gets that card
- * at once, before any preview is placed.
+ * at once, before any preview is placed. With `hold` (a guest, hosted runs on), a file is kept in this browser
+ * instead of uploaded, until the guest signs up (src/lib/held-files.ts).
*/
-export function useAttach(slots: InputSlot[], refMax: number) {
+export function useAttach(slots: InputSlot[], refMax: number, { hold = false }: { hold?: boolean } = {}) {
const { config, draft, setDraft } = useStudio();
// The latest draft, to check for room before an upload starts (callbacks outlive renders).
const latest = useRef(draft);
@@ -58,6 +71,11 @@ export function useAttach(slots: InputSlot[], refMax: number) {
/** Upload a file: `place` runs once with the local preview, the result replaces it by id. */
const start = useCallback(
(file: File, place: (v: SlotValue) => void, kind?: MediaKind) => {
+ if (hold) {
+ const v = heldSlot(file, nanoid(8), kind);
+ if (v) place(v);
+ return;
+ }
if (askFirst()) return;
const id = nanoid(8);
const entry = { ac: new AbortController(), seen: false };
@@ -83,7 +101,7 @@ export function useAttach(slots: InputSlot[], refMax: number) {
{ signal: entry.ac.signal },
);
},
- [setDraft, askFirst],
+ [setDraft, askFirst, hold],
);
const kinds = useMemo(() => new Set<MediaKind>(acceptedKinds(slots, config.multiRef)), [slots, config.multiRef]);
@@ -119,7 +137,7 @@ export function useAttach(slots: InputSlot[], refMax: number) {
const attachFiles = useCallback(
(files: File[]) => {
// A paste, a drop on the page or the "+" menu: one card for the lot, and no toast about kinds or room on top.
- if (askFirst()) return;
+ if (!hold && askFirst()) return;
const frames = latest.current.frames;
// Frames mode: each still becomes the next frame, up to ten.
const usable = files.filter((f) => (frames ? kindOfFile(f) === "image" : kinds.has(kindOfFile(f))));
@@ -137,7 +155,7 @@ export function useAttach(slots: InputSlot[], refMax: number) {
if (rejected.length) noRoom();
for (const i of placed) start(batch[i], place);
},
- [askFirst, kinds, start, place, noRoom, slots, config.multiRef, refMax],
+ [askFirst, hold, kinds, start, place, noRoom, slots, config.multiRef, refMax],
);
/** A slot tile: replace its value (an upload it held is cancelled by the reaper). A drawing belongs to the image it was made on. */
diff --git a/src/components/studio/audio-controls.tsx b/src/components/studio/audio-controls.tsx
index ff659128..cb15bb30 100644
--- a/src/components/studio/audio-controls.tsx
+++ b/src/components/studio/audio-controls.tsx
@@ -72,7 +72,8 @@ export function VoicePicker({
setOpen(false);
};
// Someone whose upload would be refused (a guest, an account with no GPU or key) gets its card, not the file chooser.
- const askFirst = useAskBeforeUpload();
+ // (A voice sample is uploaded as it is picked: a guest signs up first, even where a studio keeps its pictures.)
+ const askFirst = useAskBeforeUpload({ hold: false });
const clean = useMaybeClean();
const upload = () => {
if (!askFirst()) return file.current?.click();
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index 79cd2737..8bd94fbf 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -4,7 +4,7 @@ import { OrbitPad, orbitOptions } from "@/components/studio/orbit-pad";
import { ArrowUp, AtSign, Cloud, Cpu, GalleryHorizontalEnd, LayoutDashboard, Loader2, Sparkles, X } from "lucide-react";
import dynamic from "next/dynamic";
import Link from "next/link";
-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { flushSync } from "react-dom";
import { toast } from "sonner";
import { openAddKey } from "@/components/keys/your-keys";
@@ -22,10 +22,13 @@ import { formatsOf } from "@/lib/av/formats";
import { poolRunState, quoteBody, useHostedQuote, useSettled, type RunOn } from "@/lib/hosted";
import { PoolNote } from "./pool-note";
import { poolRunsModel } from "@/lib/pool-rules";
+import { HoldFilesCtx } from "@/lib/held-files";
+import { pendingStep } from "@/lib/guest-draft";
+import { useGuestDraft } from "./guest-draft";
import { ExactOrbitControls } from "@/components/exact-orbit-controls";
import { useFlyAround } from "@/components/fly-around-run";
import { exactDefaults, takesExact, type ExactOrbit } from "@/lib/exact-orbit";
-import { CONNECT_GPU_EVENT, enhance, useClipFacts, useCreateGeneration, useElements, useEngine, useHydrated, useIsOwner, useLikelyVisitor, useStatus } from "@/lib/api";
+import { askToSignUp, CONNECT_GPU_EVENT, enhance, useClipFacts, useCreateGeneration, useElements, useEngine, useHydrated, useIsOwner, useLikelyVisitor, useStatus } from "@/lib/api";
import { usePagePlace } from "@/components/gpu/use-page-place";
import { applyMentions, elementsNote, type StudioElement } from "@/lib/catalog/elements";
import { applySketch, stripMotionPaths } from "@/lib/catalog/sketch";
@@ -270,7 +273,7 @@ export function Composer({ docked }: { docked: boolean }) {
// Upscale hub: the attached clip's header (length, size, frame rate). Its length prices per-second tools and
// travels with the request (params.sourceDuration), with its rate for a route billed by frames (params.sourceFps);
// a clip swapped since a Reuse never keeps the old one's.
- const facts = useClipFacts(config.clipFacts && !typed.slots.video?.uploading ? typed.slots.video?.ref : undefined).data;
+ const facts = useClipFacts(config.clipFacts && !typed.slots.video?.uploading && !typed.slots.video?.held ? typed.slots.video?.ref : undefined).data;
// Regenerate · creative needs words: a clip with none (an upload) can have Fuobe's reading model on your GPU describe it,
// into the prompt box to edit before the run. A second instance, so the composer's own Generate state isn't touched.
const describeRun = useCreateGeneration();
@@ -279,7 +282,7 @@ export function Composer({ docked }: { docked: boolean }) {
useEffect(() => () => describeAlive.current?.abort(), []);
// Lipsync: a talking avatar is as long as its voice (the voice's header prices it and goes with the request); not while a
// video is attached (lip re-sync keeps the clip's length).
- const voiceRef = config.voiceFacts && !typed.slots.video?.ref && !typed.slots.audio?.uploading ? typed.slots.audio?.ref : undefined;
+ const voiceRef = config.voiceFacts && !typed.slots.video?.ref && !typed.slots.audio?.uploading && !typed.slots.audio?.held ? typed.slots.audio?.ref : undefined;
const voice = useClipFacts(voiceRef).data;
// "Clean the voice first" (Transcribe, Lipsync): the recording or the video's speech apart from its music and effects
// before the model hears it. On for a video's speech on your GPU, off for a recording (src/lib/av/voice-first.ts).
@@ -551,7 +554,13 @@ export function Composer({ docked }: { docked: boolean }) {
: config.multiRef.kind === "video"
? Math.min(config.multiRef.max, model?.engine === "open" ? 4 : config.multiRef.max)
: Math.min(config.multiRef.max, Math.max(0, ((model ? imageLimit(model, refOp) : opts.maxImages) ?? 1) - slots.filter((s) => s.accept === "image").length));
- const attach = useAttach(slots, refMax);
+ // Hosted runs on, a guest's files are kept in this browser until sign-up (HoldFilesForGuests), and its whole draft and
+ // the run it pressed come back after it (useGuestDraft).
+ const guestHold = useContext(HoldFilesCtx);
+ const attach = useAttach(slots, refMax, { hold: guestHold });
+ const guestDraft = useGuestDraft({ hold: guestHold, viewer: status?.viewer?.kind, draft: typed, setDraft });
+ // The price changed since its guest pressed Run: said once, and Run waits for a click.
+ const [priceNote, setPriceNote] = useState<string | null>(null);
// Frames mode (Video studio): up to 10 stills at their times, as the picked model can take them.
const framesOn = !!config.frames && !!draft.frames;
@@ -614,8 +623,12 @@ export function Composer({ docked }: { docked: boolean }) {
const runOn: RunOn = runOnPick ?? (ownOnline && viewerInfo?.prefer !== "pool" ? "own" : "pool");
const hostedHere = !!viewerInfo?.hosted && model?.engine === "open";
const poolPrice = hostedHere && runOn === "pool";
- const priceBody = useSettled(poolPrice ? quoteBody(signed.request, runOn) : null);
- const hostedCheck = useHostedQuote(priceBody).data;
+ const wantPrice = poolPrice ? quoteBody(signed.request, runOn) : null;
+ const priceBody = useSettled(wantPrice);
+ const priceQuery = useHostedQuote(priceBody);
+ const hostedCheck = priceQuery.data;
+ // The price check has answered for the draft as it is now (not one typed a moment ago).
+ const priceSettled = !wantPrice || (priceBody === wantPrice && priceQuery.isFetched && !priceQuery.isFetching);
const hostedQuote = hostedCheck?.quote;
// The price check's answer: refused (busy, a limit, not offered here, paused…), Run is off and says why; otherwise
// the price, and where the run would stand in line with the wait.
@@ -770,6 +783,13 @@ export function Composer({ docked }: { docked: boolean }) {
return;
}
toast.dismiss("composer-blocker");
+ setPriceNote(null);
+ // A guest (hosted runs on): the draft, its kept files and this run wait for the sign-up, with the price shown; back
+ // here as an account, the run starts by itself when the price is unchanged.
+ if (guestHold) {
+ guestDraft.keepRun(poolPrice && hostedQuote?.allowed ? { amount: hostedQuote.amount, priceVersion: hostedQuote.priceVersion, text: hostedQuote.text } : null);
+ return askToSignUp("run");
+ }
setRecent((r) => pushRecent(r, draft.modelId));
// The server resolves @mentions and drawings itself; only pin the operation when there are none.
// No "Queued" toast: the new card (and the "1 generating ↑" pill when it's off-screen) says it.
@@ -965,6 +985,20 @@ export function Composer({ docked }: { docked: boolean }) {
});
const settling = !catalog.ready || presetLoading || uploading || (needsFull && !catalog.complete);
const step = startRequest ? startStep({ settling, blocker }) : "wait";
+
+ // Back from sign-up with the run its guest pressed: once the draft, its files and the price check have settled, it
+ // starts by itself when the price is the one the guest saw; otherwise the new price shows and Run waits for a click.
+ // Something missing (a file that didn't come back) leaves it to the blocker's line.
+ const pendingRun = guestDraft.pending;
+ const clearPending = guestDraft.clearPending;
+ useEffect(() => {
+ if (!pendingRun) return;
+ const next = pendingStep({ settled: !settling && priceSettled, blocked: !!blocker, pool: poolPrice, shown: pendingRun.shown, quote: hostedQuote });
+ if (next === "wait") return;
+ clearPending();
+ if (next === "start") submitRef.current();
+ else if (next === "note" && hostedQuote) setPriceNote(`The price is now ${hostedQuote.text}. Press Generate to start.`);
+ }, [pendingRun, clearPending, settling, priceSettled, blocker, poolPrice, hostedQuote]);
const blockedSlot = blocker?.slot;
useEffect(() => {
if (step === "wait" || startRequest <= startedFor.current) return;
@@ -1673,6 +1707,11 @@ export function Composer({ docked }: { docked: boolean }) {
)}
{/* Folded (docked, not focused), the composer stays one line: the wait shows again once it opens. */}
{!blocker && !gpuSetup && poolState && (poolState.refused || !collapsed) && <PoolNote state={poolState} />}
+ {!blocker && priceNote && !poolRefused && (
+ <p data-price-note className="px-2 text-[12px] font-medium text-foreground">
+ {priceNote}
+ </p>
+ )}
{!blocker && gpuSetup && (
<p className="px-2 text-[12px] text-muted-foreground">
<button
diff --git a/src/components/studio/guest-draft.ts b/src/components/studio/guest-draft.ts
new file mode 100644
index 00000000..17a5347f
--- /dev/null
+++ b/src/components/studio/guest-draft.ts
@@ -0,0 +1,69 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { clearDraft, readDraft, restoredDraft, saveDraft, savePendingRun, takePendingRun, type PendingRun, type ShownPrice } from "@/lib/guest-draft";
+import { replaceAttachment } from "@/lib/composer";
+import { readHeld } from "@/lib/held-files";
+import { uploadHeld, type SlotValue } from "./media-slot";
+import type { Draft } from "./studio-context";
+
+/**
+ * A guest's whole draft through sign-up (hosted runs on; src/lib/guest-draft.ts), for the studio composer:
+ * - a guest whose files are kept in this browser (`hold`) has the draft saved for this page as it changes;
+ * - once who is looking is known, a saved draft comes back (its kept files with fresh previews); for an account (just
+ * signed up) its kept files are uploaded as the account's own, and the run its guest pressed is handed back (`pending`)
+ * for the composer to start once the price check agrees.
+ * Nothing happens for the owner, nor for a guest with hosted runs off (nothing is saved for them).
+ */
+export function useGuestDraft({ hold, viewer, draft, setDraft }: { hold: boolean; viewer: "guest" | "account" | undefined; draft: Draft; setDraft: (patch: Partial<Draft> | ((d: Draft) => Partial<Draft>)) => void }) {
+ const path = useRef<string | null>(null);
+ useEffect(() => {
+ path.current = window.location.pathname;
+ }, []);
+
+ const [pending, setPending] = useState<PendingRun | null>(null);
+ const restored = useRef(false);
+ useEffect(() => {
+ if (restored.current || !viewer || !path.current) return;
+ restored.current = true;
+ const here = path.current;
+ if (viewer === "account") {
+ const run = takePendingRun(here);
+ if (run) setPending(run);
+ }
+ const kept = readDraft<Draft>(here);
+ if (!kept) return;
+ // Back as an account: the draft is its own from here on (saved no more), and its kept files go up now.
+ const account = viewer === "account";
+ if (account) clearDraft(here);
+ const { draft: draftNow, held } = restoredDraft(kept, account) as { draft: Draft; held: SlotValue[] };
+ // A prompt the link brought (?prompt=) wins over the saved words, as it does for the words kept per page.
+ setDraft((d) => ({ ...draftNow, prompt: d.prompt || draftNow.prompt }));
+ const swap = (id: string | undefined, v: SlotValue | null) => id && setDraft((d) => replaceAttachment(d, id, v) ?? {});
+ for (const v of held) {
+ if (account) {
+ void uploadHeld(v).then((up) => swap(v.id, up));
+ continue;
+ }
+ // Still a guest: the kept file shows again (a file the browser no longer has leaves the draft).
+ void readHeld(v.held!).then((file) => swap(v.id, file ? { ...v, preview: URL.createObjectURL(file) } : null));
+ }
+ }, [viewer, setDraft]);
+
+ // Saved as it changes, while the guest's files are kept here (never before a saved draft was read back).
+ useEffect(() => {
+ if (hold && restored.current && path.current) saveDraft(path.current, draft as unknown as Parameters<typeof saveDraft>[1]);
+ }, [hold, draft]);
+
+ /** A guest pressed Run: the draft and the run (with the price it showed) wait for the sign-up. */
+ const keepRun = useCallback(
+ (shown: ShownPrice) => {
+ if (!path.current) return;
+ saveDraft(path.current, draft as unknown as Parameters<typeof saveDraft>[1]);
+ savePendingRun(path.current, shown);
+ },
+ [draft],
+ );
+
+ return { pending, clearPending: useCallback(() => setPending(null), []), keepRun };
+}
diff --git a/src/components/studio/hold-files.tsx b/src/components/studio/hold-files.tsx
new file mode 100644
index 00000000..adcfbae8
--- /dev/null
+++ b/src/components/studio/hold-files.tsx
@@ -0,0 +1,14 @@
+"use client";
+
+import { useHydrated, useStatus } from "@/lib/api";
+import { HoldFilesCtx } from "@/lib/held-files";
+
+/**
+ * Around a studio composer: with hosted runs on, a guest's files are kept in this browser until sign-up instead of
+ * opening "Create a free account" (src/lib/held-files.ts). Off, and for anyone signed in, nothing changes.
+ */
+export function HoldFilesForGuests({ children }: { children: React.ReactNode }) {
+ const hydrated = useHydrated();
+ const v = useStatus().data?.viewer;
+ return <HoldFilesCtx.Provider value={hydrated && v?.kind === "guest" && !!v.hosted}>{children}</HoldFilesCtx.Provider>;
+}
diff --git a/src/components/studio/media-slot.tsx b/src/components/studio/media-slot.tsx
index 17996677..8e14fe5d 100644
--- a/src/components/studio/media-slot.tsx
+++ b/src/components/studio/media-slot.tsx
@@ -12,7 +12,8 @@ import { signInHref, useAskBeforeUpload, useAssets, useIsGuest, type Asset } fro
import { toastError } from "@/lib/refusals";
import { postFile } from "@/lib/upload";
import type { MediaKind } from "@/lib/catalog/types";
-import { slotCaption } from "@/lib/composer";
+import { PLACEHOLDER, slotCaption } from "@/lib/composer";
+import { dropHeld, holdFile, readHeld } from "@/lib/held-files";
import { cn } from "@/lib/utils";
import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import type { SketchMode, Stroke } from "./sketch-editor";
@@ -26,6 +27,11 @@ export interface SlotValue {
kind: MediaKind;
name?: string;
uploading?: boolean;
+ /**
+ * A guest's file kept in this browser until sign-up (hosted runs on; src/lib/held-files.ts), by its kept id: `ref` is a
+ * stand-in until it is uploaded as the new account's own.
+ */
+ held?: string;
/** Picked from the library: whether it was an upload or a result made here. */
source?: "upload" | "generation";
/** Drawings and masks: the strokes they were made from, so the editor reopens them (in image pixels). */
@@ -101,6 +107,44 @@ export async function fileToSlot(file: File, onChange: (v: SlotValue | null) =>
}
}
+/**
+ * A guest's file kept in this browser until sign-up (hosted runs on): its tile at once, with a stand-in ref for the price
+ * check, and the file kept under `id` (held-files.ts). Null, said in a toast, for a file over the size limit.
+ */
+export function heldSlot(file: File, id: string, kind?: MediaKind): SlotValue | null {
+ if (file.size > MAX_MB * 1024 * 1024) {
+ toast.error(`That file's over ${MAX_MB} MB. Try a smaller one.`);
+ return null;
+ }
+ const k: MediaKind = kind ?? kindOfFile(file);
+ void holdFile(id, file);
+ return { id, ref: PLACEHOLDER[k], preview: URL.createObjectURL(file), kind: k, name: file.name, held: id };
+}
+
+/**
+ * Upload a guest's kept file now that it has an account: the value as the server keeps it, or null when the file is gone
+ * or the upload was refused (said in a toast). The kept copy is dropped once it is uploaded.
+ */
+export async function uploadHeld(v: SlotValue): Promise<SlotValue | null> {
+ const file = v.held ? await readHeld(v.held) : null;
+ if (!file) {
+ toast(`Add ${v.name ? `“${v.name}”` : "your file"} again: it wasn't kept through sign-up.`);
+ return null;
+ }
+ try {
+ const asset = await upload(file);
+ if (asset.kind && asset.kind !== v.kind) {
+ toast.error(wrongKindMessage(v.kind));
+ return null;
+ }
+ void dropHeld(v.held!);
+ return { ...(v.sketch && { sketch: v.sketch }), ...(v.id && { id: v.id }), ref: asset.url, preview: asset.url, kind: asset.kind ?? v.kind, name: v.name };
+ } catch (e) {
+ toastError(e, "Upload failed. Please try again.");
+ return null;
+ }
+}
+
/**
* Upload into a list kept in React state (reference photos, a storyboard's looks): appended once
* with its preview, then replaced by id when the upload finishes, or dropped if it fails. A file
diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsx
index 4db58766..a81bb2b8 100644
--- a/src/components/studio/studio-page.tsx
+++ b/src/components/studio/studio-page.tsx
@@ -26,6 +26,7 @@ import { cn } from "@/lib/utils";
import { ComposerBridgeCtx, useComposerBridge, type ComposerBridge } from "./attachments";
import { CatalogProvider, useCatalog } from "./catalog";
import { Composer } from "./composer";
+import { HoldFilesForGuests } from "./hold-files";
import { EngineSwitch } from "./engine-switch";
import { HubHeaderExtras, useInHub } from "./hub-chrome";
import { Feed } from "./feed";
@@ -642,7 +643,9 @@ function StudioBody({ header, tabs, examples }: { header?: React.ReactNode; tabs
</div>
)}
<div data-composer className={cn("mx-auto w-full", hasItems ? "max-w-[800px]" : "max-w-[760px]")}>
- <Composer docked={hasItems} />
+ <HoldFilesForGuests>
+ <Composer docked={hasItems} />
+ </HoldFilesForGuests>
</div>
</div>
diff --git a/src/lib/api.ts b/src/lib/api.ts
index b7b0e458..a89319d7 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -1,7 +1,7 @@
"use client";
import { keepPreviousData, useInfiniteQuery, useMutation, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";
-import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
+import { useCallback, useContext, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
import { toast } from "sonner";
import type { AssistThread, AssistThreadSummary, AssistThreadView } from "./assist";
import type { OwnerGpuView, TestProvider } from "./connections";
@@ -30,6 +30,7 @@ import { cursorAfter, filterToSearch, type AssetUse, type FeedFilter, type Folde
import { markRefusalShown, refusalShown, responseError } from "./refusals";
import { PLACE_ASK_HEADER, RUNS_CHANGED_EVENT } from "./guest-access";
import type { PoolRules } from "./pool-rules";
+import { HoldFilesCtx } from "./held-files";
import { postFile } from "./upload";
import type { ShareCreated, ShareInfo, ShareListItem, SharePatch, ShareRequest } from "./share";
import type { AccessSummary } from "./model-access";
@@ -1364,19 +1365,23 @@ export function askToSignUp(action: RefusalAction = "upload"): void {
* GPU or add a key". The function returns true when it asked (the chooser stays shut, the file stays out), and false
* for anyone the upload takes, and while who is looking isn't known yet (the server's refusal opens the same card).
* `action` "run" asks the same way before a run of a picture already on the site (a GPU-only tool's hand-off).
+ * In a studio composer that keeps a guest's files in the browser until sign-up (HoldFilesCtx, hosted runs on), a guest's
+ * file is taken (it isn't uploaded); `hold: false` asks anyway (a voice sample, which only an account's upload takes).
*/
-export function useAskBeforeUpload({ gpuOnly = false }: { gpuOnly?: boolean } = {}): (action?: RefusalAction) => boolean {
+export function useAskBeforeUpload({ gpuOnly = false, hold = true }: { gpuOnly?: boolean; hold?: boolean } = {}): (action?: RefusalAction) => boolean {
const guest = useIsGuest();
+ const holds = useContext(HoldFilesCtx) && hold;
const seen = useStatus().data?.viewer;
// With hosted runs on, an account adds pictures for runs on this studio's GPUs: the upload says if a kind isn't taken.
// A GPU-only tool (gpuOnly) asks for the GPU even when the account has a key: no key runs it.
const nowhere = seen?.kind === "account" && !seen.gpu.connected && (gpuOnly || !seen.keys?.length) && !seen.hosted;
return useCallback((action: RefusalAction = "upload") => {
+ if (guest && holds && action === "upload") return false;
if (guest) askToSignUp(action);
else if (nowhere) window.dispatchEvent(new CustomEvent<ConnectGpuDetail>(CONNECT_GPU_EVENT, { detail: { action, ...(gpuOnly && { gpuOnly }) } }));
else return false;
return true;
- }, [guest, nowhere, gpuOnly]);
+ }, [guest, holds, nowhere, gpuOnly]);
}
/**
diff --git a/src/lib/guest-draft.ts b/src/lib/guest-draft.ts
new file mode 100644
index 00000000..c962b07a
--- /dev/null
+++ b/src/lib/guest-draft.ts
@@ -0,0 +1,152 @@
+import type { MediaKind } from "./catalog/types";
+
+/**
+ * A guest's whole studio draft through sign-up (hosted runs on): the words, the model and its settings, the preset and
+ * the files attached (kept in this browser: held-files.ts), saved in this tab's sessionStorage per page. Run pressed by a
+ * guest also saves the run itself with the price it showed: back on the same page as an account, the studio restores
+ * the draft, uploads the kept files as the account's own, and starts the run by itself when the price is unchanged;
+ * otherwise it shows the new price and waits for a click.
+ */
+
+/** An attachment as the studio draft keeps it (src/components/studio/media-slot.tsx SlotValue). */
+export interface DraftValue {
+ id?: string;
+ ref: string;
+ preview: string;
+ kind: MediaKind;
+ name?: string;
+ uploading?: boolean;
+ /** Kept in this browser until the guest signs up (held-files.ts): `ref` is a stand-in until it is uploaded. */
+ held?: string;
+ source?: "upload" | "generation";
+ sketch?: unknown;
+}
+
+/** The parts of a studio draft that hold attachments; everything else is kept as it is. */
+export interface DraftLike<V extends DraftValue = DraftValue> {
+ slots: Partial<Record<string, V | null>>;
+ refs: V[];
+ frames?: { value: V; at: number }[];
+}
+
+/** Every attachment of a draft passed through `fn` (null takes it out: an empty slot, a reference or a frame gone). */
+export function mapValues<D extends DraftLike>(d: D, fn: (v: D["refs"][number]) => D["refs"][number] | null): D {
+ const slots = Object.fromEntries(Object.entries(d.slots).map(([k, v]) => [k, v ? fn(v) : v])) as D["slots"];
+ const refs = d.refs.map(fn).filter((v): v is D["refs"][number] => !!v);
+ const frames = d.frames?.flatMap((f) => {
+ const v = fn(f.value);
+ return v ? [{ ...f, value: v }] : [];
+ });
+ return { ...d, slots, refs, ...(d.frames && { frames }) };
+}
+
+/** The attachments a draft keeps in this browser, by kept-file id. */
+export function heldValues(d: DraftLike): DraftValue[] {
+ const out: DraftValue[] = [];
+ mapValues(d, (v) => (v.held && out.push(v), v));
+ return out;
+}
+
+/**
+ * A draft as it is saved: a kept file without its preview (a page address that dies with the page), and an upload that
+ * hasn't finished taken out (nothing of it would be there after a reload).
+ */
+export function keepDraft<D extends DraftLike>(d: D): D {
+ return mapValues(d, (v) => (v.held ? { ...v, preview: "", uploading: undefined } : v.uploading || v.preview.startsWith("blob:") ? null : v));
+}
+
+const DAY = 24 * 60 * 60_000;
+const draftKey = (path: string) => `fuobe:guest-draft:${path}`;
+const PENDING_KEY = "fuobe:pending-run";
+
+function store(): Storage | null {
+ try {
+ return typeof sessionStorage === "undefined" ? null : sessionStorage;
+ } catch {
+ return null;
+ }
+}
+
+/** Save a guest's draft for this page. Never throws (a full or blocked storage keeps nothing). */
+export function saveDraft(path: string, d: DraftLike & Record<string, unknown>): void {
+ try {
+ store()?.setItem(draftKey(path), JSON.stringify({ at: Date.now(), draft: keepDraft(d) }));
+ } catch {}
+}
+
+/** The draft saved for this page within a day, or null. */
+export function readDraft<D extends DraftLike>(path: string): D | null {
+ try {
+ const raw = store()?.getItem(draftKey(path));
+ if (!raw) return null;
+ const kept = JSON.parse(raw) as { at?: number; draft?: D };
+ if (!kept.draft || !kept.at || Date.now() - kept.at > DAY) return null;
+ return kept.draft;
+ } catch {
+ return null;
+ }
+}
+
+export function clearDraft(path: string): void {
+ try {
+ store()?.removeItem(draftKey(path));
+ } catch {}
+}
+
+/** The price a guest's run showed when Run was pressed (null: none to compare, so it never starts by itself). */
+export type ShownPrice = { amount: number; priceVersion: string; text: string } | null;
+
+export interface PendingRun {
+ path: string;
+ shown: ShownPrice;
+ at: number;
+}
+
+/** A guest pressed Run here: kept for this tab, to start once signed up. */
+export function savePendingRun(path: string, shown: ShownPrice): void {
+ try {
+ store()?.setItem(PENDING_KEY, JSON.stringify({ path, shown, at: Date.now() } satisfies PendingRun));
+ } catch {}
+}
+
+/** The run pressed on this page within the hour, taken (it starts at most once), or null. */
+export function takePendingRun(path: string): PendingRun | null {
+ try {
+ const s = store();
+ const raw = s?.getItem(PENDING_KEY);
+ if (!raw) return null;
+ const p = JSON.parse(raw) as PendingRun;
+ if (p.path !== path) return null;
+ s!.removeItem(PENDING_KEY);
+ return Date.now() - p.at < 60 * 60_000 ? p : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Is the price now the one the guest saw (the same amount and the same words)? Then the run starts by itself. */
+export function priceUnchanged(shown: ShownPrice, now: { allowed: boolean; amount: number; text: string } | undefined): boolean {
+ return !!shown && !!now && now.allowed && now.amount === shown.amount && now.text === shown.text;
+}
+
+/**
+ * A saved draft as it comes back: its kept files listed (to show again for a guest, or to upload for an account), each
+ * without a preview until its file is read, and marked uploading for an account so Run waits for them.
+ */
+export function restoredDraft<D extends DraftLike>(kept: D, account: boolean): { draft: D; held: DraftValue[] } {
+ const held: DraftValue[] = [];
+ const draft = mapValues(kept, (v) => (v.held ? (held.push(v), { ...v, preview: "", uploading: account || undefined }) : v));
+ return { draft, held };
+}
+
+/**
+ * What the run a guest pressed does once back as an account: wait (the draft, its files or the price check haven't
+ * settled), start (the price is the one the guest saw), note (a new price: shown, and Run waits for a click), or none
+ * (something is missing, which the blocker says; or no price was shown to compare).
+ */
+export function pendingStep(o: { settled: boolean; blocked: boolean; pool: boolean; shown: ShownPrice; quote?: { allowed: boolean; amount: number; text: string } }): "wait" | "start" | "note" | "none" {
+ if (!o.settled) return "wait";
+ if (o.blocked || !o.pool) return "none";
+ if (priceUnchanged(o.shown, o.quote)) return "start";
+ return o.shown && o.quote?.allowed && o.quote.text ? "note" : "none";
+}
diff --git a/src/lib/held-files.ts b/src/lib/held-files.ts
new file mode 100644
index 00000000..2e6e2442
--- /dev/null
+++ b/src/lib/held-files.ts
@@ -0,0 +1,97 @@
+"use client";
+
+import { createContext } from "react";
+
+/**
+ * Files a guest attaches before signing up (hosted runs on): kept in this browser, never uploaded, until the guest has an
+ * account. They live in IndexedDB, so they survive the sign-up page and the reload after it (the studio then uploads them
+ * as the new account's own files); where IndexedDB isn't there (a private window), in this page's memory only. A file
+ * kept for more than a day is dropped.
+ */
+
+const DB = "fuobe-held-files";
+const STORE = "files";
+const MAX_AGE_MS = 24 * 60 * 60_000;
+
+/** The studio composer holds a guest's files this way (useAskBeforeUpload then opens no sign-up card for them). */
+export const HoldFilesCtx = createContext(false);
+
+declare global {
+ var __fuobeHeldFiles: Map<string, File> | undefined;
+}
+
+const memory = () => (globalThis.__fuobeHeldFiles ??= new Map());
+
+function open(): Promise<IDBDatabase | null> {
+ return new Promise((resolve) => {
+ try {
+ if (typeof indexedDB === "undefined") return resolve(null);
+ const req = indexedDB.open(DB, 1);
+ req.onupgradeneeded = () => req.result.createObjectStore(STORE);
+ req.onsuccess = () => resolve(req.result);
+ req.onerror = () => resolve(null);
+ req.onblocked = () => resolve(null);
+ } catch {
+ resolve(null);
+ }
+ });
+}
+
+async function withStore<T>(mode: IDBTransactionMode, fn: (s: IDBObjectStore) => IDBRequest<T>): Promise<T | null> {
+ const db = await open();
+ if (!db) return null;
+ return new Promise((resolve) => {
+ try {
+ const tx = db.transaction(STORE, mode);
+ const req = fn(tx.objectStore(STORE));
+ req.onsuccess = () => resolve(req.result);
+ req.onerror = () => resolve(null);
+ tx.oncomplete = () => db.close();
+ } catch {
+ db.close();
+ resolve(null);
+ }
+ });
+}
+
+/** Keep a file under `id` until the guest signs up (or for a day). Never throws. */
+export async function holdFile(id: string, file: File): Promise<void> {
+ memory().set(id, file);
+ await withStore("readwrite", (s) => s.put({ file, name: file.name, type: file.type, at: Date.now() }, id));
+ void dropOldHeld();
+}
+
+/** A kept file, or null when it is gone (cleared by the browser, older than a day, never kept here). */
+export async function readHeld(id: string): Promise<File | null> {
+ const mem = memory().get(id);
+ if (mem) return mem;
+ const row = (await withStore("readonly", (s) => s.get(id) as IDBRequest<{ file: Blob; name: string; type: string; at: number } | undefined>)) ?? null;
+ if (!row || Date.now() - row.at > MAX_AGE_MS) return null;
+ return row.file instanceof File ? row.file : new File([row.file], row.name, { type: row.type });
+}
+
+/** Forget a kept file (uploaded, or taken out of the draft). */
+export async function dropHeld(id: string): Promise<void> {
+ memory().delete(id);
+ await withStore("readwrite", (s) => s.delete(id));
+}
+
+/** Forget every kept file older than a day. */
+async function dropOldHeld(): Promise<void> {
+ const db = await open();
+ if (!db) return;
+ try {
+ const tx = db.transaction(STORE, "readwrite");
+ const cursor = tx.objectStore(STORE).openCursor();
+ cursor.onsuccess = () => {
+ const c = cursor.result;
+ if (!c) return;
+ const at = (c.value as { at?: number } | undefined)?.at ?? 0;
+ if (Date.now() - at > MAX_AGE_MS) c.delete();
+ c.continue();
+ };
+ tx.oncomplete = () => db.close();
+ } catch {
+ db.close();
+ }
+}
diff --git a/tests/hosted-guest-draft.test.ts b/tests/hosted-guest-draft.test.ts
new file mode 100644
index 00000000..e23c5af4
--- /dev/null
+++ b/tests/hosted-guest-draft.test.ts
@@ -0,0 +1,174 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { createElement, type ReactNode } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+/*
+ * A guest on a studio with hosted runs on: a photo can be attached before sign-up (kept in this browser, never uploaded),
+ * the whole draft (words, settings, files) survives sign-up, and the run the guest pressed starts by itself once back as
+ * an account when the price is unchanged; otherwise the new price shows and Run waits. With hosted runs off a guest's
+ * file still opens "Create a free account", as before.
+ */
+
+/** This tab's storage, as a browser keeps it. */
+class MemoryStorage {
+ private m = new Map<string, string>();
+ getItem = (k: string) => this.m.get(k) ?? null;
+ setItem = (k: string, v: string) => void this.m.set(k, String(v));
+ removeItem = (k: string) => void this.m.delete(k);
+ clear = () => this.m.clear();
+}
+const storage = new MemoryStorage();
+vi.stubGlobal("sessionStorage", storage);
+const events: string[] = [];
+const win = new EventTarget();
+win.addEventListener("fuobe:guest-prompt", (e) => events.push(`guest:${(e as CustomEvent<{ action?: string }>).detail?.action}`));
+vi.stubGlobal("window", win);
+
+const draftLib = await import("@/lib/guest-draft");
+const held = await import("@/lib/held-files");
+const { heldSlot, uploadHeld } = await import("@/components/studio/media-slot");
+const { useAskBeforeUpload } = await import("@/lib/api");
+const { PLACEHOLDER } = await import("@/lib/composer");
+
+const png = (name = "me.png") => new File([new Uint8Array([137, 80, 78, 71])], name, { type: "image/png" });
+const value = (o: Record<string, unknown> = {}) => ({ id: "v1", ref: "/api/files/uploads/a.png", preview: "/api/files/uploads/a.png", kind: "image" as const, ...o });
+type Kept = import("@/lib/guest-draft").DraftLike & { prompt: string; params: Record<string, unknown>; presetId?: string } & Record<string, unknown>;
+const draft = (o: Record<string, unknown> = {}): Kept => ({ prompt: "a fox", negativePrompt: "", modelId: "oss-z-image-turbo", params: { aspectRatio: "1:1" }, slots: {}, refs: [], presetOptions: {}, ...o }) as Kept;
+
+beforeEach(() => {
+ storage.clear();
+ events.length = 0;
+});
+afterEach(() => vi.restoreAllMocks());
+
+describe("the draft a guest keeps through sign-up", () => {
+ it("keeps everything: the words, the model, its settings and its files (a kept file without its page-only preview)", () => {
+ const d = draft({
+ presetId: "motion-orbit",
+ slots: { image: value({ id: "h1", held: "h1", ref: PLACEHOLDER.image, preview: "blob:http://localhost/1" }), endImage: value({ id: "u1", uploading: true, preview: "blob:x" }) },
+ refs: [value({ id: "r1" })],
+ frames: [{ value: value({ id: "f1", held: "f1", preview: "blob:y" }), at: 0 }],
+ });
+ const kept = draftLib.keepDraft(d);
+ expect(kept.prompt).toBe("a fox");
+ expect(kept.params).toEqual({ aspectRatio: "1:1" });
+ expect(kept.presetId).toBe("motion-orbit");
+ expect(kept.slots.image).toMatchObject({ held: "h1", ref: PLACEHOLDER.image, preview: "" });
+ // An upload that hadn't finished isn't there after a reload.
+ expect(kept.slots.endImage).toBeNull();
+ expect(kept.refs).toEqual([value({ id: "r1" })]);
+ expect(kept.frames?.[0].value).toMatchObject({ held: "f1", preview: "" });
+ expect(draftLib.heldValues(kept).map((v) => v.held)).toEqual(["h1", "f1"]);
+ });
+
+ it("is saved per page for a day, and read back", () => {
+ draftLib.saveDraft("/image", draft({ prompt: "kept" }));
+ expect(draftLib.readDraft<Kept>("/image")?.prompt).toBe("kept");
+ expect(draftLib.readDraft("/video")).toBeNull();
+ vi.spyOn(Date, "now").mockReturnValue(Date.now() + 25 * 60 * 60_000);
+ expect(draftLib.readDraft("/image")).toBeNull();
+ vi.restoreAllMocks();
+ draftLib.clearDraft("/image");
+ expect(draftLib.readDraft("/image")).toBeNull();
+ });
+
+ it("comes back with its kept files listed: uploading for an account (Run waits), shown again for a guest", () => {
+ const kept = draftLib.keepDraft(draft({ slots: { image: value({ id: "h1", held: "h1", preview: "blob:1" }) }, refs: [value({ id: "r1" })] }));
+ const account = draftLib.restoredDraft(kept, true);
+ expect(account.held.map((v) => v.held)).toEqual(["h1"]);
+ expect(account.draft.slots.image).toMatchObject({ held: "h1", uploading: true, preview: "" });
+ expect(account.draft.refs[0]).toEqual(value({ id: "r1" }));
+ expect(draftLib.restoredDraft(kept, false).draft.slots.image?.uploading).toBeUndefined();
+ });
+});
+
+describe("the run a guest pressed", () => {
+ const free = { amount: 0, priceVersion: "v1", text: "Free" };
+ it("is kept for its page, taken once, and only within the hour", () => {
+ draftLib.savePendingRun("/image", free);
+ expect(draftLib.takePendingRun("/video")).toBeNull();
+ expect(draftLib.takePendingRun("/image")).toMatchObject({ path: "/image", shown: free });
+ expect(draftLib.takePendingRun("/image")).toBeNull();
+ draftLib.savePendingRun("/image", free);
+ vi.spyOn(Date, "now").mockReturnValue(Date.now() + 61 * 60_000);
+ expect(draftLib.takePendingRun("/image")).toBeNull();
+ });
+
+ it("starts by itself only when the price is the one the guest saw; a new price is shown and waits for a click", () => {
+ const step = (o: Partial<Parameters<typeof draftLib.pendingStep>[0]>) => draftLib.pendingStep({ settled: true, blocked: false, pool: true, shown: free, quote: { allowed: true, amount: 0, text: "Free" }, ...o });
+ expect(step({})).toBe("start");
+ expect(step({ settled: false })).toBe("wait");
+ expect(step({ quote: { allowed: true, amount: 2, text: "2 units" } })).toBe("note");
+ // Refused now (a limit, busy): Run is off and says why; nothing starts.
+ expect(step({ quote: { allowed: false, amount: 0, text: "Free" } })).toBe("none");
+ // A file that didn't come back: the blocker says so.
+ expect(step({ blocked: true })).toBe("none");
+ // No price to compare (the guest's run wasn't on this studio's GPUs): never by itself.
+ expect(step({ shown: null })).toBe("none");
+ expect(step({ pool: false })).toBe("none");
+ // No billing service: no words either side, the same price.
+ expect(draftLib.pendingStep({ settled: true, blocked: false, pool: true, shown: { amount: 0, priceVersion: "", text: "" }, quote: { allowed: true, amount: 0, text: "" } })).toBe("start");
+ });
+});
+
+describe("a guest's files, kept in this browser", () => {
+ it("are kept until sign-up and forgotten after", async () => {
+ await held.holdFile("k1", png());
+ expect((await held.readHeld("k1"))?.name).toBe("me.png");
+ await held.dropHeld("k1");
+ expect(await held.readHeld("k1")).toBeNull();
+ });
+
+ it("an attached photo gets its tile at once, with a stand-in for the price check, and nothing is uploaded", async () => {
+ const fetchSpy = vi.spyOn(globalThis, "fetch");
+ const v = heldSlot(png(), "k2");
+ expect(v).toMatchObject({ id: "k2", held: "k2", kind: "image", name: "me.png", ref: PLACEHOLDER.image });
+ expect(v?.preview.startsWith("blob:")).toBe(true);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ expect((await held.readHeld("k2"))?.name).toBe("me.png");
+ // Over the size limit: not kept.
+ expect(heldSlot({ size: 300 * 1024 * 1024, name: "big.png", type: "image/png" } as File, "k3")).toBeNull();
+ });
+
+ it("go up as the new account's own files, and the kept copy is dropped", async () => {
+ await held.holdFile("k4", png("face.png"));
+ const calls: { url: string; name: string | null }[] = [];
+ vi.stubGlobal("fetch", async (url: string, init: RequestInit) => {
+ calls.push({ url, name: new Headers(init.headers).get("X-File-Name") });
+ return Response.json({ id: "a1", url: "/api/files/uploads/face.png", kind: "image" }, { status: 201 });
+ });
+ const up = await uploadHeld({ id: "k4", held: "k4", ref: PLACEHOLDER.image, preview: "", kind: "image", name: "face.png", uploading: true });
+ expect(calls).toEqual([{ url: "/api/uploads", name: "face.png" }]);
+ expect(up).toEqual({ id: "k4", ref: "/api/files/uploads/face.png", preview: "/api/files/uploads/face.png", kind: "image", name: "face.png" });
+ expect(await held.readHeld("k4")).toBeNull();
+ // A file the browser no longer has leaves the draft (the composer then asks for it again).
+ expect(await uploadHeld({ id: "k5", held: "k5", ref: PLACEHOLDER.image, preview: "", kind: "image" })).toBeNull();
+ vi.unstubAllGlobals();
+ vi.stubGlobal("sessionStorage", storage);
+ vi.stubGlobal("window", win);
+ });
+});
+
+describe("attaching as a guest", () => {
+ function Probe({ hold }: { hold?: boolean }) {
+ const ask = useAskBeforeUpload(hold === undefined ? {} : { hold });
+ return createElement("span", null, String(ask()));
+ }
+ const asGuest = (node: ReactNode, holds: boolean) => {
+ const qc = new QueryClient();
+ qc.setQueryData(["viewer"], { publicSignup: true, signedIn: false, owner: false, account: null });
+ return renderToStaticMarkup(createElement(QueryClientProvider, { client: qc }, createElement(held.HoldFilesCtx.Provider, { value: holds }, node)));
+ };
+
+ it("in a studio that keeps a guest's files (hosted runs on): the file is taken, no sign-up card", () => {
+ expect(asGuest(createElement(Probe), true)).toBe("<span>false</span>");
+ expect(events).toEqual([]);
+ });
+
+ it("a voice sample still asks to sign up first; and with hosted runs off every file does, as before", () => {
+ expect(asGuest(createElement(Probe, { hold: false }), true)).toBe("<span>true</span>");
+ expect(asGuest(createElement(Probe), false)).toBe("<span>true</span>");
+ expect(events).toEqual(["guest:upload", "guest:upload"]);
+ });
+});