فهرست منبع

feat(webui): a Functions settings tab, and stop the filter builder lying

Two findings from the UI audit, worst first.

The documents filter builder offered `search` in an operator dropdown
sitting between a field-name input and a value input, with no helper
text anywhere. That layout asserts a field scope the operator does not
have: `search` is a case-insensitive substring over the WHOLE document,
including the id and the keys. A user who picked a field and `search`
got matches from fields they never named - the same misreading that was
live in a consumer's product, where a keyword fallback matched a chat id
and a category instead of the text field it named.

The field input is now DISABLED for it rather than merely annotated,
because a control that cannot affect the result should not look like it
can. The hint points at `regex`, which is the field-scoped substring.
`contains` gets its own hint too, since array membership is just as easy
to read as a substring.

And a project's function settings had no UI at all: no tab, no client
method. Both the per-kind wall caps (since 0.6.0) and `network_egress`
(0.11.0) were reachable only by curl, and a control nobody can see is a
control nobody knows exists. That mattered most for egress - an operator
could not tell whether a project's functions were allowed outbound
access, let alone revoke it.

The new tab is admin-only, matching the route, which is requireAdmin
rather than requireProjectManage because these bound what one project
takes from a runner every other project shares. Egress renders THREE
states, since network_egress is the effective value while
network_egress_set says whether it was chosen or inherited - "allow
(inherited)" is a different statement from "allow, set here". An empty
wall-cap means NO project cap rather than a cap of zero, so it is held
as a string to keep an empty input and a zero distinguishable all the
way to the request.

Also types the search response's scan_capped/scanned/scan_cap/
filter_mode even though the UI offers no filters on a vector search yet,
so a silently short result is visible to whoever adds them rather than
discovered afterwards.

Three things learned the hard way and recorded: `npx tsc --noEmit` is
NOT the build check - it passed a malformed import that `npm run build`
rejected; SaveButton IS a submit button and must not be nested in
another; and the toast store takes (msg, kind) positionally.

npm run build passes.
fszontagh 1 ماه پیش
والد
کامیت
5571dd312c
6فایلهای تغییر یافته به همراه261 افزوده شده و 4 حذف شده
  1. 4 1
      CLAUDE.md
  2. 22 1
      webui/src/api/client.ts
  3. 39 2
      webui/src/pages/Documents.tsx
  4. 9 0
      webui/src/pages/Settings.tsx
  5. 164 0
      webui/src/pages/settings/ProjectFunctionsTab.tsx
  6. 23 0
      webui/src/types/index.ts

+ 4 - 1
CLAUDE.md

@@ -37,7 +37,10 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - `src/` - the server. `vectorapi_core` static lib + `main.cpp`. Namespace `svapi`. Flat headers, quoted includes.
   - `db_gateway` (`qualify(project,coll)` + `DbGateway` over `smartbotic::database::Client`), `settings_store` (global settings **and per-project embedding overrides**, hot-reload, one subscribe stream for both), `project_settings` (`ProjectEmbeddingSettings` + the pure `resolveEmbedding()`), `outbound_http` (User-Agent + TLS defaults for every external call), `key_store` (API keys, hot-reload, bootstrap admin key), `collection_registry` (per-project metadata), `embeddings` (OpenAI), `auth` (sessions, bearer/cookie), `server` (ApiServer + auth helpers), `handlers/*` (one file per route group).
   - Auth model: pre-routing **authenticates** `/api/*` (401); each handler **authorizes** via `requireKey` → `requireAdmin` / `requireProjectAccess` (403). Keys are referenced by a stable **`id`** (not the secret).
-- `webui/` - React 19 + Vite + TS (strict, `erasableSyntaxOnly`) + Tailwind + Monaco. `pages/Functions.tsx` holds `fn`/`tab` in the URL (a draft is `?new=1` and carries no source, so it is deliberately not shareable); `components/ScopeRules.tsx` is the `rules`/`ops` editor shared by key scopes and function policies, with `allowEmpty` for the latter because an empty function policy is legal. `require_human_token` is hidden for function policies: it is a captcha header check in `requireCapability`, and a function is authorized through `requireCapabilityCore`, which never sees an HTTP request - offering it would store a field that silently does nothing. Cookie-session auth (`credentials:'include'`). Pages read `currentProject`/`admin` from `useAuthStore`; all calls go through `src/api/client.ts`. **Documents keeps `collection`, the filter triple (`field`/`op`/`value`) and `open` in the URL**, so relation links are ordinary links and any filtered view is shareable; changing collection closes an open editor (it belongs to the collection being left). `pages/Settings.tsx` is a tab shell over `pages/settings/*` (Embeddings, Cache & performance, Access & security, Web UI are admin-only; the per-project embeddings tab is not, so `/settings` is **not** admin-gated in `App.tsx`). Shared controls live in `components/form.tsx`.
+- `webui/` - React 19 + Vite + TS (strict, `erasableSyntaxOnly`) + Tailwind + Monaco. **`npx tsc --noEmit` is NOT the build check** - it passed on a malformed import that `npm run build` (`tsc -b && vite build`) rejected, because the project build uses different settings. Verify a UI change with `npm run build`.
+  - **A `Functions` settings tab exists and is ADMIN-ONLY**, matching its route (`requireAdmin`, not `requireProjectManage`): it bounds what one project may take from a runner every other project shares. It carries the per-kind wall caps and `network_egress`, both of which were previously reachable only by curl - and a control nobody can see is a control nobody knows exists, which mattered most for egress, where an operator could not tell whether a project's functions had outbound access. Egress renders THREE states, because `network_egress` is the effective value and `network_egress_set` says whether it was chosen or inherited: "allow (inherited)" is a different statement from "allow, set here". An empty wall-cap field means NO project cap, which is not a cap of zero, so it is held as a string to keep an empty input and a zero distinguishable all the way to the request.
+  - **The documents filter builder DISABLES the field input for `search`**, rather than annotating it. `search` ignores the field - it is a case-insensitive substring over the whole document, id and keys included - and the three inputs read as field/op/value, which asserts a scope it does not have. A control that cannot affect the result must not look like it can. The hint points at `regex` for a field-scoped substring, and `contains` gets its own hint because array membership is equally easy to misread as a substring.
+  - `SaveButton` IS a `<button type="submit">`, so it belongs inside a `<form onSubmit>` and must not be wrapped in another button. The toast store's `push` takes `(msg, kind)` positionally, not an options object. `pages/Functions.tsx` holds `fn`/`tab` in the URL (a draft is `?new=1` and carries no source, so it is deliberately not shareable); `components/ScopeRules.tsx` is the `rules`/`ops` editor shared by key scopes and function policies, with `allowEmpty` for the latter because an empty function policy is legal. `require_human_token` is hidden for function policies: it is a captcha header check in `requireCapability`, and a function is authorized through `requireCapabilityCore`, which never sees an HTTP request - offering it would store a field that silently does nothing. Cookie-session auth (`credentials:'include'`). Pages read `currentProject`/`admin` from `useAuthStore`; all calls go through `src/api/client.ts`. **Documents keeps `collection`, the filter triple (`field`/`op`/`value`) and `open` in the URL**, so relation links are ordinary links and any filtered view is shareable; changing collection closes an open editor (it belongs to the collection being left). `pages/Settings.tsx` is a tab shell over `pages/settings/*` (Embeddings, Cache & performance, Access & security, Web UI are admin-only; the per-project embeddings tab is not, so `/settings` is **not** admin-gated in `App.tsx`). Shared controls live in `components/form.tsx`.
 - `runner/` - the **function runner service**, a second binary (`smartbotic-vectorapi-runner`). **Four** layers split by what they must link, which is also what decides where each can be tested: `runner_core` (QuickJS engine + pool, no database), `runner_protocol` (`/run`, `/validate`, `/health` as JSON in / JSON out, no transport and no database - which is why its 30 tests run on the dev host), `runner_net` (libcurl + the IMAP/MIME parsers + the mail budget + the error map; links neither `vectorapi_core` nor the database client, so its ~200 tests run on the dev host too), `runner_host` (the `ctx.*` surface; links `vectorapi_core` AND `runner_net`). `src/main.cpp` is the only part that links the world and the only part the dev host cannot build. The QuickJS execution core (`runner_core`). **Builds as its own top-level project** (`cmake -S runner -B build-runner`), which is the one part of this repo that compiles on the Void dev host, since it links neither `vectorapi_core` nor the database client. `BUILD_RUNNER=ON` wires it into the root build; it is **OFF by default** because it vendors QuickJS from GitHub at configure time and an ordinary build must not start depending on a network fetch.
 - `api/` - `openapi.json` (3.1), `llms.txt` (llmstxt.org), `docs/` (Redoc page). Served at `/openapi.json`, `/llms.txt`, `/docs`. Shipped in the server `.deb`. **Keep these in sync when changing routes.**
 - `packaging/` - `build.sh` (`--local` + Docker trixie), `deb/create-debs.sh`, control templates, systemd unit, maintainer scripts. `docs/superpowers/` - design spec (esp. **Addendum A**) + the 3 implementation plans.

+ 22 - 1
webui/src/api/client.ts

@@ -6,6 +6,7 @@ import type {
   RelationDefinition, DeleteImpact,
   FunctionSummary,
   FunctionsListResponse, FunctionDetail, FunctionRun, InvokeEnvelope, InvokeRequest,
+  ProjectFunctionSettings, ProjectFunctionSettingsPatch,
 } from '@/types'
 import { ApiError } from '@/types'
 import { serverUrl } from '@/api/base'
@@ -97,13 +98,33 @@ export const api = {
   storeVector: (project: string, coll: string, body: { id?: string; text?: string; vector?: number[]; metadata?: Record<string, unknown> }) =>
     request<{ id: string }>(`${P(project)}/collections/${enc(coll)}/vectors`, { method: 'POST', body: JSON.stringify(body) }),
   search: (project: string, coll: string, body: { query_text?: string; query_vector?: number[]; top_k?: number; min_score?: number }) =>
-    request<{ results: SearchResult[] }>(`${P(project)}/collections/${enc(coll)}/search`, { method: 'POST', body: JSON.stringify(body) }),
+    // The completeness metadata is typed even though the UI offers no filters
+    // on a vector search yet, so `scan_capped` cannot currently be true here.
+    // Typing it now means that if filters are ever added, a silently short
+    // result is visible to whoever adds them rather than discovered later.
+    // `filter_mode` distinguishes "uncapped by construction" (server) from
+    // "complete this time" (walk) - the boolean alone cannot.
+    request<{
+      results: SearchResult[]
+      scan_capped: boolean
+      scanned: number
+      scan_cap?: number
+      filter_mode: 'server' | 'walk' | 'none'
+    }>(`${P(project)}/collections/${enc(coll)}/search`, { method: 'POST', body: JSON.stringify(body) }),
 
   // stats
   projectStats: (project: string) => request<ProjectStats>(`${P(project)}/stats`),
   globalStats: () => request<GlobalStats>('/api/v1/stats'),
 
   // settings (admin)
+  getProjectFunctionSettings: (project: string) =>
+    request<ProjectFunctionSettings>(`${P(project)}/settings/functions`),
+  updateProjectFunctionSettings: (project: string, patch: ProjectFunctionSettingsPatch) =>
+    request<ProjectFunctionSettings>(`${P(project)}/settings/functions`, {
+      method: 'PUT',
+      body: JSON.stringify(patch),
+    }),
+
   getProjectEmbeddings: (project: string) =>
     request<ProjectEmbeddingsView>(`${P(project)}/settings/embeddings`),
   updateProjectEmbeddings: (project: string, patch: ProjectEmbeddingsPatch) =>

+ 39 - 2
webui/src/pages/Documents.tsx

@@ -22,6 +22,22 @@ type FilterOp = 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte' | 'in' | 'contains' |
 
 const FILTER_OPS: FilterOp[] = ['eq', 'ne', 'gt', 'gte', 'lt', 'lte', 'in', 'contains', 'exists', 'regex', 'search']
 
+// `search` IGNORES the field name: it is a case-insensitive substring over the
+// whole document, including the id and the keys. The three inputs below read as
+// field / op / value, which asserts a scope this operator does not have - a
+// user picking a field and `search` gets matches from fields they never named.
+// The same misreading was live in a consumer's product, matching a chat id
+// where it meant to match a text field.
+//
+// So the field input is DISABLED for it rather than merely annotated: a control
+// that cannot affect the result should not look like it can. `regex` is the
+// field-scoped substring and the hint points there.
+const FIELDLESS_OPS: FilterOp[] = ['search']
+
+function ignoresField(op: FilterOp): boolean {
+  return FIELDLESS_OPS.includes(op)
+}
+
 // ─── Helpers ──────────────────────────────────────────────────────────────────
 
 function compactPreview(doc: Record<string, unknown>): string {
@@ -133,14 +149,21 @@ function FilterBar({
   const inputClass =
     'rounded-md bg-slate-800 border border-slate-600 text-slate-200 text-sm px-3 py-1.5 placeholder-slate-500 focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500/40'
 
+  const fieldIgnored = ignoresField(filterOp)
+
   return (
+    <div className="flex flex-col gap-1.5">
     <div className="flex flex-wrap items-center gap-2">
       <input
         type="text"
-        placeholder="field"
+        placeholder={fieldIgnored ? 'not used' : 'field'}
         value={filterField}
         onChange={(e) => onFieldChange(e.target.value)}
-        className={`${inputClass} w-28`}
+        disabled={fieldIgnored}
+        title={fieldIgnored
+          ? `the '${filterOp}' operator ignores the field name`
+          : undefined}
+        className={`${inputClass} w-28 ${fieldIgnored ? 'opacity-40 cursor-not-allowed' : ''}`}
         data-testid="filter-field"
       />
       <select
@@ -187,6 +210,20 @@ function FilterBar({
         Search
       </button>
     </div>
+    {fieldIgnored && (
+      <p className="text-xs text-amber-400/90" data-testid="filter-op-hint">
+        <strong>search</strong> ignores the field name: it matches a
+        case-insensitive substring anywhere in the document, including its id and
+        its keys. For a substring within one field use <strong>regex</strong>.
+      </p>
+    )}
+    {filterOp === 'contains' && (
+      <p className="text-xs text-slate-400" data-testid="filter-op-hint">
+        <strong>contains</strong> is array membership, not a substring: it matches
+        when the field is an array holding this value.
+      </p>
+    )}
+    </div>
   )
 }
 

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

@@ -7,6 +7,7 @@ import CacheTab from '@/pages/settings/CacheTab'
 import AccessTab from '@/pages/settings/AccessTab'
 import WebuiTab from '@/pages/settings/WebuiTab'
 import ProjectEmbeddingsTab from '@/pages/settings/ProjectEmbeddingsTab'
+import ProjectFunctionsTab from '@/pages/settings/ProjectFunctionsTab'
 
 interface TabDef {
   id: string
@@ -32,6 +33,14 @@ export default function Settings() {
       adminOnly: false,
       render: () => <ProjectEmbeddingsTab />,
     },
+    {
+      id: 'functions',
+      label: 'Functions',
+      // Admin-only, matching the route: these bound what one project may take
+      // from a runner every other project shares.
+      adminOnly: true,
+      render: () => <ProjectFunctionsTab />,
+    },
   ].filter((t) => admin || !t.adminOnly)
 
   const [active, setActive] = useState(tabs[0]?.id ?? 'project')

+ 164 - 0
webui/src/pages/settings/ProjectFunctionsTab.tsx

@@ -0,0 +1,164 @@
+import { useEffect, useState } from 'react'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+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 { ProjectFunctionSettingsPatch } from '@/types'
+
+/// A project's function limits and its network egress.
+///
+/// ADMIN ONLY, matching the route, which is requireAdmin rather than
+/// requireProjectManage: these constrain what one tenant may take from a
+/// runner every other project shares, so the party they constrain must not be
+/// the party who sets them.
+///
+/// Until this existed both settings were reachable only by curl - a control
+/// nobody can see is a control nobody knows exists, and that was especially
+/// true of the egress switch, where an operator could not tell whether a
+/// project's functions were allowed outbound access at all.
+
+/// `''` means "no project cap", which is NOT a cap of zero: the runner's own
+/// ceiling for that kind applies instead. Kept as a string so an empty input
+/// and a zero stay distinguishable all the way to the request.
+function capToInput(ms: number | null): string {
+  return ms === null ? '' : String(ms)
+}
+
+export default function ProjectFunctionsTab() {
+  const admin = useAuthStore((s) => s.admin)
+  const project = useAuthStore((s) => s.currentProject)
+  const toast = useToastStore((s) => s.push)
+  const qc = useQueryClient()
+
+  const { data, isLoading, error } = useQuery({
+    queryKey: ['project-function-settings', project],
+    queryFn: () => api.getProjectFunctionSettings(project!),
+    enabled: admin && !!project,
+  })
+
+  const [http, setHttp] = useState('')
+  const [job, setJob] = useState('')
+  // Three states, not two. `network_egress` is the EFFECTIVE value and is
+  // never null, while `network_egress_set` says whether it was chosen here or
+  // inherited - and "allow (inherited)" is a different statement from
+  // "allow (set for this project)".
+  const [egress, setEgress] = useState<'inherit' | 'allow' | 'deny'>('inherit')
+  const [saving, setSaving] = useState(false)
+
+  useEffect(() => {
+    if (!data) return
+    setHttp(capToInput(data.max_wall_time_ms.http))
+    setJob(capToInput(data.max_wall_time_ms.job))
+    setEgress(data.network_egress_set ? data.network_egress : 'inherit')
+  }, [data])
+
+  if (!admin) {
+    return (
+      <p className="text-sm text-slate-400">
+        These settings are admin-only: they bound what one project may take from
+        a runner shared with every other project.
+      </p>
+    )
+  }
+  if (!project) return <p className="text-sm text-slate-400">Select a project first.</p>
+  if (isLoading) return <p className="text-sm text-slate-400">Loading…</p>
+  if (error) return <p className="text-sm text-rose-400">{String(error)}</p>
+
+  async function onSubmit(e: React.FormEvent) {
+    e.preventDefault()
+    if (!project) return
+    const patch: ProjectFunctionSettingsPatch = {
+      max_wall_time_ms: {
+        // An empty field means "clear the cap", which the route spells as null.
+        http: http.trim() === '' ? null : Number(http),
+        job: job.trim() === '' ? null : Number(job),
+      },
+      network_egress: egress === 'inherit' ? null : egress,
+    }
+    setSaving(true)
+    try {
+      await api.updateProjectFunctionSettings(project, patch)
+      await qc.invalidateQueries({ queryKey: ['project-function-settings', project] })
+      toast('Function settings saved', 'success')
+    } catch (e) {
+      toast(e instanceof ApiError ? e.message : String(e), 'error')
+    } finally {
+      setSaving(false)
+    }
+  }
+
+  const effective = data?.network_egress ?? 'allow'
+  const inherited = data ? !data.network_egress_set : true
+
+  return (
+    <form onSubmit={onSubmit} className="flex flex-col gap-5 max-w-2xl">
+      <FormRow
+        label="Network egress"
+        hint="Whether this project's functions may make outbound calls at all. Covers BOTH ctx.fetch and ctx.mail - a project denied the network is denied both, refused before any name is resolved, so a denied project does not even emit a DNS query."
+        badge={inherited ? <Badge>inherited</Badge> : <Badge tone="indigo">set here</Badge>}
+      >
+        <div className="flex items-center gap-3">
+          <select
+            value={egress}
+            onChange={(e) => setEgress(e.target.value as 'inherit' | 'allow' | 'deny')}
+            className={inputCls}
+            data-testid="egress-select"
+          >
+            <option value="inherit">inherit (allow)</option>
+            <option value="allow">allow</option>
+            <option value="deny">deny</option>
+          </select>
+          <span className="text-xs text-slate-400">
+            effective: <strong className={effective === 'deny' ? 'text-rose-400' : 'text-slate-200'}>{effective}</strong>
+          </span>
+        </div>
+      </FormRow>
+
+      {egress === 'deny' && (
+        <p className="text-xs text-amber-400/90" data-testid="egress-warning">
+          Every outbound call from this project's functions will be refused with
+          <code className="mx-1">egress_blocked</code>, including mail. Functions
+          that fetch or send will fail, not degrade.
+        </p>
+      )}
+
+      <FormRow
+        label="Max wall time, HTTP runs"
+        hint="Milliseconds. Empty means no project cap, which is not the same as zero - the runner's own ceiling for HTTP runs applies instead. Narrowing only: this cannot raise a ceiling."
+      >
+        <input
+          type="number"
+          min={1}
+          value={http}
+          placeholder="no project cap"
+          onChange={(e) => setHttp(e.target.value)}
+          className={`${inputCls} w-40`}
+          data-testid="wall-http"
+        />
+      </FormRow>
+
+      <FormRow
+        label="Max wall time, JOB runs"
+        hint="Milliseconds. Separate from the HTTP cap on purpose: one number could not express 'short for routes, long for cron', so capping a project's routes used to cut its cron work too."
+      >
+        <input
+          type="number"
+          min={1}
+          value={job}
+          placeholder="no project cap"
+          onChange={(e) => setJob(e.target.value)}
+          className={`${inputCls} w-40`}
+          data-testid="wall-job"
+        />
+      </FormRow>
+
+      {/* SaveButton IS the button, with type="submit" - wrapping it in another
+          button nests one inside the other and only works by accident. */}
+      <div className="flex items-center gap-3">
+        <SaveButton saving={saving} />
+      </div>
+    </form>
+  )
+}

+ 23 - 0
webui/src/types/index.ts

@@ -65,6 +65,29 @@ export interface EmbeddingTier {
   openai_api_key_set: boolean
 }
 
+/// A project's FUNCTION settings. Admin-only, and distinct from the embedding
+/// overrides: the route is requireAdmin rather than requireProjectManage,
+/// because these constrain what one tenant can take from a shared runner.
+export interface ProjectFunctionSettings {
+  /// The per-kind wall-time cap, in milliseconds. `null` for a kind means no
+  /// project cap, which is NOT the same as a cap of zero - the runner's own
+  /// ceiling for that kind applies instead.
+  max_wall_time_ms: { http: number | null; job: number | null }
+  /// The EFFECTIVE value, never null: "allow" or "deny".
+  network_egress: 'allow' | 'deny'
+  /// Whether that value was chosen for this project or inherited from the
+  /// default. The pair is what lets this render as three states rather than
+  /// two - "allow (inherited)" is a different statement from "allow (set)".
+  network_egress_set: boolean
+}
+
+/// A partial update. An absent key leaves that setting alone; an explicit null
+/// clears it back to inherited. That asymmetry is the route's, not ours.
+export interface ProjectFunctionSettingsPatch {
+  max_wall_time_ms?: { http?: number | null; job?: number | null }
+  network_egress?: 'allow' | 'deny' | null
+}
+
 export interface ProjectEmbeddingsView {
   effective: EmbeddingTier
   inherited: EmbeddingTier