فهرست منبع

feat: rebuild the admin UI around what the API actually exposes SV-132

The owner's report: "the webui lacks many features we have in vectorapi. The
left side menu is a big mess. Relations is in the admin section." Measured
rather than taken on impression: `files` and `secrets` are per-project API
resources with NO user interface at all, and there was nowhere to configure a
project's hostnames or TLS - which is why the owner could not find it.

NAVIGATION is grouped PROJECT / ADMINISTRATION along the server's own
authorization model, with the project selector moved above the items it
governs. Nothing is hidden: an item the session cannot use renders disabled
with the reason, where the admin group previously just vanished.

NEW SURFACES: Hostnames & TLS tab, Files page, Secrets page.

SERVER FIX IN THE SAME CHANGE - `memory_max_bytes` is now returned by
/api/v1/stats. `Client::MemoryStats` carries maxMemoryBytes and the handler was
dropping it, so the dashboard could only say "53%" with no denominator - and a
reader shown a bare percent assumes it is 53% of the MACHINE, which is the one
reading that is never correct.

A REFUSAL MESSAGE OF MINE WAS LYING, found by an implementer reading the
handler. `mayClaimHostname` normalised BEFORE validating, and normalisation
strips the port - so `Example.COM:8443` was ACCEPTED as `example.com` while the
422 text promised that a port is refused. The check was dead code. Measured
with a compiled probe before fixing. Now the RAW value is judged first, and the
port is REFUSED rather than normalised away: an operator typing a port believes
this service will answer on it, and accepting the value while serving a
different one is the accepted-and-ignored shape this codebase keeps paying for.

THREE ERRORS IN MY OWN BRIEFS, each caught by an implementer reading the code
rather than trusting me, and each would have shipped a silent defect:
- I gave the embedding cache fields as `hits`/`misses`. They are `cache_hits`/
  `cache_misses`. Code written to my brief would have read undefined and
  rendered the empty-cache state for EVERY condition.
- I said `dbMetadataFields()` has six entries. It has seven - `_updated_by`.
- I said Relations is miscategorised under Admin. It is project-SCOPED but
  every handler runs requireAdmin BEFORE requireProjectAccess, reads included.
  So the nav item moved to PROJECT and the route gate stayed, with the
  reasoning at the route. Moving it and dropping the gate - the obvious reading
  of my brief - would have produced exactly the 403-on-click I asked to avoid.

FINDINGS THE IMPLEMENTERS MEASURED THAT NOBODY HAD WRITTEN DOWN:
- Timestamps are NOT unconditionally milliseconds. `timestampPrecision` can be
  "ns" and the migration converts rows ONE AT A TIME, so a single collection can
  hold both at once. No route exposes the configured precision, so the UI infers
  per value using the database's own 10^15 discriminator and labels the unit.
  Rendering ns as ms puts a row in the year 58000 and reads as corruption.
- Collection `created_at` is SECONDS while a document's `_created_at` is
  milliseconds. Documented so the two helpers are not later "unified".
- `scope_filtered` and `composite_unique` were being discarded by client.ts
  entirely.
- The documents listing's `has_more`/`total` (shipped in 0.18.2) were ignored by
  the page, which still used a full-page heuristic that offers a Next button
  onto an empty page whenever the last page is exactly full.

The empty-collections list now has FOUR distinguishable renderings rather than
one, including "the server did not say whether this view is scope-limited, so an
empty list cannot be read as an empty project" - this codebase's most repeated
trap, finally visible to the person looking at it.

Secrets are rendered write-only with no control implying a value can be read
back: no masked field, no reveal, and `set` shown as a WORD rather than dots,
which look like a value.

1522/1522 serial; webui `npm run build` clean (the real check, not tsc --noEmit).
fszontagh 6 روز پیش
والد
کامیت
2c22a6b23d

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.19.1
+0.20.0

+ 1 - 1
api/openapi.json

@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "info": {
     "title": "smartbotic-vectorapi",
-    "version": "0.19.1",
+    "version": "0.20.0",
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
   },
   "components": {

+ 12 - 0
src/handlers/stats.cpp

@@ -42,6 +42,18 @@ void registerStatsRoutes(ApiServer& s) {
         auto mem = d->db.client().getMemoryStats();
         out["memory_pressure_level"]   = mem.pressureLevel;
         out["memory_pressure_percent"] = mem.pressurePercent;
+        // THE DENOMINATOR, without which the percent above is uninterpretable.
+        // A reader shown "53%" with no budget assumes it is 53% of the MACHINE,
+        // which is the one reading that is never correct: it is a fraction of
+        // the database's CONFIGURED budget, and on this deployment the two
+        // differ by a factor of ten. The struct already carries it and we were
+        // dropping it on the floor.
+        //
+        // Note it comes from getMemoryStats() while `memory_used_bytes` above
+        // comes from getStats() - two different calls, so the pair can disagree
+        // slightly. That is worth knowing before anyone computes one from the
+        // other and reports the difference as a leak.
+        out["memory_max_bytes"]        = mem.maxMemoryBytes;
         out["projects"]                = d->db.listProjects().size();
         auto cs = embeddingCache().stats();
         double total = double(cs.hits + cs.misses);

+ 24 - 0
src/hostnames.cpp

@@ -39,6 +39,27 @@ std::string normaliseHost(std::string_view h) {
     return out;
 }
 
+std::string rawHostnameError(std::string_view raw) {
+    // Trim the OWS a header value may carry, then judge what the user typed.
+    while (!raw.empty() && (raw.front() == ' ' || raw.front() == '\t')) raw.remove_prefix(1);
+    while (!raw.empty() && (raw.back() == ' ' || raw.back() == '\t')) raw.remove_suffix(1);
+    if (raw.empty()) return "a hostname is required";
+    if (raw.find("://") != std::string_view::npos)
+        return "a scheme is not part of a hostname: drop the 'https://'";
+    if (raw.find('/') != std::string_view::npos)
+        return "a path is not part of a hostname";
+    if (raw.find('@') != std::string_view::npos)
+        return "userinfo is not part of a hostname";
+    // A port. An IPv6 literal legitimately contains colons inside brackets, but
+    // a bracketed literal is refused anyway by validHostname, so any colon here
+    // is a port.
+    if (raw.find(':') != std::string_view::npos)
+        return "a port is not part of a hostname: this service answers on one "
+               "port and cannot serve another, so the port is refused rather "
+               "than ignored";
+    return {};
+}
+
 bool validHostname(std::string_view host) {
     if (host.empty() || host.size() > 253) return false;
     // No wildcard, no scheme, no path, no port, no userinfo - a project
@@ -151,6 +172,9 @@ HostClaimRefusal mayClaimHostname(
     std::string_view host, std::string_view project, const std::string& adminHost,
     const std::vector<std::string>& globalHosts,
     const std::unordered_map<std::string, std::vector<HostEntry>>& byProject) {
+    // The RAW value first: normalisation strips a port, so judging the
+    // normalised form cannot see one.
+    if (!rawHostnameError(host).empty()) return HostClaimRefusal::Invalid;
     const std::string h = normaliseHost(host);
     if (h.empty() || !validHostname(h)) return HostClaimRefusal::Invalid;
 

+ 17 - 0
src/hostnames.hpp

@@ -221,6 +221,23 @@ HostClaimRefusal mayClaimHostname(std::string_view host, std::string_view projec
                                   const std::vector<std::string>& globalHosts,
                                   const std::unordered_map<std::string, std::vector<HostEntry>>& byProject);
 
+/// Does the RAW, un-normalised value carry something we cannot honour?
+///
+/// THIS EXISTS BECAUSE THE REFUSAL MESSAGE WAS LYING. `mayClaimHostname` ran
+/// `normaliseHost` BEFORE `validHostname`, and normalisation strips the port -
+/// so `example.com:8443` was silently accepted as `example.com` while the 422
+/// text promised that a port is refused. The check was dead code.
+///
+/// It is refused rather than normalised away, which is the choice worth
+/// recording: an operator who types a port believes this service will answer on
+/// it, and it will not - we serve one port. Accepting the value and quietly
+/// serving a different one is the accepted-and-ignored shape this codebase has
+/// paid for more than once, and it answers 200 while discarding the only part
+/// the author cared about.
+///
+/// Returns an empty string when the raw value is acceptable.
+std::string rawHostnameError(std::string_view raw);
+
 /// Is this a hostname a project may register?
 ///
 /// Deliberately strict, and WILDCARDS ARE REFUSED. A project registering

+ 34 - 0
tests/test_hostnames.cpp

@@ -515,3 +515,37 @@ TEST(HostGating, AShortPathOnTheLoopbackAdminSurfaceIsStillREFUSED) {
     EXPECT_FALSE(resolveProject("", loopbackAdmin, true).ok);
     EXPECT_TRUE(resolveProject("novitax", loopbackAdmin, true).ok);
 }
+
+// --- the raw value, before normalisation can hide anything ------------------
+
+using svapi::rawHostnameError;
+
+TEST(RawHostname, APORTIsREFUSEDRatherThanStrippedSilently) {
+    // THE REGRESSION. mayClaimHostname normalised BEFORE validating, and
+    // normalisation strips the port - so `example.com:8443` was accepted as
+    // `example.com` while the 422 text promised a port is refused. The check
+    // was dead code and the message was a lie.
+    EXPECT_FALSE(rawHostnameError("example.com:8443").empty());
+    EXPECT_FALSE(rawHostnameError("Example.COM:8443").empty());
+    EXPECT_EQ(mayClaimHostname("Example.COM:8443", "p", "admin.example.com", {}, {}),
+              HostClaimRefusal::Invalid)
+        << "a port was accepted and silently normalised away";
+}
+
+TEST(RawHostname, SchemePathAndUserinfoAreRefusedByNAMERatherThanByAccident) {
+    // Each previously failed for an INCIDENTAL reason - `https://example.com`
+    // normalises to `https`, a single label - so the caller was told the wrong
+    // thing about their own input.
+    EXPECT_FALSE(rawHostnameError("https://example.com").empty());
+    EXPECT_FALSE(rawHostnameError("example.com/path").empty());
+    EXPECT_FALSE(rawHostnameError("user@example.com").empty());
+}
+
+TEST(RawHostname, AnOrdinaryHostnameIsACCEPTED_thePairing) {
+    // Without this the tests above would pass against a function that refused
+    // everything.
+    EXPECT_TRUE(rawHostnameError("nt.kb.smartbotics.ai").empty());
+    EXPECT_TRUE(rawHostnameError("  ok.example.com  ").empty()) << "OWS is trimmed, not refused";
+    EXPECT_EQ(mayClaimHostname("nt.kb.smartbotics.ai", "p", "admin.example.com", {}, {}),
+              HostClaimRefusal::None);
+}

+ 20 - 0
webui/src/App.tsx

@@ -13,6 +13,8 @@ import Settings from '@/pages/Settings'
 import ProjectsAdmin from '@/pages/ProjectsAdmin'
 import KeysAdmin from '@/pages/KeysAdmin'
 import RelationsAdmin from '@/pages/RelationsAdmin'
+import ProjectFiles from '@/pages/ProjectFiles'
+import ProjectSecrets from '@/pages/ProjectSecrets'
 
 /// Shown while the server is being asked whether the restored session is real.
 /// Rendering the shell here is what used to flash the authenticated UI at a
@@ -70,6 +72,13 @@ export const routes: RouteObject[] = [
           // and the page itself renders the policy editor read-only unless the
           // session is an admin one (the policy route is the admin-only part).
           { path: 'functions', element: <Functions /> },
+          // Files and Secrets are deliberately NOT admin-gated. File READS
+          // authorize through the `_files` scope rules and the secrets LISTING
+          // is project-manage, so an admin-only route would hide both from
+          // exactly the keys entitled to them. Each page degrades in place when
+          // a WRITE is refused, which is the narrower and correct boundary.
+          { path: 'files', element: <ProjectFiles /> },
+          { path: 'secrets', element: <ProjectSecrets /> },
           // Settings is not admin-gated: a project manager reaches the per-project
           // embedding tab here. The page renders only the tabs the key may use.
           { path: 'settings', element: <Settings /> },
@@ -78,6 +87,17 @@ export const routes: RouteObject[] = [
             children: [
               { path: 'projects', element: <ProjectsAdmin /> },
               { path: 'keys', element: <KeysAdmin /> },
+              // RELATIONS IS GROUPED WITH THE PROJECT ITEMS IN THE NAV AND IS
+              // STILL ADMIN-GATED HERE, AND THE TWO ARE NOT IN CONFLICT.
+              // The route is project-scoped (`/api/v1/projects/{p}/relations`),
+              // which is why it belongs beside Collections and Documents rather
+              // than under Administration - it describes one project's data
+              // model. But being project-scoped says WHERE a route acts, not
+              // WHO may call it: every relations handler in
+              // `src/handlers/relations.cpp` runs `requireAdmin(k)` before
+              // `requireProjectAccess(k, project)`, the list and read routes
+              // included. Dropping this gate on the strength of the URL shape
+              // would put a non-admin on a page whose every call answers 403.
               { path: 'relations', element: <RelationsAdmin /> },
             ],
           },

+ 68 - 4
webui/src/api/client.ts

@@ -1,14 +1,17 @@
 import type {
   LoginResponse, CollectionMeta, ApiKeyPublic, ApiKeyCreated,
   SearchResult, ProjectStats, GlobalStats, FindResult, SettingsView,
-  KeyScope, IndexDef, IndexValue, CreateIndexResult,
+  KeyScope, IndexValue, CreateIndexResult,
   ProjectEmbeddingsView, ProjectEmbeddingsPatch,
   RelationDefinition, DeleteImpact,
   FunctionSummary,
   FunctionsListResponse, FunctionDetail, FunctionRun, InvokeEnvelope, InvokeRequest,
   ProjectFunctionSettings, ProjectFunctionSettingsPatch,
-  ProjectHostnamesView, ProjectStaticSettings,
+  ProjectHostnamesView, ProjectHostnamesPatch, ProjectStaticSettings,
+  ProjectFile, ProjectFilesView,
+  ProjectSecretsView, ProjectSecretSummary,
   CollectionSchema, SchemaChangeResult, SchemaSuggestion, SchemaMode,
+  CollectionsListResponse, IndexesResponse,
 } from '@/types'
 import { ApiError } from '@/types'
 import { serverUrl } from '@/api/base'
@@ -63,7 +66,10 @@ export const api = {
     if (params?.sort) qs.set('sort', params.sort)
     if (params?.desc) qs.set('desc', 'true')
     const s = qs.toString()
-    return request<{ collections: CollectionMeta[] }>(`${P(project)}/collections${s ? `?${s}` : ''}`)
+    // The envelope, not just the array: `scope_filtered` says whether this
+    // view may be partial, and dropping it would make an empty list from a
+    // scoped key indistinguishable from an empty project.
+    return request<CollectionsListResponse>(`${P(project)}/collections${s ? `?${s}` : ''}`)
   },
   getCollection: (project: string, name: string) => request<CollectionMeta>(`${P(project)}/collections/${enc(name)}`),
   createCollection: (project: string, body: { name: string; kind: 'json' | 'vector'; vector_dimension?: number; embedding_model?: string }) =>
@@ -73,7 +79,11 @@ export const api = {
 
   // indexes
   listIndexes: (project: string, coll: string) =>
-    request<{ indexes: IndexDef[] }>(`${P(project)}/collections/${enc(coll)}/indexes`),
+    // `composite_unique` travels in its own array beside `indexes`. It was
+    // being discarded here, so a composite constraint - the one that refuses
+    // a write for a reason no single-field index explains - was invisible to
+    // the whole UI.
+    request<IndexesResponse>(`${P(project)}/collections/${enc(coll)}/indexes`),
   createIndex: (project: string, coll: string, field: string, unique: boolean) =>
     request<CreateIndexResult>(`${P(project)}/collections/${enc(coll)}/indexes`,
       { method: 'POST', body: JSON.stringify({ field, unique }) }),
@@ -218,6 +228,60 @@ export const api = {
     request<{ function_id: string; runs: FunctionRun[] }>(
       `${P(project)}/functions/${enc(id)}/logs?limit=${limit}`),
 
+  /// REPLACES the whole list. There is no merge and no partial update, so a
+  /// caller MUST read the current hostnames, edit that array and send it back
+  /// whole - sending one entry removes every other one.
+  updateProjectHostnames: (project: string, hostnames: ProjectHostnamesPatch['hostnames']) =>
+    request<ProjectHostnamesView>(`${P(project)}/settings/hostnames`, {
+      method: 'PUT',
+      body: JSON.stringify({ hostnames }),
+    }),
+
+  // ---- project files ----------------------------------------------------
+  // Reads answer to the scope rules under the reserved `_files`
+  // pseudo-collection; writes additionally require project-manage.
+  listFiles: (project: string, limit = 100, offset = 0) =>
+    request<ProjectFilesView>(`${P(project)}/files?limit=${limit}&offset=${offset}`),
+  getFileInfo: (project: string, name: string) =>
+    request<ProjectFile>(`${P(project)}/files/${enc(name)}/info`),
+  /// The raw bytes ARE the body - not base64, not a JSON wrapper - so this one
+  /// call overrides the JSON content type the shared helper would otherwise
+  /// send. `path` travels as `X-File-Path` because the body is already spoken
+  /// for; OMITTING it removes any path the previous upload set, since a PUT
+  /// replaces the record rather than merging into it.
+  uploadFile: (project: string, name: string, body: Blob, contentType: string, path?: string) =>
+    request<ProjectFile>(`${P(project)}/files/${enc(name)}`, {
+      method: 'PUT',
+      body,
+      headers: {
+        'Content-Type': contentType || 'application/octet-stream',
+        ...(path ? { 'X-File-Path': path } : {}),
+      },
+    }),
+  deleteFile: (project: string, name: string) =>
+    request<{ deleted: string }>(`${P(project)}/files/${enc(name)}`, { method: 'DELETE' }),
+  /// A URL rather than a fetch: the download answers with the stored bytes and
+  /// the stored content type, so a browser handles it better than we can. The
+  /// cookie session travels with a same-origin navigation, and the mount
+  /// prefix has to be applied here exactly as the shared helper applies it.
+  fileDownloadUrl: (project: string, name: string) =>
+    serverUrl(`${P(project)}/files/${enc(name)}`),
+
+  // ---- project secrets --------------------------------------------------
+  // Listing is project-manage; writing and deleting are ADMIN-only, because a
+  // stored value is a live credential every function then runs with.
+  listSecrets: (project: string) => request<ProjectSecretsView>(`${P(project)}/secrets`),
+  /// Write-only storage: this is the only call that ever carries a value, and
+  /// nothing reads one back. 201 on a first write, 200 on a rotation.
+  putSecret: (project: string, name: string, value: string) =>
+    request<ProjectSecretSummary>(`${P(project)}/secrets/${enc(name)}`, {
+      method: 'PUT',
+      body: JSON.stringify({ value }),
+    }),
+  deleteSecret: (project: string, name: string) =>
+    request<{ deleted: string; project: string }>(`${P(project)}/secrets/${enc(name)}`,
+      { method: 'DELETE' }),
+
   getSettings: () => request<SettingsView>('/api/v1/settings'),
   updateSettings: (patch: Partial<Omit<SettingsView, 'openai_api_key_set'> & { openai_api_key?: string }>) =>
     request<{ ok: boolean }>('/api/v1/settings', { method: 'PUT', body: JSON.stringify(patch) }),

+ 17 - 99
webui/src/components/AppShell.tsx

@@ -1,68 +1,12 @@
-import { useNavigate, NavLink, Outlet } from 'react-router-dom'
-import { serverUrl } from '@/api/base'
-import {
-  LayoutDashboard,
-  Database,
-  FileText,
-  Search,
-  Code2,
-  Settings,
-  FolderKanban,
-  KeyRound,
-  Share2,
-  LogOut,
-  BookOpen,
-} from 'lucide-react'
+import { useNavigate, Outlet } from 'react-router-dom'
+import { LogOut } from 'lucide-react'
 import { useAuthStore } from '@/stores/authStore'
-import { ProjectSelector } from './ProjectSelector'
+import { Sidebar } from './Sidebar'
 import { Toast } from './Toast'
 
-interface NavItem {
-  to: string
-  label: string
-  icon: React.ReactNode
-}
-
-const mainNav: NavItem[] = [
-  { to: '/', label: 'Dashboard', icon: <LayoutDashboard size={18} /> },
-  { to: '/collections', label: 'Collections', icon: <Database size={18} /> },
-  { to: '/documents', label: 'Documents', icon: <FileText size={18} /> },
-  { to: '/rag', label: 'RAG Tester', icon: <Search size={18} /> },
-  { to: '/functions', label: 'Functions', icon: <Code2 size={18} /> },
-  // Every key that can manage a project can manage that project's embedding
-  // settings, so Settings is not in the admin-only group.
-  { to: '/settings', label: 'Settings', icon: <Settings size={18} /> },
-]
-
-const adminNav: NavItem[] = [
-  { to: '/projects', label: 'Projects', icon: <FolderKanban size={18} /> },
-  { to: '/keys', label: 'Keys', icon: <KeyRound size={18} /> },
-  { to: '/relations', label: 'Relations', icon: <Share2 size={18} /> },
-]
-
-function SidebarLink({ item }: { item: NavItem }) {
-  return (
-    <NavLink
-      to={item.to}
-      end={item.to === '/'}
-      className={({ isActive }) =>
-        [
-          'flex items-center gap-3 px-3 py-2 rounded-md text-sm font-medium transition',
-          isActive
-            ? 'bg-indigo-600/30 text-indigo-300'
-            : 'text-slate-400 hover:text-slate-200 hover:bg-slate-700/50',
-        ].join(' ')
-      }
-    >
-      {item.icon}
-      {item.label}
-    </NavLink>
-  )
-}
-
 export function AppShell() {
-  const admin = useAuthStore((s) => s.admin)
   const logout = useAuthStore((s) => s.logout)
+  const currentProject = useAuthStore((s) => s.currentProject)
   const navigate = useNavigate()
 
   const handleLogout = () => {
@@ -73,49 +17,23 @@ export function AppShell() {
 
   return (
     <div className="flex min-h-screen bg-[#0b0f17] text-slate-100">
-      {/* Sidebar */}
-      <aside className="w-56 shrink-0 flex flex-col bg-[#080c12] border-r border-slate-800">
-        {/* Brand */}
-        <div className="px-4 py-5 border-b border-slate-800">
-          <span className="text-lg font-bold tracking-tight text-indigo-300">VectorAPI</span>
-        </div>
-
-        {/* Nav */}
-        <nav className="flex-1 px-3 py-4 flex flex-col gap-1">
-          {mainNav.map((item) => (
-            <SidebarLink key={item.to} item={item} />
-          ))}
-
-          <a
-            href={serverUrl('/docs')}
-            target="_blank"
-            rel="noreferrer"
-            className="flex items-center gap-3 px-3 py-2 rounded-md text-sm font-medium transition text-slate-400 hover:text-slate-200 hover:bg-slate-700/50"
-          >
-            <BookOpen size={18} />
-            API Docs
-          </a>
-
-          {admin && (
-            <>
-              <div className="mt-4 mb-1 px-3">
-                <span className="text-[10px] uppercase tracking-widest text-slate-600 font-semibold">
-                  Admin
-                </span>
-              </div>
-              {adminNav.map((item) => (
-                <SidebarLink key={item.to} item={item} />
-              ))}
-            </>
-          )}
-        </nav>
-      </aside>
+      <Sidebar />
 
       {/* Main area */}
       <div className="flex-1 flex flex-col min-w-0">
-        {/* Top bar */}
+        {/* Top bar. The project SWITCHER lives in the sidebar, above the items
+            it governs; this is the read-only statement of which project the
+            page below is showing, so the answer is on screen without having to
+            look at a control. */}
         <header className="flex items-center justify-between px-6 py-3 border-b border-slate-800 bg-[#0b0f17]">
-          <ProjectSelector />
+          <div className="text-sm text-slate-500">
+            Project:{' '}
+            {currentProject === null ? (
+              <span className="text-amber-400/80">none selected</span>
+            ) : (
+              <span className="text-slate-300 font-medium">{currentProject}</span>
+            )}
+          </div>
           <button
             onClick={handleLogout}
             data-testid="logout-btn"

+ 183 - 0
webui/src/components/Sidebar.tsx

@@ -0,0 +1,183 @@
+import { NavLink } from 'react-router-dom'
+import {
+  LayoutDashboard,
+  Database,
+  FileText,
+  Search,
+  Code2,
+  Settings as SettingsIcon,
+  FolderKanban,
+  KeyRound,
+  Share2,
+  BookOpen,
+} from 'lucide-react'
+import { serverUrl } from '@/api/base'
+import { useAuthStore } from '@/stores/authStore'
+import { ProjectSelector } from './ProjectSelector'
+
+/// The left nav is grouped by the server's OWN authorization model rather than
+/// by what felt tidy at the time, because that is the division a user can
+/// predict: a PROJECT item acts inside the selected project, an ADMINISTRATION
+/// item acts server-wide and needs an admin key.
+///
+/// `disabledReason` is the one rule for anything the current session cannot
+/// use. Nothing is silently hidden: an item a key cannot reach renders greyed
+/// and SAYS WHY, because hiding it leaves the user hunting for a page they were
+/// told exists, and leaving it live sends them into a 403 that names neither
+/// the route nor the missing grant.
+interface NavItem {
+  to: string
+  label: string
+  icon: React.ReactNode
+  disabledReason?: string
+}
+
+function SidebarLink({ item }: { item: NavItem }) {
+  if (item.disabledReason) {
+    return (
+      <span
+        title={item.disabledReason}
+        aria-disabled="true"
+        data-testid={`nav-disabled-${item.to}`}
+        className="flex items-center gap-3 px-3 py-2 rounded-md text-sm font-medium
+                   text-slate-600 cursor-not-allowed select-none"
+      >
+        {item.icon}
+        <span className="truncate">{item.label}</span>
+      </span>
+    )
+  }
+  return (
+    <NavLink
+      to={item.to}
+      end={item.to === '/'}
+      className={({ isActive }) =>
+        [
+          'flex items-center gap-3 px-3 py-2 rounded-md text-sm font-medium transition',
+          isActive
+            ? 'bg-indigo-600/30 text-indigo-300'
+            : 'text-slate-400 hover:text-slate-200 hover:bg-slate-700/50',
+        ].join(' ')
+      }
+    >
+      {item.icon}
+      <span className="truncate">{item.label}</span>
+    </NavLink>
+  )
+}
+
+function NavSection({ title, items }: { title: string; items: NavItem[] }) {
+  return (
+    <div className="flex flex-col gap-1">
+      <div className="mt-4 mb-1 px-3">
+        <span className="text-[10px] uppercase tracking-widest text-slate-600 font-semibold">
+          {title}
+        </span>
+      </div>
+      {items.map((item) => (
+        <SidebarLink key={item.to} item={item} />
+      ))}
+    </div>
+  )
+}
+
+export function Sidebar() {
+  const admin = useAuthStore((s) => s.admin)
+  const currentProject = useAuthStore((s) => s.currentProject)
+
+  // Every PROJECT item resolves its route against the selected project, so with
+  // none selected they would all act on nothing.
+  const noProject = currentProject === null ? 'Select a project first.' : undefined
+
+  // Relations is a PER-PROJECT surface and belongs here next to Collections and
+  // Documents - it describes this project's data model, not the server's.
+  //
+  // It is nevertheless ADMIN-ONLY TO CALL: every relations route in
+  // `src/handlers/relations.cpp` runs `requireAdmin(k)` BEFORE
+  // `requireProjectAccess(k, project)`, list and read included. The route being
+  // project-scoped says where it acts, NOT who may call it, so a non-admin
+  // project key is refused 403 on all of them. Grouping it correctly and
+  // disabling it for a non-admin session keeps both facts visible.
+  const projectNav: NavItem[] = [
+    { to: '/', label: 'Dashboard', icon: <LayoutDashboard size={18} /> },
+    { to: '/collections', label: 'Collections', icon: <Database size={18} />, disabledReason: noProject },
+    { to: '/documents', label: 'Documents', icon: <FileText size={18} />, disabledReason: noProject },
+    {
+      to: '/relations',
+      label: 'Relations',
+      icon: <Share2 size={18} />,
+      disabledReason: admin
+        ? noProject
+        : 'Relations needs an admin key: every relations route requires one, read included.',
+    },
+    { to: '/files', label: 'Files', icon: <FileText size={18} />, disabledReason: noProject },
+    { to: '/secrets', label: 'Secrets', icon: <Code2 size={18} />, disabledReason: noProject },
+    { to: '/functions', label: 'Functions', icon: <Code2 size={18} />, disabledReason: noProject },
+    { to: '/rag', label: 'RAG Tester', icon: <Search size={18} />, disabledReason: noProject },
+  ]
+
+  // Settings is listed here because the surfaces that dominate it - global
+  // embeddings, cache, access, Web UI - are all `requireAdmin`. It is
+  // deliberately NOT disabled for a non-admin key: the per-project embeddings
+  // tab is `requireProjectManage`, so a project manager has something real to
+  // do on that page, and the page itself renders only the tabs the key may use.
+  const adminNav: NavItem[] = [
+    {
+      to: '/projects',
+      label: 'Projects',
+      icon: <FolderKanban size={18} />,
+      disabledReason: admin ? undefined : 'Creating and deleting projects needs an admin key.',
+    },
+    {
+      to: '/keys',
+      label: 'API Keys',
+      icon: <KeyRound size={18} />,
+      disabledReason: admin ? undefined : 'Key management needs an admin key.',
+    },
+    {
+      to: '/settings',
+      label: 'Settings',
+      icon: <SettingsIcon size={18} />,
+    },
+  ]
+
+  return (
+    <aside className="w-60 shrink-0 flex flex-col bg-[#080c12] border-r border-slate-800">
+      <div className="px-4 py-5 border-b border-slate-800">
+        <span className="text-lg font-bold tracking-tight text-indigo-300">VectorAPI</span>
+      </div>
+
+      {/* The selected project decides what every PROJECT item below acts on, so
+          it sits above them rather than in the top bar, where it read as a
+          page-level control and left the user unable to tell which project
+          they were looking at. */}
+      <div className="px-3 py-3 border-b border-slate-800 flex flex-col gap-1.5">
+        <span className="px-1 text-[10px] uppercase tracking-widest text-slate-600 font-semibold">
+          Current project
+        </span>
+        <ProjectSelector />
+        {currentProject === null && (
+          <span className="px-1 text-xs text-amber-400/80">No project selected.</span>
+        )}
+      </div>
+
+      <nav className="flex-1 px-3 pb-4 flex flex-col gap-1 overflow-y-auto">
+        <NavSection title="Project" items={projectNav} />
+        <NavSection title="Administration" items={adminNav} />
+
+        <div className="mt-auto pt-4">
+          <a
+            href={serverUrl('/docs')}
+            target="_blank"
+            rel="noreferrer"
+            className="flex items-center gap-3 px-3 py-2 rounded-md text-sm font-medium transition
+                       text-slate-500 hover:text-slate-200 hover:bg-slate-700/50"
+          >
+            <BookOpen size={18} />
+            API Docs
+          </a>
+        </div>
+      </nav>
+    </aside>
+  )
+}

+ 166 - 18
webui/src/pages/Collections.tsx

@@ -4,6 +4,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query'
 import {
   Plus, Trash2, ChevronRight, RefreshCw, Search as SearchIcon,
   FileText, Database, HardDrive, Layers, ArrowUp, ArrowDown, ArrowUpDown, Info,
+  EyeOff, ShieldCheck, ShieldOff, HelpCircle, KeyRound,
 } from 'lucide-react'
 import { api } from '@/api/client'
 import { useAuthStore } from '@/stores/authStore'
@@ -25,10 +26,16 @@ function humanizeBytes(bytes: number): string {
   return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`
 }
 
+// The registry stamps `created_at` with time(2) - SECONDS since the epoch, not
+// the milliseconds a document's `_created_at` carries. The two are different
+// units on two different routes and multiplying by the wrong one is a 1970 date
+// or a year-56000 one, so the conversion is stated here rather than shared.
 function formatDate(ts: number): string {
-  if (!ts) return '—'
+  if (!ts) return 'not recorded'
   try {
-    return new Date(ts * 1000).toLocaleString()
+    const d = new Date(ts * 1000)
+    if (Number.isNaN(d.getTime())) return String(ts)
+    return d.toLocaleString()
   } catch {
     return String(ts)
   }
@@ -258,7 +265,10 @@ function StatChip({ icon, label, value }: { icon: React.ReactNode; label: string
   )
 }
 
-function SummaryBar({ collections }: { collections: CollectionMeta[] }) {
+function SummaryBar({ collections, scopeFiltered }: {
+  collections: CollectionMeta[]
+  scopeFiltered?: boolean
+}) {
   const totals = useMemo(() => {
     let docs = 0, bytes = 0, vectors = 0
     let hasDocs = false, hasBytes = false
@@ -270,12 +280,18 @@ function SummaryBar({ collections }: { collections: CollectionMeta[] }) {
     return { docs, bytes, vectors, hasDocs, hasBytes }
   }, [collections])
 
+  // The totals are sums over the ROWS RETURNED. For a scoped key that is not
+  // the project's total, and a figure labelled "Documents" that silently means
+  // "documents you can see" is the kind of number someone later quotes as a
+  // project total.
+  const suffix = scopeFiltered === true ? ' (visible)' : ''
+
   return (
     <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
-      <StatChip icon={<Layers size={16} />} label="Collections" value={collections.length.toLocaleString()} />
-      <StatChip icon={<FileText size={16} />} label="Documents" value={totals.hasDocs ? totals.docs.toLocaleString() : '—'} />
-      <StatChip icon={<HardDrive size={16} />} label="Total size" value={totals.hasBytes ? humanizeBytes(totals.bytes) : '—'} />
-      <StatChip icon={<Database size={16} />} label="Vector collections" value={totals.vectors.toLocaleString()} />
+      <StatChip icon={<Layers size={16} />} label={`Collections${suffix}`} value={collections.length.toLocaleString()} />
+      <StatChip icon={<FileText size={16} />} label={`Documents${suffix}`} value={totals.hasDocs ? totals.docs.toLocaleString() : '—'} />
+      <StatChip icon={<HardDrive size={16} />} label={`Total size${suffix}`} value={totals.hasBytes ? humanizeBytes(totals.bytes) : '—'} />
+      <StatChip icon={<Database size={16} />} label={`Vector collections${suffix}`} value={totals.vectors.toLocaleString()} />
     </div>
   )
 }
@@ -291,6 +307,71 @@ function DetailRow({ label, value }: { label: string; value: React.ReactNode })
   )
 }
 
+// `relations_enforced` is OMITTED by the collection route when the database
+// declined to answer, so there are THREE states and the third is not a synonym
+// for the second: "not enforced" is a setting, "not reported" is an unknown.
+// Drawing an unknown as a switch in the off position states something nobody
+// measured.
+function EnforcementValue({ enforced }: { enforced?: boolean }) {
+  if (enforced === undefined) {
+    return (
+      <span className="inline-flex items-center gap-1.5 text-amber-300">
+        <HelpCircle size={13} /> not reported
+      </span>
+    )
+  }
+  return enforced ? (
+    <span className="inline-flex items-center gap-1.5 text-emerald-300">
+      <ShieldCheck size={13} /> enforced
+    </span>
+  ) : (
+    <span className="inline-flex items-center gap-1.5 text-slate-300">
+      <ShieldOff size={13} /> not enforced
+    </span>
+  )
+}
+
+// Composite unique constraints, which the indexes route reports in its own
+// array beside `indexes` and which nothing in this UI displayed. A composite is
+// the constraint that refuses a write for a reason no single-field index
+// explains, so leaving it unshown is how a duplicate-key refusal becomes
+// unexplainable from the UI alone.
+//
+// Shares the `['indexes', project, collection]` query key with the index panel,
+// so this costs no extra request.
+function CompositeConstraints({ project, collection }: { project: string; collection: string }) {
+  const { data, isLoading, isError } = useQuery({
+    queryKey: ['indexes', project, collection],
+    queryFn: () => api.listIndexes(project, collection),
+  })
+
+  if (isLoading || isError) return null
+  const composites = data?.composite_unique
+  // ABSENT is not an empty list: a server that does not report the field has
+  // told us nothing about this collection's composite constraints, where an
+  // empty array says there are none.
+  if (composites === undefined) return null
+
+  return (
+    <div className="rounded-lg border border-slate-700/40 bg-slate-800/30 px-4 py-3">
+      <p className="text-xs font-medium uppercase tracking-wide text-slate-400">Composite unique constraints</p>
+      {composites.length === 0 ? (
+        <p className="mt-1 text-xs text-slate-500">None declared.</p>
+      ) : (
+        <ul className="mt-2 flex flex-col gap-1.5">
+          {composites.map((c, i) => (
+            <li key={i} className="flex items-center gap-2 text-xs">
+              <KeyRound size={13} className="text-indigo-400 shrink-0" />
+              <span className="font-mono text-slate-200">{c.fields.join(' + ')}</span>
+              <span className="text-slate-500">must be unique together</span>
+            </li>
+          ))}
+        </ul>
+      )}
+    </div>
+  )
+}
+
 interface DetailDrawerProps {
   project: string
   name: string | null
@@ -333,11 +414,18 @@ function CollectionDetailDrawer({ project, name, onClose }: DetailDrawerProps) {
               <DetailRow label="Embedding model" value={data.embedding_model || '—'} />
             )}
             <DetailRow label="Created" value={formatDate(data.created_at)} />
+            <DetailRow
+              label="Relations enforced"
+              value={<EnforcementValue enforced={data.relations_enforced} />}
+            />
           </dl>
 
           {/* Indexes */}
           <IndexPanel project={project} collection={data.name} />
 
+          {/* Composite unique constraints, which the index panel does not show */}
+          <CompositeConstraints project={project} collection={data.name} />
+
           {/* JSON Schema (database 2.16.0+; the panel renders nothing when
               `has_schema` is absent, which means this database has no schemas
               at all rather than this collection having none) */}
@@ -381,9 +469,12 @@ interface CollectionsTableProps {
   sort: SortField
   desc: boolean
   onSort: (field: SortField) => void
+  /// The server's own `scope_filtered`. UNDEFINED means the server did not
+  /// report it, which is a third answer and not a false one.
+  scopeFiltered?: boolean
 }
 
-function CollectionsTable({ collections, project, query, sort, desc, onSort }: CollectionsTableProps) {
+function CollectionsTable({ collections, project, query, sort, desc, onSort, scopeFiltered }: CollectionsTableProps) {
   const push = useToastStore((s) => s.push)
   const queryClient = useQueryClient()
   const navigate = useNavigate()
@@ -406,14 +497,44 @@ function CollectionsTable({ collections, project, query, sort, desc, onSort }: C
     }
   }
 
+  // An empty list has FOUR readings here and they are not interchangeable.
+  // Collapsing them into "no collections yet" is this codebase's most repeated
+  // trap: it reports an absence as a fact about the project when it may be a
+  // fact about the key, or about the filter, or about nothing at all.
   if (collections.length === 0) {
     return (
-      <div className="rounded-xl border border-slate-700/40 bg-slate-800/30 px-6 py-12 text-center">
-        <p className="text-slate-400 text-sm">
-          {query
-            ? `No collections match “${query}”.`
-            : 'No collections yet. Create one to get started.'}
-        </p>
+      <div
+        className="rounded-xl border border-slate-700/40 bg-slate-800/30 px-6 py-12 text-center"
+        data-testid="collections-empty"
+      >
+        {query ? (
+          <p className="text-slate-400 text-sm">
+            No collections match “{query}”.
+            {scopeFiltered === true && ' Your key is scoped, so this view may be partial even without the filter.'}
+          </p>
+        ) : scopeFiltered === true ? (
+          <div className="flex flex-col items-center gap-2">
+            <EyeOff size={18} className="text-amber-400/80" />
+            <p className="text-slate-300 text-sm">No collections are visible to this key.</p>
+            <p className="text-slate-500 text-xs max-w-md">
+              This key is scoped, so this view may be partial. An empty list here does not
+              mean the project is empty - it means nothing in it is within this key&apos;s scope.
+            </p>
+          </div>
+        ) : scopeFiltered === false ? (
+          <p className="text-slate-400 text-sm">
+            This project has no collections yet. Create one to get started.
+          </p>
+        ) : (
+          <div className="flex flex-col items-center gap-2">
+            <HelpCircle size={18} className="text-amber-400/80" />
+            <p className="text-slate-300 text-sm">No collections returned.</p>
+            <p className="text-slate-500 text-xs max-w-md">
+              This server did not say whether the view is scope-limited, so an empty list
+              cannot be read as an empty project.
+            </p>
+          </div>
+        )}
       </div>
     )
   }
@@ -430,6 +551,7 @@ function CollectionsTable({ collections, project, query, sort, desc, onSort }: C
               <th className="text-left px-4 py-3 text-xs font-semibold text-slate-400 uppercase tracking-wider">Embedding Model</th>
               <SortHeader label="Documents" field="documents" sort={sort} desc={desc} onSort={onSort} align="right" />
               <SortHeader label="Size" field="size" sort={sort} desc={desc} onSort={onSort} align="right" />
+              <SortHeader label="Created" field="created_at" sort={sort} desc={desc} onSort={onSort} align="right" />
               <th className="text-right px-4 py-3 text-xs font-semibold text-slate-400 uppercase tracking-wider">Actions</th>
             </tr>
           </thead>
@@ -465,6 +587,9 @@ function CollectionsTable({ collections, project, query, sort, desc, onSort }: C
                 <td className="px-4 py-3 text-right text-slate-300">
                   {col.size_bytes !== undefined ? humanizeBytes(col.size_bytes) : <span className="text-slate-600">—</span>}
                 </td>
+                <td className="px-4 py-3 text-right text-slate-400 text-xs whitespace-nowrap">
+                  {formatDate(col.created_at)}
+                </td>
                 <td className="px-4 py-3 text-right">
                   <div className="flex items-center justify-end gap-1">
                     <button
@@ -536,13 +661,13 @@ function TableSkeleton() {
   return (
     <div className="rounded-xl border border-slate-700/40 overflow-hidden animate-pulse">
       <div className="bg-slate-800/60 px-4 py-3 flex gap-8">
-        {[80, 60, 60, 120, 60, 60, 60].map((w, i) => (
+        {[80, 60, 60, 120, 60, 60, 90, 60].map((w, i) => (
           <div key={i} className="h-3 rounded bg-slate-700/60" style={{ width: w }} />
         ))}
       </div>
       {[1, 2, 3].map((i) => (
         <div key={i} className="border-t border-slate-700/20 bg-slate-900/20 px-4 py-4 flex gap-8">
-          {[80, 60, 60, 120, 60, 60, 60].map((w, j) => (
+          {[80, 60, 60, 120, 60, 60, 90, 60].map((w, j) => (
             <div key={j} className="h-3 rounded bg-slate-700/30" style={{ width: w }} />
           ))}
         </div>
@@ -608,6 +733,11 @@ export default function Collections() {
   }
 
   const collections = data?.collections ?? []
+  // TRUE for every scoped key whether or not anything was actually withheld.
+  // It means "your view may be partial", never "something was hidden" - the
+  // stronger wording would leak one bit about what exists outside this key's
+  // scope, which is the thing the scope filter is for.
+  const scopeFiltered = data?.scope_filtered
   const showControls = !isLoading && !isError && (collections.length > 0 || q.length > 0)
 
   return (
@@ -621,7 +751,8 @@ export default function Collections() {
             {!isLoading && !isError && (
               <span className="ml-2 text-slate-500">
                 ({collections.length} {collections.length === 1 ? 'collection' : 'collections'}
-                {q ? ' matching' : ''})
+                {q ? ' matching' : ''}
+                {scopeFiltered === true ? ' visible to this key' : ''})
               </span>
             )}
           </p>
@@ -636,9 +767,25 @@ export default function Collections() {
         </button>
       </div>
 
+      {/* Scope notice. Shown whenever the key is scoped, including when nothing
+          was withheld - because "nothing was withheld" is not something this
+          response says, and claiming it would be the leak. */}
+      {!isLoading && !isError && scopeFiltered === true && (
+        <div
+          className="flex items-start gap-2.5 rounded-lg border border-amber-500/20 bg-amber-500/5 px-4 py-3"
+          data-testid="collections-scope-notice"
+        >
+          <EyeOff size={15} className="text-amber-400/80 mt-0.5 shrink-0" />
+          <p className="text-xs text-amber-200/90">
+            This key is scoped, so this view may be partial.
+            {collections.length > 0 && ' The totals below cover only what is listed here.'}
+          </p>
+        </div>
+      )}
+
       {/* Summary */}
       {!isLoading && !isError && collections.length > 0 && (
-        <SummaryBar collections={collections} />
+        <SummaryBar collections={collections} scopeFiltered={scopeFiltered} />
       )}
 
       {/* Controls: server-side filter + refresh */}
@@ -685,6 +832,7 @@ export default function Collections() {
           sort={sort}
           desc={desc}
           onSort={handleSort}
+          scopeFiltered={scopeFiltered}
         />
       )}
 

+ 243 - 92
webui/src/pages/Dashboard.tsx

@@ -1,20 +1,51 @@
 import { useEffect } from 'react'
 import { useQuery, useQueryClient, useIsFetching } from '@tanstack/react-query'
 import {
-  FolderOpen,
   Layers,
   FileText,
   Database,
   Gauge,
   LayoutGrid,
   RefreshCw,
+  Zap,
+  ArrowDownToLine,
+  SearchCode,
 } from 'lucide-react'
 import { api } from '@/api/client'
 import { useAuthStore } from '@/stores/authStore'
 import { useToastStore } from '@/stores/toastStore'
 import type { ProjectStats, GlobalStats } from '@/types'
 
-// ─── helpers ─────────────────────────────────────────────────────────────────
+// --- types ------------------------------------------------------------------
+
+/// `GET /api/v1/stats` returns two things the shipped `GlobalStats` type does
+/// not describe, so it is widened HERE rather than in `@/types`, which another
+/// change is editing concurrently:
+///
+///  - an `embedding` object (`src/handlers/stats.cpp`), and
+///  - NOTHING AT ALL in several fields `GlobalStats` declares as required.
+///    When `getStats()` fails the handler writes `total_documents = 0` and
+///    emits no `total_collections`, `memory_used_bytes`, `insert_count` or
+///    `query_count`. A type that promises those are present turns a degraded
+///    answer into `undefined.toLocaleString()`, i.e. a blank page where the
+///    server was trying to say "the stats call failed". Everything is therefore
+///    optional and absence renders as "not reported", which is a different
+///    statement from zero.
+interface EmbeddingCacheStats {
+  cache_size?: number
+  cache_capacity?: number
+  cache_hits?: number
+  cache_misses?: number
+  cache_bytes?: number
+}
+
+interface ServerStats extends Partial<GlobalStats> {
+  embedding?: EmbeddingCacheStats
+  db_client_version?: string
+  db_client_commit?: string
+}
+
+// --- helpers ----------------------------------------------------------------
 
 function humanizeBytes(bytes: number): string {
   if (bytes < 1024) return `${bytes} B`
@@ -23,6 +54,12 @@ function humanizeBytes(bytes: number): string {
   return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`
 }
 
+/// One spelling for "the server did not send this", so a missing field never
+/// renders as a confident 0.
+function count(n: number | undefined): string {
+  return n === undefined ? 'not reported' : n.toLocaleString()
+}
+
 type PressureLevel = 'normal' | 'soft' | 'hard' | 'emergency'
 
 function pressureColor(level: string): string {
@@ -45,24 +82,55 @@ function pressureBg(level: string): string {
   return map[level as PressureLevel] ?? 'bg-slate-700/30 border-slate-600/30'
 }
 
-// ─── sub-components ───────────────────────────────────────────────────────────
+interface HitRateView {
+  value: string
+  sub: string
+}
+
+/// AN EMPTY CACHE AND A CACHE THAT IS MISSING EVERYTHING ARE OPPOSITE
+/// CONDITIONS AND MUST NOT RENDER THE SAME. With no requests yet the ratio is
+/// undefined, not zero, so it is reported as such: 0% is a real and alarming
+/// measurement that nothing here has earned.
+///
+/// The rate is computed from the raw counts rather than taken from the server's
+/// own `cache_hit_ratio`, which is `total > 0 ? hits / total : 0.0` and so
+/// collapses exactly this distinction before it leaves the process.
+function hitRate(e: EmbeddingCacheStats | undefined): HitRateView {
+  if (!e || e.cache_hits === undefined || e.cache_misses === undefined) {
+    return { value: 'not reported', sub: 'the server sent no cache counters' }
+  }
+  const total = e.cache_hits + e.cache_misses
+  if (total === 0) {
+    return { value: 'no requests yet', sub: '0 hits, 0 misses' }
+  }
+  const pct = (e.cache_hits / total) * 100
+  return {
+    value: `${pct.toFixed(1)}%`,
+    sub: `${e.cache_hits.toLocaleString()} hits, ${e.cache_misses.toLocaleString()} misses`,
+  }
+}
+
+// --- sub-components ---------------------------------------------------------
 
 interface StatCardProps {
   icon: React.ReactNode
   label: string
   value: React.ReactNode
   sub?: string
-  extra?: string
+  hint?: string
 }
 
-function StatCard({ icon, label, value, sub, extra }: StatCardProps) {
+function StatCard({ icon, label, value, sub, hint }: StatCardProps) {
   return (
-    <div className={`rounded-xl border bg-slate-800/60 border-slate-700/40 p-5 flex flex-col gap-3 ${extra ?? ''}`}>
+    <div
+      className="rounded-xl border bg-slate-800/60 border-slate-700/40 p-5 flex flex-col gap-3"
+      title={hint}
+    >
       <div className="flex items-center gap-2 text-slate-400 text-sm font-medium">
         <span className="w-4 h-4">{icon}</span>
         {label}
       </div>
-      <div className="text-2xl font-bold text-slate-100 leading-none">{value}</div>
+      <div className="text-2xl font-bold text-slate-100 leading-none break-words">{value}</div>
       {sub && <div className="text-xs text-slate-500">{sub}</div>}
     </div>
   )
@@ -78,19 +146,23 @@ function SkeletonCard() {
   )
 }
 
-// ─── project stats row ────────────────────────────────────────────────────────
-
-interface ProjectSectionProps {
-  currentProject: string
+function SectionHeading({ title, note }: { title: string; note?: string }) {
+  return (
+    <div className="mb-3">
+      <h2 className="text-sm font-semibold text-slate-400 uppercase tracking-wider">{title}</h2>
+      {note && <p className="text-xs text-slate-600 mt-0.5">{note}</p>}
+    </div>
+  )
 }
 
-function ProjectSection({ currentProject }: ProjectSectionProps) {
+// --- project stats ----------------------------------------------------------
+
+function ProjectSection({ currentProject }: { currentProject: string }) {
   const push = useToastStore((s) => s.push)
 
   const { data, isLoading, isError, error } = useQuery<ProjectStats>({
     queryKey: ['projectStats', currentProject],
     queryFn: () => api.projectStats(currentProject),
-    enabled: true,
   })
 
   useEffect(() => {
@@ -99,14 +171,18 @@ function ProjectSection({ currentProject }: ProjectSectionProps) {
     }
   }, [isError, error, push])
 
+  const heading = (
+    <SectionHeading
+      title={`Project: ${currentProject}`}
+      note="Totals for the selected project only. Source: GET /api/v1/projects/{project}/stats"
+    />
+  )
+
   if (isLoading) {
     return (
       <section>
-        <h2 className="text-sm font-semibold text-slate-400 uppercase tracking-wider mb-3">
-          Project — {currentProject}
-        </h2>
-        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
-          <SkeletonCard />
+        {heading}
+        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
           <SkeletonCard />
           <SkeletonCard />
         </div>
@@ -117,9 +193,7 @@ function ProjectSection({ currentProject }: ProjectSectionProps) {
   if (isError || !data) {
     return (
       <section>
-        <h2 className="text-sm font-semibold text-slate-400 uppercase tracking-wider mb-3">
-          Project — {currentProject}
-        </h2>
+        {heading}
         <p className="text-red-400 text-sm">Failed to load project stats.</p>
       </section>
     )
@@ -127,57 +201,54 @@ function ProjectSection({ currentProject }: ProjectSectionProps) {
 
   return (
     <section>
-      <h2 className="text-sm font-semibold text-slate-400 uppercase tracking-wider mb-3">
-        Project — {data.project}
-      </h2>
-      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
-        <StatCard
-          icon={<FolderOpen size={16} />}
-          label="Project"
-          value={data.project}
-          sub="current project"
-        />
+      {heading}
+      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
         <StatCard
           icon={<Layers size={16} />}
           label="Collections"
-          value={data.collections}
-          sub="in this project"
+          value={count(data.collections)}
+          sub={`in ${data.project}`}
         />
         <StatCard
           icon={<FileText size={16} />}
           label="Documents"
-          value={data.documents.toLocaleString()}
-          sub="across all collections"
+          value={count(data.documents)}
+          sub="across this project's collections"
         />
       </div>
     </section>
   )
 }
 
-// ─── global stats row (admin only) ───────────────────────────────────────────
+// --- server stats (admin only) ----------------------------------------------
 
-function GlobalSection() {
+function ServerSection() {
   const push = useToastStore((s) => s.push)
 
-  const { data, isLoading, isError, error } = useQuery<GlobalStats>({
+  const { data, isLoading, isError, error } = useQuery<ServerStats>({
     queryKey: ['globalStats'],
-    queryFn: api.globalStats,
+    queryFn: () => api.globalStats(),
   })
 
   useEffect(() => {
     if (isError && error instanceof Error) {
-      push(`Global stats error: ${error.message}`, 'error')
+      push(`Server stats error: ${error.message}`, 'error')
     }
   }, [isError, error, push])
 
+  const heading = (
+    <SectionHeading
+      title="Server"
+      note="Server-wide totals across every project. Admin key required. Source: GET /api/v1/stats"
+    />
+  )
+
   if (isLoading) {
     return (
       <section>
-        <h2 className="text-sm font-semibold text-slate-400 uppercase tracking-wider mb-3">
-          Global (admin)
-        </h2>
-        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-4">
-          {Array.from({ length: 5 }).map((_, i) => <SkeletonCard key={i} />)}
+        {heading}
+        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
+          {Array.from({ length: 6 }).map((_, i) => <SkeletonCard key={i} />)}
         </div>
       </section>
     )
@@ -186,72 +257,152 @@ function GlobalSection() {
   if (isError || !data) {
     return (
       <section>
-        <h2 className="text-sm font-semibold text-slate-400 uppercase tracking-wider mb-3">
-          Global (admin)
-        </h2>
-        <p className="text-red-400 text-sm">Failed to load global stats.</p>
+        {heading}
+        <p className="text-red-400 text-sm">Failed to load server stats.</p>
       </section>
     )
   }
 
-  const level = data.memory_pressure_level
+  const level = data.memory_pressure_level ?? 'unknown'
+  const pct = data.memory_pressure_percent
+  const rate = hitRate(data.embedding)
+  const cacheSize = data.embedding?.cache_size
+  const cacheCapacity = data.embedding?.cache_capacity
+  const cacheBytes = data.embedding?.cache_bytes
 
   return (
-    <section>
-      <h2 className="text-sm font-semibold text-slate-400 uppercase tracking-wider mb-3">
-        Global (admin)
-      </h2>
-      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-4">
-        <StatCard
-          icon={<FileText size={16} />}
-          label="Total Documents"
-          value={data.total_documents.toLocaleString()}
-          sub="across all projects"
-        />
-        <StatCard
-          icon={<Layers size={16} />}
-          label="Total Collections"
-          value={data.total_collections}
-          sub="across all projects"
-        />
-        <StatCard
-          icon={<Database size={16} />}
-          label="Memory Used"
-          value={humanizeBytes(data.memory_used_bytes)}
-          sub={`${data.memory_pressure_percent.toFixed(1)}% of limit`}
+    <section className="flex flex-col gap-6">
+      <div>
+        {heading}
+        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
+          <StatCard
+            icon={<FileText size={16} />}
+            label="Total documents"
+            value={count(data.total_documents)}
+            sub="across all projects"
+          />
+          <StatCard
+            icon={<Layers size={16} />}
+            label="Total collections"
+            value={count(data.total_collections)}
+            sub="across all projects"
+          />
+          <StatCard
+            icon={<LayoutGrid size={16} />}
+            label="Projects"
+            value={count(data.projects)}
+            sub="known to the database"
+          />
+          <StatCard
+            icon={<ArrowDownToLine size={16} />}
+            label="Inserts"
+            value={count(data.insert_count)}
+            sub="since the database started"
+          />
+          <StatCard
+            icon={<SearchCode size={16} />}
+            label="Queries"
+            value={count(data.query_count)}
+            sub="since the database started"
+          />
+          <StatCard
+            icon={<Database size={16} />}
+            label="Memory in use"
+            value={
+              data.memory_used_bytes === undefined
+                ? 'not reported'
+                : humanizeBytes(data.memory_used_bytes)
+            }
+            sub="database working set"
+          />
+        </div>
+      </div>
+
+      <div>
+        <SectionHeading
+          title="Memory pressure"
+          note="A fraction of the database's CONFIGURED memory budget, not of the machine's RAM."
         />
-        <div
-          className={`rounded-xl border p-5 flex flex-col gap-3 ${pressureBg(level)}`}
-        >
-          <div className="flex items-center gap-2 text-slate-400 text-sm font-medium">
-            <span className="w-4 h-4"><Gauge size={16} /></span>
-            Memory Pressure
-          </div>
-          <div className={`text-2xl font-bold leading-none capitalize ${pressureColor(level)}`}>
-            {level}
+        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
+          <div className={`rounded-xl border p-5 flex flex-col gap-3 ${pressureBg(level)}`}>
+            <div className="flex items-center gap-2 text-slate-400 text-sm font-medium">
+              <span className="w-4 h-4"><Gauge size={16} /></span>
+              Pressure level
+            </div>
+            <div className={`text-2xl font-bold leading-none capitalize ${pressureColor(level)}`}>
+              {level}
+            </div>
+            <div className="text-xs text-slate-500">
+              normal / soft / hard / emergency
+            </div>
           </div>
-          <div className="text-xs text-slate-500">{data.memory_pressure_percent.toFixed(1)}% utilized</div>
+          <StatCard
+            icon={<Gauge size={16} />}
+            label="Budget used"
+            // NEVER "N% memory used": a reader takes that to mean the machine.
+            // This is a percentage of a budget the operator configured
+            // (`storage.memory.max_memory_mb`), which the stats route does not
+            // report, so the budget cannot be named here.
+            value={pct === undefined ? 'not reported' : `${pct.toFixed(1)}% of budget`}
+            sub="percentage of the configured memory budget"
+            hint="The budget itself is not exposed by /api/v1/stats, so only the fraction can be shown."
+          />
         </div>
-        <StatCard
-          icon={<LayoutGrid size={16} />}
-          label="Projects"
-          value={data.projects}
-          sub="active projects"
+      </div>
+
+      <div>
+        <SectionHeading
+          title="Embedding cache"
+          note="In-process LRU over (endpoint, model, text). Per process: the runner keeps its own."
         />
+        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
+          <StatCard
+            icon={<Zap size={16} />}
+            label="Hit rate"
+            value={rate.value}
+            sub={rate.sub}
+          />
+          <StatCard
+            icon={<Layers size={16} />}
+            label="Entries"
+            value={
+              cacheSize === undefined
+                ? 'not reported'
+                : cacheCapacity === undefined
+                  ? cacheSize.toLocaleString()
+                  : `${cacheSize.toLocaleString()} / ${cacheCapacity.toLocaleString()}`
+            }
+            sub={cacheCapacity === undefined ? 'cached entries' : 'cached entries of capacity'}
+          />
+          <StatCard
+            icon={<Database size={16} />}
+            label="Cache size"
+            value={cacheBytes === undefined ? 'not reported' : humanizeBytes(cacheBytes)}
+            sub="vectors held in memory"
+          />
+        </div>
       </div>
+
+      {(data.db_client_version || data.db_client_commit) && (
+        <p className="text-xs text-slate-600">
+          Database client library: {data.db_client_version ?? 'unknown'}
+          {data.db_client_commit ? ` (${data.db_client_commit})` : ''}
+          {' '}- what the linker bound at runtime, not what the build targeted.
+        </p>
+      )}
     </section>
   )
 }
 
-// ─── page ─────────────────────────────────────────────────────────────────────
+// --- page -------------------------------------------------------------------
 
 export default function Dashboard() {
   const currentProject = useAuthStore((s) => s.currentProject)
   const admin = useAuthStore((s) => s.admin)
   const queryClient = useQueryClient()
 
-  // Stats are fetched on demand — this button re-fetches the project + global
-  // stats (no background polling).
+  // Stats are fetched on demand. This button re-fetches the project and server
+  // stats; there is no background polling.
   const fetching = useIsFetching({
     predicate: (query) => {
       const key = query.queryKey[0]
@@ -286,12 +437,12 @@ export default function Dashboard() {
         ? <ProjectSection currentProject={currentProject} />
         : (
           <p className="text-slate-400 text-sm">
-            No project selected — choose a project from the selector above.
+            No project selected. Choose one from the selector in the sidebar.
           </p>
         )
       }
 
-      {admin && <GlobalSection />}
+      {admin && <ServerSection />}
     </div>
   )
 }

+ 357 - 17
webui/src/pages/Documents.tsx

@@ -3,7 +3,7 @@ import { Link, useSearchParams } from 'react-router-dom'
 import { useQuery, useQueryClient } from '@tanstack/react-query'
 import {
   Plus, Search, Pencil, ChevronLeft, ChevronRight, Database,
-  Copy, ArrowUp, ArrowDown, ArrowUpDown, RefreshCw,
+  Copy, ArrowUp, ArrowDown, ArrowUpDown, RefreshCw, Lock, Bot, User,
 } from 'lucide-react'
 import { api } from '@/api/client'
 import { useAuthStore } from '@/stores/authStore'
@@ -13,7 +13,7 @@ import { ConfirmDialog } from '@/components/ConfirmDialog'
 import { JsonEditor } from '@/components/JsonEditor'
 import { RelationLinks } from '@/components/RelationLinks'
 import { DeleteImpactDialog } from '@/components/DeleteImpactDialog'
-import { ApiError } from '@/types'
+import { ApiError, DB_METADATA_FIELDS } from '@/types'
 import type { CollectionMeta } from '@/types'
 
 // ─── Filter op types ──────────────────────────────────────────────────────────
@@ -240,12 +240,295 @@ function FilterBar({
   )
 }
 
+// ─── Database metadata ────────────────────────────────────────────────────────
+
+const META_KEYS: readonly string[] = DB_METADATA_FIELDS
+
+function isMetaKey(key: string): boolean {
+  return META_KEYS.includes(key)
+}
+
+// Split a document the database handed back into the metadata it ATTACHED and
+// the body that is actually stored.
+//
+// These are not two views of one thing: the body is what a write sends and the
+// metadata is what every read overwrites. Showing them mixed invites a user to
+// edit a reserved key, and this service strips reserved keys from a write body,
+// so that edit would be accepted, discarded, and look like it worked.
+function splitDocument(doc: Record<string, unknown>): {
+  meta: Record<string, unknown>
+  body: Record<string, unknown>
+} {
+  const meta: Record<string, unknown> = {}
+  const body: Record<string, unknown> = {}
+  for (const [k, v] of Object.entries(doc)) {
+    if (isMetaKey(k)) meta[k] = v
+    else body[k] = v
+  }
+  return { meta, body }
+}
+
+// Remove any reserved key a user typed into the editor by hand.
+//
+// The panel keeps them out of the editor, but the editor is free-form JSON and
+// nothing stops someone typing `_version` into it. The server would strip it
+// anyway; stripping here as well is what lets the UI SAY so, instead of the
+// write quietly differing from what the user wrote.
+function stripMetadata(doc: Record<string, unknown>): {
+  body: Record<string, unknown>
+  removed: string[]
+} {
+  const { meta, body } = splitDocument(doc)
+  return { body, removed: Object.keys(meta) }
+}
+
+// Document timestamps are epoch MILLISECONDS by default - but a collection can
+// be configured for NANOSECONDS (`CollectionConfig::timestampPrecision`), and
+// `migrateCollectionTimestamps()` converts rows one at a time, so a single
+// collection can legitimately hold both at once. No route of ours reports a
+// collection's configured precision, so the value itself is the only evidence
+// available, and the discriminator used here is the database's OWN: its
+// migration skips already-converted rows on a 10^15 threshold.
+//
+// Guessing wrong is not a cosmetic error. A nanosecond value rendered as
+// milliseconds lands in the year 58000 and reads as corrupted data.
+const NS_THRESHOLD = 1e15
+
+function isNanoseconds(raw: number): boolean {
+  return raw >= NS_THRESHOLD
+}
+
+function epochToMillis(raw: number): number {
+  return isNanoseconds(raw) ? raw / 1e6 : raw
+}
+
+function formatEpoch(raw: number): string {
+  try {
+    const d = new Date(epochToMillis(raw))
+    if (Number.isNaN(d.getTime())) return '(not a renderable time)'
+    return d.toLocaleString()
+  } catch {
+    return '(not a renderable time)'
+  }
+}
+
+function relativeToNow(ms: number): string {
+  const delta = ms - Date.now()
+  const abs = Math.abs(delta)
+  const units: Array<[number, string]> = [
+    [86400000, 'day'], [3600000, 'hour'], [60000, 'minute'], [1000, 'second'],
+  ]
+  for (const [size, name] of units) {
+    if (abs >= size) {
+      const n = Math.round(abs / size)
+      const plural = n === 1 ? '' : 's'
+      return delta >= 0 ? `in ${n} ${name}${plural}` : `${n} ${name}${plural} ago`
+    }
+  }
+  return delta >= 0 ? 'in under a second' : 'under a second ago'
+}
+
+function asNumber(v: unknown): number | null {
+  if (typeof v === 'number' && Number.isFinite(v)) return v
+  if (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v))) return Number(v)
+  return null
+}
+
+function MetaRow({ label, hint, children }: {
+  label: string
+  hint?: React.ReactNode
+  children: React.ReactNode
+}) {
+  return (
+    <div className="px-3 py-2">
+      <div className="flex items-baseline justify-between gap-4">
+        <dt className="text-[11px] uppercase tracking-wider text-slate-500 shrink-0 font-mono">{label}</dt>
+        <dd className="text-xs text-slate-200 text-right break-all">{children}</dd>
+      </div>
+      {hint && <p className="mt-1 text-[11px] text-slate-500 text-right">{hint}</p>}
+    </div>
+  )
+}
+
+// A timestamp, shown BOTH ways on purpose: the local time is what a human
+// reads and the raw value is what a caller puts in a `?filter=` - so showing
+// only one of them makes the other a separate lookup.
+function TimestampValue({ raw }: { raw: number }) {
+  const ns = isNanoseconds(raw)
+  return (
+    <span className="inline-flex flex-col items-end gap-0.5">
+      <span>{formatEpoch(raw)}</span>
+      <span className="font-mono text-[11px] text-slate-500">
+        {raw}
+        <span className="ml-1 text-slate-600">{ns ? 'ns' : 'ms'}</span>
+      </span>
+    </span>
+  )
+}
+
+// `fn:<project>/<function-id>` identifies the FUNCTION that wrote the row, and
+// the function id is the half that carries the information: a consumer depends
+// on that granularity as their only after-the-fact attribution channel, which
+// is why it is rendered whole and never shortened to the project.
+function WriterValue({ value }: { value: unknown }) {
+  const s = typeof value === 'string' ? value : JSON.stringify(value)
+  if (typeof s === 'string' && s.startsWith('fn:')) {
+    return (
+      <span className="inline-flex items-center gap-1.5 justify-end">
+        <Bot size={12} className="text-indigo-400 shrink-0" />
+        <span className="font-mono text-indigo-300">{s}</span>
+      </span>
+    )
+  }
+  return (
+    <span className="inline-flex items-center gap-1.5 justify-end">
+      <User size={12} className="text-slate-500 shrink-0" />
+      <span className="font-mono">{s || <span className="text-slate-600">-</span>}</span>
+    </span>
+  )
+}
+
+// `_expires_at` has THREE readings, not two, and the third is the one that
+// looks like a bug when it is not:
+//
+//   absent  - no expiry. Never zero, and never "unknown".
+//   future  - the row will be swept at that time.
+//   PAST    - the row is past its deadline AND IS STILL HERE. Expiry is lazy:
+//             the sweep runs on its own schedule, so a row sitting past its
+//             expiry is ordinary, not evidence of a fault. It is also the row
+//             that must be left OUT of a restore, since a restored row carries
+//             no TTL and would come back immortal.
+function ExpiryValue({ present, raw }: { present: boolean; raw: number | null }) {
+  if (!present) {
+    return <span className="text-slate-400">no expiry</span>
+  }
+  if (raw === null) {
+    return <span className="text-amber-300">present but not a number</span>
+  }
+  const ms = epochToMillis(raw)
+  const expired = ms <= Date.now()
+  return (
+    <span className="inline-flex flex-col items-end gap-0.5">
+      <span className={expired ? 'text-amber-300' : 'text-slate-200'}>
+        {formatEpoch(raw)} ({relativeToNow(ms)})
+      </span>
+      <span className="font-mono text-[11px] text-slate-500">{raw} ms</span>
+      {expired && (
+        <span className="text-[11px] text-amber-400/90">
+          past its expiry and still stored - the sweep runs on its own schedule
+        </span>
+      )}
+    </span>
+  )
+}
+
+// The read-only half of a document.
+function DocumentMetaPanel({ meta, onCopy }: {
+  meta: Record<string, unknown>
+  onCopy: (text: string, label: string) => void
+}) {
+  if (Object.keys(meta).length === 0) return null
+
+  const id = meta['_id']
+  const version = asNumber(meta['_version'])
+  const createdAt = asNumber(meta['_created_at'])
+  const updatedAt = asNumber(meta['_updated_at'])
+  // Membership, not truthiness: ABSENT means "no expiry", and a present value
+  // can legitimately be in the past. `meta['_expires_at'] ? ...` would collapse
+  // both of those into the same rendering.
+  const expiresPresent = Object.prototype.hasOwnProperty.call(meta, '_expires_at')
+  const expiresAt = asNumber(meta['_expires_at'])
+
+  // Anything the database starts attaching that this UI does not know about
+  // yet. Listed rather than dropped: a field nobody renders is how a reader
+  // learns the server moved ahead of the UI.
+  const known = ['_id', '_version', '_created_at', '_updated_at', '_created_by', '_updated_by', '_expires_at']
+  const extra = Object.entries(meta).filter(([k]) => !known.includes(k))
+
+  return (
+    <div className="rounded-lg border border-slate-700/40 bg-slate-900/40" data-testid="doc-meta-panel">
+      <div className="flex items-center gap-2 border-b border-slate-700/40 px-3 py-2">
+        <Lock size={12} className="text-slate-500" />
+        <span className="text-xs font-semibold text-slate-300">Database metadata</span>
+        <span className="text-[11px] text-slate-500">
+          read-only - attached by the database, never part of the stored body
+        </span>
+      </div>
+
+      <dl className="divide-y divide-slate-700/30">
+        {id !== undefined && (
+          <MetaRow label="_id" hint="the document's identity; it is taken from the URL on a write, never from the body">
+            <span className="inline-flex items-center gap-1.5 justify-end">
+              <span className="font-mono">{String(id)}</span>
+              <button
+                onClick={() => onCopy(String(id), 'Document ID')}
+                className="p-1 rounded text-slate-500 hover:text-slate-200 hover:bg-slate-700/50 transition"
+                aria-label="Copy document ID"
+                title="Copy ID"
+              >
+                <Copy size={11} />
+              </button>
+            </span>
+          </MetaRow>
+        )}
+
+        {version !== null && (
+          <MetaRow label="_version" hint="the value a conditional write passes as ?if_version=">
+            <span className="font-mono">{version}</span>
+          </MetaRow>
+        )}
+
+        {createdAt !== null && (
+          <MetaRow label="_created_at">
+            <TimestampValue raw={createdAt} />
+          </MetaRow>
+        )}
+
+        {updatedAt !== null && (
+          <MetaRow label="_updated_at">
+            <TimestampValue raw={updatedAt} />
+          </MetaRow>
+        )}
+
+        {meta['_created_by'] !== undefined && (
+          <MetaRow label="_created_by" hint="a function writes as fn:<project>/<function-id>">
+            <WriterValue value={meta['_created_by']} />
+          </MetaRow>
+        )}
+
+        {meta['_updated_by'] !== undefined && (
+          <MetaRow label="_updated_by">
+            <WriterValue value={meta['_updated_by']} />
+          </MetaRow>
+        )}
+
+        <MetaRow
+          label="_expires_at"
+          hint={expiresPresent ? undefined : 'the field is absent, which means no expiry - it is never reported as zero'}
+        >
+          <ExpiryValue present={expiresPresent} raw={expiresAt} />
+        </MetaRow>
+
+        {extra.map(([k, v]) => (
+          <MetaRow key={k} label={k} hint="reserved by the database; this UI has no specific rendering for it yet">
+            <span className="font-mono">{JSON.stringify(v)}</span>
+          </MetaRow>
+        ))}
+      </dl>
+    </div>
+  )
+}
+
 // ─── Document editor modal ────────────────────────────────────────────────────
 
 interface DocEditorModalProps {
   open: boolean
   title: string
+  /// The STORED BODY only. The database's own fields are rendered separately
+  /// and read-only, so the editor cannot be used to write one.
   initialJson: string
+  /// The database's attached fields for this document, empty for a new one.
+  meta: Record<string, unknown>
   // Present only when editing an existing document; enables the relation links
   // and the delete-impact preview.
   project?: string
@@ -254,13 +537,14 @@ interface DocEditorModalProps {
   onClose: () => void
   onSave: (parsed: Record<string, unknown>) => Promise<void>
   onDelete?: () => void
+  onCopy: (text: string, label: string) => void
   saving: boolean
 }
 
 function DocEditorModal({
-  open, title, initialJson,
+  open, title, initialJson, meta,
   project, collection, docId,
-  onClose, onSave, onDelete, saving,
+  onClose, onSave, onDelete, onCopy, saving,
 }: DocEditorModalProps) {
   const [json, setJson] = useState(initialJson)
   const [jsonValid, setJsonValid] = useState(true)
@@ -286,6 +570,8 @@ function DocEditorModal({
     <>
       <Modal open={open} title={title} onClose={onClose}>
         <div className="flex flex-col gap-4">
+          <DocumentMetaPanel meta={meta} onCopy={onCopy} />
+
           <JsonEditor
             value={json}
             onChange={setJson}
@@ -300,7 +586,11 @@ function DocEditorModal({
           {project && collection && docId && jsonValid && (() => {
             let parsed: Record<string, unknown> = {}
             try { parsed = JSON.parse(json) as Record<string, unknown> } catch { return null }
-            return <RelationLinks project={project} collection={collection} doc={parsed} />
+            // The WHOLE document, metadata included. The editor now holds only
+            // the body, and a relation is free to be declared on a field this
+            // split moved out of it - so passing the body alone would silently
+            // stop resolving those links.
+            return <RelationLinks project={project} collection={collection} doc={{ ...meta, ...parsed }} />
           })()}
 
           <div className="flex items-center justify-between pt-1">
@@ -372,13 +662,21 @@ interface ResultsTableProps {
   sortField: string
   sortDesc: boolean
   onSortById: () => void
+  /// Whether a filter was in force for this result. An empty collection and a
+  /// filter that matched nothing are different facts, and one message for both
+  /// makes the reader guess which they are looking at.
+  filtered: boolean
 }
 
-function ResultsTable({ docs, onRowClick, onCopy, sortField, sortDesc, onSortById }: ResultsTableProps) {
+function ResultsTable({ docs, onRowClick, onCopy, sortField, sortDesc, onSortById, filtered }: ResultsTableProps) {
   if (docs.length === 0) {
     return (
       <div className="rounded-xl border border-slate-700/40 bg-slate-800/30 px-6 py-10 text-center">
-        <p className="text-slate-400 text-sm">No documents found.</p>
+        <p className="text-slate-400 text-sm" data-testid="docs-empty">
+          {filtered
+            ? 'No documents match this filter. The collection may still hold documents.'
+            : 'This collection holds no documents.'}
+        </p>
       </div>
     )
   }
@@ -473,7 +771,10 @@ type ModalMode = 'new' | 'edit'
 interface ModalState {
   mode: ModalMode
   docId: string
+  /// The stored body, which is the only part a write sends.
   json: string
+  /// The database's attached fields, rendered read-only.
+  meta: Record<string, unknown>
 }
 
 export default function Documents() {
@@ -516,7 +817,7 @@ export default function Documents() {
 
   // Modal state
   const [modalOpen, setModalOpen] = useState(false)
-  const [modalState, setModalState] = useState<ModalState>({ mode: 'new', docId: '', json: '{}' })
+  const [modalState, setModalState] = useState<ModalState>({ mode: 'new', docId: '', json: '{}', meta: {} })
   const [saving, setSaving] = useState(false)
 
   // Auto-select first collection on project change
@@ -546,13 +847,20 @@ export default function Documents() {
 
   const docs = findData?.documents ?? []
   const docCount = findData?.count ?? null
+  // `total` is the exact number of rows matching the filters, computed server
+  // side BEFORE pagination - not an estimate and not a page count.
+  const totalMatching = findData?.total ?? null
 
-  // Pagination — the API returns a page of results (no grand total), so we use
-  // the full-page heuristic: a full page means there is probably a next page.
   const limitNum = parseInt(limit, 10) || 50
   const offsetNum = parseInt(offset, 10) || 0
   const canPrev = offsetNum > 0
-  const canNext = docs.length >= limitNum
+  // `has_more` is the server's own answer and it is emitted unconditionally,
+  // so an ABSENT field means one thing only: a server older than the release
+  // that added it. That is the single case the old full-page heuristic is
+  // still right for, and it is wrong whenever the last page happens to be
+  // exactly full - which offered a Next button onto an empty page.
+  const hasMoreReported = findData?.has_more
+  const canNext = hasMoreReported ?? docs.length >= limitNum
 
   const invalidateDocs = () => {
     void queryClient.invalidateQueries({ queryKey: ['documents', currentProject, effectiveCollection] })
@@ -600,7 +908,13 @@ export default function Documents() {
       try {
         const full = await api.getDocument(currentProject, effectiveCollection, openId)
         if (cancelled) return
-        setModalState({ mode: 'edit', docId: openId, json: JSON.stringify(full, null, 2) })
+        const split = splitDocument(full)
+        setModalState({
+          mode: 'edit',
+          docId: openId,
+          json: JSON.stringify(split.body, null, 2),
+          meta: split.meta,
+        })
         setModalOpen(true)
       } catch (err) {
         if (!cancelled) push(`Could not open ${openId}: ${err instanceof ApiError ? err.message : String(err)}`, 'error')
@@ -640,10 +954,15 @@ export default function Documents() {
     const id = docId(doc)
     try {
       const fullDoc = await api.getDocument(currentProject, effectiveCollection, id)
+      // The editor gets the BODY; the database's own fields go to the
+      // read-only panel. Editing one of them would be accepted here and
+      // discarded by the server, which is the worst of both.
+      const split = splitDocument(fullDoc)
       setModalState({
         mode: 'edit',
         docId: id,
-        json: JSON.stringify(fullDoc, null, 2),
+        json: JSON.stringify(split.body, null, 2),
+        meta: split.meta,
       })
       setModalOpen(true)
     } catch (err) {
@@ -656,12 +975,23 @@ export default function Documents() {
   const handleSave = async (parsed: Record<string, unknown>) => {
     if (!currentProject || !effectiveCollection) return
     setSaving(true)
+    // Reserved keys never reach the request. The server strips them anyway, so
+    // sending one would be accepted and silently discarded - the user would see
+    // a successful save and an unchanged value. Stripping here lets the UI name
+    // what it dropped instead.
+    const { body, removed } = stripMetadata(parsed)
+    if (removed.length > 0) {
+      push(
+        `${removed.join(', ')} ${removed.length === 1 ? 'is' : 'are'} attached by the database and cannot be written - left out of this save.`,
+        'info',
+      )
+    }
     try {
       if (modalState.mode === 'new') {
-        await api.insertDocument(currentProject, effectiveCollection, parsed)
+        await api.insertDocument(currentProject, effectiveCollection, body)
         push('Document inserted.', 'success')
       } else {
-        await api.putDocument(currentProject, effectiveCollection, modalState.docId, parsed)
+        await api.putDocument(currentProject, effectiveCollection, modalState.docId, body)
         push('Document saved.', 'success')
       }
       setModalOpen(false)
@@ -759,9 +1089,10 @@ export default function Documents() {
           <p className="text-slate-400 text-sm mt-1">
             Project: <span className="text-slate-300 font-mono">{currentProject}</span>
             {docCount !== null && (
-              <span className="ml-2 text-slate-500">
+              <span className="ml-2 text-slate-500" data-testid="docs-count">
                 — showing {docCount.toLocaleString()}
                 {(canNext || offsetNum > 0) && ` (rows ${(offsetNum + 1).toLocaleString()}–${(offsetNum + docs.length).toLocaleString()})`}
+                {totalMatching !== null && ` of ${totalMatching.toLocaleString()} matching`}
               </span>
             )}
           </p>
@@ -779,7 +1110,7 @@ export default function Documents() {
           </button>
           <button
             onClick={() => {
-              setModalState({ mode: 'new', docId: '', json: '{}' })
+              setModalState({ mode: 'new', docId: '', json: '{}', meta: {} })
               setModalOpen(true)
             }}
             disabled={!effectiveCollection}
@@ -862,6 +1193,7 @@ export default function Documents() {
           sortField={sortField}
           sortDesc={sortDesc}
           onSortById={toggleSortById}
+          filtered={appliedQs.includes('filter=')}
         />
       )}
 
@@ -870,6 +1202,12 @@ export default function Documents() {
         <div className="flex items-center justify-between text-sm">
           <span className="text-slate-500 text-xs">
             Page {Math.floor(offsetNum / limitNum) + 1}
+            {totalMatching !== null && ` of ${Math.max(1, Math.ceil(totalMatching / limitNum)).toLocaleString()}`}
+            {hasMoreReported === undefined && (
+              <span className="ml-2 text-slate-600" title="This server does not report has_more; the Next button is a guess from a full page.">
+                (page count estimated)
+              </span>
+            )}
           </span>
           <div className="flex items-center gap-2">
             <button
@@ -899,12 +1237,14 @@ export default function Documents() {
         open={modalOpen}
         title={modalState.mode === 'new' ? 'New Document' : `Edit Document — ${modalState.docId}`}
         initialJson={modalState.json}
+        meta={modalState.meta}
         project={modalState.mode === 'edit' ? currentProject : undefined}
         collection={modalState.mode === 'edit' ? effectiveCollection : undefined}
         docId={modalState.mode === 'edit' ? modalState.docId : undefined}
         onClose={() => setModalOpen(false)}
         onSave={(parsed) => handleSave(parsed)}
         onDelete={modalState.mode === 'edit' ? () => void handleDelete() : undefined}
+        onCopy={(text, label) => void handleCopy(text, label)}
         saving={saving}
       />
     </div>

+ 415 - 0
webui/src/pages/ProjectFiles.tsx

@@ -0,0 +1,415 @@
+import { useState } from 'react'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { Download, Trash2, Upload } from 'lucide-react'
+import { api } from '@/api/client'
+import { Badge, FormRow, inputCls } from '@/components/form'
+import { ConfirmDialog } from '@/components/ConfirmDialog'
+import { useAuthStore } from '@/stores/authStore'
+import { useToastStore } from '@/stores/toastStore'
+import { ApiError } from '@/types'
+import type { ProjectFile } from '@/types'
+
+/// A project's stored binary assets: a logo, a signature image, a built SPA.
+///
+/// Reading answers to the scope rules under the reserved `_files`
+/// pseudo-collection, so any key granted it can list and download. WRITING
+/// additionally requires project-manage, because replacing a tenant's asset is
+/// a management act - a scoped read key must not be able to swap a logo. The
+/// UI does not pre-gate the write controls on that, because a session cannot
+/// see whether its own key carries project-manage; the server refuses with 403
+/// and the refusal is rendered as it arrives.
+
+const PAGE_SIZE = 50
+
+/// The per-file metadata key the static mount reads. A file carrying one is
+/// reachable without a credential once static serving is on; a file without one
+/// is private whatever the static setting says.
+const PATH_KEY = 'path'
+
+const MAX_NAME_LEN = 128
+const MAX_PATH_LEN = 1024
+
+export function formatBytes(n: number): string {
+  if (n < 1024) return `${n} B`
+  if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`
+  return `${(n / (1024 * 1024)).toFixed(2)} MiB`
+}
+
+export function formatDate(epochSeconds: number): string {
+  if (!epochSeconds) return 'unknown'
+  return new Date(epochSeconds * 1000).toLocaleString(undefined, {
+    year: 'numeric',
+    month: 'short',
+    day: 'numeric',
+    hour: '2-digit',
+    minute: '2-digit',
+  })
+}
+
+/// The client half of the server's `fileNameRejection`. The server is the
+/// authority; this exists so a bad name is visible before the upload rather
+/// than after it.
+export function fileNameError(name: string): string | null {
+  if (name === '') return 'A file name is required.'
+  if (name.length > MAX_NAME_LEN) return `A file name may be at most ${MAX_NAME_LEN} characters.`
+  if (name.includes('..')) return "A file name may not contain '..'."
+  if (name.startsWith('.')) return "A file name may not start with '.'."
+  if (name.includes('/') || name.includes('\\')) {
+    return 'A file name may not contain a path separator. It is one flat name; the served path is set separately below.'
+  }
+  if (!/^[A-Za-z0-9._-]+$/.test(name)) {
+    return "A file name may contain only letters, digits, '.', '-' and '_'."
+  }
+  return null
+}
+
+/// The client half of the server's `staticPathError`.
+export function filePathError(path: string): string | null {
+  if (path === '') return null // absent is legal, and means private
+  if (path.length > MAX_PATH_LEN) return `A path may be at most ${MAX_PATH_LEN} characters.`
+  if (!path.startsWith('/')) return "A path must start with '/'."
+  if (path.includes('?') || path.includes('#')) return "A path may not contain '?' or '#'."
+  if (path.split('/').some((s) => s === '..')) return "A path may not contain a '..' segment."
+  if (path !== '/' && path.endsWith('/')) return 'A path must not end with a slash.'
+  if (path.includes('//')) return 'A path must not contain an empty segment.'
+  const first = path.split('/').filter((s) => s !== '')[0] ?? ''
+  if (first === 'api' || first === 'fn' || first === 'healthz') {
+    return `A path may not sit under /${first}: the service's own surfaces always win, so nothing there would ever be reached.`
+  }
+  return null
+}
+
+/// A browser-chosen filename turned into a name this API accepts, so the
+/// common case needs no typing. Shown in the field rather than applied
+/// silently - the user has to be able to see what will be stored.
+export function suggestName(raw: string): string {
+  const base = raw.split(/[\\/]/).pop() ?? raw
+  const cleaned = base.replace(/[^A-Za-z0-9._-]/g, '-').replace(/^\.+/, '')
+  return cleaned.slice(0, MAX_NAME_LEN)
+}
+
+function pathOf(f: ProjectFile): string {
+  return f.metadata?.[PATH_KEY] ?? ''
+}
+
+export default function ProjectFiles() {
+  const project = useAuthStore((s) => s.currentProject)
+  const toast = useToastStore((s) => s.push)
+  const qc = useQueryClient()
+
+  const [offset, setOffset] = useState(0)
+  const [name, setName] = useState('')
+  const [path, setPath] = useState('')
+  const [picked, setPicked] = useState<File | null>(null)
+  const [uploading, setUploading] = useState(false)
+  const [toDelete, setToDelete] = useState<string | null>(null)
+
+  const filesQuery = useQuery({
+    queryKey: ['project-files', project, offset],
+    queryFn: () => api.listFiles(project!, PAGE_SIZE, offset),
+    enabled: !!project,
+  })
+
+  if (!project) return <p className="text-sm text-slate-400">Select a project first.</p>
+
+  const data = filesQuery.data
+  const files = data?.files ?? []
+  const nameErr = name === '' ? null : fileNameError(name)
+  const pathErr = filePathError(path.trim())
+  const canUpload = !uploading && picked !== null && name !== '' && !nameErr && !pathErr
+
+  async function onUpload(e: React.FormEvent) {
+    e.preventDefault()
+    if (!project || !picked || !canUpload) return
+    setUploading(true)
+    try {
+      const trimmedPath = path.trim()
+      const stored = await api.uploadFile(
+        project,
+        name,
+        picked,
+        picked.type || 'application/octet-stream',
+        trimmedPath === '' ? undefined : trimmedPath,
+      )
+      await qc.invalidateQueries({ queryKey: ['project-files', project] })
+      toast(
+        trimmedPath === ''
+          ? `Uploaded ${stored.name}. It carries no path, so it stays private.`
+          : `Uploaded ${stored.name} at ${trimmedPath}. It is public once static serving is on.`,
+        'success',
+      )
+      setPicked(null)
+      setName('')
+      setPath('')
+    } catch (err) {
+      toast(
+        err instanceof ApiError
+          ? err.status === 403
+            ? `Refused: uploading a file needs a project-manage key. ${err.message}`
+            : err.message
+          : String(err),
+        'error',
+      )
+    } finally {
+      setUploading(false)
+    }
+  }
+
+  async function onDelete(fileName: string) {
+    if (!project) return
+    try {
+      await api.deleteFile(project, fileName)
+      await qc.invalidateQueries({ queryKey: ['project-files', project] })
+      toast(`Deleted ${fileName}.`, 'success')
+    } catch (err) {
+      toast(
+        err instanceof ApiError
+          ? err.status === 403
+            ? `Refused: deleting a file needs a project-manage key. ${err.message}`
+            : err.message
+          : String(err),
+        'error',
+      )
+    }
+  }
+
+  return (
+    <div className="flex flex-col gap-6 max-w-5xl">
+      <div>
+        <h1 className="text-2xl font-semibold text-slate-100">Files</h1>
+        <p className="text-slate-400 text-sm mt-1">
+          Binary assets stored against <strong>{project}</strong> - a logo, a
+          signature image, a built front end. A function reads them through{' '}
+          <code>ctx.files</code>, which is read-only; writing one is a
+          management act and happens here.
+        </p>
+      </div>
+
+      {/* ---- upload ---- */}
+      <form
+        onSubmit={onUpload}
+        className="rounded-xl border border-slate-700 bg-slate-800/30 px-6 py-5 flex flex-col gap-5"
+      >
+        <h2 className="text-sm font-medium text-slate-200">Upload a file</h2>
+
+        <FormRow
+          label="File"
+          hint="The bytes are sent as the request body, and the browser's own content type travels with them."
+        >
+          <input
+            type="file"
+            onChange={(e) => {
+              const f = e.target.files?.[0] ?? null
+              setPicked(f)
+              if (f && name === '') setName(suggestName(f.name))
+            }}
+            className="text-sm text-slate-300 file:mr-3 file:rounded-md file:border-0 file:bg-slate-700 file:px-3 file:py-1.5 file:text-sm file:text-slate-200"
+            data-testid="file-picker"
+          />
+          {picked && (
+            <p className="text-xs text-slate-500">
+              {formatBytes(picked.size)} · {picked.type || 'application/octet-stream'}
+            </p>
+          )}
+        </FormRow>
+
+        <FormRow
+          label="Stored name"
+          hint="One flat name - letters, digits, '.', '-' and '_'. Uploading an existing name REPLACES it."
+        >
+          <input
+            type="text"
+            value={name}
+            placeholder="logo.png"
+            onChange={(e) => setName(e.target.value)}
+            className={`${inputCls} w-80 font-mono`}
+            data-testid="file-name"
+          />
+        </FormRow>
+        {nameErr && (
+          <p className="text-xs text-rose-400" data-testid="file-name-error">
+            {nameErr}
+          </p>
+        )}
+
+        <FormRow
+          label="Served path (optional)"
+          hint="The alias this file is served at when static serving is on. Leave it empty and the file is PRIVATE: reachable only through the authenticated files route, never by a browser."
+          badge={path.trim() === '' ? <Badge>private</Badge> : <Badge tone="amber">public</Badge>}
+        >
+          <input
+            type="text"
+            value={path}
+            placeholder="/assets/logo.png"
+            onChange={(e) => setPath(e.target.value)}
+            className={`${inputCls} w-96 font-mono`}
+            data-testid="file-path"
+          />
+        </FormRow>
+        {pathErr && (
+          <p className="text-xs text-rose-400" data-testid="file-path-error">
+            {pathErr}
+          </p>
+        )}
+        <p className="text-xs text-slate-500" data-testid="file-path-note">
+          The path is stored on the file itself, and an upload REPLACES the whole
+          record rather than merging into it - so re-uploading a file without a
+          path removes the path it had and makes it private again. That is the
+          only way to take a path off.
+        </p>
+
+        {/* Not a SaveButton: this form uploads rather than saving a settings
+            document, and the label has to say which. It is still the form's
+            own submit button. */}
+        <button
+          type="submit"
+          disabled={!canUpload}
+          className="inline-flex items-center gap-2 self-start rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
+          data-testid="file-upload-submit"
+        >
+          <Upload size={14} />
+          {uploading ? 'Uploading...' : 'Upload'}
+        </button>
+      </form>
+
+      {/* ---- listing ---- */}
+      <div className="rounded-xl border border-slate-700 bg-slate-800/30">
+        <div className="px-6 py-4 border-b border-slate-700 flex items-center justify-between">
+          <h2 className="text-sm font-medium text-slate-200">
+            Stored files{' '}
+            {data && (
+              <span className="text-slate-500 font-normal">
+                ({data.total} in this project)
+              </span>
+            )}
+          </h2>
+          {data && (
+            <span className="text-xs text-slate-500">
+              showing {files.length === 0 ? 0 : offset + 1}
+              {files.length > 1 ? `-${offset + files.length}` : ''}
+            </span>
+          )}
+        </div>
+
+        {filesQuery.isLoading && <p className="px-6 py-4 text-sm text-slate-400">Loading...</p>}
+        {filesQuery.error && (
+          <p className="px-6 py-4 text-sm text-rose-400">{String(filesQuery.error)}</p>
+        )}
+        {!filesQuery.isLoading && files.length === 0 && (
+          <p className="px-6 py-4 text-sm text-slate-400">This project has no files.</p>
+        )}
+
+        {files.length > 0 && (
+          <table className="w-full text-sm">
+            <thead>
+              <tr className="text-left text-xs text-slate-500 border-b border-slate-700">
+                <th className="px-6 py-2 font-medium">Name</th>
+                <th className="px-3 py-2 font-medium">Served at</th>
+                <th className="px-3 py-2 font-medium">Type</th>
+                <th className="px-3 py-2 font-medium">Size</th>
+                <th className="px-3 py-2 font-medium">Uploaded</th>
+                <th className="px-3 py-2 font-medium"></th>
+              </tr>
+            </thead>
+            <tbody>
+              {files.map((f) => {
+                const p = pathOf(f)
+                return (
+                  <tr key={f.name} className="border-b border-slate-700/50" data-testid="file-row">
+                    <td className="px-6 py-3">
+                      <div className="font-mono text-slate-200">{f.name}</div>
+                      <div className="text-[11px] text-slate-500 font-mono" title="checksum">
+                        {f.checksum.slice(0, 16)}
+                        {f.checksum.length > 16 ? '...' : ''}
+                      </div>
+                    </td>
+                    <td className="px-3 py-3">
+                      {p === '' ? (
+                        <Badge>private</Badge>
+                      ) : (
+                        <span className="font-mono text-xs text-amber-300">{p}</span>
+                      )}
+                    </td>
+                    <td className="px-3 py-3 text-slate-400 text-xs">{f.content_type}</td>
+                    <td className="px-3 py-3 text-slate-400 text-xs">{formatBytes(f.size)}</td>
+                    <td className="px-3 py-3 text-slate-400 text-xs">{formatDate(f.created_at)}</td>
+                    <td className="px-3 py-3">
+                      <div className="flex items-center justify-end gap-1">
+                        <a
+                          href={api.fileDownloadUrl(project, f.name)}
+                          target="_blank"
+                          rel="noreferrer"
+                          title="Download"
+                          aria-label={`Download ${f.name}`}
+                          className="rounded-md p-2 text-slate-400 hover:text-slate-100 hover:bg-slate-700/60"
+                          data-testid="file-download"
+                        >
+                          <Download size={16} />
+                        </a>
+                        <button
+                          type="button"
+                          onClick={() => setToDelete(f.name)}
+                          title="Delete"
+                          aria-label={`Delete ${f.name}`}
+                          className="rounded-md p-2 text-slate-400 hover:text-rose-300 hover:bg-slate-700/60"
+                          data-testid="file-delete"
+                        >
+                          <Trash2 size={16} />
+                        </button>
+                      </div>
+                    </td>
+                  </tr>
+                )
+              })}
+            </tbody>
+          </table>
+        )}
+
+        {/* The order is newest-first WITHIN a page and is not a stable global
+            order, so this is paging through an offset rather than through a
+            sorted sequence - and it is said rather than implied by a tidy
+            pager. */}
+        <div className="px-6 py-3 flex items-center gap-3 border-t border-slate-700">
+          <button
+            type="button"
+            disabled={offset === 0}
+            onClick={() => setOffset((o) => Math.max(0, o - PAGE_SIZE))}
+            className="rounded-md border border-slate-600 px-3 py-1.5 text-xs text-slate-300 hover:bg-slate-700/60 disabled:opacity-40 disabled:cursor-not-allowed"
+            data-testid="files-prev"
+          >
+            Previous
+          </button>
+          <button
+            type="button"
+            disabled={!data?.has_more}
+            onClick={() => setOffset((o) => o + PAGE_SIZE)}
+            className="rounded-md border border-slate-600 px-3 py-1.5 text-xs text-slate-300 hover:bg-slate-700/60 disabled:opacity-40 disabled:cursor-not-allowed"
+            data-testid="files-next"
+          >
+            Next
+          </button>
+          <p className="text-xs text-slate-500" data-testid="files-order-note">
+            Newest first within a page. That is not a stable order across pages:
+            a file uploaded while you are reading shifts the window, so a name
+            can appear twice or not at all. Use it to browse, not to enumerate.
+          </p>
+        </div>
+      </div>
+
+      <ConfirmDialog
+        open={toDelete !== null}
+        title="Delete this file?"
+        message={
+          toDelete
+            ? `${toDelete} will be removed. Anything serving it - a static path, a function reading it through ctx.files - stops finding it immediately.`
+            : ''
+        }
+        confirmLabel="Delete"
+        onConfirm={() => {
+          if (toDelete) void onDelete(toDelete)
+        }}
+        onClose={() => setToDelete(null)}
+      />
+    </div>
+  )
+}

+ 350 - 0
webui/src/pages/ProjectSecrets.tsx

@@ -0,0 +1,350 @@
+import { useState } from 'react'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { KeyRound, Trash2 } from 'lucide-react'
+import { api } from '@/api/client'
+import { Badge, FormRow, inputCls } from '@/components/form'
+import { ConfirmDialog } from '@/components/ConfirmDialog'
+import { useAuthStore } from '@/stores/authStore'
+import { useToastStore } from '@/stores/toastStore'
+import { ApiError } from '@/types'
+
+/// Per-project secrets: what a function reads as `ctx.env.<NAME>`.
+///
+/// WRITE-ONLY STORAGE, and this page is built so nothing on it ever suggests
+/// otherwise. There is no masked value field, no dots standing in for a stored
+/// string and no reveal control, because every one of those implies a value
+/// that could be read back and none can be: no GET on this resource returns a
+/// value, deliberately and permanently. The list carries a name, a `set` flag
+/// and two timestamps, and that is the whole of what the server will say.
+///
+/// Authority is split: LISTING is project-manage (a function author needs to
+/// know which names their code may read, and a project-manage caller can
+/// already read every function's source), while WRITING and DELETING are
+/// ADMIN-only, because a stored value is a live credential every function in
+/// the project then executes with.
+
+const MAX_NAME_LEN = 64
+
+/// The client half of the server's `validSecretName`: `[A-Z_][A-Z0-9_]*`. The
+/// uppercase rule is not cosmetic - the name becomes an environment variable,
+/// and a case-insensitive host would otherwise let one project store the same
+/// secret under two spellings.
+export function secretNameError(name: string): string | null {
+  if (name === '') return 'A name is required.'
+  if (name.length > MAX_NAME_LEN) return `A name may be at most ${MAX_NAME_LEN} characters.`
+  if (/^[0-9]/.test(name)) {
+    return 'A name may not start with a digit: it has to be a usable identifier in ctx.env.'
+  }
+  if (!/^[A-Z0-9_]+$/.test(name)) {
+    return 'A name may contain only A-Z, 0-9 and underscore. Lower case is refused rather than folded, so one secret can never be stored under two spellings.'
+  }
+  return null
+}
+
+export function formatDate(epochSeconds: number): string {
+  if (!epochSeconds) return 'unknown'
+  return new Date(epochSeconds * 1000).toLocaleString(undefined, {
+    year: 'numeric',
+    month: 'short',
+    day: 'numeric',
+    hour: '2-digit',
+    minute: '2-digit',
+  })
+}
+
+export default function ProjectSecrets() {
+  const admin = useAuthStore((s) => s.admin)
+  const project = useAuthStore((s) => s.currentProject)
+  const toast = useToastStore((s) => s.push)
+  const qc = useQueryClient()
+
+  const [name, setName] = useState('')
+  const [value, setValue] = useState('')
+  const [saving, setSaving] = useState(false)
+  const [toDelete, setToDelete] = useState<string | null>(null)
+
+  const secretsQuery = useQuery({
+    queryKey: ['project-secrets', project],
+    queryFn: () => api.listSecrets(project!),
+    enabled: !!project,
+  })
+
+  if (!project) return <p className="text-sm text-slate-400">Select a project first.</p>
+
+  const data = secretsQuery.data
+  const secrets = data?.secrets ?? []
+  const existing = secrets.some((s) => s.name === name)
+  const nameErr = name === '' ? null : secretNameError(name)
+  const maxValueBytes = data?.max_value_bytes ?? 8192
+  const tooLong = new TextEncoder().encode(value).length > maxValueBytes
+  const atLimit =
+    !existing && data !== undefined && data.count >= data.max_secrets && name !== ''
+  const canSave = !saving && name !== '' && !nameErr && value !== '' && !tooLong && !atLimit
+
+  async function onSubmit(e: React.FormEvent) {
+    e.preventDefault()
+    if (!project || !canSave) return
+    setSaving(true)
+    try {
+      await api.putSecret(project, name, value)
+      await qc.invalidateQueries({ queryKey: ['project-secrets', project] })
+      toast(
+        existing
+          ? `${name} rotated. The previous value is gone and cannot be recovered.`
+          : `${name} stored. It is readable only by this project's functions, as ctx.env.${name}.`,
+        'success',
+      )
+      setName('')
+      // Cleared immediately on success: there is no reason for a credential to
+      // sit in a field after it has been sent.
+      setValue('')
+    } catch (err) {
+      toast(
+        err instanceof ApiError
+          ? err.status === 403
+            ? `Refused: writing a secret is admin-only. ${err.message}`
+            : err.message
+          : String(err),
+        'error',
+      )
+    } finally {
+      setSaving(false)
+    }
+  }
+
+  async function onDelete(secretName: string) {
+    if (!project) return
+    try {
+      await api.deleteSecret(project, secretName)
+      await qc.invalidateQueries({ queryKey: ['project-secrets', project] })
+      toast(`${secretName} deleted. Any function reading it now sees nothing.`, 'success')
+    } catch (err) {
+      toast(
+        err instanceof ApiError
+          ? err.status === 403
+            ? `Refused: deleting a secret is admin-only. ${err.message}`
+            : err.message
+          : String(err),
+        'error',
+      )
+    }
+  }
+
+  return (
+    <div className="flex flex-col gap-6 max-w-4xl">
+      <div>
+        <h1 className="text-2xl font-semibold text-slate-100">Secrets</h1>
+        <p className="text-slate-400 text-sm mt-1">
+          Credentials this project's functions read as{' '}
+          <code>ctx.env.&lt;NAME&gt;</code> - a bot token, a provider key, a mail
+          password. They live outside the documents API, so even a policy
+          granting every collection cannot read them.
+        </p>
+      </div>
+
+      {/* Stated once, at the top, because it governs how every control below
+          is built. */}
+      <div
+        className="rounded-md border border-slate-600 bg-slate-800/60 px-4 py-3"
+        data-testid="secrets-write-only"
+      >
+        <p className="text-sm text-slate-300">
+          <strong>Write-only.</strong> A stored value can never be read back -
+          not here, not through the API, not by an admin. Nothing on this page
+          shows a value, because there is no request that would return one. The
+          list below says which names exist and when each was last written, and
+          that is everything the server will tell anyone.
+        </p>
+        <p className="text-xs text-slate-400 mt-2">
+          So a value you cannot reproduce is gone once it is overwritten: a
+          rotation replaces it with no way back.
+        </p>
+      </div>
+
+      {/* The override, because the operator who hits it has no way to work it
+          out from this screen - the edit saves, the list updates, and the
+          function goes on seeing the old value. */}
+      <div
+        className="rounded-md border border-amber-500/30 bg-amber-500/10 px-4 py-3"
+        data-testid="secrets-host-override"
+      >
+        <p className="text-xs text-amber-300">
+          A host variable wins over anything stored here. If{' '}
+          <code>SVAPI_FN_{project}__NAME</code> is set in the runner's
+          environment file, that value reaches the function and the stored one
+          is ignored - which is deliberate, so a stolen API credential cannot
+          shadow a break-glass value. If an edit here appears to have no effect,
+          that variable is the first thing to check.
+        </p>
+      </div>
+
+      {/* ---- write ---- */}
+      {admin ? (
+        <form
+          onSubmit={onSubmit}
+          className="rounded-xl border border-slate-700 bg-slate-800/30 px-6 py-5 flex flex-col gap-5"
+        >
+          <h2 className="text-sm font-medium text-slate-200">
+            Store or rotate a secret
+          </h2>
+
+          <FormRow
+            label="Name"
+            hint="A-Z, 0-9 and underscore, not starting with a digit. This is the name the function reads: ctx.env.NAME."
+            badge={existing ? <Badge tone="amber">rotates an existing secret</Badge> : undefined}
+          >
+            <input
+              type="text"
+              value={name}
+              placeholder="OPENAI_API_KEY"
+              onChange={(e) => setName(e.target.value.toUpperCase())}
+              className={`${inputCls} w-80 font-mono`}
+              data-testid="secret-name"
+            />
+          </FormRow>
+          {nameErr && (
+            <p className="text-xs text-rose-400" data-testid="secret-name-error">
+              {nameErr}
+            </p>
+          )}
+
+          <FormRow
+            label="Value"
+            hint="Sent once and never returned. Leaving this empty is not how a secret is removed - delete it below instead, because an empty value would read as present but broken."
+          >
+            {/* A plain field the user is typing INTO, never a field that looks
+                like it was populated from the server. It starts empty on every
+                load and is cleared the moment the write succeeds. */}
+            <input
+              type="password"
+              value={value}
+              autoComplete="new-password"
+              placeholder={existing ? 'New value for this secret' : 'The value to store'}
+              onChange={(e) => setValue(e.target.value)}
+              className={`${inputCls} w-full max-w-xl font-mono`}
+              data-testid="secret-value"
+            />
+          </FormRow>
+          {tooLong && (
+            <p className="text-xs text-rose-400" data-testid="secret-value-too-long">
+              The value is longer than the {maxValueBytes} bytes this server
+              accepts.
+            </p>
+          )}
+          {existing && (
+            <p className="text-xs text-amber-400/90" data-testid="secret-rotate-warning">
+              <strong>{name}</strong> already exists. Saving overwrites it, and
+              the value it holds now cannot be recovered afterwards.
+            </p>
+          )}
+          {atLimit && (
+            <p className="text-xs text-rose-400" data-testid="secret-limit">
+              This project already holds the maximum of {data?.max_secrets}{' '}
+              secrets. An existing name can still be rotated; a new one needs
+              one deleting first.
+            </p>
+          )}
+
+          <button
+            type="submit"
+            disabled={!canSave}
+            className="inline-flex items-center gap-2 self-start rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
+            data-testid="secret-submit"
+          >
+            <KeyRound size={14} />
+            {saving ? 'Storing...' : existing ? 'Rotate' : 'Store'}
+          </button>
+        </form>
+      ) : (
+        <p className="text-sm text-slate-400" data-testid="secrets-read-only">
+          Writing and deleting a secret are admin-only: a stored value is a live
+          credential that every function in this project then runs with. The
+          names below are readable with a project-manage key so a function
+          author knows what their code may reach.
+        </p>
+      )}
+
+      {/* ---- listing ---- */}
+      <div className="rounded-xl border border-slate-700 bg-slate-800/30">
+        <div className="px-6 py-4 border-b border-slate-700">
+          <h2 className="text-sm font-medium text-slate-200">
+            Stored names{' '}
+            {data && (
+              <span className="text-slate-500 font-normal">
+                ({data.count} of {data.max_secrets})
+              </span>
+            )}
+          </h2>
+        </div>
+
+        {secretsQuery.isLoading && <p className="px-6 py-4 text-sm text-slate-400">Loading...</p>}
+        {secretsQuery.error && (
+          <p className="px-6 py-4 text-sm text-rose-400">{String(secretsQuery.error)}</p>
+        )}
+        {!secretsQuery.isLoading && secrets.length === 0 && (
+          <p className="px-6 py-4 text-sm text-slate-400">
+            This project holds no secrets.
+          </p>
+        )}
+
+        {secrets.length > 0 && (
+          <table className="w-full text-sm">
+            <thead>
+              <tr className="text-left text-xs text-slate-500 border-b border-slate-700">
+                <th className="px-6 py-2 font-medium">Name</th>
+                <th className="px-3 py-2 font-medium">Created</th>
+                <th className="px-3 py-2 font-medium">Last written</th>
+                <th className="px-3 py-2 font-medium"></th>
+              </tr>
+            </thead>
+            <tbody>
+              {secrets.map((s) => (
+                <tr key={s.name} className="border-b border-slate-700/50" data-testid="secret-row">
+                  <td className="px-6 py-3">
+                    <span className="font-mono text-slate-200">{s.name}</span>
+                    {/* `set` is the server's own flag. It is rendered as a word,
+                        never as a row of dots: dots look like a value. */}
+                    <span className="ml-2">
+                      {s.set ? <Badge tone="indigo">value stored</Badge> : <Badge>empty</Badge>}
+                    </span>
+                  </td>
+                  <td className="px-3 py-3 text-slate-400 text-xs">{formatDate(s.created_at)}</td>
+                  <td className="px-3 py-3 text-slate-400 text-xs">{formatDate(s.updated_at)}</td>
+                  <td className="px-3 py-3 text-right">
+                    {admin && (
+                      <button
+                        type="button"
+                        onClick={() => setToDelete(s.name)}
+                        title="Delete"
+                        aria-label={`Delete ${s.name}`}
+                        className="rounded-md p-2 text-slate-400 hover:text-rose-300 hover:bg-slate-700/60"
+                        data-testid="secret-delete"
+                      >
+                        <Trash2 size={16} />
+                      </button>
+                    )}
+                  </td>
+                </tr>
+              ))}
+            </tbody>
+          </table>
+        )}
+      </div>
+
+      <ConfirmDialog
+        open={toDelete !== null}
+        title="Delete this secret?"
+        message={
+          toDelete
+            ? `${toDelete} will be removed, and its value is not recoverable - nothing has a copy. Any function reading ctx.env.${toDelete} will find nothing from the next run onwards.`
+            : ''
+        }
+        confirmLabel="Delete"
+        onConfirm={() => {
+          if (toDelete) void onDelete(toDelete)
+        }}
+        onClose={() => setToDelete(null)}
+      />
+    </div>
+  )
+}

+ 9 - 0
webui/src/pages/Settings.tsx

@@ -8,6 +8,7 @@ import AccessTab from '@/pages/settings/AccessTab'
 import WebuiTab from '@/pages/settings/WebuiTab'
 import ProjectEmbeddingsTab from '@/pages/settings/ProjectEmbeddingsTab'
 import ProjectFunctionsTab from '@/pages/settings/ProjectFunctionsTab'
+import ProjectHostnamesTab from '@/pages/settings/ProjectHostnamesTab'
 import ProjectStaticTab from '@/pages/settings/ProjectStaticTab'
 
 interface TabDef {
@@ -42,6 +43,14 @@ export default function Settings() {
       adminOnly: true,
       render: () => <ProjectFunctionsTab />,
     },
+    {
+      id: 'hostnames',
+      label: 'Hostnames & TLS',
+      // Admin-only, matching the route: on the short path form the hostname is
+      // the tenancy boundary, so a project must not be able to claim one.
+      adminOnly: true,
+      render: () => <ProjectHostnamesTab />,
+    },
     {
       id: 'static',
       label: 'Static files',

+ 376 - 0
webui/src/pages/settings/ProjectHostnamesTab.tsx

@@ -0,0 +1,376 @@
+import { useEffect, useState } from 'react'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { Plus, Trash2 } from 'lucide-react'
+import { api } from '@/api/client'
+import { Badge, FormRow, inputCls, SaveButton } from '@/components/form'
+import { useAuthStore } from '@/stores/authStore'
+import { useToastStore } from '@/stores/toastStore'
+import { ApiError } from '@/types'
+import type { ProjectHostname } from '@/types'
+
+/// The hostnames a project answers on, and what a request path then looks like.
+///
+/// ADMIN ONLY, matching the route, and for the reason the handler gives: on the
+/// short path form the hostname IS the tenancy boundary, so a project-manage
+/// key must not be able to attach one to its own project.
+///
+/// Two things on this screen are not derivable from the list and must therefore
+/// be rendered rather than left to be inferred:
+///   - `served`, which says whether host gating is in force at all. A hostname
+///     stored while the deployment has not named itself is saved and INERT, and
+///     the list is byte-identical in both states.
+///   - what `path_style` does to a URL. 'short' and 'full' are meaningless as
+///     bare words, so each row shows the actual URL it produces.
+
+/// Normalise a hostname the way the SERVER does before it compares anything
+/// (`normaliseHost`): lowercase, drop a scheme the user pasted, drop a port,
+/// drop one trailing dot. This is not a refusal - the server accepts
+/// `Example.COM:8443` and matches it as `example.com` - so showing the typed
+/// value unchanged would be showing something the deployment will not use.
+export function normaliseHostInput(raw: string): string {
+  let h = raw.trim().toLowerCase()
+  h = h.replace(/^[a-z][a-z0-9+.-]*:\/\//, '')
+  // A path or a query the user pasted along with the name. Dropped here so the
+  // refusal below talks about the NAME, which is the part they must fix.
+  h = h.replace(/[/?#].*$/, '')
+  // Userinfo, same reason.
+  h = h.replace(/^[^@]*@/, '')
+  if (!h.startsWith('[')) h = h.replace(/:.*$/, '')
+  if (h.length > 1 && h.endsWith('.')) h = h.slice(0, -1)
+  return h
+}
+
+/// Why this hostname cannot be claimed, or null. Mirrors the server's
+/// `validHostname` over an ALREADY NORMALISED name, so the two agree on what a
+/// name is. The server remains the authority - it also knows about collisions
+/// and reserved names, which nothing here can see - and its 422 is rendered
+/// verbatim when it disagrees.
+export function hostnameError(normalised: string): string | null {
+  if (normalised === '') return 'A hostname is required.'
+  if (normalised.length > 253) return 'A hostname may be at most 253 characters.'
+  if (normalised.includes('*')) {
+    return 'A wildcard is refused here. A wildcard belongs in a certificate; this list holds exact names, one row each.'
+  }
+  if (!/^[a-zA-Z0-9.-]+$/.test(normalised)) {
+    return 'A hostname may contain only letters, digits, hyphens and dots.'
+  }
+  for (const label of normalised.split('.')) {
+    if (label === '') return 'A hostname may not contain an empty label, a leading dot or a trailing dot.'
+    if (label.length > 63) return 'Each label of a hostname may be at most 63 characters.'
+    if (label.startsWith('-') || label.endsWith('-')) {
+      return 'No label of a hostname may start or end with a hyphen.'
+    }
+  }
+  if (!normalised.includes('.')) {
+    return 'A single-label name is refused: it is a local alias, and registering one would make an intranet name resolve to a tenant.'
+  }
+  return null
+}
+
+/// The concrete URL a path style produces on this host. The whole point of
+/// showing it: 'short' and 'full' say nothing on their own, and the difference
+/// between them is exactly one path segment that a caller either must send or
+/// must not.
+export function exampleUrl(host: string, style: 'short' | 'full', project: string): string {
+  const h = host || 'your-host.example.com'
+  return style === 'short'
+    ? `https://${h}/api/v1/collections/notes/documents`
+    : `https://${h}/api/v1/projects/${project}/collections/notes/documents`
+}
+
+interface Row extends ProjectHostname {
+  /// Stable across edits so React keeps the input focused while typing, which
+  /// an index key does not once a row above is removed.
+  key: string
+}
+
+let rowSeq = 0
+function newRow(host = '', pathStyle: 'short' | 'full' = 'short'): Row {
+  rowSeq += 1
+  return { key: `row-${rowSeq}`, host, path_style: pathStyle }
+}
+
+export default function ProjectHostnamesTab() {
+  const admin = useAuthStore((s) => s.admin)
+  const project = useAuthStore((s) => s.currentProject)
+  const toast = useToastStore((s) => s.push)
+  const qc = useQueryClient()
+
+  const hostsQuery = useQuery({
+    queryKey: ['project-hostnames', project],
+    queryFn: () => api.getProjectHostnames(project!),
+    enabled: admin && !!project,
+  })
+
+  const [rows, setRows] = useState<Row[]>([])
+  const [saving, setSaving] = useState(false)
+  /// The server's own refusal, kept beside the client check rather than in
+  /// place of it. The three slugs are kept APART because their remedies are:
+  /// invalid means change the value, taken means negotiate for the name,
+  /// reserved means you cannot have it at all.
+  const [serverRefusal, setServerRefusal] = useState<{ code: string; message: string } | null>(null)
+
+  useEffect(() => {
+    const d = hostsQuery.data
+    if (!d) return
+    setRows(d.hostnames.map((h) => newRow(h.host, h.path_style)))
+  }, [hostsQuery.data])
+
+  if (!admin) {
+    return (
+      <p className="text-sm text-slate-400">
+        Hostnames are admin-only. On the short path form the hostname is the
+        tenancy boundary for every caller, so a project cannot attach one to
+        itself.
+      </p>
+    )
+  }
+  if (!project) return <p className="text-sm text-slate-400">Select a project first.</p>
+  if (hostsQuery.isLoading) return <p className="text-sm text-slate-400">Loading...</p>
+  if (hostsQuery.error) return <p className="text-sm text-rose-400">{String(hostsQuery.error)}</p>
+
+  /// Deployment-level, NOT per hostname: it says whether this server is gating
+  /// on hostnames at all, which it only does once the deployment has named
+  /// itself with an admin or global hostname.
+  const gating = hostsQuery.data?.served === true
+  const storedCount = hostsQuery.data?.hostnames.length ?? 0
+
+  const normalised = rows.map((r) => normaliseHostInput(r.host))
+  const rowErrors = rows.map((r, i) => (r.host.trim() === '' ? null : hostnameError(normalised[i]!)))
+  const duplicate = normalised.some(
+    (h, i) => h !== '' && normalised.findIndex((o) => o === h) !== i,
+  )
+  const anyBlank = rows.some((r) => r.host.trim() === '')
+  const canSave = !saving && !anyBlank && !duplicate && rowErrors.every((e) => e === null)
+
+  async function onSubmit(e: React.FormEvent) {
+    e.preventDefault()
+    if (!project || !canSave) return
+    // The whole list, every time. There is no merge on this route: what is
+    // sent becomes what is stored, so anything left out is removed.
+    const body: ProjectHostname[] = rows.map((r, i) => ({
+      host: normalised[i] ?? r.host.trim(),
+      path_style: r.path_style,
+    }))
+    setSaving(true)
+    setServerRefusal(null)
+    try {
+      await api.updateProjectHostnames(project, body)
+      await qc.invalidateQueries({ queryKey: ['project-hostnames', project] })
+      // The toast says which of the two states the save landed in, because the
+      // list it leaves behind cannot.
+      toast(
+        body.length === 0
+          ? `${project} now answers on no hostname of its own.`
+          : gating
+            ? `Saved. ${project} answers on ${body.length} hostname${body.length === 1 ? '' : 's'}.`
+            : `Saved, and not in force: this deployment is not gating on hostnames yet, so these names serve nothing today.`,
+        'success',
+      )
+    } catch (err) {
+      if (err instanceof ApiError && err.code) {
+        setServerRefusal({ code: err.code, message: err.message })
+      }
+      toast(err instanceof ApiError ? err.message : String(err), 'error')
+    } finally {
+      setSaving(false)
+    }
+  }
+
+  return (
+    <form onSubmit={onSubmit} className="flex flex-col gap-5 max-w-3xl">
+      <p className="text-xs text-slate-400">
+        The names this project answers on. A request arriving on one of them is
+        this project's, whatever path it carries.
+      </p>
+
+      {/* `served` rendered FIRST and prominently, because it is the one thing
+          that makes an identical list mean two different things. */}
+      {gating ? (
+        <div
+          className="rounded-md border border-emerald-500/30 bg-emerald-500/10 px-4 py-3"
+          data-testid="hostnames-gating-on"
+        >
+          <p className="text-sm text-emerald-300">
+            <strong>Host gating is in force.</strong> Hostnames stored here are
+            live: a request arriving on one of them is routed to{' '}
+            <strong>{project}</strong>.
+          </p>
+        </div>
+      ) : (
+        <div
+          className="rounded-md border border-amber-500/30 bg-amber-500/10 px-4 py-3"
+          data-testid="hostnames-gating-off"
+        >
+          <p className="text-sm text-amber-300">
+            <strong>Stored, and not in force.</strong> This deployment has not
+            named itself, so the server is not gating on hostnames and nothing
+            below serves anything today. Set an admin hostname or a global
+            hostname in the global settings to turn gating on; every name stored
+            here takes effect at that moment, with no further change needed.
+          </p>
+          {storedCount > 0 && (
+            <p className="text-xs text-amber-300/80 mt-2">
+              {storedCount} hostname{storedCount === 1 ? ' is' : 's are'} stored
+              and inert right now.
+            </p>
+          )}
+        </div>
+      )}
+
+      <FormRow
+        label="Hostnames"
+        hint="One exact name per row. No wildcard, no scheme and no path: a wildcard belongs in a certificate, not here. A scheme, a port or a trailing dot that you paste is dropped, because that is what the server compares."
+        badge={rows.length > 0 ? <Badge tone="indigo">{rows.length}</Badge> : <Badge>none</Badge>}
+      >
+        <div className="flex flex-col gap-3">
+          {rows.length === 0 && (
+            <p className="text-xs text-slate-500" data-testid="hostnames-empty">
+              No hostname. This project is reachable only through the shared
+              name, with <code>/projects/{project}/</code> in the path.
+            </p>
+          )}
+
+          {rows.map((row, i) => {
+            const err = rowErrors[i]
+            const norm = normalised[i] ?? ''
+            const normalisedAway = norm !== '' && norm !== row.host.trim()
+            return (
+              <div
+                key={row.key}
+                className="rounded-md border border-slate-700 bg-slate-800/40 px-3 py-3 flex flex-col gap-2"
+                data-testid="hostname-row"
+              >
+                <div className="flex items-center gap-2">
+                  <input
+                    type="text"
+                    value={row.host}
+                    placeholder="app.example.com"
+                    onChange={(e) => {
+                      const next = e.target.value
+                      setRows((rs) => rs.map((r) => (r.key === row.key ? { ...r, host: next } : r)))
+                      setServerRefusal(null)
+                    }}
+                    className={`${inputCls} flex-1 font-mono`}
+                    data-testid="hostname-host"
+                  />
+                  <select
+                    value={row.path_style}
+                    onChange={(e) => {
+                      const next = e.target.value === 'full' ? 'full' : 'short'
+                      setRows((rs) =>
+                        rs.map((r) => (r.key === row.key ? { ...r, path_style: next } : r)),
+                      )
+                    }}
+                    className={`${inputCls} w-36`}
+                    data-testid="hostname-path-style"
+                  >
+                    <option value="short">short path</option>
+                    <option value="full">full path</option>
+                  </select>
+                  <button
+                    type="button"
+                    onClick={() => setRows((rs) => rs.filter((r) => r.key !== row.key))}
+                    title="Remove this hostname"
+                    aria-label="Remove this hostname"
+                    className="rounded-md p-2 text-slate-400 hover:text-rose-300 hover:bg-slate-700/60"
+                    data-testid="hostname-remove"
+                  >
+                    <Trash2 size={16} />
+                  </button>
+                </div>
+
+                {/* The setting is meaningless as a bare word, so every row says
+                    what it does to a real URL on the name that was typed. */}
+                <p className="text-xs text-slate-500" data-testid="hostname-example">
+                  {row.path_style === 'short'
+                    ? 'Short: the project comes from the hostname, so the path carries no project segment.'
+                    : 'Full: the hostname selects nothing, so the path must still carry /projects/' +
+                      project +
+                      '/.'}
+                  <br />
+                  <code className="text-slate-300">
+                    {exampleUrl(norm, row.path_style, project)}
+                  </code>
+                </p>
+
+                {normalisedAway && (
+                  <p className="text-xs text-slate-400" data-testid="hostname-normalised">
+                    Stored and matched as <code className="text-slate-200">{norm}</code>. A scheme,
+                    a port, a path or a trailing dot is not part of the name the server compares.
+                  </p>
+                )}
+                {err && (
+                  <p className="text-xs text-rose-400" data-testid="hostname-error">
+                    {err}
+                  </p>
+                )}
+              </div>
+            )
+          })}
+
+          <button
+            type="button"
+            onClick={() => setRows((rs) => [...rs, newRow()])}
+            className="inline-flex items-center gap-2 self-start rounded-md border border-slate-600 px-3 py-1.5 text-sm text-slate-300 hover:bg-slate-700/60"
+            data-testid="hostname-add"
+          >
+            <Plus size={14} /> Add a hostname
+          </button>
+        </div>
+      </FormRow>
+
+      {duplicate && (
+        <p className="text-xs text-rose-400" data-testid="hostnames-duplicate">
+          The same hostname appears twice. A name can only point at one project,
+          and it cannot point at this one twice.
+        </p>
+      )}
+
+      {serverRefusal && (
+        <div
+          className="rounded-md border border-rose-500/30 bg-rose-500/10 px-4 py-3"
+          data-testid="hostnames-server-refusal"
+        >
+          <p className="text-sm text-rose-300">Refused: {serverRefusal.message}</p>
+          {/* The remedy, per slug, because the three are genuinely different
+              actions and one shared sentence would send a caller to the wrong
+              one. */}
+          <p className="text-xs text-rose-300/80 mt-1">
+            {serverRefusal.code === 'hostname_taken'
+              ? 'Another project holds this name. Nothing here can take it: it has to be removed from that project first.'
+              : serverRefusal.code === 'hostname_reserved'
+                ? "This is the deployment's own admin or global hostname. It can never be claimed by a project, so pick a different name."
+                : serverRefusal.code === 'invalid_hostname'
+                  ? 'Change the value. A wildcard, a scheme, a path or a single-label name is not a name this service will serve.'
+                  : 'Nothing was saved. The stored list is unchanged.'}
+          </p>
+        </div>
+      )}
+
+      {/* Said next to the control that does it, not in a doc nobody opens. */}
+      <div className="flex flex-col gap-2">
+        <p className="text-xs text-amber-400/90" data-testid="hostnames-replace-warning">
+          Saving REPLACES the whole list. Whatever is shown above becomes the
+          complete set of hostnames for <strong>{project}</strong>, and any name
+          not listed here is removed.
+        </p>
+        <SaveButton saving={saving} disabled={!canSave} />
+      </div>
+
+      {/* TLS, stated on the page because a user who adds a hostname and walks
+          away has done half the job. */}
+      <div className="rounded-md border border-slate-700 bg-slate-800/40 px-4 py-3">
+        <h3 className="text-sm font-medium text-slate-200">TLS certificates</h3>
+        <p className="text-xs text-slate-400 mt-1" data-testid="hostnames-tls">
+          Certificates are not configured here and are not issued from this
+          screen: an external ACME client writes them into a directory the
+          server watches, and the server picks one per hostname by SNI. A
+          hostname with no certificate gets a REFUSED handshake rather than the
+          wrong certificate, so adding a name below is only half the job - a
+          certificate covering it has to exist before a browser can reach it.
+        </p>
+      </div>
+    </form>
+  )
+}

+ 128 - 1
webui/src/types/index.ts

@@ -75,7 +75,21 @@ export interface GlobalStats {
   insert_count: number; query_count: number;
   memory_pressure_level: string; memory_pressure_percent: number; projects: number;
 }
-export interface FindResult { documents: Record<string, unknown>[]; count: number }
+export interface FindResult {
+  documents: Record<string, unknown>[]
+  /// The size of THIS page. Unchanged in meaning, which is why `has_more` and
+  /// `total` were added beside it rather than redefining it in place.
+  count: number
+  /// Whether another page follows. Emitted unconditionally by the documents
+  /// listing - unfiltered, empty, and on the last page - so an absent field
+  /// means exactly one thing: a server older than the release that added it.
+  /// Absent must therefore fall back to a heuristic rather than be read as
+  /// "there is no more".
+  has_more?: boolean
+  /// The exact number of rows matching the filters, computed by the server
+  /// BEFORE pagination. Not an estimate and not a page count.
+  total?: number
+}
 export interface SettingsView {
   openai_api_base: string
   openai_api_key_set: boolean
@@ -344,3 +358,116 @@ export interface ProjectStaticSettings {
   /// Sent verbatim on every served file.
   cache_control: string
 }
+
+/// PUT /settings/hostnames. The body REPLACES the whole list: a partial list
+/// silently drops the rest, which is why every caller here reads first, edits
+/// the array it read, and sends the whole thing back.
+export interface ProjectHostnamesPatch {
+  hostnames: ProjectHostname[]
+}
+
+/// One stored file, as the files routes report it. Never the database id.
+export interface ProjectFile {
+  name: string
+  content_type: string
+  size: number
+  checksum: string
+  /// Seconds since the epoch, like every other timestamp this API returns.
+  created_at: number
+  /// Always present, empty object included, so its absence means exactly one
+  /// thing - a server older than the release that added it. `path` is the only
+  /// key this UI reads: it is the alias the file is served at when static
+  /// serving is on, and a file without one is private.
+  metadata: Record<string, string>
+}
+
+/// GET /files. `has_more` and `total` are emitted unconditionally, so a full
+/// page and the last page are distinguishable - they used to be identical.
+export interface ProjectFilesView {
+  files: ProjectFile[]
+  has_more: boolean
+  total: number
+}
+
+/// One secret, as every read route reports it. There is NO value field here
+/// and there never will be: no GET returns a value, by design. `set` is a flag
+/// of its own rather than implied by a masked string, so nothing in a client
+/// can be tempted to parse a placeholder as a credential.
+export interface ProjectSecretSummary {
+  name: string
+  set: boolean
+  created_at: number
+  updated_at: number
+}
+
+/// GET /secrets. The limits travel with the list so a UI can show them without
+/// hardcoding a copy that drifts from the server's.
+export interface ProjectSecretsView {
+  project: string
+  secrets: ProjectSecretSummary[]
+  count: number
+  max_secrets: number
+  max_value_bytes: number
+}
+
+// ─── Collection listing / index listing envelopes ─────────────────────────────
+
+/// GET /projects/{p}/collections.
+///
+/// `scope_filtered` is TRUE for every SCOPED key whether or not anything was
+/// actually withheld - it means "your view may be partial", never "something
+/// was hidden". The stronger reading would leak one bit about the existence of
+/// a collection outside the caller's scope, which is precisely what the
+/// listing's scope filter exists to prevent.
+///
+/// Optional because a server older than the release that added it omits the
+/// field, and an ABSENT flag is not a false one: on such a server an empty
+/// list genuinely cannot be told apart from an empty project, and a UI must
+/// say so rather than pick the reassuring reading.
+export interface CollectionsListResponse {
+  collections: CollectionMeta[]
+  scope_filtered?: boolean
+}
+
+/// A composite unique constraint. Named by a LIST of fields rather than by one
+/// field, and carrying no `distinct_values`/`entries`, because a composite
+/// backs no query - which is why the API reports these in their own array
+/// rather than as extra rows in `indexes`.
+export interface CompositeUniqueIndex {
+  fields: string[]
+  /// Always true; stated rather than implied so one key reads the same across
+  /// both halves of the response.
+  unique: boolean
+}
+
+/// GET /projects/{p}/collections/{c}/indexes.
+export interface IndexesResponse {
+  indexes: IndexDef[]
+  composite_unique?: CompositeUniqueIndex[]
+}
+
+// ─── Database document metadata ───────────────────────────────────────────────
+
+/// The keys the database ATTACHES to every document it hands back, and which
+/// this service STRIPS from every write body - `dbMetadataFields()` in
+/// `src/documents_util.hpp`.
+///
+/// SEVEN, not six: `_updated_by` belongs to the set and is the one most often
+/// dropped when the list is quoted from memory rather than read from the
+/// header.
+///
+/// They are not part of the stored body and cannot be written. A caller that
+/// posts one has it discarded server-side, so a UI that lets a user edit one
+/// is offering an action that silently does nothing - which is worse than
+/// refusing it, because the edit looks accepted.
+export const DB_METADATA_FIELDS = [
+  '_id',
+  '_version',
+  '_created_at',
+  '_updated_at',
+  '_created_by',
+  '_updated_by',
+  '_expires_at',
+] as const
+
+export type DbMetadataField = (typeof DB_METADATA_FIELDS)[number]