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

14.1 KB
Raw Blame
import { useEffect, useState } from 'react';
import { getSettings, updateSettings } from '../../services/api';
import useProviderModels from '../../hooks/useProviderModels';
import ProviderModelSelector from '../ProviderModelSelector';
import toast from '../ui/Toast';
import { isLocalEndpoint } from '../../utils/providerEndpoints';
import {
  PRIVATE_UNTRUSTED_CONTENT_SOURCES,
  UNTRUSTED_CONTENT_SOURCES,
  UNTRUSTED_CONTENT_SOURCE_LABELS,
} from '../../lib/untrustedContentSources';

const SOURCES = [
  ['defaults', 'Shared defaults'],
  ...UNTRUSTED_CONTENT_SOURCES.map(source => [source, UNTRUSTED_CONTENT_SOURCE_LABELS[source] || source]),
];
const PRIVATE_SOURCES = PRIVATE_UNTRUSTED_CONTENT_SOURCES;
const apiProvider = provider => provider.type === 'api';
const localApiProvider = provider => apiProvider(provider) && isLocalEndpoint(provider.endpoint);
const INPUT_CLASS = 'w-full min-w-0 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white';

export default function UntrustedContentPolicyPanel() {
  const [config, setConfig] = useState(null);
  const [saved, setSaved] = useState(null);
  const [source, setSource] = useState('defaults');
  const [error, setError] = useState('');
  const [saving, setSaving] = useState(false);
  const { providers, loading } = useProviderModels({ filter: apiProvider, allowDefault: true, silent: true });
  const load = () => getSettings({ silent: true }).then(settings => {
    const policy = settings.untrustedContent || {};
    setConfig(policy); setSaved(JSON.stringify(policy)); setError('');
  }).catch(() => setError('Could not load content policies. Retry before editing.'));
  useEffect(() => { load(); }, []);

  const policy = source === 'defaults' ? config?.defaults || {} : config?.sources?.[source] || {};
  const isPrivate = PRIVATE_SOURCES.includes(source);
  const inheritedLayers = [config?.defaults || {}, isPrivate && source !== 'messages' ? config?.sources?.messages || {} : {}];
  const mergeLayers = layers => layers.reduce((merged, layer) => ({
    ...merged,
    ...(Object.hasOwn(layer, 'providerId') && layer.providerId !== merged.providerId ? { model: null } : {}),
    ...layer,
  }), {});
  const defaults = mergeLayers(inheritedLayers);
  const effective = mergeLayers([...inheritedLayers, policy]);
  const effectiveValue = name => effective[name];
  const inheritanceName = isPrivate && source !== 'messages' ? 'message defaults' : 'shared defaults';
  const selectedProvider = providers.find(provider => provider.id === effectiveValue('providerId'));
  // Mirrors selectUntrustedContentProvider (server/lib/untrustedContent.js):
  // a pinned provider is used as-is; Automatic takes the first eligible
  // provider that resolves a model, never one that cannot.
  const eligibleProvider = provider => provider.enabled !== false && (isPrivate ? localApiProvider : apiProvider)(provider);
  const resolution = (() => {
    const pinned = effectiveValue('providerId');
    const candidates = pinned ? providers.filter(provider => provider.id === pinned) : providers;
    const usable = candidates.filter(eligibleProvider);
    for (const provider of usable) {
      const model = effectiveValue('model') || provider.defaultModel;
      if (model) return { provider, model };
    }
    if (!usable.length) return { problem: pinned ? 'The pinned provider is not available for this source.' : 'No eligible API provider is available for this source.' };
    return { problem: pinned
      ? 'The pinned provider has no default model; pick an installed model.'
      : 'No eligible API provider has a default model; pick an installed model.' };
  })();
  const patch = fields => setConfig(current => source === 'defaults'
    ? { ...current, defaults: { ...current?.defaults, ...fields } }
    : { ...current, sources: { ...current?.sources, [source]: { ...current?.sources?.[source], ...fields } } });
  const changeNumber = (name, value) => {
    if (value !== '') patch({ [name]: Number(value) });
  };
  // Removing the key is what re-inherits; writing a null/'' would pin the
  // source to an explicit empty value the resolver would then layer on.
  const clearField = name => {
    const { [name]: _cleared, ...rest } = policy;
    setConfig(current => source === 'defaults'
      ? { ...current, defaults: rest }
      : { ...current, sources: { ...current.sources, [source]: rest } });
  };
  const save = () => {
    setSaving(true);
    updateSettings({ untrustedContent: config }).then(() => {
      setSaved(JSON.stringify(config));
      toast.success('Content safety policies saved');
    }).catch(() => {}).finally(() => setSaving(false));
  };

  return (
    <div className="border-t border-port-border pt-4 space-y-3 min-w-0">
      <h3 className="text-sm font-medium text-white">Content safety policies</h3>
      <p className="text-sm text-gray-300 max-w-2xl">Choose how each source is screened and which provider analyzes it.</p>
      <details className="text-xs text-gray-400 max-w-2xl">
        <summary className="cursor-pointer text-port-accent">How sources inherit settings</summary>
        <p className="mt-2 leading-relaxed">Shared defaults apply to every source. Messages adds defaults for email, iMessage, and Signal; each channel can override them. Private analysis stays on this machine. Screening never gives external text authority or the analysis model tools. GitHub review schedules are configured separately.</p>
      </details>
      {error && <p role="alert" className="text-xs text-port-warning">{error} <button type="button" onClick={load} className="underline">Retry</button></p>}
      {!config ? !error && <p className="text-xs text-gray-500">Loading policies…</p> : (
        <form onSubmit={event => { event.preventDefault(); save(); }} className="space-y-3">
          <fieldset disabled={saving} className="space-y-4 min-w-0 max-w-3xl">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div>
                <label htmlFor="abuse-policy-source" className="block text-xs text-gray-400 mb-1">Source</label>
                <select id="abuse-policy-source" value={source} onChange={event => setSource(event.target.value)} className={INPUT_CLASS}>
                  {SOURCES.map(([value, label]) => <option key={value} value={value}>{label}</option>)}
                </select>
              </div>
              <div>
                <label htmlFor="abuse-policy-classifier" className="block text-xs text-gray-400 mb-1">Classifier requirement</label>
                <select id="abuse-policy-classifier" value={policy.classifierMode || ''} onChange={event => {
                  const value = event.target.value;
                  if (value) patch({ classifierMode: value });
                  else clearField('classifierMode');
                }} className={INPUT_CLASS}>
                  <option value="">{source === 'defaults' ? 'Required (shipped default)' : `Inherit ${inheritanceName} (${defaults.classifierMode || 'required'})`}</option>
                  <option value="required">Required</option>
                  <option value="optional">Optional only when never installed</option>
                </select>
              </div>
            </div>
            {(policy.classifierMode || defaults.classifierMode) === 'optional' && <p className="text-xs text-port-warning">Optional allows deterministic screening alone on machines without the classifier. Those checks miss attacks the classifier could catch. Failed or partial installations still block.</p>}
            <div className="border-t border-port-border pt-4 space-y-3">
              <h4 className="text-sm font-medium text-white">Local decision scorer</h4>
              <p className="text-xs text-gray-400 max-w-2xl">Closed-set questions for this source (reply or not, triage action, priority) can be answered by the local jev entailment model instead of a chat provider. It abstains rather than guessing, and an abstention falls back to the provider above.</p>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label htmlFor="abuse-policy-jev-mode" className="block text-xs text-gray-400 mb-1">Local scorer</label>
                  <select id="abuse-policy-jev-mode" value={policy.jevMode || ''} onChange={event => {
                    const value = event.target.value;
                    if (value) patch({ jevMode: value });
                    else clearField('jevMode');
                  }} className={INPUT_CLASS}>
                    <option value="">{source === 'defaults' ? 'Shadow (shipped default)' : `Inherit ${inheritanceName} (${defaults.jevMode || 'off'})`}</option>
                    <option value="off">Shadow — compare with the provider</option>
                    <option value="disabled">Disabled — do not run Jev</option>
                    <option value="prefer">Prefer — local first, provider on abstain</option>
                    <option value="only">Only — local first, skip the item on abstain</option>
                  </select>
                </div>
                <div>
                  <label htmlFor="abuse-policy-jevMinMargin" className="block text-xs text-gray-400 mb-1">Minimum decision margin</label>
                  <input id="abuse-policy-jevMinMargin" className={INPUT_CLASS} type="number" min={0} max={1} step={0.01}
                    value={policy.jevMinMargin ?? defaults.jevMinMargin ?? ''}
                    placeholder="Per-decision default"
                    onChange={event => (event.target.value === '' ? clearField('jevMinMargin') : changeNumber('jevMinMargin', event.target.value))} />
                </div>
              </div>
              {effectiveValue('jevMode') === 'only' && <p className="text-xs text-port-warning">Only skips an item the scorer cannot separate instead of calling a provider. Skipped items are reported, never treated as &ldquo;no action needed&rdquo;.</p>}
              <p className="text-xs text-gray-500">The margin raises the bar for every decision on this source; it cannot lower a decision&rsquo;s own floor, so a destructive recommendation keeps deferring to the provider. <a href="/models/decision-classifiers/jev" className="text-port-accent hover:underline">Install and measure jev</a></p>
            </div>
            <div className="border-t border-port-border pt-4 space-y-3">
              <h4 className="text-sm font-medium text-white">Analysis provider</h4>
              <ProviderModelSelector
                providers={providers}
                selectedProviderId={effectiveValue('providerId') || ''}
                selectedModel={effectiveValue('model') || ''}
                availableModels={selectedProvider?.models?.length ? selectedProvider.models : selectedProvider?.defaultModel ? [selectedProvider.defaultModel] : []}
                onProviderChange={providerId => patch({ providerId: providerId || null, model: null })}
                onModelChange={model => patch({ model: model || null })}
                label="Analysis API provider"
                loading={loading}
                selectionPolicy={{ provider: isPrivate ? localApiProvider : apiProvider }}
                emptyProviderOption="Automatic eligible API provider"
                emptyModelOption="Provider default model"
                alwaysShowModel
              />
              {!loading && (resolution.problem
                ? <p role="status" className="text-xs text-port-warning">Analysis is not ready for {source === 'defaults' ? 'sources that use shared defaults' : 'this source'}: {resolution.problem}</p>
                : <p className="text-xs text-gray-400">Resolves to {resolution.provider.name || resolution.provider.id} with model {resolution.model}.</p>)}
              <p className="text-xs text-gray-500">{isPrivate ? 'Only local API endpoints are eligible for private messages. Cloud APIs, CLI agents, and provider fallback are blocked.' : 'Choose an API provider for text analysis. Automatic selection uses an eligible API provider; a failed provider never falls back. Cloud APIs may receive public sources.'} <a href="/ai" className="text-port-accent hover:underline">Configure providers</a></p>
            </div>
            <details className="rounded-lg border border-port-border p-3">
              <summary className="cursor-pointer text-sm text-port-accent">Advanced screening limits</summary>
              <p className="my-3 text-xs text-gray-400 max-w-2xl">Limits apply to this source. Input must also fit the provider’s context window; evidence that cannot fit completely is blocked.</p>
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                {[
                  ['minBenignScore', 'Minimum benign score', 0.9, 1, 0.01, 0.9],
                  ['maxInputChars', 'Input limit (characters)', 1000, 2000000, 1, 2000000],
                  ['maxOutputChars', 'Output limit (characters)', 100, 100000, 1, 32000],
                ].map(([name, label, min, max, step, fallback]) => (
                  <div key={name}>
                    <label htmlFor={`abuse-policy-${name}`} className="block text-xs text-gray-400 mb-1">{label}</label>
                    <input id={`abuse-policy-${name}`} className={INPUT_CLASS} type="number" onInvalid={event => { event.currentTarget.closest('details').open = true; }} min={min} max={max} step={step} required value={policy[name] ?? defaults[name] ?? fallback} onChange={event => changeNumber(name, event.target.value)} />
                  </div>
                ))}
              </div>
            </details>
          </fieldset>
          <div className="flex flex-wrap gap-2">
            <button type="submit" disabled={saving || JSON.stringify(config) === saved} className="px-3 py-2 text-xs rounded bg-port-accent text-white disabled:opacity-50">{saving ? 'Saving…' : 'Save content policies'}</button>
            {source !== 'defaults' && <button type="button" disabled={saving || !config.sources?.[source]} onClick={() => setConfig(current => {
              const sources = { ...current.sources };
              delete sources[source];
              return { ...current, sources };
            })} className="px-3 py-2 text-xs rounded border border-port-border text-gray-300 disabled:opacity-50">Use {inheritanceName} for this source</button>}
          </div>
        </form>
      )}
    </div>
  );
}