Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor([issue-3032]): extract useHfTokenStatus and share the HF gated-access UI pieces

[._.]/ Adam Eivye4a8263f23a6
diff --git a/client/src/components/imageGen/HfTokenBanner.jsx b/client/src/components/imageGen/HfTokenBanner.jsx
index 7f83fea4b8..cbbe9557e3 100644
--- a/client/src/components/imageGen/HfTokenBanner.jsx
+++ b/client/src/components/imageGen/HfTokenBanner.jsx
@@ -15,6 +15,45 @@ import { ExternalLink, Key, Loader2 } from 'lucide-react';
import toast from '../ui/Toast';
import apiCore from '../../services/apiCore';
+/**
+ * Where a resolved token came from, phrased for the user — keyed by the `source`
+ * `server/lib/hfToken.js` reports. Shared so every gated surface names the same
+ * command: three separate copies had drifted, and one still told users to run the
+ * deprecated `huggingface-cli login` while its neighbor said `hf auth login`.
+ */
+export const HF_SOURCE_LABEL = {
+ stored: 'stored in settings',
+ env: 'from the HF_TOKEN environment variable',
+ cli: 'from `hf auth login`',
+};
+
+/**
+ * The gated repos whose terms must be accepted, as deep links. Rendered wherever
+ * gated access is explained — including the token-present case, since a token alone
+ * doesn't grant access. `linkClassName` lets a caller match its surrounding box
+ * (warning banner vs. neutral confirmation) without forking the markup.
+ * @param {{models: {label: string, url: string}[], linkClassName?: string}} props
+ */
+export function GatedModelList({ models, linkClassName = 'underline text-white' }) {
+ if (!models?.length) return null;
+ return (
+ <ul className="mt-1.5 space-y-1">
+ {models.map((m) => (
+ <li key={m.url}>
+ <a
+ href={m.url}
+ target="_blank"
+ rel="noreferrer"
+ className={`inline-flex items-center gap-1 ${linkClassName}`}
+ >
+ <ExternalLink className="h-3 w-3" /> {m.label}
+ </a>
+ </li>
+ ))}
+ </ul>
+ );
+}
+
/**
* @param {object} props
* @param {string} [props.modelLabel] Single gated model's display name.
@@ -59,15 +98,7 @@ export default function HfTokenBanner({ modelLabel, licenseUrl, models, onSaved
This needs a free Hugging Face account. Accept the terms for each gated model below (signed in to
Hugging Face), then create a read token at {tokenLink} and paste it here.
</div>
- <ul className="mt-1.5 space-y-1">
- {models.map((m) => (
- <li key={m.url}>
- <a href={m.url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 underline text-white">
- <ExternalLink className="h-3 w-3" /> {m.label}
- </a>
- </li>
- ))}
- </ul>
+ <GatedModelList models={models} />
</div>
) : (
<div>
diff --git a/client/src/components/install/MidiGatedModal.jsx b/client/src/components/install/MidiGatedModal.jsx
index add71841d6..6d4154f590 100644
--- a/client/src/components/install/MidiGatedModal.jsx
+++ b/client/src/components/install/MidiGatedModal.jsx
@@ -19,41 +19,26 @@
import { useEffect, useState } from 'react';
import { KeyRound, Loader2, RotateCw } from 'lucide-react';
import Modal from '../ui/Modal';
-import HfTokenBanner from '../imageGen/HfTokenBanner';
-import { getHfTokenStatus } from '../../services/api';
-
-const SOURCE_LABEL = {
- stored: 'stored in settings',
- env: 'from the HF_TOKEN environment variable',
- cli: 'from `hf auth login`',
-};
+import HfTokenBanner, { HF_SOURCE_LABEL } from '../imageGen/HfTokenBanner';
+import { useHfTokenStatus } from '../../hooks/useHfTokenStatus';
export default function MidiGatedModal({ open, repo, onSaved, onClose }) {
const licenseUrl = repo ? `https://huggingface.co/${repo}` : 'https://huggingface.co';
const licenseLinkText = licenseUrl.replace(/^https?:\/\//, '');
- // null = still checking; then { hfTokenPresent, source }. Re-checked each time
- // the modal opens so a token saved on a prior pass is reflected.
- const [tokenStatus, setTokenStatus] = useState(null);
+ // Re-checked each time the modal opens (the hook resets to unknown while closed)
+ // so a token saved on a prior pass is reflected. `errorAs: 'absent'` because this
+ // modal only opens AFTER a gated-repo 403 — if the status call itself fails, the
+ // paste form is the more useful guess than showing nothing.
+ const { present: tokenPresent, source: tokenSource } = useHfTokenStatus({ enabled: open, errorAs: 'absent' });
// Escape hatch: when a token IS present but the license-accept + retry still
// 403s, the stored token may be invalid — let the user drop to the paste form.
const [forceTokenEntry, setForceTokenEntry] = useState(false);
- useEffect(() => {
- if (!open) {
- setTokenStatus(null);
- setForceTokenEntry(false);
- return;
- }
- let cancelled = false;
- getHfTokenStatus()
- .then((s) => { if (!cancelled) setTokenStatus({ hfTokenPresent: !!s?.hfTokenPresent, source: s?.source || 'none' }); })
- .catch(() => { if (!cancelled) setTokenStatus({ hfTokenPresent: false, source: 'none' }); });
- return () => { cancelled = true; };
- }, [open]);
+ useEffect(() => { if (!open) setForceTokenEntry(false); }, [open]);
- const checking = tokenStatus === null;
- const hasToken = !!tokenStatus?.hfTokenPresent;
+ const checking = tokenPresent === null;
+ const hasToken = tokenPresent === true;
// Show the license-only view when a token is already configured and the user
// hasn't explicitly asked to replace it.
const licenseOnly = hasToken && !forceTokenEntry;
@@ -87,7 +72,7 @@ export default function MidiGatedModal({ open, repo, onSaved, onClose }) {
<div className="rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-3 text-xs text-port-warning space-y-3">
<div>
Your HuggingFace token is already configured
- {SOURCE_LABEL[tokenStatus.source] ? ` (${SOURCE_LABEL[tokenStatus.source]})` : ''} — but you
+ {HF_SOURCE_LABEL[tokenSource] ? ` (${HF_SOURCE_LABEL[tokenSource]})` : ''} — but you
haven&apos;t accepted the license for{' '}
<a href={licenseUrl} target="_blank" rel="noreferrer" className="underline text-white">
{licenseLinkText}
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 1ed84e3bfc..a98ec5b1b0 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -102,6 +102,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `usePendingListRows` | List-of-rows where a new row is held client-side until a required column fills, then promoted to `onChange`. | Editable list whose nameless rows would otherwise be dropped by the server sanitizer (WardrobeSection, CharacterDetailEditor list sections). |
| `useKeyboardControls` | Keyboard binding for CyberCity mode toggle. | CyberCity-specific. |
| `useKeyboardShortcuts` | `useKeyboardShortcuts(active, bindings, opts?)` — fire a `{ key: handler }` map while `active`; ignores events from editable fields (`isEditableTarget` also exported), ⌘/Ctrl/Alt chords, OS key auto-repeat (`{ ignoreRepeat: false }` to opt back in), and any keystroke while an `aria-modal` dialog is open (`{ enabledInDialog: true }` for a modal-owned shortcut); a falsy handler disables that key. | Single-surface action shortcuts (editorial comment card prev/next + accept/dismiss/generate, #1603). Not for held-key/game input (that's `useKeyboardControls`). |
+| `useHfTokenStatus` | Reads the central HuggingFace token status (`GET /image-gen/setup/hf-token-status` → `server/lib/hfToken.js`: stored → env → `hf auth login`). Returns `{ present, source, refresh }` where `present` is TRI-state — `null` means "unknown/failed", not "absent" — so a slow fetch can't flash a token nag at a user who has one. `{ enabled }` gates the fetch (false resets to unknown, so a modal re-checks per open); `{ errorAs: 'absent' }` opts a surface into offering the paste form when the status call fails. | Any gated-HuggingFace surface (3D page, MIDI gated modal, Image Gen banners) — use this instead of re-rolling the fetch, or the same blip renders differently per page. |
| `useKeyboardHelp` | Esc closes, even from inputs/textareas. | Help/cheatsheet modals. |
| `useLockToggle` | Optimistic-PATCH lock toggle. | New "lock this field/stage/arc" button — use this, do not re-implement. |
| `usePopoverPosition` | Viewport-clamped `{ left, top, width }` for a fixed-position portal popover anchored to a trigger; re-measures on open and rAF-coalesced on capture-phase scroll/resize. Returns `{ triggerRef, popoverRef, style, reposition }`; pass `anchorRef` to follow a parent-owned trigger. | Any portal-into-`<body>` menu/popover placed relative to a button (ThemeSwitcher, CollectionPickerShell) — use this instead of re-rolling the measure/flip/clamp/reflow plumbing. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 7715f5a7d7..86b530ae52 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -118,6 +118,7 @@ export * from './useAutoRefetch.js';
export * from './useCmdKSearch.js';
export * from './useCooldownTick.js';
export { default as useDrawerTab } from './useDrawerTab.js';
+export * from './useHfTokenStatus.js';
export * from './useKeyboardHelp.js';
export * from './useLockToggle.js';
export * from './useScrollLock.js';
diff --git a/client/src/hooks/useHfTokenStatus.js b/client/src/hooks/useHfTokenStatus.js
new file mode 100644
index 0000000000..0f56eb40ed
--- /dev/null
+++ b/client/src/hooks/useHfTokenStatus.js
@@ -0,0 +1,64 @@
+/**
+ * Read the CENTRAL HuggingFace token status (`GET /image-gen/setup/hf-token-status`,
+ * backed by `server/lib/hfToken.js`: stored token → env vars → `hf auth login` file).
+ *
+ * Every gated-model surface needs the same three-state answer — token present / not
+ * present / not yet known — and each one had grown its own copy with its own failure
+ * policy, so the same offline blip rendered a nag on one page and nothing on another.
+ * This is the single reader.
+ *
+ * `present` is deliberately tri-state: `null` means "not fetched yet or the fetch
+ * failed", NOT "absent". Callers must branch on all three, or a slow status call
+ * flashes "add a token" at a user who already has one (the absent-vs-unknown rule in
+ * CLAUDE.md). A surface that would rather offer the paste form on a failed fetch opts
+ * in explicitly with `errorAs: 'absent'`.
+ */
+
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { getHfTokenStatus } from '../services/api';
+import useMounted from './useMounted';
+
+const UNKNOWN = { present: null, source: null };
+
+/**
+ * @param {object} [options]
+ * @param {boolean} [options.enabled] Fetch when true; flipping to false resets the
+ * status to unknown, so a modal re-checks on each open instead of showing a stale
+ * answer from a previous session.
+ * @param {'unknown'|'absent'} [options.errorAs] What a failed fetch means. Default
+ * `'unknown'` (render nothing rather than lie). `'absent'` suits a surface already
+ * opened *because* of a gated-repo failure, where offering the paste form is the
+ * more useful guess.
+ * @returns {{present: boolean|null, source: string|null, refresh: () => void}}
+ */
+export function useHfTokenStatus({ enabled = true, errorAs = 'unknown' } = {}) {
+ const [status, setStatus] = useState(UNKNOWN);
+ const mountedRef = useMounted();
+ // Generation counter so a response from a previous open/refresh can't overwrite a
+ // newer one (the repo's stale-async convention).
+ const runIdRef = useRef(0);
+
+ const refresh = useCallback(() => {
+ const runId = ++runIdRef.current;
+ const apply = (next) => {
+ if (mountedRef.current && runIdRef.current === runId) setStatus(next);
+ };
+ getHfTokenStatus()
+ .then((data) => apply({ present: !!data?.hfTokenPresent, source: data?.source || 'none' }))
+ .catch(() => { if (errorAs === 'absent') apply({ present: false, source: 'none' }); });
+ }, [errorAs, mountedRef]);
+
+ useEffect(() => {
+ if (!enabled) {
+ // Invalidate any in-flight response so it can't land after the reset.
+ runIdRef.current += 1;
+ setStatus(UNKNOWN);
+ return;
+ }
+ refresh();
+ }, [enabled, refresh]);
+
+ return { ...status, refresh };
+}
+
+export default useHfTokenStatus;
diff --git a/client/src/hooks/useHfTokenStatus.test.js b/client/src/hooks/useHfTokenStatus.test.js
new file mode 100644
index 0000000000..984ac2a87a
--- /dev/null
+++ b/client/src/hooks/useHfTokenStatus.test.js
@@ -0,0 +1,80 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { renderHook, waitFor, act } from '@testing-library/react';
+
+const getHfTokenStatus = vi.fn();
+vi.mock('../services/api', () => ({ getHfTokenStatus: (...a) => getHfTokenStatus(...a) }));
+
+import { useHfTokenStatus } from './useHfTokenStatus';
+
+describe('useHfTokenStatus', () => {
+ beforeEach(() => { vi.clearAllMocks(); });
+
+ it('starts unknown and resolves to the fetched presence + source', async () => {
+ getHfTokenStatus.mockResolvedValue({ hfTokenPresent: true, source: 'env' });
+ const { result } = renderHook(() => useHfTokenStatus());
+ // Tri-state: unknown BEFORE the fetch settles — callers render nothing here
+ // rather than flashing a token nag at someone who has one.
+ expect(result.current.present).toBeNull();
+ await waitFor(() => expect(result.current.present).toBe(true));
+ expect(result.current.source).toBe('env');
+ });
+
+ it('leaves the status unknown when the fetch fails, by default', async () => {
+ getHfTokenStatus.mockRejectedValue(new Error('offline'));
+ const { result } = renderHook(() => useHfTokenStatus());
+ await waitFor(() => expect(getHfTokenStatus).toHaveBeenCalled());
+ // A transient blip must not read as "no token" — that's the absent-vs-failed rule.
+ expect(result.current.present).toBeNull();
+ });
+
+ it('reports a failed fetch as absent when the caller opts in', async () => {
+ getHfTokenStatus.mockRejectedValue(new Error('offline'));
+ const { result } = renderHook(() => useHfTokenStatus({ errorAs: 'absent' }));
+ await waitFor(() => expect(result.current.present).toBe(false));
+ expect(result.current.source).toBe('none');
+ });
+
+ it('does not fetch while disabled, and resets to unknown when disabled again', async () => {
+ getHfTokenStatus.mockResolvedValue({ hfTokenPresent: true, source: 'stored' });
+ const { result, rerender } = renderHook(({ enabled }) => useHfTokenStatus({ enabled }), {
+ initialProps: { enabled: false },
+ });
+ expect(getHfTokenStatus).not.toHaveBeenCalled();
+ expect(result.current.present).toBeNull();
+
+ rerender({ enabled: true });
+ await waitFor(() => expect(result.current.present).toBe(true));
+
+ // Closing a modal must clear the answer so the next open re-checks rather than
+ // showing a stale one.
+ rerender({ enabled: false });
+ expect(result.current.present).toBeNull();
+ });
+
+ it('refresh() re-reads the status after a token is saved', async () => {
+ getHfTokenStatus.mockResolvedValue({ hfTokenPresent: false, source: 'none' });
+ const { result } = renderHook(() => useHfTokenStatus());
+ await waitFor(() => expect(result.current.present).toBe(false));
+
+ getHfTokenStatus.mockResolvedValue({ hfTokenPresent: true, source: 'stored' });
+ act(() => { result.current.refresh(); });
+ await waitFor(() => expect(result.current.present).toBe(true));
+ expect(result.current.source).toBe('stored');
+ });
+
+ it('drops a stale in-flight response so it cannot overwrite a newer one', async () => {
+ let resolveFirst;
+ getHfTokenStatus.mockImplementationOnce(() => new Promise((r) => { resolveFirst = r; }));
+ const { result } = renderHook(() => useHfTokenStatus());
+
+ // A second read starts and lands while the first is still pending.
+ getHfTokenStatus.mockResolvedValue({ hfTokenPresent: true, source: 'stored' });
+ act(() => { result.current.refresh(); });
+ await waitFor(() => expect(result.current.present).toBe(true));
+
+ // The stale first response now settles — it must NOT clobber the newer answer.
+ await act(async () => { resolveFirst({ hfTokenPresent: false, source: 'none' }); });
+ expect(result.current.present).toBe(true);
+ expect(result.current.source).toBe('stored');
+ });
+});
diff --git a/client/src/pages/Media3D.jsx b/client/src/pages/Media3D.jsx
index e9c56f861e..4405fbbd93 100644
--- a/client/src/pages/Media3D.jsx
+++ b/client/src/pages/Media3D.jsx
@@ -1,14 +1,15 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import { Boxes, CheckCircle2, Download, AlertTriangle, Loader2, ExternalLink, ImagePlus, Sparkles, KeyRound } from 'lucide-react';
-import { getImageTo3dTargets, createImageTo3dModel, getImageTo3dModel, listImageTo3dModels, getHfTokenStatus } from '../services/api';
+import { getImageTo3dTargets, createImageTo3dModel, getImageTo3dModel, listImageTo3dModels } from '../services/api';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
import useMounted from '../hooks/useMounted';
import { nameFromImageFilename, timeAgo } from '../utils/formatters';
import RuntimeInstallModal from '../components/install/RuntimeInstallModal';
import GalleryImagePicker from '../components/imageGen/GalleryImagePicker';
import GlbViewer from '../components/media/GlbViewer';
-import HfTokenBanner from '../components/imageGen/HfTokenBanner';
+import HfTokenBanner, { GatedModelList, HF_SOURCE_LABEL } from '../components/imageGen/HfTokenBanner';
+import { useHfTokenStatus } from '../hooks/useHfTokenStatus';
import MediaImage from '../components/MediaImage';
import { imageTo3dStatusMeta } from '../components/media/imageTo3dStatus';
@@ -26,15 +27,6 @@ const HF_GATED_MODELS = {
],
};
-// How the resolved token reached us, for the "already configured" line. PortOS
-// injects whichever one it found into the render's environment, so all three are
-// equally good — naming the source just tells the user where to change it.
-const HF_SOURCE_LABEL = {
- stored: 'saved in PortOS',
- env: 'from the HF_TOKEN environment variable',
- cli: 'from huggingface-cli login',
-};
-
// Prerequisite notice for a target that needs gated Hugging Face access. Driven by
// the CENTRAL token store (GET /image-gen/setup/hf-token-status) — the same one the
// Image Gen page writes — so a user who already pasted a token isn't told to go set
@@ -62,15 +54,7 @@ function HfAccessNotice({ models, tokenPresent, tokenSource, onSaved }) {
Accept the terms for these gated models on your Hugging Face account if you haven’t — a token alone
doesn’t grant access:
</p>
- <ul className="mt-1.5 space-y-1">
- {models.map((m) => (
- <li key={m.url}>
- <a href={m.url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-port-accent hover:underline">
- <ExternalLink className="h-3 w-3" /> {m.label}
- </a>
- </li>
- ))}
- </ul>
+ <GatedModelList models={models} linkClassName="text-port-accent hover:underline" />
</div>
);
}
@@ -191,10 +175,9 @@ export default function Media3D() {
// Existing image-to-3D records (newest-first) so the page doubles as a library:
// each links to its `/media/3d/:id` detail view.
const [records, setRecords] = useState([]);
- // Central HF-token status (stored / env / cli), for the gated-model notice.
- // `null` = not fetched yet — distinct from `false` (fetched, genuinely absent), so
- // a slow status call can't flash the "add a token" banner at a user who has one.
- const [hfToken, setHfToken] = useState({ present: null, source: null });
+ // Central HF-token status (stored / env / cli) for the gated-model notice. `present`
+ // is tri-state — see useHfTokenStatus; `null` means unknown, not absent.
+ const { present: hfTokenPresent, source: hfTokenSource, refresh: refreshHfToken } = useHfTokenStatus();
const mountedRef = useMounted(); // gate setState after the create/poll awaits
const load = useCallback(() => {
@@ -220,20 +203,8 @@ export default function Media3D() {
: [record, ...prev]));
}, [mountedRef]);
- // Read-only presence check against the shared store — no LLM/provider call, so it
- // is safe to run on mount. A failure leaves `present: null`, which renders nothing
- // rather than nagging on a transient blip.
- const loadHfToken = useCallback(() => {
- getHfTokenStatus()
- .then((data) => {
- if (mountedRef.current) setHfToken({ present: !!data?.hfTokenPresent, source: data?.source || null });
- })
- .catch(() => { /* leave unknown — the notice stays hidden rather than lying */ });
- }, [mountedRef]);
-
useEffect(() => { load(); }, [load]);
useEffect(() => { loadRecords(); }, [loadRecords]);
- useEffect(() => { loadHfToken(); }, [loadHfToken]);
const selectedImage = useMemo(
() => (imageFromRoute
@@ -396,9 +367,9 @@ export default function Media3D() {
{gatedHfModels && (
<HfAccessNotice
models={gatedHfModels}
- tokenPresent={hfToken.present}
- tokenSource={hfToken.source}
- onSaved={loadHfToken}
+ tokenPresent={hfTokenPresent}
+ tokenSource={hfTokenSource}
+ onSaved={refreshHfToken}
/>
)}
diff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.js
index ba0e9ea4ed..c3fcd68792 100644
--- a/server/services/imageTo3d/models.js
+++ b/server/services/imageTo3d/models.js
@@ -40,6 +40,10 @@ const activeRenders = new Map();
* A runner takes `{ imagePath, outputPath, onProgress, env }` and returns a
* `{ promise, kill }` pair — `promise` resolves `{ assetPath }`; `kill` SIGTERMs the
* render so a mid-flight delete can terminate it (see `runTrellis2Generate`).
+ * `env` is a LOCAL-lane concern (the child-process environment, carrying the HF
+ * token); a future hosted-API runner should ignore it, and when one lands this is
+ * the seam to generalize into a per-runner credential declaration rather than a
+ * spawn-shaped bag every target receives.
*/
const TARGET_RUNNERS = {
trellis2: { isInstalled: isTrellis2Installed, run: runTrellis2Generate },