소스 검색

feat(webui): manage functions from the admin UI, and document authoring

A Functions page: list, Monaco source editor, admin-only policy editor,
enable toggle, invoke, and run logs. The backend shipped without any of
this, so until now functions were reachable only by hand.

The error states carry the weight. 503 no_runner explains the thing an
operator hits first - installing the runner does not enable functions,
the server needs functions.runners in its config - rather than showing a
generic failure, and says plainly that nothing was stored. 422
compile_failed renders against the editor, which is the author's main
feedback loop. 422 id_mismatch explains that the id lives in the script,
not the URL.

The push client type has no policy field at all, so the UI structurally
cannot imply a policy was saved by a code push.

require_human_token is hidden for function policies: it is a captcha
header check in requireCapability, while a function is authorized through
requireCapabilityCore in the runner, which never sees an HTTP request.
Offering it would store a field that looks like a security control and is
not. A non-admin sees the policy read-only rather than not at all,
because the policy is why their function gets a 403.

The scope editor is extracted from KeysAdmin and shared, with allowEmpty
for function policies.

llms.txt documented how to MANAGE functions but never how to write one -
no `on` block, no ctx surface, no return-shape rule - so an LLM reading
it could not have written a function for this API. Now documented, with
each builder terminal's actual return type, ctx.fetch being SSRF-guarded,
ctx.env's per-project scoping, and the envelope-vs-body rule. Also states
that the stored descriptor.method is an ARRAY and is omitted entirely
when a function accepts any method, which the singular source form hid.

Verified: npm run build clean, and the page driven through a mock of the
documented contract. Nothing involving a real runner was exercised -
there is no function-capable backend on the dev host.

Bumps VERSION to 0.4.0 - a new subsystem, a second binary and a third
package, not a patch.

openapi.json also gains /fn/{project}/{path}, the public dispatch route,
which was documented in NEITHER openapi.json nor llms.txt: each of the
agents that owned one file assumed the other covered it. A cross-check
over every svr.Get/Post/Put/Patch/Delete registration now confirms every
function route appears in openapi. The only undocumented paths left are
the pre-existing meta endpoints and the SPA's own /ui/* session routes.

417/417 in the Debian 13 container with BUILD_RUNNER=ON.
fszontagh 1 개월 전
부모
커밋
79f9d0f57f

+ 1 - 1
CLAUDE.md

@@ -31,7 +31,7 @@ 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. 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. `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`). Three 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_host` (the `ctx.*` surface; links `vectorapi_core`). `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.

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.3.3
+0.4.0

+ 40 - 0
api/llms.txt

@@ -147,6 +147,37 @@ Precedence for one embedding call: the collection's own `embedding_model` wins,
 
 Server-side JavaScript that serves HTTP routes. These routes require a key granted the project (admin keys reach every project); capability-scoped publishable keys are refused. **Changing a function's policy is admin-only** - developers push code, admins grant what it may touch, exactly as keys already work.
 
+### Writing a function
+
+A function is an ES module exporting a trigger declaration and a default handler:
+
+```js
+export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic', method: 'GET' };
+
+export default async function (ctx) {
+  const docs = await ctx.collections('kb_chunks')
+      .filter(`topic:eq:${ctx.params.topic}`).limit(20).find();
+  const hits = await ctx.collections('kb_chunks')
+      .search({ query_text: ctx.query.q, top_k: 5, filters: ['lang:eq:hu'] });
+  ctx.log('found', docs.length, 'documents');
+  return { status: 200, body: { docs, hits } };
+}
+```
+
+`on` fields: `id` (required), `type` (`http`, default), `route` (required for http), `method` (a string or an array of strings; **absent means every method**), `timeoutMs` (clamped to the runner's ceiling), `singleFlight`. The STORED `descriptor` always reports `method` as an **array**, and omits it entirely when the function accepts any method - a client rendering it must not assume the singular form the source uses.
+
+`ctx` carries the trigger: `method`, `path`, `params` (the `:name` captures), `query`, `headers`, `body`. Repeated query keys collapse to the last value.
+
+- `ctx.collections(name)` - a chainable builder. `.filter('field:op:value')`, `.limit(n)`, `.offset(n)`, `.sort('field')` or `.sort('-field')` for descending, then a terminal: `.find()` returns an **array**, `.get(id)` returns the document or **null**, `.insert(doc)` returns `{id}`, `.update(id, doc)` returns `{id}`, `.patch(id, fields)` returns `{id, version}`, `.delete(id)` returns `{deleted}`. Filters use the same `field:op:value` grammar as `?filter=`, parsed by the same code and evaluated by the database, so a filter means the same thing here as over HTTP.
+- Vector collections additionally take `.search({query_text|query_vector, top_k, min_score, filters})`, returning an **array** of hits, and `.store({text|vector, metadata})`. Embedding resolves through the normal precedence, so a project's provider override applies.
+- `ctx.fetch(url, {method, headers, body})` - outbound HTTP, **SSRF-guarded**: loopback, private and link-local destinations are refused, which means a function cannot call this API back. The refusal is reported in the run's console rather than as a network error.
+- `ctx.env.<NAME>` - secrets for THIS project only, from the runner's environment (`SVAPI_FN_<project>__<NAME>` in `runner.env`). Never another project's, and never the runner's own configuration.
+- `ctx.log(...)` - captured into the run's `console`, bounded.
+
+**A denied collection access throws a catchable error** naming the collection and the operation, rather than returning an empty result - so a missing grant looks like a failure, not like missing data.
+
+**The return value shapes the response.** An object whose keys are a non-empty subset of `{status, headers, body}` is a response envelope; any other object is sent as a `200` body; an object MIXING envelope keys with other keys **fails the run** rather than being guessed at. Host calls are synchronous, so `await` is optional - it works because awaiting a non-promise is a no-op.
+
 **The id lives in the source, not in the URL.** A script exports `export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic', method: 'GET' }`, and that `id` is the registry row's identity. `path` records where the author keeps the file and carries no meaning, so moving `kb-search.js` to `lib/search.js` keeps the same row - and the policy an admin granted travels with it.
 
 **Every write is compiled on a runner before it is stored.** The engine that validates is the engine that will execute. A compile failure is **422** `compile_failed` with the error; an `on` block with no id is **422** `missing_function_id`; no healthy runner is **503** `no_runner` and nothing is stored. Code is never stored unvalidated.
@@ -163,6 +194,15 @@ Server-side JavaScript that serves HTTP routes. These routes require a key grant
 - `POST /api/v1/projects/{project}/functions/{id}/invoke` `{method?, path?, params?, query?, headers?, body?}` - Run the function once and record the run. Every field is optional: an empty body invokes it with its declared route as the path and `POST` as the method. Returns **200** whenever the run was *performed*, with `{run_id, ok, status, headers, body, console, duration_ms, error, timed_out, out_of_memory}` - the function's own failure is in that envelope, not in the HTTP status, so "the function returned 500" stays distinguishable from "the invoke could not be performed". A disabled or invalid function is **409**; a runner that cannot be reached is **503** `runner_unreachable`, and the failed attempt is still logged.
 - `GET  /api/v1/projects/{project}/functions/{id}/logs` - Recorded runs, newest first: `{function_id, runs:[{run_id, function_id, trigger, ok, status, duration_ms, error, console, started_at}]}`. `?limit=` defaults to 50. **The log keeps only the newest N runs per function** (trimmed on every write, since there is no scheduler yet), so a limit above N returns N and an old `run_id` eventually stops resolving.
 
+### Calling a function
+
+- `ANY /fn/{project}/{path}` - **Unauthenticated.** This is where a published function is served; it takes no API key, because a function's HTTP route is public by design. The project is the first path segment and the rest is matched against that project's `on` routes, so `/fn/acme/kb/hungary` reaches the `acme` function declaring `route: '/kb/:topic'` with `topic = "hungary"`.
+- The function chooses the response: its returned `status`, `headers` and `body` are sent as-is. Returning a plain object with none of those keys sends it as a `200` body, and an object mixing them with other keys **fails the run** rather than being guessed at.
+- A path matching no function is **404**; a path that matches but not for this method is **405** with an `Allow:` header. Disabled and invalid functions are simply absent, so they are **404** too - a public caller learns nothing about what a project contains.
+- A function that threw is **500**, a wall-time timeout is **504** `function_timeout`, exceeding the memory ceiling is **500** `function_out_of_memory`, and no healthy runner is **503** `runner_unavailable` with `Retry-After`. **The function's error text is never returned** - a stack trace on an open endpoint is an information leak. The response carries `error.details.run_id`, and the message is in `GET .../functions/{id}/logs`.
+- Request `Cookie`, `Authorization`, `Proxy-Authorization` and `X-Captcha-Token` headers are **not** forwarded to the function. The web UI is served from this same origin, so forwarding `Cookie` would hand a logged-in admin's session to every function author in the project.
+- Repeated query parameters collapse to the last value (`?tag=a&tag=b` gives `tag = "b"`), and `HEAD` is not routable.
+
 ## Stats
 
 - `GET /api/v1/projects/{project}/stats` - Per-project stats (collections, document counts). Accessible to any key granted the project.

+ 41 - 1
api/openapi.json

@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "info": {
     "title": "smartbotic-vectorapi",
-    "version": "0.3.3",
+    "version": "0.4.0",
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
   },
   "components": {
@@ -13,6 +13,38 @@
         "description": "API key issued by the /api/v1/keys endpoint. Pass as Authorization: Bearer <KEY>."
       }
     },
+    "pathItems": {
+      "FunctionDispatch": {
+        "get": {
+          "tags": ["Functions"],
+          "summary": "Invoke a published function",
+          "description": "Served without authentication. The function's returned status, headers and body are sent as-is; an object carrying none of those keys is sent as a 200 body. Cookie, Authorization, Proxy-Authorization and X-Captcha-Token are not forwarded to the function, because the web UI shares this origin and forwarding Cookie would hand an admin session to every function author in the project. Repeated query parameters collapse to the last value, and HEAD is not routable.",
+          "security": [],
+          "parameters": [
+            { "name": "project", "in": "path", "required": true, "schema": { "type": "string" },
+              "description": "Project owning the function. Must exist; charset is restricted to [A-Za-z0-9_-]." },
+            { "name": "path", "in": "path", "required": true, "schema": { "type": "string" },
+              "description": "The remainder of the path, matched against the project's declared routes. A '..' segment is refused." }
+          ],
+          "responses": {
+            "200": { "description": "Whatever the function returned. The status, headers and content type are the function's own.",
+                     "content": { "application/json": { "schema": {} } } },
+            "404": { "description": "No enabled, valid function matches this path. Disabled and invalid functions are absent from matching, so a public caller cannot tell them from a path that was never published.",
+                     "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
+            "405": { "description": "The path matches a function that does not declare this method. Carries an Allow header listing the methods every function on this path declares.",
+                     "headers": { "Allow": { "schema": { "type": "string" }, "description": "e.g. \"GET, PUT\"" } },
+                     "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
+            "500": { "description": "The function threw (code function_error), or exceeded its memory ceiling (function_out_of_memory). The function's error text is deliberately NOT included - a stack trace on an open endpoint is an information leak. error.details.run_id locates the full message in the function's run log.",
+                     "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
+            "503": { "description": "No healthy runner (code runner_unavailable). Transient; carries Retry-After.",
+                     "headers": { "Retry-After": { "schema": { "type": "string" } } },
+                     "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
+            "504": { "description": "The function exceeded its wall-time budget (code function_timeout).",
+                     "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
+          }
+        }
+      }
+    },
     "schemas": {
       "FunctionDescriptor": {
         "type": "object",
@@ -1617,6 +1649,14 @@
         }
       }
     },
+    "/fn/{project}/{path}": {
+      "description": "Public dispatch for a project's HTTP functions. Unauthenticated by design: a published function's route is public. The project is the first path segment; the remainder is matched against that project's declared routes.",
+      "get":    { "$ref": "#/components/pathItems/FunctionDispatch/get" },
+      "post":   { "$ref": "#/components/pathItems/FunctionDispatch/get" },
+      "put":    { "$ref": "#/components/pathItems/FunctionDispatch/get" },
+      "patch":  { "$ref": "#/components/pathItems/FunctionDispatch/get" },
+      "delete": { "$ref": "#/components/pathItems/FunctionDispatch/get" }
+    },
     "/api/v1/projects/{project}/functions": {
       "parameters": [
         {

+ 10 - 0
docs/superpowers/specs/2026-10-06-function-runtime-design.md

@@ -320,3 +320,13 @@ system user, so a sandbox escape inherits none of the server's credentials.
   it. Bounded damage over an unbounded host, but a shared-fate failure mode.
 - The runner unit has not been checked with `systemd-analyze verify`; Void has
   no systemd. Run it on the first Debian target.
+
+### Follow-ups left open at 0.4.0
+
+- **No way to ask whether a runner is configured or healthy.** `RunnerPool`
+  already has `statusJson()`, but nothing surfaces it, so the web UI can only
+  explain `no_runner` after a push has failed rather than warning before someone
+  writes a script. A read-only field on the functions list envelope would fix it.
+  Same for `functions.runs_kept`, which the UI currently hardcodes as 50.
+- A logged run carries no `headers`, while a fresh invoke envelope does, so a
+  client naturally trying to render both with one component cannot.

+ 5 - 0
webui/src/App.tsx

@@ -7,6 +7,7 @@ import { AppShell } from '@/components/AppShell'
 import Dashboard from '@/pages/Dashboard'
 import Collections from '@/pages/Collections'
 import Documents from '@/pages/Documents'
+import Functions from '@/pages/Functions'
 import RagTester from '@/pages/RagTester'
 import Settings from '@/pages/Settings'
 import ProjectsAdmin from '@/pages/ProjectsAdmin'
@@ -65,6 +66,10 @@ export const routes: RouteObject[] = [
           { path: 'collections', element: <Collections /> },
           { path: 'documents', element: <Documents /> },
           { path: 'rag', element: <RagTester /> },
+          // Not admin-gated: a project key manages that project's functions,
+          // 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 /> },
           // 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 /> },

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

@@ -4,6 +4,7 @@ import type {
   KeyScope, IndexDef, IndexValue, CreateIndexResult,
   ProjectEmbeddingsView, ProjectEmbeddingsPatch,
   RelationDefinition, DeleteImpact,
+  FunctionSummary, FunctionDetail, FunctionRun, InvokeEnvelope, InvokeRequest,
 } from '@/types'
 import { ApiError } from '@/types'
 import { serverUrl } from '@/api/base'
@@ -25,7 +26,7 @@ async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
   }
   const text = await res.text()
   const body = text ? JSON.parse(text) : {}
-  if (!res.ok) throw new ApiError(res.status, body?.error?.message || res.statusText, body?.error?.details)
+  if (!res.ok) throw new ApiError(res.status, body?.error?.message || res.statusText, body?.error?.details, body?.error?.code)
   return body as T
 }
 
@@ -130,6 +131,36 @@ export const api = {
     request<{ id: string }>(`${P(project)}/collections/${enc(collection)}/documents/${enc(id)}`,
       { method: 'PATCH', body: JSON.stringify(patch) }),
 
+  // functions
+  // The listing carries no `source`; the single-function GET does.
+  listFunctions: (project: string) =>
+    request<{ functions: FunctionSummary[] }>(`${P(project)}/functions`),
+  getFunction: (project: string, id: string) =>
+    request<FunctionDetail>(`${P(project)}/functions/${enc(id)}`),
+  // No id field on create: the id comes from the script's `on` block, which is
+  // why this is a POST to the collection and not a PUT to a chosen URL.
+  createFunction: (project: string, body: { source: string; path?: string }) =>
+    request<FunctionSummary>(`${P(project)}/functions`, { method: 'POST', body: JSON.stringify(body) }),
+  // A code push never carries a policy: the server ignores the field, so it is
+  // deliberately not sendable from here either.
+  putFunction: (project: string, id: string, body: { source: string; path?: string }) =>
+    request<FunctionSummary>(`${P(project)}/functions/${enc(id)}`, { method: 'PUT', body: JSON.stringify(body) }),
+  deleteFunction: (project: string, id: string) =>
+    request<{ deleted: string }>(`${P(project)}/functions/${enc(id)}`, { method: 'DELETE' }),
+  // Admin-only, and the only route that changes a policy.
+  setFunctionPolicy: (project: string, id: string, policy: KeyScope) =>
+    request<FunctionSummary>(`${P(project)}/functions/${enc(id)}/policy`,
+      { method: 'PUT', body: JSON.stringify({ policy }) }),
+  setFunctionEnabled: (project: string, id: string, enabled: boolean) =>
+    request<{ function_id: string; enabled: boolean }>(`${P(project)}/functions/${enc(id)}/enabled`,
+      { method: 'PUT', body: JSON.stringify({ enabled }) }),
+  invokeFunction: (project: string, id: string, body: InvokeRequest) =>
+    request<InvokeEnvelope>(`${P(project)}/functions/${enc(id)}/invoke`,
+      { method: 'POST', body: JSON.stringify(body) }),
+  functionLogs: (project: string, id: string, limit = 50) =>
+    request<{ function_id: string; runs: FunctionRun[] }>(
+      `${P(project)}/functions/${enc(id)}/logs?limit=${limit}`),
+
   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) }),

+ 2 - 0
webui/src/components/AppShell.tsx

@@ -5,6 +5,7 @@ import {
   Database,
   FileText,
   Search,
+  Code2,
   Settings,
   FolderKanban,
   KeyRound,
@@ -27,6 +28,7 @@ const mainNav: NavItem[] = [
   { 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} /> },

+ 203 - 0
webui/src/components/ScopeRules.tsx

@@ -0,0 +1,203 @@
+// The rules/ops vocabulary, shared by an API key's scope and a function's
+// policy. Extracted from KeysAdmin rather than copied: a function policy IS a
+// key scope server-side (one KeyScope, one enforcement path), so two editors
+// would drift the moment an op is added.
+//
+// The two callers differ in exactly two ways, both props:
+//   - a scoped key needs at least one rule, a function policy may be empty
+//     (empty means the function reaches nothing, which an admin must be able
+//     to restore);
+//   - `require_human_token` is an HTTP-only check (it looks for an
+//     X-Captcha-Token header), so it is meaningless on a function and hidden
+//     there instead of offered and ignored.
+
+import { Plus, Trash2 } from 'lucide-react'
+import type { KeyOp, KeyScopeRule } from '@/types'
+
+export const KEY_OPS: readonly KeyOp[] = ['read', 'list', 'search', 'insert', 'update', 'delete']
+
+export function emptyRule(): KeyScopeRule {
+  return { collection: '', ops: [], require_human_token: false }
+}
+
+/// `collection[ops,...]` for every usable rule, or '' when there are none.
+/// A rule with no collection or no ops is dropped: the server rejects it, and
+/// half-typed rows in the editor should not look like grants.
+export function rulesSummary(rules: KeyScopeRule[]): string {
+  return rules
+    .filter((r) => r.collection && r.ops.length > 0)
+    .map((r) => `${r.collection}[${r.ops.join(',')}]`)
+    .join(', ')
+}
+
+/// Drop the rows the server would reject, and normalise what is left.
+export function usableRules(rules: KeyScopeRule[], withHumanToken: boolean): KeyScopeRule[] {
+  return rules
+    .filter((r) => r.collection.trim() && r.ops.length > 0)
+    .map((r) => ({
+      collection: r.collection.trim(),
+      ops: r.ops,
+      require_human_token: withHumanToken ? (r.require_human_token ?? false) : false,
+    }))
+}
+
+const accents = {
+  teal: 'text-teal-300 hover:text-teal-200 bg-teal-700/20 hover:bg-teal-700/40 border-teal-700/30',
+  indigo: 'text-indigo-300 hover:text-indigo-200 bg-indigo-700/20 hover:bg-indigo-700/40 border-indigo-700/30',
+}
+
+interface ScopeRulesEditorProps {
+  rules: KeyScopeRule[]
+  onChange: (next: KeyScopeRule[]) => void
+  /// True when the rule list may be emptied (a function policy). False keeps
+  /// the last row, as a scoped key cannot be saved without one.
+  allowEmpty?: boolean
+  /// False for a function policy, which never sees a captcha header.
+  showHumanToken?: boolean
+  accent?: 'teal' | 'indigo'
+  label?: string
+  /// Shown under the rules when the list is empty.
+  emptyHint?: string
+}
+
+export function ScopeRulesEditor({
+  rules,
+  onChange,
+  allowEmpty = false,
+  showHumanToken = true,
+  accent = 'teal',
+  label = 'Collection rules',
+  emptyHint,
+}: ScopeRulesEditorProps) {
+  const updateRule = (idx: number, patch: Partial<KeyScopeRule>) =>
+    onChange(rules.map((r, i) => (i === idx ? { ...r, ...patch } : r)))
+
+  const toggleRuleOp = (idx: number, op: KeyOp) =>
+    onChange(
+      rules.map((r, i) => {
+        if (i !== idx) return r
+        const ops = r.ops.includes(op) ? r.ops.filter((o) => o !== op) : [...r.ops, op]
+        return { ...r, ops }
+      }),
+    )
+
+  const canRemove = allowEmpty || rules.length > 1
+
+  return (
+    <div>
+      <div className="flex items-center justify-between mb-2">
+        <label className="text-xs font-medium text-slate-400">
+          {label}
+          {!allowEmpty && <span className="text-red-400"> *</span>}
+        </label>
+        <button
+          type="button"
+          onClick={() => onChange([...rules, emptyRule()])}
+          className={`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium border transition ${accents[accent]}`}
+          data-testid="scope-add-rule"
+        >
+          <Plus size={11} />
+          Add rule
+        </button>
+      </div>
+
+      <div className="flex flex-col gap-3">
+        {rules.map((rule, idx) => (
+          <div
+            key={idx}
+            className="rounded-md border border-slate-700/40 bg-slate-800/50 px-3 py-3 flex flex-col gap-2"
+          >
+            <div className="flex items-center gap-2">
+              <input
+                type="text"
+                value={rule.collection}
+                onChange={(e) => updateRule(idx, { collection: e.target.value })}
+                placeholder="collection name"
+                className="flex-1 rounded-md bg-slate-900 border border-slate-600 text-slate-100 px-3 py-1.5 text-xs placeholder-slate-500 focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500/40"
+              />
+              {canRemove && (
+                <button
+                  type="button"
+                  onClick={() => onChange(rules.filter((_, i) => i !== idx))}
+                  className="inline-flex items-center px-2 py-1.5 rounded text-xs text-red-400 hover:text-red-300 hover:bg-red-500/10 transition"
+                  aria-label="Remove rule"
+                >
+                  <Trash2 size={13} />
+                </button>
+              )}
+            </div>
+            <div className="flex flex-wrap gap-2">
+              {KEY_OPS.map((op) => {
+                const active = rule.ops.includes(op)
+                return (
+                  <button
+                    key={op}
+                    type="button"
+                    onClick={() => toggleRuleOp(idx, op)}
+                    className={[
+                      'inline-flex items-center px-2 py-0.5 rounded text-xs font-mono border transition',
+                      active
+                        ? 'bg-indigo-600/30 border-indigo-500/50 text-indigo-300'
+                        : 'bg-slate-800 border-slate-600/40 text-slate-400 hover:border-slate-500 hover:text-slate-300',
+                    ].join(' ')}
+                  >
+                    {op}
+                  </button>
+                )
+              })}
+            </div>
+            {showHumanToken && (
+              <label className="flex items-center gap-2 cursor-pointer select-none w-fit">
+                <input
+                  type="checkbox"
+                  checked={rule.require_human_token ?? false}
+                  onChange={(e) => updateRule(idx, { require_human_token: e.target.checked })}
+                  className="w-3.5 h-3.5 rounded border-slate-600 bg-slate-800 accent-indigo-500"
+                />
+                <span className="text-xs text-slate-400">Require human token (CAPTCHA)</span>
+              </label>
+            )}
+          </div>
+        ))}
+      </div>
+
+      {rules.length === 0 && emptyHint && (
+        <p className="text-xs text-amber-300/80 mt-2">{emptyHint}</p>
+      )}
+    </div>
+  )
+}
+
+/// Read-only rendering of the same vocabulary, for a caller who may see a
+/// policy but not change it.
+export function ScopeRulesView({ rules }: { rules: KeyScopeRule[] }) {
+  if (rules.length === 0) {
+    return (
+      <p className="text-sm text-amber-300">
+        No rules: this function reaches no collection at all.
+      </p>
+    )
+  }
+  return (
+    <ul className="flex flex-col gap-2">
+      {rules.map((r, idx) => (
+        <li
+          key={idx}
+          className="flex flex-wrap items-center gap-2 rounded-md border border-slate-700/40 bg-slate-800/40 px-3 py-2"
+        >
+          <span className="font-mono text-xs text-slate-200">{r.collection}</span>
+          <span className="flex flex-wrap gap-1">
+            {r.ops.map((op) => (
+              <span
+                key={op}
+                className="inline-flex items-center px-1.5 py-0.5 rounded text-[11px] font-mono bg-indigo-600/20 border border-indigo-500/30 text-indigo-300"
+              >
+                {op}
+              </span>
+            ))}
+          </span>
+        </li>
+      ))}
+    </ul>
+  )
+}

+ 35 - 0
webui/src/components/SourceEditor.tsx

@@ -0,0 +1,35 @@
+import Editor from '@monaco-editor/react'
+
+interface SourceEditorProps {
+  value: string
+  onChange: (value: string) => void
+  height?: number
+  readOnly?: boolean
+}
+
+/// Monaco for a function's JavaScript source. The JSON sibling is JsonEditor;
+/// this one deliberately does not validate anything locally, because the only
+/// verdict that counts comes from the runner that will execute the code (a
+/// push is compiled there before it is stored).
+export function SourceEditor({ value, onChange, height = 420, readOnly = false }: SourceEditorProps) {
+  return (
+    <div className="rounded-md overflow-hidden border border-slate-700/60" style={{ height }}>
+      <Editor
+        height={height}
+        language="javascript"
+        theme="vs-dark"
+        value={value}
+        onChange={(v) => onChange(v ?? '')}
+        options={{
+          minimap: { enabled: false },
+          fontSize: 13,
+          lineNumbers: 'on',
+          scrollBeyondLastLine: false,
+          readOnly,
+          tabSize: 2,
+          automaticLayout: true,
+        }}
+      />
+    </div>
+  )
+}

+ 7 - 0
webui/src/monacoSetup.ts

@@ -1,11 +1,18 @@
 import * as monaco from 'monaco-editor'
 import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker'
 import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker'
+// The JavaScript editor on the Functions page is backed by monaco's TypeScript
+// worker (JS and TS share it). Without this mapping monaco hands a JS model the
+// plain editor worker, which does not speak the language protocol, so editing a
+// function's source throws from inside the worker. Bundled locally like the
+// others - the CDN loader is not an option offline.
+import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker'
 import { loader } from '@monaco-editor/react'
 
 self.MonacoEnvironment = {
   getWorker(_workerId: string, label: string): Worker {
     if (label === 'json') return new jsonWorker()
+    if (label === 'javascript' || label === 'typescript') return new tsWorker()
     return new editorWorker()
   },
 }

+ 1387 - 0
webui/src/pages/Functions.tsx

@@ -0,0 +1,1387 @@
+import { Fragment, useEffect, useRef, useState } from 'react'
+import { useSearchParams } from 'react-router-dom'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import {
+  Plus, RefreshCw, Trash2, Play, Copy, ShieldAlert, Globe, AlertTriangle,
+  CheckCircle2, XCircle, Code2,
+} from 'lucide-react'
+import { api } from '@/api/client'
+import { mountBase } from '@/api/base'
+import { useAuthStore } from '@/stores/authStore'
+import { useToastStore } from '@/stores/toastStore'
+import { ConfirmDialog } from '@/components/ConfirmDialog'
+import { JsonEditor } from '@/components/JsonEditor'
+import { SourceEditor } from '@/components/SourceEditor'
+import { ScopeRulesEditor, ScopeRulesView, usableRules } from '@/components/ScopeRules'
+import { Toggle, inputCls } from '@/components/form'
+import { ApiError } from '@/types'
+import type {
+  FunctionSummary, FunctionDetail, FunctionDescriptor, FunctionRun,
+  InvokeEnvelope, InvokeRequest, KeyScope, KeyScopeRule,
+} from '@/types'
+
+// ─── helpers ──────────────────────────────────────────────────────────────────
+
+function formatDate(epoch: number): string {
+  if (!epoch) return '-'
+  return new Date(epoch * 1000).toLocaleString(undefined, {
+    year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit',
+  })
+}
+
+/// An absent `method` list means EVERY method, which is the opposite of what an
+/// empty cell suggests - so it is spelled out.
+function methodsLabel(d: FunctionDescriptor): string {
+  const m = d.method ?? []
+  return m.length > 0 ? m.join(' ') : 'any method'
+}
+
+function routeLabel(d: FunctionDescriptor): string {
+  if (d.type === 'http') return d.route || '(no route)'
+  if (d.type === 'cron') return `cron ${d.schedule ?? ''}`.trim()
+  return `${d.table ?? ''} ${d.event ?? ''}`.trim()
+}
+
+/// Where the public dispatcher serves this function. Built on mountBase() for
+/// the same reason every other URL is: behind a subpath proxy the prefix is
+/// stripped before the server sees the request, so only the browser knows it.
+function publicUrl(project: string, d: FunctionDescriptor): string {
+  return `${location.origin}${mountBase()}/fn/${encodeURIComponent(project)}${d.route ?? ''}`
+}
+
+function detailField(details: unknown, key: string): string {
+  if (details && typeof details === 'object' && !Array.isArray(details)) {
+    const v = (details as Record<string, unknown>)[key]
+    if (typeof v === 'string') return v
+  }
+  return ''
+}
+
+function errMessage(err: unknown): string {
+  return err instanceof ApiError || err instanceof Error ? err.message : String(err)
+}
+
+const STARTER_SOURCE = `// The id lives in the source, never in the URL or the file name: it is the
+// registry row's identity, so the policy an admin grants travels with the code.
+export const on = {
+  id: 'hello',
+  type: 'http',
+  route: '/hello',
+  method: 'GET',
+}
+
+export default async function (ctx) {
+  ctx.log('called with', ctx.query)
+  return { status: 200, body: { ok: true, greeted: ctx.query.name || 'world' } }
+}
+`
+
+const INVOKE_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']
+
+// ─── error panels ─────────────────────────────────────────────────────────────
+
+function ErrorPanel({
+  tone = 'red',
+  title,
+  children,
+}: {
+  tone?: 'red' | 'amber'
+  title: string
+  children?: React.ReactNode
+}) {
+  const tones = {
+    red: 'border-red-500/30 bg-red-500/5',
+    amber: 'border-amber-500/30 bg-amber-500/5',
+  }
+  const titles = { red: 'text-red-300', amber: 'text-amber-300' }
+  return (
+    <div className={`rounded-xl border px-4 py-3 ${tones[tone]}`} data-testid="fn-error-panel">
+      <p className={`text-sm font-medium ${titles[tone]}`}>{title}</p>
+      {children && <div className="mt-2 text-xs text-slate-300 flex flex-col gap-2">{children}</div>}
+    </div>
+  )
+}
+
+/// Why a push or an invoke failed, in the terms the operator has to act in.
+///
+/// The slugs are not interchangeable: `no_runner` is a server configuration
+/// problem and nothing was stored, `compile_failed` is the author's own code,
+/// `id_mismatch` is a misunderstanding about where the id lives. One generic
+/// red toast for all three is what sends an operator to the wrong file.
+function PushErrorPanel({
+  err,
+  onOpenExisting,
+}: {
+  err: ApiError
+  onOpenExisting?: (id: string) => void
+}) {
+  if (err.code === 'no_runner') {
+    return (
+      <ErrorPanel title="No function runner is available - nothing was stored.">
+        <p>
+          Installing the runner package does not switch functions on. The server has to be told
+          where the runners are: add a <code className="text-slate-200">functions.runners</code>{' '}
+          list to its <code className="text-slate-200">config.json</code> and restart it.
+        </p>
+        <pre className="rounded-md bg-slate-950 border border-slate-700/60 px-3 py-2 overflow-x-auto text-[11px] text-slate-300">
+{`"functions": {
+  "runners": ["127.0.0.1:9100"],
+  "runs_kept": 50
+}`}
+        </pre>
+        <p>
+          If runners are already configured, then none of them is answering the health check.
+          Check that the runner service is up and that its token matches the server's
+          (<code className="text-slate-200">SVAPI_RUNNER_TOKEN</code>).
+        </p>
+        <p className="text-slate-400">
+          The server said: <span className="font-mono">{err.message}</span>
+        </p>
+      </ErrorPanel>
+    )
+  }
+
+  if (err.code === 'runner_unreachable') {
+    return (
+      <ErrorPanel title="The runner could not be reached - nothing was stored.">
+        <p>
+          A runner is configured but did not give a usable answer. Code is never stored
+          unvalidated, so this push did not change anything.
+        </p>
+        <p className="text-slate-400 font-mono">{err.message}</p>
+      </ErrorPanel>
+    )
+  }
+
+  if (err.code === 'compile_failed') {
+    return (
+      <ErrorPanel title="The function did not compile - nothing was stored.">
+        <pre className="rounded-md bg-slate-950 border border-red-500/20 px-3 py-2 overflow-x-auto text-[11px] text-red-300 whitespace-pre-wrap">
+          {err.message}
+        </pre>
+        <p className="text-slate-400">
+          Compiled on a runner, by the same engine that would execute it.
+        </p>
+      </ErrorPanel>
+    )
+  }
+
+  if (err.code === 'missing_function_id') {
+    return (
+      <ErrorPanel title="The script declares no id.">
+        <p>
+          The exported <code className="text-slate-200">on</code> block needs an{' '}
+          <code className="text-slate-200">id</code>. The file path is never used as a fallback,
+          because the path is where you keep the file and the id is what the policy is attached to.
+        </p>
+      </ErrorPanel>
+    )
+  }
+
+  if (err.code === 'id_mismatch') {
+    const declared = detailField(err.details, 'declared')
+    const url = detailField(err.details, 'url')
+    return (
+      <ErrorPanel title="The script's id does not match the function you are editing.">
+        <p>
+          This script declares{' '}
+          <span className="font-mono text-slate-200">{declared || '(unknown)'}</span>, but you are
+          pushing to <span className="font-mono text-slate-200">{url || '(unknown)'}</span>. The id
+          lives in the source, not in the URL, so this is not a rename: saving it here would move
+          your code onto another function's policy.
+        </p>
+        <p>
+          Either put the id back, or create{' '}
+          <span className="font-mono text-slate-200">{declared || 'the new id'}</span> as a new
+          function.
+        </p>
+      </ErrorPanel>
+    )
+  }
+
+  if (err.code === 'function_exists') {
+    const existing = detailField(err.details, 'function_id')
+    return (
+      <ErrorPanel tone="amber" title="That id is already registered.">
+        <p>
+          A function with this id exists already, so creating it would overwrite someone else's
+          code. Open it and push to it instead - that keeps its policy and its enabled state.
+        </p>
+        {existing && onOpenExisting && (
+          <button
+            type="button"
+            onClick={() => onOpenExisting(existing)}
+            className="self-start inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium text-white bg-indigo-600 hover:bg-indigo-500 transition"
+          >
+            Open {existing}
+          </button>
+        )}
+      </ErrorPanel>
+    )
+  }
+
+  if (err.code === 'function_disabled' || err.code === 'function_invalid') {
+    return (
+      <ErrorPanel tone="amber" title="This function cannot run right now.">
+        <p>{err.message}</p>
+        <p>
+          Enable it, or push a version that compiles. The registry row and its policy are kept
+          either way.
+        </p>
+      </ErrorPanel>
+    )
+  }
+
+  return <ErrorPanel title={`Request failed (${err.status}).`}><p>{err.message}</p></ErrorPanel>
+}
+
+// ─── list ─────────────────────────────────────────────────────────────────────
+
+function StateBadges({ fn }: { fn: FunctionSummary }) {
+  return (
+    <div className="flex flex-wrap items-center gap-1">
+      <span
+        className={[
+          'inline-block px-2 py-0.5 rounded text-xs font-medium border',
+          fn.enabled
+            ? 'bg-emerald-500/15 text-emerald-300 border-emerald-500/30'
+            : 'bg-slate-600/30 text-slate-400 border-slate-600/30',
+        ].join(' ')}
+      >
+        {fn.enabled ? 'enabled' : 'disabled'}
+      </span>
+      {!fn.valid && (
+        <span className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-red-500/15 text-red-300 border border-red-500/30">
+          invalid
+        </span>
+      )}
+      {fn.policy.rules.length === 0 && (
+        <span
+          className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-amber-500/15 text-amber-300 border border-amber-500/30"
+          title="Empty policy: the function runs but reaches no collection."
+        >
+          no data access
+        </span>
+      )}
+    </div>
+  )
+}
+
+function FunctionsTable({
+  functions,
+  selected,
+  onSelect,
+}: {
+  functions: FunctionSummary[]
+  selected: string
+  onSelect: (id: string) => void
+}) {
+  if (functions.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 functions in this project yet.</p>
+      </div>
+    )
+  }
+
+  return (
+    <div className="rounded-xl border border-slate-700/40 overflow-x-auto">
+      <table className="w-full text-sm">
+        <thead>
+          <tr className="border-b border-slate-700/40 bg-slate-800/60">
+            {['Function', 'Trigger', 'Methods', 'State', 'Last error', 'Updated'].map((h) => (
+              <th
+                key={h}
+                className="text-left px-4 py-3 text-xs font-semibold text-slate-400 uppercase tracking-wider"
+              >
+                {h}
+              </th>
+            ))}
+          </tr>
+        </thead>
+        <tbody>
+          {functions.map((fn, idx) => (
+            <tr
+              key={fn.function_id}
+              onClick={() => onSelect(fn.function_id)}
+              className={[
+                'border-b border-slate-700/20 cursor-pointer transition hover:bg-indigo-500/5',
+                fn.function_id === selected ? 'bg-indigo-500/10' : idx % 2 === 0 ? 'bg-slate-900/30' : 'bg-slate-800/20',
+              ].join(' ')}
+              data-testid="fn-row"
+            >
+              <td className="px-4 py-3">
+                <div className="font-mono text-slate-200 text-xs">{fn.function_id}</div>
+                {fn.path && <div className="font-mono text-slate-500 text-[11px]">{fn.path}</div>}
+              </td>
+              <td className="px-4 py-3 font-mono text-slate-300 text-xs">
+                <span className="text-slate-500">{fn.descriptor.type}</span> {routeLabel(fn.descriptor)}
+              </td>
+              <td className="px-4 py-3 font-mono text-slate-400 text-xs">{methodsLabel(fn.descriptor)}</td>
+              <td className="px-4 py-3"><StateBadges fn={fn} /></td>
+              <td className="px-4 py-3 text-xs text-red-400/80 max-w-xs truncate" title={fn.last_error}>
+                {fn.last_error || <span className="text-slate-600">-</span>}
+              </td>
+              <td className="px-4 py-3 text-slate-400 text-xs whitespace-nowrap">{formatDate(fn.updated_at)}</td>
+            </tr>
+          ))}
+        </tbody>
+      </table>
+    </div>
+  )
+}
+
+// ─── public URL ───────────────────────────────────────────────────────────────
+
+function PublicUrlPanel({ project, fn }: { project: string; fn: FunctionSummary }) {
+  const push = useToastStore((s) => s.push)
+  if (fn.descriptor.type !== 'http') return null
+  const url = publicUrl(project, fn.descriptor)
+
+  const copy = async () => {
+    try {
+      await navigator.clipboard.writeText(url)
+      push('Public URL copied to clipboard.', 'success')
+    } catch {
+      push('Copy failed - clipboard unavailable.', 'error')
+    }
+  }
+
+  return (
+    <div className="rounded-xl border border-amber-500/25 bg-amber-500/5 px-4 py-3 flex flex-col gap-2">
+      <div className="flex items-center gap-2">
+        <Globe size={14} className="text-amber-300" />
+        <span className="text-sm font-medium text-amber-300">Public, unauthenticated URL</span>
+      </div>
+      <div className="flex items-center gap-2">
+        <input
+          readOnly
+          value={url}
+          onClick={(e) => (e.target as HTMLInputElement).select()}
+          className="flex-1 rounded-md bg-slate-950 border border-slate-600 text-slate-200 font-mono text-xs px-3 py-2 focus:outline-none focus:border-indigo-500"
+          data-testid="fn-public-url"
+        />
+        <button
+          onClick={() => void copy()}
+          className="inline-flex items-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium bg-slate-700 hover:bg-slate-600 text-slate-200 transition shrink-0"
+          aria-label="Copy public URL"
+        >
+          <Copy size={14} />
+          Copy
+        </button>
+      </div>
+      <p className="text-xs text-slate-300">
+        Anyone who can reach this server can call this URL: <span className="font-mono">/fn/*</span>{' '}
+        carries no API key and no session. The only gates are this function being enabled and
+        valid, plus whatever the code itself checks. Accepts {methodsLabel(fn.descriptor)}.
+      </p>
+    </div>
+  )
+}
+
+// ─── source tab ───────────────────────────────────────────────────────────────
+
+interface SourceTabProps {
+  project: string
+  /// Null while creating: there is no id to push to until the script declares
+  /// one and the server has accepted it.
+  existing: FunctionDetail | null
+  onSaved: (id: string) => void
+  onOpenExisting: (id: string) => void
+}
+
+function SourceTab({ project, existing, onSaved, onOpenExisting }: SourceTabProps) {
+  const push = useToastStore((s) => s.push)
+  const [source, setSource] = useState(existing?.source ?? STARTER_SOURCE)
+  const [path, setPath] = useState(existing?.path ?? '')
+  const [saving, setSaving] = useState(false)
+  const [pushError, setPushError] = useState<ApiError | null>(null)
+
+  // A different function (or a fresh draft) replaces the buffer outright: the
+  // source belongs to the row being left, exactly as the document editor drops
+  // a document when its collection changes.
+  const bufferKey = existing ? `${existing.function_id}:${existing.content_hash}` : 'new'
+  useEffect(() => {
+    setSource(existing?.source ?? STARTER_SOURCE)
+    setPath(existing?.path ?? '')
+    setPushError(null)
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, [bufferKey])
+
+  const dirty = source !== (existing?.source ?? STARTER_SOURCE) || path !== (existing?.path ?? '')
+
+  const save = async () => {
+    setSaving(true)
+    setPushError(null)
+    try {
+      const body = { source, path: path.trim() }
+      if (existing) {
+        await api.putFunction(project, existing.function_id, body)
+        push(`Pushed ${existing.function_id}. Its policy and enabled state are unchanged.`, 'success')
+        onSaved(existing.function_id)
+      } else {
+        const created = await api.createFunction(project, body)
+        push(`Registered ${created.function_id}.`, 'success')
+        onSaved(created.function_id)
+      }
+    } catch (err) {
+      if (err instanceof ApiError) setPushError(err)
+      else push(`Push failed: ${errMessage(err)}`, 'error')
+    } finally {
+      setSaving(false)
+    }
+  }
+
+  return (
+    <div className="flex flex-col gap-4">
+      <div className="flex flex-wrap items-end gap-3">
+        <div className="flex-1 min-w-60">
+          <label className="block text-xs font-medium text-slate-400 mb-1">
+            Path <span className="text-slate-500">(where you keep the file; carries no meaning)</span>
+          </label>
+          <input
+            type="text"
+            value={path}
+            onChange={(e) => setPath(e.target.value)}
+            placeholder="kb-search.js"
+            className={inputCls}
+            data-testid="fn-path"
+          />
+        </div>
+        <button
+          onClick={() => void save()}
+          disabled={saving || (!!existing && !dirty)}
+          className="inline-flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-500 transition disabled:opacity-50 disabled:cursor-not-allowed"
+          data-testid="fn-save-source"
+        >
+          {saving ? 'Compiling...' : existing ? 'Push code' : 'Register function'}
+        </button>
+      </div>
+
+      <SourceEditor value={source} onChange={setSource} height={440} />
+
+      {pushError && <PushErrorPanel err={pushError} onOpenExisting={onOpenExisting} />}
+
+      <p className="text-xs text-slate-500">
+        Every push is compiled on a runner before it is stored, by the engine that will execute it.
+        A push carries code only: the policy below and the enabled state are server state, so
+        pushing never changes them - and never re-enables a function someone turned off.
+      </p>
+    </div>
+  )
+}
+
+// ─── policy tab ───────────────────────────────────────────────────────────────
+
+function PolicyTab({
+  project,
+  fn,
+  admin,
+  onSaved,
+}: {
+  project: string
+  fn: FunctionSummary
+  admin: boolean
+  onSaved: () => void
+}) {
+  const pushToast = useToastStore((s) => s.push)
+  const [rules, setRules] = useState<KeyScopeRule[]>(fn.policy.rules)
+  const [origins, setOrigins] = useState(fn.policy.origins.join(', '))
+  const [rateLimit, setRateLimit] = useState(fn.policy.rate_limit_per_min)
+  const [expiresAt, setExpiresAt] = useState(fn.policy.expires_at)
+  const [saving, setSaving] = useState(false)
+  const [err, setErr] = useState<ApiError | null>(null)
+
+  useEffect(() => {
+    setRules(fn.policy.rules)
+    setOrigins(fn.policy.origins.join(', '))
+    setRateLimit(fn.policy.rate_limit_per_min)
+    setExpiresAt(fn.policy.expires_at)
+    setErr(null)
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, [fn.function_id, fn.updated_at])
+
+  // A caller who may not edit still needs to SEE the policy: it is the answer
+  // to "why does my function get a 403?", and that question is asked by the
+  // person who wrote the code, not by the admin who granted the access.
+  if (!admin) {
+    return (
+      <div className="flex flex-col gap-4">
+        <div className="rounded-xl border border-slate-700/40 bg-slate-800/30 px-4 py-3 flex items-start gap-2">
+          <ShieldAlert size={15} className="text-slate-400 mt-0.5 shrink-0" />
+          <p className="text-xs text-slate-400">
+            Read-only: only an admin key can change a function's policy. Developers push code,
+            admins grant what it may touch - the same split API keys have. If this function gets a
+            403 from <span className="font-mono">ctx.collections(...)</span>, this list is why.
+          </p>
+        </div>
+        <ScopeRulesView rules={fn.policy.rules} />
+        <PolicyLimitsView policy={fn.policy} />
+      </div>
+    )
+  }
+
+  const save = async () => {
+    setSaving(true)
+    setErr(null)
+    try {
+      const policy: KeyScope = {
+        // require_human_token is dropped: it is an HTTP-header check and a
+        // function never presents one, so storing it would be decoration.
+        rules: usableRules(rules, false),
+        origins: origins.split(',').map((o) => o.trim()).filter((o) => o.length > 0),
+        rate_limit_per_min: rateLimit,
+        expires_at: expiresAt,
+      }
+      await api.setFunctionPolicy(project, fn.function_id, policy)
+      pushToast(
+        policy.rules.length === 0
+          ? `Policy replaced: ${fn.function_id} now reaches no collection.`
+          : `Policy replaced for ${fn.function_id}.`,
+        'success',
+      )
+      onSaved()
+    } catch (e) {
+      if (e instanceof ApiError) setErr(e)
+      else pushToast(`Could not save the policy: ${errMessage(e)}`, 'error')
+    } finally {
+      setSaving(false)
+    }
+  }
+
+  return (
+    <div className="flex flex-col gap-4">
+      <p className="text-xs text-slate-400">
+        Replaces the whole policy. Rules that name no collection or no operation are dropped - the
+        server rejects them. An <span className="text-amber-300">empty rule set is legal</span> and
+        means the function reaches nothing: it still runs, logs and calls out, but touches no
+        collection.
+      </p>
+
+      <ScopeRulesEditor
+        rules={rules}
+        onChange={setRules}
+        allowEmpty
+        showHumanToken={false}
+        accent="indigo"
+        label="Collection rules"
+        emptyHint="Saving with no rules grants no data access at all. That is a valid policy, not an unfinished one."
+      />
+
+      <div>
+        <label className="block text-xs font-medium text-slate-400 mb-1">
+          Allowed origins <span className="text-slate-500">(comma-separated; empty = any)</span>
+        </label>
+        <input
+          type="text"
+          value={origins}
+          onChange={(e) => setOrigins(e.target.value)}
+          placeholder="https://app.example.com"
+          className={inputCls}
+        />
+      </div>
+
+      <div className="flex flex-wrap gap-3">
+        <div className="flex-1 min-w-40">
+          <label className="block text-xs font-medium text-slate-400 mb-1">
+            Rate limit / min <span className="text-slate-500">(0 = unlimited)</span>
+          </label>
+          <input
+            type="number"
+            min={0}
+            step={1}
+            value={rateLimit}
+            onChange={(e) => setRateLimit(Math.max(0, Math.floor(Number(e.target.value) || 0)))}
+            className={inputCls}
+          />
+        </div>
+        <div className="flex-1 min-w-40">
+          <label className="block text-xs font-medium text-slate-400 mb-1">
+            Expires at <span className="text-slate-500">(epoch seconds; 0 = never)</span>
+          </label>
+          <input
+            type="number"
+            min={0}
+            step={1}
+            value={expiresAt}
+            onChange={(e) => setExpiresAt(Math.max(0, Math.floor(Number(e.target.value) || 0)))}
+            className={inputCls}
+          />
+        </div>
+      </div>
+
+      {err && <PushErrorPanel err={err} />}
+
+      <button
+        onClick={() => void save()}
+        disabled={saving}
+        className="self-start inline-flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-500 transition disabled:opacity-50"
+        data-testid="fn-save-policy"
+      >
+        {saving ? 'Saving...' : 'Replace policy'}
+      </button>
+    </div>
+  )
+}
+
+function PolicyLimitsView({ policy }: { policy: KeyScope }) {
+  return (
+    <dl className="grid grid-cols-[auto,1fr] gap-x-4 gap-y-1 text-xs">
+      <dt className="text-slate-500">Origins</dt>
+      <dd className="text-slate-300 font-mono">
+        {policy.origins.length > 0 ? policy.origins.join(', ') : 'any'}
+      </dd>
+      <dt className="text-slate-500">Rate limit</dt>
+      <dd className="text-slate-300 font-mono">
+        {policy.rate_limit_per_min > 0 ? `${policy.rate_limit_per_min}/min` : 'unlimited'}
+      </dd>
+      <dt className="text-slate-500">Expires</dt>
+      <dd className="text-slate-300 font-mono">
+        {policy.expires_at > 0 ? formatDate(policy.expires_at) : 'never'}
+      </dd>
+    </dl>
+  )
+}
+
+// ─── invoke tab ───────────────────────────────────────────────────────────────
+
+/// A JSON object field small enough to stay a textarea. Invalid JSON is the
+/// caller's own typo, so it is reported here and blocks the run rather than
+/// being sent as a string.
+function JsonObjectField({
+  label,
+  hint,
+  value,
+  onChange,
+}: {
+  label: string
+  hint: string
+  value: string
+  onChange: (v: string) => void
+}) {
+  const invalid = value.trim() !== '' && !parsesToObject(value)
+  return (
+    <div className="flex-1 min-w-52">
+      <label className="block text-xs font-medium text-slate-400 mb-1">
+        {label} <span className="text-slate-500">{hint}</span>
+      </label>
+      <textarea
+        value={value}
+        onChange={(e) => onChange(e.target.value)}
+        rows={3}
+        spellCheck={false}
+        className={`${inputCls} font-mono text-xs`}
+        placeholder="{}"
+      />
+      {invalid && <p className="text-xs text-red-400 mt-1">Not a JSON object.</p>}
+    </div>
+  )
+}
+
+function parsesToObject(text: string): boolean {
+  try {
+    const v: unknown = JSON.parse(text)
+    return !!v && typeof v === 'object' && !Array.isArray(v)
+  } catch {
+    return false
+  }
+}
+
+function parseObjectOrUndefined(text: string): Record<string, unknown> | undefined {
+  if (text.trim() === '') return undefined
+  try {
+    return JSON.parse(text) as Record<string, unknown>
+  } catch {
+    return undefined
+  }
+}
+
+function InvokeTab({ project, fn }: { project: string; fn: FunctionSummary }) {
+  const push = useToastStore((s) => s.push)
+  const queryClient = useQueryClient()
+  const [method, setMethod] = useState((fn.descriptor.method ?? [])[0] ?? 'POST')
+  const [path, setPath] = useState(fn.descriptor.route ?? '')
+  const [params, setParams] = useState('')
+  const [query, setQuery] = useState('')
+  const [headers, setHeaders] = useState('')
+  const [body, setBody] = useState('')
+  const [running, setRunning] = useState(false)
+  const [envelope, setEnvelope] = useState<InvokeEnvelope | null>(null)
+  const [err, setErr] = useState<ApiError | null>(null)
+
+  useEffect(() => {
+    setMethod((fn.descriptor.method ?? [])[0] ?? 'POST')
+    setPath(fn.descriptor.route ?? '')
+    setEnvelope(null)
+    setErr(null)
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, [fn.function_id])
+
+  const bodyInvalid = body.trim() !== '' && !parsesJson(body)
+  const blocked =
+    bodyInvalid ||
+    [params, query, headers].some((t) => t.trim() !== '' && !parsesToObject(t))
+
+  const run = async () => {
+    setRunning(true)
+    setErr(null)
+    try {
+      const req: InvokeRequest = { method, path }
+      const p = parseObjectOrUndefined(params)
+      const q = parseObjectOrUndefined(query)
+      const h = parseObjectOrUndefined(headers)
+      if (p) req.params = p
+      if (q) req.query = q
+      if (h) req.headers = h
+      if (body.trim() !== '') req.body = JSON.parse(body) as unknown
+      const env = await api.invokeFunction(project, fn.function_id, req)
+      setEnvelope(env)
+      // The run was recorded, so the log the Runs tab shows is now stale.
+      void queryClient.invalidateQueries({ queryKey: ['function-logs', project, fn.function_id] })
+    } catch (e) {
+      if (e instanceof ApiError) setErr(e)
+      else push(`Invoke failed: ${errMessage(e)}`, 'error')
+    } finally {
+      setRunning(false)
+    }
+  }
+
+  return (
+    <div className="flex flex-col gap-4">
+      <p className="text-xs text-slate-400">
+        Every field is optional. Left as they are, the function runs on its declared route. The
+        invoke is recorded in the run log either way.
+      </p>
+
+      <div className="flex flex-wrap items-end gap-3">
+        <div>
+          <label className="block text-xs font-medium text-slate-400 mb-1">Method</label>
+          <select
+            value={method}
+            onChange={(e) => setMethod(e.target.value)}
+            className="rounded-md bg-slate-800 border border-slate-600 text-slate-200 text-sm px-3 py-2 focus:outline-none focus:border-indigo-500"
+          >
+            {INVOKE_METHODS.map((m) => (
+              <option key={m} value={m}>{m}</option>
+            ))}
+          </select>
+        </div>
+        <div className="flex-1 min-w-60">
+          <label className="block text-xs font-medium text-slate-400 mb-1">
+            Path <span className="text-slate-500">(defaults to the declared route)</span>
+          </label>
+          <input
+            type="text"
+            value={path}
+            onChange={(e) => setPath(e.target.value)}
+            placeholder={fn.descriptor.route ?? '/'}
+            className={`${inputCls} font-mono text-xs`}
+          />
+        </div>
+      </div>
+
+      <div className="flex flex-wrap gap-3">
+        <JsonObjectField label="Params" hint="(the route's :name captures)" value={params} onChange={setParams} />
+        <JsonObjectField label="Query" hint="(?a=b)" value={query} onChange={setQuery} />
+        <JsonObjectField label="Headers" hint="(cookies are never forwarded)" value={headers} onChange={setHeaders} />
+      </div>
+
+      <div>
+        <label className="block text-xs font-medium text-slate-400 mb-1">
+          Body <span className="text-slate-500">(JSON; empty sends null)</span>
+        </label>
+        <JsonEditor value={body} onChange={setBody} height={150} />
+        {bodyInvalid && <p className="text-xs text-red-400 mt-1">Invalid JSON - fix before running.</p>}
+      </div>
+
+      <button
+        onClick={() => void run()}
+        disabled={running || blocked}
+        className="self-start inline-flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-500 transition disabled:opacity-50"
+        data-testid="fn-invoke"
+      >
+        <Play size={15} />
+        {running ? 'Running...' : 'Run once'}
+      </button>
+
+      {err && <PushErrorPanel err={err} />}
+      {envelope && <EnvelopeView env={envelope} />}
+    </div>
+  )
+}
+
+function parsesJson(text: string): boolean {
+  try {
+    JSON.parse(text)
+    return true
+  } catch {
+    return false
+  }
+}
+
+/// The whole envelope, and the distinction it exists for: the invoke succeeded
+/// whenever a run was performed, so a function answering 500 is reported here
+/// as a performed run that returned 500 - not as a failed request.
+function EnvelopeView({ env }: { env: InvokeEnvelope }) {
+  const Icon = env.ok ? CheckCircle2 : XCircle
+  return (
+    <div className="rounded-xl border border-slate-700/40 bg-slate-800/30 flex flex-col" data-testid="fn-envelope">
+      <div className="flex flex-wrap items-center gap-3 px-4 py-3 border-b border-slate-700/40">
+        <span className="inline-flex items-center gap-1.5 text-sm font-medium text-slate-200">
+          <Icon size={15} className={env.ok ? 'text-emerald-400' : 'text-red-400'} />
+          Run performed
+        </span>
+        <span
+          className={[
+            'inline-block px-2 py-0.5 rounded text-xs font-medium border',
+            env.ok
+              ? 'bg-emerald-500/15 text-emerald-300 border-emerald-500/30'
+              : 'bg-red-500/15 text-red-300 border-red-500/30',
+          ].join(' ')}
+        >
+          ok: {String(env.ok)}
+        </span>
+        <span className="inline-block px-2 py-0.5 rounded text-xs font-mono bg-slate-700/50 text-slate-300 border border-slate-600/40">
+          status {env.status}
+        </span>
+        <span className="text-xs text-slate-400 font-mono">{env.duration_ms} ms</span>
+        {env.timed_out && (
+          <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-amber-500/15 text-amber-300 border border-amber-500/30">
+            <AlertTriangle size={11} /> timed out
+          </span>
+        )}
+        {env.out_of_memory && (
+          <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-amber-500/15 text-amber-300 border border-amber-500/30">
+            <AlertTriangle size={11} /> out of memory
+          </span>
+        )}
+        <span className="text-xs text-slate-500 font-mono ml-auto">run {env.run_id.slice(0, 12)}...</span>
+      </div>
+
+      <div className="px-4 py-3 flex flex-col gap-3">
+        <p className="text-xs text-slate-500">
+          The invoke itself returned HTTP 200 because the run happened. The status above is the
+          function's own answer, so {env.status} here is a function result, not a failed request.
+        </p>
+
+        {env.error && (
+          <div>
+            <p className="text-xs font-medium text-slate-400 mb-1">Error</p>
+            <pre className="rounded-md bg-slate-950 border border-red-500/20 px-3 py-2 overflow-x-auto text-[11px] text-red-300 whitespace-pre-wrap">
+              {env.error}
+            </pre>
+          </div>
+        )}
+
+        <div>
+          <p className="text-xs font-medium text-slate-400 mb-1">Body</p>
+          <pre className="rounded-md bg-slate-950 border border-slate-700/60 px-3 py-2 overflow-x-auto max-h-72 text-[11px] text-slate-300">
+            {JSON.stringify(env.body ?? null, null, 2)}
+          </pre>
+        </div>
+
+        {Object.keys(env.headers ?? {}).length > 0 && (
+          <div>
+            <p className="text-xs font-medium text-slate-400 mb-1">Response headers</p>
+            <pre className="rounded-md bg-slate-950 border border-slate-700/60 px-3 py-2 overflow-x-auto text-[11px] text-slate-300">
+              {JSON.stringify(env.headers, null, 2)}
+            </pre>
+          </div>
+        )}
+
+        <ConsoleView lines={env.console} />
+      </div>
+    </div>
+  )
+}
+
+function ConsoleView({ lines }: { lines: string[] }) {
+  return (
+    <div>
+      <p className="text-xs font-medium text-slate-400 mb-1">Console</p>
+      {lines.length === 0 ? (
+        <p className="text-xs text-slate-500">The function logged nothing.</p>
+      ) : (
+        <pre className="rounded-md bg-slate-950 border border-slate-700/60 px-3 py-2 overflow-x-auto max-h-60 text-[11px] text-slate-300">
+          {lines.join('\n')}
+        </pre>
+      )}
+    </div>
+  )
+}
+
+// ─── runs tab ─────────────────────────────────────────────────────────────────
+
+function RunsTab({ project, fn }: { project: string; fn: FunctionSummary }) {
+  const [limit, setLimit] = useState(50)
+  const [open, setOpen] = useState('')
+
+  const { data, isLoading, isError, error, refetch, isFetching } = useQuery({
+    queryKey: ['function-logs', project, fn.function_id, limit],
+    queryFn: () => api.functionLogs(project, fn.function_id, limit),
+  })
+
+  const runs: FunctionRun[] = data?.runs ?? []
+
+  return (
+    <div className="flex flex-col gap-4">
+      <div className="flex flex-wrap items-end gap-3">
+        <div>
+          <label className="block text-xs font-medium text-slate-400 mb-1">Limit</label>
+          <input
+            type="number"
+            min={1}
+            value={limit}
+            onChange={(e) => setLimit(Math.max(1, Math.floor(Number(e.target.value) || 1)))}
+            className={`${inputCls} w-24`}
+          />
+        </div>
+        <button
+          onClick={() => void refetch()}
+          disabled={isFetching}
+          className="inline-flex items-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium text-slate-300 bg-slate-700/50 hover:bg-slate-700 transition disabled:opacity-50"
+        >
+          <RefreshCw size={15} className={isFetching ? 'animate-spin' : ''} />
+          Refresh
+        </button>
+      </div>
+
+      {/* The log is trimmed on every write, so "fewer rows than asked for" is
+          the normal state, not a loading glitch, and an old run_id is gone for
+          good rather than momentarily missing. */}
+      <p className="text-xs text-slate-500">
+        Newest first. Only the newest runs per function are kept (50 by default, set by the
+        server's <span className="font-mono">functions.runs_kept</span>), and the log is trimmed on
+        every write - so asking for more than that returns what is left, and a run_id from an older
+        run stops resolving altogether.
+      </p>
+
+      {isError && (
+        <ErrorPanel title="Could not load the run log.">
+          <p>{errMessage(error)}</p>
+        </ErrorPanel>
+      )}
+
+      {isLoading && (
+        <div className="rounded-xl border border-slate-700/40 bg-slate-800/30 px-6 py-8 text-center animate-pulse">
+          <p className="text-slate-400 text-sm">Loading runs...</p>
+        </div>
+      )}
+
+      {!isLoading && !isError && runs.length === 0 && (
+        <div className="rounded-xl border border-slate-700/40 bg-slate-800/30 px-6 py-8 text-center">
+          <p className="text-slate-400 text-sm">No runs kept for this function.</p>
+          <p className="text-slate-500 text-xs mt-1">
+            Either it has never run, or every run it had has been trimmed away.
+          </p>
+        </div>
+      )}
+
+      {runs.length > 0 && (
+        <div className="rounded-xl border border-slate-700/40 overflow-x-auto">
+          <table className="w-full text-sm">
+            <thead>
+              <tr className="border-b border-slate-700/40 bg-slate-800/60">
+                {['Started', 'Trigger', 'Result', 'Status', 'Duration', 'Error'].map((h) => (
+                  <th
+                    key={h}
+                    className="text-left px-4 py-3 text-xs font-semibold text-slate-400 uppercase tracking-wider"
+                  >
+                    {h}
+                  </th>
+                ))}
+              </tr>
+            </thead>
+            <tbody>
+              {runs.map((r, idx) => (
+                <Fragment key={r.run_id}>
+                  <tr
+                    onClick={() => setOpen(open === r.run_id ? '' : r.run_id)}
+                    className={[
+                      'border-b border-slate-700/20 cursor-pointer transition hover:bg-indigo-500/5',
+                      idx % 2 === 0 ? 'bg-slate-900/30' : 'bg-slate-800/20',
+                    ].join(' ')}
+                    data-testid="fn-run-row"
+                  >
+                    <td className="px-4 py-2.5 text-xs text-slate-300 whitespace-nowrap">
+                      {formatDate(r.started_at)}
+                    </td>
+                    <td className="px-4 py-2.5 text-xs font-mono text-slate-400">{r.trigger}</td>
+                    <td className="px-4 py-2.5">
+                      <span
+                        className={[
+                          'inline-block px-2 py-0.5 rounded text-xs font-medium border',
+                          r.ok
+                            ? 'bg-emerald-500/15 text-emerald-300 border-emerald-500/30'
+                            : 'bg-red-500/15 text-red-300 border-red-500/30',
+                        ].join(' ')}
+                      >
+                        {r.ok ? 'ok' : 'failed'}
+                      </span>
+                    </td>
+                    <td className="px-4 py-2.5 text-xs font-mono text-slate-300">{r.status}</td>
+                    <td className="px-4 py-2.5 text-xs font-mono text-slate-400">{r.duration_ms} ms</td>
+                    <td className="px-4 py-2.5 text-xs text-red-400/80 max-w-xs truncate" title={r.error}>
+                      {r.error || <span className="text-slate-600">-</span>}
+                    </td>
+                  </tr>
+                  {open === r.run_id && (
+                    <tr className="border-b border-slate-700/20 bg-slate-950/40">
+                      <td colSpan={6} className="px-4 py-3">
+                        <p className="text-[11px] text-slate-500 font-mono mb-2 break-all">run {r.run_id}</p>
+                        <ConsoleView lines={r.console} />
+                      </td>
+                    </tr>
+                  )}
+                </Fragment>
+              ))}
+            </tbody>
+          </table>
+        </div>
+      )}
+    </div>
+  )
+}
+
+// ─── detail ───────────────────────────────────────────────────────────────────
+
+type TabId = 'source' | 'policy' | 'invoke' | 'runs'
+
+function FunctionDetailPanel({
+  project,
+  summary,
+  detail,
+  detailLoading,
+  admin,
+  tab,
+  onTab,
+  onRefresh,
+  onDelete,
+  onOpenExisting,
+  onSaved,
+}: {
+  project: string
+  summary: FunctionSummary
+  detail: FunctionDetail | null
+  detailLoading: boolean
+  admin: boolean
+  tab: TabId
+  onTab: (t: TabId) => void
+  onRefresh: () => void
+  onDelete: () => void
+  onOpenExisting: (id: string) => void
+  onSaved: (id: string) => void
+}) {
+  const push = useToastStore((s) => s.push)
+  const [togglingEnabled, setTogglingEnabled] = useState(false)
+  const [confirmDelete, setConfirmDelete] = useState(false)
+
+  const setEnabled = async (next: boolean) => {
+    setTogglingEnabled(true)
+    try {
+      await api.setFunctionEnabled(project, summary.function_id, next)
+      push(`${summary.function_id} ${next ? 'enabled' : 'disabled'}.`, 'success')
+      onRefresh()
+    } catch (e) {
+      push(`Could not change the enabled state: ${errMessage(e)}`, 'error')
+    } finally {
+      setTogglingEnabled(false)
+    }
+  }
+
+  const tabs: { id: TabId; label: string }[] = [
+    { id: 'source', label: 'Source' },
+    { id: 'policy', label: admin ? 'Policy' : 'Policy (read-only)' },
+    { id: 'invoke', label: 'Invoke' },
+    { id: 'runs', label: 'Runs' },
+  ]
+
+  return (
+    <div className="flex flex-col gap-4 rounded-xl border border-slate-700/40 bg-slate-800/20 px-5 py-4">
+      <div className="flex flex-wrap items-start justify-between gap-3">
+        <div>
+          <h2 className="text-lg font-semibold text-slate-100 font-mono">{summary.function_id}</h2>
+          <p className="text-xs text-slate-500 mt-0.5 font-mono">
+            {summary.descriptor.type} {routeLabel(summary.descriptor)} · {methodsLabel(summary.descriptor)}
+            {summary.path && ` · ${summary.path}`}
+          </p>
+          <p className="text-xs text-slate-500 mt-0.5">
+            updated {formatDate(summary.updated_at)} · hash{' '}
+            <span className="font-mono">{summary.content_hash.slice(0, 12)}</span>
+          </p>
+        </div>
+        <div className="flex items-center gap-3">
+          <div className={togglingEnabled ? 'opacity-50 pointer-events-none' : ''}>
+            <Toggle checked={summary.enabled} onChange={(next) => void setEnabled(next)} />
+          </div>
+          <button
+            onClick={() => setConfirmDelete(true)}
+            className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium text-red-400 hover:text-red-300 hover:bg-red-500/10 transition"
+            data-testid="fn-delete"
+          >
+            <Trash2 size={13} />
+            Delete
+          </button>
+        </div>
+      </div>
+
+      {!summary.valid && (
+        <ErrorPanel title="The last push did not compile, so this function is marked invalid.">
+          <p className="font-mono text-slate-300">{summary.last_error || 'no error recorded'}</p>
+          <p>It keeps its row and its policy. Push a version that compiles to bring it back.</p>
+        </ErrorPanel>
+      )}
+
+      <PublicUrlPanel project={project} fn={summary} />
+
+      <div className="flex flex-wrap gap-1 border-b border-slate-700">
+        {tabs.map((t) => (
+          <button
+            key={t.id}
+            type="button"
+            onClick={() => onTab(t.id)}
+            className={[
+              'px-4 py-2 text-sm font-medium border-b-2 -mb-px transition',
+              t.id === tab ? 'border-indigo-500 text-slate-100' : 'border-transparent text-slate-400 hover:text-slate-200',
+            ].join(' ')}
+            data-testid={`fn-tab-${t.id}`}
+          >
+            {t.label}
+          </button>
+        ))}
+      </div>
+
+      {tab === 'source' &&
+        (detailLoading || !detail ? (
+          <p className="text-sm text-slate-400 animate-pulse">Loading source...</p>
+        ) : (
+          <SourceTab
+            project={project}
+            existing={detail}
+            onSaved={onSaved}
+            onOpenExisting={onOpenExisting}
+          />
+        ))}
+      {tab === 'policy' && (
+        <PolicyTab project={project} fn={summary} admin={admin} onSaved={onRefresh} />
+      )}
+      {tab === 'invoke' && <InvokeTab project={project} fn={summary} />}
+      {tab === 'runs' && <RunsTab project={project} fn={summary} />}
+
+      <ConfirmDialog
+        open={confirmDelete}
+        title="Delete function"
+        message={`Delete "${summary.function_id}"? Its code, its policy and its run log go with it, and its public URL stops answering.`}
+        confirmLabel="Delete"
+        onConfirm={onDelete}
+        onClose={() => setConfirmDelete(false)}
+      />
+    </div>
+  )
+}
+
+// ─── page ─────────────────────────────────────────────────────────────────────
+
+export default function Functions() {
+  const currentProject = useAuthStore((s) => s.currentProject)
+  const admin = useAuthStore((s) => s.admin)
+  const push = useToastStore((s) => s.push)
+  const queryClient = useQueryClient()
+
+  // Selection and tab live in the URL, so a function (and the tab someone was
+  // looking at) is a shareable link, exactly as a filtered Documents view is.
+  const [searchParams, setSearchParams] = useSearchParams()
+  const selectedId = searchParams.get('fn') ?? ''
+  const creating = searchParams.get('new') === '1'
+  const tab = (searchParams.get('tab') as TabId) || 'source'
+
+  const setParams = (patch: Record<string, string>) => {
+    setSearchParams((prev) => {
+      const next = new URLSearchParams(prev)
+      for (const [k, v] of Object.entries(patch)) {
+        if (v) next.set(k, v)
+        else next.delete(k)
+      }
+      return next
+    }, { replace: true })
+  }
+
+  const select = (id: string) => setParams({ fn: id, new: '', tab: tab })
+  const startNew = () => setParams({ fn: '', new: '1', tab: 'source' })
+  const clearSelection = () => setParams({ fn: '', new: '', tab: '' })
+
+  const { data, isLoading, isError, error, refetch, isFetching } = useQuery({
+    queryKey: ['functions', currentProject],
+    queryFn: () => api.listFunctions(currentProject!),
+    enabled: !!currentProject,
+  })
+
+  const functions = data?.functions ?? []
+  const summary = functions.find((f) => f.function_id === selectedId) ?? null
+
+  // The selected function belongs to the project being left, so switching
+  // project drops the selection instead of showing a stale editor. Keyed on an
+  // actual change, not on the first render: clearing on mount would empty the
+  // query string of a shared ?fn=...&tab=... link before it ever resolved.
+  const lastProject = useRef<string | null>(null)
+  useEffect(() => {
+    if (lastProject.current !== null && lastProject.current !== currentProject) clearSelection()
+    lastProject.current = currentProject
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, [currentProject])
+
+  // Only the single-function GET carries the source.
+  const { data: detail, isLoading: detailLoading } = useQuery({
+    queryKey: ['function', currentProject, selectedId],
+    queryFn: () => api.getFunction(currentProject!, selectedId),
+    enabled: !!currentProject && !!selectedId && !!summary,
+  })
+
+  const refresh = () => {
+    void queryClient.invalidateQueries({ queryKey: ['functions', currentProject] })
+    void queryClient.invalidateQueries({ queryKey: ['function', currentProject] })
+  }
+
+  const handleSaved = (id: string) => {
+    refresh()
+    if (id !== selectedId || creating) setParams({ fn: id, new: '', tab: 'source' })
+  }
+
+  const handleDelete = async () => {
+    if (!currentProject || !summary) return
+    try {
+      await api.deleteFunction(currentProject, summary.function_id)
+      push(`${summary.function_id} deleted.`, 'success')
+    } catch (e) {
+      // A 404 means it is already gone; the end state is the one asked for.
+      if (e instanceof ApiError && e.status === 404) {
+        push('That function was already removed; refreshed the list.', 'info')
+      } else {
+        push(`Delete failed: ${errMessage(e)}`, 'error')
+        return
+      }
+    }
+    clearSelection()
+    refresh()
+  }
+
+  if (!currentProject) {
+    return (
+      <div className="flex flex-col gap-8">
+        <div>
+          <h1 className="text-2xl font-semibold text-slate-100">Functions</h1>
+          <p className="text-slate-400 text-sm mt-1">Server-side JavaScript that serves HTTP routes.</p>
+        </div>
+        <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 project selected - choose a project from the selector above.
+          </p>
+        </div>
+      </div>
+    )
+  }
+
+  return (
+    <div className="flex flex-col gap-6">
+      <div className="flex items-center justify-between flex-wrap gap-3">
+        <div>
+          <h1 className="text-2xl font-semibold text-slate-100">Functions</h1>
+          <p className="text-slate-400 text-sm mt-1">
+            Project: <span className="text-slate-300 font-mono">{currentProject}</span>
+            {!isLoading && !isError && (
+              <span className="ml-2 text-slate-500">
+                ({functions.length} {functions.length === 1 ? 'function' : 'functions'})
+              </span>
+            )}
+          </p>
+        </div>
+        <div className="flex items-center gap-2">
+          <button
+            onClick={() => void refetch()}
+            disabled={isFetching}
+            className="inline-flex items-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium text-slate-300 bg-slate-700/50 hover:bg-slate-700 transition disabled:opacity-50"
+            title="Refresh functions"
+          >
+            <RefreshCw size={15} className={isFetching ? 'animate-spin' : ''} />
+            Refresh
+          </button>
+          <button
+            onClick={startNew}
+            className="flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-500 transition"
+            data-testid="new-fn-btn"
+          >
+            <Plus size={16} />
+            New function
+          </button>
+        </div>
+      </div>
+
+      {isError && (
+        <ErrorPanel title="Failed to load functions.">
+          <p>{errMessage(error)}</p>
+        </ErrorPanel>
+      )}
+
+      {isLoading && (
+        <div className="rounded-xl border border-slate-700/40 bg-slate-800/30 px-6 py-10 text-center animate-pulse">
+          <p className="text-slate-400 text-sm">Loading functions...</p>
+        </div>
+      )}
+
+      {!isLoading && !isError && (
+        <FunctionsTable functions={functions} selected={selectedId} onSelect={select} />
+      )}
+
+      {creating && (
+        <div className="flex flex-col gap-4 rounded-xl border border-indigo-500/30 bg-indigo-500/5 px-5 py-4">
+          <div className="flex items-center justify-between gap-3">
+            <div className="flex items-center gap-2">
+              <Code2 size={16} className="text-indigo-300" />
+              <h2 className="text-lg font-semibold text-slate-100">New function</h2>
+            </div>
+            <button
+              onClick={clearSelection}
+              className="px-3 py-1.5 rounded-md text-xs font-medium text-slate-300 bg-slate-700/50 hover:bg-slate-700 transition"
+            >
+              Discard
+            </button>
+          </div>
+          <p className="text-xs text-slate-400">
+            The id comes from the script's <span className="font-mono">on</span> block, so there is
+            nothing to name here. A first registration inherits the project's default policy, which
+            grants no collection at all: the function runs, logs and can call out, but reaches no
+            data until an admin grants it a rule.
+          </p>
+          <SourceTab
+            project={currentProject}
+            existing={null}
+            onSaved={handleSaved}
+            onOpenExisting={(id) => select(id)}
+          />
+        </div>
+      )}
+
+      {summary && !creating && (
+        <FunctionDetailPanel
+          project={currentProject}
+          summary={summary}
+          detail={detail ?? null}
+          detailLoading={detailLoading}
+          admin={admin}
+          tab={tab}
+          onTab={(t) => setParams({ tab: t })}
+          onRefresh={refresh}
+          onDelete={() => void handleDelete()}
+          onOpenExisting={(id) => select(id)}
+          onSaved={handleSaved}
+        />
+      )}
+
+      {selectedId && !summary && !isLoading && !creating && (
+        <ErrorPanel tone="amber" title={`No function named "${selectedId}" in this project.`}>
+          <p>It may have been deleted, or the link was made for another project.</p>
+        </ErrorPanel>
+      )}
+    </div>
+  )
+}

+ 5 - 108
webui/src/pages/KeysAdmin.tsx

@@ -5,8 +5,9 @@ import { api } from '@/api/client'
 import { useToastStore } from '@/stores/toastStore'
 import { Modal } from '@/components/Modal'
 import { ConfirmDialog } from '@/components/ConfirmDialog'
+import { ScopeRulesEditor, emptyRule, rulesSummary, usableRules } from '@/components/ScopeRules'
 import { ApiError } from '@/types'
-import type { ApiKeyPublic, ApiKeyCreated, KeyOp, KeyScopeRule, KeyScope } from '@/types'
+import type { ApiKeyPublic, ApiKeyCreated, KeyScopeRule, KeyScope } from '@/types'
 
 // ─── helpers ──────────────────────────────────────────────────────────────────
 
@@ -23,13 +24,8 @@ function formatDate(epoch: number): string {
 const inputCls =
   'w-full rounded-md bg-slate-800 border border-slate-600 text-slate-100 px-3 py-2 text-sm placeholder-slate-500 focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500/40'
 
-const KEY_OPS = ['read', 'list', 'search', 'insert', 'update', 'delete'] as const
-
 function scopeSummary(scope: KeyScope): string {
-  const rules = scope.rules
-    .filter((r) => r.collection && r.ops.length > 0)
-    .map((r) => `${r.collection}[${r.ops.join(',')}]`)
-    .join(', ')
+  const rules = rulesSummary(scope.rules)
   const rate = scope.rate_limit_per_min > 0 ? ` · ${scope.rate_limit_per_min}/min` : ''
   return `scoped: ${rules || '(no rules)'}${rate}`
 }
@@ -114,10 +110,6 @@ interface NewKeyFormProps {
   onCancel: () => void
 }
 
-function emptyRule(): KeyScopeRule {
-  return { collection: '', ops: [], require_human_token: false }
-}
-
 function NewKeyForm({ allProjects, onCreated, onCancel }: NewKeyFormProps) {
   const push = useToastStore((s) => s.push)
 
@@ -144,23 +136,6 @@ function NewKeyForm({ allProjects, onCreated, onCancel }: NewKeyFormProps) {
     setIsAdmin((v) => !v)
   }
 
-  const updateRule = (idx: number, patch: Partial<KeyScopeRule>) => {
-    setRules((prev) => prev.map((r, i) => (i === idx ? { ...r, ...patch } : r)))
-  }
-
-  const toggleRuleOp = (idx: number, op: KeyOp) => {
-    setRules((prev) =>
-      prev.map((r, i) => {
-        if (i !== idx) return r
-        const ops = r.ops.includes(op) ? r.ops.filter((o) => o !== op) : [...r.ops, op]
-        return { ...r, ops }
-      }),
-    )
-  }
-
-  const addRule = () => setRules((prev) => [...prev, emptyRule()])
-  const removeRule = (idx: number) => setRules((prev) => prev.filter((_, i) => i !== idx))
-
   const handleSubmit = async (e: React.FormEvent) => {
     e.preventDefault()
     if (!label.trim()) {
@@ -178,13 +153,7 @@ function NewKeyForm({ allProjects, onCreated, onCancel }: NewKeyFormProps) {
     try {
       let scope: KeyScope | undefined
       if (isScoped) {
-        const validRules = rules
-          .filter((r) => r.collection.trim() && r.ops.length > 0)
-          .map((r) => ({
-            collection: r.collection.trim(),
-            ops: r.ops,
-            require_human_token: r.require_human_token ?? false,
-          }))
+        const validRules = usableRules(rules, true)
         const originsArr = origins
           .split(',')
           .map((o) => o.trim())
@@ -288,79 +257,7 @@ function NewKeyForm({ allProjects, onCreated, onCancel }: NewKeyFormProps) {
       {isScoped && (
         <div className="flex flex-col gap-4 rounded-lg border border-teal-700/30 bg-teal-900/10 px-4 py-4">
           {/* Rules */}
-          <div>
-            <div className="flex items-center justify-between mb-2">
-              <label className="text-xs font-medium text-slate-400">
-                Collection rules <span className="text-red-400">*</span>
-              </label>
-              <button
-                type="button"
-                onClick={addRule}
-                className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium text-teal-300 hover:text-teal-200 bg-teal-700/20 hover:bg-teal-700/40 border border-teal-700/30 transition"
-              >
-                <Plus size={11} />
-                Add rule
-              </button>
-            </div>
-
-            <div className="flex flex-col gap-3">
-              {rules.map((rule, idx) => (
-                <div
-                  key={idx}
-                  className="rounded-md border border-slate-700/40 bg-slate-800/50 px-3 py-3 flex flex-col gap-2"
-                >
-                  <div className="flex items-center gap-2">
-                    <input
-                      type="text"
-                      value={rule.collection}
-                      onChange={(e) => updateRule(idx, { collection: e.target.value })}
-                      placeholder="collection name"
-                      className="flex-1 rounded-md bg-slate-900 border border-slate-600 text-slate-100 px-3 py-1.5 text-xs placeholder-slate-500 focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500/40"
-                    />
-                    {rules.length > 1 && (
-                      <button
-                        type="button"
-                        onClick={() => removeRule(idx)}
-                        className="inline-flex items-center px-2 py-1.5 rounded text-xs text-red-400 hover:text-red-300 hover:bg-red-500/10 transition"
-                        aria-label="Remove rule"
-                      >
-                        <Trash2 size={13} />
-                      </button>
-                    )}
-                  </div>
-                  <div className="flex flex-wrap gap-2">
-                    {KEY_OPS.map((op) => {
-                      const active = rule.ops.includes(op)
-                      return (
-                        <button
-                          key={op}
-                          type="button"
-                          onClick={() => toggleRuleOp(idx, op)}
-                          className={[
-                            'inline-flex items-center px-2 py-0.5 rounded text-xs font-mono border transition',
-                            active
-                              ? 'bg-indigo-600/30 border-indigo-500/50 text-indigo-300'
-                              : 'bg-slate-800 border-slate-600/40 text-slate-400 hover:border-slate-500 hover:text-slate-300',
-                          ].join(' ')}
-                        >
-                          {op}
-                        </button>
-                      )
-                    })}
-                  </div>
-                  <label className="flex items-center gap-2 cursor-pointer select-none w-fit">
-                    <input
-                      type="checkbox"
-                      checked={rule.require_human_token ?? false}
-                      onChange={(e) => updateRule(idx, { require_human_token: e.target.checked })}
-                      className="w-3.5 h-3.5 rounded border-slate-600 bg-slate-800 accent-indigo-500"
-                    />
-                    <span className="text-xs text-slate-400">Require human token (CAPTCHA)</span>
-                  </label>
-                </div>
-              ))}
-            </div>
-          </div>
+          <ScopeRulesEditor rules={rules} onChange={setRules} />
 
           {/* Origins */}
           <div>

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

@@ -107,11 +107,16 @@ export interface DeleteImpact {
 export class ApiError extends Error {
   status: number
   details?: unknown
-  constructor(status: number, message: string, details?: unknown) {
+  /// The server's machine-readable slug (`error.code`): 'no_runner',
+  /// 'compile_failed', 'id_mismatch', ... A status alone is not enough to tell
+  /// those apart, and the Functions page has to explain each one differently.
+  code?: string
+  constructor(status: number, message: string, details?: unknown, code?: string) {
     super(message)
     this.name = 'ApiError'
     this.status = status
     this.details = details
+    this.code = code
   }
 }
 
@@ -130,3 +135,82 @@ export type CreateIndexResult = {
   rows_indexed: number
   already_existed: boolean
 }
+
+// ─── functions ────────────────────────────────────────────────────────────────
+
+/// The validated `on` block a script exports. Only `id` and `type` are always
+/// present; the rest depends on the trigger.
+export interface FunctionDescriptor {
+  id: string
+  type: 'http' | 'cron' | 'db'
+  /// http: the route pattern, with `:name` path params.
+  route?: string
+  /// http: the declared methods. ABSENT MEANS EVERY METHOD, never "none".
+  method?: string[]
+  schedule?: string
+  table?: string
+  event?: string
+  timeoutMs?: number
+  singleFlight?: boolean
+}
+
+/// A registry row as the list route returns it: no `source`, so the listing
+/// stays small no matter how much code a project holds.
+export interface FunctionSummary {
+  function_id: string
+  path: string
+  content_hash: string
+  descriptor: FunctionDescriptor
+  /// What the function may touch. Same vocabulary as a key scope, except that
+  /// an empty rule set is legal and means "reaches nothing".
+  policy: KeyScope
+  enabled: boolean
+  valid: boolean
+  last_error: string
+  created_at: number
+  updated_at: number
+}
+
+/// The single-function view, which adds the code.
+export interface FunctionDetail extends FunctionSummary {
+  source: string
+}
+
+/// One recorded run, as the log route returns it.
+export interface FunctionRun {
+  run_id: string
+  function_id: string
+  trigger: string
+  ok: boolean
+  status: number
+  duration_ms: number
+  error: string
+  console: string[]
+  started_at: number
+}
+
+/// What an invoke reports. The HTTP status of the invoke itself is 200 whenever
+/// the run was performed, so `ok`/`status` here are the function's own result.
+export interface InvokeEnvelope {
+  run_id: string
+  ok: boolean
+  status: number
+  headers: Record<string, string>
+  body: unknown
+  console: string[]
+  duration_ms: number
+  error: string
+  timed_out: boolean
+  out_of_memory: boolean
+}
+
+/// Every field is optional: an empty body runs the function on its declared
+/// route with POST.
+export interface InvokeRequest {
+  method?: string
+  path?: string
+  params?: Record<string, unknown>
+  query?: Record<string, unknown>
+  headers?: Record<string, unknown>
+  body?: unknown
+}