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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Hosted runs: a guest's run starts after sign-up only as it was pressed
Adarsh3bbe86eefb9a
diff --git a/src/components/studio/attachments.ts b/src/components/studio/attachments.tsindex 9a609027..4354753c 100644--- a/src/components/studio/attachments.ts+++ b/src/components/studio/attachments.ts@@ -18,20 +18,25 @@ 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>();+/**+ * The kept files (src/lib/held-files.ts) one draft held and no longer holds, to forget: `seen` is that draft's own+ * list (updated here), so a file another studio's draft holds is never dropped by this one.+ */+export function heldToDrop(seen: Set<string>, held: ReadonlySet<string>): string[] {+ for (const id of held) seen.add(id);+ const gone = [...seen].filter((id) => !held.has(id));+ for (const id of gone) seen.delete(id);+ return gone;+}/** 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">) {+ // A guest's kept files this draft has held: one it takes out is forgotten too (each studio page has its own draft).+ const heldSeen = useRef(new Set<string>());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);- }+ for (const id of heldToDrop(heldSeen.current, held)) void dropHeld(id);if (!inflight.size) return;const ids = new Set(values.map((v) => v?.id).filter(Boolean));for (const [id, e] of inflight) {diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsxindex 8bd94fbf..e7c99ac5 100644--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@ -987,18 +987,22 @@ export function Composer({ docked }: { docked: boolean }) {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.+ // starts by itself when the price is the one the guest saw on the draft Run was pressed on. Otherwise Run waits for a+ // click, with a line saying why: a kept file didn't come back, the draft changed after Run, or a new price. Something+ // else missing leaves it to the blocker's line.const pendingRun = guestDraft.pending;const clearPending = guestDraft.clearPending;+ const keptLost = guestDraft.lost;useEffect(() => {if (!pendingRun) return;- const next = pendingStep({ settled: !settling && priceSettled, blocked: !!blocker, pool: poolPrice, shown: pendingRun.shown, quote: hostedQuote });+ const next = pendingStep({ settled: !settling && priceSettled, blocked: !!blocker, pool: poolPrice, shown: pendingRun.shown, quote: hostedQuote, lost: keptLost, same: pendingRun.same });if (next === "wait") return;clearPending();if (next === "start") submitRef.current();+ else if (next === "lost") setPriceNote("Add your file again, then press Generate.");+ else if (next === "ask") setPriceNote("Your draft is back. Press Generate to start.");else if (next === "note" && hostedQuote) setPriceNote(`The price is now ${hostedQuote.text}. Press Generate to start.`);- }, [pendingRun, clearPending, settling, priceSettled, blocker, poolPrice, hostedQuote]);+ }, [pendingRun, clearPending, settling, priceSettled, blocker, poolPrice, hostedQuote, keptLost]);const blockedSlot = blocker?.slot;useEffect(() => {if (step === "wait" || startRequest <= startedFor.current) return;@@ -1347,7 +1351,7 @@ export function Composer({ docked }: { docked: boolean }) {)}{hasCleanVoice && <CleanVoiceSwitch status className="hidden max-w-[16rem] shrink-0 sm:flex" hint="first, free on your GPU" />}{config.sketch && draft.slots.image?.ref && !draft.slots.image.uploading && (- <SketchTools modes={config.sketch} image={draft.slots.image.ref} autoOpen={config.sketchAutoOpen} />+ <SketchTools modes={config.sketch} image={draft.slots.image.ref} autoOpen={config.sketchAutoOpen} held={!!draft.slots.image.held} />)}{config.multiRef &&draft.refs.map((r, i) => (diff --git a/src/components/studio/guest-draft.ts b/src/components/studio/guest-draft.tsindex 17a5347f..b13288b5 100644--- a/src/components/studio/guest-draft.ts+++ b/src/components/studio/guest-draft.ts@@ -1,18 +1,35 @@"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 { clearDraft, readDraft, restoredDraft, restoredPrompt, sameDraft, 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";+/**+ * Upload a restored draft's kept files as the new account's own: each one takes its stand-in's place as it lands, or+ * leaves the draft when it didn't come back (`lost` is said first, in the same turn, so the run its guest pressed+ * never starts without it).+ */+export function uploadKept(held: SlotValue[], up: (v: SlotValue) => Promise<SlotValue | null>, on: { lost: () => void; swap: (id: string | undefined, v: SlotValue | null) => void }): Promise<void> {+ return Promise.all(+ held.map((v) =>+ up(v).then((next) => {+ if (!next) on.lost();+ on.swap(v.id, next);+ }),+ ),+ ).then(() => undefined);+}+/*** 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.+ * signed up) its kept files are uploaded as the account's own, and the run its guest pressed is handed back (`pending`,+ * with whether the draft is still the one Run was pressed on) for the composer to start once the price check agrees.+ * `lost`: a kept file didn't come back, so that run waits for the person.* 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 }) {@@ -21,33 +38,34 @@ export function useGuestDraft({ hold, viewer, draft, setDraft }: { hold: booleanpath.current = window.location.pathname;}, []);- const [pending, setPending] = useState<PendingRun | null>(null);+ const [pending, setPending] = useState<(PendingRun & { same: boolean }) | null>(null);+ const [lost, setLost] = useState(false);const restored = useRef(false);useEffect(() => {if (restored.current || !viewer || !path.current) return;restored.current = true;const here = path.current;+ const kept = readDraft<Draft>(here);+ let pressed = false;if (viewer === "account") {const run = takePendingRun(here);- if (run) setPending(run);+ pressed = !!run && sameDraft(run, kept);+ if (run) setPending({ ...run, same: pressed });}- 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 }));+ // A prompt the link brought (?prompt=) wins over the saved words, except for the run its guest pressed.+ setDraft((d) => ({ ...draftNow, prompt: restoredPrompt(d.prompt, draftNow.prompt, pressed) }));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));+ if (account) {+ void uploadKept(held, uploadHeld, { lost: () => setLost(true), swap });+ return;}+ // Still a guest: the kept file shows again (a file the browser no longer has leaves the draft).+ for (const v of held) 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).@@ -55,15 +73,16 @@ export function useGuestDraft({ hold, viewer, draft, setDraft }: { hold: booleanif (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. */+ /** A guest pressed Run: the draft and the run (with the price it showed, and the draft it was pressed on) 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);+ const kept = draft as unknown as Parameters<typeof saveDraft>[1];+ saveDraft(path.current, kept);+ savePendingRun(path.current, shown, kept);},[draft],);- return { pending, clearPending: useCallback(() => setPending(null), []), keepRun };+ return { pending, lost, clearPending: useCallback(() => setPending(null), []), keepRun };}diff --git a/src/components/studio/hold-files.tsx b/src/components/studio/hold-files.tsxindex adcfbae8..eaa37311 100644--- a/src/components/studio/hold-files.tsx+++ b/src/components/studio/hold-files.tsx@@ -1,14 +1,22 @@"use client";+import { useEffect } from "react";import { useHydrated, useStatus } from "@/lib/api";-import { HoldFilesCtx } from "@/lib/held-files";+import { savedHeldIds } from "@/lib/guest-draft";+import { HoldFilesCtx, sweepHeld } 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.+ * opening "Create a free account" (src/lib/held-files.ts). Off, and for anyone signed in, nothing changes. As the page+ * opens, kept files nobody needs any more are cleared: for a guest, those no draft saved in this tab holds (and older+ * than a day); for anyone else, those older than a day.*/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>;+ const holds = hydrated && v?.kind === "guest" && !!v.hosted;+ useEffect(() => {+ if (hydrated) void sweepHeld(holds ? savedHeldIds() : null);+ }, [hydrated, holds]);+ return <HoldFilesCtx.Provider value={holds}>{children}</HoldFilesCtx.Provider>;}diff --git a/src/components/studio/sketch-tools.tsx b/src/components/studio/sketch-tools.tsxindex 60e4bfbd..c536696a 100644--- a/src/components/studio/sketch-tools.tsx+++ b/src/components/studio/sketch-tools.tsx@@ -3,23 +3,33 @@import { Brush, PenLine, X } from "lucide-react";import { useEffect, useRef, useState } from "react";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { useAskBeforeUpload } from "@/lib/api";import { SketchEditor, type SketchMode } from "./sketch-editor";import { useStudio } from "./studio-context";-/** "Paint area" / "Draw" buttons next to the first image, and the resulting drawing chip. */-export function SketchTools({ modes, image, autoOpen }: { modes: SketchMode[]; image: string; autoOpen?: SketchMode }) {+/**+ * "Paint area" / "Draw" buttons next to the first image, and the resulting drawing chip. `held`: the image is a guest's,+ * kept in the browser until sign-up (hosted runs on); a drawing is uploaded as it is saved, so the guest is asked to sign+ * up first, and the editor doesn't open by itself.+ */+export function SketchTools({ modes, image, autoOpen, held = false }: { modes: SketchMode[]; image: string; autoOpen?: SketchMode; held?: boolean }) {const { draft, setDraft } = useStudio();const [editing, setEditing] = useState<SketchMode | null>(null);const opened = useRef<string | null>(null);const current = draft.slots.sketch;const mode: SketchMode | null = draft.slots.mask?.ref ? "mask" : current?.ref ? "draw" : null;+ const askFirst = useAskBeforeUpload({ hold: false });+ const edit = (m: SketchMode | null) => {+ if (held && askFirst()) return;+ setEditing(m);+ };useEffect(() => {- if (autoOpen && !current && opened.current !== image) {+ if (autoOpen && !held && !current && opened.current !== image) {opened.current = image;setEditing(autoOpen);}- }, [autoOpen, image, current]);+ }, [autoOpen, held, image, current]);const clear = () =>setDraft((d) => {@@ -35,7 +45,7 @@ export function SketchTools({ modes, image, autoOpen }: { modes: SketchMode[]; i<Tooltip><TooltipTrigger asChild><button- onClick={() => setEditing(mode)}+ onClick={() => edit(mode)}className="size-full overflow-hidden rounded-xl border-2 border-primary bg-muted"aria-label={mode === "mask" ? "Edit the painted area" : "Edit the drawing"}>@@ -61,7 +71,7 @@ export function SketchTools({ modes, image, autoOpen }: { modes: SketchMode[]; i<Tooltip key={m}><TooltipTrigger asChild><button- onClick={() => setEditing(m)}+ onClick={() => edit(m)}// Generate points here when the painted area is what it's waiting for.data-slot-key={m === "mask" ? "mask" : "sketch"}className="flex size-14 shrink-0 flex-col items-center justify-center gap-0.5 rounded-xl border border-dashed border-primary/50 bg-brand-faint text-brand-text transition-colors hover:border-primary"diff --git a/src/components/studio/voice-recorder.tsx b/src/components/studio/voice-recorder.tsxindex e7bbb2fb..9dc2b622 100644--- a/src/components/studio/voice-recorder.tsx+++ b/src/components/studio/voice-recorder.tsx@@ -67,7 +67,8 @@ export function VoiceRecorder({ onRecorded, max = 60, className, clean }: { onReconst stop = () => rec.current?.state === "recording" && rec.current.stop();// A guest, or an account with neither its own GPU nor its own key, gets its card before the microphone: the sample would be refused.- const askFirst = useAskBeforeUpload();+ // (A recording is uploaded as soon as it stops: a guest signs up first, even in a studio that keeps its pictures.)+ const askFirst = useAskBeforeUpload({ hold: false });const start = async () => {if (askFirst()) return;diff --git a/src/lib/guest-draft.ts b/src/lib/guest-draft.tsindex c962b07a..dfd88ef5 100644--- a/src/lib/guest-draft.ts+++ b/src/lib/guest-draft.ts@@ -4,8 +4,8 @@ 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.+ * the draft, uploads the kept files as the account's own, and starts the run by itself when the price is unchanged, the+ * draft is the one Run was pressed on and every kept file came back; otherwise it says why and waits for a click.*//** An attachment as the studio draft keeps it (src/components/studio/media-slot.tsx SlotValue). */@@ -93,6 +93,36 @@ export function clearDraft(path: string): void {} catch {}}+/** The kept files every draft saved in this tab holds (any page's): the files this tab may still need. */+export function savedHeldIds(): Set<string> {+ const out = new Set<string>();+ try {+ const s = store();+ if (!s) return out;+ for (let i = 0; i < s.length; i++) {+ const key = s.key(i);+ if (!key?.startsWith(draftKey(""))) continue;+ const d = readDraft(key.slice(draftKey("").length));+ if (d) for (const v of heldValues(d)) out.add(v.held!);+ }+ } catch {}+ return out;+}++/**+ * A short fingerprint of a draft as it is saved (keepDraft): the run a guest pressed starts by itself only on the same+ * draft, never on one edited after Run was pressed.+ */+export function draftPrint(d: DraftLike): string {+ const s = JSON.stringify(keepDraft(d));+ let h = 0x811c9dc5;+ for (let i = 0; i < s.length; i++) {+ h ^= s.charCodeAt(i);+ h = Math.imul(h, 0x01000193) >>> 0;+ }+ return `${s.length.toString(36)}.${h.toString(36)}`;+}+/** 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;@@ -100,15 +130,22 @@ export interface PendingRun {path: string;shown: ShownPrice;at: number;+ /** The draft Run was pressed on (draftPrint). */+ draft?: string;}-/** A guest pressed Run here: kept for this tab, to start once signed up. */-export function savePendingRun(path: string, shown: ShownPrice): void {+/** A guest pressed Run here on this draft: kept for this tab, to start once signed up. */+export function savePendingRun(path: string, shown: ShownPrice, draft?: DraftLike): void {try {- store()?.setItem(PENDING_KEY, JSON.stringify({ path, shown, at: Date.now() } satisfies PendingRun));+ store()?.setItem(PENDING_KEY, JSON.stringify({ path, shown, at: Date.now(), ...(draft && { draft: draftPrint(draft) }) } satisfies PendingRun));} catch {}}+/** Is this the draft the guest pressed Run on (not one edited since)? */+export function sameDraft(run: Pick<PendingRun, "draft">, kept: DraftLike | null): boolean {+ return !!run.draft && !!kept && draftPrint(kept) === run.draft;+}+/** 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 {@@ -140,13 +177,38 @@ export function restoredDraft<D extends DraftLike>(kept: D, account: boolean): {}/**- * 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).+ * The words a restored draft starts with: a prompt the link brought (?prompt=, still in the address the sign-up returns+ * to) wins over the saved words, as it does for the words kept per page; but the run its guest pressed comes back with+ * the words it was pressed on (`pressed`: that run is back, on the same draft).*/-export function pendingStep(o: { settled: boolean; blocked: boolean; pool: boolean; shown: ShownPrice; quote?: { allowed: boolean; amount: number; text: string } }): "wait" | "start" | "note" | "none" {+export function restoredPrompt(link: string, saved: string, pressed: boolean): string {+ return pressed ? saved : link || saved;+}++/**+ * What the run a guest pressed does once back as an account:+ * - lost: one of its kept files didn't come back (gone from the browser, or its upload refused): it never starts without+ * it, and the person is asked to add it again;+ * - wait: the draft, its files or the price check haven't settled;+ * - ask: the draft was edited after Run was pressed (`same` false): it waits for a click on what is there now;+ * - start: the price is the one the guest saw;+ * - note: a new price, shown, and Run waits for a click;+ * - none: something is missing (the blocker says what), it would run elsewhere, it is refused now, 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 };+ lost: boolean;+ same: boolean;+}): "wait" | "start" | "note" | "ask" | "lost" | "none" {+ if (o.lost) return "lost";if (!o.settled) return "wait";if (o.blocked || !o.pool) return "none";+ if (!o.same) return o.quote?.allowed ? "ask" : "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.tsindex 2e6e2442..a787e191 100644--- a/src/lib/held-files.ts+++ b/src/lib/held-files.ts@@ -1,27 +1,45 @@"use client";+import { nanoid } from "nanoid";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.+ * as the new account's own files); where IndexedDB isn't there (a private window), in this page's memory only.+ *+ * Nothing is kept longer than it is needed. Each studio page that opens sweeps the kept files (sweepHeld): a file kept+ * for more than a day goes, and so does one that no saved draft of its tab holds any more, once that tab has no page+ * open (each tab marks its pages with a lock while they are open). A file read after a day is dropped as it is read.*/const DB = "fuobe-held-files";const STORE = "files";const MAX_AGE_MS = 24 * 60 * 60_000;+/** This tab's id for the files it keeps (sessionStorage: the same through reloads, gone with the tab). */+const TAB_KEY = "fuobe:held-tab";+const LOCK_PREFIX = "fuobe-held:";/** 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;+ var __fuobeHeldTab: Promise<string> | undefined;}const memory = () => (globalThis.__fuobeHeldFiles ??= new Map());+/** A kept file as IndexedDB stores it. */+interface HeldRow {+ file: Blob;+ name: string;+ type: string;+ at: number;+ /** The tab that kept it (rows from before tabs were noted have none). */+ tab?: string;+}+function open(): Promise<IDBDatabase | null> {return new Promise((resolve) => {try {@@ -54,19 +72,80 @@ async function withStore<T>(mode: IDBTransactionMode, fn: (s: IDBObjectStore) =>});}+function tabStorage(): Storage | null {+ try {+ return typeof sessionStorage === "undefined" ? null : sessionStorage;+ } catch {+ return null;+ }+}++function newTab(): string {+ const id = nanoid(10);+ try {+ tabStorage()?.setItem(TAB_KEY, id);+ } catch {}+ return id;+}++/** Hold a tab's lock while this page is open, without waiting: false when another page holds it (a duplicated tab). */+function takeLock(locks: LockManager, tab: string): Promise<boolean> {+ return new Promise((resolve) => {+ locks+ .request(`${LOCK_PREFIX}${tab}`, { ifAvailable: true }, (lock) => {+ resolve(!!lock);+ return lock ? new Promise<never>(() => {}) : undefined;+ })+ .catch(() => resolve(false));+ });+}++/**+ * This page's tab id, marked as in use for as long as the page is open, so another tab's sweep leaves its files alone.+ * A duplicated tab (which copies the id with its sessionStorage) takes a new one.+ */+export function claimTab(): Promise<string> {+ return (globalThis.__fuobeHeldTab ??= (async () => {+ let tab = tabStorage()?.getItem(TAB_KEY) || newTab();+ const locks = typeof navigator !== "undefined" ? navigator.locks : undefined;+ if (!locks) return tab;+ if (!(await takeLock(locks, tab))) {+ tab = newTab();+ await takeLock(locks, tab);+ }+ return tab;+ })());+}++/** The tabs with a page open now (null: this browser can't tell, so every other tab counts as open). */+async function openTabs(): Promise<Set<string> | null> {+ const locks = typeof navigator !== "undefined" ? navigator.locks : undefined;+ if (!locks) return null;+ try {+ const q = await locks.query();+ return new Set((q.held ?? []).map((l) => l.name ?? "").filter((n) => n.startsWith(LOCK_PREFIX)).map((n) => n.slice(LOCK_PREFIX.length)));+ } catch {+ return 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();+ const tab = await claimTab();+ await withStore("readwrite", (s) => s.put({ file, name: file.name, type: file.type, at: Date.now(), tab } satisfies HeldRow, id));}/** 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;+ const row = (await withStore("readonly", (s) => s.get(id) as IDBRequest<HeldRow | undefined>)) ?? null;+ if (!row) return null;+ if (Date.now() - row.at > MAX_AGE_MS) {+ void dropHeld(id);+ return null;+ }return row.file instanceof File ? row.file : new File([row.file], row.name, { type: row.type });}@@ -76,21 +155,62 @@ export async function dropHeld(id: string): Promise<void> {await withStore("readwrite", (s) => s.delete(id));}-/** Forget every kept file older than a day. */-async function dropOldHeld(): Promise<void> {+/**+ * The kept files a sweep drops: every one older than a day; and, with `keep` (the files this tab's saved drafts and this+ * page hold, swept for a guest), every other one of this tab's, or of a tab with no page open any more.+ */+export function heldToSweep(rows: { id: string; at: number; tab?: string }[], o: { now: number; tab: string; keep: ReadonlySet<string> | null; open: ReadonlySet<string> | null }): string[] {+ return rows+ .filter((r) => {+ if (o.now - r.at > MAX_AGE_MS) return true;+ if (!o.keep || o.keep.has(r.id)) return false;+ if (!r.tab || r.tab === o.tab) return true;+ return !!o.open && !o.open.has(r.tab);+ })+ .map((r) => r.id);+}++/** Does this browser have the kept files' store (null: it can't say)? */+async function heldStoreExists(): Promise<boolean | null> {+ try {+ if (typeof indexedDB === "undefined") return false;+ if (typeof indexedDB.databases !== "function") return null;+ return (await indexedDB.databases()).some((d) => d.name === DB);+ } catch {+ return null;+ }+}++/**+ * Sweep the kept files as a studio page opens (heldToSweep). `keep`: the files this tab's saved drafts hold, for a+ * guest; null sweeps only the files older than a day. Never throws.+ */+export async function sweepHeld(keep: ReadonlySet<string> | null): Promise<void> {+ // Nothing kept in this browser: nothing to sweep (and no store is made for it). Anyone else's page sweeps only a+ // store it knows is there.+ const store = await heldStoreExists();+ if (store === false || (store === null && !keep)) return;+ const tab = keep ? await claimTab() : "";+ const live = keep ? await openTabs() : null;const db = await open();if (!db) return;try {const tx = db.transaction(STORE, "readwrite");- const cursor = tx.objectStore(STORE).openCursor();+ const files = tx.objectStore(STORE);+ const rows: { id: string; at: number; tab?: string }[] = [];+ const cursor = files.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();+ if (c) {+ const v = c.value as Partial<HeldRow> | undefined;+ rows.push({ id: String(c.key), at: v?.at ?? 0, ...(v?.tab && { tab: v.tab }) });+ return c.continue();+ }+ const kept = keep && new Set([...keep, ...memory().keys()]);+ for (const id of heldToSweep(rows, { now: Date.now(), tab, keep: kept, open: live })) files.delete(id);};tx.oncomplete = () => db.close();+ tx.onerror = () => db.close();} catch {db.close();}diff --git a/tests/hosted-guest-draft.test.ts b/tests/hosted-guest-draft.test.tsindex e23c5af4..2ed5cbeb 100644--- a/tests/hosted-guest-draft.test.ts+++ b/tests/hosted-guest-draft.test.ts@@ -1,3 +1,5 @@+import fs from "node:fs";+import path from "node:path";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { createElement, type ReactNode } from "react";import { renderToStaticMarkup } from "react-dom/server";@@ -17,6 +19,10 @@ class MemoryStorage {setItem = (k: string, v: string) => void this.m.set(k, String(v));removeItem = (k: string) => void this.m.delete(k);clear = () => this.m.clear();+ key = (i: number) => [...this.m.keys()][i] ?? null;+ get length() {+ return this.m.size;+ }}const storage = new MemoryStorage();vi.stubGlobal("sessionStorage", storage);@@ -28,6 +34,8 @@ 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 { heldToDrop } = await import("@/components/studio/attachments");+const { uploadKept } = await import("@/components/studio/guest-draft");const { useAskBeforeUpload } = await import("@/lib/api");const { PLACEHOLDER } = await import("@/lib/composer");@@ -95,20 +103,66 @@ describe("the run a guest pressed", () => {expect(draftLib.takePendingRun("/image")).toBeNull();});+ 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" }, lost: false, same: true, ...o });+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.+ // A required file missing: 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");+ expect(step({ shown: { amount: 0, priceVersion: "", text: "" }, quote: { allowed: true, amount: 0, text: "" } })).toBe("start");+ });++ it("never starts without a kept file that didn't come back, even in a slot the run could do without", () => {+ // When every run costs the same ("Free") and a reference photo or start frame is optional, only the lost file+ // stops it, and the person is asked to add it again.+ expect(step({ lost: true })).toBe("lost");+ expect(step({ lost: true, settled: false })).toBe("lost");+ });++ it("a kept file that didn't come back is said before it leaves the draft (in the same turn, so the run can't start first)", async () => {+ const order: string[] = [];+ const kept = [value({ id: "h1", held: "h1" }), value({ id: "h2", held: "h2" })];+ await uploadKept(kept, async (v) => (v.id === "h1" ? { ...v, held: undefined, ref: "/api/files/uploads/h1.png" } : null), {+ lost: () => order.push("lost"),+ swap: (id, v) => order.push(`${id}:${v ? "up" : "gone"}`),+ });+ expect(order).toEqual(["h1:up", "lost", "h2:gone"]);+ });++ it("starts by itself only on the draft Run was pressed on; a draft edited after Run waits for a click", () => {+ const pressed = draft({ slots: { image: value({ id: "h1", held: "h1", ref: PLACEHOLDER.image, preview: "blob:1" }) } });+ draftLib.saveDraft("/image", pressed);+ draftLib.savePendingRun("/image", free, pressed);+ const run = draftLib.takePendingRun("/image")!;+ expect(run.draft).toBeTruthy();+ // Read back after the sign-up: the same draft.+ expect(draftLib.sameDraft(run, draftLib.readDraft("/image"))).toBe(true);+ // Edited while still a guest (the draft goes on being saved): not the one pressed.+ draftLib.saveDraft("/image", { ...pressed, prompt: "a fox in the rain" });+ expect(draftLib.sameDraft(run, draftLib.readDraft("/image"))).toBe(false);+ draftLib.saveDraft("/image", { ...pressed, slots: {} });+ expect(draftLib.sameDraft(run, draftLib.readDraft("/image"))).toBe(false);+ // A run kept with no draft to compare never starts by itself.+ expect(draftLib.sameDraft({}, draftLib.readDraft("/image"))).toBe(false);+ expect(step({ same: false })).toBe("ask");+ expect(step({ same: false, quote: { allowed: false, amount: 0, text: "Free" } })).toBe("none");+ });++ it("the run a guest pressed comes back with the words it was pressed on, even when the link brought other words", () => {+ // The sign-up returns to the page's address, ?prompt= and all: the guest's own words win for the run it pressed.+ expect(draftLib.restoredPrompt("a cat", "a fox in the rain", true)).toBe("a fox in the rain");+ // No run pressed (or a draft edited after Run): the link's words win, as they do for the words kept per page.+ expect(draftLib.restoredPrompt("a cat", "a fox in the rain", false)).toBe("a cat");+ expect(draftLib.restoredPrompt("", "a fox in the rain", false)).toBe("a fox in the rain");});});@@ -148,6 +202,61 @@ describe("a guest's files, kept in this browser", () => {vi.stubGlobal("sessionStorage", storage);vi.stubGlobal("window", win);});++ it("each studio's draft forgets only the files it held itself: one taken out of a draft never takes another studio's", () => {+ // Two studio pages open at once (/image and /video), each with its own draft and its own list.+ const image = new Set<string>();+ const video = new Set<string>();+ expect(heldToDrop(image, new Set(["x"]))).toEqual([]);+ // The Video studio's draft never held x: nothing of the Image studio's is dropped there.+ expect(heldToDrop(video, new Set())).toEqual([]);+ expect(heldToDrop(video, new Set(["y"]))).toEqual([]);+ expect(heldToDrop(video, new Set())).toEqual(["y"]);+ // x is still in the Image studio's draft: kept, until that draft lets it go.+ expect(heldToDrop(image, new Set(["x"]))).toEqual([]);+ expect(heldToDrop(image, new Set())).toEqual(["x"]);+ expect(heldToDrop(image, new Set())).toEqual([]);+ });++ it("are cleared once nobody needs them: after a day, and when no draft of an open tab holds them", () => {+ const now = Date.now();+ const rows = [+ { id: "old", at: now - 24 * 60 * 60_000 - 1, tab: "t1" },+ { id: "mine-kept", at: now, tab: "t1" },+ { id: "mine-gone", at: now, tab: "t1" },+ { id: "open-tab", at: now, tab: "t2" },+ { id: "closed-tab", at: now, tab: "t3" },+ { id: "no-tab", at: now },+ ];+ // A guest's studio page in tab t1, with t2 open too.+ expect(held.heldToSweep(rows, { now, tab: "t1", keep: new Set(["mine-kept"]), open: new Set(["t1", "t2"]) })).toEqual(["old", "mine-gone", "closed-tab", "no-tab"]);+ // A browser that can't tell which tabs are open: another tab's files stay until their day is up.+ expect(held.heldToSweep(rows, { now, tab: "t1", keep: new Set(["mine-kept"]), open: null })).toEqual(["old", "mine-gone", "no-tab"]);+ // Anyone else (or before who is looking is known): only the files older than a day.+ expect(held.heldToSweep(rows, { now, tab: "t1", keep: null, open: null })).toEqual(["old"]);+ });++ it("the files a tab may still need are those its saved drafts hold, on any page", () => {+ draftLib.saveDraft("/image", draft({ slots: { image: value({ id: "a", held: "a" }) } }));+ draftLib.saveDraft("/video", draft({ refs: [value({ id: "b", held: "b" }), value({ id: "c" })] }));+ expect([...draftLib.savedHeldIds()].sort()).toEqual(["a", "b"]);+ });++ it("each tab marks its files as in use while a page of it is open; a duplicated tab takes an id of its own", async () => {+ globalThis.__fuobeHeldTab = undefined;+ storage.setItem("fuobe:held-tab", "copied");+ // The tab it was copied from still has a page open.+ let release = () => {};+ void navigator.locks.request("fuobe-held:copied", () => new Promise<void>((r) => (release = r)));+ await new Promise((r) => setTimeout(r, 10));+ const tab = await held.claimTab();+ expect(tab).not.toBe("copied");+ expect(storage.getItem("fuobe:held-tab")).toBe(tab);+ expect(await held.claimTab()).toBe(tab);+ const names = ((await navigator.locks.query()).held ?? []).map((l) => l.name);+ expect(names).toContain(`fuobe-held:${tab}`);+ release();+ });});describe("attaching as a guest", () => {@@ -171,4 +280,17 @@ describe("attaching as a guest", () => {expect(asGuest(createElement(Probe), false)).toBe("<span>true</span>");expect(events).toEqual(["guest:upload", "guest:upload"]);});++ it("a recording, or a drawing on a kept picture, is uploaded as soon as it is made: the guest signs up first", () => {+ const src = (f: string) => fs.readFileSync(path.join(process.cwd(), f), "utf8");+ // The Record chip (VoicePicker's recorder) and its Upload button ask before the microphone or the file chooser.+ expect(src("src/components/studio/voice-recorder.tsx")).toContain("useAskBeforeUpload({ hold: false })");+ expect(src("src/components/studio/audio-controls.tsx")).toContain("useAskBeforeUpload({ hold: false })");+ // Paint area and Draw on a kept picture ask before the editor opens, and it never opens by itself.+ const sketch = src("src/components/studio/sketch-tools.tsx");+ expect(sketch).toContain("useAskBeforeUpload({ hold: false })");+ expect(sketch).toContain("if (held && askFirst()) return;");+ expect(sketch).toContain("autoOpen && !held");+ expect(src("src/components/studio/composer.tsx")).toContain("held={!!draft.slots.image.held}");+ });});