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.

Notifications: "your job is done" while Fuobe is in the background, and the running count in the tab title

Claude19958436924c
diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsx
index d78ed3b5..027f9be6 100644
--- a/src/components/app-sidebar.tsx
+++ b/src/components/app-sidebar.tsx
@@ -73,6 +73,7 @@ import {
} from "@/components/ui/sidebar";
import { Kbd } from "@/components/ui/kbd";
import { GlobalShortcuts } from "@/components/global-shortcuts";
+import { JobNotifications } from "@/components/job-notifications";
import { useEngineMode, useStatus } from "@/lib/api";
import { groupId, NAV_CLOSED_KEY, navActive, parseClosed, SIDEBAR_STATE_SCRIPT, sidebarOpenFromCookie } from "@/lib/nav";
import { cn } from "@/lib/utils";
@@ -281,6 +282,7 @@ export function StudioChrome({ children }: { children: React.ReactNode }) {
{children}
</SidebarInset>
<GlobalShortcuts />
+ <JobNotifications />
</SidebarShell>
);
}
diff --git a/src/components/job-notifications.tsx b/src/components/job-notifications.tsx
new file mode 100644
index 00000000..bf627cac
--- /dev/null
+++ b/src/components/job-notifications.tsx
@@ -0,0 +1,163 @@
+"use client";
+
+import dynamic from "next/dynamic";
+import { useRouter } from "next/navigation";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { toast } from "sonner";
+import { anotherTabVisible, keepStreamWhileHidden, leadsStream, useGenerationEvents, useRunningGenerations } from "@/lib/api";
+import type { Generation } from "@/lib/catalog/types";
+import {
+ dueJobs,
+ longestRunning,
+ notificationText,
+ runningJobs,
+ seedWatch,
+ SETTLE_MS,
+ shouldNotify,
+ shouldOffer,
+ titleWithCount,
+ watchEvent,
+ type FinishedJob,
+ type WatchState,
+} from "@/lib/job-watch";
+import { notificationPermission, notificationsEnabled, useNotificationPrefs } from "@/lib/notification-prefs";
+
+/** The result viewer is its own chunk: it loads when a notification is clicked. */
+const Viewer = dynamic(() => import("@/components/studio/viewer").then((m) => m.Viewer));
+
+/**
+ * Jobs in the background, for every page in the app frame: the number running in the tab title
+ * ("(2) Library · Fuobe"), a one-time offer to turn on notifications once a job runs a while, and
+ * a system notification when a job finishes or fails while nobody is looking at Fuobe. Only the
+ * tab that reads the live stream for the browser (its leader) notifies, so tabs don't repeat it;
+ * clicking the notification brings that tab forward and opens the result. The decisions are pure
+ * (src/lib/job-watch.ts).
+ */
+export function JobNotifications() {
+ const router = useRouter();
+ const running = useRunningGenerations();
+ const prefs = useNotificationPrefs();
+ const [shown, setShown] = useState<Generation | null>(null);
+ const watch = useRef<WatchState>({});
+ const latest = useRef(prefs);
+ useEffect(() => {
+ latest.current = prefs;
+ });
+
+ // ---- the tab title: "(2) …" while jobs run
+ const count = runningJobs(running.data ?? []);
+ useEffect(() => {
+ const apply = () => {
+ const next = titleWithCount(document.title, count);
+ if (next !== document.title) document.title = next;
+ };
+ apply();
+ // Next sets the title again on every navigation: put the count back in front.
+ const observer = new MutationObserver(apply);
+ observer.observe(document.head, { subtree: true, childList: true, characterData: true });
+ return () => {
+ observer.disconnect();
+ document.title = titleWithCount(document.title, 0);
+ };
+ }, [count]);
+
+ // ---- finished jobs → a notification (leader tab, nobody looking)
+ const open = useCallback(
+ async (job: FinishedJob) => {
+ window.focus();
+ if (job.outcome === "failed") {
+ const { title, body } = notificationText(job);
+ toast.error(title, { description: body, action: { label: "Open Library", onClick: () => router.push("/library") } });
+ return;
+ }
+ try {
+ const res = await fetch(`/api/generations/${job.generation.id}`);
+ const g = res.ok ? ((await res.json()) as Generation) : null;
+ if (g?.outputs.length) setShown(g);
+ else router.push("/library");
+ } catch {
+ router.push("/library");
+ }
+ },
+ [router],
+ );
+
+ const notify = useCallback(
+ async (job: FinishedJob) => {
+ if (!notificationsEnabled() || !leadsStream() || document.visibilityState !== "hidden") return;
+ const otherVisible = await anotherTabVisible();
+ const ok = shouldNotify({
+ enabled: notificationsEnabled(),
+ permission: notificationPermission(),
+ leader: leadsStream(),
+ hidden: document.visibilityState === "hidden",
+ otherVisible,
+ });
+ if (!ok) return;
+ const { title, body } = notificationText(job);
+ try {
+ // The tag replaces rather than repeats one job's notification (and dedupes tabs that each read their own stream).
+ const n = new Notification(title, { body, tag: `fuobe-${job.key}`, icon: "/favicon.ico" });
+ n.onclick = () => {
+ n.close();
+ void open(job);
+ };
+ } catch {
+ // Some mobile browsers only notify from a service worker: the tab title still shows it.
+ }
+ },
+ [open],
+ );
+
+ const check = useCallback(() => {
+ const now = Date.now();
+ const { state, done } = dueJobs(watch.current, now);
+ watch.current = state;
+ for (const job of done) void notify(job);
+ const p = latest.current;
+ if (shouldOffer({ permission: p.permission, enabled: p.enabled, asked: p.asked, visible: document.visibilityState === "visible", runningFor: longestRunning(state, now) })) {
+ p.markAsked();
+ toast("Want a heads-up when it’s done?", {
+ id: "notify-offer",
+ description: "Fuobe can send a notification when a job finishes while you’re in another tab or app.",
+ duration: 15_000,
+ action: {
+ label: "Notify me",
+ onClick: () =>
+ void p.setEnabled(true).then((on) =>
+ on ? toast.success("Notifications are on", { description: "Change it any time in Settings → Notifications." }) : toast("Notifications are blocked in this browser", { description: "Allow them in the site settings, then turn them on in Settings." }),
+ ),
+ },
+ cancel: { label: "Not now", onClick: () => {} },
+ });
+ }
+ }, [notify]);
+
+ useGenerationEvents((ev) => {
+ const before = watch.current;
+ watch.current = watchEvent(before, ev, Date.now());
+ // A job just went quiet: look again once it has settled (a timer started now isn't held back much in a background tab).
+ if (watch.current !== before && Object.values(watch.current).some((j) => j.quietSince != null && before[j.key]?.quietSince == null)) setTimeout(check, SETTLE_MS + 100);
+ });
+
+ // Jobs already running when the page opened are watched too.
+ useEffect(() => {
+ if (running.data) watch.current = seedWatch(watch.current, running.data, Date.now());
+ }, [running.data]);
+
+ // While something runs: settle checks and the offer, every couple of seconds.
+ const busy = count > 0;
+ useEffect(() => {
+ if (!busy) return;
+ const t = setInterval(check, 2000);
+ return () => clearInterval(t);
+ }, [busy, check]);
+
+ // Hidden for a while, a tab lets go of the stream; with notifications on it keeps listening while a job runs.
+ useEffect(() => {
+ keepStreamWhileHidden(() => notificationsEnabled() && Object.values(watch.current).some((j) => j.quietSince == null));
+ return () => keepStreamWhileHidden(null);
+ }, []);
+
+ return shown ? <Viewer generation={shown} index={0} onClose={() => setShown(null)} /> : null;
+}
diff --git a/src/components/notification-settings.tsx b/src/components/notification-settings.tsx
new file mode 100644
index 00000000..cc361644
--- /dev/null
+++ b/src/components/notification-settings.tsx
@@ -0,0 +1,64 @@
+"use client";
+
+import { BellRing } from "lucide-react";
+import { useId } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Switch } from "@/components/ui/switch";
+import { useHydrated } from "@/lib/api";
+import { useNotificationPrefs } from "@/lib/notification-prefs";
+
+/** Settings → Notifications: this browser's opt-in for "your job is done" notifications. */
+export function NotificationSettings() {
+ const id = useId();
+ const hydrated = useHydrated();
+ const { enabled, permission, setEnabled } = useNotificationPrefs();
+ if (!hydrated) return <div className="h-14" aria-hidden />;
+ if (permission === "unsupported") {
+ return (
+ <p className="rounded-lg bg-muted px-3 py-2.5 text-[13px] leading-relaxed text-muted-foreground">
+ This browser can&apos;t show notifications here. Open Fuobe over https:// or on localhost to turn them on. The tab title still shows how many jobs are running.
+ </p>
+ );
+ }
+ const blocked = permission === "denied";
+ return (
+ <div className="space-y-3">
+ <div className="flex items-center gap-3">
+ <label htmlFor={id} className="min-w-0 flex-1 cursor-pointer">
+ <span className="block text-[13px] font-medium">Tell me when a job is done</span>
+ <span className="block text-[12px] leading-snug text-muted-foreground">
+ A system notification when a generation or studio job finishes or fails while Fuobe is in the background. Click it to see the result.
+ </span>
+ </label>
+ <Switch
+ id={id}
+ checked={enabled}
+ disabled={blocked}
+ onCheckedChange={(v) =>
+ void setEnabled(v).then((on) => {
+ if (v && !on) toast("Notifications are blocked in this browser", { description: "Allow them in the site settings, then try again." });
+ })
+ }
+ />
+ </div>
+ {blocked && <p className="text-[12px] text-muted-foreground">Notifications are blocked for this site. Allow them in your browser&apos;s site settings, then come back to turn them on.</p>}
+ {enabled && (
+ <Button
+ variant="outline"
+ size="sm"
+ className="rounded-full"
+ onClick={() => {
+ try {
+ new Notification("Notifications are on", { body: "This is how Fuobe tells you a job is done.", tag: "fuobe-test", icon: "/favicon.ico" });
+ } catch {
+ toast.error("This browser only shows notifications from an installed app");
+ }
+ }}
+ >
+ <BellRing className="size-3.5" /> Send a test
+ </Button>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/settings-form.tsx b/src/components/settings-form.tsx
index f2f72787..cb3eb4cc 100644
--- a/src/components/settings-form.tsx
+++ b/src/components/settings-form.tsx
@@ -10,6 +10,7 @@ import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
+import { NotificationSettings } from "@/components/notification-settings";
import { SecuritySettings } from "@/components/security-settings";
interface PublicSetting {
@@ -353,6 +354,14 @@ export function SettingsForm() {
</div>
</Section>
+ <Section
+ id="notifications"
+ title="Notifications"
+ description="Get a heads-up from your browser when something you started finishes while you're in another tab or app. Saved in this browser; nothing is sent anywhere."
+ >
+ <NotificationSettings />
+ </Section>
+
<Section
id="security"
title="Security"
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 4bf366d4..2b21e073 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -140,6 +140,10 @@ interface ClientStreamState {
hiddenTimer: ReturnType<typeof setTimeout> | null;
stopTimer: ReturnType<typeof setTimeout> | null;
hooked: boolean;
+ /** Keep the stream (or our place in line) while hidden: browser notifications are on and a job runs. */
+ keepHidden: (() => boolean) | null;
+ /** "Anyone on screen?" questions waiting for an answer, by id. */
+ seen: Map<string, () => void>;
}
declare global {
@@ -166,6 +170,8 @@ const live = (): ClientStreamState =>
hiddenTimer: null,
stopTimer: null,
hooked: false,
+ keepHidden: null,
+ seen: new Map(),
});
const shared = () => typeof navigator !== "undefined" && !!navigator.locks && typeof BroadcastChannel !== "undefined";
@@ -268,6 +274,15 @@ function openChannel() {
ch.onmessage = (e: MessageEvent) => {
const m = toChannelMessage(e.data);
if (!m) return;
+ // Any tab: say so when asked whether Fuobe is on screen; the asker hears the first answer.
+ if (m.type === "seen?") {
+ if (document.visibilityState === "visible") post({ type: "seen", id: m.id });
+ return;
+ }
+ if (m.type === "seen") {
+ s.seen?.get(m.id)?.();
+ return;
+ }
if (m.type === "hello") {
if (s.leader) post({ type: "state", connected: s.connected });
return;
@@ -312,10 +327,14 @@ function stop() {
function onVisibility() {
const s = live();
if (document.visibilityState === "hidden") {
- s.hiddenTimer ??= setTimeout(() => {
- s.hiddenTimer = null;
- stop();
- }, HIDDEN_GRACE_MS);
+ const arm = () =>
+ setTimeout(() => {
+ // Notifications on and a job running: the stream is how we hear it finish, so keep it.
+ if (s.keepHidden?.()) return void (s.hiddenTimer = arm());
+ s.hiddenTimer = null;
+ stop();
+ }, HIDDEN_GRACE_MS);
+ s.hiddenTimer ??= arm();
return;
}
if (s.hiddenTimer) clearTimeout(s.hiddenTimer);
@@ -359,6 +378,36 @@ export function useGenerationStream(): boolean {
);
}
+/** Whether this tab reads the live stream for the browser (its leader), or its own (no Web Locks). */
+export function leadsStream(): boolean {
+ const s = live();
+ return s.running && (!shared() || s.leader);
+}
+
+/** Keep this tab's stream while it's hidden whenever `keep()` says so (null: the usual 30 s grace). */
+export function keepStreamWhileHidden(keep: (() => boolean) | null): void {
+ live().keepHidden = keep;
+}
+
+/** Whether another Fuobe tab is on screen: asked on the tabs' channel, answered within `ms` (false without one). */
+export function anotherTabVisible(ms = 200): Promise<boolean> {
+ const s = live();
+ if (!s.channel) return Promise.resolve(false);
+ const id = Math.random().toString(36).slice(2);
+ // (A state kept across a hot reload may predate the map.)
+ s.seen ??= new Map();
+ return new Promise((resolve) => {
+ const done = (v: boolean) => {
+ clearTimeout(timer);
+ s.seen.delete(id);
+ resolve(v);
+ };
+ const timer = setTimeout(() => done(false), ms);
+ s.seen.set(id, () => done(true));
+ post({ type: "seen?", id });
+ });
+}
+
/**
* Listen to the shared live stream (one per browser) from a view with its own caches, instead of
* opening another EventSource. Returns whether it's connected; poll when it isn't.
@@ -394,6 +443,22 @@ export function useGenerations(filter: FeedFilter, opts: { keepPrevious?: boolea
});
}
+const RUNNING: FeedFilter = { statuses: ["queued", "running"], limit: 100 };
+
+/**
+ * Everything queued or running, anywhere (the tab title's job count). The live stream keeps it
+ * current (a job that finishes leaves the list); polling is only a slow safety net.
+ */
+export function useRunningGenerations() {
+ const connected = useGenerationStream();
+ return useQuery({
+ queryKey: feedKey(RUNNING),
+ queryFn: async () => (await json<{ items: Generation[] }>(await fetch(`/api/generations?${filterToSearch(RUNNING)}`))).items,
+ structuralSharing: shareById,
+ refetchInterval: (q) => (q.state.data?.length ? (connected ? 30_000 : 5000) : false),
+ });
+}
+
export const LIBRARY_PAGE = 60;
/** The Library's paged list ("Load more" pages back with the before cursor). */
diff --git a/src/lib/generation-stream.ts b/src/lib/generation-stream.ts
index 0ffb7f0a..3754cf43 100644
--- a/src/lib/generation-stream.ts
+++ b/src/lib/generation-stream.ts
@@ -208,13 +208,21 @@ export function needsCatchUp(was: boolean, now: boolean, everConnected: boolean)
/**
* What tabs say to each other on the BroadcastChannel. One tab (the leader) reads the stream and
* passes on every event and its connection state; a tab that joins says hello to get the state.
+ * Before a system notification the leader asks "anyone on screen?" (`seen?`); a visible tab answers
+ * `seen` with the same id (src/lib/job-watch.ts: nobody is notified while they're looking at Fuobe).
*/
-export type ChannelMessage = { type: "event"; ev: StreamEvent } | { type: "state"; connected: boolean } | { type: "hello" };
+export type ChannelMessage =
+ | { type: "event"; ev: StreamEvent }
+ | { type: "state"; connected: boolean }
+ | { type: "hello" }
+ | { type: "seen?"; id: string }
+ | { type: "seen"; id: string };
export function toChannelMessage(data: unknown): ChannelMessage | null {
if (!data || typeof data !== "object") return null;
const m = data as Record<string, unknown>;
if (m.type === "hello") return { type: "hello" };
+ if ((m.type === "seen?" || m.type === "seen") && typeof m.id === "string" && m.id) return { type: m.type, id: m.id };
if (m.type === "state" && typeof m.connected === "boolean") return { type: "state", connected: m.connected };
if (m.type !== "event" || !m.ev || typeof m.ev !== "object") return null;
const ev = m.ev as Record<string, unknown>;
diff --git a/src/lib/job-watch.ts b/src/lib/job-watch.ts
new file mode 100644
index 00000000..af64a8ad
--- /dev/null
+++ b/src/lib/job-watch.ts
@@ -0,0 +1,169 @@
+/**
+ * Watching jobs from the live stream (src/lib/generation-stream.ts) for the browser: how many are
+ * running (the tab title, "(2) Fuobe"), which have just finished (a system notification while
+ * Fuobe is in the background), and when to offer those notifications. Pure, so it's tested
+ * without a browser; src/components/job-notifications.tsx wires it to the stream, the title,
+ * the Notification API and the stream's leader tab.
+ *
+ * A job is a batch: the generations that share a batchId (a pipeline's steps, a studio run, a
+ * request split into several jobs), else one generation. It's done when none of its members is
+ * queued or running, and stays done for SETTLE_MS: studios that add their next steps a moment
+ * later (Faceless: the scenes after the narration's timings) are still the same job.
+ */
+import type { Generation, GenerationStatus, MediaKind } from "./catalog/types";
+import type { StreamEvent } from "./generation-stream";
+import { userTitle } from "./library";
+
+/** How long a job must stay finished before it counts as done. */
+export const SETTLE_MS = 6000;
+/** A job running this long is worth offering notifications for (once). */
+export const OFFER_AFTER_MS = 20_000;
+
+const ACTIVE = new Set<GenerationStatus>(["queued", "running"]);
+export const isActive = (g: Pick<Generation, "status">) => ACTIVE.has(g.status);
+
+/** The job a generation belongs to. */
+export const jobKey = (g: Pick<Generation, "id" | "batchId">) => g.batchId ?? g.id;
+
+export interface WatchedJob {
+ key: string;
+ /** Member generation → its latest status. */
+ members: Record<string, GenerationStatus>;
+ /** When this browser first saw it running (its clock). */
+ since: number;
+ /** When its last member stopped running (null while one still runs). */
+ quietSince: number | null;
+ /** The member that finished last (it names the job and is what a click opens). */
+ last: Generation | null;
+ /** The first member that failed. */
+ failed: Generation | null;
+}
+
+export type WatchState = Record<string, WatchedJob>;
+
+function upsert(state: WatchState, g: Generation, now: number): WatchState {
+ const key = jobKey(g);
+ const job = state[key];
+ if (isActive(g)) {
+ const next: WatchedJob = job
+ ? { ...job, members: { ...job.members, [g.id]: g.status }, quietSince: null }
+ : { key, members: { [g.id]: g.status }, since: now, quietSince: null, last: null, failed: null };
+ return { ...state, [key]: next };
+ }
+ // A job only counts if it was seen running here: an old result changing (a like, a rename) isn't news.
+ if (!job || !(g.id in job.members)) return state;
+ const members = { ...job.members, [g.id]: g.status };
+ const running = Object.values(members).some((s) => ACTIVE.has(s));
+ return {
+ ...state,
+ [key]: {
+ ...job,
+ members,
+ quietSince: running ? null : (job.quietSince ?? now),
+ last: g.status === "succeeded" || !job.last ? g : job.last,
+ failed: job.failed ?? (g.status === "failed" ? g : null),
+ },
+ };
+}
+
+/** Apply one stream event. Returns the same object when nothing changed. */
+export function watchEvent(state: WatchState, ev: StreamEvent, now: number): WatchState {
+ if (ev.type === "generation") return ev.generation.deletedAt ? forget(state, ev.generation.id) : upsert(state, ev.generation, now);
+ return forget(state, ev.id);
+}
+
+/** A generation deleted (or trashed) stops being part of its job; a job left empty is dropped. */
+function forget(state: WatchState, id: string): WatchState {
+ const key = Object.keys(state).find((k) => id in state[k].members);
+ if (!key) return state;
+ const members = { ...state[key].members };
+ delete members[id];
+ const next = { ...state };
+ if (!Object.keys(members).length) delete next[key];
+ else next[key] = { ...state[key], members, quietSince: Object.values(members).some((s) => ACTIVE.has(s)) ? null : (state[key].quietSince ?? null) };
+ return next;
+}
+
+/** Start watching what's already running (the list loaded when the page opened). */
+export function seedWatch(state: WatchState, running: Generation[], now: number): WatchState {
+ let next = state;
+ for (const g of running) if (isActive(g) && !(jobKey(g) in next && g.id in next[jobKey(g)].members)) next = upsert(next, g, now);
+ return next;
+}
+
+/** How many jobs are running (the "(2)" in the tab title). */
+export function runningJobs(gens: Pick<Generation, "id" | "batchId" | "status">[]): number {
+ return new Set(gens.filter(isActive).map(jobKey)).size;
+}
+
+/** "(2) Library · Fuobe" — the count in front of a title (replacing an earlier one), none when idle. */
+export function titleWithCount(title: string, count: number): string {
+ const bare = title.replace(/^\(\d+\)\s+/, "");
+ return count > 0 ? `(${count}) ${bare}` : bare;
+}
+
+export interface FinishedJob {
+ key: string;
+ outcome: "ready" | "failed";
+ /** The generation to open (ready) or name (failed). */
+ generation: Generation;
+ /** How many results it made (members that succeeded). */
+ results: number;
+}
+
+/**
+ * Jobs that have stayed finished for `settle` ms: taken out of the state and returned. A job whose
+ * members were all canceled ends quietly (you canceled it).
+ */
+export function dueJobs(state: WatchState, now: number, settle = SETTLE_MS): { state: WatchState; done: FinishedJob[] } {
+ const done: FinishedJob[] = [];
+ let next = state;
+ for (const job of Object.values(state)) {
+ if (job.quietSince == null || now - job.quietSince < settle) continue;
+ if (next === state) next = { ...state };
+ delete next[job.key];
+ const results = Object.values(job.members).filter((s) => s === "succeeded").length;
+ if (job.failed) done.push({ key: job.key, outcome: "failed", generation: job.failed, results });
+ else if (job.last && results) done.push({ key: job.key, outcome: "ready", generation: job.last, results });
+ }
+ return { state: next, done };
+}
+
+/** The longest any watched job has been running (for the one-time offer). */
+export function longestRunning(state: WatchState, now: number): number {
+ return Math.max(0, ...Object.values(state).filter((j) => j.quietSince == null).map((j) => now - j.since));
+}
+
+const NOUN: Record<MediaKind, [string, string]> = {
+ image: ["image", "images"],
+ video: ["video", "videos"],
+ audio: ["audio clip", "audio clips"],
+ text: ["text", "texts"],
+ model3d: ["3D model", "3D models"],
+};
+
+const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1).trimEnd()}…` : s);
+
+/** The words of a notification: "Your video is ready" + its title; "Couldn't finish: <title>" + why. */
+export function notificationText(job: FinishedJob): { title: string; body: string } {
+ const g = job.generation;
+ const name = clip(g.request.batchTitle?.trim() || userTitle(g), 120);
+ if (job.outcome === "failed") return { title: `Couldn’t finish: ${clip(name, 60)}`, body: clip(g.error?.trim() || "Something went wrong. Open Fuobe to try again.", 160) };
+ const [one, many] = NOUN[g.kind] ?? NOUN.image;
+ const title = job.results > 1 && g.kind !== "text" ? `${job.results} ${many} are ready` : `Your ${one} is ready`;
+ return { title, body: name };
+}
+
+/**
+ * Whether this tab shows the system notification: notifications are on and allowed, it reads the
+ * live stream for the browser (the leader, so tabs don't repeat it), and nobody is looking: this
+ * tab is hidden and no other Fuobe tab is on screen.
+ */
+export function shouldNotify(s: { enabled: boolean; permission: NotificationPermission | "unsupported"; leader: boolean; hidden: boolean; otherVisible: boolean }): boolean {
+ return s.enabled && s.permission === "granted" && s.leader && s.hidden && !s.otherVisible;
+}
+
+/** Whether to offer notifications now: once, while a job has been running a while, if the browser can still ask. */
+export function shouldOffer(s: { permission: NotificationPermission | "unsupported"; enabled: boolean; asked: boolean; visible: boolean; runningFor: number }): boolean {
+ return s.permission !== "unsupported" && s.permission !== "denied" && !s.asked && !(s.enabled && s.permission === "granted") && s.visible && s.runningFor >= OFFER_AFTER_MS;
+}
diff --git a/src/lib/notification-prefs.ts b/src/lib/notification-prefs.ts
new file mode 100644
index 00000000..a00bf97c
--- /dev/null
+++ b/src/lib/notification-prefs.ts
@@ -0,0 +1,83 @@
+"use client";
+
+import { useCallback, useEffect, useSyncExternalStore } from "react";
+
+/**
+ * Browser notifications are opt-in and per browser: the choice lives in localStorage (the site's
+ * permission is the browser's anyway). Settings → Notifications and the one-time offer use this.
+ */
+const ENABLED_KEY = "fuobe.notifications";
+const ASKED_KEY = "fuobe.notifications.asked";
+
+export type Permission = NotificationPermission | "unsupported";
+
+const listeners = new Set<() => void>();
+const changed = () => listeners.forEach((l) => l());
+
+function read(key: string): string | null {
+ try {
+ return localStorage.getItem(key);
+ } catch {
+ return null;
+ }
+}
+
+function write(key: string, value: string) {
+ try {
+ localStorage.setItem(key, value);
+ } catch {}
+ changed();
+}
+
+/** The site's notification permission; "unsupported" without the API (plain http on a LAN address, some browsers). */
+export function notificationPermission(): Permission {
+ if (typeof window === "undefined" || typeof Notification === "undefined" || !window.isSecureContext) return "unsupported";
+ return Notification.permission;
+}
+
+export const notificationsEnabled = () => read(ENABLED_KEY) === "on" && notificationPermission() === "granted";
+
+function subscribe(cb: () => void) {
+ listeners.add(cb);
+ window.addEventListener("storage", cb);
+ return () => {
+ listeners.delete(cb);
+ window.removeEventListener("storage", cb);
+ };
+}
+
+const snapshot = () => `${read(ENABLED_KEY) ?? ""}|${read(ASKED_KEY) ?? ""}|${notificationPermission()}`;
+
+/** Notification preferences for this browser, kept in sync across tabs and with the site permission. */
+export function useNotificationPrefs() {
+ const snap = useSyncExternalStore(subscribe, snapshot, () => "||unsupported");
+ const [on, asked, permission] = snap.split("|") as [string, string, Permission];
+ // The permission changes in the browser's own UI too.
+ useEffect(() => {
+ let status: PermissionStatus | null = null;
+ navigator.permissions
+ ?.query({ name: "notifications" })
+ .then((s) => {
+ status = s;
+ s.onchange = changed;
+ })
+ .catch(() => {});
+ return () => {
+ if (status) status.onchange = null;
+ };
+ }, []);
+ /** Turn notifications on (asking the browser first when it hasn't been asked) or off. Resolves to whether they're on. */
+ const setEnabled = useCallback(async (v: boolean): Promise<boolean> => {
+ write(ASKED_KEY, "1");
+ if (!v) {
+ write(ENABLED_KEY, "off");
+ return false;
+ }
+ let p = notificationPermission();
+ if (p === "default") p = await Notification.requestPermission();
+ write(ENABLED_KEY, p === "granted" ? "on" : "off");
+ return p === "granted";
+ }, []);
+ const markAsked = useCallback(() => write(ASKED_KEY, "1"), []);
+ return { enabled: on === "on" && permission === "granted", asked: asked === "1", permission, setEnabled, markAsked };
+}
diff --git a/tests/e2e/notifications.mjs b/tests/e2e/notifications.mjs
new file mode 100644
index 00000000..189393c2
--- /dev/null
+++ b/tests/e2e/notifications.mjs
@@ -0,0 +1,165 @@
+// Browser notifications and the running-jobs count in the tab title (src/components/job-notifications.tsx),
+// in a real browser against the live stream. The app must be running; demo mode is fine.
+// Usage: node tests/e2e/notifications.mjs [appUrl]. Exits 1 on the first failure.
+//
+// The Notification API is replaced by a recorder (headless Chromium shows nothing) and the page can be
+// "hidden" on demand (document.visibilityState), so the checks don't depend on window focus.
+//
+// 1. The title shows "(1) …" while a job runs and drops it when it's done.
+// 2. A job finishing while the tab is hidden → one notification ("Your image is ready" + its prompt);
+// clicking it opens the result in the viewer.
+// 3. A job finishing while you look at the tab → no notification.
+// 4. The leader tab hidden while another tab is on screen → none; two hidden tabs → one (only the
+// stream's leader notifies).
+// 5. The one-time offer appears once a job has run ~20 s (clock fast-forwarded) and "Notify me" turns them on.
+// 6. Settings → Notifications: the switch and "Send a test".
+import assert from "node:assert/strict";
+import { DESKTOP, launch, openRoute } from "./_browser.mjs";
+
+const app = (process.argv.slice(2).find((a) => !a.startsWith("--")) ?? "http://localhost:3000").replace(/\/$/, "");
+const browser = await launch();
+const step = (name) => console.log(`- ${name}`);
+
+/** Record notifications, allow them (or not yet), and let the test hide the page. */
+function fakes({ permission = "granted", on = true } = {}) {
+ return [
+ ({ permission, on }) => {
+ window.__shown = [];
+ class FakeNotification {
+ static permission = permission;
+ static async requestPermission() {
+ FakeNotification.permission = "granted";
+ return "granted";
+ }
+ constructor(title, opts = {}) {
+ Object.assign(this, { title, ...opts, closed: false });
+ window.__shown.push(this);
+ }
+ close() {
+ this.closed = true;
+ }
+ }
+ window.Notification = FakeNotification;
+ let hidden = false;
+ Object.defineProperty(Document.prototype, "visibilityState", { configurable: true, get: () => (hidden ? "hidden" : "visible") });
+ Object.defineProperty(Document.prototype, "hidden", { configurable: true, get: () => hidden });
+ window.__setHidden = (v) => {
+ hidden = v;
+ document.dispatchEvent(new Event("visibilitychange"));
+ };
+ try {
+ if (on) localStorage.setItem("fuobe.notifications", "on");
+ else localStorage.removeItem("fuobe.notifications");
+ localStorage.removeItem("fuobe.notifications.asked");
+ } catch {}
+ },
+ { permission, on },
+ ];
+}
+
+/** Start a demo image job from the page (same origin, like the composer). */
+const start = (page, prompt) =>
+ page.evaluate(async (prompt) => {
+ const res = await fetch("/api/generations", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ feature: "image", modelId: "nano-banana-pro", prompt }) });
+ return (await res.json()).items[0].id;
+ }, prompt);
+
+const shown = (page) => page.evaluate(() => window.__shown.map((n) => ({ title: n.title, body: n.body, tag: n.tag })));
+
+try {
+ {
+ const ctx = await browser.newContext(DESKTOP);
+ await ctx.addInitScript(...fakes());
+ const page = await ctx.newPage();
+ await openRoute(page, `${app}/library`);
+ // Let the live stream connect first (a job created before it would only be seen by polling).
+ await page.waitForTimeout(1500);
+
+ step("the title counts the running job, then drops the count");
+ await start(page, "a red kite over the dunes");
+ await page.waitForFunction(() => document.title.startsWith("(1) "), null, { timeout: 15_000 });
+ await page.waitForFunction(() => !/^\(\d+\) /.test(document.title), null, { timeout: 30_000 });
+
+ step("finished while you look at it: no notification");
+ await page.waitForTimeout(7_000);
+ assert.deepEqual(await shown(page), []);
+
+ step("finished while the tab is hidden: one notification, and clicking it opens the result");
+ await start(page, "a paper boat in the rain");
+ await page.evaluate(() => window.__setHidden(true));
+ await page.waitForFunction(() => window.__shown.length > 0, null, { timeout: 30_000 });
+ await page.waitForTimeout(1_000);
+ const list = await shown(page);
+ assert.equal(list.length, 1, JSON.stringify(list));
+ assert.equal(list[0].title, "Your image is ready");
+ assert.equal(list[0].body, "a paper boat in the rain");
+ await page.evaluate(() => {
+ window.__setHidden(false);
+ window.__shown[0].onclick();
+ });
+ await page.getByRole("dialog").first().waitFor({ timeout: 15_000 });
+ await page.keyboard.press("Escape");
+ await ctx.close();
+ }
+ {
+ step("the leader tab hidden but another Fuobe tab on screen: no notification");
+ const ctx = await browser.newContext(DESKTOP);
+ await ctx.addInitScript(...fakes());
+ const a = await ctx.newPage();
+ const b = await ctx.newPage();
+ await openRoute(a, `${app}/library`);
+ await openRoute(b, `${app}/settings`);
+ await a.waitForTimeout(1500);
+ await a.evaluate(() => window.__setHidden(true));
+ await start(b, "you're looking at the other tab");
+ await a.waitForTimeout(16_000);
+ assert.equal((await shown(a)).length + (await shown(b)).length, 0);
+
+ step("two hidden tabs: only the stream's leader notifies");
+ await b.evaluate(() => window.__setHidden(true));
+ await start(b, "two tabs, one ping");
+ await a.waitForTimeout(16_000);
+ const total = (await shown(a)).length + (await shown(b)).length;
+ assert.equal(total, 1, `notifications across both tabs: ${total}`);
+ await ctx.close();
+ }
+ {
+ step("a job running ~20 s offers notifications once; Notify me turns them on");
+ const ctx = await browser.newContext(DESKTOP);
+ await ctx.addInitScript(...fakes({ permission: "default", on: false }));
+ const page = await ctx.newPage();
+ await page.clock.install();
+ await openRoute(page, `${app}/library`);
+ await page.clock.runFor(1500);
+ await start(page, "a slow one");
+ await page.waitForFunction(() => document.title.startsWith("(1) "), null, { timeout: 15_000 });
+ await page.clock.runFor(21_000);
+ const offer = page.getByText("Want a heads-up when it’s done?");
+ await offer.waitFor({ timeout: 10_000 });
+ await page.getByRole("button", { name: "Notify me" }).click();
+ await page.waitForFunction(() => localStorage.getItem("fuobe.notifications") === "on", null, { timeout: 5_000 });
+ await ctx.close();
+ }
+ {
+ step("Settings → Notifications: the switch and Send a test");
+ const ctx = await browser.newContext(DESKTOP);
+ await ctx.addInitScript(...fakes({ permission: "default", on: false }));
+ const page = await ctx.newPage();
+ await openRoute(page, `${app}/settings#notifications`);
+ const toggle = page.getByRole("switch", { name: /Tell me when a job is done/ });
+ assert.equal(await toggle.getAttribute("aria-checked"), "false");
+ await toggle.click();
+ await page.waitForFunction(() => localStorage.getItem("fuobe.notifications") === "on");
+ await page.getByRole("button", { name: "Send a test" }).click();
+ assert.equal((await shown(page)).at(-1)?.title, "Notifications are on");
+ await toggle.click();
+ await page.waitForFunction(() => localStorage.getItem("fuobe.notifications") === "off");
+ await ctx.close();
+ }
+ console.log("\nnotifications: all checks passed");
+} catch (e) {
+ console.error(`\nFAILED: ${e.message}`);
+ process.exitCode = 1;
+} finally {
+ await browser.close();
+}
diff --git a/tests/job-watch.test.ts b/tests/job-watch.test.ts
new file mode 100644
index 00000000..a7ba4d40
--- /dev/null
+++ b/tests/job-watch.test.ts
@@ -0,0 +1,173 @@
+import { describe, expect, it } from "vitest";
+import type { Generation } from "@/lib/catalog/types";
+import type { StreamEvent } from "@/lib/generation-stream";
+import {
+ dueJobs,
+ longestRunning,
+ notificationText,
+ OFFER_AFTER_MS,
+ runningJobs,
+ seedWatch,
+ SETTLE_MS,
+ shouldNotify,
+ shouldOffer,
+ titleWithCount,
+ watchEvent,
+ type WatchState,
+} from "@/lib/job-watch";
+
+let n = 0;
+function gen(p: Partial<Generation> = {}): Generation {
+ n++;
+ return {
+ id: `g${n}`,
+ batchId: null,
+ feature: "video",
+ presetId: null,
+ modelId: "kling-3",
+ engine: "cloud",
+ provider: "fal",
+ op: "t2v",
+ kind: "video",
+ status: "queued",
+ progress: null,
+ message: null,
+ prompt: "a fox in the snow",
+ request: { feature: "video", modelId: "kling-3", prompt: "a fox in the snow" },
+ outputs: [],
+ error: null,
+ costUsd: null,
+ favorite: false,
+ createdAt: 1000,
+ updatedAt: 1000,
+ completedAt: null,
+ ...p,
+ };
+}
+
+const ev = (g: Generation): StreamEvent => ({ type: "generation", generation: g });
+const play = (state: WatchState, events: [Generation, number][]) => events.reduce((s, [g, t]) => watchEvent(s, ev(g), t), state);
+
+describe("jobs in the tab title", () => {
+ it("counts running jobs: a pipeline's steps (one batch) are one job", () => {
+ const list = [gen({ status: "running", batchId: "b1" }), gen({ status: "queued", batchId: "b1" }), gen({ status: "queued" }), gen({ status: "succeeded" })];
+ expect(runningJobs(list)).toBe(2);
+ expect(runningJobs([])).toBe(0);
+ });
+
+ it("puts the count in front of the title, replacing an old one, and removes it when idle", () => {
+ expect(titleWithCount("Library · Fuobe", 2)).toBe("(2) Library · Fuobe");
+ expect(titleWithCount("(2) Library · Fuobe", 3)).toBe("(3) Library · Fuobe");
+ expect(titleWithCount("(3) Library · Fuobe", 0)).toBe("Library · Fuobe");
+ expect(titleWithCount("(Draft) notes", 0)).toBe("(Draft) notes");
+ });
+});
+
+describe("a finished job (watchEvent → dueJobs)", () => {
+ it("is due once it has stayed finished for the settle time, then forgotten", () => {
+ const g = gen();
+ let s = play({}, [
+ [g, 0],
+ [{ ...g, status: "running" }, 1000],
+ ]);
+ expect(dueJobs(s, 2000).done).toEqual([]);
+ const ready = { ...g, status: "succeeded" as const, outputs: [{ url: "/api/files/o.mp4", kind: "video" as const }] };
+ s = watchEvent(s, ev(ready), 30_000);
+ expect(dueJobs(s, 30_000 + SETTLE_MS - 1).done).toEqual([]);
+ const { state, done } = dueJobs(s, 30_000 + SETTLE_MS);
+ expect(done).toEqual([{ key: g.id, outcome: "ready", generation: ready, results: 1 }]);
+ expect(state).toEqual({});
+ });
+
+ it("waits for the whole pipeline, and for steps a studio adds a moment later (same batch)", () => {
+ const a = gen({ batchId: "ep" });
+ const b = gen({ batchId: "ep" });
+ let s = play({}, [
+ [a, 0],
+ [b, 0],
+ [{ ...a, status: "succeeded" }, 5000],
+ ]);
+ expect(Object.values(s)[0].quietSince).toBeNull(); // b still queued
+ s = watchEvent(s, ev({ ...b, status: "succeeded" }), 9000);
+ // Faceless starts the scene clips after the narration's timings: within the settle time, it's the same job.
+ const c = gen({ batchId: "ep" });
+ s = watchEvent(s, ev(c), 9000 + SETTLE_MS - 1000);
+ expect(dueJobs(s, 9000 + SETTLE_MS).done).toEqual([]);
+ s = watchEvent(s, ev({ ...c, status: "succeeded", kind: "video" }), 20_000);
+ const { done } = dueJobs(s, 20_000 + SETTLE_MS);
+ expect(done.map((d) => [d.key, d.outcome, d.results, d.generation.id])).toEqual([["ep", "ready", 3, c.id]]);
+ });
+
+ it("reports a failure with the failed step, and stays quiet when you canceled it", () => {
+ const a = gen({ batchId: "x" });
+ const b = gen({ batchId: "x" });
+ let s = play({}, [
+ [a, 0],
+ [b, 0],
+ [{ ...a, status: "failed", error: "Out of credits" }, 1000],
+ [{ ...b, status: "failed", error: "Waiting on a step that failed" }, 1000],
+ ]);
+ const failed = dueJobs(s, 1000 + SETTLE_MS).done[0];
+ expect([failed.outcome, failed.generation.id]).toEqual(["failed", a.id]);
+ const c = gen();
+ s = play({}, [
+ [c, 0],
+ [{ ...c, status: "canceled" }, 10],
+ ]);
+ expect(dueJobs(s, 10 + SETTLE_MS)).toEqual({ state: {}, done: [] });
+ });
+
+ it("ignores results it never saw running (an old result liked or renamed) and drops deleted ones", () => {
+ const old = gen({ status: "succeeded" });
+ expect(watchEvent({}, ev(old), 0)).toEqual({});
+ const g = gen();
+ let s = watchEvent({}, ev(g), 0);
+ s = watchEvent(s, { type: "deleted", id: g.id }, 100);
+ expect(s).toEqual({});
+ // Moved to the Trash while running: gone too.
+ s = watchEvent(watchEvent({}, ev(g), 0), ev({ ...g, deletedAt: 50 }), 50);
+ expect(s).toEqual({});
+ });
+
+ it("watches what was already running when the page opened", () => {
+ const running = [gen({ status: "running" }), gen({ status: "queued", batchId: "b" })];
+ const s = seedWatch({}, running, 0);
+ expect(Object.keys(s).sort()).toEqual([running[0].id, "b"].sort());
+ expect(seedWatch(s, running, 10)).toBe(s);
+ expect(longestRunning(s, OFFER_AFTER_MS)).toBe(OFFER_AFTER_MS);
+ });
+});
+
+describe("notifications", () => {
+ it("says what's ready in plain words, and why a job failed", () => {
+ const video = gen({ status: "succeeded", request: { feature: "video", modelId: "kling-3", prompt: "a fox in the snow" } });
+ expect(notificationText({ key: "k", outcome: "ready", generation: video, results: 1 })).toEqual({ title: "Your video is ready", body: "a fox in the snow" });
+ const images = gen({ kind: "image", status: "succeeded", request: { feature: "image", modelId: "nano-banana-pro", prompt: "x", batchTitle: "Perfume shots" } });
+ expect(notificationText({ key: "k", outcome: "ready", generation: images, results: 4 })).toEqual({ title: "4 images are ready", body: "Perfume shots" });
+ const failed = gen({ status: "failed", error: "The provider is out of credits" });
+ expect(notificationText({ key: "k", outcome: "failed", generation: failed, results: 0 })).toEqual({ title: "Couldn’t finish: a fox in the snow", body: "The provider is out of credits" });
+ });
+
+ it("only the stream's leader tab notifies, when on and allowed, and only when nobody is looking", () => {
+ const base = { enabled: true, permission: "granted" as const, leader: true, hidden: true, otherVisible: false };
+ expect(shouldNotify(base)).toBe(true);
+ expect(shouldNotify({ ...base, leader: false })).toBe(false); // another tab reads the stream: it notifies
+ expect(shouldNotify({ ...base, hidden: false })).toBe(false); // you're looking at it
+ expect(shouldNotify({ ...base, otherVisible: true })).toBe(false); // another Fuobe tab is on screen
+ expect(shouldNotify({ ...base, enabled: false })).toBe(false);
+ expect(shouldNotify({ ...base, permission: "denied" })).toBe(false);
+ });
+
+ it("offers them once, on screen, when a job has run a while and the browser can still ask", () => {
+ const base = { permission: "default" as const, enabled: false, asked: false, visible: true, runningFor: OFFER_AFTER_MS };
+ expect(shouldOffer(base)).toBe(true);
+ expect(shouldOffer({ ...base, runningFor: OFFER_AFTER_MS - 1 })).toBe(false);
+ expect(shouldOffer({ ...base, asked: true })).toBe(false);
+ expect(shouldOffer({ ...base, visible: false })).toBe(false);
+ expect(shouldOffer({ ...base, permission: "denied" })).toBe(false);
+ expect(shouldOffer({ ...base, permission: "unsupported" })).toBe(false);
+ expect(shouldOffer({ ...base, permission: "granted", enabled: true })).toBe(false);
+ // Allowed for the site but off in Fuobe and never asked: offer to turn them on.
+ expect(shouldOffer({ ...base, permission: "granted" })).toBe(true);
+ });
+});
diff --git a/tests/library-pure.test.ts b/tests/library-pure.test.ts
index 2a233eb4..c41f541b 100644
--- a/tests/library-pure.test.ts
+++ b/tests/library-pure.test.ts
@@ -282,7 +282,10 @@ describe("round-3 fixes", () => {
expect(toChannelMessage({ type: "event", ev: { type: "deleted", id: "x" } })).toEqual({ type: "event", ev: { type: "deleted", id: "x" } });
expect(toChannelMessage({ type: "state", connected: true })).toEqual({ type: "state", connected: true });
expect(toChannelMessage({ type: "hello" })).toEqual({ type: "hello" });
- for (const bad of [null, "x", { type: "state" }, { type: "event", ev: { type: "generation", generation: { id: 1 } } }, { type: "nope" }]) expect(toChannelMessage(bad)).toBeNull();
+ // "Anyone on screen?" and its answer (no notification while you're looking at another Fuobe tab).
+ expect(toChannelMessage({ type: "seen?", id: "q1" })).toEqual({ type: "seen?", id: "q1" });
+ expect(toChannelMessage({ type: "seen", id: "q1", extra: 1 })).toEqual({ type: "seen", id: "q1" });
+ for (const bad of [null, "x", { type: "state" }, { type: "event", ev: { type: "generation", generation: { id: 1 } } }, { type: "nope" }, { type: "seen?" }, { type: "seen", id: 3 }]) expect(toChannelMessage(bad)).toBeNull();
});
it("lets a server event replace a local edit (no browser clock in updatedAt)", () => {