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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: gate Prompt Guard install on Hugging Face access
[._.]/ Adam Eivy10fa574ac003
diff --git a/client/src/components/imageGen/HfTokenBanner.jsx b/client/src/components/imageGen/HfTokenBanner.jsxindex d4e35e00e2..3375d6459a 100644--- a/client/src/components/imageGen/HfTokenBanner.jsx+++ b/client/src/components/imageGen/HfTokenBanner.jsx@@ -32,7 +32,7 @@ export const HF_SOURCE_LABEL = {* 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+ * @param {{models: {label: string, url: string, linkLabel?: string}[], linkClassName?: string}} props*/export function GatedModelList({ models, linkClassName = 'underline text-white' }) {if (!models?.length) return null;@@ -46,7 +46,7 @@ export function GatedModelList({ models, linkClassName = 'underline text-white'rel="noreferrer"className={`inline-flex items-center gap-1 ${linkClassName}`}>- <ExternalLink className="h-3 w-3" /> {m.label}+ <ExternalLink className="h-3 w-3" /> {m.linkLabel || m.label}</a></li>))}@@ -92,8 +92,9 @@ export default function HfTokenBanner({ modelLabel, licenseUrl, models, onSavedreturn (<div className="rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-3 text-xs text-port-warning space-y-2"><div>- 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.+ This needs a free Hugging Face account. Open each gated model card below, submit any required+ usage/access request, and accept its terms (while signed in to Hugging Face). Then create a read+ token at {tokenLink} and paste it here.<GatedModelList models={list} /></div><div className="flex flex-col sm:flex-row gap-2 items-stretch sm:items-center">diff --git a/client/src/components/imageGen/PromptGuardHfAccessNotice.jsx b/client/src/components/imageGen/PromptGuardHfAccessNotice.jsxnew file mode 100644index 0000000000..49829c5572--- /dev/null+++ b/client/src/components/imageGen/PromptGuardHfAccessNotice.jsx@@ -0,0 +1,83 @@+import { useEffect, useState } from 'react';+import { KeyRound, Loader2 } from 'lucide-react';+import HfTokenBanner, { GatedModelList, HF_SOURCE_LABEL } from './HfTokenBanner';++const DEFAULT_MODEL = {+ name: 'Llama Prompt Guard 2 86M',+ sourceUrl: 'https://huggingface.co/meta-llama/Llama-Prompt-Guard-2-86M',+};++/**+ * Hugging Face access prerequisite for the managed Prompt Guard classifier.+ *+ * A token and gated-model approval are separate facts: the token can already be+ * configured while the model owner still has to approve the usage request. The+ * caller supplies the central tri-state token status so an unavailable status+ * check never flashes a false "add a token" form.+ */+export default function PromptGuardHfAccessNotice({ tokenPresent, tokenSource, model, onSaved }) {+ const [replacing, setReplacing] = useState(false);+ const resolvedModel = {+ name: typeof model?.name === 'string' && model.name.trim() ? model.name.trim() : DEFAULT_MODEL.name,+ sourceUrl: typeof model?.sourceUrl === 'string' && model.sourceUrl.trim()+ ? model.sourceUrl.trim()+ : DEFAULT_MODEL.sourceUrl,+ };+ const accessModel = {+ label: resolvedModel.name,+ url: resolvedModel.sourceUrl,+ linkLabel: 'Open model card and submit usage request',+ };++ useEffect(() => {+ if (!tokenPresent) setReplacing(false);+ }, [tokenPresent]);++ const handleSaved = () => {+ setReplacing(false);+ onSaved?.();+ };++ if (tokenPresent === null) {+ return (+ <div className="flex items-center gap-2 text-xs text-gray-400" data-testid="prompt-guard-hf-checking">+ <Loader2 size={14} className="animate-spin" />+ Checking Hugging Face token status…+ </div>+ );+ }++ if (!tokenPresent || replacing) {+ return (+ <div data-testid="prompt-guard-hf-token-entry" className="space-y-2">+ <p className="text-xs text-port-warning">+ Prompt Guard is a gated Hugging Face model. Submit the usage request on its model card and accept+ any terms before installing; the token below only authenticates the download.+ </p>+ <HfTokenBanner models={[accessModel]} onSaved={handleSaved} />+ </div>+ );+ }++ return (+ <div data-testid="prompt-guard-hf-access" className="rounded-lg border border-port-border bg-port-bg/40 p-3 text-xs text-gray-400">+ <div className="flex items-center gap-1.5 font-medium text-port-success">+ <KeyRound className="h-3.5 w-3.5" />+ Hugging Face token configured+ {HF_SOURCE_LABEL[tokenSource] ? ` (${HF_SOURCE_LABEL[tokenSource]})` : ''}+ </div>+ <p className="mt-1">+ A token does not grant gated access by itself. Submit the usage request and accept the model terms+ on your Hugging Face account before retrying the install:+ </p>+ <GatedModelList models={[accessModel]} linkClassName="text-port-accent hover:underline" />+ <button+ type="button"+ onClick={() => setReplacing(true)}+ className="mt-2 text-xs underline text-gray-400 hover:text-white"+ >+ Use a different token+ </button>+ </div>+ );+}diff --git a/client/src/components/imageGen/PromptGuardHfAccessNotice.test.jsx b/client/src/components/imageGen/PromptGuardHfAccessNotice.test.jsxnew file mode 100644index 0000000000..d80ad11544--- /dev/null+++ b/client/src/components/imageGen/PromptGuardHfAccessNotice.test.jsx@@ -0,0 +1,49 @@+import { describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen } from '@testing-library/react';+import PromptGuardHfAccessNotice from './PromptGuardHfAccessNotice';++vi.mock('../ui/Toast', () => ({+ default: Object.assign(vi.fn(), {+ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn(),+ }),+}));++const MODEL = {+ name: 'Llama Prompt Guard 2 86M',+ sourceUrl: 'https://huggingface.co/meta-llama/Llama-Prompt-Guard-2-86M',+};++describe('PromptGuardHfAccessNotice', () => {+ it('does not guess that a token is absent while the status check is pending', () => {+ render(<PromptGuardHfAccessNotice tokenPresent={null} model={MODEL} />);++ expect(screen.getByTestId('prompt-guard-hf-checking')).toHaveTextContent('Checking Hugging Face token status');+ expect(screen.queryByPlaceholderText('hf_…')).toBeNull();+ });++ it('reuses the token-entry banner and explicitly links to the usage request', () => {+ render(<PromptGuardHfAccessNotice tokenPresent={false} tokenSource="none" model={MODEL} />);++ expect(screen.getByTestId('prompt-guard-hf-token-entry')).toBeInTheDocument();+ expect(screen.getByPlaceholderText('hf_…')).toBeInTheDocument();+ expect(screen.getByRole('link', { name: /open model card and submit usage request/i })).toHaveAttribute(+ 'href',+ MODEL.sourceUrl,+ );+ });++ it('shows the access-request branch without asking for a second token', () => {+ render(<PromptGuardHfAccessNotice tokenPresent model={MODEL} tokenSource="stored" />);++ expect(screen.getByTestId('prompt-guard-hf-access')).toHaveTextContent('token configured (stored in settings)');+ expect(screen.getByRole('link', { name: /submit usage request/i })).toHaveAttribute('href', MODEL.sourceUrl);+ expect(screen.queryByPlaceholderText('hf_…')).toBeNull();+ });++ it('keeps the replacement-token escape hatch', () => {+ render(<PromptGuardHfAccessNotice tokenPresent model={MODEL} tokenSource="env" />);++ fireEvent.click(screen.getByRole('button', { name: /use a different token/i }));+ expect(screen.getByPlaceholderText('hf_…')).toBeInTheDocument();+ });+});diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex 0cd0a542c4..0dde3cd843 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -23,7 +23,9 @@ import RuntimeServersCard from './RuntimeServersCard.jsx';import MtplxServerCard from './MtplxServerCard.jsx';import LocalLlmBackendCard from './LocalLlmBackendCard.jsx';import LocalLlmInstalledModels from './LocalLlmInstalledModels.jsx';+import PromptGuardHfAccessNotice from '../imageGen/PromptGuardHfAccessNotice.jsx';import TabPills from '../ui/TabPills.jsx';+import { useHfTokenStatus } from '../../hooks/useHfTokenStatus';const BACKENDS = [{ id: 'ollama', label: 'Ollama', icon: Cpu },@@ -166,6 +168,9 @@ export function LocalLlmTab({ view }) {const [catalogLoading, setCatalogLoading] = useState(false);const [catalogError, setCatalogError] = useState('');const [guardStatus, setGuardStatus] = useState(null);+ const { present: guardHfTokenPresent, source: guardHfTokenSource, refresh: refreshGuardHfToken } = useHfTokenStatus({+ enabled: activeView === 'library',+ });// Total unified/system memory (GB) reported by the HF search, used to caption// the RAM-aware quant defaults. null until the first Hugging Face search.const [systemMemoryGb, setSystemMemoryGb] = useState(null);@@ -1535,6 +1540,12 @@ export function LocalLlmTab({ view }) {<p className="text-xs text-gray-300 max-w-3xl">Llama Prompt Guard 2 86M screens complete external issues, comments, and pull-request diffs before they reach a reasoning agent. It is a pinned local classifier with no chat, tools, MCP, or repository access; flagged or inconclusive content is withheld.</p>+ <PromptGuardHfAccessNotice+ tokenPresent={guardHfTokenPresent}+ tokenSource={guardHfTokenSource}+ model={guardStatus}+ onSaved={refreshGuardHfToken}+ /><div className="flex items-center gap-2 flex-wrap text-[11px] text-gray-500"><span>Llama Prompt Guard 2 86M</span><span>·</span>@@ -1566,7 +1577,7 @@ export function LocalLlmTab({ view }) {<buttontype="button"onClick={installGuard}- disabled={busy || !guardStatus}+ disabled={busy || !guardStatus || guardHfTokenPresent !== true}className="px-2.5 py-1 text-xs bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1"><Download size={12} /> Install model-abuse guarddiff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsxindex ef6551db88..91840597b6 100644--- a/client/src/components/settings/LocalLlmTab.test.jsx+++ b/client/src/components/settings/LocalLlmTab.test.jsx@@ -7,6 +7,7 @@ vi.mock('../../services/api', () => ({getLocalLlmCatalog: vi.fn(),getLocalLlmHuggingFaceSearch: vi.fn(),getModelAbuseGuardStatus: vi.fn(),+ getHfTokenStatus: vi.fn(),installModelAbuseGuard: vi.fn(),cancelModelAbuseGuardInstall: vi.fn(),installLocalLlmModel: vi.fn(),@@ -49,6 +50,7 @@ import {getLocalLlmStatus,getLocalLlmCatalog,getModelAbuseGuardStatus,+ getHfTokenStatus,installModelAbuseGuard,cancelModelAbuseGuardInstall,installLocalLlmBackend,@@ -117,6 +119,7 @@ beforeEach(() => {modelCached: false,runtimeReady: false,});+ getHfTokenStatus.mockResolvedValue({ hfTokenPresent: true, source: 'stored' });installModelAbuseGuard.mockResolvedValue({ ok: true, ready: true });cancelModelAbuseGuardInstall.mockResolvedValue({ cancelled: true });installLocalLlmBackend.mockResolvedValue({ success: true });diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 227c3b8593..4470a0bac6 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -194,8 +194,14 @@ router.post('/security-guard/install', asyncHandler(async (req, res) => {onEvent: ({ event, message }) => emit(event, message),})if (!result?.ok) {- emit('error', result?.code || 'Prompt Guard installation failed')- throw new ServerError(result?.code || 'Prompt Guard installation failed', { status: 502 })+ const code = result?.code || 'security-guard-install-failed'+ const message = code === 'security-guard-huggingface-token-required'+ ? 'Add a Hugging Face read token before installing Prompt Guard.'+ : code === 'security-guard-huggingface-access-required'+ ? 'Hugging Face has not granted Prompt Guard access yet. Submit the usage request on its model card, then retry.'+ : code+ emit('error', message)+ throw new ServerError(message, { status: 502, code })}res.json(result)}))diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.jsindex b7d88c2cd9..2c916197f2 100644--- a/server/routes/localLlm.test.js+++ b/server/routes/localLlm.test.js@@ -190,6 +190,30 @@ describe('local LLM playground routes', () => {expect(cancelModelAbuseGuardInstall).toHaveBeenCalled();});+ it('returns actionable Prompt Guard access prerequisites from the install route', async () => {+ installModelAbuseGuard.mockResolvedValueOnce({+ ok: false,+ code: 'security-guard-huggingface-token-required',+ });+ const missingToken = await request(makeApp()).post('/api/local-llm/security-guard/install').send({});+ expect(missingToken.status).toBe(502);+ expect(missingToken.body).toMatchObject({+ code: 'security-guard-huggingface-token-required',+ error: 'Add a Hugging Face read token before installing Prompt Guard.',+ });++ installModelAbuseGuard.mockResolvedValueOnce({+ ok: false,+ code: 'security-guard-huggingface-access-required',+ });+ const missingAccess = await request(makeApp()).post('/api/local-llm/security-guard/install').send({});+ expect(missingAccess.status).toBe(502);+ expect(missingAccess.body).toMatchObject({+ code: 'security-guard-huggingface-access-required',+ error: 'Hugging Face has not granted Prompt Guard access yet. Submit the usage request on its model card, then retry.',+ });+ });+it('POST /install forwards force so a redownload can replace on-disk weights', async () => {installModel.mockResolvedValue({ success: true, modelId: 'unsloth/Qwen3.8-27B-GGUF@UD-Q4_K_M' });diff --git a/server/services/modelAbuseGuard.js b/server/services/modelAbuseGuard.jsindex ba1b3988f1..7ede94be9c 100644--- a/server/services/modelAbuseGuard.js+++ b/server/services/modelAbuseGuard.js@@ -41,6 +41,7 @@ import { withSpawnCwdEnv } from '../lib/spawnCwd.js';import { detectVenvBasePythonSync, createVenv, installPackages } from '../lib/pythonSetup.js';import { safeChildProcessOptions } from '../lib/processEnv.js';import { downloadHfRepo } from './hfDownload.js';+import { getHfToken } from './hfToken.js';import { listModels } from './localLlm.js';import * as ollamaManager from './ollamaManager.js';@@ -279,6 +280,11 @@ export async function getModelAbuseGuardStatus() {export function installModelAbuseGuard({ onEvent } = {}) {if (installInFlight) return installInFlight;installInFlight = (async () => {+ // Do this before creating a venv or installing packages. The model is gated+ // on Hugging Face, so a missing token is an operator prerequisite—not a+ // reason to leave a half-useful runtime behind and discover the problem+ // only after setup has changed the install.+ if (!(await getHfToken())) return failure('security-guard-huggingface-token-required');const basePython = detectVenvBasePythonSync();if (!basePython) return failure('security-guard-python-unavailable');await ensureDir(dirname(GUARD_VENV_DIR));diff --git a/server/services/modelAbuseGuard.test.js b/server/services/modelAbuseGuard.test.jsindex c92aacfb8a..6ea217e901 100644--- a/server/services/modelAbuseGuard.test.js+++ b/server/services/modelAbuseGuard.test.js@@ -2,11 +2,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const listModels = vi.fn();const getModelCapabilities = vi.fn();+const getHfToken = vi.fn();vi.mock('./localLlm.js', () => ({ listModels }));vi.mock('./ollamaManager.js', () => ({ getModelCapabilities }));+vi.mock('./hfToken.js', () => ({ getHfToken }));-const { validatePublicReviewModel } = await import('./modelAbuseGuard.js');+const { installModelAbuseGuard, validatePublicReviewModel } = await import('./modelAbuseGuard.js');const LOCAL_CLAUDE = {id: 'claude-ollama',@@ -19,6 +21,7 @@ const LOCAL_CLAUDE = {describe('validatePublicReviewModel', () => {beforeEach(() => {vi.clearAllMocks();+ getHfToken.mockResolvedValue('hf_test_token');listModels.mockResolvedValue([{ id: 'safe-model' }]);getModelCapabilities.mockResolvedValue(['completion']);});@@ -60,4 +63,13 @@ describe('validatePublicReviewModel', () => {await expect(validatePublicReviewModel({ provider: LOCAL_CLAUDE, model: 'safe-model' })).resolves.toMatchObject({ ok: false, code: 'public-review-model-catalog-unavailable' });});++ it('requires the Hugging Face token before preparing the guard runtime', async () => {+ getHfToken.mockResolvedValue(null);++ await expect(installModelAbuseGuard()).resolves.toMatchObject({+ ok: false,+ code: 'security-guard-huggingface-token-required',+ });+ });});