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

6.8 KB
Raw Blame
import { useState, useCallback } from 'react';
import { useNavigate } from 'react-router';
import { Shield, LayoutDashboard, KeyRound, Building2, Repeat, ShieldOff } from 'lucide-react';
import { useValidTab } from '../hooks/useValidTab';
import useUrlParams from '../hooks/useUrlParams';
import { getPrivacySubjects } from '../services/api';
import PageHeader from '../components/PageHeader';
import TabPills from '../components/ui/TabPills';
import PrivacyOverviewTab from '../components/privacy/PrivacyOverviewTab';
import PrivacyVaultTab from '../components/privacy/PrivacyVaultTab';
import PrivacyOrgsTab from '../components/privacy/PrivacyOrgsTab';
import PrivacyChangesTab from '../components/privacy/PrivacyChangesTab';
import PrivacyBrokersTab from '../components/privacy/PrivacyBrokersTab';
import SubjectSwitcher from '../components/privacy/SubjectSwitcher';
import SubjectsDrawer from '../components/privacy/SubjectsDrawer';
import ListLoadError from '../components/ui/ListLoadError';
import useListResource from '../hooks/useListResource.js';
import { SELF_SUBJECT_ID, privacyTabPath } from '../components/privacy/constants';
import { getPageNavTabs } from '../../../server/lib/navManifest.js';
import { buildPageNavTabs } from '../lib/pageNavTabs.js';

// Icon per tab id. The manifest (`tabGroup: 'privacy'`) owns id/label/order —
// this page owns only how each tab looks; the page-local "Overview" label
// (vs. the manifest's "Privacy") comes from the manifest's `tabLabel`. Throws
// at import time on drift.
const TAB_PRESENTATION = {
  overview: { icon: LayoutDashboard },
  vault: { icon: KeyRound },
  organizations: { icon: Building2 },
  changes: { icon: Repeat },
  brokers: { icon: ShieldOff },
};

export const TABS = buildPageNavTabs(getPageNavTabs('privacy'), TAB_PRESENTATION, 'Privacy');

export default function Privacy() {
  const navigate = useNavigate();
  const activeTab = useValidTab(TABS, 'overview');
  const [searchParams, updateParams] = useUrlParams();
  const [drawerOpen, setDrawerOpen] = useState(false);

  // Which household subject is in scope lives in the URL (#3658), so a view of
  // a specific person's records is shareable and reload-safe — same rule as any
  // other selection. An absent param means `self`, matching the server default.
  const subjectId = searchParams.get('subject') || SELF_SUBJECT_ID;

  const fetchSubjects = useCallback(async () => {
    const rows = await getPrivacySubjects({ silent: true });
    return Array.isArray(rows) ? rows : [];
  }, []);
  const subjectsResource = useListResource(fetchSubjects);
  const {
    items: subjects,
    state: subjectsState,
    error: subjectsError,
    retry: retrySubjects,
    setItems: setSubjects,
  } = subjectsResource;

  // `self` is the default scope, so it stays out of the URL entirely — a null
  // patch value is `useUrlParams`'s delete signal.
  const selectSubject = useCallback((id) => {
    updateParams({ subject: id === SELF_SUBJECT_ID ? null : id }, { replace: true });
  }, [updateParams]);

  const handleCreated = (subject) => {
    // Creation writes exactly one local-only `pii_vault` grant — broker
    // purposes start ungranted (#8332).
    setSubjects((prev) => [...prev, { ...subject, consentCount: 1, recordCount: 0, activeScopes: ['pii_vault'] }]);
    selectSubject(subject.id);
  };

  const handleDeleted = (deletedId) => {
    setSubjects((prev) => prev.filter((s) => s.id !== deletedId));
    // Never strand the view on a subject that no longer exists.
    if (deletedId === subjectId) selectSubject(SELF_SUBJECT_ID);
  };

  // A broker purpose was granted/revoked in the Household drawer — mirror it
  // into the subject list so the drawer and the Brokers tab reflect it without
  // a refetch. A grant also appends an audit row (revocation only stamps one).
  const handleConsentChanged = (changedId, scope, granted) => {
    setSubjects((prev) => prev.map((s) => {
      if (s.id !== changedId) return s;
      const scopes = new Set(s.activeScopes ?? []);
      if (granted) scopes.add(scope); else scopes.delete(scope);
      return {
        ...s,
        activeScopes: [...scopes].sort(),
        ...(granted ? { consentCount: (s.consentCount ?? 0) + 1 } : {}),
      };
    }));
  };

  // `undefined` until the subject list loads — the Brokers tab only warns about
  // missing broker consent once it actually knows the grants.
  const activeSubject = subjects.find((s) => s.id === subjectId);

  // Carry the subject across tabs, but drop tab-local params (e.g. the brokers
  // tab's `?case=`) so switching tabs can't reopen a stale drawer.
  const goToTab = (id) => navigate(privacyTabPath(id, subjectId));

  const renderTab = () => {
    switch (activeTab) {
      case 'vault': return <PrivacyVaultTab subjectId={subjectId} />;
      case 'organizations': return <PrivacyOrgsTab subjectId={subjectId} />;
      case 'changes': return <PrivacyChangesTab subjectId={subjectId} />;
      case 'brokers': return (
        <PrivacyBrokersTab
          subjectId={subjectId}
          consentScopes={activeSubject?.activeScopes}
          onManageConsent={() => setDrawerOpen(true)}
        />
      );
      case 'overview':
      default: return <PrivacyOverviewTab subjectId={subjectId} />;
    }
  };

  return (
    <div className="flex h-full min-h-0 flex-col">
      <PageHeader
        icon={Shield}
        title="Privacy Center"
        subtitle="Your PII vault and who holds it"
      />
      <TabPills
        tabs={TABS}
        activeTab={activeTab}
        onChange={goToTab}
        mobileCompact
        ariaLabel="Privacy Center sections"
      />
      <div className="flex-1 min-h-0 overflow-auto p-4 md:p-6 space-y-4">
        {subjectsState === 'error' && (
          <ListLoadError what="household subjects" error={subjectsError} onRetry={retrySubjects} />
        )}
        <div>
          <SubjectSwitcher
            subjects={subjects}
            subjectId={subjectId}
            onChange={selectSubject}
            onManage={() => setDrawerOpen(true)}
          />
        </div>
        {subjectsState === 'ready' && subjects.length === 0 && (
          <p className="text-xs text-gray-500">No household subjects on record.</p>
        )}
        {/* Keying on the subject remounts the tab when the scope changes, so ALL
            of its local state resets at once — revealed plaintext, open drawers,
            expanded rows, filters. Clearing those by hand inside each tab's
            `load()` both missed some and fired on ordinary post-mutation
            refetches, collapsing rows the user had just opened. */}
        <div className="pt-4" key={subjectId}>
          {renderTab()}
        </div>

      </div>
      <SubjectsDrawer
        open={drawerOpen}
        subjects={subjects}
        onClose={() => setDrawerOpen(false)}
        onCreated={handleCreated}
        onDeleted={handleDeleted}
        onConsentChanged={handleConsentChanged}
      />
    </div>
  );
}