Multiplayer agent harness for work.
Migrate admin tabs to Lit and streamline Users and Slack settings (#1441)
Regan Bell685b77260278
diff --git a/.github/workflows/cicd.yml b/.github/workflows/cicd.ymlindex 0c4ec43b4..69db0d181 100644--- a/.github/workflows/cicd.yml+++ b/.github/workflows/cicd.yml@@ -229,8 +229,11 @@ jobs:cache-dependency-path: |package-lock.jsonplugins/web-ui/package-lock.json- - name: Install core dependencies- run: npm ci+ plugins/admin/package-lock.json+ - name: Install core and mounted admin dependencies+ run: |+ npm ci+ npm ci --prefix plugins/admin- name: Install, typecheck, test, buildworking-directory: plugins/web-uirun: |diff --git a/deploy/admin/Dockerfile b/deploy/admin/Dockerfileindex 548e5af2a..4df4235f4 100644--- a/deploy/admin/Dockerfile+++ b/deploy/admin/Dockerfile@@ -6,6 +6,7 @@ COPY plugins/admin/package.json plugins/admin/package-lock.json ./RUN npm ci --omit=dev && rm -rf /root/.npm /tmp/node-compile-cacheCOPY plugins/admin/src ./src+COPY plugins/admin/ui ./uiCOPY plugins/chassis/src /chassis/srcCOPY plugins/admin/public ./publicCOPY plugins/admin/tsconfig.json ./diff --git a/deploy/web-ui/Dockerfile b/deploy/web-ui/Dockerfileindex 322f6c697..11ab3b892 100644--- a/deploy/web-ui/Dockerfile+++ b/deploy/web-ui/Dockerfile@@ -16,8 +16,10 @@ RUN npm ci --omit=dev && rm package-lock.json \&& rm -rf /root/.npm /tmp/node-compile-cacheCOPY plugins/web-ui/server ./serverCOPY plugins/web-ui/src/app-edit.ts ./src/app-edit.ts+COPY plugins/admin/package.json plugins/admin/package-lock.json /admin/+RUN npm ci --prefix /admin --omit=dev && rm -rf /root/.npm /tmp/node-compile-cacheCOPY plugins/admin/src /admin/src-RUN ln -s /app/node_modules /admin/node_modules+COPY plugins/admin/ui /admin/uiCOPY plugins/admin/public /admin/publicCOPY plugins/chassis/src /chassis/srcCOPY --from=build /app/dist-web ./dist-webdiff --git a/plugins/admin/README.md b/plugins/admin/README.mdindex 67bb0b1a2..9b23ca358 100644--- a/plugins/admin/README.md+++ b/plugins/admin/README.md@@ -43,7 +43,11 @@ CORE_API_URL=http://localhost:8080 CORE_ORG_ID=acme PORT=8090 npm start```-No build step, an optional Sentry backend error reporter (pure `node:http` + native TS). Node 24+.+No separate build command is needed. The Node 24+ server bundles the admin Lit modules once at startup and embeds them in the existing CSP-hashed script. The backend uses `node:http` and native TypeScript, with optional Sentry error reporting.++The admin tabs render through the Lit modules in `ui/`, with `ui/admin.ts` as their shared entry point. They use the existing light-DOM elements, classes, and styles without layout wrappers. Settings drafts, validation, dirty state, and save feedback render from state; list views own filtering, pagination, and editor state. Stable row keys preserve focus. Shared table, card, and list templates live in `ui/shared.ts`. Specialized safe Markdown, XML, and tool-output formatters remain shared adapters in the shell.++The shared admin controller retains routing, API calls, and change-review dialogs. Successful saves commit the submitted snapshot, preserving newer edits made while a request was in flight. Scope and render generations prevent stale requests from replacing a newer page. Related settings refresh independently so changing one section cannot discard neighboring drafts. Run `npm test` and `npm run typecheck` from this directory after changing the UI.Env: `CORE_API_URL` (default `http://localhost:8080`), `CORE_ORG_ID` (default `acme`),`PORT` (default `8090`) and `CORE_SIGNING_SECRET` (required outside isolated development). Thediff --git a/plugins/admin/package-lock.json b/plugins/admin/package-lock.jsonindex c69c36981..469a35c1e 100644--- a/plugins/admin/package-lock.json+++ b/plugins/admin/package-lock.json@@ -8,16 +8,675 @@"name": "qm-admin-plugin","version": "0.1.0","dependencies": {- "@sentry/node": "10.75.0"+ "@sentry/node": "10.75.0",+ "esbuild": "^0.28.1",+ "lit": "^3.3.3"},"devDependencies": {+ "@types/jsdom": "^28.0.3","@types/node": "^24.0.0",+ "jsdom": "^29.1.1","typescript": "^5.8.2"},"engines": {"node": ">=24.0.0"}},+ "node_modules/@asamuzakjp/css-color": {+ "version": "5.1.11",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-5.1.11.tgz",+ "integrity": "sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/generational-cache": "^1.0.1",+ "@csstools/css-calc": "^3.2.0",+ "@csstools/css-color-parser": "^4.1.0",+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/dom-selector": {+ "version": "7.1.1",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-7.1.1.tgz",+ "integrity": "sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/generational-cache": "^1.0.1",+ "@asamuzakjp/nwsapi": "^2.3.9",+ "bidi-js": "^1.0.3",+ "css-tree": "^3.2.1",+ "is-potential-custom-element-name": "^1.0.1"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/generational-cache": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/generational-cache/-/generational-cache-1.0.1.tgz",+ "integrity": "sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/nwsapi": {+ "version": "2.3.9",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz",+ "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@bramus/specificity": {+ "version": "2.4.2",+ "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz",+ "integrity": "sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "css-tree": "^3.0.0"+ },+ "bin": {+ "specificity": "bin/cli.js"+ }+ },+ "node_modules/@csstools/color-helpers": {+ "version": "6.1.1",+ "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.1.tgz",+ "integrity": "sha512-gLNsunvwf3mCi5u5o46/Z/JcJMnhbHSaZ69rkgPzNM3J4s8hWwpPUQB6/tt0EDFyCiWzxANlx+2LJwpYj4zS1w==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT-0",+ "engines": {+ "node": ">=20.19.0"+ }+ },+ "node_modules/@csstools/css-calc": {+ "version": "3.4.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.0.tgz",+ "integrity": "sha512-XQKj5B7QiZcHiegCOCAzcAOJdhGgWOHbbu62h5e5mkHnn8lWcfiJhllkqWmxu5zWR9jucPHuo1iTB56P033hcg==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-color-parser": {+ "version": "4.2.3",+ "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.3.tgz",+ "integrity": "sha512-y4LpL+lmpuyKDiEFq2PnZUVFdAjsoB/qQJod79yLNokXyW7jewi+/WJ69EfItj8A2unWtxXnGjw6LYXgXu5ZjA==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@csstools/color-helpers": "^6.1.1",+ "@csstools/css-calc": "^3.4.0"+ },+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-parser-algorithms": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz",+ "integrity": "sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-syntax-patches-for-csstree": {+ "version": "1.1.14",+ "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.14.tgz",+ "integrity": "sha512-HpbVXyrofRXpHpgkNIjU/3EWR4WJvOkO3emNK/L6X/mTJU7bGUI3AkkpoTNXznQLp0KRjLHELTGeKI5dIkI9JQ==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT-0",+ "peerDependencies": {+ "css-tree": "^3.2.1"+ },+ "peerDependenciesMeta": {+ "css-tree": {+ "optional": true+ }+ }+ },+ "node_modules/@csstools/css-tokenizer": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.1.tgz",+ "integrity": "sha512-bPlN9S9O1A0euCpEWE4qnvB5YDuyYVsUTrxSgmAM1Is0j4tICHoVyOVAXfWMP/kS9ZrjvyIXWV2PmomiAXXqOw==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": ">=20.19.0"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",+ "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",+ "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",+ "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",+ "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",+ "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",+ "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",+ "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",+ "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",+ "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",+ "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",+ "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",+ "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",+ "cpu": [+ "loong64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",+ "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",+ "cpu": [+ "mips64el"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",+ "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",+ "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",+ "cpu": [+ "riscv64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",+ "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",+ "cpu": [+ "s390x"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",+ "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",+ "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",+ "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",+ "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",+ "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",+ "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",+ "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",+ "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",+ "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",+ "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@exodus/bytes": {+ "version": "1.15.1",+ "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.1.tgz",+ "integrity": "sha512-S6mL0yNB/Abt9Ei4tq8gDhcczc4S3+vQ4ra7vxnAf+YHC02srtqxKKZghx2Dq6p0e66THKwR6r8N6P95wEty7Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ },+ "peerDependencies": {+ "@noble/hashes": "^1.8.0 || ^2.0.0"+ },+ "peerDependenciesMeta": {+ "@noble/hashes": {+ "optional": true+ }+ }+ },+ "node_modules/@lit-labs/ssr-dom-shim": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/@lit-labs/ssr-dom-shim/-/ssr-dom-shim-1.6.0.tgz",+ "integrity": "sha512-VHb0ALPMTlgKjM6yIxxoQNnpKyUKLD04VzeQdsiXkMqkvYlAHxq9glGLmgbb889/1GsohSOAjvQYoiBppXFqrQ==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@lit/reactive-element": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/@lit/reactive-element/-/reactive-element-2.1.2.tgz",+ "integrity": "sha512-pbCDiVMnne1lYUIaYNN5wrwQXDtHaYtg7YEFPeW+hws6U47WeFvISGUWekPGKWOP1ygrs0ef0o1VJMk1exos5A==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "@lit-labs/ssr-dom-shim": "^1.5.0"+ }+ },"node_modules/@opentelemetry/api": {"version": "1.9.1","resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz",@@ -246,6 +905,26 @@"node": ">=18"}},+ "node_modules/@types/jsdom": {+ "version": "28.0.3",+ "resolved": "https://registry.npmjs.org/@types/jsdom/-/jsdom-28.0.3.tgz",+ "integrity": "sha512-/HQ2uFoetFTXuye8vzIcHw2z6Fwi7Hi/qcgC+RoS9NCyewiqxhVGqlG+ViGB6lkax481R6dmhf1I7lIGlzJStQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*",+ "@types/tough-cookie": "*",+ "parse5": "^8.0.0",+ "undici-types": "^7.21.0"+ }+ },+ "node_modules/@types/jsdom/node_modules/undici-types": {+ "version": "7.29.1",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.29.1.tgz",+ "integrity": "sha512-2xO3p6gANwOmhSFwNy2MMYISbHTtM+K3bY0bqpD1gOGpUPIe+yFXCobxbz0s2jm7E0faMxIFcZUcCKa+N6Ozlg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/node": {"version": "24.12.4","resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.4.tgz",@@ -256,12 +935,63 @@"undici-types": "~7.16.0"}},+ "node_modules/@types/tough-cookie": {+ "version": "4.0.5",+ "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.5.tgz",+ "integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/trusted-types": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",+ "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",+ "license": "MIT"+ },+ "node_modules/bidi-js": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz",+ "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "require-from-string": "^2.0.2"+ }+ },"node_modules/cjs-module-lexer": {"version": "2.2.1","resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-2.2.1.tgz","integrity": "sha512-Ca8swihM+/4yKecYHY52kgJd300hi2lADU/a1RxNTRe+RJ9jvqQlESpbz9DnG9mowez8qwXHB8qYdIUw9e+F5Q==","license": "MIT"},+ "node_modules/css-tree": {+ "version": "3.2.1",+ "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz",+ "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "mdn-data": "2.27.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0"+ }+ },+ "node_modules/data-urls": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz",+ "integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "whatwg-mimetype": "^5.0.0",+ "whatwg-url": "^16.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },"node_modules/debug": {"version": "4.4.3","resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",@@ -279,12 +1009,86 @@}}},+ "node_modules/decimal.js": {+ "version": "10.6.0",+ "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",+ "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/entities": {+ "version": "8.1.0",+ "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz",+ "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=20.19.0"+ },+ "funding": {+ "url": "https://github.com/fb55/entities?sponsor=1"+ }+ },"node_modules/es-module-lexer": {"version": "3.0.2","resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-3.0.2.tgz","integrity": "sha512-BuIB67FngDSyQ/dpQNOZybwdEBDUGJQvOqwWr4ha/ufYiqzuEwPkKO2zLhRAgay28tStRIHUeWmszZAJo3GCOg==","license": "MIT"},+ "node_modules/esbuild": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",+ "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.28.1",+ "@esbuild/android-arm": "0.28.1",+ "@esbuild/android-arm64": "0.28.1",+ "@esbuild/android-x64": "0.28.1",+ "@esbuild/darwin-arm64": "0.28.1",+ "@esbuild/darwin-x64": "0.28.1",+ "@esbuild/freebsd-arm64": "0.28.1",+ "@esbuild/freebsd-x64": "0.28.1",+ "@esbuild/linux-arm": "0.28.1",+ "@esbuild/linux-arm64": "0.28.1",+ "@esbuild/linux-ia32": "0.28.1",+ "@esbuild/linux-loong64": "0.28.1",+ "@esbuild/linux-mips64el": "0.28.1",+ "@esbuild/linux-ppc64": "0.28.1",+ "@esbuild/linux-riscv64": "0.28.1",+ "@esbuild/linux-s390x": "0.28.1",+ "@esbuild/linux-x64": "0.28.1",+ "@esbuild/netbsd-arm64": "0.28.1",+ "@esbuild/netbsd-x64": "0.28.1",+ "@esbuild/openbsd-arm64": "0.28.1",+ "@esbuild/openbsd-x64": "0.28.1",+ "@esbuild/openharmony-arm64": "0.28.1",+ "@esbuild/sunos-x64": "0.28.1",+ "@esbuild/win32-arm64": "0.28.1",+ "@esbuild/win32-ia32": "0.28.1",+ "@esbuild/win32-x64": "0.28.1"+ }+ },+ "node_modules/html-encoding-sniffer": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz",+ "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@exodus/bytes": "^1.6.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },"node_modules/import-in-the-middle": {"version": "3.5.1","resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-3.5.1.tgz",@@ -299,6 +1103,102 @@"node": ">=18"}},+ "node_modules/is-potential-custom-element-name": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",+ "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/jsdom": {+ "version": "29.1.1",+ "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-29.1.1.tgz",+ "integrity": "sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/css-color": "^5.1.11",+ "@asamuzakjp/dom-selector": "^7.1.1",+ "@bramus/specificity": "^2.4.2",+ "@csstools/css-syntax-patches-for-csstree": "^1.1.3",+ "@exodus/bytes": "^1.15.0",+ "css-tree": "^3.2.1",+ "data-urls": "^7.0.0",+ "decimal.js": "^10.6.0",+ "html-encoding-sniffer": "^6.0.0",+ "is-potential-custom-element-name": "^1.0.1",+ "lru-cache": "^11.3.5",+ "parse5": "^8.0.1",+ "saxes": "^6.0.0",+ "symbol-tree": "^3.2.4",+ "tough-cookie": "^6.0.1",+ "undici": "^7.25.0",+ "w3c-xmlserializer": "^5.0.0",+ "webidl-conversions": "^8.0.1",+ "whatwg-mimetype": "^5.0.0",+ "whatwg-url": "^16.0.1",+ "xml-name-validator": "^5.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || >=24.0.0"+ },+ "peerDependencies": {+ "canvas": "^3.0.0"+ },+ "peerDependenciesMeta": {+ "canvas": {+ "optional": true+ }+ }+ },+ "node_modules/lit": {+ "version": "3.3.3",+ "resolved": "https://registry.npmjs.org/lit/-/lit-3.3.3.tgz",+ "integrity": "sha512-fycuvZg/hkpozL00lm1pEJH5nN/lr9ZXd6mJI2HSN4+Bzc+LDNdEApJ6HFbPkdFNHLvOplIIuJvxkS4XUxqirw==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "@lit/reactive-element": "^2.1.0",+ "lit-element": "^4.2.0",+ "lit-html": "^3.3.0"+ }+ },+ "node_modules/lit-element": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/lit-element/-/lit-element-4.2.2.tgz",+ "integrity": "sha512-aFKhNToWxoyhkNDmWZwEva2SlQia+jfG0fjIWV//YeTaWrVnOxD89dPKfigCUspXFmjzOEUQpOkejH5Ly6sG0w==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "@lit-labs/ssr-dom-shim": "^1.5.0",+ "@lit/reactive-element": "^2.1.0",+ "lit-html": "^3.3.0"+ }+ },+ "node_modules/lit-html": {+ "version": "3.3.3",+ "resolved": "https://registry.npmjs.org/lit-html/-/lit-html-3.3.3.tgz",+ "integrity": "sha512-el8M6jK2o3RXBnrSHX3ZKrsN8zEV63pSExTO1wYJz7QndGYZ8353e2a5PPX+qHe2aGayfnchQmkAojaWAREOIA==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "@types/trusted-types": "^2.0.2"+ }+ },+ "node_modules/lru-cache": {+ "version": "11.5.2",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz",+ "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==",+ "dev": true,+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": "20 || >=22"+ }+ },+ "node_modules/mdn-data": {+ "version": "2.27.1",+ "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",+ "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==",+ "dev": true,+ "license": "CC0-1.0"+ },"node_modules/module-details-from-path": {"version": "1.0.4","resolved": "https://registry.npmjs.org/module-details-from-path/-/module-details-from-path-1.0.4.tgz",@@ -311,6 +1211,39 @@"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==","license": "MIT"},+ "node_modules/parse5": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz",+ "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "entities": "^8.0.0"+ },+ "funding": {+ "url": "https://github.com/inikulin/parse5?sponsor=1"+ }+ },+ "node_modules/punycode": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/require-from-string": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },"node_modules/require-in-the-middle": {"version": "8.0.1","resolved": "https://registry.npmjs.org/require-in-the-middle/-/require-in-the-middle-8.0.1.tgz",@@ -324,6 +1257,82 @@"node": ">=9.3.0 || >=8.10.0 <9.0.0"}},+ "node_modules/saxes": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",+ "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "xmlchars": "^2.2.0"+ },+ "engines": {+ "node": ">=v12.22.7"+ }+ },+ "node_modules/source-map-js": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/symbol-tree": {+ "version": "3.2.4",+ "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",+ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tldts": {+ "version": "7.4.13",+ "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.13.tgz",+ "integrity": "sha512-iHtaIWWIbMDkCeJdTBzZFGgbluE5J+oHlb2g7+oAz1S1gpuVpabRZdQyd471Vl8UUkcz2vXSL8xZH2kyCe8tfA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tldts-core": "^7.4.13"+ },+ "bin": {+ "tldts": "bin/cli.js"+ }+ },+ "node_modules/tldts-core": {+ "version": "7.4.13",+ "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.13.tgz",+ "integrity": "sha512-mbYsrih5FRtGxs3Usvl/PqwJsNpp+jsmrdFviiK02teHDG0/HebBG/pqCylje3kzgXYzuLoHJF/0mz9W53t8Xg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tough-cookie": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz",+ "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "tldts": "^7.0.5"+ },+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/tr46": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz",+ "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "punycode": "^2.3.1"+ },+ "engines": {+ "node": ">=20"+ }+ },"node_modules/typescript": {"version": "5.9.3","resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",@@ -338,12 +1347,87 @@"node": ">=14.17"}},+ "node_modules/undici": {+ "version": "7.29.1",+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.1.tgz",+ "integrity": "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=20.18.1"+ }+ },"node_modules/undici-types": {"version": "7.16.0","resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz","integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==","dev": true,"license": "MIT"+ },+ "node_modules/w3c-xmlserializer": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",+ "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "xml-name-validator": "^5.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/webidl-conversions": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz",+ "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/whatwg-mimetype": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz",+ "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/whatwg-url": {+ "version": "16.0.1",+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz",+ "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@exodus/bytes": "^1.11.0",+ "tr46": "^6.0.0",+ "webidl-conversions": "^8.0.1"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/xml-name-validator": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",+ "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/xmlchars": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",+ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",+ "dev": true,+ "license": "MIT"}}}diff --git a/plugins/admin/package.json b/plugins/admin/package.jsonindex a4c05c3ef..b5387b996 100644--- a/plugins/admin/package.json+++ b/plugins/admin/package.json@@ -13,10 +13,14 @@"test": "NODE_ENV=test ALLOW_UNSIGNED_TEST_IDENTITY=1 node --test"},"devDependencies": {+ "@types/jsdom": "^28.0.3","@types/node": "^24.0.0",+ "jsdom": "^29.1.1","typescript": "^5.8.2"},"dependencies": {- "@sentry/node": "10.75.0"+ "@sentry/node": "10.75.0",+ "esbuild": "^0.28.1",+ "lit": "^3.3.3"}}diff --git a/plugins/admin/public/index.html b/plugins/admin/public/index.htmlindex 9111a8c8f..1c6c7d01b 100644--- a/plugins/admin/public/index.html+++ b/plugins/admin/public/index.html@@ -272,6 +272,7 @@line-height: 1;flex: 0 0 auto;}+.emoji-picker {position: absolute;z-index: 60;@@ -1294,7 +1295,55 @@display: flex;gap: 8px;}+ .slack-message-example {+ margin: 20px 0 0;+ padding: 16px;+ border: 1px solid var(--border);+ border-radius: var(--radius);+ background: var(--surface);+ }+ .slack-message-example figcaption {+ margin-bottom: 12px;+ color: var(--muted);+ font-size: 12px;+ }+ .slack-example-message {+ display: flex;+ gap: 10px;+ }+ .slack-example-avatar {+ display: grid;+ place-items: center;+ width: 36px;+ height: 36px;+ border-radius: 6px;+ background: var(--cta);+ color: var(--cta-foreground);+ flex-shrink: 0;+ }+ .slack-example-message p {+ margin: 4px 0;+ }+ .slack-example-link {+ color: var(--text);+ text-decoration: underline;+ }+ .user-resource-links {+ display: flex;+ flex-wrap: wrap;+ gap: 12px 24px;+ margin-bottom: 20px;+ font-size: 13px;+ }+ .user-resource-links a {+ color: var(--muted);+ white-space: nowrap;+ }+ .user-resource-links a:hover {+ color: var(--text);+ }.rowbtn {+ white-space: nowrap;padding: 3px 10px;font-size: 12px;}@@ -3046,6 +3095,7 @@display: block;color: var(--muted);}+ body[data-subview="slack-settings"] #view-governance section.card:not(.sv-slack-settings),body[data-subview="models"] #view-governance section.card:not(.sv-models),body[data-subview="credentials"] #view-governance section.card:not(.sv-credentials),body[data-subview="customize"] #view-governance section.card:not(.sv-customize),@@ -3054,6 +3104,9 @@}body[data-subview="models"] #view-governance .governance-group:not(#governance-intelligence),body[data-subview="credentials"] #view-governance .governance-group:not(#governance-credentials),+ body[data-subview="slack-settings"] #view-governance .governance-group,+ body[data-subview="slack-settings"] #view-governance .governance-overview,+ body[data-subview="slack-settings"] #view-governance .governance-sections,body[data-subview="customize"] #view-governance .governance-group,body[data-subview="governance"] #view-governance #governance-intelligence,body[data-subview="governance"] #view-governance #governance-credentials,@@ -3069,6 +3122,7 @@}body[data-subview="models"] #view-governance .governance-layout,body[data-subview="credentials"] #view-governance .governance-layout,+ body[data-subview="slack-settings"] #view-governance .governance-layout,body[data-subview="customize"] #view-governance .governance-layout {grid-template-columns: minmax(0, 1fr);}@@ -5831,14 +5885,6 @@padding: 0;min-width: 0;}- #view-data .users-layout .users-setting {- display: grid;- grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);- gap: 32px;- }- #view-data .users-layout .users-setting > .head {- margin: 0;- }#view-data .users-layout .users-roster > .head {display: grid;grid-template-columns: minmax(0, 1fr) auto;@@ -5874,10 +5920,6 @@font-size: 13px;}@media (max-width: 720px) {- #view-data .users-layout .users-setting {- grid-template-columns: minmax(0, 1fr);- gap: 16px;- }#view-data .users-layout .users-roster > .head {display: flex;flex-direction: column;@@ -6237,6 +6279,11 @@gap: 16px;}}+ #view-governance.governance-pending .governance-layout,+ #view-governance.governance-pending .governance-overview,+ #view-governance.governance-pending .environment-notice {+ display: none;+ }</style><style data-admin-components></style></head>@@ -6369,196 +6416,9 @@and never displayed again.</p></div>- <div class="setup-grid">- <section class="setup-step">- <span class="badge muted" id="onboarding-model-badge">Not ready</span>- <h2>1. Model provider</h2>- <p id="onboarding-model-summary">Add the key the agent will use for its base model.</p>- </section>- <section class="setup-step">- <span class="badge muted" id="onboarding-slack-badge">Optional</span>- <h2>2. Slack app</h2>- <p id="onboarding-slack-summary">- Create the Slack app, install it, then add its bot and Socket Mode tokens.- </p>- <div class="foot">- <a- class="header-button"- id="onboarding-slack-create"- href="https://api.slack.com/apps?new_app=1"- target="_blank"- rel="noopener noreferrer"- >Create Slack app ↗</a- >- <button type="button" data-onboarding-target="slack">Enter Slack tokens</button>- </div>- </section>- <section class="setup-step">- <span class="badge muted" id="onboarding-oauth-badge">Optional</span>- <h2>3. OAuth apps</h2>- <p id="onboarding-oauth-summary">- Add Google, GitHub, Notion, or other OAuth clients to make those connectors available.- </p>- <div class="foot">- <button type="button" data-onboarding-target="oauth">Configure OAuth apps</button>- </div>- </section>- </div>- <section class="card">- <div class="head">- <h2>Base model</h2>- <p>- Choose a supported provider and model. Saving validates the key, stores it write-only, and makes the- selected model the organization default.- </p>- </div>- <div class="body setup-form">- <label- >Provider- <select id="onboarding-model-provider"></select>- </label>- <label- >Base model- <select id="onboarding-model-id"></select- ></label>- <label- >API key- <input type="password" id="onboarding-model-key" autocomplete="off" placeholder="Write-only API key"- /></label>- </div>- <div class="foot">- <button class="primary" id="onboarding-model-save">Validate and connect</button- ><button class="danger" id="onboarding-model-delete">Disable this provider</button- ><span class="status" id="st-onboarding-model"></span>- </div>- </section>- <section class="card">- <div class="head">- <h2>Models on existing providers</h2>- <p>- Start with a provider and model ID. We look up exact catalog or provider metadata before asking for- any missing details. Organization credentials are inherited; subscription support is not implied.- </p>- </div>- <div class="body">- <table class="table">- <thead>- <tr>- <th>Model</th>- <th>Provider</th>- <th>Template</th>- <th></th>- </tr>- </thead>- <tbody id="model-registry-rows"></tbody>- </table>- <p class="muted" id="model-registry-empty">No additional models.</p>- </div>- <div class="body setup-form">- <label- >Provider- <select id="model-registry-provider">- <option value="openai">OpenAI</option>- <option value="anthropic">Anthropic</option>- </select></label- >- <label- >Model ID- <input- type="text"- id="model-registry-id"- autocomplete="off"- placeholder="e.g. claude-opus-4-6"- required- /></label>- </div>- <div class="foot"><button id="model-registry-lookup" class="primary">Look up model</button></div>- <div class="body" id="model-registry-result" hidden>- <p id="model-registry-source" class="muted"></p>- <p id="model-registry-summary"></p>- <p id="model-registry-lookup-note" class="muted"></p>- <div id="model-registry-missing" hidden>- <h3>Complete missing information</h3>- <p class="muted">- These fields were not available from the exact model record. Use the provider's documentation;- choose a compatible template explicitly.- </p>- <div class="setup-form" id="model-registry-missing-fields"></div>- </div>- <details id="model-registry-advanced">- <summary>Advanced overrides</summary>- <p class="muted">- Review imported values or override them. Pricing is per million tokens. Overrides require- verification again.- </p>- <div class="setup-form" id="model-registry-advanced-fields">- <label- >Display name <input type="text" id="model-registry-name" autocomplete="off" required- /></label>- <label- >Compatible builtin template- <select id="model-registry-template"></select- ></label>- <p class="muted" id="model-registry-capabilities"></p>- <label- >Context window (tokens)- <input id="model-registry-contextWindow" type="number" min="2" step="1" required- /></label>- <label- >Maximum output (tokens)- <input id="model-registry-maxTokens" type="number" min="1" step="1" required- /></label>- <label- >Input ($ / million tokens)- <input id="model-registry-input" type="number" min="0" step="any" required- /></label>- <label- >Output ($ / million tokens)- <input id="model-registry-output" type="number" min="0" step="any" required- /></label>- <label- >Cache read ($ / million tokens)- <input id="model-registry-cacheRead" type="number" min="0" step="any" required- /></label>- <label- >Cache write ($ / million tokens)- <input id="model-registry-cacheWrite" type="number" min="0" step="any" required- /></label>- <label class="check"- ><input id="model-registry-base" type="checkbox" checked /> Offer in admin model choices</label- >- <label class="check"- ><input id="model-registry-webui" type="checkbox" checked /> Offer in web picker by default</label- >- <label class="check"- ><input id="model-registry-fastMode" type="checkbox" /> Model supports the Anthropic fast- tier</label- >- <label class="check"- ><input id="model-registry-auxiliary" type="checkbox" /> Eligible for auxiliary tasks</label- >- <details>- <summary>Advanced pricing tiers</summary>- <label- >JSON array of inputTokensAbove, input, output, cacheRead and cacheWrite- <textarea id="model-registry-tiers" rows="4" placeholder="[]"></textarea>- </label>- </details>- </div>- </details>- </div>- <p class="muted" id="model-registry-verification-notice">- Verify and enable sends a synthetic connection check using the organization's serving credentials. It- may incur a small provider charge (up to 128 output tokens per request; an additional check with fast- mode; provider retries may apply). A successful check confirms access now, not pricing, maximum context,- every capability, or personal-key access. Failed checks do not save or enable the new definition.- Existing saved settings remain unchanged. A failed recheck of those settings removes their verification.- </p>- <div class="foot">- <button class="primary" id="model-registry-save" disabled>Verify and enable</button- ><button id="model-registry-new">New model</button><span class="status" id="st-model-registry"></span>- </div>- </section>+ <template data-onboarding-ui="steps"></template>+ <template data-onboarding-ui="provider"></template>+ <template data-onboarding-ui="registry"></template><section class="card"><div class="head"><h2>Custom providers</h2>@@ -6591,6 +6451,7 @@</div><div id="view-governance">+ <p id="governance-loading" class="hint hidden" role="status">Loading settings…</p><aside class="environment-notice admin-notice hidden" id="environment-notice" role="status"><div><strong id="environment-notice-title"></strong>@@ -6638,1052 +6499,42 @@<h2>Autonomy</h2><p>How agents reason, act, and respond without supervision.</p></div>- <section class="card sv-governance setting-row hidden" id="card-security-posture">- <div class="head">- <h2>Security posture</h2>- <p>Choose how the agent screens external content and when it requires your approval.</p>- </div>- <div class="body">- <select id="security-posture" data-choice-state hidden>- <option value="dangerous">Dangerous — no content scans; nothing pauses between tool calls</option>- <option value="auto">Auto — use the deployment’s configured screener</option>- <option value="strict">Strict — approve tool actions</option>- </select>- <div class="choice-stack">- <label class="posture-choice"- ><input- type="radio"- name="security-posture-choice"- value="auto"- data-choice-for="security-posture"- /><span- ><strong>Auto</strong- ><small- >Default. Blocks private-network access. Screens external content when the deployment- configures a screener; model screening is off by default.</small- ></span- ></label- >- <label class="posture-choice"- ><input- type="radio"- name="security-posture-choice"- value="dangerous"- data-choice-for="security-posture"- /><span><strong>Dangerous</strong><small>No content screening.</small></span></label- >- <label class="posture-choice"- ><input- type="radio"- name="security-posture-choice"- value="strict"- data-choice-for="security-posture"- /><span- ><strong>Strict</strong><small>Every tool action requires human approval.</small></span- ></label- >- </div>- </div>- <div class="foot">- <button class="primary" data-save="security-posture">Apply</button- ><span class="status" id="st-security-posture"></span>- </div>- </section>- <section class="card sv-governance hidden" id="card-auto-flagger">- <div class="head">- <h2>Auto flagger</h2>- <p>- Model and prompt used when the deployment explicitly enables model screening in Auto mode. These- settings do not enable screening. The security boundary and required verdict format remain fixed.- </p>- </div>- <div class="body">- <div class="screening-details">- <div class="governance-field-grid">- <div>- <label for="auto-flagger-harness">Harness</label>- <select id="auto-flagger-harness"></select>- </div>- <div>- <label for="auto-flagger-model">Model</label>- <select id="auto-flagger-model"></select>- </div>- </div>- <div class="governance-prompt">- <label for="auto-flagger-rubric">Quarantine prompt (classification rubric)</label>- <textarea id="auto-flagger-rubric" rows="6" maxlength="20000"></textarea>- </div>- <div class="screening-test-options">- <h3>Test Auto flagger</h3>- <p class="screening-test-help">- Try the model and prompt above on recent screenings without applying changes.- </p>- <div class="screening-test-fields">- <label for="auto-flagger-window">Recent screenings to test</label>- <div class="screening-count">- <input- id="auto-flagger-window"- type="number"- inputmode="numeric"- min="1"- max="500"- step="1"- value="100"- aria-describedby="auto-flagger-window-range"- />- <span id="auto-flagger-window-range">1–500</span>- </div>- <label- class="screening-compare"- title="Also replay the configuration in effect today, so the flag rates are comparable"- >- <input type="checkbox" id="auto-flagger-compare" />Compare with the currently applied- configuration- </label>- <button id="auto-flagger-test" type="button">Run test</button>- </div>- </div>- </div>- </div>- <div class="foot">- <button id="auto-flagger-reset" type="button">Restore default</button>- <button class="primary" data-save="auto-flagger">Apply</button>- <span class="status" id="st-auto-flagger"></span>- </div>- <div class="foot" id="auto-flagger-test-result" hidden>- <span class="status" id="st-auto-flagger-test"></span>- </div>- </section>- <section class="card sv-governance setting-row hidden" id="card-approval-grant-modes">- <div class="head">- <h2>Approval grant options</h2>- <p>- Which standing options an approval card offers besides "Allow once". Composes tighten-only with- the org value; disabling a mode also suspends existing grants of that mode until it is re-enabled.- Predeclared command approvals and strict-posture tool approvals both honor this.- </p>- </div>- <div class="body">- <label- ><input type="checkbox" id="approval-grant-session" /> Offer "Allow session" (grant lasts for the- conversation)</label- >- <label- ><input type="checkbox" id="approval-grant-always" /> Offer "Allow always" (standing grant across- turns)</label- >- </div>- <div class="foot">- <button class="primary" data-save="approval-grant-modes">Apply</button- ><span class="status" id="st-approval-grant-modes"></span>- </div>- </section>- <section class="card sv-governance" id="card-command-policy">- <div class="head">- <h2>Command policy</h2>- </div>- <div class="body">- <div class="policy-rules" id="rules"></div>- <p class="hint rules-empty" id="rules-empty">No command rules yet.</p>- <div class="policy-actions">- <button id="add-rule" type="button">+ Add rule</button>- <button id="policy-more" type="button" class="hidden"></button>- <button id="policy-test-open" type="button">Test a command…</button>- </div>- <div class="policy-warnings" id="policy-warnings" aria-live="polite"></div>- </div>- <div class="foot">- <button class="primary" data-save="command-policy">Save</button- ><span class="status" id="st-policy"></span>- </div>- </section>- <section class="card sv-customize" id="card-soul">- <div class="head">- <h2>Organization SOUL</h2>- <p>- Write the standing instructions composed into every system prompt for this scope. Saving creates a- durable revision; restoring an older revision creates a new one.- </p>- </div>- <div class="body soul-preview-body">- <div class="soul-preview-label" id="soul-preview-label">Standing instructions</div>- <p class="soul-preview" id="soul-preview" aria-labelledby="soul-preview-label">- No saved instructions- </p>- </div>- <div class="body soul-workbench">- <label for="soul">Standing instructions</label>- <textarea id="soul" maxlength="100000" placeholder="No scope-specific instructions"></textarea>- <div class="soul-meta">- <span id="soul-ver"></span><span id="soul-size"></span><span id="soul-validation"></span>- </div>- <div class="soul-diff" id="soul-diff">- <section>- <h3>Saved revision</h3>- <pre id="soul-saved">No saved instructions</pre>- </section>- <section>- <h3>Current draft</h3>- <pre id="soul-draft">No draft changes</pre>- </section>- </div>- <div class="soul-history" id="soul-history" aria-label="SOUL version history"></div>- </div>- <div class="foot">- <button type="button" class="viewlink" id="soul-history-link">View history ›</button- ><button type="button" id="soul-edit">Edit</button- ><button class="primary" data-save="soul">Save</button><span class="status" id="st-soul"></span>- </div>- </section>- <section class="card sv-governance hidden" id="card-ambient-policy">- <div class="head">- <h2>Ambient reply policy</h2>- <p>- What the agent proactively acts on in this channel. The standing order is plain prose the ambient- judge weighs each batch of new messages against. Empty means it stays silent unless addressed. The- bot ledger says how each automated poster is treated: <b>ignore</b> never wakes the judge,- <b>rollup</b> batches its posts (judged at most once per the given hours), <b>action</b> marks its- posts as triggers to act on, <b>user</b> reads it like a person.- </p>- </div>- <div class="body">- <label for="ambient-enabled">Ambient behavior</label>- <p class="hint" style="margin: 2px 0 6px">- When off, the agent never wakes on overheard messages in this channel; it only responds to direct- @mentions. Default: on for channels with 8 or fewer members, off for larger ones.- </p>- <select id="ambient-enabled" style="margin-bottom: 14px">- <option value="default">Default (by channel size)</option>- <option value="on">On</option>- <option value="off">Off</option>- </select>- <label for="ambient-orders">Standing order</label>- <textarea- id="ambient-orders"- placeholder="(none, the agent stays silent here unless addressed)"- ></textarea>- <div class="tablewrap" style="margin-top: 14px">- <table class="rules">- <thead>- <tr>- <th style="width: 34%">Bot (author name)</th>- <th style="width: 30%">Handling</th>- <th>Rollup hours</th>- <th></th>- </tr>- </thead>- <tbody id="ambient-bots"></tbody>- </table>- </div>- <p class="hint rules-empty" id="ambient-bots-empty">No bots in the ledger yet.</p>- <button id="add-bot" type="button" style="margin-top: 10px">+ Add bot</button>- </div>- <div class="foot">- <button type="button" class="viewlink" data-viewlink="judgments">View judgment log ›</button- ><button class="primary" data-save="ambient-policy">Save</button- ><span class="status" id="st-ambient-policy"></span>- </div>- </section>+ <template data-governance-card="card-security-posture"></template>+ <template data-governance-card="card-auto-flagger"></template>+ <template data-governance-card="card-approval-grant-modes"></template>+ <template data-governance-card="card-command-policy"></template>+ <template data-settings-card="card-soul"></template>+ <template data-governance-card="card-ambient-policy"></template><div class="governance-group" id="governance-boundaries"><h2>Data boundaries</h2><p>What can leave a scope, which audiences can see it, and how deployment authority is carried.</p></div>- <section class="card sv-governance setting-row hidden" id="card-sharing-posture">- <div class="head">- <h2>Sharing posture</h2>- <p>- The organization is a ceiling. Personal and room scopes can opt out, and Isolated always wins.- </p>- </div>- <div class="body">- <p id="sharing-posture-effective"></p>- <select id="sharing-posture" data-choice-state hidden>- <option value="isolated">Isolated</option>- <option value="open">Open</option>- </select>- <div class="choice-stack">- <label class="posture-choice"- ><input- type="radio"- name="sharing-posture-choice"- value="isolated"- data-choice-for="sharing-posture"- /><span- ><strong>Isolated</strong- ><small>Resources stay in their own scope unless explicitly shared.</small></span- ></label- >- <label class="posture-choice"- ><input- type="radio"- name="sharing-posture-choice"- value="open"- data-choice-for="sharing-posture"- /><span- ><strong>Open</strong- ><small- >QM can use your saved memories, files, and skills across conversations when you ask it for- help. In a group conversation, this could risk revealing private information to- others.</small- ></span- ></label- >- </div>- </div>- <div class="foot">- <button class="primary" data-save="sharing-posture">Apply</button>- <button type="button" id="sharing-posture-inherit" hidden>Follow organization</button>- <span class="status" id="st-sharing-posture"></span>- </div>- </section>- <section class="card sv-governance" id="card-egress">- <div class="head">- <h2>Egress policy</h2>- </div>- <div class="body">- <div- class="governance-capability admin-notice admin-notice--warning"- id="egress-capability"- role="status"- >- <div>- <strong>Agent computer egress policy unavailable</strong- ><span- >The agent computer provider cannot enforce host restrictions on all outbound traffic.</span- >- </div>- </div>- <div class="egress-empty-state">- <span class="hint" id="egress-empty">No egress rules.</span>- <div class="egress-actions">- <button type="button" id="egress-add-deny">+ Denylist</button>- <button type="button" id="egress-add-allow">+ Allowlist</button>- </div>- </div>- <div class="egress-editor hidden" id="egress-deny-editor">- <label for="egress-deny">Denylist: hosts the agent may never reach</label>- <textarea id="egress-deny" placeholder="ads.example.com pastebin.com"></textarea>- </div>- <div class="egress-editor hidden" id="egress-allow-editor">- <label for="egress">Allowlist: when present, only these outbound hosts may be reached</label>- <textarea id="egress" placeholder="example.com api.internal"></textarea>- </div>- <div class="policy-warnings" id="egress-warnings" aria-live="polite"></div>- </div>- <div class="foot">- <button type="button" class="viewlink" data-viewlink="egress">View logs ›</button- ><button class="primary" data-save="egress">Save draft</button- ><span class="status" id="st-egress"></span>- </div>- </section>- <section class="card sv-governance setting-row hidden" id="card-external-slack">- <div class="head">- <h2>External Slack audience</h2>- <p>- Org-wide, default off. When on, internal members may chat with the agent in Slack rooms whose- audience includes an external user (Connect member or guest). Its replies, and anything it reads- there, are visible to those externals. Externals themselves still can't interact.- </p>- </div>- <div class="body">- <input type="checkbox" id="external-slack-participants" hidden />- <div class="choice-stack">- <label class="posture-choice"- ><input- type="radio"- name="external-slack-choice"- value="off"- data-checkbox-for="external-slack-participants"- /><span- ><strong>Internal only</strong- ><small- >Default. The agent stays silent in Slack rooms that include an external user.</small- ></span- ></label- >- <label class="posture-choice"- ><input- type="radio"- name="external-slack-choice"- value="on"- data-checkbox-for="external-slack-participants"- /><span- ><strong>Allow mixed rooms</strong- ><small- >Internal members can use the agent where externals are present. Externals still cannot- interact.</small- ></span- ></label- >- </div>- </div>- <div class="foot">- <button class="primary" data-save="external-slack-participants">Apply</button- ><span class="status" id="st-external-slack-participants"></span>- </div>- </section>- <section class="card sv-governance setting-row hidden" id="card-internal-member-overrides">- <div class="head">- <h2 id="internal-member-overrides-title">Internal member overrides</h2>- <p id="internal-member-overrides-help">- Treat listed Slack users as internal members, including guests and people missing from the- directory. This grants internal-member access, not just permission to mention the agent. Rooms- containing only internal members may use organization credentials. Add only trusted colleagues.- Enter one Slack user ID or Slack-profile email per line (commas also accepted).- </p>- </div>- <div class="body">- <textarea- id="internal-member-overrides"- rows="4"- aria-labelledby="internal-member-overrides-title"- aria-describedby="internal-member-overrides-help internal-member-overrides-count"- spellcheck="false"- placeholder="[email protected] U0123ABCDE"- style="width: 100%; max-width: 560px; font-family: var(--mono, monospace)"- ></textarea>- <small class="muted" id="internal-member-overrides-count"></small>- </div>- <div class="foot">- <button class="primary" data-save="internal-member-overrides">Apply</button- ><span class="status" id="st-internal-member-overrides"></span>- </div>- </section>- <section class="card sv-customize setting-row hidden" id="card-org-ambient">- <div class="head">- <h2>Ambient behavior</h2>- <p>- Org-wide, default on. When off, the agent never acts on overheard messages in any channel,- regardless of per-channel settings; it only responds to direct @mentions.- </p>- </div>- <div class="body">- <label class="setting-toggle">- <input type="checkbox" id="org-ambient" />- <span class="setting-switch" aria-hidden="true"></span>- <span class="setting-copy"- ><strong>Allow ambient behavior</strong- ><small- >Channels choose per-channel; without a choice, ambient defaults off in channels with more- than 8 members.</small- ></span- >- </label>- </div>- <div class="foot">- <button class="primary" data-save="org-ambient">Apply</button- ><span class="status" id="st-org-ambient"></span>- </div>- </section>- <section class="card sv-customize setting-row hidden" id="card-channel-header-pin-default">- <div class="head">- <h2>Channel pinned header</h2>- <p>- Org-wide, default off. When on, the agent posts and pins a small header message (naming the model- in use) in every Slack channel it's in. Channels can still override it either way from their- project page.- </p>- </div>- <div class="body">- <label class="setting-toggle">- <input type="checkbox" id="channel-header-pin-default" />- <span class="setting-switch" aria-hidden="true"></span>- <span class="setting-copy"- ><strong>Pin the header by default</strong- ><small- >Applies to channels without an explicit choice; flipping this updates existing channels- within a moment.</small- ></span- >- </label>- </div>- <div class="foot">- <button class="primary" data-save="channel-header-pin-default">Apply</button- ><span class="status" id="st-channel-header-pin-default"></span>- </div>- </section>+ <template data-governance-card="card-sharing-posture"></template>+ <template data-governance-card="card-egress"></template>+ <template data-integrations-card="card-external-slack"></template>+ <template data-integrations-card="card-internal-member-overrides"></template>+ <template data-integrations-card="card-channel-header-pin-default"></template>+ <template data-integrations-card="card-ack-emoji"></template><div class="governance-group" id="governance-intelligence"><h2>Models & browsing</h2><p>The models, browser runtime, and organization context available on future turns.</p></div>- <section class="card sv-models hidden" id="card-base-model">- <div class="head">- <h2>Default runtime</h2>- <p>The harness, model, and reasoning level used across your organization unless overridden.</p>- </div>- <div class="body">- <div class="model-runtime-fields">- <div>- <label for="base-harness">Harness</label>- <select id="base-harness"></select>- </div>- <div>- <label for="base-model">Model</label>- <select id="base-model"></select>- </div>- <div>- <label for="base-effort">Reasoning level</label>- <select id="base-effort"></select>- </div>- </div>- <label class="setting-toggle" id="base-fast-mode-control" style="display: none">- <input type="checkbox" id="base-fast-mode" />- <span class="setting-switch" aria-hidden="true"></span>- <span class="setting-copy"- ><strong>Fast mode</strong><small>Only available for supported models.</small></span- >- </label>- </div>- <div class="foot">- <button class="primary" data-save="runtime">Apply</button- ><span class="status" id="st-runtime"></span>- </div>- </section>- <section class="card sv-models hidden" id="card-webui-models">- <div class="head">- <h2>Enabled models</h2>- </div>- <div class="body">- <div class="model-add-row">- <div class="model-add-field">- <label for="webui-models-add">Add a model</label>- <select id="webui-models-add">- <option value="">Choose a model…</option>- </select>- </div>- <button type="button" id="webui-models-add-button" disabled>+ Add model</button>- </div>- <div id="webui-models-list" class="model-list">- <p id="webui-models-empty" class="hint">No additional models enabled.</p>- </div>- </div>- <div class="foot">- <button class="primary" data-save="webui-models">Save</button- ><span class="status" id="st-webui-models"></span>- </div>- </section>- <section class="card sv-customize setting-row hidden" id="card-branding">- <div class="head">- <h2>Branding</h2>- <p>- How this org's surfaces look. Accent is the highlight color across the web UI, admin, and portal;- icon is the square image beside the name in the top left; mark is a 1–2 character badge drawn over- that icon instead; label is the assistant's name everywhere it introduces itself; organization- name is how the assistant refers to this org. Leave a field blank to use the deployment default.- </p>- </div>- <div class="body">- <label for="branding-accent">Accent color</label>- <input type="text" id="branding-accent" style="max-width: 200px" placeholder="#4f46e5" />- <label for="branding-mark-url" style="margin-top: 12px">Brand icon (https image URL)</label>- <input- type="url"- id="branding-mark-url"- style="max-width: 420px"- maxlength="500"- placeholder="https://example.com/icon.png"- />- <label for="branding-mark" style="margin-top: 12px">Brand mark (1–2 chars)</label>- <input type="text" id="branding-mark" style="max-width: 200px" maxlength="2" placeholder="A" />- <label for="branding-self-label" style="margin-top: 12px">Assistant label</label>- <input- type="text"- id="branding-self-label"- style="max-width: 320px"- maxlength="40"- placeholder="Agent"- />- <label for="branding-org-name" style="margin-top: 12px">Organization name</label>- <input- type="text"- id="branding-org-name"- style="max-width: 320px"- maxlength="40"- placeholder="Acme Corp"- />- </div>- <div class="foot">- <button class="primary" data-save="branding">Apply</button- ><span class="status" id="st-branding"></span>- </div>- </section>- <section class="card sv-customize setting-row hidden" id="card-people-directory">- <div class="head">- <h2>People directory</h2>- <p>- Public page or URL where the agent can look up a person's current role or title (e.g.- https://www.example.com/people). Used when getting to know someone. Leave blank to disable.- </p>- </div>- <div class="body">- <label for="people-directory-url">Directory URL</label>- <input- type="text"- id="people-directory-url"- style="max-width: 480px"- placeholder="https://www.example.com/people"- />- </div>- <div class="foot">- <button class="primary" data-save="people-directory-url">Apply</button- ><span class="status" id="st-people-directory-url"></span>- </div>- </section>- <section class="card sv-customize hidden" id="card-ack-emoji">- <div class="head">- <h2>Slack ack emoji</h2>- <p>- The emoji the bot may react with to acknowledge a Slack message, org-wide. Add names from the- workspace's emoji (custom and standard). Remove every chip to restore the built-in rotation.- </p>- </div>- <div class="body">- <div id="ack-emoji-chips" style="display: flex; flex-wrap: wrap; gap: 6px; align-items: center">- <span style="position: relative; display: inline-block">- <button type="button" id="ack-emoji-open" class="ghost" aria-haspopup="true">- + Add emoji- </button>- <div class="emoji-picker hidden" id="ack-emoji-picker">- <input type="text" id="ack-emoji-search" placeholder="Search emoji" autocomplete="off" />- <div class="emoji-picker-scroll" id="ack-emoji-results"></div>- </div>- </span>- </div>- </div>- <div class="foot">- <button class="primary" data-save="ack-emoji">Save</button- ><span class="status" id="st-ack-emoji"></span>- </div>- </section>- <section class="card sv-customize setting-row hidden" id="card-turn-wall-clock">- <div class="head">- <h2>Turn budget</h2>- <p>- Maximum wall-clock time for a turn, org-wide. Use 60–86400 seconds, 0 for no limit, or leave blank- to use the deployment default.- </p>- </div>- <div class="body">- <label for="turn-wall-clock">Seconds</label>- <input- type="number"- id="turn-wall-clock"- min="0"- max="86400"- step="1"- style="max-width: 160px"- placeholder="Deployment default"- />- </div>- <div class="foot">- <button class="primary" data-save="turn-wall-clock">Apply</button- ><span class="status" id="st-turn-wall-clock"></span>- </div>- </section>- <section class="card sv-customize hidden" id="card-feature-flags">- <div class="head">- <h2>Feature flags</h2>- <p>Enable a feature for selected scopes. Changes apply on the next turn without a restart.</p>- </div>- <div class="body">- <div id="feature-flag-list" class="hint">No enabled scopes.</div>- <div class="editor-grid" style="margin-top: 16px">- <label- >Feature- <select id="feature-flag-name">- <option value="command_scoped_credentials">Command-scoped credentials</option>- <option value="persistent_subagents">Persistent subagents</option>- </select>- </label>- <label- >Scope ID- <input id="feature-flag-scope" placeholder="personal:principal-id" autocomplete="off" />- <span class="hint">For persistent subagents, use the person’s personal scope.</span>- </label>- </div>- </div>- <div class="foot">- <button class="primary" id="feature-flag-enable">+ Add flag</button>- <span class="status" id="st-feature-flags"></span>- </div>- </section>+ <template data-settings-card="card-base-model"></template>+ <template data-settings-card="card-webui-models"></template>+ <template data-settings-card="card-branding"></template>+ <template data-settings-card="card-feature-flags"></template><div class="governance-group" id="governance-credentials"><h2>Credentials</h2><p>Shared server-side authority available to agents in this organization.</p></div>- <section class="card sv-credentials" id="card-service-credentials">- <div class="head">- <h2>Shared service credentials</h2>- <p>- The agent calls these services by proxy such that secrets never reach a sandbox. Review the- complete effective capability (destination, authentication, methods, paths, and principals) before- saving.- </p>- </div>- <div class="body">- <div id="sc-list" class="hint" role="status" aria-live="polite">Loading credentials…</div>- </div>- <div- class="body hidden"- id="sc-editor"- style="border-top: 1px solid var(--border, #2a2a2a); padding-top: 12px"- >- <div class="sc-form-head">- <p class="hint" id="sc-form-title">Add a credential</p>- <span class="badge muted" id="sc-form-mode">New</span>- </div>- <div class="sc-semantics" aria-label="Blank value semantics">- <div>- <strong>Blank secret</strong- ><span id="sc-secret-semantics">New credentials require a secret.</span>- </div>- <div><strong>Blank method</strong><span>Uses the broker default: GET only.</span></div>- <div><strong>Blank paths</strong><span>Allows every path on the selected host.</span></div>- </div>- <div class="editor-grid">- <div>- <label style="display: block; margin-bottom: 8px"- >Slug <span class="hint">lowercase identifier</span- ><input- type="text"- id="sc-slug"- placeholder="credential-name"- autocomplete="off"- style="width: 100%"- /></label>- <label style="display: block; margin-bottom: 8px"- >Display name- <input type="text" id="sc-name" placeholder="Credential display name" style="width: 100%"- /></label>- <label style="display: block; margin-bottom: 8px"- >Delivery <span class="hint">how the secret is used</span>- <select id="sc-delivery" style="width: 100%">- <option value="broker">- Broker: core stamps it onto proxied HTTP calls; the secret never leaves core- </option>- <option value="env">- Sandbox env: injected into all-internal conversations under an env var (e.g. a- browser-provider key for the browse skill)- </option>- </select>- </label>- <label style="display: block; margin-bottom: 8px" class="sc-env-only hidden"- >Env var <span class="hint">UPPER_SNAKE_CASE; the skill reads this</span- ><input- type="text"- id="sc-envkey"- placeholder="STEEL_API_KEY"- autocomplete="off"- style="width: 100%"- /></label>- <label style="display: block; margin-bottom: 8px" class="sc-broker-only"- >Destination host <span class="hint">bare hostname only</span- ><input- type="text"- id="sc-host"- placeholder="service.example"- autocomplete="off"- style="width: 100%"- /></label>- <label style="display: block; margin-bottom: 8px"- >Secret- <input- type="password"- id="sc-secret"- autocomplete="new-password"- placeholder="Write-only secret"- style="width: 100%"- /></label>- <p class="field-hint" id="sc-secret-hint">- The secret is write-only. It cannot be viewed after saving.- </p>- <div class="sc-broker-only" style="display: flex; gap: 10px">- <label style="display: block; margin-bottom: 8px; flex: 1"- >Authentication header <span class="hint">blank = Authorization</span- ><input type="text" id="sc-header" placeholder="Default: Authorization" style="width: 100%"- /></label>- <label style="display: block; margin-bottom: 8px; flex: 1"- >Value prefix <span class="hint">blank = Bearer</span- ><input type="text" id="sc-scheme" placeholder="Default: Bearer" style="width: 100%"- /></label>- </div>- <label style="display: block; margin-bottom: 8px" class="sc-broker-only"- >Allowed HTTP methods <span class="hint">comma-separated; blank = GET</span- ><input type="text" id="sc-methods" placeholder="GET" style="width: 100%"- /></label>- <label style="display: block; margin-bottom: 8px" class="sc-broker-only"- >Allowed path prefixes <span class="hint">one per line; blank = any path</span- ><textarea id="sc-paths" placeholder="/allowed/path/"></textarea>- </label>- <label- style="display: flex; align-items: center; gap: 10px; cursor: pointer; margin-bottom: 10px"- ><input type="checkbox" id="sc-enabled" style="width: auto" checked /> Credential is- enabled</label- >- <label- class="sc-broker-only"- style="display: flex; align-items: center; gap: 10px; cursor: pointer; margin-bottom: 10px"- ><input type="checkbox" id="sc-deployments" style="width: auto" checked /> Published apps may- use it, acting as their publisher</label- >- <p class="hint sc-broker-only" style="margin-bottom: 6px">Principals with access</p>- <p class="hint sc-env-only hidden" style="margin-bottom: 6px">- Access: every all-internal conversation. Env delivery is not gated by grants. Rooms with- externals get nothing, everyone else gets the env var.- </p>- <label- class="sc-broker-only"- style="display: flex; align-items: center; gap: 8px; cursor: pointer; margin-bottom: 6px"- ><input- type="radio"- name="sc-share"- id="sc-share-org"- value="org"- style="width: auto"- checked- />- Everyone in this organization</label- >- <label- class="sc-broker-only"- style="display: flex; align-items: center; gap: 8px; cursor: pointer; margin-bottom: 6px"- ><input type="radio" name="sc-share" value="people" style="width: auto" /> Only selected- people or teams</label- >- <input- type="text"- id="sc-people"- class="sc-broker-only"- list="sc-people-options"- placeholder="Principal IDs, comma-separated"- style="width: 100%; display: none"- />- <datalist id="sc-people-options"></datalist>- <div class="sc-picker sc-broker-only" id="sc-picker">- <input- type="text"- id="sc-picker-search"- placeholder="Search people to grant access…"- autocomplete="off"- spellcheck="false"- />- <div class="sc-picker-list" id="sc-picker-list" hidden></div>- </div>- <div class="identity-chips sc-broker-only" id="sc-people-chips"></div>- </div>- <aside class="editor-panel" aria-live="polite">- <h3>Effective capability</h3>- <dl class="capability-summary">- <div>- <dt>State</dt>- <dd id="sc-cap-state">Enabled</dd>- </div>- <div>- <dt>Host</dt>- <dd id="sc-cap-host">Not set</dd>- </div>- <div>- <dt>Auth</dt>- <dd id="sc-cap-auth">Authorization header · no prefix</dd>- </div>- <div>- <dt>Methods</dt>- <dd id="sc-cap-methods">GET</dd>- </div>- <div>- <dt>Paths</dt>- <dd id="sc-cap-paths">Any path</dd>- </div>- <div>- <dt>Access</dt>- <dd id="sc-cap-principals">Everyone in this organization</dd>- </div>- <div>- <dt>Secret</dt>- <dd id="sc-cap-secret">Required before first save</dd>- </div>- </dl>- </aside>- </div>- </div>- <div class="foot">- <button type="button" class="viewlink" data-viewlink="audit">View usage ›</button- ><button type="button" id="sc-add">+ Add credential</button- ><button class="primary hidden" id="sc-save">Save credential</button- ><button class="hidden" id="sc-reset">Cancel</button- ><span class="status" id="st-service-credentials"></span>- </div>- </section>+ <template data-settings-card="card-service-credentials"></template></div></div></div><div id="view-connectors" class="hidden">- <section class="card" id="card-connectors">- <div class="head">- <h2>OAuth apps</h2>- <p>- Each connector needs its own OAuth app's client ID and secret before anyone can link it. A connector- stays hidden in everyone's web UI until you set its client here. The secret is write-only and never- displayed. Applies org-wide.- </p>- </div>- <div class="body"><div id="conn-list" class="hint">No connectors configured.</div></div>- <div- class="body hidden"- id="conn-editor"- style="border-top: 1px solid var(--border, #2a2a2a); padding-top: 12px"- >- <div class="sc-form-head">- <p class="hint" id="conn-form-title">Add a connector</p>- <span class="badge muted" id="conn-form-mode">New</span>- </div>- <label style="display: block; margin-bottom: 8px"- >Connector- <select id="conn-provider" style="width: 100%"></select- ></label>- <div id="conn-guide" class="hint" style="margin: 0 0 12px"></div>- <label style="display: block; margin-bottom: 8px"- >Client ID- <input- type="text"- id="conn-client-id"- autocomplete="off"- placeholder="OAuth client ID"- style="width: 100%"- /></label>- <label style="display: block; margin-bottom: 8px"- >Client secret- <input- type="password"- id="conn-client-secret"- autocomplete="off"- placeholder="(write-only)"- style="width: 100%"- /></label>- <p class="field-hint" id="conn-secret-hint">- Secret values are write-only and will not be displayed after saving.- </p>- <label style="display: flex; align-items: center; gap: 10px; cursor: pointer; margin-bottom: 10px"- ><input type="checkbox" id="conn-enabled" style="width: auto" checked /> Enabled</label- >- </div>- <div class="foot">- <button type="button" id="add-oauth-app">+ Add OAuth app</button- ><button class="primary hidden" id="conn-save">Save connector</button- ><button class="hidden" id="conn-reset">Cancel</button><span class="status" id="st-connectors"></span>- </div>- </section>- <section class="card" id="card-slack-installation">- <div class="head">- <h2>Slack</h2>- </div>- <div class="body">- <div class="slack-connection">- <div class="slack-connection-info">- <h3 id="slack-installation-state">Connect your workspace</h3>- <p class="hint" id="slack-installation-description">Add the QM app to get started.</p>- </div>- <div class="slack-connection-actions">- <button class="hidden" id="slack-installation-start">- <svg width="20" height="20" viewBox="0 0 127 127" aria-hidden="true" focusable="false">- <path- d="M27.2 80c0 7.3-5.9 13.2-13.2 13.2C6.7 93.2.8 87.3.8 80c0-7.3 5.9-13.2 13.2-13.2h13.2V80zm6.6 0c0-7.3 5.9-13.2 13.2-13.2 7.3 0 13.2 5.9 13.2 13.2v33c0 7.3-5.9 13.2-13.2 13.2-7.3 0-13.2-5.9-13.2-13.2V80z"- fill="#E01E5A"- />- <path- d="M47 27c-7.3 0-13.2-5.9-13.2-13.2C33.8 6.5 39.7.6 47 .6c7.3 0 13.2 5.9 13.2 13.2V27H47zm0 6.7c7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2H13.9C6.6 60.1.7 54.2.7 46.9c0-7.3 5.9-13.2 13.2-13.2H47z"- fill="#36C5F0"- />- <path- d="M99.9 46.9c0-7.3 5.9-13.2 13.2-13.2 7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2H99.9V46.9zm-6.6 0c0 7.3-5.9 13.2-13.2 13.2-7.3 0-13.2-5.9-13.2-13.2V13.8C66.9 6.5 72.8.6 80.1.6c7.3 0 13.2 5.9 13.2 13.2v33.1z"- fill="#2EB67D"- />- <path- d="M80.1 99.8c7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2-7.3 0-13.2-5.9-13.2-13.2V99.8h13.2zm0-6.6c-7.3 0-13.2-5.9-13.2-13.2 0-7.3 5.9-13.2 13.2-13.2h33.1c7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2H80.1z"- fill="#ECB22E"- />- </svg>- <span id="slack-installation-start-label">Add to Slack</span>- </button>- <button class="danger hidden" id="slack-installation-delete">Disconnect</button>- </div>- </div>- <details id="slack-own-app-guide">- <summary>- <span id="slack-own-app-label">Use your own Slack app</span>- <span class="slack-guide-arrow" aria-hidden="true">›</span>- </summary>- <p>- Give your bot its own name and identity. Start with our preconfigured manifest, then connect your- app below.- </p>- <ol>- <li>- <a- id="slack-installation-create"- href="https://api.slack.com/apps?new_app=1"- target="_blank"- rel="noopener noreferrer"- >Create your preconfigured Slack app ↗</a- >. Choose your company workspace, review the permissions, and click <strong>Create</strong>. The- manifest sets up the bot, message events, buttons, and Socket Mode for you.- </li>- <li>- In <strong>OAuth & Permissions</strong>, click <strong>Install to Workspace</strong> and- approve access. Copy the <strong>Bot User OAuth Token</strong> starting with <code>xoxb-</code>.- </li>- <li>- In <strong>Basic Information → App-Level Tokens</strong>, click- <strong>Generate Token and Scopes</strong>. Name it <strong>QM connection</strong>, add- <code>connections:write</code>, and generate it. Copy the token starting with <code>xapp-</code>.- </li>- <li>- Paste both tokens below and click <strong>Validate and connect</strong>. Keep this page open while- you work in Slack. Tokens must come from the same app.- </li>- <li>- Invite your new bot to a channel, mention it, then send it a DM to check both surfaces. It only- sees conversations it can access; older history may be incomplete.- </li>- </ol>- <p class="hint">- Replacing a connected app changes the bot identity. Invite the new bot to your channels and start a- new DM with it. The old app stays installed until a workspace admin removes it.- <span id="slack-hosted-switch" class="hidden"- >To switch back to the QM app, disconnect here first, then choose Add to Slack.</span- >- </p>- <button type="button" id="slack-enter-tokens">I have both tokens</button>- <div class="hidden" id="slack-token-editor">- <label style="display: block; margin-bottom: 8px"- >Bot User OAuth Token- <input- type="password"- id="slack-bot-token"- autocomplete="off"- placeholder="xoxb-…"- style="width: 100%"- /></label>- <label style="display: block; margin-bottom: 8px"- >App-Level Token- <input- type="password"- id="slack-app-token"- autocomplete="off"- placeholder="xapp-…"- style="width: 100%"- /></label>- <p class="field-hint">- Use an app-level token with <code>connections:write</code>. Saving activates or reloads the Slack- surface within a few seconds.- </p>- <button class="primary hidden" id="slack-installation-save">Validate and connect</button>- </div>- </details>- <span class="status" role="status" id="st-slack-installation"></span>- </div>- </section>+ <template data-integrations-card="card-connectors"></template>+ <template data-integrations-card="card-slack-installation"></template></div><div id="view-design" class="hidden"></div>@@ -7732,54 +6583,11 @@</div></dialog>- <dialog class="custom-provider-dialog" id="custom-provider-dialog" aria-labelledby="custom-provider-title">- <div class="project-dialog-head">- <div>- <h2 id="custom-provider-title">Add custom provider</h2>- <p>Connect an OpenAI Chat Completions, OpenAI Responses, or Anthropic Messages endpoint.</p>- </div>- <button class="project-icon-button" type="button" id="custom-provider-close" aria-label="Close">×</button>- </div>- <div class="custom-provider-form">- <label>Provider id (slug)<input id="custom-provider-id" autocomplete="off" placeholder="litellm" /></label>- <label>Display name<input id="custom-provider-name" autocomplete="off" placeholder="LiteLLM" /></label>- <label- >Protocol<select id="custom-provider-protocol">- <option value="openai">OpenAI Chat Completions</option>- <option value="openai-responses">OpenAI Responses</option>- <option value="anthropic">Anthropic Messages</option>- </select></label- >- <label- >Base URL<input id="custom-provider-url" autocomplete="off" placeholder="https://gateway.internal/v1"- /></label>- <label class="custom-provider-key"- >API key<input- type="password"- id="custom-provider-key"- autocomplete="off"- placeholder="Write-only; blank on edit keeps the stored key"- /></label>- <label class="custom-provider-models"- >Models <span class="label-detail">one per line: id | name | context | max tokens</span- ><textarea- id="custom-provider-models"- rows="4"- placeholder="deepseek-chat | DeepSeek V3.2 | 128000 | 8192"- ></textarea>- </label>- <label class="inline custom-provider-validation"- ><input type="checkbox" id="custom-provider-validate" checked /> Validate the key against the endpoint</label- >- <span class="status" id="st-custom-provider" aria-live="polite"></span>- </div>- <div class="project-dialog-actions">- <button type="button" id="custom-provider-cancel">Cancel</button- ><button class="primary" id="custom-provider-save">Save provider</button>- </div>- </dialog>+ <template data-settings-card="custom-provider-dialog"></template><script>+ "__GOVERNANCE_UI__";+ governanceUI.mountCards();const themeMedia = window.matchMedia("(prefers-color-scheme: dark)");function syncAdminTheme() {const saved = localStorage.getItem("theme") || "system";@@ -7793,16 +6601,10 @@if (event.key === "theme") syncAdminTheme();});const $ = (id) => document.getElementById(id);- const EFFECTS = ["allow", "deny", "require_approval"];const EFFECT_LABELS = { allow: "Allow", deny: "Deny", require_approval: "Require approval" };- const CUSTOM_PROVIDER_PROTOCOL_LABELS = {- openai: "OpenAI Chat Completions",- "openai-responses": "OpenAI Responses",- anthropic: "Anthropic Messages",- };const SECTIONS = [{- views: ["governance", "models", "credentials", "connectors", "customize", "users"],+ views: ["governance", "models", "credentials", "connectors", "slack-settings", "customize", "users"],},{label: "Logs",@@ -7816,39 +6618,11 @@];const VIEWS = [...SECTIONS.flatMap((s) => s.views), "onboarding", "user", "ackemoji", "keychain"];- function paritySubsection(card) {- card.classList.remove("card", "sv-governance", "sv-models", "sv-credentials", "sv-customize");- card.classList.add("parity-subsection");- const save = card.querySelector("[data-save]");- if (save) card.dataset.saveScope = save.dataset.save;- return card;- }- function parityGroup(id, title, subview, cards) {- const section = document.createElement("section");- section.className = "card " + subview;- section.id = id;- const head = document.createElement("div");- head.className = "head";- const heading = document.createElement("h2");- heading.textContent = title;- head.appendChild(heading);- const body = document.createElement("div");- body.className = "body";- cards.forEach((card) => body.appendChild(paritySubsection(card)));- section.append(head, body);- return section;- }function prepareParityCards() {const content = document.querySelector("#view-governance .governance-content");const anchor = $("governance-credentials");const layout = content.parentElement;- const channelDefaults = parityGroup("card-channel-defaults", "Channel defaults", "sv-customize", [- $("card-org-ambient"),- $("card-channel-header-pin-default"),- ]);- [$("card-approval-grant-modes"), $("card-ack-emoji")].forEach((card) =>- card.classList.add("reference-omitted"),- );+ $("card-approval-grant-modes").classList.add("reference-omitted");const providers = document.createElement("section");providers.className = "card sv-models";@@ -7856,11 +6630,7 @@providers.innerHTML ='<div class="head"><h2>Custom providers</h2><p>OpenAI Chat Completions, OpenAI Responses, and Anthropic Messages endpoints. Their models join the pickers above and below.</p></div><div class="body"><div class="tablewrap" id="model-custom-provider-table"><table><thead><tr><th>Provider</th><th>Protocol</th><th>Endpoint</th><th>Models</th><th>Key</th><th></th></tr></thead><tbody id="model-custom-provider-rows"></tbody></table></div><div id="custom-provider-summary" class="hint">Loading providers…</div></div><div class="foot"><button type="button" id="add-custom-provider">+ Add provider</button></div>';- const governanceAmbient = document.createElement("section");- governanceAmbient.className = "card sv-governance hidden";- governanceAmbient.id = "card-governance-org-ambient";- governanceAmbient.innerHTML =- '<div class="head"><h2>Ambient reply policy</h2><p>@-mentions are always answered. Each ambient decision is recorded in the judgments log.</p><button type="button" class="viewlink" data-viewlink="judgments">View judgment log ›</button></div><div class="body"><select id="governance-org-ambient" data-choice-state hidden><option value="on">Agent judges all messages and replies when useful</option><option value="off">Agent does not read messages or reply unless @-mentioned</option></select><div class="choice-stack"><label class="posture-choice"><input type="radio" name="ambient-reply-choice" value="on" data-choice-for="governance-org-ambient"><span><strong>Reply when useful</strong><small>Agent judges all messages and replies when useful</small></span></label><label class="posture-choice"><input type="radio" name="ambient-reply-choice" value="off" data-choice-for="governance-org-ambient"><span><strong>Only when mentioned</strong><small>Agent does not read messages or reply unless @-mentioned</small></span></label></div></div><div class="foot"><button type="button" class="primary" id="governance-org-ambient-save" disabled>Apply</button><span class="status" id="st-governance-org-ambient"></span></div>';+ const governanceAmbient = governanceUI.createCard("card-governance-org-ambient");$("card-command-policy").after(governanceAmbient);const keychains = document.createElement("section");@@ -7876,9 +6646,6 @@$("card-webui-models"),$("card-soul"),$("card-branding"),- $("card-people-directory"),- channelDefaults,- $("card-turn-wall-clock"),$("card-feature-flags"),$("card-service-credentials"),keychains,@@ -7911,7 +6678,14 @@builtIns.id = "card-built-in-connectors";builtIns.innerHTML ='<div class="head"><h2>Built-in connectors</h2></div><div class="body" id="built-in-connectors">Loading connectors…</div>';- connectorView.insertBefore($("card-slack-installation"), $("card-connectors"));+ $("card-slack-installation").classList.add("sv-slack-settings");+ [+ "card-slack-installation",+ "card-external-slack",+ "card-internal-member-overrides",+ "card-channel-header-pin-default",+ "card-ack-emoji",+ ].forEach((id) => content.appendChild($(id)));connectorView.appendChild(builtIns);document.querySelectorAll("#view-governance section.card > .foot > .viewlink").forEach((link) => {link.closest("section.card").querySelector(":scope > .head").appendChild(link);@@ -7957,8 +6731,8 @@if (!dialog.open) dialog.showModal();}- let governanceOrgAmbientSaved = "on";document.querySelectorAll("[data-choice-for]").forEach((input) => {+ if (input.closest(".sv-governance, .sv-slack-settings, .sv-models, .sv-customize")) return;input.onchange = () => {const select = $(input.dataset.choiceFor);select.value = input.value;@@ -7967,6 +6741,7 @@};});document.querySelectorAll("[data-checkbox-for]").forEach((input) => {+ if (input.closest(".sv-slack-settings")) return;input.onchange = () => {const checkbox = $(input.dataset.checkboxFor);checkbox.checked = input.value === "on";@@ -7974,25 +6749,6 @@checkbox.dispatchEvent(new Event("change", { bubbles: true }));};});- $("governance-org-ambient").onchange = () => {- $("org-ambient").checked = $("governance-org-ambient").value === "on";- $("org-ambient").dispatchEvent(new Event("input", { bubbles: true }));- $("governance-org-ambient-save").disabled = $("governance-org-ambient").value === governanceOrgAmbientSaved;- };- $("governance-org-ambient-save").onclick = () => {- sectionButton("org-ambient")?.click();- $("governance-org-ambient-save").disabled = true;- };- const orgAmbientStatus = $("st-org-ambient");- new MutationObserver(() => {- $("st-governance-org-ambient").textContent = orgAmbientStatus.textContent;- $("st-governance-org-ambient").className = orgAmbientStatus.className;- if (- orgAmbientStatus.classList.contains("err") &&- $("governance-org-ambient").value !== governanceOrgAmbientSaved- )- $("governance-org-ambient-save").disabled = false;- }).observe(orgAmbientStatus, { childList: true, attributes: true, characterData: true, subtree: true });const VIEW_TITLE = {onboarding: "Onboarding",governance: "Governance",@@ -8015,7 +6771,8 @@crons: "Crons",deployments: "Apps",retention: "Retention",- slack: "Slack",+ slack: "Slack messages",+ "slack-settings": "Slack",judgments: "Judgments",ackemoji: "Ack emoji","design-system": "Design system",@@ -8044,6 +6801,7 @@"models","credentials","customize",+ "slack-settings",]);const ENDPOINT = { history: "sessions", files: "files", live: "runs" };const HISTORY_PAGE_SIZE = 50;@@ -8067,11 +6825,6 @@let memDraft = null;let memDraftScope = null;let cronDestinationEditId = null;- let ackEmojiNames = [];- let ackEmojiStandard = [];- let ackEmojiCatalog = {};- let ackEmojiCatalogLoaded = false;- let ackEmojiCatalogError = null;const transcriptVisibility = { thinking: true, toolResults: true };const API_BASE = "__ADMIN_BASE__";@@ -8166,6 +6919,15 @@const fmtPct = (n) => ((n || 0) * 100).toFixed(1) + "%";const statusTimers = new Map();function setStatus(id, msg, kind, sticky = false) {+ if (id === "st-service-credentials") {+ governanceUI.settings.credentialStatus(msg, kind || "");+ return;+ }+ const governanceKey = governanceUI.statusKey(id);+ if (governanceKey) {+ governanceUI.status(governanceKey, msg, kind || "");+ return;+ }const el = $(id);if (!el) return;if (statusTimers.has(id)) {@@ -8352,7 +7114,7 @@.replace(/[_-]/g, " ").replace(/\b\w/g, (m) => m.toUpperCase());function labelRole(role) {- return String(role || "").replace(/_/g, " ");+ return role === "org_admin" ? "admin" : String(role || "").replace(/_/g, " ");}function scopeKind(scopeId) {return String(scopeId || "").split(":")[0] || "scope";@@ -8405,157 +7167,18 @@return text.trim() || fallback;}}- function fileUploadBox() {- const box = document.createElement("div");- box.className = "file-upload";- const actions = document.createElement("div");- actions.className = "file-upload-actions";- const status = document.createElement("span");- status.className = "status muted";- const button = document.createElement("button");- button.type = "button";- button.className = "primary upload-button";- button.innerHTML =- '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 16V3m-5 5 5-5 5 5M4 15v5a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-5"/></svg><span>Upload</span>';- const input = document.createElement("input");- input.type = "file";- input.multiple = true;- input.className = "hidden";- let busy = false;- async function upload(files) {- const picked = [...files].filter((f) => f && f.size >= 0);- if (!picked.length || busy) return;- busy = true;- button.disabled = true;- uploadStatusMessage(- status,- "Uploading " + picked.length + " " + (picked.length === 1 ? "file" : "files") + "...",- "saving",- );- let uploaded = 0;- try {- for (const file of picked) {- const r = await fetch(API_BASE + "/api/files/upload?scope=" + encodeURIComponent(scope), {- method: "POST",- headers: {- "content-type": file.type || "application/octet-stream",- "x-file-name": encodeURIComponent(file.name || "file"),- "x-content-sha256": await fileSha256(file),- },- body: file,- });- if (!r.ok) throw new Error(uploadErrorMessage(await r.text(), "Upload failed (" + r.status + ")."));- uploaded += 1;- }- uploadStatusMessage(- status,- "Uploaded " + picked.length + " " + (picked.length === 1 ? "file" : "files") + ".",- "ok",- );- dataCache.clear();- await renderData();- } catch (err) {- const partial = uploaded ? "Uploaded " + uploaded + " of " + picked.length + " before failure. " : "";- uploadStatusMessage(status, partial + (err instanceof Error ? err.message : "Upload failed."), "err");- if (uploaded) {- dataCache.clear();- await renderData();- }- } finally {- busy = false;- button.disabled = false;- input.value = "";- box.classList.remove("dragging");- }- }- button.onclick = () => input.click();- input.onchange = () => upload(input.files || []);- const dragHasFiles = (e) => Array.from(e.dataTransfer?.types || []).includes("Files");- box.ondragenter = (e) => {- if (dragHasFiles(e)) {- e.preventDefault();- box.classList.add("dragging");- }- };- box.ondragover = (e) => {- if (dragHasFiles(e)) e.preventDefault();- };- box.ondragleave = (e) => {- if (!(e.relatedTarget instanceof Node) || !box.contains(e.relatedTarget)) box.classList.remove("dragging");- };- box.ondrop = (e) => {- if (!dragHasFiles(e)) return;- e.preventDefault();- box.classList.remove("dragging");- upload(e.dataTransfer.files || []);- };- actions.append(status, button, input);- box.append(actions);- return box;- }function fmtDuration(start, end) {if (start == null) return "-";return fmtMs((end ?? Date.now()) - start);}function table(headers, rows, emptyMsg) {- if (!rows.length) {- const p = document.createElement("p");- p.className = "empty";- p.textContent = emptyMsg;- return p;- }- const t = document.createElement("table");- const thead = document.createElement("thead");- const htr = document.createElement("tr");- headers.forEach((h) => {- const th = document.createElement("th");- if (h && h.nodeType) th.appendChild(h);- else th.textContent = h;- htr.appendChild(th);- });- thead.appendChild(htr);- t.appendChild(thead);- const tb = document.createElement("tbody");- rows.forEach((r) => {- const tr = document.createElement("tr");- r.forEach((cell) => {- const td = document.createElement("td");- renderCell(td, cell);- tr.appendChild(td);- });- tb.appendChild(tr);- });- t.appendChild(tb);- return tableWrap(t);+ return governanceUI.shared.node(governanceUI.shared.table(headers, rows, emptyMsg));}function dataCard(title, desc, node) {- const sec = document.createElement("section");- sec.className = "card";- const head = document.createElement("div");- head.className = "head";- const h = document.createElement("h2");- h.textContent = title;- head.appendChild(h);- if (desc) {- const p = document.createElement("p");- p.textContent = desc;- head.appendChild(p);- }- const body = document.createElement("div");- body.className = "body";- body.appendChild(node);- sec.appendChild(head);- sec.appendChild(body);- return sec;+ return governanceUI.shared.node(governanceUI.shared.card(title, desc, node));}function bareDataCard(node) {- const sec = document.createElement("section");- sec.className = "card";- const body = document.createElement("div");- body.className = "body";- body.appendChild(node);- sec.appendChild(body);- return sec;+ return governanceUI.shared.node(governanceUI.shared.bareCard(node));}function showView(which, label) {@@ -8674,8 +7297,9 @@const path = scopeInPath ? API_BASE + "/history/scopes/" + scopeSegment : API_BASE + "/history";return q ? path + "?" + q : path;}- if (st.view === "connectors" && st.setup === "slack") p.set("setup", "slack");- if (st.view === "connectors" && ["setup", "install", "connected"].includes(st.slack)) p.set("slack", st.slack);+ if (["connectors", "slack-settings"].includes(st.view) && st.setup === "slack") p.set("setup", "slack");+ if (["connectors", "slack-settings"].includes(st.view) && ["setup", "install", "connected"].includes(st.slack))+ p.set("slack", st.slack);if (st.scope && SCOPED.has(st.view)) p.set("scope", st.scope);if (st.view === "errors" && st.page > 1) p.set("page", st.page);if (st.principal) p.set("principal", st.principal);@@ -8719,7 +7343,7 @@else if (segs[1] === "scopes") pathScope = decodePathSegment(segs[2] ?? "");}const slackStep = ["setup", "install", "connected"].includes(p.get("slack"));- const raw = p.get("setup") === "slack" || slackStep ? "connectors" : p.get("view") || fromPath;+ const raw = p.get("setup") === "slack" || slackStep ? "slack-settings" : p.get("view") || fromPath;const v = raw === "skill-packs" ? "skills" : raw === "design" ? "design-system" : raw;const session = pathSession || p.get("session") || null;@@ -8758,6 +7382,7 @@let transcriptObserver = null;function render(st) {+ governanceUI.transcript.cancel();if (transcriptObserver) {transcriptObserver.disconnect();transcriptObserver = null;@@ -8775,6 +7400,7 @@$("app-view").classList.toggle("crons-view", view === "crons");$("app-view").classList.toggle("governance-view", isGovLike(view));document.body.dataset.subview = view;+ setGovernancePending(view === "governance" && governanceReadyScope !== scope);document.body.dataset.adminKit = ["crons","deployments",@@ -8793,6 +7419,7 @@"credentials","connectors","customize",+ "slack-settings","users","design-system",].includes(view)@@ -8814,6 +7441,7 @@);if (view === "onboarding") return void loadOnboarding();if (isGovLike(view)) {+ if (view === "slack-settings") void loadSlackInstallation();return void loadScope();}if (view === "connectors") return void loadConnectors();@@ -8827,7 +7455,7 @@renderCurrentData();}- const GOV_LIKE = new Set(["governance", "models", "credentials", "customize"]);+ const GOV_LIKE = new Set(["governance", "models", "credentials", "customize", "slack-settings"]);function isGovLike(v) {return GOV_LIKE.has(v);}@@ -8880,7 +7508,10 @@confirmLabel: "Discard and leave",danger: true,}).then((confirmed) => {- if (confirmed) commitGo(st);+ if (confirmed) {+ if (view === "governance") governanceReadyScope = null;+ commitGo(st);+ }});}function setView(v) {@@ -8894,23 +7525,6 @@document.querySelectorAll("[data-viewlink]").forEach((button) => {button.onclick = () => setView(button.dataset.viewlink);});- $("soul-history-link").onclick = () => {- $("card-soul").classList.add("is-editing");- $("soul-edit").textContent = "Cancel";- $("soul-history").scrollIntoView({ behavior: "smooth", block: "center" });- };- $("soul-edit").onclick = () => {- const card = $("card-soul");- const editing = card.classList.toggle("is-editing");- $("soul-edit").textContent = editing ? "Cancel" : "Edit";- if (editing) {- $("soul").focus();- return;- }- $("soul").value = soulSaved;- updateSoulWorkbench();- updateSectionDirty("soul");- };$("add-custom-provider").onclick = () => openCustomProviderEditor();$("onboarding-add-custom-provider").onclick = () => openCustomProviderEditor();function route() {@@ -9167,28 +7781,6 @@wrap.append(icon, clear);return wrap;}- function renderTranscriptHeaderControls(onChange) {- const controls = $("header-controls");- controls.textContent = "";- const checkbox = (label, key) => {- const wrap = document.createElement("label");- wrap.className = "header-check";- const input = document.createElement("input");- input.type = "checkbox";- input.checked = transcriptVisibility[key];- input.setAttribute("aria-label", "Show " + label);- input.onchange = () => {- transcriptVisibility[key] = input.checked;- onChange();- };- const prefix = document.createElement("span");- prefix.className = "header-check-prefix";- prefix.textContent = "Show ";- wrap.append(input, prefix, document.createTextNode(label));- return wrap;- };- controls.append(checkbox("thinking", "thinking"), checkbox("tool results", "toolResults"));- }function transcriptEntryHidden(entryTypes, hasDelivery, visibility = transcriptVisibility) {return ((!visibility.thinking && entryTypes.includes("thinking")) ||@@ -9236,62 +7828,7 @@}function denseList(items, rowOf, onOpen, emptyMsg) {- if (!items.length) {- const p = document.createElement("p");- p.className = "empty";- p.textContent = emptyMsg;- return p;- }- const list = document.createElement("div");- list.className = "dense-list";- items.forEach((it) => {- const r = rowOf(it);- const row = document.createElement(r.href ? "a" : "div");- row.className = "dense-row" + (r.cls ? " " + r.cls : "");- if (r.href) {- row.href = r.href;- if (r.target) {- row.target = r.target;- row.rel = "noopener";- }- } else {- row.tabIndex = 0;- row.setAttribute("role", "button");- }- if (r.icon) {- const ic = document.createElement("span");- ic.className = "dense-icon";- if (r.icon.nodeType) ic.appendChild(r.icon);- else ic.textContent = r.icon;- row.appendChild(ic);- }- const name = document.createElement("span");- name.className = "dense-name";- name.textContent = r.name;- row.appendChild(name);- const prev = document.createElement("span");- prev.className = "dense-preview";- if (r.preview && r.preview.nodeType) prev.appendChild(r.preview);- else prev.textContent = r.preview == null ? "" : r.preview;- row.appendChild(prev);- if (r.time != null) {- const tm = document.createElement("span");- tm.className = "dense-time";- tm.textContent = r.time;- row.appendChild(tm);- }- row.onclick = (e) => {- if (r.href && (r.target || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)) return;- if (r.href) e.preventDefault();- onOpen(it);- };- if (!r.href)- row.onkeydown = (e) => {- if (e.key === "Enter") onOpen(it);- };- list.appendChild(row);- });- return list;+ return governanceUI.shared.node(governanceUI.shared.denseList(items, rowOf, onOpen, emptyMsg));}const orgOwnView = () => orgWideView() && urlToState().own === "1";@@ -9361,7 +7898,7 @@}}- const FOCUS_REFRESH_EXEMPT = new Set(["governance", "connectors", "user"]);+ const FOCUS_REFRESH_EXEMPT = new Set(["governance", "connectors", "slack-settings", "user"]);window.addEventListener("focus", () => {if ($("app-view").classList.contains("hidden")) return;if (isGovLike(view) || FOCUS_REFRESH_EXEMPT.has(view)) return;@@ -9381,99 +7918,62 @@else renderData();});- let webuiModelIds = [];let loadedGovernanceScope = null;+ let governanceReadyScope = null;let loadedCommandPolicyPresent = false;- let governanceOverviewData = {};- let soulVersion = 0;- let soulSaved = "";- let soulHistory = [];let serviceCredDirectory = [];let serviceCredChannels = [];- function updateSoulWorkbench() {- const draft = $("soul").value;- $("soul-preview").textContent = soulSaved || "No saved instructions";- $("soul-saved").textContent = soulSaved || "No saved instructions";- $("soul-draft").textContent =- draft === soulSaved ? "No draft changes" : draft || "Instructions will be cleared";- $("soul-size").textContent =- draft.length.toLocaleString() +- " characters · about " +- Math.ceil(draft.length / 4).toLocaleString() +- " tokens";- $("soul-validation").textContent = draft.length >= 100000 ? "Maximum length reached" : "Draft valid";- }- function renderSoulHistory() {- const root = $("soul-history");- root.textContent = "";- const heading = document.createElement("h3");- heading.textContent = "Version history";- root.appendChild(heading);- if (!soulHistory.length) {- const empty = document.createElement("p");- empty.className = "hint";- empty.textContent = "History begins with the next saved revision.";- root.appendChild(empty);- return;- }- soulHistory.forEach((revision) => {- const row = document.createElement("div");- row.className = "soul-revision";- const meta = document.createElement("p");- meta.textContent = "Version " + revision.version;- const detail = document.createElement("small");- detail.textContent =- (revision.updatedBy || "Author unavailable") +- " · " +- (revision.updatedAt ? fmtTime(revision.updatedAt) : "Time unavailable");- meta.appendChild(detail);- const restore = document.createElement("button");- restore.type = "button";- restore.textContent = revision.version === soulVersion ? "Current" : "Restore";- restore.disabled = revision.version === soulVersion;- restore.onclick = async () => {- const immutable = { ...revision };- const targetScope = scope;- const expectedVersion = soulVersion;- const confirmed = await reviewGovernanceChange({- title: "Restore SOUL version " + immutable.version + "?",- subtitle: "The saved instructions from this revision will replace the current SOUL.",- facts: [- ["Scope", governanceScopeName(targetScope)],- ["Current", "Version " + expectedVersion],- ["Restore", "Version " + immutable.version],- ],- warning:- "This does not erase history. A new revision will be created, and future turns will use it immediately.",- confirmLabel: "Restore version " + immutable.version,- danger: true,- });- if (!confirmed) return;- restore.disabled = true;- setStatus("st-soul", "Restoring…", "saving", true);- const r = await api("PUT", "/api/scopes/" + encodeURIComponent(targetScope) + "/soul", {- content: immutable.content,- expectedVersion,- });- if (!r.ok) {- restore.disabled = false;- if (r.status === 409) await refreshSoulConflict();- return setStatus(- "st-soul",- r.status === 409- ? "SOUL changed; latest revision loaded and your draft was preserved."- : r.data?.message || "Restore failed.",- "err",- true,- );- }- await loadScope();+ governanceUI.settings.configureSoul({+ formatTime: fmtTime,+ restore: async (revision) => {+ const immutable = { ...revision };+ const targetScope = scope;+ const targetGeneration = governanceReq;+ const draftBefore = JSON.stringify(governanceUI.settings.collect("soul"));+ const expectedVersion = governanceUI.settings.collect("soul").expectedVersion;+ const confirmed = await reviewGovernanceChange({+ title: "Restore SOUL version " + immutable.version + "?",+ subtitle: "The saved instructions from this revision will replace the current SOUL.",+ facts: [+ ["Scope", governanceScopeName(targetScope)],+ ["Current", "Version " + expectedVersion],+ ["Restore", "Version " + immutable.version],+ ],+ warning:+ "This does not erase history. A new revision will be created, and future turns will use it immediately.",+ confirmLabel: "Restore version " + immutable.version,+ danger: true,+ });+ if (!confirmed || scope !== targetScope || governanceReq !== targetGeneration) return;+ setStatus("st-soul", "Restoring…", "saving", true);+ const r = await api("PUT", "/api/scopes/" + encodeURIComponent(targetScope) + "/soul", {+ content: immutable.content,+ expectedVersion,+ });+ if (scope !== targetScope || governanceReq !== targetGeneration) return;+ if (!r.ok) {+ if (r.status === 409) await refreshSoulConflict();+ return setStatus(+ "st-soul",+ r.status === 409+ ? "SOUL changed; latest revision loaded and your draft was preserved."+ : r.data?.message || "Restore failed.",+ "err",+ true,+ );+ }+ const fresh = await api("GET", "/api/scopes/" + encodeURIComponent(targetScope) + "?view=customize");+ if (scope !== targetScope || governanceReq !== targetGeneration) return;+ if (!fresh.ok)+ return setStatus("st-soul", "Restored, but the latest version could not be refreshed.", "warn", true);+ if (JSON.stringify(governanceUI.settings.collect("soul")) === draftBefore)+ governanceUI.settings.load(fresh.data, targetScope, "soul");+ else governanceUI.settings.refreshSoul(fresh.data);+ sectionSnapshots.set("soul", governanceUI.settings.states.get("soul").baseline);+ if (!governanceUI.settings.states.get("soul").dirty)setStatus("st-soul", "Version " + immutable.version + " restored as a new revision", "ok", true);- };- row.append(meta, restore);- root.appendChild(row);- });- }+ },+ });function setGovernanceStatus(id, value, detail, tone) {const root = $(id);root.dataset.tone = tone || "neutral";@@ -9481,7 +7981,6 @@root.querySelector(".detail").textContent = detail;}function renderGovernanceOverview(data) {- governanceOverviewData = { ...data };const posture = data.securityPosture || "auto";let postureTone = "ok";if (posture === "dangerous") postureTone = "danger";@@ -9521,27 +8020,6 @@egressDetail,enforcement.active ? "ok" : "warn",);- const capability = $("egress-capability");- capability.classList.toggle("hidden", !!enforcement.active);- let enforcementTitle = "Agent computer egress policy unavailable";- if (enforcement.reason === "control_plane_unconfigured") enforcementTitle = "Enforcement is not activated";- capability.querySelector("strong").textContent = enforcementTitle;- let enforcementSummary =- "Agent computers use " +- titleCase(enforcement.backend) +- ", which cannot enforce host restrictions on all outbound traffic. A configured egress proxy still applies policy to traffic sent through it.";- if (enforcement.reason === "control_plane_unconfigured") {- enforcementSummary = "Egress enforcement has not been activated for agent computers.";- }- capability.querySelector("span").textContent = enforcementSummary;- const egressCard = $("card-egress");- egressCard.classList.toggle("egress-disabled", !enforcement.active);- [$("egress"), $("egress-deny"), $("egress-add-deny"), $("egress-add-allow")].forEach(- (control) => (control.disabled = !enforcement.active),- );- const egressSave = sectionButton("egress");- egressSave.textContent = "Save policy";- egressSave.disabled = !enforcement.active;if ("externalSlackParticipants" in data) {const external = !!data.externalSlackParticipants;setGovernanceStatus(@@ -9589,6 +8067,13 @@$("environment-notice-open").onclick = () =>go({ view: "governance", scope: attachment.environmentId, session: null, page: 1 });}+ function setGovernancePending(pending) {+ const root = $("view-governance");+ if (pending) $("governance-loading").textContent = "Loading settings…";+ root.classList.toggle("governance-pending", pending);+ root.setAttribute("aria-busy", String(pending));+ $("governance-loading").classList.toggle("hidden", !pending);+ }let governanceReq = 0;async function loadScope() {const requestedScope = scope;@@ -9597,8 +8082,7 @@const scopeChanged = scope !== loadedGovernanceScope;if (requestedView === "credentials") {serviceCredList = [];- setServiceCredentialState("Loading credentials…");- $("sc-add").disabled = true;+ governanceUI.settings.credentialLoading();void loadPersonalKeychainSummary(requestId, requestedScope);}const r = await api(@@ -9608,11 +8092,17 @@if (requestId !== governanceReq || requestedScope !== scope || requestedView !== view) return;if (!r.ok) {if (requestedView === "credentials") {- setServiceCredentialState(+ governanceUI.settings.credentialLoading(r.status === 403 ? "You don't administer this scope." : "Could not load credentials.",true,);}+ if (requestedView === "governance" && governanceReadyScope !== requestedScope) {+ $("governance-loading").textContent =+ r.status === 403+ ? "You don't administer this scope."+ : "Could not load settings. Select Governance to retry.";+ }setStatus("st-policy",r.status === 403 ? "You don't administer this scope." : r.data?.message || "Failed to load.",@@ -9621,482 +8111,53 @@return;}const refreshModelChoices = [];- renderEnvironmentNotice(r.data);- renderGovernanceOverview(r.data);- syncGovernanceSectionNav();- loadedCommandPolicyPresent = r.data.commandPolicy != null;- renderPolicy(r.data.commandPolicy);- const showSecurityPosture = "securityPosture" in (r.data || {});- $("card-security-posture").classList.toggle("hidden", !showSecurityPosture);- if (showSecurityPosture) {- $("security-posture").value = r.data.securityPosture || "auto";- document- .querySelectorAll('[data-choice-for="security-posture"]')- .forEach((input) => (input.checked = input.value === $("security-posture").value));- }- const showAutoFlagger = scope.startsWith("org:") && "autoFlagger" in (r.data || {});- $("card-auto-flagger").classList.toggle("hidden", !showAutoFlagger);- if (scopeChanged) $("auto-flagger-test-result").hidden = true;- if (showAutoFlagger) {- const current = r.data.autoFlagger || r.data.autoFlaggerDefault;- const harness = $("auto-flagger-harness");- const model = $("auto-flagger-model");- const harnessOptions = [...(r.data.harnessOptions || [])];- if (!harnessOptions.includes(current.harnessId)) harnessOptions.push(current.harnessId);- const modelsByHarness = r.data.modelsByHarness || {};- harness.textContent = "";- harnessOptions.forEach((id) => {- const option = document.createElement("option");- option.value = id;- option.textContent = { pi: "Pi", opencode: "OpenCode", codex: "Codex", claude: "Claude Code" }[id] || id;- harness.appendChild(option);- });- harness.value = current.harnessId;- model.textContent = "";- const syncAutoFlaggerModels = () => {- const options = [...(modelsByHarness[harness.value] || [])];- const prior = model.value || current.modelId;- if (harness.value === current.harnessId && !options.some((entry) => entry.id === current.modelId)) {- options.push({ id: current.modelId, name: current.modelId + " (configured; unavailable)" });- }- model.textContent = "";- options.forEach((entry) => {- const option = document.createElement("option");- option.value = entry.id;- option.textContent = entry.name + " (" + entry.id + ")";- model.appendChild(option);- });- model.value = options.some((entry) => entry.id === prior) ? prior : (options[0] || {}).id || "";- };- harness.oninput = syncAutoFlaggerModels;- refreshModelChoices.push(syncAutoFlaggerModels);- syncAutoFlaggerModels();- $("auto-flagger-rubric").value = current.rubric;+ if (requestedView === "governance") {+ renderEnvironmentNotice(r.data);+ renderGovernanceOverview(r.data);+ syncGovernanceSectionNav();+ loadedCommandPolicyPresent = r.data.commandPolicy != null;+ governanceUI.load(r.data, scope);+ if (scopeChanged) $("auto-flagger-test-result").hidden = true;}- const showSharingPosture = "sharingPosture" in (r.data || {});- $("card-sharing-posture").classList.toggle("hidden", !showSharingPosture);- if (showSharingPosture) renderSharingPosture(r.data);- const showGrantModes = "approvalGrantModes" in (r.data || {});- $("card-approval-grant-modes").classList.toggle("hidden", !showGrantModes);- if (showGrantModes) {- const gm = r.data.approvalGrantModes || { session: true, always: true };- $("approval-grant-session").checked = gm.session !== false;- $("approval-grant-always").checked = gm.always !== false;- }- soulVersion = r.data.soulVersion || 0;- soulSaved = r.data.soul || "";- soulHistory = r.data.soulHistory || [];- $("card-soul").classList.remove("is-editing");- $("soul-edit").textContent = "Edit";- $("soul").value = soulSaved;- $("soul-ver").textContent = soulVersion ? "Saved version " + soulVersion : "No saved revision";- updateSoulWorkbench();- renderSoulHistory();- $("card-ambient-policy").classList.toggle("hidden", !("ambientPolicy" in r.data));- renderAmbientPolicy(r.data.ambientPolicy);- populateEgress(r.data.egress);- const showExternalSlack = scope.startsWith("org:") && "externalSlackParticipants" in r.data;- $("card-external-slack").classList.toggle("hidden", !showExternalSlack);- if (showExternalSlack) {- $("external-slack-participants").checked = !!r.data.externalSlackParticipants;- document- .querySelectorAll('[data-checkbox-for="external-slack-participants"]')- .forEach((input) => (input.checked = input.value === (r.data.externalSlackParticipants ? "on" : "off")));- }- const showInternalOverrides = scope.startsWith("org:") && "internalMemberOverrides" in r.data;- $("card-internal-member-overrides").classList.toggle("hidden", !showInternalOverrides);- if (showInternalOverrides) {- const members = Array.isArray(r.data.internalMemberOverrides) ? r.data.internalMemberOverrides : [];- $("internal-member-overrides").value = members.join("\n");- $("internal-member-overrides-count").textContent = members.length- ? members.length + " override" + (members.length === 1 ? "" : "s")- : "No overrides configured.";- }- const showOrgAmbient = scope.startsWith("org:") && "orgAmbient" in r.data;- $("card-org-ambient").classList.toggle("hidden", !showOrgAmbient);- $("card-governance-org-ambient").classList.toggle("hidden", !showOrgAmbient);- if (showOrgAmbient) {- $("org-ambient").checked = r.data.orgAmbient !== false;- governanceOrgAmbientSaved = r.data.orgAmbient === false ? "off" : "on";- $("governance-org-ambient").value = governanceOrgAmbientSaved;- document.querySelectorAll('[data-choice-for="governance-org-ambient"]').forEach((input) => {- input.checked = input.value === governanceOrgAmbientSaved;- });- $("governance-org-ambient-save").disabled = true;- }- const showHeaderPinDefault = scope.startsWith("org:") && "channelHeaderPinDefault" in r.data;- $("card-channel-header-pin-default").classList.toggle("hidden", !showHeaderPinDefault);- if (showHeaderPinDefault) $("channel-header-pin-default").checked = !!r.data.channelHeaderPinDefault;+ if (requestedView === "customize") governanceUI.settings.load(r.data, scope, "soul");+ if (requestedView === "slack-settings") governanceUI.integrations.loadScope(r.data, scope);const opts = r.data.baseModelOptions || [];- const dflt = r.data.baseModelDefault || "";- const harnessDefault = r.data.harnessDefault || "pi";- const harnessOptions =- Array.isArray(r.data.harnessOptions) && r.data.harnessOptions.length- ? r.data.harnessOptions- : [harnessDefault];const modelsByHarness = r.data.modelsByHarness || {};- const showBaseModel = scope.startsWith("org:") && opts.length > 0 && dflt && "runtime" in r.data;- $("card-base-model").classList.toggle("hidden", !showBaseModel);- if (showBaseModel) {- const current = r.data.runtime || { harnessId: harnessDefault, modelId: r.data.baseModel || dflt };- const harness = $("base-harness");- harness.textContent = "";- harnessOptions.forEach((id) => {- const o = document.createElement("option");- o.value = id;- o.textContent =- { pi: "pi (default)", opencode: "OpenCode", codex: "Codex", claude: "Claude Code" }[id] || id;- harness.appendChild(o);- });- harness.value = harnessOptions.includes(current.harnessId) ? current.harnessId : harnessOptions[0];- const effort = $("base-effort");- const thinkingLevelsByHarness = r.data.thinkingLevelsByHarness || {};- const syncEffort = () => {- const thinkingLevels = thinkingLevelsByHarness[harness.value] || ["auto"];- const prior = effort.value || current.effortLevel || "auto";- effort.textContent = "";- thinkingLevels.forEach((level) => {- const o = document.createElement("option");- o.value = level;- o.textContent =- {- auto: "Auto",- low: "Low",- medium: "Medium",- high: "High",- xhigh: "Extra high",- max: "Max",- ultracode: "Ultracode",- }[level] || level;- effort.appendChild(o);- });- effort.value = thinkingLevels.includes(prior) ? prior : "auto";- };- const fastMode = $("base-fast-mode");- fastMode.checked = current.fastMode === true;- const syncFastMode = () => {- const fastCapable =- (r.data.fastModeHarnessIds || []).includes(harness.value) &&- (r.data.fastModeModelIds || []).includes($("base-model").value);- $("base-fast-mode-control").style.display = fastCapable ? "" : "none";- fastMode.disabled = !fastCapable;- if (!fastCapable) fastMode.checked = false;- };- const syncModels = () => {- const selectedHarness = harness.value;- const compatible = modelsByHarness[selectedHarness] || opts;- const sel = $("base-model");- const prior = sel.value || current.modelId;- sel.textContent = "";- compatible.forEach((m) => {- const o = document.createElement("option");- o.value = m.id;- o.textContent = m.name + " (" + m.id + ")";- sel.appendChild(o);- });- sel.value = compatible.some((m) => m.id === prior) ? prior : (compatible[0] || {}).id || "";- sel.oninput = syncFastMode;- syncEffort();- syncFastMode();- };- harness.oninput = syncModels;- refreshModelChoices.push(syncModels);- syncModels();+ if (requestedView === "models") {+ governanceUI.settings.load(r.data, scope, "runtime");+ governanceUI.settings.load(r.data, scope, "webui-models");}- const showWebuiModels = scope.startsWith("org:") && opts.length > 0;- $("card-webui-models").classList.toggle("hidden", !showWebuiModels);- if (showWebuiModels) {- const catalogModels = () =>- Object.values(modelsByHarness)- .flat()- .concat(opts)- .filter((m, i, all) => m && m.id && all.findIndex((x) => x && x.id === m.id) === i);- const modelLabel = (id) => {- const m = catalogModels().find((x) => x.id === id);- return m && m.name && m.name !== id ? m.name + " (" + id + ")" : id;- };- const configured = Array.isArray(r.data.webuiModels) ? r.data.webuiModels.filter(Boolean) : [];- webuiModelIds = [...configured];- const list = $("webui-models-list");- const empty = $("webui-models-empty");- const addSelect = $("webui-models-add");- const addButton = $("webui-models-add-button");- const renderChips = () => {- list.querySelectorAll("[data-chip]").forEach((n) => n.remove());- empty.classList.toggle("hidden", webuiModelIds.length > 0);- webuiModelIds.forEach((id) => {- const chip = document.createElement("span");- chip.dataset.chip = id;- chip.className = "model-chip";- const label = document.createElement("span");- label.textContent = modelLabel(id);- const x = document.createElement("button");- x.type = "button";- x.innerHTML =- '<svg width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" aria-hidden="true"><path d="m4 4 8 8M12 4l-8 8" /></svg>';- x.setAttribute("aria-label", "Remove " + id);- x.onclick = () => {- webuiModelIds = webuiModelIds.filter((v) => v !== id);- renderChips();- updateSectionDirty("webui-models");- };- chip.appendChild(label);- chip.appendChild(x);- list.appendChild(chip);- });- const prior = addSelect.value;- addSelect.textContent = "";- const placeholder = document.createElement("option");- placeholder.value = "";- placeholder.textContent = "Choose a model…";- addSelect.appendChild(placeholder);- catalogModels()- .filter((m) => !webuiModelIds.includes(m.id))- .forEach((m) => {- const o = document.createElement("option");- o.value = m.id;- o.textContent = modelLabel(m.id);- addSelect.appendChild(o);- });- addSelect.value = [...addSelect.options].some((o) => o.value === prior) ? prior : "";- addSelect.disabled = addSelect.options.length === 1;- addButton.disabled = !addSelect.value;- };- const addModel = () => {- const id = addSelect.value;- if (!id) return;- if (!webuiModelIds.includes(id)) webuiModelIds.push(id);- renderChips();- updateSectionDirty("webui-models");- };- addSelect.onchange = () => (addButton.disabled = !addSelect.value);- addButton.onclick = addModel;- refreshModelChoices.push(renderChips);- renderChips();+ refreshModelChoices.push(() => governanceUI.settings.updateCatalog(r.data));+ if (requestedView === "customize") {+ savedBranding = r.data.branding || {};+ governanceUI.settings.load(r.data, scope, "branding");}- function autoSaveAckEmoji() {- updateSectionDirty("ack-emoji");- const btn = sectionButton("ack-emoji");- if (btn && !btn.disabled) btn.click();++ if (requestedView === "credentials") {+ serviceCredDirectory = r.data.directoryMembers || [];+ serviceCredChannels = r.data.directoryChannels || [];+ const options = $("sc-people-options");+ options.textContent = "";+ serviceCredDirectory.forEach((member) => {+ const option = document.createElement("option");+ option.value = member.principalId;+ option.label = member.displayName;+ options.appendChild(option);+ });}- function initAckEmojiPicker() {- const chips = $("ack-emoji-chips");- const openBtn = $("ack-emoji-open");- const picker = $("ack-emoji-picker");- const search = $("ack-emoji-search");- const results = $("ack-emoji-results");- const emojiChar = (name) => {- const hit = (ackEmojiStandard || []).find((e) => e[0] === name);- return hit ? hit[1] : "";- };- const renderAckChips = () => {- chips.querySelectorAll("[data-chip]").forEach((n) => n.remove());- ackEmojiNames.forEach((name) => {- const chip = document.createElement("span");- chip.dataset.chip = name;- chip.style.cssText =- "display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border:1px solid var(--border, #d4d4d4);border-radius:999px;font-size:13px";- const label = document.createElement("span");- const url = ackEmojiCatalog[name];- if (url) {- const img = document.createElement("img");- img.src = url;- img.alt = name;- img.className = "ack-emoji-img";- img.style.marginRight = "4px";- label.appendChild(img);- } else {- const ch = emojiChar(name);- if (ch) label.appendChild(document.createTextNode(ch + " "));- }- label.appendChild(document.createTextNode(":" + name + ":"));- const x = document.createElement("button");- x.type = "button";- x.textContent = "\u00d7";- x.setAttribute("aria-label", "Remove " + name);- x.style.cssText = "border:0;background:none;cursor:pointer;padding:0;font-size:14px;line-height:1";- x.onclick = () => {- ackEmojiNames = ackEmojiNames.filter((v) => v !== name);- renderAckChips();- autoSaveAckEmoji();- };- chip.appendChild(label);- chip.appendChild(x);- chips.insertBefore(chip, openBtn.parentElement);- });- };- const addEmoji = (name) => {- if (!name || !/^[a-z0-9_+-]+$/.test(name)) return;- if (!ackEmojiNames.includes(name)) {- ackEmojiNames.push(name);- renderAckChips();- autoSaveAckEmoji();- }- };- const emojiButton = (name, render) => {- const b = document.createElement("button");- b.type = "button";- b.title = ":" + name + ":";- b.setAttribute("aria-label", name);- render(b);- b.onclick = () => {- addEmoji(name);- closePicker();- };- return b;- };- const renderResults = () => {- const q = search.value.trim().toLowerCase().replace(/:/g, "");- results.textContent = "";- if (ackEmojiCatalogError) {- const notice = document.createElement("div");- notice.className = "emoji-picker-empty";- notice.textContent = ackEmojiCatalogError;- results.appendChild(notice);- return;- }- const taken = new Set(ackEmojiNames);- const sections = [];- const custom = Object.keys(ackEmojiCatalog)- .filter((n) => !taken.has(n) && (!q || n.includes(q)))- .sort();- if (custom.length) {- sections.push([- "Custom",- custom.map((n) =>- emojiButton(n, (b) => {- const img = document.createElement("img");- img.src = ackEmojiCatalog[n];- img.alt = n;- img.loading = "lazy";- b.appendChild(img);- }),- ),- ]);- }- const byCategory = new Map();- (ackEmojiStandard || []).forEach((e) => {- const name = e[0];- if (taken.has(name) || ackEmojiCatalog[name]) return;- if (q && !name.includes(q)) return;- if (!byCategory.has(e[2])) byCategory.set(e[2], []);- byCategory.get(e[2]).push(emojiButton(name, (b) => (b.textContent = e[1])));- });- byCategory.forEach((buttons, category) => sections.push([category, buttons]));- if (!sections.length) {- const empty = document.createElement("div");- empty.className = "emoji-picker-empty";- empty.textContent = "No emoji match \u201c" + search.value.trim() + "\u201d";- results.appendChild(empty);- return;- }- sections.forEach(([title, buttons]) => {- const head = document.createElement("div");- head.className = "emoji-picker-section";- head.textContent = title;- const grid = document.createElement("div");- grid.className = "emoji-picker-grid";- buttons.forEach((b) => grid.appendChild(b));- results.appendChild(head);- results.appendChild(grid);- });- };- const closePicker = () => {- picker.classList.add("hidden");- document.removeEventListener("mousedown", onOutside);- };- const onOutside = (e) => {- if (!picker.contains(e.target) && e.target !== openBtn) closePicker();- };- openBtn.onclick = () => {- if (!picker.classList.contains("hidden")) return closePicker();- picker.classList.remove("hidden");- search.value = "";- renderResults();- search.focus();- document.addEventListener("mousedown", onOutside);- };- search.oninput = renderResults;- search.onkeydown = (e) => {- if (e.key === "Escape") {- e.preventDefault();- closePicker();- }- if (e.key === "Enter") {- e.preventDefault();- const first = results.querySelector("button");- if (first) first.click();- }- };- if (!ackEmojiCatalogLoaded) {- ackEmojiCatalogLoaded = true;- api("GET", "/api/slack-emoji")- .then((res) => {- if (res && res.ok && res.data) {- if (res.data.emoji) ackEmojiCatalog = res.data.emoji;- if (Array.isArray(res.data.standard)) ackEmojiStandard = res.data.standard;- ackEmojiCatalogError = null;- } else if (res && res.status === 404) {- ackEmojiCatalogError =- "Slack isn't connected on this deployment, so no emoji can be listed. Set SLACK_BOT_TOKEN on the core service (or complete the Slack installation on this page); on deployments where the token lives with the Slack plugin, the catalog appears after the plugin next starts and publishes it.";- } else {- const detail = res && res.data && res.data.message ? " (" + res.data.message + ")" : "";- ackEmojiCatalogError =- "Couldn't load emoji from Slack" + detail + ". Check the bot token and try again.";- }- renderAckChips();- if (typeof renderResults === "function") renderResults();- })- .catch(() => {- ackEmojiCatalogError = "Couldn't reach the server to load emoji. Reload and try again.";- });- }- renderAckChips();- }- const showPeopleDirectory = scope.startsWith("org:");- $("card-people-directory").classList.toggle("hidden", !showPeopleDirectory);- if (showPeopleDirectory) $("people-directory-url").value = r.data.peopleDirectoryUrl || "";- const showAckEmoji = scope.startsWith("org:") && "ackEmoji" in r.data;- $("card-ack-emoji").classList.toggle("hidden", !showAckEmoji);- if (showAckEmoji) {- ackEmojiNames = Array.isArray(r.data.ackEmoji) ? [...r.data.ackEmoji] : [];- initAckEmojiPicker();- }- const showBranding = scope.startsWith("org:") && "branding" in r.data;- $("card-branding").classList.toggle("hidden", !showBranding);- if (showBranding) {- const b = r.data.branding || {};- $("branding-accent").value = b.accent || "";- $("branding-mark").value = b.mark || "";- $("branding-mark-url").value = b.markUrl || "";- $("branding-self-label").value = b.selfLabel || "";- $("branding-org-name").value = b.orgName || "";- }-- const showTurnWallClock = scope.startsWith("org:") && "turnWallClockSec" in r.data;- $("card-turn-wall-clock").classList.toggle("hidden", !showTurnWallClock);- if (showTurnWallClock) $("turn-wall-clock").value = r.data.turnWallClockSec ?? "";- serviceCredDirectory = r.data.directoryMembers || [];- serviceCredChannels = r.data.directoryChannels || [];- const options = $("sc-people-options");- options.textContent = "";- serviceCredDirectory.forEach((member) => {- const option = document.createElement("option");- option.value = member.principalId;- option.label = member.displayName;- options.appendChild(option);- });- const showFeatureFlags = scope.startsWith("org:") && "featureFlags" in r.data;- $("card-feature-flags").classList.toggle("hidden", !showFeatureFlags);- if (showFeatureFlags) renderFeatureFlags(r.data.featureFlags || []);- renderServiceCreds(r.data.serviceCredentials || []);+ if (requestedView === "customize") void governanceUI.settings.loadFlags(r.data, scope);+ if (requestedView === "credentials") renderServiceCreds(r.data.serviceCredentials || []);if (view === "models") void loadCustomProviders();if (view === "credentials") {- $("sc-add").disabled = false;void loadServiceCredentialUsage(requestedScope, requestId);}if (scopeChanged) resetScForm();+ if (requestedView === "governance") {+ governanceReadyScope = requestedScope;+ setGovernancePending(false);+ flattenGovernanceCards();+ }loadedGovernanceScope = scope;initCustomDropdowns($("view-governance"));captureGovernanceSnapshots();@@ -10123,6 +8184,7 @@for (const [harness, models] of Object.entries(fresh.data.modelsByHarness || {})) {append((modelsByHarness[harness] ||= []), models);}+ if (requestedView === "governance") governanceUI.updateCatalog(fresh.data);refreshModelChoices.forEach((refresh) => refresh());initCustomDropdowns($("view-governance"));})@@ -10130,21 +8192,13 @@}}async function refreshSoulConflict() {- const draft = $("soul").value;const fresh = await api("GET","/api/scopes/" + encodeURIComponent(scope) + "?view=" + encodeURIComponent(view),);if (!fresh.ok) return false;- soulVersion = fresh.data.soulVersion || 0;- soulSaved = fresh.data.soul || "";- soulHistory = fresh.data.soulHistory || [];- $("soul").value = draft;- $("soul-ver").textContent = soulVersion ? "Saved version " + soulVersion : "No saved revision";- updateSoulWorkbench();- renderSoulHistory();- sectionSnapshots.set("soul", JSON.stringify({ content: soulSaved, expectedVersion: soulVersion }));- updateSectionDirty("soul");+ governanceUI.settings.refreshSoul(fresh.data);+ sectionSnapshots.set("soul", governanceUI.settings.states.get("soul").baseline);return true;}async function refreshServiceCredentialConflict() {@@ -10169,82 +8223,30 @@});const credentials = fresh.data.serviceCredentials || [];const refreshedEditing = credentials.find((credential) => credential.slug === scEditing);- if (refreshedEditing) scEditVersion = refreshedEditing.updatedAt;+ if (refreshedEditing) {+ scEditVersion = refreshedEditing.updatedAt;+ governanceUI.settings.credentialState.version = scEditVersion;+ }renderServiceCreds(credentials);void loadServiceCredentialUsage(requestedScope, requestId);renderServiceCredentialCapability();updateScFormDirty();return refreshedEditing ? "present" : "missing";}- let featureFlagRows = [];- function renderFeatureFlags(rows) {- featureFlagRows = rows || [];- const root = $("feature-flag-list");- root.textContent = "";- const enabled = featureFlagRows.flatMap((row) =>- (row.enabledScopes || []).map((scopeId) => ({ featureName: row.featureName, scopeId })),- );- if (!enabled.length) {- root.className = "hint";- root.textContent = "No enabled scopes.";- return;- }- root.className = "";- enabled.forEach(({ featureName, scopeId }) => {- const line = document.createElement("div");- line.className = "setting-row";- const code = document.createElement("code");- code.textContent = featureName + ": " + scopeId;- const remove = document.createElement("button");- remove.className = "danger";- remove.textContent = "Disable";- remove.onclick = () => updateFeatureFlag(scopeId, false, featureName);- line.append(code, remove);- root.appendChild(line);- });- }- async function updateFeatureFlag(scopeId, on, featureName = $("feature-flag-name").value) {- const status = $("st-feature-flags");- status.textContent = on ? "Enabling…" : "Disabling…";- const result = await api("PUT", "/api/scopes/" + encodeURIComponent(scope) + "/feature-flags", {- featureName,- scopeId,- on,- });- if (!result.ok) {- status.textContent = result.error || "Save failed.";- return;- }- status.textContent = on ? "Enabled." : "Disabled.";- await loadScope();- }- $("feature-flag-enable").onclick = () => {- const scopeId = $("feature-flag-scope").value.trim();- if (!scopeId) {- $("st-feature-flags").textContent = "Enter a scope ID.";- return;- }- updateFeatureFlag(scopeId, true);- };+ let savedBranding = {};+ governanceUI.settings.configureFlags({+ buildSelector: buildScopeMultiSelect,+ loadChoices: async () => {+ if (!scopeDir) await loadScopeDirectory();+ return (scopeDir || []).map((row) => ({ scopeId: row.scopeId, label: row.label || row.scopeId }));+ },+ save: (targetScope, body) =>+ api("PUT", "/api/scopes/" + encodeURIComponent(targetScope) + "/feature-flags", body),+ });let scEditing = null;let scEditVersion = null;- let scSnapshot = "";let serviceCredList = [];- let serviceCredentialResolutionError = "";- function setServiceCredentialState(message, retry = false) {- const root = $("sc-list");- root.className = "hint";- root.textContent = message;- if (retry) {- const button = document.createElement("button");- button.type = "button";- button.textContent = "Retry";- button.style.marginInlineStart = "8px";- button.onclick = () => loadScope();- root.appendChild(button);- }- }async function loadServiceCredentialUsage(requestedScope, requestId) {if (!serviceCredList.length) return;const result = await api("GET", "/api/scopes/" + encodeURIComponent(requestedScope) + "/credential-usage");@@ -10258,122 +8260,21 @@})),);}- function serviceCredentialUsageLabel(credential) {- if (credential.usageUnavailable) return "Usage unavailable";- if (credential.usageCount == null) return "Loading usage…";- const window = credential.usageCount- ? " since " + fmtTime(credential.usageSince)- : " in retained broker history";- return (- (credential.usageTruncated ? "at least " : "") + plural(credential.usageCount, "successful use") + window- );- }+ governanceUI.settings.configureCredentials({+ label: serviceCredentialPrincipalLabel,+ formatTime: fmtTime,+ edit: loadScForm,+ remove: deleteSc,+ reload: loadScope,+ });function renderServiceCreds(list) {serviceCredList = list;- const root = $("sc-list");- root.textContent = "";- if (!list.length) {- root.className = "hint";- root.textContent = "No credentials configured.";- return;- }- root.className = "";- list.forEach((c) => {- const row = document.createElement("div");- row.className = "credential-row";- if (c.slug === scEditing) row.classList.add("is-editing");- const left = document.createElement("div");- left.className = "credential-main";- const title = document.createElement("div");- title.className = "credential-title";- const name = document.createElement("strong");- name.textContent = c.name || c.slug;- const slug = document.createElement("span");- slug.className = "credential-slug";- slug.textContent = c.slug;- title.append(name, slug);- const orgWide = (c.grantees || []).some((g) => g.startsWith("org:"));- const who = orgWide ? "Organization-wide" : plural((c.grantees || []).length, "principal");- const meta = document.createElement("div");- meta.className = "hint";- const target =- c.delivery === "env"- ? "sandbox env $" + (c.envKey || "?")- : c.host + " · " + (c.allowedMethods && c.allowedMethods.length ? c.allowedMethods.join("/") : "GET");- meta.textContent = target + " · " + serviceCredentialUsageLabel(c);- const badges = document.createElement("div");- badges.className = "credential-badges";- badges.append(- badge(c.delivery === "env" ? "Env" : "Broker", "info"),- badge(c.enabled === false ? "Disabled" : "Enabled", c.enabled === false ? "warn" : "ok"),- badge(c.hasSecret ? "Secret set" : "Secret missing", c.hasSecret ? "ok" : "err"),- badge(who, orgWide ? "info" : "muted"),- ...(c.delivery !== "env" && c.deployments === false ? [badge("No apps", "muted")] : []),- );- left.append(title, meta, badges);- const actions = document.createElement("div");- actions.className = "credential-actions";- const edit = document.createElement("button");- edit.type = "button";- edit.textContent = "Edit";- edit.onclick = () => loadScForm(c);- const del = document.createElement("button");- del.type = "button";- del.className = "rowbtn danger";- del.textContent = "Delete";- del.title = "Delete credential";- del.setAttribute("aria-label", "Delete " + (c.name || c.slug));- del.onclick = () => deleteSc(c);- actions.appendChild(edit);- actions.appendChild(del);- row.appendChild(left);- row.appendChild(actions);- root.appendChild(row);- });+ governanceUI.settings.loadCredentials(list, serviceCredDirectory, serviceCredChannels, scopeDir || [], scope);}function loadScForm(c) {- $("sc-editor").classList.remove("hidden");- scAddButton.classList.add("hidden");- $("sc-save").classList.remove("hidden");- $("sc-reset").classList.remove("hidden");scEditing = c.slug;scEditVersion = c.updatedAt;- $("sc-form-title").textContent = "Editing " + c.slug;- $("sc-form-mode").textContent = "Editing";- $("sc-form-mode").className = "badge info";- $("sc-save").textContent = "Save changes";- $("sc-reset").textContent = "Cancel";- $("sc-slug").value = c.slug;- $("sc-slug").disabled = true;- $("sc-name").value = c.name;- $("sc-host").value = c.host;- $("sc-delivery").value = c.delivery || "broker";- $("sc-envkey").value = c.envKey || "";- syncScDelivery();- $("sc-secret").value = "";- $("sc-secret").placeholder = c.hasSecret ? "Stored secret retained when blank" : "Write-only secret";- $("sc-secret-hint").textContent = c.hasSecret- ? "Stored secret is set. Leave blank to keep it; enter a new value to replace it."- : "No stored secret yet. Enter one to make this credential usable.";- $("sc-secret-semantics").textContent = c.hasSecret- ? "Keeps the stored secret unchanged."- : "A secret is required before saving.";- $("sc-header").value = (c.injection && c.injection.header) || "";- $("sc-scheme").value = (c.injection && c.injection.scheme) || "";- $("sc-methods").value = (c.allowedMethods || []).join(", ");- $("sc-paths").value = (c.allowedPathPrefixes || []).join("\n");- $("sc-enabled").checked = c.enabled !== false;- $("sc-deployments").checked = c.deployments !== false;- const orgWide = (c.grantees || []).some((g) => g.startsWith("org:"));- $("sc-share-org").checked = orgWide;- document.querySelector("input[name=sc-share][value=people]").checked = !orgWide;-- $("sc-people").value = orgWide- ? ""- : (c.grantees || []).map((g) => (g.startsWith("personal:") ? g.slice("personal:".length) : g)).join(", ");- syncScPeople();- captureScForm();- renderServiceCreds(serviceCredList);+ governanceUI.settings.credentialState.begin(c);openScDialog();$("sc-name").focus();}@@ -10382,203 +8283,11 @@const wasOpen = dialog.open;if (wasOpen) dialog.close();scStatusHome.appendChild($("st-service-credentials"));- $("sc-editor").classList.add("hidden");- scAddButton.classList.remove("hidden");- $("sc-save").classList.add("hidden");- $("sc-reset").classList.add("hidden");scEditing = null;scEditVersion = null;- $("sc-form-title").textContent = "Add a credential";- $("sc-form-mode").textContent = "New";- $("sc-form-mode").className = "badge muted";- $("sc-save").textContent = "Save credential";- $("sc-reset").textContent = "Cancel";- $("sc-slug").value = "";- $("sc-slug").disabled = false;- $("sc-name").value = "";- $("sc-host").value = "";- $("sc-delivery").value = "broker";- $("sc-envkey").value = "";- syncScDelivery();- $("sc-secret").value = "";- $("sc-secret").placeholder = "(write-only)";- $("sc-secret-hint").textContent = "The secret is write-only. It cannot be viewed after saving.";- $("sc-secret-semantics").textContent = "New credentials require a secret.";- $("sc-header").value = "";- $("sc-scheme").value = "";- $("sc-methods").value = "";- $("sc-paths").value = "";- $("sc-enabled").checked = true;- $("sc-deployments").checked = true;- $("sc-share-org").checked = true;- document.querySelector("input[name=sc-share][value=people]").checked = false;- $("sc-people").value = "";- syncScPeople();- captureScForm();- if (serviceCredList.length) renderServiceCreds(serviceCredList);+ governanceUI.settings.credentialState.reset();if (wasOpen) scAddButton.focus();}- function syncScDelivery() {- const env = $("sc-delivery").value === "env";- document- .querySelectorAll("#card-service-credentials .sc-broker-only")- .forEach((el) => el.classList.toggle("hidden", env));- document- .querySelectorAll("#card-service-credentials .sc-env-only")- .forEach((el) => el.classList.toggle("hidden", !env));- }- function scSelectedIds() {- return $("sc-people")- .value.split(",")- .map((x) => x.trim())- .filter(Boolean);- }- function scWriteSelected(ids) {- $("sc-people").value = ids.join(", ");- renderServiceCredentialCapability();- updateScFormDirty();- drawScPicker();- }- function drawScPicker() {- const list = $("sc-picker-list");- const search = $("sc-picker-search");- if (!list || !search) return;- const q = search.value.trim().toLowerCase();- const selected = scSelectedIds();- const selSet = new Set(selected);- list.textContent = "";- const item = (id, label, checked) => {- const el = document.createElement("div");- el.className = "sc-picker-item";- const cb = document.createElement("input");- cb.type = "checkbox";- cb.checked = checked;- const span = document.createElement("span");- span.textContent = label;- el.append(cb, span);- el.onmousedown = (e) => {- e.preventDefault();- const next = checked ? selected.filter((x) => x !== id) : [...selected, id];- scWriteSelected(next);- };- return el;- };- if (selected.length) {- const h = document.createElement("div");- h.className = "sc-picker-group";- h.textContent = "Has access";- list.appendChild(h);- selected.forEach((id) => {- list.appendChild(item(id, serviceCredentialPrincipalLabel(id), true));- });- }- const candidates = serviceCredDirectory.filter((m) => {- if (selSet.has(m.principalId)) return false;- if (!q) return true;- return (- m.principalId.toLowerCase().includes(q) ||- (m.displayName || "").toLowerCase().includes(q) ||- (m.slackId || "").toLowerCase().includes(q)- );- });- if (candidates.length) {- const h = document.createElement("div");- h.className = "sc-picker-group";- h.textContent = "People";- list.appendChild(h);- }- candidates.slice(0, 30).forEach((m) => {- list.appendChild(item(m.principalId, m.displayName + " (" + m.principalId + ")", false));- });- if (candidates.length > 30) {- const more = document.createElement("div");- more.className = "sc-picker-more";- more.textContent = "…" + (candidates.length - 30) + " more — keep typing";- list.appendChild(more);- }- const channelScopes = new Map((scopeDir || []).map((s) => [s.scopeId, s]));- serviceCredChannels.forEach((channel) =>- channelScopes.set("channel:" + channel.channelId, {- scopeId: "channel:" + channel.channelId,- label: channel.name,- }),- );- const channels = [...channelScopes.values()].filter((s) => {- if (!s.scopeId.startsWith("channel:") || selSet.has(s.scopeId)) return false;- if (!q) return true;- return s.scopeId.toLowerCase().includes(q) || (s.label || "").toLowerCase().includes(q);- });- if (channels.length) {- const h = document.createElement("div");- h.className = "sc-picker-group";- h.textContent = "Channels";- list.appendChild(h);- channels.slice(0, 15).forEach((s) => {- list.appendChild(- item(s.scopeId, s.label ? "#" + s.label.replace(/^#/, "") + " (" + s.scopeId + ")" : s.scopeId, false),- );- });- if (channels.length > 15) {- const more = document.createElement("div");- more.className = "sc-picker-more";- more.textContent = "…" + (channels.length - 15) + " more channels — keep typing";- list.appendChild(more);- }- }- list.hidden = document.activeElement !== search && !list.contains(document.activeElement);- }- function initScPicker() {- const search = $("sc-picker-search");- const list = $("sc-picker-list");- if (!search || search.dataset.wired) return;- search.dataset.wired = "1";- search.addEventListener("focus", () => {- drawScPicker();- list.hidden = false;- });- search.addEventListener("input", () => {- drawScPicker();- list.hidden = false;- });- search.addEventListener("blur", () => {- setTimeout(() => {- if (!list.contains(document.activeElement)) list.hidden = true;- }, 150);- });- }- function syncScPeople() {- initScPicker();- const picker = $("sc-picker");- if (picker) picker.style.display = $("sc-share-org").checked ? "none" : "";- drawScPicker();- const orgWide = $("sc-share-org").checked;- $("sc-people").disabled = orgWide;- $("sc-people").placeholder = orgWide ? "Organization-wide access selected" : "Principal IDs, comma-separated";- renderServiceCredentialCapability();- }- function serviceCredentialGrantees() {- serviceCredentialResolutionError = "";- return $("sc-share-org").checked- ? [scope]- : $("sc-people")- .value.split(",")- .map((s) => s.trim())- .filter(Boolean)- .map((id) => {- if (/^(personal|team|org|channel|group):/.test(id)) return id;- const q = id.toLowerCase();- const identifiers = serviceCredDirectory.filter(- (member) => member.principalId.toLowerCase() === q || member.slackId?.toLowerCase() === q,- );- if (identifiers.length === 1) return "personal:" + identifiers[0].principalId;- const names = serviceCredDirectory.filter((member) => member.displayName.toLowerCase() === q);- if (names.length === 1) return "personal:" + names[0].principalId;- if (names.length > 1 || identifiers.length > 1)- serviceCredentialResolutionError =- "\u201c" + id + "\u201d matches multiple people. Use an exact principal ID.";- return "personal:" + id;- });- }function serviceCredentialPrincipalLabel(grantee) {if (grantee.startsWith("org:")) return "Everyone in this organization";if (grantee.startsWith("channel:")) {@@ -10592,141 +8301,16 @@return member ? member.displayName + " (" + id + ")" : grantee;}function renderServiceCredentialCapability() {- if (!$("sc-cap-host")) return;- const methods = $("sc-methods")- .value.split(",")- .map((s) => s.trim().toUpperCase())- .filter(Boolean);- const paths = $("sc-paths")- .value.split("\n")- .map((s) => s.trim())- .filter(Boolean);- const grantees = serviceCredentialGrantees();- const header = $("sc-header").value.trim() || "Authorization";- const envDelivery = $("sc-delivery").value === "env";- $("sc-cap-state").textContent = $("sc-enabled").checked- ? "Enabled"- : envDelivery- ? "Disabled: never injected"- : "Disabled: broker requests refused";- if (envDelivery) {- $("sc-cap-host").textContent = $("sc-envkey").value.trim()- ? "Sandbox env $" + $("sc-envkey").value.trim()- : "Env var not set";- $("sc-cap-auth").textContent = "Injected into all-internal conversations; rooms with externals get nothing";- $("sc-cap-methods").textContent = "None";- $("sc-cap-paths").textContent = "Never served by the credential broker";- } else {- $("sc-cap-host").textContent = $("sc-host").value.trim()- ? $("sc-host").value.trim() + " and its subdomains"- : "Not set";- $("sc-cap-auth").textContent = header + " header · prefix “" + ($("sc-scheme").value || "Bearer") + "”";- $("sc-cap-methods").textContent = (methods.length ? methods : ["GET"]).join(", ");- $("sc-cap-paths").textContent = paths.length ? paths.join(", ") : "Any path on this host";- }- $("sc-cap-principals").textContent = envDelivery- ? "Every all-internal conversation; grants don't gate env delivery"- : (grantees.map(serviceCredentialPrincipalLabel).join(", ") || "No principal selected") +- ($("sc-deployments").checked- ? " · published apps, acting as their publisher"- : " · switched off for published apps");- const editing = serviceCredList.find((c) => c.slug === scEditing);- let secretStatus = "Required before first save";- if ($("sc-secret").value) secretStatus = "Will replace the stored secret";- else if (editing?.hasSecret) secretStatus = "Stored secret retained";- $("sc-cap-secret").textContent = secretStatus;- const chips = $("sc-people-chips");- chips.textContent = "";- if (!$("sc-share-org").checked)- grantees.forEach((grantee) => {- const chip = document.createElement("span");- chip.className = "identity-chip";- const label = serviceCredentialPrincipalLabel(grantee);- chip.textContent = label;- if (/^group:/.test(grantee)) {- const unsupported = document.createElement("small");- unsupported.textContent = "unsupported · remove before saving";- chip.appendChild(unsupported);- } else if (/^channel:/.test(grantee)) {- const tag = document.createElement("small");- tag.textContent = "channel";- chip.appendChild(tag);- } else if (label === grantee) {- const unresolved = document.createElement("small");- unresolved.textContent = "unresolved";- chip.appendChild(unresolved);- }- chips.appendChild(chip);- });+ governanceUI.settings.credentialState.render();}function serviceCredentialBody() {- const actor = serviceCredList.find((credential) => credential.slug === scEditing)?.injection?.actor;- const delivery = $("sc-delivery").value === "env" ? "env" : "broker";- return {- slug: $("sc-slug").value.trim(),- name: $("sc-name").value.trim(),- delivery,- ...(delivery === "env" ? { envKey: $("sc-envkey").value.trim() } : {}),- host: delivery === "env" ? "" : $("sc-host").value.trim(),- ...($("sc-secret").value ? { secret: $("sc-secret").value } : {}),- injection: {- ...(typeof actor === "boolean" ? { actor } : {}),- ...($("sc-header").value.trim() ? { header: $("sc-header").value.trim() } : {}),- ...($("sc-scheme").value ? { scheme: $("sc-scheme").value } : {}),- },- allowedMethods: $("sc-methods")- .value.split(",")- .map((s) => s.trim())- .filter(Boolean),- allowedPathPrefixes: $("sc-paths")- .value.split("\n")- .map((s) => s.trim())- .filter(Boolean),- enabled: $("sc-enabled").checked,- deployments: delivery === "env" ? true : $("sc-deployments").checked,- // Grants don't gate env delivery, so an env credential always carries the org grant —- // the picker is hidden and a narrower selection must not ride along from broker mode.- grantees: delivery === "env" ? [scope] : serviceCredentialGrantees(),- ...(scEditing && scEditVersion != null ? { expectedUpdatedAt: scEditVersion } : {}),- };- }- function serviceCredentialSnapshot() {- return JSON.stringify({ editing: scEditing || "", body: serviceCredentialBody() });- }- function setScFormDirty(dirty) {- setCardDirty($("card-service-credentials"), dirty, "st-service-credentials", "#sc-save");- }- function captureScForm() {- scSnapshot = serviceCredentialSnapshot();- setScFormDirty(false);+ return governanceUI.settings.credentialState.collect();}function updateScFormDirty() {- syncScPeople();- syncScDelivery();- renderServiceCredentialCapability();- setScFormDirty(serviceCredentialSnapshot() !== scSnapshot);+ governanceUI.settings.credentialState.changed();}function validateServiceCredential(body) {- if (!body.slug) return "Slug is required.";- if (!body.name) return "Name is required.";- if (body.delivery === "env") {- if (!body.envKey) return "Env delivery needs an env var name.";- if (!/^[A-Z][A-Z0-9_]*$/.test(body.envKey)) return "Env var must be UPPER_SNAKE_CASE.";- if (body.envKey.startsWith("AGENT_")) return "AGENT_* env vars are reserved for the platform.";- } else if (!body.host) return "Host is required.";- if (body.delivery !== "env" && !$("sc-share-org").checked && !body.grantees.length)- return "Add at least one person or choose org-wide access.";- if (body.delivery !== "env" && serviceCredentialResolutionError) return serviceCredentialResolutionError;- const unsupported = body.grantees.find(- (grantee) => /^group:/.test(grantee) || /^personal:[^,]*:/.test(grantee),- );- if (unsupported)- return (- "Remove unsupported legacy grant “" +- unsupported +- "” before saving. Shared credentials support people, teams, channels, or the organization."- );- return "";+ return governanceUI.settings.credentialState.validate(body);}async function deleteSc(credential) {const c = {@@ -10761,12 +8345,13 @@confirmLabel: "Delete credential",danger: true,});- if (!confirmed) return;+ if (!confirmed || targetScope !== scope) return;const r = await api("PUT", "/api/scopes/" + encodeURIComponent(targetScope) + "/service-credentials", {slug: c.slug,delete: true,expectedUpdatedAt: c.updatedAt,});+ if (targetScope !== scope) return;if (r.ok) {resetScForm();await loadScope();@@ -10784,10 +8369,7 @@}scAddButton.onclick = () => {resetScForm();- $("sc-editor").classList.remove("hidden");- scAddButton.classList.add("hidden");- $("sc-save").classList.remove("hidden");- $("sc-reset").classList.remove("hidden");+ governanceUI.settings.credentialState.begin(null);openScDialog();$("sc-name").focus();};@@ -10796,6 +8378,7 @@};$("sc-save").onclick = async () => {const body = serviceCredentialBody();+ const targetScope = scope;const invalid = validateServiceCredential(body);if (invalid) {setStatus("st-service-credentials", invalid, "err");@@ -10805,8 +8388,9 @@setStatus("st-service-credentials", "Saving...", "saving", true);let r;try {- r = await api("PUT", "/api/scopes/" + encodeURIComponent(scope) + "/service-credentials", body);+ r = await api("PUT", "/api/scopes/" + encodeURIComponent(targetScope) + "/service-credentials", body);} catch {+ if (targetScope !== scope) return;updateScFormDirty();setStatus("st-service-credentials",@@ -10816,9 +8400,12 @@);return;}+ if (scope !== targetScope) return;if (r.ok) {- resetScForm();await loadScope();+ if (scope !== targetScope) return;+ governanceUI.settings.credentialState.commit(body);+ if (!governanceUI.settings.credentialState.dirty) resetScForm();setStatus("st-service-credentials", "Saved", "ok");} else {let conflictState = false;@@ -10853,612 +8440,47 @@}};- let onboardingModels = {};- let onboardingRequest = 0;- let onboardingModelStatuses = [];- function onboardingBadge(id, text, ready, optional = false) {- const el = $(id);- el.textContent = text;- el.className = "badge " + (ready ? "ok" : optional ? "muted" : "warn");- }- const MODEL_PROVIDER_LABELS = {- anthropic: "Anthropic",- openai: "OpenAI",- openrouter: "OpenRouter (hosted open models)",- };- function onboardingProviderForModel(modelId) {- const owning = Object.entries(onboardingModels).find(([, models]) =>- models.some((model) => model.id === modelId),- )?.[0];- if (owning) return owning;- return (- onboardingModelStatuses.find((item) => item.configured)?.provider ||- onboardingModelStatuses[0]?.provider ||- ""- );- }- function renderOnboardingProviderOptions(preferred) {- const select = $("onboarding-model-provider");- select.textContent = "";- const known = onboardingModelStatuses.length- ? onboardingModelStatuses- : Object.keys(MODEL_PROVIDER_LABELS).map((provider) => ({ provider, configured: false }));- known.forEach((status) => {- const option = document.createElement("option");- option.value = status.provider;- const label = MODEL_PROVIDER_LABELS[status.provider] || connectorName(status.provider);- option.textContent = status.configured ? label + " (key configured)" : label;- select.appendChild(option);- });- if (preferred && [...select.options].some((option) => option.value === preferred)) select.value = preferred;- }- function renderOnboardingModelOptions(preferred) {- const provider = $("onboarding-model-provider").value;- const select = $("onboarding-model-id");- select.textContent = "";- (onboardingModels[provider] || []).forEach((model) => {- const option = document.createElement("option");- option.value = model.id;- option.textContent = model.name;- select.appendChild(option);- });- if (preferred && [...select.options].some((option) => option.value === preferred)) select.value = preferred;- const status = onboardingModelStatuses.find((item) => item.provider === provider);- $("onboarding-model-delete").disabled = !status || status.source === "absent";- $("onboarding-model-key").placeholder = status?.configured- ? "•••• set, enter a replacement"- : "Write-only API key";- }- async function loadOnboarding() {- const requestId = ++onboardingRequest;- const requestedView = view;- void loadModelRegistry().catch(() => {});- const [models, slack, catalog, config] = await Promise.all([- api("GET", "/api/model-providers?catalog=cached"),- api("GET", "/api/slack-installation"),- api("GET", "/api/connector-catalog"),- api("GET", "/api/scopes/" + encodeURIComponent(orgScope()) + "?view=onboarding"),- ]);- if (requestId !== onboardingRequest || requestedView !== view) return;- if (!models.ok || !slack.ok || !catalog.ok || !config.ok) {- setStatus("st-onboarding-model", "Setup status could not be loaded. Try again.", "err", true);- renderOnboardingProviderOptions();- return;- }- onboardingModelStatuses = models.data.providers || [];- onboardingModels = {};- [- ...(models.data.models || []),- ...(config.data.baseModelOptions || []),- ...Object.values(config.data.modelsByHarness || {}).flat(),- ].forEach((model) => {- if (!model.provider) return;- const options = (onboardingModels[model.provider] ||= []);- if (!options.some((option) => option.id === model.id)) options.push(model);- });- const baseModel = config.data.baseModel || config.data.baseModelDefault || "";- const baseProvider = onboardingProviderForModel(baseModel);- const baseStatus = onboardingModelStatuses.find((item) => item.provider === baseProvider);- const harnessAuth = models.data.harnessAuth;- const baseHarnessAuth = Boolean(harnessAuth && harnessAuth.provider === baseProvider);- const baseReady = Boolean(baseModel) && (Boolean(baseStatus?.configured) || baseHarnessAuth);- onboardingBadge("onboarding-model-badge", baseReady ? "Ready" : "Needs a key", baseReady);- $("onboarding-model-summary").textContent = !baseModel- ? "No base model is configured yet. Pick a provider and model below."- : baseStatus?.configured- ? baseModel + " · " + (baseStatus.source === "admin" ? "admin-managed key" : "deployment key")- : baseHarnessAuth- ? baseModel + " · authenticated by the " + harnessAuth.harnessId + " harness — no API key needed."- : baseModel +- " cannot run until its " +- (MODEL_PROVIDER_LABELS[baseProvider] || connectorName(baseProvider)) +- " key is configured.";- renderOnboardingProviderOptions(baseProvider);- renderOnboardingModelOptions(baseModel);-- onboardingBadge(- "onboarding-slack-badge",- slack.data.configured ? "Connected" : "Optional",- Boolean(slack.data.configured),- true,- );- $("onboarding-slack-summary").textContent = slack.data.configured- ? "Connected to " + (slack.data.teamName || slack.data.teamId || "a Slack workspace") + "."- : "Create the Slack app, install it, then add its bot and Socket Mode tokens.";- if (slack.data.createUrl) $("onboarding-slack-create").href = slack.data.createUrl;-- const configured = (catalog.data.catalog || []).filter((item) => item.configured);- onboardingBadge(- "onboarding-oauth-badge",- configured.length ? configured.length + " configured" : "Optional",- configured.length > 0,- true,- );- $("onboarding-oauth-summary").textContent = configured.length- ? configured.map((item) => connectorName(item.provider)).join(", ") + " available in the web UI."- : "Add Google, GitHub, Notion, or other OAuth clients to make those connectors available.";- viewLoadedAt.onboarding = Date.now();- if (models.data.modelCatalogRefreshing) {- void api("GET", "/api/model-providers")- .then((fresh) => {- if (!fresh.ok || requestId !== onboardingRequest || requestedView !== view) return;- const selected = $("onboarding-model-id").value;- for (const model of fresh.data.models || []) {- const options = (onboardingModels[model.provider] ||= []);- if (!options.some((option) => option.id === model.id)) options.push(model);- }- renderOnboardingModelOptions(selected);- })- .catch(() => {});- }- }- $("onboarding-model-provider").onchange = () => renderOnboardingModelOptions();- $("onboarding-model-save").onclick = async () => {- const provider = $("onboarding-model-provider").value;- const apiKey = $("onboarding-model-key").value.trim();- const modelId = $("onboarding-model-id").value;- if (!apiKey) {- setStatus("st-onboarding-model", "Enter the provider API key.", "err");- return;- }- $("onboarding-model-save").disabled = true;- setStatus("st-onboarding-model", "Validating with " + connectorName(provider) + "…", "saving", true);- const saved = await api("PUT", "/api/model-providers/" + encodeURIComponent(provider), { apiKey });- if (!saved.ok) {- $("onboarding-model-save").disabled = false;- setStatus("st-onboarding-model", saved.data?.message || "The provider rejected this key.", "err", true);- return;- }- const selected = await api("PUT", "/api/scopes/" + encodeURIComponent(orgScope()) + "/base-model", { modelId });- $("onboarding-model-save").disabled = false;- $("onboarding-model-key").value = "";- await loadOnboarding();- await loadCustomProviders();- setStatus(- "st-onboarding-model",- selected.ok ? "Key and base model saved." : "Key saved, but the base model could not be changed.",- selected.ok ? "ok" : "err",- !selected.ok,- );- };- $("onboarding-model-delete").onclick = async () => {- const provider = $("onboarding-model-provider").value;- if (- !confirm(- "Disable the " + connectorName(provider) + " model key? Models from this provider will stop working.",- )- )- return;- const removed = await api("DELETE", "/api/model-providers/" + encodeURIComponent(provider));- if (!removed.ok) {- setStatus("st-onboarding-model", removed.data?.message || "Could not disable this provider.", "err");- return;- }- await loadOnboarding();- await loadCustomProviders();- setStatus("st-onboarding-model", "Provider disabled.", "ok");- };- let modelRegistryTemplates = [];- let modelRegistryLookup = null;- let modelRegistryLookupRequest = 0;- let modelRegistryBusy = false;- function modelRegistryTemplateOptions() {- const select = $("model-registry-template");- const previous = select.value;- select.replaceChildren();- const blank = document.createElement("option");- blank.value = "";- blank.textContent = "Choose a compatible template";- select.appendChild(blank);- for (const template of modelRegistryTemplates.filter(- (m) => m.provider === $("model-registry-provider").value,- )) {- const option = document.createElement("option");- option.value = template.id;- option.textContent = template.name;- select.appendChild(option);- }- select.value = [...select.options].some((option) => option.value === previous) ? previous : "";- modelRegistryCapabilities();- }- function modelRegistryCapabilities() {- const template = modelRegistryTemplates.find((m) => m.id === $("model-registry-template").value);- $("model-registry-capabilities").textContent = template- ? `Inherited: ${template.input.join(", ")} input; reasoning ${template.reasoning ? "yes" : "no"}.`- : "";- }- function modelRegistryIdentity() {- return { provider: $("model-registry-provider").value, id: $("model-registry-id").value.trim() };- }- function resetRegistryLookup() {- modelRegistryLookupRequest++;- modelRegistryLookup = null;- $("model-registry-result").hidden = true;- $("model-registry-save").disabled = true;- $("model-registry-save").textContent = "Verify and enable";- setStatus("st-model-registry", "", "");- }- function showRegistryLookup(result) {- modelRegistryLookup = { ...result, identity: modelRegistryIdentity() };- const spec = result.spec;- modelRegistryTemplateOptions();- for (const field of ["name", "template", "contextWindow", "maxTokens"])- $("model-registry-" + field).value = spec[field] ?? "";- for (const field of ["input", "output", "cacheRead", "cacheWrite"])- $("model-registry-" + field).value = spec.cost?.[field] ?? "";- for (const field of ["base", "webui", "auxiliary", "fastMode"])- $("model-registry-" + field).checked = spec[field] ?? (field === "base" || field === "webui");- $("model-registry-tiers").value = JSON.stringify(spec.cost?.tiers ?? [], null, 2);- $("model-registry-source").textContent =- "Source: " +- result.source +- (result.catalogGeneratedAt ? " · catalog " + new Date(result.catalogGeneratedAt).toLocaleDateString() : "");- $("model-registry-summary").textContent =- result.kind === "builtin"- ? `${spec.name} · ${spec.contextWindow.toLocaleString()} context tokens · ${spec.maxTokens.toLocaleString()} maximum output · $${spec.cost.input} input / $${spec.cost.output} output per million tokens`- : spec.name || spec.id;- $("model-registry-lookup-note").textContent = result.message;- $("model-registry-result").hidden = false;- const missing = result.missing || [];- for (const field of [- "name",- "template",- "contextWindow",- "maxTokens",- "input",- "output",- "cacheRead",- "cacheWrite",- ]) {- const label = $("model-registry-" + field).closest("label");- $(missing.includes(field) ? "model-registry-missing-fields" : "model-registry-advanced-fields").appendChild(- label,- );- }- $("model-registry-missing").hidden = !missing.length;- $("model-registry-advanced").hidden = result.kind === "builtin";- $("model-registry-advanced").open = false;- $("model-registry-save").textContent =- result.kind === "builtin" ? "Verify and enable existing model" : "Verify and enable";- $("model-registry-save").disabled = false;- modelRegistryCapabilities();- }- function editRegistryModel(spec) {- if (modelRegistryBusy) return;- resetRegistryLookup();- $("model-registry-id").disabled = Boolean(spec);- $("model-registry-provider").disabled = Boolean(spec?.provider);- $("model-registry-id").value = spec?.id || "";- $("model-registry-provider").value = spec?.provider || "openai";- modelRegistryTemplateOptions();- if (spec)- showRegistryLookup({- kind: "saved",- spec,- missing: [- ...["name", "template", "contextWindow", "maxTokens"].filter((field) => spec[field] == null),- ...["input", "output", "cacheRead", "cacheWrite"].filter((field) => spec.cost?.[field] == null),- ],- source: "Saved administrator definition",- message: "Review the saved definition under Advanced overrides. Changes require verification again.",- });- }- $("model-registry-lookup").onclick = async () => {- if (modelRegistryBusy) return;- resetRegistryLookup();- const request = modelRegistryLookupRequest;- const identity = modelRegistryIdentity();- $("model-registry-lookup").disabled = true;- setStatus("st-model-registry", "Looking up exact model metadata…", "");- try {- const response = await api("POST", "/api/model-registry/lookup", identity);- if (request !== modelRegistryLookupRequest) return;- if (!response.ok) throw new Error(response.data?.message || "Lookup failed. Try again.");- showRegistryLookup(response.data);- setStatus("st-model-registry", "Metadata loaded. Review, then verify access.", "");- } catch (error) {- if (request === modelRegistryLookupRequest) setStatus("st-model-registry", error.message, "err");- } finally {- $("model-registry-lookup").disabled = false;- }- };- async function loadModelRegistry() {- const response = await api("GET", "/api/model-registry");- if (!response.ok) {- setStatus("st-model-registry", "Could not load models.", "err");- return;- }- modelRegistryTemplates = response.data.templates;- modelRegistryTemplateOptions();- const rows = $("model-registry-rows");- rows.replaceChildren();- const enabled = response.data.models.filter((m) => !m.disabled);- $("model-registry-empty").hidden = enabled.length > 0;- for (const { spec, unavailableReason, verifiedAt } of enabled) {- const row = document.createElement("tr");- for (const value of [- (spec.name || spec.id) +- " (" +- spec.id +- ")" +- (unavailableReason- ? " — " + unavailableReason- : verifiedAt- ? " — Verified with organization credentials " + new Date(verifiedAt).toLocaleString()- : " — Not verified"),- spec.provider || "Unknown",- spec.template || "Missing",- ]) {- const cell = document.createElement("td");- cell.textContent = value;- row.appendChild(cell);- }- const actions = document.createElement("td");- const edit = document.createElement("button");- edit.textContent = "Edit";- edit.onclick = () => editRegistryModel(spec);- const remove = document.createElement("button");- remove.className = "danger";- remove.textContent = "Delete";- remove.onclick = async () => {- if (!confirm("Delete " + spec.name + "? New uses will be refused.")) return;- const result = await api("DELETE", "/api/model-registry/" + encodeURIComponent(spec.id));- if (!result.ok) {- setStatus("st-model-registry", result.data?.message || "Could not delete model.", "err");- return;- }- await loadOnboarding();- editRegistryModel(null);- setStatus("st-model-registry", "Model deleted.", "ok");- };- actions.append(edit, remove);- row.appendChild(actions);- rows.appendChild(row);- }+ governanceUI.onboarding.configure({+ api,+ orgScope: () => orgScope(),+ connectorName: (id) => connectorName(id),+ view: () => view,+ loadCustomProviders: () => loadCustomProviders(),+ loaded: () => {+ viewLoadedAt.onboarding = Date.now();+ },+ navigate: (target) => openOnboardingTarget(target),+ });+ function loadOnboarding() {+ return governanceUI.onboarding.load();}- $("model-registry-provider").onchange = () => {- resetRegistryLookup();- modelRegistryTemplateOptions();- };- $("model-registry-id").oninput = resetRegistryLookup;- $("model-registry-template").onchange = modelRegistryCapabilities;- $("model-registry-new").onclick = () => editRegistryModel(null);- $("model-registry-save").onclick = async () => {- if (modelRegistryBusy || !modelRegistryLookup) return;- const lookup = modelRegistryLookup;- const identity = modelRegistryIdentity();- if (JSON.stringify(identity) !== JSON.stringify(lookup.identity)) {- resetRegistryLookup();- return;- }- const button = $("model-registry-save");- let disabledControls = [];- try {- const value = (field) => $("model-registry-" + field).value.trim();- const number = (field) => {- if (!value(field)) throw new Error(field + " is required");- return Number(value(field));- };- const builtin = lookup.kind === "builtin";- const spec = builtin- ? null- : {- ...identity,- name: value("name"),- template: value("template"),- contextWindow: number("contextWindow"),- maxTokens: number("maxTokens"),- cost: Object.fromEntries(- ["input", "output", "cacheRead", "cacheWrite"].map((field) => [field, number(field)]),- ),- };- if (spec) {- if (!spec.name || !spec.template) throw new Error("Display name and a compatible template are required.");- spec.cost.tiers = JSON.parse(value("tiers") || "[]");- for (const field of ["base", "webui", "auxiliary", "fastMode"])- spec[field] = $("model-registry-" + field).checked;- }- modelRegistryBusy = true;- disabledControls = [...button.closest("section").querySelectorAll("input,select,textarea,button")].map(- (el) => [el, el.disabled],- );- disabledControls.forEach(([el]) => {- el.disabled = true;- });- button.textContent = "Verifying…";- setStatus("st-model-registry", "Checking the model with organization credentials…", "");- const result = await api(- builtin ? "POST" : "PUT",- "/api/model-registry/" + encodeURIComponent(identity.id) + (builtin ? "/enable" : ""),- builtin ? { provider: identity.provider, verify: true } : { ...spec, verify: true },- );- if (!result.ok) throw new Error(result.data?.message || "Could not verify model.");- await loadOnboarding();- setStatus(- "st-model-registry",- builtin- ? result.data.message- : "Model verified and enabled with organization credentials. Personal-key access may differ.",- "ok",- );- } catch (error) {- setStatus("st-model-registry", error.message, "err");- } finally {- modelRegistryBusy = false;- disabledControls.forEach(([el, disabled]) => {- el.disabled = disabled;- });- button.textContent = lookup.kind === "builtin" ? "Verify and enable existing model" : "Verify and enable";- }- };- let customProvidersLoaded = [];- function parseCustomModels(text) {- return text- .split("\n")- .map((line) => line.trim())- .filter(Boolean)- .map((line) => {- const [id, name, contextWindow, maxTokens] = line.split("|").map((part) => part.trim());- const model = { id };- if (name) model.name = name;- if (contextWindow) model.contextWindow = Number(contextWindow);- if (maxTokens) model.maxTokens = Number(maxTokens);- return model;- });- }- function closeCustomProviderEditor() {- const dialog = $("custom-provider-dialog");- if (dialog.open) dialog.close();- }- function openCustomProviderEditor(provider = null) {- $("custom-provider-title").textContent = provider ? "Edit " + provider.name : "Add custom provider";- $("custom-provider-id").value = provider?.id || "";- $("custom-provider-id").disabled = !!provider;- $("custom-provider-name").value = provider?.name || "";- $("custom-provider-protocol").value = provider?.protocol || "openai";- $("custom-provider-url").value = provider?.baseUrl || "";- $("custom-provider-key").value = "";- $("custom-provider-models").value = provider- ? provider.models- .map((model) =>- [model.id, model.name, model.contextWindow, model.maxTokens].filter((part) => part != null).join(" | "),- )- .join("\n")- : "";- $("custom-provider-validate").checked = true;- setStatus("st-custom-provider", "", "");- $("custom-provider-dialog").showModal();- $(provider ? "custom-provider-name" : "custom-provider-id").focus();- }- $("custom-provider-cancel").onclick = closeCustomProviderEditor;- $("custom-provider-close").onclick = closeCustomProviderEditor;- $("custom-provider-dialog").onclick = (event) => {- if (event.target === event.currentTarget) closeCustomProviderEditor();- };- $("custom-provider-dialog").addEventListener("cancel", (event) => {- event.preventDefault();- closeCustomProviderEditor();+ governanceUI.settings.configureProviders({+ api,+ refresh: async () => {+ await loadCustomProviders();+ if (view !== "models") return;+ const requestedScope = scope;+ const requestedGeneration = governanceReq;+ const fresh = await api("GET", "/api/scopes/" + encodeURIComponent(requestedScope) + "?view=models");+ if (fresh.ok && scope === requestedScope && view === "models" && governanceReq === requestedGeneration)+ governanceUI.settings.updateCatalog(fresh.data);+ },});- async function removeCustomProvider(provider) {- if (!confirm("Remove " + provider.name + "? Its models leave every model picker.")) return;- const removed = await api("DELETE", "/api/custom-providers/" + encodeURIComponent(provider.id));- if (!removed.ok) {- setStatus("st-custom-provider", removed.data?.message || "Could not remove this provider.", "err");- return;- }- if (view === "models") await loadScope();- else await loadCustomProviders();- setStatus("st-custom-provider", "Provider removed.", "ok");- }- function customProviderRemoveButton(provider) {- const remove = document.createElement("button");- remove.className = "danger";- remove.textContent = "Remove";- remove.onclick = () => removeCustomProvider(provider);- return remove;+ function openCustomProviderEditor(provider = null) {+ governanceUI.settings.openProvider(provider);}async function loadCustomProviders() {- const res = await api("GET", "/api/custom-providers");- if (!res.ok) return;- customProvidersLoaded = (res.data?.providers || []).filter((provider) => !provider.disabled);- $("model-custom-provider-table").hidden = customProvidersLoaded.length === 0;- $("custom-provider-summary").hidden = customProvidersLoaded.length > 0;- $("custom-provider-summary").textContent = "No custom providers.";- const modelRows = $("model-custom-provider-rows");- modelRows.textContent = "";- customProvidersLoaded.forEach((provider) => {- const tr = document.createElement("tr");- [- provider.name + " (" + provider.id + ")",- CUSTOM_PROVIDER_PROTOCOL_LABELS[provider.protocol] || provider.protocol,- provider.baseUrl,- String(provider.models.length),- provider.hasKey ? "Set (write-only)" : "None",- ].forEach((textContent) => {- const td = document.createElement("td");- td.textContent = textContent;- tr.appendChild(td);- });- const actions = document.createElement("td");- const edit = document.createElement("button");- edit.type = "button";- edit.textContent = "Edit";- edit.onclick = () => openCustomProviderEditor(provider);- actions.append(edit, customProviderRemoveButton(provider));- tr.appendChild(actions);- modelRows.appendChild(tr);- });- const rows = $("custom-provider-rows");- rows.textContent = "";- $("custom-provider-empty").hidden = customProvidersLoaded.length > 0;- customProvidersLoaded.forEach((provider) => {- const tr = document.createElement("tr");- const cells = [- provider.name + " (" + provider.id + ")",- CUSTOM_PROVIDER_PROTOCOL_LABELS[provider.protocol] || provider.protocol,- provider.baseUrl,- provider.models.map((model) => model.id).join(", "),- provider.hasKey ? "set (write-only)" : "none",- ];- cells.forEach((textContent) => {- const td = document.createElement("td");- td.textContent = textContent;- tr.appendChild(td);- });- const actions = document.createElement("td");- const edit = document.createElement("button");- edit.type = "button";- edit.textContent = "Edit";- edit.onclick = () => openCustomProviderEditor(provider);- actions.appendChild(edit);- actions.appendChild(customProviderRemoveButton(provider));- tr.appendChild(actions);- rows.appendChild(tr);- });+ await governanceUI.settings.loadProviders();}async function loadPersonalKeychainSummary(requestId, requestedScope) {- $("keychain-user-count").textContent = "—";- $("keychain-standing-count").textContent = "—";+ governanceUI.settings.keychainSummary(null);const res = await api("GET", "/api/keychain?summary=1");if (requestId !== governanceReq || requestedScope !== scope || view !== "credentials") return;- $("keychain-user-count").textContent = res.ok && res.data?.enabled !== false ? String(res.data.users) : "—";- $("keychain-standing-count").textContent =- res.ok && res.data?.enabled !== false ? String(res.data.standing) : "—";- }- $("custom-provider-save").onclick = async () => {- const id = $("custom-provider-id").value.trim();- const name = $("custom-provider-name").value.trim();- const baseUrl = $("custom-provider-url").value.trim();- const models = parseCustomModels($("custom-provider-models").value);- if (!id || !name || !baseUrl || models.length === 0) {- setStatus("st-custom-provider", "Provider id, name, base URL, and at least one model are required.", "err");- return;- }- const apiKey = $("custom-provider-key").value.trim();- const body = {- name,- protocol: $("custom-provider-protocol").value,- baseUrl,- models,- ...(apiKey ? { apiKey } : {}),- ...($("custom-provider-validate").checked ? {} : { validate: false }),- };- $("custom-provider-save").disabled = true;- setStatus("st-custom-provider", "Saving…", "saving", true);- const saved = await api("PUT", "/api/custom-providers/" + encodeURIComponent(id), body);- $("custom-provider-save").disabled = false;- if (!saved.ok) {- setStatus("st-custom-provider", saved.data?.message || "Could not save this provider.", "err", true);- return;- }- $("custom-provider-key").value = "";- if (view === "models") await loadScope();- else await loadCustomProviders();- closeCustomProviderEditor();- };+ governanceUI.settings.keychainSummary(res.ok ? res.data : null);+ }function openOnboardingTarget(target) {- setView("connectors");+ setView(target === "slack" ? "slack-settings" : "connectors");setTimeout(() =>$(target === "slack" ? "card-slack-installation" : "card-connectors")?.scrollIntoView({@@ -11468,29 +8490,9 @@100,);}- document.querySelectorAll("[data-onboarding-target]").forEach((button) => {- button.onclick = () => openOnboardingTarget(button.dataset.onboardingTarget);- });- let connectorCatalog = [];const connectorName = (id) => (id === "x" ? "X" : id.charAt(0).toUpperCase() + id.slice(1));const orgScope = () => "org:" + orgId;- let connEditing = null;- let connList = [];- const DESIGN_TOKENS = [- ["--bg", "Page behind every surface"],- ["--surface", "Cards, dialogs, table bodies"],- ["--subtle", "Quiet control and inset backgrounds"],- ["--border", "Every hairline and divider"],- ["--text", "Primary copy"],- ["--muted", "Secondary copy and hints"],- ["--cta", "Primary actions and selected controls"],- ["--ok", "Confirmed and healthy"],- ["--warn", "Needs attention"],- ["--danger", "Destructive and failed"],- ["--trigger", "Automation and triggers"],- ];-let twoWayToggleId = 0;function twoWayToggle({ label, options, value, onChange, disabled = false }) {if (options.length !== 2 || options[0].value === options[1].value)@@ -11520,995 +8522,28 @@return group;}- function designSpec(label, note, demo, stack) {- return (- '<div class="spec"><div class="spec-label">' +- label +- (note ? "<span>" + note + "</span>" : "") +- '</div><div class="spec-demo' +- (stack ? " stack" : "") +- '">' +- demo +- "</div></div>"- );+ function renderDesignLibrary() {+ governanceUI.design.show({+ stateToUrl,+ scope: () => scope,+ searchField,+ twoWayToggle,+ fileThumb,+ initCustomDropdowns,+ });}- function designSection(title, blurb, specs) {- return (- '<section class="design-group"><h2>' + title + "</h2><p>" + blurb + "</p>" + specs.join("") + "</section>"- );+ governanceUI.integrations.configure({ api, orgScope, connectorName, fmtTime });+ governanceUI.integrations.mountBuiltIns();+ async function loadConnectors() {+ return governanceUI.integrations.loadConnectors();}-- let designLibraryRendered = false;- function renderDesignLibrary() {- if (designLibraryRendered) return;- const root = $("view-design");- const swatches = DESIGN_TOKENS.map(- (t) =>- '<div class="swatch"><div class="swatch-chip" style="background: var(' +- t[0] +- ')"></div><div class="swatch-meta"><b>' +- t[0] +- "</b>" +- t[1] +- "</div></div>",- ).join("");-- root.innerHTML = [- '<p class="lead">Components and page patterns from the redesigned admin portal, including Skills, Files, Sessions, Metrics, Audit, and Egress. Examples use fictional data and do not save changes.</p>',- designSection("Foundations", "One palette, a small type scale, and consistent spacing.", [- designSpec(- "Semantic colors",- "Shared theme tokens · light and dark",- '<div class="swatches">' + swatches + "</div>",- ),- designSpec(- "Type & spacing",- "22px page title · 14px section title · 13px controls and copy",- '<div class="shell-title">Page title</div><div class="head"><h2>Section title</h2><p>Descriptions explain the setting.</p></div><label>Field label</label><p class="hint">4px label gap · 8px action gap · 24px section spacing</p>',- true,- ),- ]),- designSection(- "Page layout",- "Start with the shared shell. Align titles, sections, and rows to the same content edge; use whitespace and dividers instead of enclosing cards.",- [- designSpec(- "Desktop and mobile",- "Authored layout diagrams · .admin-main → .admin-inner → .shellbar",- '<div class="design-layouts"><div class="design-layout-frame"><div class="design-layout-nav">Sidebar<br>Independent scroll</div><div class="design-layout-main"><div class="design-layout-content"><div class="design-layout-title">Title <span>Search / action</span></div><div class="design-layout-section">Open section<br><small>Heading + description</small></div><div class="design-layout-lines">Compact rows<br>────────────────<br>Compact rows</div></div></div></div><div class="design-layout-frame mobile"><div class="design-layout-nav">Horizontal navigation</div><div class="design-layout-main"><div class="design-layout-content"><div class="design-layout-title">Title</div><div class="design-layout-section">Full-width search</div><div class="design-layout-lines">Stacked content<br>────────────<br>Local table scroll</div></div></div></div></div>',- true,- ),- designSpec(- "Width and page padding",- "Current New CSS · index.html and admin-components.css",- '<div class="tablewrap"><table><thead><tr><th>Rule</th><th>Desktop</th><th>Small screens</th></tr></thead><tbody><tr><td>Navigation</td><td>280px sidebar; independent scroll</td><td>Horizontal navigation at ≤900px</td></tr><tr><td>Content width</td><td>960px maximum, centered; fluid below that</td><td>Available width; min-width: 0</td></tr><tr><td>Main padding</td><td>28px top and sides</td><td>At ≤900px: 18px top, 14px sides with safe-area insets</td></tr><tr><td>Bottom clearance</td><td colspan="2">110px for the fixed Original / New switch</td></tr><tr><td>Page heading</td><td colspan="2">22px / 500 weight; shared shell spacing 16px (activity pages use 24px)</td></tr><tr><td>Sections</td><td colspan="2">24px between artifact sections; 12px from section heading to content</td></tr><tr><td>Controls</td><td colspan="2">32px height · 6px radius · 8px gap · 4px label gap</td></tr></tbody></table></div>',- true,- ),- designSpec(- "Choose a page pattern",- "Live references · preserve the selected organization",- '<div class="design-page-links"><a data-design-view="governance">Governance / Models</a><p>Descriptions beside settings, 40px column gap; stack on small screens. Keep Apply right-aligned with status on its left.</p><a data-design-view="skills">Skills</a><p>Open installed-skill and skill-pack sections; compact tables and an inline registration form.</p><a data-design-view="files">Files</a><p>Search in the header, flat upload toolbar, then scopes or files with metadata.</p><a data-design-view="history">Sessions</a><p>Two-way sort toggle, named environments, and a separately titled conversation list.</p><a data-design-view="audit">Audit</a> · <a data-design-view="egress">Egress</a><p>Filters above plain tables; headers stay transparent and regular-weight.</p></div>',- true,- ),- designSpec(- "Responsive behavior",- "Page-level rules",- '<ul class="design-rules"><li>At ≤900px, the sidebar becomes horizontal navigation.</li><li>At ≤640px, Skills and Files search uses the full row; dense rows allow more height and Files metadata wraps below the name.</li><li>Wide tables scroll inside .tablewrap. Never force the entire document wider than the viewport.</li><li>Keep all actions and metadata available on mobile. Use wrapping or local scrolling rather than hiding content.</li><li>Sidebar scrolling is contained; reaching its end must not scroll the main page.</li></ul>',- true,- ),- ],- ),- designSection(- "Artifact and reporting patterns",- "Compositions from the recent redesigns. Shared helpers render the lists; the form and report examples are local demonstrations.",- [- designSpec(- "Scope list",- "denseList() · shared Skills / Files row styles · Enter or click selects a demo row",- '<div id="design-scope-list"></div><p class="hint" id="design-scope-status" role="status">Choose a scope to try the row interaction.</p>',- true,- ),- designSpec(- "File list and upload toolbar",- "denseList() + fileThumb() · .file-upload · visual upload example, no network requests",- '<div class="file-upload"><div class="file-upload-actions"><button type="button" class="primary upload-button" id="design-upload"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 16V3m-5 5 5-5 5 5M4 15v5a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-5"/></svg><span>Upload</span></button></div></div><div id="design-file-list"></div><p class="hint" id="design-file-status" role="status">File names, thumbnails, sizes, and dates stay visible.</p>',- true,- ),- designSpec(- "Skill-pack registration",- ".pack-register · shared Skills styles · local form demonstration",- '<div class="pack-register"><input type="url" aria-label="Example skill repository" placeholder="https://github.com/example/skills"/><button type="button" id="design-register">Register</button><button type="button" class="linkish" id="design-advanced" aria-expanded="false" aria-controls="design-pack-advanced">Advanced</button></div><div class="pack-adv hidden" id="design-pack-advanced"><div><label for="design-pack-name">Name</label><input id="design-pack-name" type="text" placeholder="Team skills"/></div><div><label for="design-pack-ref">Ref</label><input id="design-pack-ref" type="text" placeholder="main"/></div><div><label for="design-pack-path">Path</label><input id="design-pack-path" type="text" placeholder="skills/"/></div></div><p class="hint" id="design-pack-status" role="status">Registration is a local demonstration.</p>',- true,- ),- designSpec(- "Open report section",- "Authored Metrics / Audit / Egress composition · statline() + shared table controls",- '<section class="design-open-section"><h3>Activity summary</h3><p class="hint">Keep descriptions beside the section they explain.</p><div id="design-metrics-summary"></div><div class="tablewrap"><table><thead><tr><th>Scope</th><th>Requests</th><th>Status</th></tr></thead><tbody><tr><td>Example team</td><td>128</td><td><span class="badge ok">Healthy</span></td></tr><tr><td>Research</td><td>24</td><td><span class="badge muted">Idle</span></td></tr></tbody></table></div></section>',- true,- ),- ],- ),- designSection("Actions", "32px controls with a 6px radius. Primary actions use the dark blue accent.", [- designSpec(- "Buttons",- "button · .primary · .danger",- '<button type="button" class="primary">Apply</button><button type="button">Add item</button><button type="button" class="danger">Delete</button><button type="button" disabled>Disabled</button><button type="button" class="primary" disabled>Apply</button>',- ),- designSpec(- "Quiet actions",- ".viewlink · .icon-button",- '<button type="button" class="viewlink">View history ›</button><button type="button" class="icon-button" aria-label="Remove example">×</button>',- ),- designSpec(- "Save feedback",- ".foot · .status · native input events",- '<section class="card"><div class="head"><h2>Example setting</h2><p>Edit the name to try unsaved and saved states.</p></div><div class="body"><label for="design-name">Display name</label><input id="design-name" type="text" value="Acme" /></div><div class="foot"><span class="status" id="design-status" role="status">No changes</span><button class="primary" type="button" id="design-apply" disabled>Apply</button></div></section>',- true,- ),- ]),- designSection(- "Two-way toggle",- "Choose one of two mutually exclusive options. Tab to focus; use arrow keys to switch.",- [- designSpec(- "Segmented choice",- "twoWayToggle({ label, options, value, onChange, disabled }) · shared radio group",- '<div id="design-two-way-toggle"></div><p class="hint" id="design-two-way-status" role="status">Selected: Human activity</p>',- true,- ),- designSpec(- "Disabled",- "The same component with disabled: true",- '<div id="design-two-way-disabled"></div>',- ),- ],- ),- designSection(- "Search",- "A transparent background, subtle border, search icon, and clear action. Focus uses the shared dark blue accent.",- [- designSpec(- "Search field",- "searchField() · shared with Slack and page toolbar searches",- '<div id="design-search"></div><p class="hint" id="design-search-status" role="status">Type to try the search field, then clear it.</p>',- true,- ),- designSpec(- "Populated and disabled",- "The same component with value and disabled options",- '<div id="design-search-filled"></div><div id="design-search-disabled"></div>',- true,- ),- ],- ),- designSection("Fields", "Shared sizing, labels, hints, focus rings, validation, and disabled states.", [- designSpec(- "Text fields",- "input · label · .hint",- '<label for="design-text">Client ID</label><input id="design-text" type="text" placeholder="Enter a client ID" aria-describedby="design-text-hint" /><p class="hint" id="design-text-hint">A label stays visible when the field has a value.</p><label for="design-number">Limit</label><input id="design-number" type="number" value="10" /><label for="design-disabled">Inherited value</label><input id="design-disabled" type="text" disabled value="Organization default" /><label for="design-invalid">Required value</label><input id="design-invalid" type="text" aria-invalid="true" aria-describedby="design-error" /><p class="status err" id="design-error">Enter a value to continue.</p>',- true,- ),- designSpec(- "Dropdown",- "select → shared .dd accessible dropdown",- '<label for="design-select">Scope</label><select id="design-select"><option>Organization</option><option>Team</option><option>Personal</option></select>',- true,- ),- designSpec(- "Multiline",- "textarea · same field border and label",- '<label for="design-notes">Instructions</label><textarea id="design-notes" rows="3" placeholder="Write instructions…"></textarea>',- true,- ),- designSpec(- "Choices",- ".choice-stack · .posture-choice",- '<div class="choice-stack"><label class="posture-choice"><input type="radio" name="design-choice" checked /><span><strong>Automatic</strong><small>Review activity when needed.</small></span></label><label class="posture-choice"><input type="radio" name="design-choice" /><span><strong>Always review</strong><small>Review every request.</small></span></label></div>',- true,- ),- designSpec(- "Switch & checkbox",- ".setting-toggle · .setting-switch · input[type=checkbox]",- '<label class="setting-toggle"><input type="checkbox" checked /><span class="setting-switch" aria-hidden="true"></span><span>Enable feature</span></label><label><input type="checkbox" /> Include optional details</label>',- true,- ),- ]),- designSection(- "Sections & lists",- "Open sections separated by rules, with the same headings, descriptions, and row actions.",- [- designSpec(- "Settings section",- ".card > .head / .body / .foot",- '<section class="card"><div class="head"><h2>Section title</h2><p>Explain what the setting changes.</p></div><div class="body"><label for="design-section-field">Setting label</label><input id="design-section-field" type="text" value="Default value" /></div><div class="foot"><span class="status">No changes</span><button class="primary" type="button" disabled>Apply</button></div></section>',- true,- ),- designSpec(- "List row",- ".credential-row · .credential-title · .credential-actions",- '<div class="credential-row"><div class="credential-main"><div class="credential-title"><strong>Example service</strong><span class="credential-slug">example</span></div><p class="hint">Available to the organization</p></div><div class="credential-actions"><button type="button">Edit</button><button type="button" class="danger">Delete</button></div></div>',- true,- ),- designSpec(- "Model chip",- ".model-chip · removable item",- '<div class="model-chip"><span>Example model</span><button type="button" id="design-remove-chip" aria-label="Remove example model">×</button></div><span class="hint" id="design-chip-status" role="status"></span>',- ),- designSpec(- "Badges & feedback",- ".badge · .status · semantic colors",- '<span class="badge muted">Inherited</span><span class="badge ok">Enabled</span><span class="badge warn">Needs review</span><span class="badge err">Failed</span><span class="status ok">Saved</span><span class="status err">Save failed</span>',- ),- designSpec(- "Empty state",- ".empty",- '<div class="empty">No items yet. Add an item to get started.</div>',- true,- ),- ],- ),- designSection(- "Dialogs",- "The same controls in a focused, keyboard-accessible dialog. Escape closes it and returns focus.",- [- designSpec(- "Review dialog",- "dialog.review-dialog · shared fields and actions",- '<button type="button" id="design-dialog-open">Open example dialog</button><dialog class="review-dialog" id="design-dialog" aria-labelledby="design-dialog-title"><div class="review-dialog-head"><h2 id="design-dialog-title">Example dialog</h2><p>Try the shared controls without changing any settings.</p></div><div class="review-dialog-body"><label for="design-dialog-field">Display name</label><input id="design-dialog-field" type="text" value="Example" /></div><div class="review-dialog-foot"><button type="button" id="design-dialog-close">Cancel</button><button type="button" class="primary" id="design-dialog-done">Done</button></div></dialog>',- ),- ],- ),- designSection(- "Tables",- "13px cells, quiet headers, consistent padding, and scrolling inside the table on small screens.",- [- designSpec(- "Data table",- ".tablewrap > table · th · td",- '<div class="tablewrap"><table><thead><tr><th>Name</th><th>Access</th><th>Status</th><th>Actions</th></tr></thead><tbody><tr><td>Alex Example</td><td>Organization</td><td><span class="badge ok">Active</span></td><td><button type="button">Edit</button></td></tr><tr><td>Sam Example</td><td>Team</td><td><span class="badge muted">Invited</span></td><td><button type="button" disabled>Edit</button></td></tr></tbody></table></div>',- true,- ),- ],- ),- ].join("");- const contents = document.createElement("nav");- contents.className = "design-contents";- contents.setAttribute("aria-label", "Design system sections");- root.querySelectorAll(".design-group").forEach((section) => {- const title = section.querySelector("h2").textContent;- section.id = "design-group-" + title.toLowerCase().replace(/[^a-z0-9]+/g, "-");- const link = document.createElement("a");- link.href = "#" + section.id;- link.textContent = title;- contents.appendChild(link);- });- root.querySelector(".lead").after(contents);- root.querySelectorAll(".design-page-links a").forEach((link) => {- link.href = stateToUrl({ view: link.dataset.designView, scope });- });- $("design-scope-list").appendChild(- denseList(- [- { name: "Example team", preview: "12 skills", time: "5 mins ago" },- { name: "Research", preview: "4 skills", time: "Yesterday" },- ],- (item) => item,- (item) => {- $("design-scope-status").textContent = "Selected: " + item.name;- },- "No skills yet.",- ),- );- $("design-file-list").appendChild(- denseList(- [- { name: "Research brief.pdf", size: "240 KB", date: "Today" },- { name: "Project notes.md", size: "8 KB", date: "Yesterday" },- ],- (item) => ({- name: item.name,- icon: fileThumb(item),- preview: "Example team",- time: item.size + " · " + item.date,- }),- (item) => {- $("design-file-status").textContent = "Selected: " + item.name + " (demo only)";- },- "No documents saved yet.",- ),- );- $("design-upload").onclick = () => {- $("design-file-status").textContent =- "On Files, this opens the file picker. This example does not upload files.";- };- $("design-register").onclick = () => {- $("design-pack-status").textContent = "Example registered locally. No repository was fetched.";- };- $("design-advanced").onclick = () => {- const expanded = $("design-advanced").getAttribute("aria-expanded") !== "true";- $("design-advanced").setAttribute("aria-expanded", String(expanded));- $("design-pack-advanced").classList.toggle("hidden", !expanded);- };- $("design-metrics-summary").appendChild(statline(["152 requests", "2 scopes", "Last 24 hours"]));- $("design-search").appendChild(- searchField({- placeholder: "Search messages…",- onInput: (value) => {- $("design-search-status").textContent = value- ? "Search query: " + value- : "Type to try the search field, then clear it.";- },- }),- );- $("design-search-filled").appendChild(- searchField({ placeholder: "Search messages…", value: "Product updates" }),- );- $("design-search-disabled").appendChild(searchField({ placeholder: "Search unavailable", disabled: true }));- const toggleOptions = [- { value: "human", label: "Human activity" },- { value: "all", label: "All activity" },- ];- $("design-two-way-toggle").appendChild(- twoWayToggle({- label: "Example activity sort",- options: toggleOptions,- value: "human",- onChange: (value) => {- $("design-two-way-status").textContent =- "Selected: " + toggleOptions.find((option) => option.value === value).label;- },- }),- );- $("design-two-way-disabled").appendChild(- twoWayToggle({- label: "Disabled activity sort",- options: toggleOptions,- value: "human",- disabled: true,- onChange: () => {},- }),- );- let savedName = "Acme";- $("design-name").oninput = () => {- const dirty = $("design-name").value !== savedName;- $("design-apply").disabled = !dirty;- $("design-status").textContent = dirty ? "Unsaved changes" : "No changes";- };- $("design-apply").onclick = () => {- savedName = $("design-name").value;- $("design-apply").disabled = true;- $("design-status").textContent = "Saved in this example";- };- $("design-remove-chip").onclick = () => {- $("design-remove-chip").closest(".model-chip").remove();- $("design-chip-status").textContent = "Example model removed";- };- $("design-dialog-open").onclick = () => $("design-dialog").showModal();- $("design-dialog-close").onclick = () => $("design-dialog").close();- $("design-dialog-done").onclick = () => $("design-dialog").close();- initCustomDropdowns(root);- designLibraryRendered = true;- }-- async function loadConnectors() {- void loadSlackInstallation();- const [catalog, r] = await Promise.all([- api("GET", "/api/connector-catalog"),- api("GET", "/api/scopes/" + encodeURIComponent(orgScope()) + "?view=connectors"),- ]);- if (!catalog.ok) {- setStatus("st-connectors", catalog.data?.message || "Failed to load connector setup.", "err");- return;- }- connectorCatalog = catalog.data.catalog || [];- renderBuiltInConnectors();- if (!r.ok) {- setStatus(- "st-connectors",- r.status === 403 ? "Only an org admin can manage connectors." : r.data?.message || "Failed to load.",- "err",- );- return;- }- renderConnList(r.data.connectors || []);- if (connEditing && !connList.some((c) => c.provider === connEditing)) connEditing = null;- if (connEditing) {- populateConnProviders();- $("conn-provider").value = connEditing;- $("conn-provider").disabled = true;- } else resetConnForm();- }- function renderBuiltInConnectors() {- const root = $("built-in-connectors");- root.textContent = "";- if (!connectorCatalog.length) {- root.className = "hint";- root.textContent = "No built-in connectors are available.";- return;- }- root.className = "";- connectorCatalog.forEach((connector) => {- const row = document.createElement("div");- row.className = "credential-row";- const main = document.createElement("div");- main.className = "credential-main";- const title = document.createElement("strong");- title.textContent = connectorName(connector.provider);- const state = document.createElement("div");- state.className = "hint";- state.textContent = connector.configured ? "Available to users" : "Requires an OAuth app";- main.append(title, state);- row.append(- main,- badge(connector.configured ? "Configured" : "Not configured", connector.configured ? "ok" : "muted"),- );- root.appendChild(row);- });- }- function renderConnList(list) {- connList = list;- const root = $("conn-list");- root.textContent = "";- const inherited = connectorCatalog- .filter((item) => item.configured && !list.some((entry) => entry.provider === item.provider))- .map((item) => ({ provider: item.provider, inherited: true }));- const displayed = [...list, ...inherited];- if (!displayed.length) {- root.className = "hint";- root.textContent = "No connectors configured. Add one below to make it linkable in the web UI.";- return;- }- root.className = "";- displayed.forEach((c) => {- const row = document.createElement("div");- row.className = "credential-row";- if (c.provider === connEditing) row.classList.add("is-editing");- const left = document.createElement("div");- left.className = "credential-main";- const title = document.createElement("div");- title.className = "credential-title";- const name = document.createElement("strong");- name.textContent = connectorName(c.provider);- const slug = document.createElement("span");- slug.className = "credential-slug";- slug.textContent = c.provider;- title.append(name, slug);- const meta = document.createElement("div");- meta.className = "hint";- meta.textContent = c.inherited- ? "Configured by deployment secrets"- : "client " +- (c.clientId || "None") +- (c.updatedBy ? " · by " + c.updatedBy : "") +- (c.updatedAt ? " · " + fmtTime(c.updatedAt) : "");- const badges = document.createElement("div");- badges.className = "credential-badges";- badges.append(- badge(- c.inherited ? "Enabled" : c.enabled === false ? "Disabled" : "Enabled",- c.enabled === false ? "warn" : "ok",- ),- badge(- c.inherited || c.hasSecret ? "Secret set" : "Secret missing",- c.inherited || c.hasSecret ? "ok" : "err",- ),- );- left.append(title, meta, badges);- const actions = document.createElement("div");- actions.className = "credential-actions";- if (c.inherited) {- const override = document.createElement("button");- override.type = "button";- override.textContent = "Override here";- override.onclick = () => {- resetConnForm();- $("conn-provider").value = c.provider;- renderConnGuide();- $("card-connectors").scrollIntoView({ behavior: "smooth", block: "nearest" });- };- actions.appendChild(override);- } else {- const edit = document.createElement("button");- edit.type = "button";- edit.textContent = "Edit";- edit.onclick = () => loadConnForm(c);- const del = document.createElement("button");- del.type = "button";- del.className = "rowbtn danger";- del.textContent = "Delete";- del.title = "Delete connector";- del.setAttribute("aria-label", "Delete " + connectorName(c.provider));- del.onclick = () => deleteConn(c.provider);- actions.appendChild(edit);- actions.appendChild(del);- }- row.appendChild(left);- row.appendChild(actions);- root.appendChild(row);- });- }- function populateConnProviders() {- const sel = $("conn-provider");- const cur = sel.value;- sel.textContent = "";- connectorCatalog.forEach((c) => {- const configured = c.configured;- const o = document.createElement("option");- o.value = c.provider;- o.textContent = connectorName(c.provider) + (configured ? " (configured)" : "");- sel.appendChild(o);- });- if (cur && connectorCatalog.some((c) => c.provider === cur)) sel.value = cur;- renderConnGuide();- }- function renderConnGuide() {- const root = $("conn-guide");- root.textContent = "";- const connector = connectorCatalog.find((c) => c.provider === $("conn-provider").value);- if (!connector) return;- const callbackUrl = location.origin + "/v1/connectors/oauth/" + connector.redirectPath;- const open = document.createElement("a");- open.href = connector.setupGuide.url;- open.target = "_blank";- open.rel = "noopener noreferrer";- open.textContent = "Open " + connector.setupGuide.console + " ↗";- const callback = document.createElement("div");- callback.textContent = "Callback URL: " + callbackUrl;- const scopes = document.createElement("div");- scopes.textContent = connector.scopes.length- ? "Scopes: " + connector.scopes.join(", ")- : "Scopes are selected in the provider.";- const steps = document.createElement("ol");- connector.setupGuide.steps.forEach((text) => {- const item = document.createElement("li");- item.textContent = text;- steps.appendChild(item);- });- root.append(open, callback, scopes, steps);- }- function loadConnForm(c) {- $("conn-editor").classList.remove("hidden");- $("add-oauth-app").classList.add("hidden");- $("conn-save").classList.remove("hidden");- $("conn-reset").classList.remove("hidden");- connEditing = c.provider;- $("conn-form-title").textContent = "Editing " + connectorName(c.provider);- $("conn-form-mode").textContent = "Editing";- $("conn-form-mode").className = "badge info";- $("conn-save").textContent = "Save changes";- $("conn-reset").textContent = "Cancel";- populateConnProviders();- $("conn-provider").value = c.provider;- $("conn-provider").disabled = true;- $("conn-client-id").value = c.clientId || "";- $("conn-client-secret").value = "";- $("conn-client-secret").placeholder = c.hasSecret ? "•••• set (re-enter to replace)" : "(write-only)";- $("conn-secret-hint").textContent =- "Saving requires the client secret. Re-enter it to keep this connector working.";- $("conn-enabled").checked = c.enabled !== false;- renderConnList(connList);- $("card-connectors").scrollIntoView({ behavior: "smooth", block: "nearest" });- }- function resetConnForm() {- $("conn-editor").classList.add("hidden");- $("add-oauth-app").classList.remove("hidden");- $("conn-save").classList.add("hidden");- $("conn-reset").classList.add("hidden");- connEditing = null;- $("conn-form-title").textContent = "Add a connector";- $("conn-form-mode").textContent = "New";- $("conn-form-mode").className = "badge muted";- $("conn-save").textContent = "Save connector";- $("conn-reset").textContent = "Cancel";- populateConnProviders();- $("conn-provider").disabled = false;- if ($("conn-provider").options.length) $("conn-provider").selectedIndex = 0;- renderConnGuide();- $("conn-client-id").value = "";- $("conn-client-secret").value = "";- $("conn-client-secret").placeholder = "(write-only)";- $("conn-secret-hint").textContent = "Secret values are write-only and will not be displayed after saving.";- $("conn-enabled").checked = true;- if (connList.length) renderConnList(connList);- }- $("conn-provider").onchange = renderConnGuide;- $("add-oauth-app").onclick = () => {- resetConnForm();- $("conn-editor").classList.remove("hidden");- $("add-oauth-app").classList.add("hidden");- $("conn-save").classList.remove("hidden");- $("conn-reset").classList.remove("hidden");- $("conn-client-id").focus();- $("card-connectors").scrollIntoView({ behavior: "smooth", block: "start" });- };- let slackLinkStarted = false;async function loadSlackInstallation() {- const r = await api("GET", "/api/slack-installation");- if (!r.ok) {- setStatus("st-slack-installation", r.data?.message || "Failed to load Slack status.", "err");- return;- }- $("slack-installation-start").classList.toggle("hidden", !r.data.installAvailable);- $("slack-installation-start").disabled = r.data.configured && r.data.source === "admin";- $("slack-installation-start").title =- r.data.configured && r.data.source === "admin"- ? "Remove your current connection before switching to the hosted app."- : "";- $("slack-installation-start-label").textContent = r.data.configured ? "Re-add to Slack" : "Add to Slack";- $("slack-installation-description").textContent = r.data.configured- ? r.data.source === "service"- ? "QM app"- : "Custom app"- : r.data.installAvailable- ? "Add the QM app or connect your own below."- : "Create a Slack app from our manifest, then connect it here.";- $("slack-own-app-label").textContent = r.data.installAvailable ? "Use your own Slack app" : "Set up Slack";- $("slack-hosted-switch").classList.toggle("hidden", !r.data.installAvailable);- if (!r.data.installAvailable && !r.data.configured) $("slack-own-app-guide").open = true;- if (new URLSearchParams(location.search).get("setup") === "slack") {- $("slack-own-app-guide").open = true;- $("card-slack-installation").scrollIntoView({ block: "start" });- }- if (r.data.createUrl) $("slack-installation-create").href = r.data.createUrl;- $("slack-installation-state").textContent = r.data.configured- ? r.data.teamName || r.data.teamId || "Slack workspace"- : r.data.source === "invalid_environment"- ? "Finish connecting your app"- : "Connect your workspace";- $("slack-installation-delete").classList.toggle("hidden", !r.data.configured);- $("slack-installation-delete").disabled = !r.data.configured;- const step = new URLSearchParams(location.search).get("slack");- if (!slackLinkStarted && r.data.installAvailable && ["setup", "install"].includes(step)) {- slackLinkStarted = true;- if (r.data.configured && !(r.data.source === "service" && r.data.setup?.connected === false)) {- setStatus("st-slack-installation", "Slack is already configured. Return to your conversation.", "ok");- } else {- await startSlackInstallation(step);- }- }- if (step === "connected" && r.data.configured && r.data.setup?.connected) {- setStatus("st-slack-installation", "Connected. You can return to your QM conversation.", "ok");- }- }- async function startSlackInstallation(step = "install") {- $("slack-installation-start").disabled = true;- const r = await api("POST", "/api/slack-installation/start", { step });- $("slack-installation-start").disabled = false;- if (r.ok && r.data.url) {- const form = document.createElement("form");- form.method = "POST";- form.action = r.data.url;- document.body.appendChild(form);- form.submit();- } else setStatus("st-slack-installation", "Could not start Slack installation. Please try again.", "err");- }- $("slack-installation-start").onclick = () => startSlackInstallation();- $("slack-installation-save").onclick = async () => {- const botToken = $("slack-bot-token").value.trim();- const appToken = $("slack-app-token").value.trim();- if (!botToken || !appToken) {- setStatus("st-slack-installation", "Both Slack tokens are required.", "err");- return;- }- $("slack-installation-save").disabled = true;- setStatus("st-slack-installation", "Validating with Slack…", "saving", true);- const r = await api("PUT", "/api/slack-installation", { botToken, appToken });- $("slack-installation-save").disabled = false;- if (!r.ok) {- setStatus("st-slack-installation", r.data?.message || "Slack validation failed.", "err");- return;- }- $("slack-bot-token").value = "";- $("slack-app-token").value = "";- $("slack-token-editor").classList.add("hidden");- $("slack-installation-save").classList.add("hidden");- await loadSlackInstallation();- setStatus(- "st-slack-installation",- "Tokens verified and saved. Allow a few seconds, then test a mention and DM in Slack.",- "ok",- );- };- $("slack-enter-tokens").onclick = () => {- $("slack-token-editor").classList.remove("hidden");- $("slack-installation-save").classList.remove("hidden");- $("slack-bot-token").focus();- $("card-slack-installation").scrollIntoView({ behavior: "smooth", block: "start" });- };- $("slack-installation-delete").onclick = async () => {- if (- !confirm(- "Disconnect this Slack app? QM will stop replying in Slack until you reconnect. The app will remain installed in your workspace.",- )- )- return;- const r = await api("DELETE", "/api/slack-installation");- if (!r.ok) {- setStatus("st-slack-installation", r.data?.message || "Remove failed.", "err");- return;- }- await loadSlackInstallation();- setStatus("st-slack-installation", "Slack disconnected.", "ok");- };- $("conn-reset").onclick = resetConnForm;- async function deleteConn(provider) {- if (- !confirm(- "Delete the OAuth client for " +- connectorName(provider) +- "? This hides the connector in everyone's web UI; existing links stop working.",- )- )- return;- const r = await api("PUT", "/api/scopes/" + encodeURIComponent(orgScope()) + "/connectors", {- provider,- delete: true,- });- if (r.ok) {- resetConnForm();- await loadConnectors();- setStatus("st-connectors", "Deleted", "ok");- } else setStatus("st-connectors", r.data?.message || "Delete failed.", "err");- }- $("conn-save").onclick = async () => {- const provider = $("conn-provider").value;- const clientId = $("conn-client-id").value.trim();- const clientSecret = $("conn-client-secret").value;- if (!provider) {- setStatus("st-connectors", "Choose a connector.", "err");- return;- }- if (!clientId) {- setStatus("st-connectors", "Client ID is required.", "err");- return;- }- if (!clientSecret) {- setStatus("st-connectors", "Client secret is required.", "err");- return;- }- $("conn-save").disabled = true;- setStatus("st-connectors", "Saving...", "saving", true);- const r = await api("PUT", "/api/scopes/" + encodeURIComponent(orgScope()) + "/connectors", {- provider,- clientId,- clientSecret,- enabled: $("conn-enabled").checked,- });- $("conn-save").disabled = false;- if (r.ok) {- resetConnForm();- await loadConnectors();- setStatus("st-connectors", "Saved", "ok");- } else- setStatus(- "st-connectors",- r.status === 403 ? "Only an org admin can manage connectors." : r.data?.message || "Save failed.",- "err",- );- };- function syncEffectClass(sel) {- sel.className = "policy-effect effect-control effect-" + sel.value;- }- function syncRulesEmpty() {- $("rules-empty").classList.toggle("hidden", $("rules").children.length > 0);- }- let commandPolicyMode = "denylist";- let policyRulesExpanded = false;- function syncPolicyMore() {- const extra = [...$("rules").children].slice(3);- extra.forEach((row) => row.classList.toggle("hidden", !policyRulesExpanded));- $("policy-more").classList.toggle("hidden", !extra.length || policyRulesExpanded);- $("policy-more").textContent = "Show " + extra.length + " more " + (extra.length === 1 ? "rule" : "rules");- }- function syncRuleWorkbench() {- const rows = [...$("rules").children];- const warnings = [];- const patterns = rows.map((row) => row.querySelector(".policy-pattern").value.trim());- patterns.forEach((pattern, i) => {- if (!pattern) return;- const duplicate = patterns.slice(0, i).findIndex((p) => p === pattern);- if (duplicate >= 0)- warnings.push(- "Rule " + (i + 1) + " is unreachable because rule " + (duplicate + 1) + " has the same pattern.",- );- const catchAll = patterns- .slice(0, i)- .findIndex((p) => [".*", "^.*$", "[\\s\\S]*", "^[\\s\\S]*$"].includes(p));- if (catchAll >= 0)- warnings.push("Rule " + (i + 1) + " is shadowed by catch-all rule " + (catchAll + 1) + ".");- });- const root = $("policy-warnings");- root.textContent = "";- warnings.forEach((warning) => {- const p = document.createElement("div");- p.textContent = warning;- root.appendChild(p);- });- syncRulesEmpty();- syncPolicyMore();- }- function validatePatternInput(pat) {- const pattern = pat.value.trim();- pat.setCustomValidity("");- pat.setAttribute("aria-invalid", "false");- if (!pattern) return "";- try {- new RegExp(pattern);- return "";- } catch (err) {- const message = err instanceof Error ? err.message : "Invalid regular expression.";- pat.setCustomValidity(message);- pat.setAttribute("aria-invalid", "true");- return message;- }+ return governanceUI.integrations.loadSlackInstallation();}- function ruleRow(rule) {- const row = document.createElement("div");- row.className = "policy-rule";- const pat = document.createElement("input");- pat.className = "policy-pattern";- pat.type = "text";- pat.value = rule?.pattern || "";- pat.placeholder = "regex";- pat.spellcheck = false;- pat.setAttribute("aria-label", "Command pattern");- pat.addEventListener("input", () => {- validatePatternInput(pat);- syncRuleWorkbench();- });- const sel = document.createElement("select");- sel.className = "policy-effect effect-control";- EFFECTS.forEach((e) => {- const o = document.createElement("option");- o.value = e;- o.textContent = EFFECT_LABELS[e] || e;- sel.appendChild(o);- });- sel.value = rule?.decision || "deny";- syncEffectClass(sel);- sel.addEventListener("change", () => syncEffectClass(sel));- const rsn = document.createElement("input");- rsn.className = "policy-reason";- rsn.type = "text";- rsn.value = rule?.reason || "";- rsn.placeholder = "Reason (optional)";- const del = document.createElement("button");- del.type = "button";- del.className = "rowbtn danger";- del.innerHTML =- '<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" aria-hidden="true"><path d="m4 4 8 8M12 4l-8 8" /></svg>';- del.title = "Remove this command policy rule";- del.setAttribute("aria-label", "Remove command policy rule");- del.onclick = () => {- row.remove();- syncRuleWorkbench();- updateSectionDirty("command-policy");- };- row.append(sel, pat, rsn, del);- return row;- }- function renderPolicy(cp) {- commandPolicyMode = cp?.mode || "denylist";- const body = $("rules");- body.textContent = "";- policyRulesExpanded = false;- (cp?.rules || []).forEach((r) => body.appendChild(ruleRow(r)));- syncRuleWorkbench();- }- const BOT_MODES = ["ignore", "rollup", "action", "user"];- const BOT_MODE_LABELS = {- ignore: "ignore (never wakes the judge)",- rollup: "rollup (batch, judge periodically)",- action: "action (posts are triggers)",- user: "user (read like a person)",- };- function syncBotsEmpty() {- $("ambient-bots-empty").classList.toggle("hidden", $("ambient-bots").children.length > 0);- }- function botRow(name, policy) {- const tr = document.createElement("tr");- const nm = document.createElement("input");- nm.type = "text";- nm.value = name || "";- nm.placeholder = "e.g. GitHub";- nm.spellcheck = false;- const sel = document.createElement("select");- BOT_MODES.forEach((m) => {- const o = document.createElement("option");- o.value = m;- o.textContent = BOT_MODE_LABELS[m] || m;- sel.appendChild(o);- });- sel.value = policy?.mode || "ignore";- const hrs = document.createElement("input");- hrs.type = "number";- hrs.min = "1";- hrs.step = "1";- hrs.placeholder = "24";- if (policy?.rollupHours != null) hrs.value = policy.rollupHours;- const syncHrs = () => {- hrs.disabled = sel.value !== "rollup";- };- sel.addEventListener("change", syncHrs);- syncHrs();- const del = document.createElement("button");- del.type = "button";- del.className = "rowbtn danger";- del.textContent = "Remove";- del.title = "Remove this bot from the ledger";- del.setAttribute("aria-label", "Remove bot ledger entry");- del.onclick = () => {- tr.remove();- syncBotsEmpty();- updateSectionDirty("ambient-policy");- };- [[nm], [sel], [hrs], [del, "rule-action"]].forEach(([el, cls]) => {- const td = document.createElement("td");- if (cls) td.className = cls;- td.appendChild(el);- tr.appendChild(td);- });- return tr;- }- function renderAmbientPolicy(p) {- $("card-ambient-policy").dataset.base = String(p?.updatedAt ?? 0);- let ambientEnabled = "default";- if (p?.ambientEnabled === true) ambientEnabled = "on";- else if (p?.ambientEnabled === false) ambientEnabled = "off";- $("ambient-enabled").value = ambientEnabled;- $("ambient-orders").value = p?.orders || "";- const body = $("ambient-bots");- body.textContent = "";- Object.entries(p?.bots || {}).forEach(([name, bp]) => body.appendChild(botRow(name, bp)));- syncBotsEmpty();- }- $("add-bot").onclick = () => {- const row = botRow();- $("ambient-bots").appendChild(row);- syncBotsEmpty();- updateSectionDirty("ambient-policy");- row.querySelector("input")?.focus();- };- function collectAmbientPolicy() {- const bots = {};- const seen = new Set();- for (const tr of $("ambient-bots").children) {- const [nm, sel, hrs] = tr.querySelectorAll("input, select");- const name = nm.value.trim();- if (!name) throw new Error("Every bot ledger row needs a bot name.");- if (seen.has(name.toLowerCase()))- throw new Error('Duplicate bot "' + name + '". The ledger matches names case-insensitively.');- seen.add(name.toLowerCase());- const entry = { mode: sel.value };- if (entry.mode === "rollup" && hrs.value.trim()) {- const hours = Number(hrs.value);- if (!Number.isFinite(hours) || hours <= 0)- throw new Error('Bot "' + name + '": rollup hours must be a positive number.');- entry.rollupHours = hours;- }- bots[name] = entry;- }- const ambientSel = $("ambient-enabled").value;- return {- orders: $("ambient-orders").value,- bots,- ambientEnabled: ambientSel === "default" ? null : ambientSel === "on",- baseUpdatedAt: Number($("card-ambient-policy").dataset.base || 0),- };+ function collectPolicy() {+ return governanceUI.collect("command-policy");}- $("add-rule").onclick = () => {- const row = ruleRow();- policyRulesExpanded = true;- $("rules").prepend(row);- syncRuleWorkbench();- updateSectionDirty("command-policy");- row.querySelector(".policy-pattern")?.focus();- };- $("policy-more").onclick = () => {- policyRulesExpanded = true;- syncPolicyMore();- };$("policy-test-open").onclick = () => {$("policy-test-dialog").showModal();$("policy-sample").focus();@@ -12576,150 +8611,9 @@simulatePolicy();}});- function collectPolicy() {- let firstInvalid = null;- let firstMessage = "";- const rules = [...$("rules").children]- .map((row) => {- const pat = row.querySelector(".policy-pattern");- const sel = row.querySelector(".policy-effect");- const rsn = row.querySelector(".policy-reason");- const invalid = validatePatternInput(pat);- if (invalid && !firstInvalid) {- firstInvalid = pat;- firstMessage = invalid;- }- const rule = { pattern: pat.value.trim(), decision: sel.value };- if (rsn.value.trim()) rule.reason = rsn.value.trim();- return rule;- })- .filter((r) => r.pattern);- if (firstInvalid) {- firstInvalid.focus();- firstInvalid.reportValidity?.();- throw new Error("Fix the highlighted regular expression before saving: " + firstMessage);- }- return { mode: commandPolicyMode, rules };- }- function collectEgress() {- const parse = (id, label) => {- const seen = new Set();- return $(id)- .value.split("\n")- .map((s) => s.trim().toLowerCase())- .filter(Boolean)- .map((host) => {- if (- /\s|:\/\/|[/@?#]/.test(host) ||- host.startsWith(".") ||- host.endsWith(".") ||- !/^[a-z0-9:[\]._-]+$/.test(host)- ) {- throw new Error(- label +- ' contains invalid host "' +- host +- '". Enter a hostname or IP only, with no scheme, path, port, or wildcard.',- );- }- if (seen.has(host)) throw new Error(label + ' contains duplicate host "' + host + '".');- seen.add(host);- return host;- });- };- const allowedHosts = parse("egress", "Allowlist");- const deniedHosts = parse("egress-deny", "Denylist");- const overlap = allowedHosts.find((host) => deniedHosts.includes(host));- if (overlap)- throw new Error('Host "' + overlap + '" appears in both lists. Remove it from one list before saving.');- return { allowedHosts, deniedHosts };- }- function populateEgress(policy) {- const allowedHosts = policy?.allowedHosts || [];- const deniedHosts = policy?.deniedHosts || [];- $("egress").value = allowedHosts.join("\n");- $("egress-deny").value = deniedHosts.join("\n");- const hasRules = allowedHosts.length > 0 || deniedHosts.length > 0;- $("egress-deny-editor").classList.toggle("hidden", deniedHosts.length === 0);- $("egress-allow-editor").classList.toggle("hidden", allowedHosts.length === 0);- $("egress-empty").classList.toggle("hidden", hasRules);- $("egress-add-deny").classList.toggle("hidden", deniedHosts.length > 0);- $("egress-add-allow").classList.toggle("hidden", allowedHosts.length > 0);- renderEgressValidation();- }- function renderEgressValidation() {- const root = $("egress-warnings");- root.textContent = "";- try {- collectEgress();- } catch (err) {- const row = document.createElement("div");- row.textContent = err instanceof Error ? err.message : "Invalid egress policy.";- root.appendChild(row);- }- }- $("egress").addEventListener("input", renderEgressValidation);- $("egress-deny").addEventListener("input", renderEgressValidation);- $("egress-add-deny").onclick = () => {- $("egress-deny-editor").classList.remove("hidden");- $("egress-empty").classList.add("hidden");- $("egress-add-deny").classList.add("hidden");- $("egress-deny").focus();- };- $("egress-add-allow").onclick = () => {- $("egress-allow-editor").classList.remove("hidden");- $("egress-empty").classList.add("hidden");- $("egress-add-allow").classList.add("hidden");- $("egress").focus();- };- const SAVE = {- "security-posture": () => ({ posture: $("security-posture").value }),- "auto-flagger": () => ({- harnessId: $("auto-flagger-harness").value,- modelId: $("auto-flagger-model").value,- rubric: $("auto-flagger-rubric").value,- }),-- "sharing-posture": () => ({ posture: $("sharing-posture").value }),- "approval-grant-modes": () => ({- session: $("approval-grant-session").checked,- always: $("approval-grant-always").checked,- }),- "command-policy": () => collectPolicy(),- soul: () => ({ content: $("soul").value, expectedVersion: soulVersion }),- "ambient-policy": () => collectAmbientPolicy(),- egress: () => collectEgress(),- "external-slack-participants": () => ({ on: $("external-slack-participants").checked }),- "internal-member-overrides": () => ({- members: [- ...new Set(- $("internal-member-overrides")- .value.split(/[\n,]/)- .map((m) => m.trim().toLowerCase())- .filter(Boolean),- ),- ],- }),- "org-ambient": () => ({ on: $("org-ambient").checked }),- "channel-header-pin-default": () => ({ on: $("channel-header-pin-default").checked }),- runtime: () => ({- harnessId: $("base-harness").value,- modelId: $("base-model").value,- effortLevel: $("base-effort").value,- fastMode: $("base-fast-mode").checked,- }),- "webui-models": () => ({ ids: webuiModelIds }),- "people-directory-url": () => ({ url: $("people-directory-url").value.trim() }),- "ack-emoji": () => ({ names: ackEmojiNames }),- branding: () => ({- accent: $("branding-accent").value.trim(),- mark: $("branding-mark").value.trim(),- markUrl: $("branding-mark-url").value.trim(),- selfLabel: $("branding-self-label").value.trim(),- orgName: $("branding-org-name").value.trim(),- }),- "turn-wall-clock": () => ({ sec: $("turn-wall-clock").value.trim() }),- };+ const SAVE = Object.fromEntries(+ [...governanceUI.states.keys()].map((key) => [key, () => governanceUI.collect(key)]),+ );const SAVE_ST = {"security-posture": "st-security-posture","auto-flagger": "st-auto-flagger",@@ -12731,13 +8625,11 @@egress: "st-egress","external-slack-participants": "st-external-slack-participants","internal-member-overrides": "st-internal-member-overrides",- "org-ambient": "st-org-ambient",+ "org-ambient": "st-governance-org-ambient","channel-header-pin-default": "st-channel-header-pin-default",runtime: "st-runtime","webui-models": "st-webui-models",- "people-directory-url": "st-people-directory-url","ack-emoji": "st-ack-emoji",- "turn-wall-clock": "st-turn-wall-clock",branding: "st-branding",};const SAVE_RELOADS = new Set([@@ -12747,9 +8639,7 @@"external-slack-participants","runtime","webui-models",- "people-directory-url","ack-emoji",- "turn-wall-clock","branding",]);const sectionSnapshots = new Map();@@ -12779,11 +8669,17 @@return JSON.stringify(SAVE[key]());}function setSectionDirty(key, dirty) {+ if (governanceUI.owns(key)) return;const btn = sectionButton(key);setCardDirty(btn?.closest(".card"), dirty, SAVE_ST[key], '[data-save="' + key + '"]');if (key === "egress" && $("card-egress").classList.contains("egress-disabled")) btn.disabled = true;}function captureSection(key) {+ if (governanceUI.owns(key)) {+ sectionSnapshots.set(key, JSON.stringify(governanceUI.states.get(key).collect(false)));+ governanceUI.capture(key);+ return;+ }if (!SAVE[key] || !sectionButton(key)) return;try {sectionSnapshots.set(key, serializeSection(key));@@ -12793,6 +8689,7 @@}}function updateSectionDirty(key) {+ if (governanceUI.owns(key)) return;if (!SAVE[key] || !sectionButton(key)) return;if (!sectionSnapshots.has(key)) return captureSection(key);let dirty = true;@@ -12807,8 +8704,6 @@Object.keys(SAVE_ST).forEach(captureSection);}function saveKeyForTarget(target) {- const subsection = target.closest("[data-save-scope]");- if (subsection) return subsection.dataset.saveScope;const card = target.closest(".card");const btn = card?.querySelector("[data-save]");return btn?.dataset.save || "";@@ -12895,24 +8790,10 @@}return Promise.resolve(true);}- function renderSharingPosture(data) {- const effective = data.sharingPosture || "isolated";- $("sharing-posture").value = effective;- $("sharing-posture-inherit").hidden = scope.startsWith("org:") || data.sharingPostureOverride == null;- $("sharing-posture-effective").textContent =- (data.sharingPostureOverride == null- ? scope.startsWith("org:")- ? "Default"- : "Following organization"- : "Configured: " + titleCase(data.sharingPostureOverride)) +- " · Effective: " +- titleCase(effective);- document- .querySelectorAll('[data-choice-for="sharing-posture"]')- .forEach((input) => (input.checked = input.value === effective));- }$("sharing-posture-inherit").onclick = async () => {const requestedScope = scope;+ const requestedGeneration = governanceReq;+ const draftBefore = JSON.stringify(governanceUI.collect("sharing-posture"));if (!(await reviewGovernanceChange({title: "Follow organization sharing?",@@ -12922,16 +8803,33 @@"The organization's sharing setting will apply. A personal or room Isolated override still takes precedence.",confirmLabel: "Follow organization",})) ||- requestedScope !== scope+ requestedScope !== scope ||+ requestedGeneration !== governanceReq)return;const result = await api("PUT", "/api/scopes/" + encodeURIComponent(requestedScope) + "/sharing-posture", {inherit: true,});- if (requestedScope !== scope) return;- if (result.ok) await loadScope();- setStatus("st-sharing-posture", result.ok ? "Saved" : "Could not reset sharing.", result.ok ? "ok" : "err");+ if (requestedScope !== scope || requestedGeneration !== governanceReq) return;+ if (result.ok)+ await refreshPolicySetting("sharing-posture", requestedScope, requestedGeneration, draftBefore, "Saved");+ else setStatus("st-sharing-posture", "Could not reset sharing.", "err");};+ async function refreshPolicySetting(key, requestedScope, requestedGeneration, draftBefore, message) {+ const fresh = await api("GET", "/api/scopes/" + encodeURIComponent(requestedScope) + "?view=governance");+ if (requestedScope !== scope || requestedGeneration !== governanceReq) return;+ if (!fresh.ok)+ return governanceUI.status(key, "Saved, but the current setting could not be refreshed.", "warn");+ const state = governanceUI.states.get(key);+ const currentDraft = state.collect();+ const changed = JSON.stringify(currentDraft) !== draftBefore;+ governanceUI.load(fresh.data, requestedScope, key);+ sectionSnapshots.set(key, state.baseline);+ if (changed) {+ state.draft = currentDraft;+ state.changed();+ } else governanceUI.status(key, message, "ok");+ }let governanceSaveSeq = 0;$("auto-flagger-test").onclick = async () => {const requestedScope = scope;@@ -12968,19 +8866,27 @@};$("auto-flagger-reset").onclick = async () => {const requestedScope = scope;+ const requestedGeneration = governanceReq;+ const draftBefore = JSON.stringify(governanceUI.collect("auto-flagger"));const r = await api("PUT", "/api/scopes/" + encodeURIComponent(requestedScope) + "/auto-flagger", {reset: true,});- if (requestedScope !== scope) return;+ if (requestedScope !== scope || requestedGeneration !== governanceReq) return;if (!r.ok) return setStatus("st-auto-flagger", r.data?.message || "Reset failed.", "err");- await loadScope();- if (requestedScope === scope) setStatus("st-auto-flagger", "Default restored", "ok");+ await refreshPolicySetting(+ "auto-flagger",+ requestedScope,+ requestedGeneration,+ draftBefore,+ "Default restored",+ );};document.querySelectorAll("[data-save]").forEach((btn) => {btn.onclick = async () => {const key = btn.dataset.save;const requestedScope = scope;+ const requestedGeneration = governanceReq;let body;try {body = SAVE[key]();@@ -12988,12 +8894,24 @@setStatus(SAVE_ST[key], err instanceof Error ? err.message : "Could not save.", "err");return;}- if (!(await governanceSaveReview(key, body)) || requestedScope !== scope) return;+ if (+ !(await governanceSaveReview(key, body)) ||+ requestedScope !== scope ||+ requestedGeneration !== governanceReq+ )+ return;const saveRequest = String(++governanceSaveSeq);btn.dataset.saveRequest = saveRequest;btn.disabled = true;setStatus(SAVE_ST[key], "Saving...", "saving", true);- const r = await api("PUT", "/api/scopes/" + encodeURIComponent(requestedScope) + "/" + key, body);+ const isBranding = key === "branding";+ const brandingBody = isBranding ? { ...savedBranding, ...body } : body;+ const r = await api(+ "PUT",+ "/api/scopes/" + encodeURIComponent(requestedScope) + "/" + (isBranding ? "branding" : key),+ brandingBody,+ );+ if (requestedGeneration !== governanceReq) return;if (requestedScope !== scope) {if (btn.dataset.saveRequest === saveRequest) {delete btn.dataset.saveRequest;@@ -13004,39 +8922,41 @@}if (btn.dataset.saveRequest === saveRequest) delete btn.dataset.saveRequest;if (r.ok) {- if (key === "security-posture" || key === "sharing-posture" || key === "ambient-policy") {- const fresh = await api(- "GET",- "/api/scopes/" + encodeURIComponent(scope) + "?view=" + encodeURIComponent(view),- );- if (!fresh.ok) {- updateSectionDirty(key);- setStatus(SAVE_ST[key], "Saved, but could not refresh the applied value.", "err");+ if (governanceUI.owns(key)) {+ governanceUI.commit(key, body);+ sectionSnapshots.set(key, JSON.stringify(body));+ if (isBranding) {+ savedBranding = brandingBody;+ if (!hasGovernanceDraft()) location.reload();return;}- renderGovernanceOverview(fresh.data);- if (key === "security-posture") $("security-posture").value = fresh.data.securityPosture || "auto";- else if (key === "sharing-posture") renderSharingPosture(fresh.data);- else renderAmbientPolicy(fresh.data.ambientPolicy);- captureSection(key);- } else if (key === "branding") {- sectionSnapshots.set(key, JSON.stringify(body));- updateSectionDirty(key);- setStatus(SAVE_ST[key], "Saved", "ok");- if (!hasGovernanceDraft()) location.reload();+ if (key === "soul") {+ const fresh = await api("GET", "/api/scopes/" + encodeURIComponent(requestedScope) + "?view=customize");+ if (requestedScope !== scope || requestedGeneration !== governanceReq) return;+ if (fresh.ok) {+ governanceUI.settings.refreshSoul(fresh.data);+ sectionSnapshots.set(key, governanceUI.states.get(key).baseline);+ if (!governanceUI.states.get(key).dirty) governanceUI.status(key, "Saved", "ok");+ } else governanceUI.status(key, "Saved, but the latest version could not be refreshed.", "warn");+ return;+ }+ if (key === "command-policy") loadedCommandPolicyPresent = true;+ if (["security-posture", "sharing-posture", "ambient-policy", "auto-flagger"].includes(key)) {+ const fresh = await api(+ "GET",+ "/api/scopes/" + encodeURIComponent(requestedScope) + "?view=governance",+ );+ if (requestedScope !== scope || requestedGeneration !== governanceReq) return;+ if (fresh.ok && !governanceUI.states.get(key).dirty) {+ governanceUI.load(fresh.data, requestedScope, key);+ sectionSnapshots.set(key, JSON.stringify(governanceUI.collect(key)));+ governanceUI.status(key, "Saved", "ok");+ }+ }return;} else if (SAVE_RELOADS.has(key)) await loadScope();else {- if (key === "egress") {- renderGovernanceOverview({ ...governanceOverviewData, egress: body });- populateEgress(body);- }if (key === "command-policy") loadedCommandPolicyPresent = true;- if (key === "org-ambient") {- governanceOrgAmbientSaved = body.on ? "on" : "off";- $("governance-org-ambient").value = governanceOrgAmbientSaved;- $("governance-org-ambient-save").disabled = true;- }captureSection(key);}setStatus(SAVE_ST[key], "Saved", "ok");@@ -13060,13 +8980,11 @@e.target instanceof HTMLSelectElement))return;- if (e.target.id === "soul") updateSoulWorkbench();if (e.target.closest("#card-service-credentials")) updateScFormDirty();else updateSectionDirty(saveKeyForTarget(e.target));});$("view-governance").addEventListener("change", (e) => {if (e.target instanceof HTMLInputElement || e.target instanceof HTMLSelectElement) {- if (e.target.name === "sc-share") syncScPeople();if (e.target.closest("#card-service-credentials")) updateScFormDirty();else updateSectionDirty(saveKeyForTarget(e.target));}@@ -13462,289 +9380,55 @@return svg;}function renderMetrics(root, d) {- const phaseSel = urlToState().phase;- if (phaseSel) return renderPhaseDrill(root, d, phaseSel);- defaultShell({ count: plural(d.throughput?.total ?? 0, "run") });- renderCacheHealth(root, d);- const phases = d.phases || [];- root.appendChild(- openableTable(- ["Phase", "p50", "p95", "p99", "Turns", "Trend"],- phases,- (p) => [- nodeCell(stacked(phaseLabel(p.phase), phaseDesc(p.phase))),- { text: fmtMs(p.p50), cls: "num" },- { text: fmtMs(p.p95), cls: "num" },- { text: fmtMs(p.p99), cls: "num" },- { text: p.count ? Number(p.count).toLocaleString() : "n/a", cls: "num" },- nodeCell(sparkline(p.daily), "num"),- ],- (p) => go({ view: "metrics", scope, session: null, phase: p.phase }),- "No turn metrics in this scope yet.",- ),- );- renderTurnMix(root, d);- const tp = d.throughput || {};- if (tp.total)- root.appendChild(- statline([- (tp.total ?? 0) + " runs",- (tp.done ?? 0) + " done",- (tp.failed ?? 0) + " failed",- fmtPct(tp.failureRate) + " failure rate",- ]),- );- }- function renderCacheHealth(root, d) {- const c = d.cache;- if (!c || !(c.samples || 0)) return;- root.appendChild(- statline([- (c.avgHitRatio == null ? "n/a" : fmtPct(c.avgHitRatio)) + " prompt-cache hit ratio",- (c.pooledHitRatio == null ? "n/a" : fmtPct(c.pooledHitRatio)) + " token-weighted",- (c.missRate == null ? "n/a" : fmtPct(c.missRate)) + " stable-prefix miss rate",- (c.missTurns || 0) + " miss turns",- (c.samples || 0) + " turns with cache data",- fmtTokens(c.cacheReadTotal || 0) + " read",- fmtTokens(c.cacheWriteTotal || 0) + " written",- ]),- );- }- const fmtX = (n) => (n == null ? "n/a" : String(Math.round(n * 10) / 10));- function renderTurnMix(root, d) {- const an = d.anatomy;- if (!an) return;- const a = an.traceA || {},- b = an.traceB || {},- c = an.composite || {};- if (!(c.totalTurns || 0)) return;- const share = (n) => (c.totalTurns ? fmtPct((n || 0) / c.totalTurns) : "n/a");- const rows = [- [- nodeCell(stacked("Turns that never touched a machine", "pure conversation, no tools")),- { text: share(a.samples), cls: "num" },- { text: String(a.samples || 0), cls: "num" },- { text: fmtMs(a.total && a.total.p50), cls: "num" },- { text: fmtX(a.modelCalls && a.modelCalls.avg), cls: "num" },- { text: fmtX(a.toolCalls && a.toolCalls.avg), cls: "num" },- ],- [- nodeCell(- stacked(- "Turns that used a machine",- (b.warm || 0) +- " on a warm machine (" +- fmtMs(b.provisionWarm && b.provisionWarm.p50) +- " median resume) · " +- (b.cold || 0) +- " booted cold (" +- fmtMs(b.provisionCold && b.provisionCold.p50) +- " median boot)",- ),- ),- { text: share(b.samples), cls: "num" },- { text: String(b.samples || 0), cls: "num" },- { text: fmtMs(b.total && b.total.p50), cls: "num" },- { text: fmtX(b.modelCalls && b.modelCalls.avg), cls: "num" },- { text: fmtX(b.toolCalls && b.toolCalls.avg), cls: "num" },- ],- [- nodeCell(stacked("All turns", "the blended average")),- { text: "100%", cls: "num" },- { text: String(c.totalTurns || 0), cls: "num" },- { text: fmtMs(c.total && c.total.p50), cls: "num" },- { text: fmtX(c.modelCalls && c.modelCalls.avg), cls: "num" },- { text: fmtX(c.toolCalls && c.toolCalls.avg), cls: "num" },- ],- ];- root.appendChild(- dataCard(- "Turn mix",- "How often turns provision a machine, and what each kind of turn costs.",- table(["Kind of turn", "Share", "Turns", "Median", "Model calls", "Tool calls"], rows, "No turns sampled."),- ),- );- }- function distChart(dist) {- const all = dist || [];- const rows = all.map((b, i) => ({- ...b,- label: b.le == null ? "> " + fmtMs((all[i - 1] || {}).le) : "≤ " + fmtMs(b.le),- }));- while (rows.length && !rows[rows.length - 1].count) rows.pop();- if (!rows.length) {- const p = document.createElement("p");- p.className = "empty";- p.textContent = "No samples.";- return p;- }- const max = Math.max(...rows.map((b) => b.count), 1);- const wrap = document.createElement("div");- wrap.className = "dist";- rows.forEach((b) => {- const row = document.createElement("div");- row.className = "dist-row";- const label = document.createElement("span");- label.className = "dist-label";- label.textContent = b.label;- const track = document.createElement("span");- track.className = "dist-track";- const bar = document.createElement("span");- bar.className = "dist-bar";- bar.style.width = Math.max((b.count / max) * 100, b.count ? 1 : 0) + "%";- track.appendChild(bar);- const n = document.createElement("span");- n.className = "dist-count";- n.textContent = b.count ? Number(b.count).toLocaleString() : "";- row.append(label, track, n);- wrap.appendChild(row);- });- return wrap;- }- function renderPhaseDrill(root, d, phaseKey) {- const p = (d.phases || []).find((x) => x.phase === phaseKey);- pageShell({- back: { label: "← Metrics", onClick: () => go({ view: "metrics", scope, session: null }) },- title: phaseLabel(phaseKey),- context: phaseDesc(phaseKey),+ governanceUI.metrics.metrics(root, d, {+ phase: urlToState().phase,+ scope,+ pageShell,+ defaultShell,+ go,+ phaseLabel,+ phaseDesc,+ fmtMs,+ fmtPct,+ fmtTokens,+ plural,+ shortName,+ relTime,+ turnKindWords,+ sparkline,});- if (!p || !p.count) {- const e = document.createElement("p");- e.className = "empty";- e.textContent = "No " + phaseLabel(phaseKey).toLowerCase() + " samples in this scope yet.";- root.appendChild(e);- return;- }- root.appendChild(- statline([- Number(p.count).toLocaleString() + " turns",- fmtMs(p.p50) + " p50",- fmtMs(p.p95) + " p95",- fmtMs(p.p99) + " p99",- ]),- );- root.appendChild(dataCard("Distribution", "Where the samples land.", distChart(p.dist)));- const dailyRows = (p.daily || [])- .slice()- .reverse()- .map((r) => [- { text: r.day, cls: "mono" },- { text: Number(r.count).toLocaleString(), cls: "num" },- { text: fmtMs(r.p50), cls: "num" },- { text: fmtMs(r.p95), cls: "num" },- { text: fmtMs(r.p99), cls: "num" },- ]);- root.appendChild(- dataCard(- "By day",- "Daily percentiles (UTC).",- table(["Day", "Turns", "p50", "p95", "p99"], dailyRows, "No daily samples."),- ),- );- const linkable = (t) => !!t.sessionId;- const anyLinkable = (p.worst || []).some(linkable);- root.appendChild(- dataCard(- "Worst recent turns",- anyLinkable ? "The slowest samples. Each opens the turn's transcript." : "The slowest samples.",- openableTable(- [phaseLabel(phaseKey), "Total turn", "Scope", "Machine", "Time"],- p.worst || [],- (t) => [- { text: fmtMs(t.ms), cls: "num" },- { text: t.totalMs ? fmtMs(t.totalMs) : "n/a", cls: "num" },- { text: shortName(t.scopeLabel), cls: "" },- { text: turnKindWords(t) || "None", cls: "subline" },- { text: relTime(t.ts), cls: "num" },- ],- (t) => {- if (linkable(t))- go({- view: "history",- scope: t.scopeLabel || scope,- session: t.sessionId,- ...(t.turnSeq != null ? { turn: t.turnSeq } : {}),- });- },- "No samples.",- { rowClassOf: (t) => (linkable(t) ? "" : "unlinkable") },- ),- ),- );}function renderErrors(root, d) {- const all = orgWideView();- const errors = d.errors || [];- const total = d.total ?? errors.length;- const limit = d.limit || ERRORS_PAGE_SIZE;- const offset = d.offset || 0;- defaultShell({ count: plural(total, "error") });- const rows = errors.map((e) => {- const scopeTarget = /^(personal|channel|team|org|group):.+/.test(e.scopeLabel || "") ? e.scopeLabel : null;- const fullText = e.message || "(no message)";- const previewText = firstLine(fullText, 160);- const message = document.createElement("details");- message.className = "error-message";- const summary = document.createElement("summary");- const preview = document.createElement("span");- preview.className = "error-preview";- preview.textContent = previewText;- const full = document.createElement("span");- full.className = "error-full";- full.textContent = fullText;- summary.append(preview, full);- message.append(summary);- return [- { text: e.category || "uncategorized" },- { text: e.code || "—", cls: "mono" },- nodeCell(message),- ...(all- ? [- scopeTarget- ? nodeCell(navLink(shortName(scopeTarget), { view: "errors", scope: scopeTarget }))- : { text: e.scopeLabel || "System" },- ]- : []),- e.sessionId- ? nodeCell(- navLink("View session", { view: "history", scope: scopeTarget || scope, session: e.sessionId }),- )- : { text: "—" },- timeCell(e.ts),- ];+ governanceUI.activity.errors(root, d, {+ all: orgWideView(),+ scope,+ defaultShell,+ plural,+ firstLine,+ navLink,+ shortName,+ fmtTime,+ relTime,+ go,+ egressDetail,+ errorsPageSize: ERRORS_PAGE_SIZE,});- const content = table(- ["Category", "Code", "Message", ...(all ? ["Scope"] : []), "Session", "Time"],- rows,- all ? "No errors recorded." : "No errors recorded for this scope.",- );- content.classList.add("errors-table", all ? "errors-all" : "errors-scoped");- const navigate = (n) => go({ view: "errors", scope, page: n });- root.appendChild(pager(total, limit, offset, navigate));- root.appendChild(bareDataCard(content));- root.appendChild(pager(total, limit, offset, navigate));}-function renderAudit(root, d) {- const all = orgWideView();- const events = d.events || [];- defaultShell({ count: plural(events.length, "event") });- const rows = events.map((e) => [- { text: e.principalId, cls: "mono" },- nodeCell(mutedText(e.action || "event", /revoke|delete|deny|fail/.test(String(e.action || "")) ? "err" : "")),- { text: e.status ? e.resource + " (" + e.status + ")" : e.resource || "", cls: "mono" },- ...(all ? [{ text: shortName(e.scopeLabel) }] : []),- timeCell(e.ts),- ]);- root.appendChild(- bareDataCard(- table(- ["Admin", "Action", "Resource", ...(all ? ["Scope"] : []), "Time"],- rows,- all ? "No admin activity yet." : "No admin activity for this scope.",- ),- ),- );+ governanceUI.activity.audit(root, d, {+ all: orgWideView(),+ scope,+ defaultShell,+ plural,+ firstLine,+ navLink,+ shortName,+ fmtTime,+ relTime,+ go,+ egressDetail,+ errorsPageSize: ERRORS_PAGE_SIZE,+ });}function mutedText(text, tone) {const s = document.createElement("span");@@ -13824,36 +9508,20 @@return bits.join(" · ") || "None";}function renderEgress(root, d) {- const all = orgWideView();- const recs = d.records || [];- const bs = d.bySource || {};- defaultShell({- stats: [- [String(d.total ?? recs.length), "Calls"],- [String(d.denied ?? 0), "denied requests"],- [String(d.hosts ?? 0), "Hosts"],- [String(bs.broker ?? 0), "broker requests"],- [String(bs.firewall ?? 0), "firewall requests"],- ],+ governanceUI.activity.egress(root, d, {+ all: orgWideView(),+ scope,+ defaultShell,+ plural,+ firstLine,+ navLink,+ shortName,+ fmtTime,+ relTime,+ go,+ egressDetail,+ errorsPageSize: ERRORS_PAGE_SIZE,});- const rows = recs.map((r) => [- { text: r.host, cls: "mono" },- nodeCell(egressStatus(r)),- nodeCell(mutedText(r.source || "firewall")),- ...(all ? [{ text: shortName(r.scopeLabel) }] : []),- { text: r.principalId || "None", cls: "mono" },- { text: egressDetail(r), cls: "mono" },- timeCell(r.ts),- ]);- root.appendChild(- bareDataCard(- table(- ["Host", "Status", "Source", ...(all ? ["Scope"] : []), "Principal", "Detail", "Time"],- rows,- "No egress in this scope yet.",- ),- ),- );}function cronName(c, previewAction = false) {if (!c) return "Cron";@@ -13994,424 +9662,81 @@if (dest.onBehalfOf) bits.push("on behalf of " + dest.onBehalfOf);return bits.join(" / ");}- async function saveCronDestination(id, destination) {- const path = "/api/crons/" + encodeURIComponent(id) + "/destination?scope=" + encodeURIComponent(scope);- const r = await api("PUT", path, { destination });- if (!r.ok) {- alert(r.data?.message || "Could not update destination.");- return false;- }- dataCache.clear();- return true;- }- function cronDestinationActions(c) {- const wrap = document.createElement("div");- wrap.className = "credential-actions";- const edit = document.createElement("button");- edit.type = "button";- edit.className = "rowbtn";- edit.textContent = "Edit destination";- edit.onclick = () => {- cronDestinationEditId = c.id;- renderCurrentData();- };- wrap.appendChild(edit);- const clear = document.createElement("button");- clear.type = "button";- clear.className = "rowbtn danger";- clear.textContent = "Clear destination";- clear.disabled = !c.destination;- clear.onclick = async () => {- if (!(await saveCronDestination(c.id, null))) return;- if (cronDestinationEditId === c.id) cronDestinationEditId = null;- await renderData();+ let artifactRenderGeneration = 0;+ function artifactContext() {+ const capturedScope = scope;+ const capturedView = view;+ const capturedRequest = dataReq;+ const generation = ++artifactRenderGeneration;+ const current = () =>+ scope === capturedScope &&+ view === capturedView &&+ dataReq === capturedRequest &&+ generation === artifactRenderGeneration;+ return {+ view,+ scope: capturedScope,+ orgId,+ scopeDir,+ orgWide: orgWideView(),+ index: orgWideView() && !orgOwnView(),+ own: orgOwnView(),+ cron: urlToState().cron,+ apiBase: API_BASE,+ api,+ pageShell,+ go,+ stateToUrl,+ openScopeRow,+ scopeKind,+ shortName,+ dirLabel,+ plural,+ relTime,+ fmtTime,+ fmtHistoryTime,+ fmtBytes,+ fmtDuration,+ shortId,+ titleCase,+ firstLine,+ fileName,+ fileKind,+ fileSha256,+ uploadErrorMessage,+ downloadFile,+ deploymentHref,+ cronName,+ shortSchedule,+ fmtSchedule,+ destinationSummary,+ destinationDetails,+ createdByCell,+ packRepoLabel,+ scopeCell,+ statusBadge,+ typeBadge,+ stacked,+ scopeRows,+ buildScopeMultiSelect,+ invalidate: () => dataCache.clear(),+ reload: () => (current() ? renderData() : Promise.resolve()),+ setCronEditing: (id) => {+ if (current()) cronDestinationEditId = id;+ },+ memoryDraft: () => (memDraftScope === capturedScope ? memDraft : null),+ setMemoryDraft: (draft) => {+ if (!current()) return;+ memDraft = draft;+ memDraftScope = draft === null ? null : capturedScope;+ },};- wrap.appendChild(clear);- return wrap;}- function cronDestinationEditor(c) {- const body = document.createElement("div");- const form = document.createElement("div");- form.style.display = "grid";- form.style.gridTemplateColumns = "repeat(auto-fit, minmax(160px, 1fr))";- form.style.gap = "10px";- const typeWrap = document.createElement("label");- typeWrap.textContent = "Type";- const type = document.createElement("select");- for (const value of ["slack", "principal"]) {- const opt = document.createElement("option");- opt.value = value;- opt.textContent = value;- type.appendChild(opt);- }- type.value = c.destination?.type === "principal" ? "principal" : "slack";- typeWrap.appendChild(type);- const targetWrap = document.createElement("label");- targetWrap.textContent = "Target";- const target = document.createElement("input");- target.type = "text";- target.value = c.destination?.target || "";- targetWrap.appendChild(target);- const scopeWrap = document.createElement("label");- scopeWrap.textContent = "Audience scope";- const audienceScopeId = document.createElement("input");- audienceScopeId.type = "text";- audienceScopeId.value = c.destination?.audienceScopeId || "";- scopeWrap.appendChild(audienceScopeId);- const oboWrap = document.createElement("label");- oboWrap.textContent = "On behalf of";- const onBehalfOf = document.createElement("input");- onBehalfOf.type = "text";- onBehalfOf.value = c.destination?.onBehalfOf || "";- oboWrap.appendChild(onBehalfOf);- function syncPlaceholders() {- target.placeholder = type.value === "principal" ? "principal id" : "Slack channel/thread id";- audienceScopeId.placeholder = type.value === "principal" ? "personal:U123" : "channel:C123";- onBehalfOf.disabled = type.value !== "principal";- }- type.onchange = syncPlaceholders;- syncPlaceholders();- form.append(typeWrap, targetWrap, scopeWrap, oboWrap);- body.appendChild(form);- const foot = document.createElement("div");- foot.className = "foot";- const save = document.createElement("button");- save.type = "button";- save.className = "primary";- save.textContent = "Save destination";- save.onclick = async () => {- const nextTarget = target.value.trim();- if (!nextTarget) {- target.focus();- alert("Target is required.");- return;- }- const destination = {- type: type.value,- target: nextTarget,- ...(audienceScopeId.value.trim() ? { audienceScopeId: audienceScopeId.value.trim() } : {}),- ...(type.value === "principal" && onBehalfOf.value.trim() ? { onBehalfOf: onBehalfOf.value.trim() } : {}),- };- if (!(await saveCronDestination(c.id, destination))) return;- cronDestinationEditId = null;- await renderData();- };- const cancel = document.createElement("button");- cancel.type = "button";- cancel.textContent = "Cancel";- cancel.onclick = () => {- cronDestinationEditId = null;- renderCurrentData();- };- foot.append(save, cancel);- body.appendChild(foot);- return dataCard("Edit cron destination", c.title || c.action || c.message || c.id, body);- }- const cronStatusText = (c) => {- if (c.archived) return "archived";- if (c.enabled === false) return "disabled";- return "enabled";- };function renderCrons(root, d) {- const index = orgWideView() && !orgOwnView();- const selectedCronId = urlToState().cron;- const allCrons = d.crons || [];- if (selectedCronId)- return renderCronDetail(- root,- allCrons.find((c) => c.id === selectedCronId),- selectedCronId,- );- const crons = orgOwnView() ? allCrons.filter((c) => scopeKind(c.ownerScopeId) === "org") : allCrons;- const count = (pred) => crons.filter(pred).length;- const disabled = count((c) => !c.archived && c.enabled === false);- const archived = count((c) => c.archived);- const sorted = [...crons].sort(- (a, b) => (b.lastFiredAt || b.createdAt || 0) - (a.lastFiredAt || a.createdAt || 0),- );- const lastRun = (c) => c.lastFiredAt || c.createdAt || 0;- const cronRow = (c) => {- const name = firstLine(cronName(c, true), 72);- let promptSource = "";- if (c.title) promptSource = c.action || c.message || "";- else if (c.action && c.message) promptSource = c.action;- const prompt = firstLine(promptSource, 200);- const status = cronStatusText(c);- const preview = [index ? shortName(c.ownerScopeId) : "", status === "enabled" ? "" : status, prompt]- .filter(Boolean)- .join(" · ");- return {- name,- preview,- time: shortSchedule(c.schedule) + " · " + (c.lastFiredAt ? relTime(c.lastFiredAt) : "never fired"),- cls: status === "enabled" ? "" : "dim",- href: stateToUrl({ view: "crons", scope, cron: c.id }),- };- };- const openCron = (c) => go({ view: "crons", scope, session: null, cron: c.id, page: 1 });- const names = sorted.map((c) => (cronName(c, true) + " " + (c.action || c.message || "")).toLowerCase());- const list = denseList(sorted, cronRow, openCron, index ? "No crons yet." : "No crons in this scope.");- let scopeWrap = null;- if (index) {- scopeWrap = document.createElement("div");- scopeWrap.appendChild(- scopeIndexList(allCrons, {- latestOf: lastRun,- noun: "cron",- empty: "No crons yet.",- extra: { cron: null },- }),- );- }- const noMatch = document.createElement("p");- noMatch.className = "empty hidden";- noMatch.textContent = "No crons match.";- const listWrap = document.createElement("div");- listWrap.append(list, noMatch);- wireScopeSearch({- key: "crons",- indexWrap: scopeWrap,- listWrap,- rows: [...list.children],- names,- noMatch,- total: crons.length,- shell: {- ...(index- ? { title: VIEW_TITLE.crons }- : {- back: {- label: "← " + VIEW_TITLE.crons,- onClick: () =>- go({ view: "crons", scope: "org:" + orgId, own: null, session: null, cron: null, page: 1 }),- },- title: shortName(scope),- }),- count: plural(crons.length, "cron"),- stats: [...(disabled ? [[disabled, "disabled"]] : []), ...(archived ? [[archived, "archived"]] : [])],- },- placeholder: index ? "Search all crons…" : "Search crons…",- });- const card = bareDataCard(listWrap);- if (scopeWrap) card.querySelector(".body").prepend(scopeWrap);- root.appendChild(card);+ governanceUI.artifacts.crons(root, d, artifactContext());}- function factList(pairs) {- const wrap = document.createElement("div");- wrap.className = "factlist";- pairs.forEach(([k, v]) => {- if (v == null || v === "") return;- const fk = document.createElement("div");- fk.className = "fk";- fk.textContent = k;- const fv = document.createElement("div");- fv.className = "fv";- if (v.nodeType) fv.appendChild(v);- else fv.textContent = v;- wrap.append(fk, fv);- });- return wrap;- }- function clampedPrompt(text) {- const wrap = document.createElement("div");- const body = document.createElement("p");- body.className = "prompt-body clamped";- body.textContent = text;- wrap.appendChild(body);- const toggle = document.createElement("button");- toggle.type = "button";- toggle.className = "prompt-toggle";- toggle.textContent = "Show more";- toggle.onclick = () => {- const clamped = body.classList.toggle("clamped");- toggle.textContent = clamped ? "Show more" : "Show less";- };- wrap.appendChild(toggle);-- requestAnimationFrame(() => {- if (body.scrollHeight > 0 && body.scrollHeight <= body.clientHeight + 1) toggle.remove();- });- return wrap;- }-- function renderCronDetail(root, c, cronId) {- pageShell({- back: {- label: "← " + VIEW_TITLE.crons,- onClick: () => go({ view: "crons", scope, session: null, cron: null, page: 1 }),- },- title: c ? firstLine(cronName(c, true), 90) : "Cron",- context: c ? shortName(c.ownerScopeId) : "",- });- if (!c) {- const p = document.createElement("p");- p.className = "empty";- p.textContent = "Cron " + shortId(cronId) + " isn't in this scope.";- root.appendChild(p);- return;- }- if (cronDestinationEditId === c.id) root.appendChild(cronDestinationEditor(c));- const dest = document.createElement("span");- dest.textContent =- destinationSummary(c.destination) +- (destinationDetails(c.destination) && c.destination ? " · " + destinationDetails(c.destination) : "");- root.appendChild(- factList([- ["Schedule", fmtSchedule(c.schedule)],- ["Destination", dest],- ["Owner", c.owner || c.createdBy || "None"],- ["Status", cronStatusText(c)],- ["Created", fmtTime(c.createdAt)],- ["Last fired", c.lastFiredAt ? relTime(c.lastFiredAt) : "never fired"],- ["Id", c.id],- ]),- );- const actions = cronDestinationActions(c);- actions.style.margin = "0 0 18px";- root.appendChild(actions);- const prompt = c.action || c.message || "";- if (prompt)- root.appendChild(- dataCard(- c.action ? "Prompt" : "Message",- c.action ? "Re-run as a fresh prompt at every fire." : "Delivered as-is at every fire.",- clampedPrompt(prompt),- ),- );- const firesWrap = document.createElement("div");- firesWrap.appendChild(- Object.assign(document.createElement("div"), { className: "loadingline", textContent: "Loading fires..." }),- );- root.appendChild(- dataCard(- "Recent fires",- "Each fire is a session. Click one to read its transcript. Dimmed fires delivered nothing.",- firesWrap,- ),- );- renderCronFires(firesWrap, c, cronId);- }- async function renderCronFires(container, c, cronId) {- const limit = 25;- const path = `/api/sessions?scope=${encodeURIComponent(scope)}&limit=${limit}&offset=0&category=background&origin=cron&cron=${encodeURIComponent(cronId)}`;- const r = await api("GET", path);- if (!container.isConnected) return;- container.textContent = "";- if (!r.ok) {- container.appendChild(- Object.assign(document.createElement("p"), {- className: "empty",- textContent: r.data?.message || `Failed to load fires (${r.status}).`,- }),- );- return;- }- const fires = r.data.sessions || [];- const t = denseList(- fires,- (s) => {- let delivery = "";- if (typeof s.delivered === "number") {- delivery = "silent";- if (s.delivered) delivery = "delivered" + (s.delivered > 1 ? " ×" + s.delivered : "");- }- return {- name: relTime(s.createdAt || s.lastActivity),- preview: [delivery, plural(s.turns || 0, "turn"), s.result || "(no messages)"]- .filter(Boolean)- .join(" · "),- time: plural(s.messages || 0, "entry", "entries"),- cls: typeof s.delivered === "number" && !s.delivered ? "dim" : "",- href: stateToUrl({ view: "history", scope: s.scopeId || scope, session: s.id }),- };- },- (s) => go({ view: "history", scope: s.scopeId || scope, session: s.id }),- "This cron has never fired.",- );- container.appendChild(t);- const total = r.data.total || fires.length;- if (total > limit) {- const more = document.createElement("button");- more.type = "button";- more.className = "prompt-toggle";- more.textContent = "All " + plural(total, "fire") + " →";- more.onclick = () =>- go({ view: "history", scope, session: null, page: 1, historyKind: "cron", cron: cronId });- container.appendChild(more);- }- }- function renderDeployments(root, d) {- const index = orgWideView() && !orgOwnView();- const allDeps = [...(d.deployments || [])].sort(- (a, b) => (b.lastAccessAt || b.createdAt || 0) - (a.lastAccessAt || a.createdAt || 0),- );- const deployments = orgOwnView() ? allDeps.filter((dep) => scopeKind(dep.ownerScopeId) === "org") : allDeps;- const count = plural(deployments.length, "app");- const previewOf = (dep) =>- [- titleCase(dep.status || "unknown"),- dep.currentVersion || "",- index ? shortName(dep.ownerScopeId) : "",- dep.createdBy || "",- ]- .filter(Boolean)- .join(" · ");- const depRow = (dep) => ({- name: dep.name || dep.id,- preview: previewOf(dep),- time: relTime(dep.lastAccessAt || dep.createdAt),- href: deploymentHref(dep) || undefined,- target: "_blank",- });- const openDep = (dep) => {- const href = deploymentHref(dep);- if (href) window.open(href, "_blank", "noopener,noreferrer");- };- const lastTouch = (dep) => dep.lastAccessAt || dep.createdAt || 0;- const names = deployments.map((dep) => (dep.name || dep.id).toLowerCase());- const t = denseList(deployments, depRow, openDep, index ? "No apps yet." : "No apps in this scope.");- let scopeWrap = null;- if (index) {- scopeWrap = document.createElement("div");- scopeWrap.appendChild(- scopeIndexList(allDeps, {- latestOf: lastTouch,- noun: "app",- empty: "No apps yet.",- }),- );- }- const noMatch = document.createElement("p");- noMatch.className = "empty hidden";- noMatch.textContent = "No apps match.";- const listWrap = document.createElement("div");- listWrap.append(t, noMatch);- wireScopeSearch({- key: "deployments",- indexWrap: scopeWrap,- listWrap,- rows: [...t.children],- names,- noMatch,- total: deployments.length,- shell: {- ...(index- ? {}- : {- back: {- label: "← " + VIEW_TITLE.deployments,- onClick: () =>- go({ view: "deployments", scope: "org:" + orgId, own: null, session: null, page: 1 }),- },- }),- title: index ? VIEW_TITLE.deployments : shortName(scope),- count,- },- placeholder: index ? "Search all apps…" : "Search apps…",- });- const card = bareDataCard(listWrap);- if (scopeWrap) card.querySelector(".body").prepend(scopeWrap);- root.appendChild(card);+ function renderDeployments(root, d) {+ governanceUI.artifacts.deployments(root, d, artifactContext());}function packRepoLabel(url) {@@ -14436,284 +9761,8 @@return { text: s.createdBy || "None", cls: "mono" };}- function skillIdentityKey(s) {- return (s.name || s.id) + "\u0000" + (s.createdBy || "");- }- function groupSkillsByIdentity(skills) {- const byKey = new Map();- for (const s of skills) {- const key = skillIdentityKey(s);- let g = byKey.get(key);- if (!g) {- g = { key, records: [] };- byKey.set(key, g);- }- g.records.push(s);- }- for (const g of byKey.values()) {- g.rep =- g.records.find((r) => scopeKind(r.ownerScopeId) === "org" && r.status === "published") ||- g.records.find((r) => r.status === "published") ||- g.records[0];-- g.scopeIds = g.records- .map((r) => r.ownerScopeId)- .sort((a, b) => {- if (scopeKind(a) === "org") return -1;- if (scopeKind(b) === "org") return 1;- return a.localeCompare(b);- });- }- return [...byKey.values()];- }-- function skillRemoveAction(records) {- const live = (records || []).filter((r) => r.status !== "archived");- if (!live.length) return badge("archived", "muted");- const rm = document.createElement("button");- rm.type = "button";- rm.className = "rowbtn danger";- rm.textContent = "Remove";- rm.onclick = async (e) => {- e.stopPropagation();- const name = (records[0] && (records[0].name || records[0].id)) || "this skill";- const where =- live.length === 1- ? "from " + (dirLabel(live[0].ownerScopeId) || live[0].ownerScopeId)- : "from all " + live.length + " scopes";- if (!confirm("Remove '" + name + "' " + where + "? It stops being available to agents (kept for audit)."))- return;- rm.disabled = true;- let failed = 0;- for (const r of live) {- const res = await api(- "DELETE",- "/api/skills/" + encodeURIComponent(r.id) + "?scope=" + encodeURIComponent(r.ownerScopeId || scope),- );- if (!res.ok) failed++;- }- dataCache.clear();- renderData();- if (failed) alert(failed + " scope(s) could not be removed.");- };- return rm;- }function renderSkills(root, d) {- const index = orgWideView() && !orgOwnView();-- if (index) {- const packsHolder = document.createElement("div");- root.appendChild(packsHolder);- void fillPacksSection(packsHolder);- }- const detail = document.createElement("div");-- const lastUse = (s) => s.lastUsedAt || s.updatedAt || s.createdAt || 0;- const allSkills = (d.skills || [])- .filter((s) => s.status !== "archived")- .sort((a, b) => lastUse(b) - lastUse(a) || (a.name || "").localeCompare(b.name || ""));- const skills = orgOwnView() ? allSkills.filter((s) => scopeKind(s.ownerScopeId) === "org") : allSkills;- const count =- plural(skills.length, "skill") +- (index && skills.length ? " · " + plural(new Set(skills.map((s) => s.ownerScopeId)).size, "scope") : "");-- const recordsByKey = new Map(groupSkillsByIdentity(allSkills).map((g) => [g.key, g.records]));- const openSkill = (s) => openSkillDetail(detail, s, recordsByKey.get(skillIdentityKey(s)) || [s]);- const names = skills.map((s) => ((s.name || s.id) + " " + (s.description || "")).toLowerCase());- const lastUsedText = (s) => {- if (s.lastUsedAt) return fmtHistoryTime(s.lastUsedAt);- if (lastUse(s)) return "never · imported " + fmtHistoryTime(lastUse(s));- return "never";- };-- let scopeWrap = null;- if (index) {- scopeWrap = document.createElement("div");- scopeWrap.appendChild(- scopeIndexList(allSkills, {- latestOf: lastUse,- noun: "skill",- empty: "No skills yet.",- }),- );- }- const t = openableTable(- ["Skill", ...(index ? ["Scope"] : []), "Status", "Created by", "Last used", ""],- skills,- (s) => [- nodeCell(stacked(s.name || s.id, s.description || shortId(s.id))),- ...(index ? [{ text: shortName(s.ownerScopeId), cls: "mono" }] : []),- { text: titleCase(s.status || "unknown"), cls: "subline" },- createdByCell(s),- {- text: lastUsedText(s),- cls: s.lastUsedAt ? "num" : "num subline",- },- nodeCell(skillRemoveAction([s])),- ],- openSkill,- index ? "No skills yet." : "No skills in this scope.",- { className: "skills-table" },- );- const noMatch = document.createElement("p");- noMatch.className = "empty hidden";- noMatch.textContent = "No skills match.";- const tableWrap = document.createElement("div");- tableWrap.append(t, noMatch);- wireScopeSearch({- key: "skills",- indexWrap: scopeWrap,- listWrap: tableWrap,- rows: [...t.querySelectorAll("tbody tr")],- names,- noMatch,- total: skills.length,- shell: {- ...(index- ? {}- : {- back: {- label: "← " + VIEW_TITLE.skills,- onClick: () => go({ view, scope: "org:" + orgId, own: null, session: null, page: 1 }),- },- }),- title: index ? VIEW_TITLE.skills : shortName(scope),- count,- },- placeholder: index ? "Search all skills…" : "Search skills…",- });- const card = dataCard("Installed skills", "", tableWrap);- if (scopeWrap) card.querySelector(".body").prepend(scopeWrap);- root.appendChild(card);- root.appendChild(detail);- }- async function openSkillDetail(holder, rep, group) {- group = group && group.length ? group : [rep];- holder.textContent = "";- const loading = document.createElement("div");- loading.className = "loadingline";- loading.textContent = "Loading " + (rep.name || rep.id) + "…";- holder.appendChild(loading);-- const r = await api(- "GET",- "/api/skills/" + encodeURIComponent(rep.id) + "?scope=" + encodeURIComponent(rep.ownerScopeId || scope),- );- holder.textContent = "";- if (!r.ok || !r.data) {- const p = document.createElement("p");- p.className = "empty";- p.textContent = r.status === 403 ? "You don't administer this skill's scope." : "Couldn't load this skill.";- holder.appendChild(p);- return;- }- const k = r.data;- const box = document.createElement("div");- let byFact = ["by " + (k.createdBy || "None"), "muted"];- if (k.pack) byFact = ["from " + (packRepoLabel(k.pack.url) || "pack " + shortId(k.pack.id, 8)), "muted"];- else if (k.createdBy && k.createdBy.indexOf("system:") === 0) byFact = ["built-in", "muted"];- const facts = [- { node: statusBadge(k.status) },- ["v" + k.version, "muted"],- byFact,- ["skill " + shortId(k.id, 16), "muted"],- ];- box.appendChild(badgeList(facts));- if (k.description) {- const p = document.createElement("p");- p.className = "metric-note";- p.textContent = k.description;- box.appendChild(p);- }-- const detailScopeRows = group- .slice()- .sort((a, b) => {- if (scopeKind(a.ownerScopeId) === "org") return -1;- if (scopeKind(b.ownerScopeId) === "org") return 1;- return (a.ownerScopeId || "").localeCompare(b.ownerScopeId || "");- })- .map((g) => [- scopeCell(g.ownerScopeId),- nodeCell(statusBadge(g.status)),- { text: g.version != null ? "v" + g.version : "None", cls: "num" },- nodeCell(skillScopeAction(g)),- ]);- box.appendChild(- dataCard(- "Scopes (" + group.length + ")",- "Every scope this skill is installed in. Remove takes it out of that scope only.",- table(["Scope", "Status", "Version", ""], detailScopeRows, "None"),- ),- );- const capRows = (k.requiredCapabilities || []).map((c) => [- { text: c, cls: "mono" },- nodeCell((k.grantedCapabilities || []).includes(c) ? badge("granted", "ok") : badge("not granted", "warn")),- ]);- box.appendChild(- dataCard(- "Capabilities",- "What the skill is allowed to reach. Granted at review time.",- table(["Capability", "Status"], capRows, "Requires no capabilities."),- ),- );- if ((k.approvals || []).length)- box.appendChild(- dataCard(- "Approvals",- "Reviewers who signed off on this skill.",- table(- ["Reviewer"],- k.approvals.map((a) => [{ text: a, cls: "mono" }]),- ),- ),- );- const pre = document.createElement("pre");- pre.className = "skillbody";- pre.textContent = k.body || "(empty)";- pre.style.whiteSpace = "pre-wrap";- pre.style.fontFamily = "ui-monospace, SFMono-Regular, Menlo, monospace";- pre.style.fontSize = "12px";- pre.style.margin = "0";- box.appendChild(dataCard("Instructions", "The SKILL.md the agent reads when this skill is in play.", pre));- holder.appendChild(dataCard(k.name || k.id, "", box));- holder.scrollIntoView({ behavior: "smooth", block: "nearest" });- }-- function skillScopeAction(g) {- if (g.status === "archived") return badge("archived", "muted");- const rm = document.createElement("button");- rm.type = "button";- rm.className = "rowbtn danger";- rm.textContent = "Remove";- rm.onclick = async () => {- if (- !confirm(- "Remove '" +- (g.name || g.id) +- "' from " +- (dirLabel(g.ownerScopeId) || g.ownerScopeId) +- "? It stops being available to agents in that scope (kept for audit).",- )- )- return;- const r = await api(- "DELETE",- "/api/skills/" + encodeURIComponent(g.id) + "?scope=" + encodeURIComponent(g.ownerScopeId || scope),- );- if (r.ok) {- dataCache.clear();- renderData();- } else {- alert(r.data?.message || "Failed (" + r.status + ").");- }- };- return rm;- }- async function fillPacksSection(holder) {- const r = await api("GET", "/api/skill-packs");- holder.textContent = "";- renderPacksSection(holder, (r.ok && r.data && r.data.packs) || []);+ governanceUI.artifacts.skills(root, d, artifactContext());}let openOvMenu = null;@@ -14767,229 +9816,6 @@wrap.append(btn, menu);return wrap;}- function renderPacksSection(root, packs) {- const detail = document.createElement("div");- const box = document.createElement("div");-- const mkInput = (ph, title) => {- const i = document.createElement("input");- i.type = "text";- i.placeholder = ph;- if (title) i.title = title;- i.setAttribute("aria-label", ph);- i.spellcheck = false;- return i;- };- const row = document.createElement("div");- row.className = "pack-register";- const url = mkInput("Register a pack: paste a git repo URL of SKILL.md files, then Browse it into scopes");- const adv = document.createElement("div");- adv.className = "pack-adv hidden";- const ref = mkInput(- "ref (branch or SHA)",- "Pin to a branch or full 40-hex commit SHA. Blank = the repo's default branch.",- );- const excl = mkInput("exclude globs, comma-separated", "e.g. trusted/*");- const slug = mkInput(- "deploy-token slug",- "Private-repo deploy-token credential slug. Blank = your connected GitHub account.",- );- const tier = document.createElement("select");- tier.title = "Trust tier";- for (const t of ["third-party", "internal"]) {- const o = document.createElement("option");- o.value = t;- o.textContent = "trust: " + t;- tier.appendChild(o);- }- adv.append(ref, excl, slug, tier);- const advToggle = document.createElement("button");- advToggle.type = "button";- advToggle.className = "linkish";- advToggle.setAttribute("aria-expanded", "false");-- const advHasValues = () =>- Boolean(ref.value.trim() || excl.value.trim() || slug.value.trim() || tier.value !== "third-party");- const paintAdvToggle = () => {- const open = !adv.classList.contains("hidden");- advToggle.textContent = "Advanced" + (!open && advHasValues() ? " •" : "");- advToggle.classList.toggle("open", open);- advToggle.setAttribute("aria-expanded", String(open));- };- paintAdvToggle();- for (const el of [ref, excl, slug, tier]) el.addEventListener("change", paintAdvToggle);- advToggle.onclick = () => {- adv.classList.toggle("hidden");- paintAdvToggle();- };- const status = document.createElement("span");- status.className = "status";- const btn = document.createElement("button");- btn.type = "button";- btn.className = "primary";- btn.textContent = "Register";- btn.onclick = async () => {- if (!url.value.trim()) {- status.className = "status err";- status.textContent = "A repo URL is required.";- return;- }- btn.disabled = true;- status.className = "status";- status.textContent = "Registering…";- const body = { url: url.value.trim() };- if (ref.value.trim()) body.ref = ref.value.trim();- const ex = excl.value- .split(",")- .map((x) => x.trim())- .filter(Boolean);- if (ex.length) body.config = { exclude: ex };- if (slug.value.trim()) body.authCredentialSlug = slug.value.trim();- if (tier.value !== "third-party") body.trustTier = tier.value;- const r = await api("POST", "/api/skill-packs", body);- btn.disabled = false;- if (!r.ok) {- status.className = "status err";- status.textContent = r.data?.message || "Failed (" + r.status + ").";- return;- }- dataCache.clear();- renderData();- };- row.append(url, advToggle, btn, status);- box.append(row, adv);-- const rows = packs.map((s) => {- const li = s.lastImport;- const c = (li && li.counts) || {};- const delta = li- ? "last sync: " +- (c.imported || 0) +- " new · " +- (c.updated || 0) +- " updated · " +- (c.skipped || 0) +- " skipped" +- (c.archived ? " · " + c.archived + " removed" : "")- : "";- const packNode = document.createElement("span");- packNode.className = "pack-name";- const nm = document.createElement("strong");- nm.textContent = packRepoLabel(s.url) || s.url;- packNode.appendChild(nm);- if (s.ref) {- const rf = document.createElement("span");- rf.className = "subline";- rf.textContent = " @ " + shortId(s.ref, 10);- packNode.appendChild(rf);- }- packNode.title = s.url + (delta ? "\n" + delta : "");- const skillsNode = document.createElement("span");- skillsNode.textContent = s.available != null ? (s.importedCount || 0) + " of " + s.available : "n/a";- if (s.available != null)- skillsNode.title =- (s.importedCount || 0) + " imported · " + s.available + " available (eligible) in this pack";- const st = document.createElement("span");- st.className = "status";- const setStatusText = (text, cls, title) => {- st.textContent = text;- st.className = "status" + (cls ? " " + cls : " muted");- if (title) st.title = title;- };- if (li && li.status === "error")- setStatusText("error: " + (li.error || "sync failed"), "err", li.error || "");- else if (s.updateAvailable)- setStatusText(- "update available",- "dirty",- "Upstream advanced past the imported commit. Sync now (or turn on Auto-sync) to apply.",- );- else setStatusText(li ? "up to date" : "not imported", "muted", delta);- const isTracked = s.syncMode === "tracked";- let busy = false;- const menu = overflowMenu([- { label: "Browse skills…", onClick: () => browsePack(s, detail) },- {- label: "Sync now",- title:- "Pull the pack's latest commit and refresh already-imported skills (update changed, archive removed). Does NOT add new skills; use Browse for that.",- onClick: async () => {- if (busy) return;- busy = true;- setStatusText("syncing…", "saving");- const r = await api("POST", "/api/skill-packs/" + encodeURIComponent(s.id) + "/sync", {});- busy = false;- if (!r.ok) {- setStatusText("sync failed: " + (r.data?.message || r.status), "err", r.data?.message || "");- return;- }- const d = r.data || {};- const n = (d.imported || []).length,- u = (d.updated || []).length,- a = (d.archived || []).length;- setStatusText(- n || u || a- ? "✓ " + n + " new" + (u ? " · " + u + " updated" : "") + (a ? " · " + a + " removed" : "")- : "✓ up to date",- "ok",- );- setTimeout(() => {- dataCache.clear();- renderData();- }, 1200);- },- },- {- label: isTracked ? "Turn off auto-sync" : "Turn on auto-sync",- title: isTracked- ? "Auto-sync is ON. Re-imports when the upstream advances."- : "Auto-sync is OFF. Manual Sync only.",- onClick: async () => {- if (busy) return;- busy = true;- const r = await api("PATCH", "/api/skill-packs/" + encodeURIComponent(s.id), {- syncMode: isTracked ? "pinned" : "tracked",- });- busy = false;- if (!r.ok) {- alert(r.data?.message || "Failed (" + r.status + ").");- return;- }- dataCache.clear();- renderData();- },- },- {- label: "Remove pack",- danger: true,- onClick: async () => {- if (busy) return;- if (!confirm("Remove this pack and archive its imported skills?")) return;- busy = true;- const r = await api("DELETE", "/api/skill-packs/" + encodeURIComponent(s.id));- busy = false;- if (r.ok) {- dataCache.clear();- renderData();- }- },- },- ]);- return [- { node: packNode },- { node: skillsNode, cls: "num" },- { text: s.trustTier + (isTracked ? " · auto-sync" : ""), cls: "subline" },- { node: st },- { node: menu, cls: "num" },- ];- });- box.appendChild(table(["Pack", "Skills", "Trust", "Status", ""], rows, "No packs yet. Register one above."));- root.appendChild(- dataCard("Skill packs", "Register a repository, then choose which skills to import into each scope.", box),- );- root.appendChild(detail);- }-function buildScopeMultiSelect(choices, selected, onChange) {const pick = document.createElement("div");pick.className = "scopepick";@@ -15162,538 +9988,11 @@renderChips();return pick;}- async function browsePack(s, holder) {- holder.textContent = "";- const loading = document.createElement("div");- loading.className = "loadingline";- loading.textContent = "Fetching " + s.url + "…";- holder.appendChild(loading);- const r = await api("GET", "/api/skill-packs/" + encodeURIComponent(s.id) + "/catalog");- holder.textContent = "";- if (!r.ok || !r.data) {- const p = document.createElement("p");- p.className = "empty";- p.textContent = r.data?.message || "Couldn't browse (" + r.status + ").";- holder.appendChild(p);- return;- }- const plan = r.data,- counts = plan.counts || {};- const box = document.createElement("div");- const candidates = plan.candidates || [];- const bundlePaths = plan.bundlePaths || [];-- const orgScopeId = "org:" + orgId;- const selectedScopes = new Set([orgScopeId]);- const importedInAll = (c) => {- const arr = c.importedScopes || [];- return selectedScopes.size > 0 && [...selectedScopes].every((sc) => arr.includes(sc));- };- const importedInSome = (c) => {- const arr = c.importedScopes || [];- return [...selectedScopes].some((sc) => arr.includes(sc));- };-- const importable = (c) => c.eligible && !importedInAll(c);- const catOf = (c) => {- if (importedInAll(c)) return "imported";- if (c.eligible) return "eligible";- return c.excludeReason || "excluded";- };-- const cbFor = new Map();- let checks = [];-- const headCb = document.createElement("input");- headCb.type = "checkbox";- headCb.title = "Select / deselect all importable skills";- const syncHead = () => {- const n = checks.length,- sel = checks.filter((cb) => cb.checked).length;- headCb.checked = n > 0 && sel === n;- headCb.indeterminate = sel > 0 && sel < n;- };- headCb.onchange = () => {- checks.forEach((cb) => {- cb.checked = headCb.checked;- });- headCb.indeterminate = false;- };- for (const c of candidates) {- const cb = document.createElement("input");- cb.type = "checkbox";- cb.dataset.name = c.upstreamName;- cb.onchange = syncHead;- cbFor.set(c, cb);- }- let activeFilter = "all";-- const REASON = {- all: { label: "all", tone: "muted", help: "Show every skill." },- eligible: {- label: "eligible",- tone: "ok",- help: "Eligible and not yet in the selected scope(s). Importing adds it there.",- },- imported: {- label: "imported",- tone: "info",- help: "Already imported into the selected scope(s). Sync refreshes them; un-index to remove.",- },- scope: {- label: "personal-scoped",- tone: "muted",- help: "Held back: declares a personal/owner scope, so it isn't imported as a shared pack skill.",- },- private: { label: "private", tone: "muted", help: "Held back: marked owner-only / agent-only." },- collision: {- label: "collision",- tone: "muted",- help: "Held back: the name matches an existing platform or seed skill.",- },- "binary-asset": {- label: "binary files",- tone: "muted",- help: "Held back: contains binary files (import is text-only).",- },- malformed: {- label: "malformed",- tone: "muted",- help: "Held back: missing or unreadable SKILL.md frontmatter.",- },- };- const reasonLabel = (key) => (REASON[key] ? REASON[key].label : key || "excluded");- const rowBadge = (c) => {- if (importedInAll(c)) {- const b = badge("imported", "info");- b.title = "Already imported into the selected scope(s): " + (c.importedScopes || []).join(", ");- return b;- }- if (c.eligible) {- const b = badge("eligible", "ok");- if (importedInSome(c))- b.title =- "Imported into " +- (c.importedScopes || []).join(", ") +- ". Importing adds it to the other selected scope(s).";- return b;- }- const b = badge(reasonLabel(c.excludeReason), "warn");- if (REASON[c.excludeReason]) b.title = REASON[c.excludeReason].help;- return b;- };-- const importButtons = [];- const doImport = async (status) => {- const scopes = [...selectedScopes];- const names = checks.filter((b) => b.checked).map((b) => b.dataset.name);- if (!scopes.length) {- status.className = "status err";- status.textContent = "Pick at least one scope to add skills to.";- return;- }- if (!names.length) {- status.className = "status err";- status.textContent = "Select at least one skill.";- return;- }- importButtons.forEach((b) => {- b.disabled = true;- });- status.className = "status";- status.textContent = "Importing…";- const allEligible = checks.length === names.length;- const r2 = await api("POST", "/api/skill-packs/" + encodeURIComponent(s.id) + "/import", {- selected: allEligible ? "all" : names,- scopeIds: scopes,- });- importButtons.forEach((b) => {- b.disabled = false;- });- if (!r2.ok) {- status.className = "status err";- status.textContent = r2.data?.message || "Import failed (" + r2.status + ").";- return;- }- const added = r2.data.imported?.length ?? 0;- status.className = "status ok";- status.textContent =- "✓ " +- added +- " skill" +- (added === 1 ? "" : "s") +- " added" +- (scopes.length > 1 ? " across " + scopes.length + " scopes" : "");- dataCache.clear();- setTimeout(() => renderData(), 1500);- };- const importAction = () => {- const status = document.createElement("span");- status.className = "status";- const btn = document.createElement("button");- btn.type = "button";- btn.className = "primary";- btn.textContent = "Import selected";- btn.onclick = () => doImport(status);- importButtons.push(btn);-- const wrap = document.createElement("div");- wrap.style.cssText = "display:flex; flex-direction:column; align-items:flex-start; gap:6px;";- wrap.append(btn, status);- return wrap;- };-- const summary = document.createElement("div");- summary.className = "badges";- summary.style.flex = "1";- const PILL_ORDER = [- "all",- "eligible",- "imported",- "scope",- "private",- "collision",- "binary-asset",- "malformed",- ];- const pillCount = (key) => {- if (key === "all") return candidates.length;- if (key === "eligible") return candidates.filter(importable).length;- if (key === "imported") return candidates.filter(importedInAll).length;- return counts[key] || 0;- };- const pillShown = (key) => {- if (key === "all" || key === "eligible") return true;- if (key === "imported") return candidates.some((c) => (c.importedScopes || []).length);- return !!counts[key];- };- const paintSummary = () => {- summary.textContent = "";- for (const key of PILL_ORDER) {- if (!pillShown(key)) continue;- const meta = REASON[key] || { label: key, tone: "muted", help: "" };- const b = badge(pillCount(key) + " " + meta.label, meta.tone);- b.style.cursor = "pointer";- if (activeFilter === key) {- b.style.background = "var(--text)";- b.style.color = "#fff";- b.style.borderColor = "var(--text)";- }- b.title = (meta.help ? meta.help + " " : "") + (key === "all" ? "" : "Click to show only these.");- b.onclick = () => {- activeFilter = key;- recompute();- };- summary.append(b);- }- };-- const tableHolder = document.createElement("div");- const renderRows = () => {- const shown = candidates.filter((c) => activeFilter === "all" || catOf(c) === activeFilter);- const rows = shown.map((c) => {- const desc = (c.normalized && c.normalized.manifest && c.normalized.manifest.description) || "";- return [{ node: cbFor.get(c) }, { node: stacked(c.upstreamName, desc) }, { node: rowBadge(c) }];- });- tableHolder.textContent = "";- tableHolder.appendChild(- table(- [headCb, "Skill", ""],- rows,- activeFilter === "all" ? "No skills found in this pack." : "No " + reasonLabel(activeFilter) + " skills.",- ),- );- };-- const recompute = () => {- checks = [];- for (const c of candidates) {- const cb = cbFor.get(c);- const imp = importable(c);- const was = cb.dataset.imp === "1";- cb.disabled = !imp;- if (!imp) cb.checked = false;- else if (!was) cb.checked = true;- cb.dataset.imp = imp ? "1" : "0";- if (imp) checks.push(cb);- }- renderRows();- paintSummary();- syncHead();- };-- const scopeChoices = [- { scopeId: orgScopeId, label: "org-wide" },- ...scopeRows().map((row) => ({- scopeId: row.scopeId,- label: row.label || dirLabel(row.scopeId) || row.scopeId,- })),- ];- const scopeRow = document.createElement("div");- scopeRow.style.cssText = "display:flex; align-items:center; gap:8px; flex-wrap:wrap; margin:2px 0 4px;";- const scopeLab = document.createElement("span");- scopeLab.textContent = "Add to scopes:";- scopeLab.style.cssText = "font-size:12px; opacity:0.7;";- scopeRow.append(scopeLab, buildScopeMultiSelect(scopeChoices, selectedScopes, recompute));- box.appendChild(scopeRow);-- if (bundlePaths.length) {- const details = document.createElement("details");- details.style.margin = "8px 0";- const summary = document.createElement("summary");- summary.textContent =- bundlePaths.length +- " shared pack file" +- (bundlePaths.length === 1 ? "" : "s") +- " (contained under a pack-owned directory)";- const pre = document.createElement("pre");- pre.textContent = bundlePaths.join("\n");- pre.style.cssText =- "max-height:180px;overflow:auto;font-size:11px;padding:10px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);";- details.append(summary, pre);- box.appendChild(details);- }-- const topRow = document.createElement("div");- topRow.style.display = "flex";- topRow.style.alignItems = "center";- topRow.style.gap = "12px";- topRow.style.flexWrap = "wrap";- topRow.style.margin = "10px 0 16px";- topRow.append(summary, importAction());- box.appendChild(topRow);-- box.appendChild(tableHolder);- const bottomImport = importAction();- bottomImport.style.marginTop = "10px";- box.appendChild(bottomImport);- recompute();- const card = dataCard(- "Browse: " + s.url,- "Choose target scopes, then import. Eligible skills are added to every selected scope; excluded skills show why. They appear on the Skills page once imported.",- box,- );-- card.style.position = "relative";- const close = document.createElement("button");- close.type = "button";- close.textContent = "✕";- close.title = "Close";- close.setAttribute("aria-label", "Close browse");- close.style.cssText =- "position:absolute;top:10px;right:12px;border:none;background:transparent;cursor:pointer;font-size:18px;line-height:1;color:var(--text);opacity:0.55;padding:4px;";- close.onmouseenter = () => {- close.style.opacity = "1";- };- close.onmouseleave = () => {- close.style.opacity = "0.55";- };- close.onclick = () => {- holder.textContent = "";- };- card.appendChild(close);- holder.appendChild(card);- holder.scrollIntoView({ behavior: "smooth", block: "nearest" });- }function renderMemory(root, d) {- if (Array.isArray(d.scopes)) return renderMemoryIndex(root, d);-- if (scopeDir) {- pageShell({- back: { label: "← Memory", onClick: () => go({ view: "memory", scope: "org:" + orgId, session: null }) },- title: orgWideView() ? "Org-wide" : shortName(scope),- });- }- const server = d.content || "";- const wrap = document.createElement("div");- const ta = document.createElement("textarea");- ta.id = "memory-text";- ta.spellcheck = false;- ta.setAttribute("aria-label", "Notebook contents");- ta.value = memDraft !== null && memDraftScope === scope ? memDraft : server;- ta.style.minHeight = "340px";- ta.style.fontFamily = "ui-monospace, SFMono-Regular, Menlo, monospace";- ta.style.fontSize = "12px";- ta.placeholder = "No memory stored for this scope yet. Anything you write here, the agent will remember.";- const foot = document.createElement("div");- foot.className = "foot";- const save = document.createElement("button");- save.className = "primary";- save.textContent = "Save";- const st = document.createElement("span");- st.className = "status";- st.id = "st-memory";- const syncHint = () => {- if (ta.value !== server) setStatus("st-memory", "Unsaved changes", "");- };- ta.oninput = () => {- memDraft = ta.value;- memDraftScope = scope;- };- if (ta.value !== server) syncHint();- save.onclick = async () => {- save.disabled = true;- const r = await api("PUT", "/api/memory?scope=" + encodeURIComponent(scope), { content: ta.value });- save.disabled = false;- if (r.ok) {- memDraft = null;- memDraftScope = null;- setStatus("st-memory", "Saved ✓", "ok");- } else- setStatus(- "st-memory",- r.status === 403 ? "You don't administer this scope." : r.data?.message || "Save failed.",- "err",- );- };- foot.append(save, st);- wrap.append(ta, foot);- const label = document.createElement("label");- label.htmlFor = "memory-text";- label.textContent = "Notebook contents";- wrap.prepend(label);- st.setAttribute("role", "status");- const card = dataCard("Notebook", "What the agent remembers in this scope. Changes apply when you save.", wrap);- card.classList.add("memory-editor");- root.appendChild(card);- }- function renderMemoryIndex(root, d) {- let query = "";- const list = document.createElement("div");- list.className = "memory-notebooks";- const scopes = (d.scopes || []).filter((s) => s.hasMemory || scopeKind(s.scopeId) === "org");- const written = scopes.filter((s) => s.hasMemory);- const hasTimestamps = written.some((s) => s.updatedAt);- scopes.sort((a, b) =>- hasTimestamps- ? (b.updatedAt || 0) - (a.updatedAt || 0) || (b.bytes || 0) - (a.bytes || 0)- : (b.bytes || 0) - (a.bytes || 0),- );- const openScope = (s) =>- go(- scopeKind(s.scopeId) === "org"- ? { view: "memory", scope: s.scopeId, session: null, mem: "edit" }- : { view: "memory", scope: s.scopeId, session: null },- );- pageShell({- title: VIEW_TITLE.memory,- count: plural(written.length, "notebook"),- search: {- placeholder: "Search notebooks…",- onInput: (value) => {- query = value.trim().toLowerCase();- draw();- },- },- context: written.length && !hasTimestamps ? "sorted by size (this backend keeps no edit history)" : "",- });- const draw = () => {- const visible = scopes.filter(- (s) => !query || [s.label, shortName(s.scopeId), s.scopeId].join(" ").toLowerCase().includes(query),- );- const t = denseList(- visible,- (s) => ({- name: scopeKind(s.scopeId) === "org" ? "org" : s.label || shortName(s.scopeId),- preview: s.hasMemory ? fmtBytes(s.bytes || 0) : "empty",- time: s.updatedAt ? relTime(s.updatedAt) : "Never",- href: stateToUrl(- scopeKind(s.scopeId) === "org"- ? { view: "memory", scope: s.scopeId, mem: "edit" }- : { view: "memory", scope: s.scopeId },- ),- }),- openScope,- query ? "No notebooks match your search." : "No notebooks yet. The agent hasn't remembered anything.",- );- const headings = document.createElement("div");- headings.className = "memory-columns";- for (const text of ["Notebook", "Size", "Last updated"]) {- const label = document.createElement("span");- label.textContent = text;- headings.appendChild(label);- }- list.replaceChildren(headings, t);- };- draw();- root.appendChild(list);+ governanceUI.artifacts.memory(root, d, artifactContext());}function renderRetention(root, d) {- const a = d.active || {};- root.appendChild(- kpis([- [a.dau ?? 0, "DAU"],- [a.wau ?? 0, "WAU"],- [a.mau ?? 0, "MAU"],- [(a.stickiness ?? 0) + "%", "Stickiness (DAU/MAU)"],- ]),- );- const stick = document.createElement("div");- stick.className = "metric-note";- let stickinessTone = "muted";- if ((a.stickiness ?? 0) >= 30) stickinessTone = "ok";- else if ((a.stickiness ?? 0) >= 10) stickinessTone = "warn";- stick.append("Stickiness", badge(String(a.stickiness ?? 0) + "%", stickinessTone));- root.appendChild(stick);- const nvr = d.newVsReturning || {};- root.appendChild(- dataCard(- "New vs returning",- `Distinct active users in the trailing ${nvr.window || "30d"}.`,- table(- ["New", "Returning"],- [- [- { text: String(nvr.newUsers ?? 0), cls: "num" },- { text: String(nvr.returning ?? 0), cls: "num" },- ],- ],- "No activity yet.",- ),- ),- );- const retentionCell = (p) => {- let tone = "muted";- if (p >= 40) tone = "ok";- else if (p >= 15) tone = "warn";- return nodeCell(badge(p + "%", tone), "num");- };- const cohortRows = (d.cohorts || []).map((c) => [- c.week,- { text: String(c.size), cls: "num" },- ...(c.retained || []).map(retentionCell),- ]);- root.appendChild(- dataCard(- "Weekly retention cohorts",- "Of users first active in a week, the share active in following weeks. Channel attribution is approximate.",- table(["Cohort (week of)", "Users", "W0", "W1", "W2", "W3", "W4"], cohortRows, "No cohorts yet."),- ),- );- const pu = d.perUser || { sessions: {}, turns: {} };- const dist = table(- ["Metric", "p50", "p95"],- [- [- "Sessions / user",- { text: String(pu.sessions?.p50 ?? 0), cls: "num" },- { text: String(pu.sessions?.p95 ?? 0), cls: "num" },- ],- [- "Turns / user",- { text: String(pu.turns?.p50 ?? 0), cls: "num" },- { text: String(pu.turns?.p95 ?? 0), cls: "num" },- ],- ],- "No users yet.",- );- root.appendChild(- dataCard(- "Per-user distribution",- `${d.totals?.users ?? 0} users · ${d.totals?.sessions ?? 0} sessions. ${d.attribution || ""}`,- dist,- ),- );+ governanceUI.artifacts.retention(root, d);}function actionTable(headers, items, cellsOf, emptyMsg) {if (!items.length) {@@ -15726,31 +10025,33 @@t.appendChild(tb);return tableWrap(t);}- async function revokeGrant(g) {- if (- !confirm(- 'Revoke admin access for "' +- g.principalId +- '"? The core will refuse this if it would remove the last org admin.',- )- )- return;- const r = await api(- "DELETE",- "/api/grants/" +- encodeURIComponent(g.principalId) +- "?scope=" +- encodeURIComponent(g.scopeId) +- "&role=" +- encodeURIComponent(g.role),- );- if (r.ok) renderData();- else- setStatus(- "st-users",- r.status === 403 ? "Only an org admin may revoke." : r.data?.message || "Revoke failed.",- "err",- );+ async function changeUserAdmin(user, event) {+ event?.stopPropagation?.();+ const revoke = user.admin?.isAdmin;+ const principalId = user.principalId;+ if (!confirm((revoke ? "Revoke admin access for " : "Make admin: ") + principalId + "?")) return;+ const button = event?.currentTarget;+ if (button) button.disabled = true;+ setStatus("st-users", "");+ try {+ const r = revoke+ ? await api(+ "DELETE",+ "/api/grants/" ++ encodeURIComponent(principalId) ++ "?scope=" ++ encodeURIComponent(user.admin.scopeId) ++ "&role=" ++ encodeURIComponent(user.admin.role),+ )+ : await api("POST", "/api/grants", { principalId, role: "org_admin", scopeId: "org:" + orgId });+ if (r.ok) await renderData();+ else setStatus("st-users", r.data?.message || "Could not update admin access.", "err");+ } catch {+ setStatus("st-users", "Network error. Try again.", "err");+ } finally {+ if (button) button.disabled = false;+ }}async function revokeExternalUser(m) {const question =@@ -15763,7 +10064,7 @@elsesetStatus("st-external",- r.status === 403 ? "Only an org admin may revoke." : r.data?.message || "Revoke failed.",+ r.status === 403 ? "Only an admin may revoke." : r.data?.message || "Revoke failed.","err",);}@@ -15785,552 +10086,26 @@return p.displayName ? `${p.displayName} (${p.principalId})` : p.principalId;}function renderKeychain(root, d) {- if (d.enabled === false) {- const p = document.createElement("p");- p.className = "empty";- p.textContent = "Keychain is not configured for this deployment.";- root.appendChild(- dataCard(- "Keychain unavailable",- "Stable key material is required before the core can store keychain records.",- p,- ),- );- return;- }- const people = d.people || [];- const credentials = d.credentials || [];- const grants = d.grants || [];- const asks = d.asks || [];- const activeGrants = grants.filter((g) => g.status === "active" && (!g.expiresAt || g.expiresAt > Date.now()));- const pendingAsks = asks.filter((a) => a.status === "pending");- let filterVal = "";- defaultShell({- stats: [- [people.length, "People"],- [credentials.length, "Credentials"],- [activeGrants.length, "Active grants"],- [pendingAsks.length, "Pending asks"],- ],- search: {- placeholder: "person, service, audience, purpose",- onInput: (v) => {- filterVal = v;- drawLists();- },- },+ governanceUI.keychain.keychain(root, d, {+ defaultShell,+ fmtTime,+ scopeKind,+ openUser: (principal) => go({ view: "user", scope, session: null, principal }),});-- const credById = new Map(credentials.map((c) => [c.id, c]));- const peopleById = new Map(people.map((p) => [p.principalId, p]));- const personName = (id) => keychainPersonLabel(peopleById.get(id) || { principalId: id });- const credName = (id) => {- const c = credById.get(id);- return c ? `${c.service}${c.accountLabel ? " - " + c.accountLabel : ""}` : id;- };-- const lists = document.createElement("div");- lists.className = "list-root";- root.appendChild(lists);- const matches = (parts) => parts.join(" ").toLowerCase().includes(filterVal.trim().toLowerCase());- const drawLists = () => {- lists.textContent = "";- const filteredPeople = people.filter((p) => matches([p.principalId, p.displayName || ""]));- const filteredCreds = credentials.filter((c) =>- matches([- c.ownerId,- personName(c.ownerId),- c.service,- c.kind,- c.envKey || "",- c.accountLabel || "",- c.host || "",- (c.targets || []).join(" "),- ]),- );- const filteredGrants = grants.filter((g) =>- matches([- g.ownerId,- personName(g.ownerId),- g.audienceScopeId,- g.mode,- g.status,- g.purpose,- credName(g.credentialId),- ]),- );- const filteredAsks = asks.filter((a) =>- matches([- a.ownerId,- personName(a.ownerId),- a.requesterId,- personName(a.requesterId),- a.requesterScopeId,- a.status,- a.purpose,- credName(a.credentialId),- ]),- );-- lists.appendChild(- dataCard(- "People",- "Everyone known through sessions, admin grants, keychain records, grants, or asks.",- table(- ["Person", "Keychain", "Active grants", "Pending asks"],- filteredPeople.map((p) => [- nodeCell(stacked(p.displayName || p.principalId, p.displayName ? p.principalId : ""), "mono"),- {- action: {- label: String(p.credentialCount || 0),- title: "Open this person's credentials and grants",- run: () => go({ view: "user", scope, session: null, principal: p.principalId }),- },- },- {- action: {- label: String(p.activeGrantCount || 0),- title: "Open this person's credentials and grants",- run: () => go({ view: "user", scope, session: null, principal: p.principalId }),- },- },- { text: String(p.pendingAskCount || 0), cls: "num" },- ]),- "No people match.",- ),- ),- );-- lists.appendChild(- dataCard(- "Credentials",- "Metadata only. Secret material and encrypted values are never returned to admin.",- table(- ["Owner", "Credential", "Delivery", "Account", "Expiry"],- filteredCreds.map((c) => [- nodeCell(stacked(personName(c.ownerId), c.ownerId), "mono"),- nodeCell(stacked(c.service, c.id), "mono"),- nodeCell(- mutedText(- [c.kind || "unknown", c.envKey, ...(c.targets || []).slice(0, 2)].filter(Boolean).join(" · "),- ),- ),- c.accountLabel || c.host || "-",- { text: keychainExpiry(c.expiresAt), cls: "num" },- ]),- "No keychain credentials match.",- ),- ),- );-- lists.appendChild(- dataCard(- "Grants",- "Purpose-bound keychain grants from an owner to an audience scope.",- table(- ["Owner", "Credential", "Audience", "Mode", "Status", "Purpose"],- filteredGrants.map((g) => {- const [label, kind] = keychainGrantStatus(g);- let labelKind = "";- if (kind === "err") labelKind = "err";- else if (kind === "warn") labelKind = "warn";- let purposeDetail = "";- if (g.usedBy) purposeDetail = "used by " + g.usedBy;- else if (g.askId) purposeDetail = "ask " + g.askId;- return [- nodeCell(stacked(personName(g.ownerId), g.ownerId), "mono"),- nodeCell(stacked(credName(g.credentialId), g.credentialId), "mono"),- nodeCell(stacked(g.audienceScopeId, scopeKind(g.audienceScopeId)), "mono"),- nodeCell(mutedText(g.mode || "unknown")),- nodeCell(mutedText(label, labelKind)),- nodeCell(stacked(g.purpose || "-", purposeDetail)),- ];- }),- "No keychain grants match.",- ),- ),- );-- lists.appendChild(- dataCard(- "Asks",- "Outstanding and resolved cross-conversation consent requests.",- table(- ["Owner", "Requester", "Credential", "Scope", "Status", "Purpose"],- filteredAsks.map((a) => [- nodeCell(stacked(personName(a.ownerId), a.ownerId), "mono"),- nodeCell(stacked(personName(a.requesterId), a.requesterId), "mono"),- nodeCell(stacked(credName(a.credentialId), a.credentialId), "mono"),- nodeCell(stacked(a.requesterScopeId, scopeKind(a.requesterScopeId)), "mono"),- nodeCell(mutedText(a.status || "unknown", a.status === "pending" ? "warn" : "")),- nodeCell(stacked(a.purpose || "-", a.expiresAt ? keychainExpiry(a.expiresAt) : "")),- ]),- "No keychain asks match.",- ),- ),- );- };- drawLists();}function renderUsers(root, d) {- const layout = document.createElement("div");- layout.className = "users-layout";- root.appendChild(layout);- root = layout;- const users = d.users || [];- const grants = d.grants || [];- const externalUsers = d.externalUsers || [];- let filterVal = "";- let kcCounts = null;- void api("GET", "/api/keychain").then((r) => {- if (!r.ok || r.data?.enabled === false) return;- kcCounts = new Map(- (r.data?.people || []).map((p) => [p.principalId, [p.credentialCount || 0, p.activeGrantCount || 0]]),- );- drawLists();- });- defaultShell({- stats: [- [users.length, "Users"],- [grants.length, "Admins"],- ],- search: {- placeholder: "principal, role, or scope",- onInput: (v) => {- filterVal = v;- drawLists();- },- },- });-- const form = document.createElement("div");- form.className = "grant-form";- const mkField = (cls, labelText, control) => {- const f = document.createElement("div");- f.className = "f" + (cls ? " " + cls : "");- const l = document.createElement("label");- l.textContent = labelText;- control.id = "users-" + labelText.toLowerCase().replaceAll(" ", "-");- l.htmlFor = control.id;- f.append(l, control);- return f;- };- const pInput = document.createElement("input");- pInput.type = "text";- pInput.placeholder = "[email protected] or U07ABCD";- pInput.spellcheck = false;- pInput.autocapitalize = "none";- const grantBtn = document.createElement("button");- grantBtn.className = "primary";- grantBtn.type = "button";- grantBtn.textContent = "Grant";- grantBtn.onclick = async () => {- const principalId = pInput.value.trim();- if (!principalId) return setStatus("st-users", "Principal id required.", "err");- const r = await api("POST", "/api/grants", { principalId, role: "org_admin", scopeId: "org:" + orgId });- if (r.ok) {- pInput.value = "";- renderData();- } else- setStatus(- "st-users",- r.status === 403 ? "Only an org admin may grant." : r.data?.message || "Grant failed.",- "err",- );- };- form.append(mkField("grow", "Email or principal ID", pInput), grantBtn);- const formCard = dataCard(- "Grant org admin",- "Enter their email or principal ID. They do not need to appear in the Users table first. Org admins only.",- form,- );- const st = document.createElement("p");- st.className = "status";- st.id = "st-users";- st.style.margin = "10px 0 0";- formCard.querySelector(".body").appendChild(st);- formCard.classList.add("users-setting");- root.appendChild(formCard);-- const impForm = document.createElement("div");- impForm.className = "grant-form";- const impInput = document.createElement("input");- impInput.type = "text";- impInput.placeholder = "principal id or name (e.g. [email protected])";- impInput.spellcheck = false;- impInput.autocapitalize = "none";- impInput.setAttribute("list", "imp-suggest");- const impDatalist = document.createElement("datalist");- impDatalist.id = "imp-suggest";- const impBtn = document.createElement("button");- impBtn.className = "primary";- impBtn.type = "button";- impBtn.textContent = "Open web UI as ↗";- let impTimer = null,- impSeq = 0;-- const dirMembers = async (q) => {- const r = await api("GET", "/api/directory?q=" + encodeURIComponent(q));- if (!r.ok) throw new Error(r.data?.message || "directory lookup failed (" + r.status + ")");- return r.data?.members || [];- };- impInput.addEventListener("input", () => {- const q = impInput.value.trim();- clearTimeout(impTimer);- if (q.length < 2) return;- impTimer = setTimeout(async () => {- const seq = ++impSeq;- let members;- try {- members = await dirMembers(q);- } catch {- return;- }- if (seq !== impSeq) return;- impDatalist.textContent = "";- members.forEach((m) => {- const opt = document.createElement("option");- opt.value = m.displayName || m.principalId;- opt.label = m.principalId;- impDatalist.appendChild(opt);- });- }, 200);+ governanceUI.users.users(root, d, {+ api,+ defaultShell,+ fmtTime,+ relTime,+ labelRole,+ confirm,+ openWebUiAs,+ orgScope: "org:" + orgId,+ clearCache: () => dataCache.clear(),+ openUser: (principal) => go({ view: "user", scope, session: null, principal }),});-- impBtn.onclick = async () => {- const v = impInput.value.trim();- if (!v) return setStatus("st-imp", "Principal id or name required.", "err");- setStatus("st-imp", "");- impBtn.disabled = true;- try {- const members = await dirMembers(v);- if (members.length > 1)- return setStatus("st-imp", "Matches several people. Pick one from the suggestions.", "err");- await openWebUiAs(members[0]?.principalId ?? v);- } catch (e) {- setStatus("st-imp", "Couldn't resolve that (" + (e?.message || "directory lookup failed") + ").", "err");- } finally {- impBtn.disabled = false;- }- };- impForm.append(mkField("grow", "Principal id or name", impInput), impBtn);- const impCard = dataCard(- "Impersonate a user",- "Open the assistant Web UI as any principal, for support, debugging, or onboarding tests. Time-boxed and audited.",- impForm,- );- const impSt = document.createElement("p");- impSt.className = "status";- impSt.id = "st-imp";- impSt.style.margin = "10px 0 0";- impCard.querySelector(".body").append(impDatalist, impSt);- impCard.classList.add("users-setting");- root.appendChild(impCard);-- const inviteEmail = d.inviteEmail || {};- const emailInput = document.createElement("input");- emailInput.type = "email";- emailInput.placeholder = "[email protected]";- emailInput.spellcheck = false;- emailInput.autocapitalize = "none";- const roleSelect = document.createElement("select");- roleSelect.append(new Option("Member", "member"), new Option("Org admin", "org_admin"));- const isoDay = (ms) => new Date(ms).toISOString().slice(0, 10);- const expiresInput = document.createElement("input");- expiresInput.type = "date";- expiresInput.min = isoDay(Date.now());- expiresInput.value = isoDay(Date.now() + 30 * 86400000);- const inviteBtn = document.createElement("button");- inviteBtn.className = "primary";- inviteBtn.type = "button";- inviteBtn.textContent = inviteEmail.configured === false ? "Add user" : "Send invite";- inviteBtn.onclick = async () => {- const email = emailInput.value.trim();- if (!email) return setStatus("st-external", "Email required.", "err");- if (!expiresInput.value) return setStatus("st-external", "Expiry date required.", "err");- inviteBtn.disabled = true;- const r = await api("POST", "/api/external-users", {- email,- role: roleSelect.value,- expiresAt: expiresInput.value,- });- inviteBtn.disabled = false;- if (!r.ok)- return setStatus(- "st-external",- r.status === 403 ? "Only an org admin may invite." : r.data?.message || "Invite failed.",- "err",- );- const member = r.data.member;- const expires = " (expires " + fmtTime(member.expiresAt) + ")";- await renderData();- setStatus(- "st-external",- r.data.emailSent- ? "Invite sent to " + member.email + expires- : r.data.emailProblem- ? "Added " +- member.email +- ", but no invitation email was sent: " +- r.data.emailProblem +- "." +- (r.data.signInUrl ? " Portal: " + r.data.signInUrl + ". A working sign-in method is required." : "")- : "Updated " + member.email + " — " + labelRole(member.role) + expires,- r.data.emailSent || !r.data.emailProblem ? "ok" : "dirty",- true,- );- };- const inviteForm = document.createElement("div");- inviteForm.className = "grant-form";- inviteForm.append(- mkField("grow", "Email", emailInput),- mkField("", "Role", roleSelect),- mkField("", "Expires", expiresInput),- inviteBtn,- );- const inviteNote = document.createElement("p");- inviteNote.className = inviteEmail.configured === false ? "hint flag-warn" : "hint";- const signInHint = inviteEmail.signInUrl ? " Sign-in link to share: " + inviteEmail.signInUrl : "";- inviteNote.textContent =- inviteEmail.configured === false- ? (inviteEmail.problem || "Invitation emails are not configured") +- ". Users can still be added, but need a configured sign-in method before they can log in." +- signInHint- : "Invitation emails go out through Resend — core needs RESEND_API_KEY and AUTH_EMAIL_FROM. Without them users can still be added, but need a configured sign-in method before they can log in.";- const invite = document.createElement("div");- invite.className = "hidden";- invite.style.margin = "0 0 14px";- invite.append(inviteForm, inviteNote);- const addBtn = document.createElement("button");- addBtn.type = "button";- addBtn.className = "rowbtn";- addBtn.textContent = "Invite external user";- addBtn.title = "Invite external user";- addBtn.setAttribute("aria-label", "Invite external user");- addBtn.setAttribute("aria-expanded", "false");- addBtn.onclick = () => {- const open = !invite.classList.toggle("hidden");- addBtn.setAttribute("aria-expanded", String(open));- if (open) emailInput.focus();- };- const externalSt = document.createElement("p");- externalSt.className = "status";- externalSt.id = "st-external";- externalSt.style.margin = "10px 0 0";-- const lists = document.createElement("div");- lists.className = "list-root";- root.prepend(lists);- const orgAdminCount = grants.filter((g) => g.role === "org_admin").length;- const matches = (parts) => parts.join(" ").toLowerCase().includes(filterVal.trim().toLowerCase());- const drawLists = () => {- lists.textContent = "";- const filteredGrants = grants.filter((g) => matches([g.principalId, g.role, g.scopeId, g.grantedBy || ""]));- const filteredUsers = users.filter((u) =>- matches([u.principalId, u.admin?.role || "", u.admin?.scopeId || "member"]),- );- const filteredExternal = externalUsers.filter((m) => matches([m.email, m.role, m.invitedBy || "", m.status]));-- const admins = actionTable(- ["Principal", "Role", "Scope", "Granted by", ""],- filteredGrants,- (g) => [- { text: g.principalId, cls: "mono" },- nodeCell(mutedText(g.role ? labelRole(g.role) : "member")),- nodeCell(stacked(g.scopeId, scopeKind(g.scopeId)), "mono"),- g.grantedBy || "-",- {- action: {- label: "Revoke",- danger: true,- disabled: orgAdminCount <= 1 && g.role === "org_admin",- title: orgAdminCount <= 1 ? "The last org admin cannot be revoked." : "",- run: () => revokeGrant(g),- },- },- ],- "No admins match.",- );- lists.appendChild(- dataCard("Admins", "Who can govern this org. Revoking removes their admin rights immediately.", admins),- );-- const kcFor = (id) => (kcCounts && kcCounts.get(id)) || null;- const roster = openableTable(- ["Principal", "Role", "Last seen", "Sessions", "Turns", "Credentials", "Grants", "", ""],- filteredUsers,- (u) => [- { text: u.principalId, cls: "mono" },- nodeCell(mutedText(u.admin?.isAdmin ? labelRole(u.admin.role) : "member")),- u.lastSeenAt ? timeCell(u.lastSeenAt) : { text: "-", cls: "num" },- { text: String(u.sessionCount), cls: "num" },- { text: String(u.turnCount), cls: "num" },- { text: kcFor(u.principalId) ? String(kcFor(u.principalId)[0]) : "-", cls: "num" },- { text: kcFor(u.principalId) ? String(kcFor(u.principalId)[1]) : "-", cls: "num" },- {- action: {- label: "Impersonate ↗",- run: (ev) => {- ev?.stopPropagation?.();- openWebUiAs(u.principalId);- },- },- },- u.admin?.isAdmin- ? { text: "" }- : {- action: {- label: "Make admin",- run: (ev) => {- ev?.stopPropagation?.();- pInput.value = u.principalId;- pInput.focus();- form.scrollIntoView({ block: "center" });- },- },- },- ],- (u) => go({ view: "user", scope, session: null, principal: u.principalId }),- "No users match.",- );- const usersCard = dataCard(- "Users",- "Everyone who has used the agent — click a row for their activity, artifacts, and config.",- roster,- );- lists.prepend(usersCard);-- const external = actionTable(- ["Email", "Role", "Expires", "Invited by", "Status", ""],- filteredExternal,- (m) => [- { text: m.email, cls: "mono" },- nodeCell(mutedText(labelRole(m.role))),- (m.status === "active" ? "Ends " : "Ended ") + isoDay(m.expiresAt) + " (UTC)",- m.invitedBy || "-",- { badge: m.status === "active" ? "Active" : "Expired", kind: m.status === "active" ? "ok" : "warn" },- m.status === "active"- ? { action: { label: "Revoke", danger: true, run: () => revokeExternalUser(m) } }- : Date.now() - m.expiresAt >= 86400000- ? { action: { label: "Remove", run: () => revokeExternalUser(m) } }- : "",- ],- externalUsers.length- ? "No external users match."- : "No external users. Use Invite external user to invite an outside collaborator.",- );- const externalCard = dataCard(- "External users",- "Outside collaborators invited by email until an expiry date. Org members do not need an external invite.",- external,- );- externalCard.classList.add("users-roster");- externalCard.querySelector(".head").appendChild(addBtn);- externalCard.querySelector(".body").prepend(invite);- externalCard.querySelector(".body").appendChild(externalSt);- lists.appendChild(externalCard);- };- drawLists();}const fmtBytes = (n) => {@@ -16812,330 +10587,71 @@++dataReq;const root = $("view-data");root.textContent = "";- if (!scopeDir) {- pageShell({ title: VIEW_TITLE.history });- const loading = document.createElement("div");- loading.className = "loadingline";- loading.textContent = scopeDirNote;- root.appendChild(loading);- return;- }- const rows = scopeRows();- const activeRows = rows.filter((s) => (s.sessions || 0) > 0 || (s.backgroundSessions || 0) > 0);- const quietRows = rows.filter((s) => !(s.sessions || 0) && !(s.backgroundSessions || 0));-- if (scopeSort === "human") {- activeRows.sort(- (a, b) =>- (b.lastConversationActivity || 0) - (a.lastConversationActivity || 0) ||- (b.sessions || 0) - (a.sessions || 0) ||- (b.lastActivity || 0) - (a.lastActivity || 0) ||- a.scopeId.localeCompare(b.scopeId),- );- }- const sortControl = document.createElement("div");- sortControl.className = "shell-sort";- const sortLabel = document.createElement("span");- sortLabel.className = "shell-sort-label";- sortLabel.textContent = "Sort:";- const seg = twoWayToggle({- label: "Sort sessions",- options: [- { value: "human", label: "Human activity" },- { value: "all", label: "All activity" },- ],- value: scopeSort,- onChange: (value) => {- scopeSort = value;- renderScopeIndex();- $("shellbar").querySelector(".two-way-toggle input:checked")?.focus({ preventScroll: true });- },- });- sortControl.append(sortLabel, seg);- pageShell({+ governanceUI.history.scopeIndex(root, {+ ready: !!scopeDir,+ note: scopeDirNote,title: VIEW_TITLE.history,- count: plural(activeRows.length, "active scope"),- actions: [sortControl],+ rows: scopeDir ? scopeRows() : [],+ sort: scopeSort,+ pageShell,+ plural,+ environments: environmentDir,+ historyKind,+ shortName,+ selectScope,+ stateToUrl,+ relTime,+ sessionCountsLabel,+ scopeTitle,+ sortControl: () =>+ twoWayToggle({+ label: "Sort sessions",+ options: [+ { value: "human", label: "Human activity" },+ { value: "all", label: "All activity" },+ ],+ value: scopeSort,+ onChange: (value) => {+ scopeSort = value;+ renderScopeIndex();+ $("shellbar").querySelector(".two-way-toggle input:checked")?.focus({ preventScroll: true });+ },+ }),});- const activityTime = (s) => (scopeSort === "human" ? s.lastConversationActivity || 0 : s.lastActivity || 0);- const attachedScopesLabel = (attached) => {- if (!attached.length) return "no scopes attached";- const names = attached.map((id) => shortName(id));- const shown = names.slice(0, 4).join(", ");- const extra = names.length - 4;- return extra > 0 ? `${shown} +${plural(extra, "more scope")}` : shown;- };- if (environmentDir.length) {- const environments = denseList(- environmentDir,- (environment) => {- const attached = environment.attachedScopes || [];- const preview = document.createElement("span");- preview.textContent = attachedScopesLabel(attached);- if (attached.length) preview.title = attached.map((id) => shortName(id)).join(", ");- return {- name: environment.name || shortName(environment.id),- preview,- href: stateToUrl({ view: "history", scope: environment.id, historyKind }),- };- },- (environment) => selectScope(environment.id),- "No named environments.",- );- root.appendChild(- dataCard("Named environments", "Named computers and working memory that scopes can share.", environments),- );- }- const t = denseList(- activeRows,- (s) => {- const preview = document.createElement("span");- const counts = document.createElement("span");- counts.className = "dense-tag";- counts.textContent = sessionCountsLabel(s.sessions || 0, s.backgroundSessions || 0);- preview.appendChild(counts);- if (s.environmentAttachment) {- const env = document.createElement("span");- env.className = "dense-tag";- env.textContent =- "env: " + (s.environmentAttachment.environmentName || shortName(s.environmentAttachment.environmentId));- env.title = "This scope is attached to a named environment.";- preview.appendChild(env);- }- if (s.lastMessage) preview.appendChild(document.createTextNode(s.lastMessage));- return {- name: shortName(s.scopeId),- preview,- time: activityTime(s) ? relTime(activityTime(s)) : "Never",- href: stateToUrl({ view: "history", scope: s.scopeId, historyKind }),- };- },- (s) => selectScope(s.scopeId),- rows.length ? "No conversations yet." : "No scopes yet. Nobody has talked to the agent.",- );- root.appendChild(dataCard("Conversations by person or channel", "", t));- if (quietRows.length) {- const quiet = document.createElement("details");- quiet.className = "history-quiet";- const summary = document.createElement("summary");- summary.textContent = `${quietRows.length} known scope${quietRows.length === 1 ? "" : "s"} without conversations`;- const chips = document.createElement("div");- chips.className = "history-empty-scopes";- quietRows.forEach((s) => {- const button = document.createElement("button");- button.type = "button";- button.className = "history-empty-scope";- button.textContent = scopeTitle(s.scopeId);- button.onclick = () => selectScope(s.scopeId);- chips.appendChild(button);- });- quiet.append(summary, chips);- root.appendChild(quiet);- }}function renderHistory(root, d) {- const rawSessions = d.sessions || [];- const kindSessions = rawSessions.filter((s) => historyKindMatches(s, historyKind));- const sessions = kindSessions;- const countsByCategory = d.totalByCategory || {};- const totalByType = d.totalByType || d.byType || {};- const countForMode = (kind) => {- if (kind === "conversation") return countsByCategory.conversation ?? 0;-- if (kind === "cron")- return d.distinctCrons ?? totalByType.cron ?? totalByType.cron_wake ?? totalByType.cron_monologue ?? 0;- if (kind === "background") {- const cronN = totalByType.cron ?? totalByType.cron_wake ?? totalByType.cron_monologue ?? 0;- return Math.max(0, (countsByCategory.background ?? 0) - cronN);- }- return d.total ?? rawSessions.length;- };- const cronSel = historyKind === "cron" ? urlToState().cron : null;- const total = (cronSel ? d.total : countForMode(historyKind)) || sessions.length;- const limit = d.limit || HISTORY_PAGE_SIZE;- const offset = d.offset || 0;- const actualPage = Math.floor(offset / limit) + 1;- if (actualPage !== page) {- page = actualPage;- const st = { view: "history", scope, session: null, page, historyKind, cron: cronSel };- history.replaceState(st, "", stateToUrl(st));- }- const typeLabel = (k) => {- if (k === "dm") return "DM";- if (k === "cron_monologue" || k === "cron_wake" || k === "cron") return "Cron";- return titleCase(String(k).replaceAll("_", " "));- };- const modeLabel = historyModeLabel(historyKind);- const modeTab = (value) => ({- label: KIND_LABEL[value],- count: countForMode(value) || 0,- active: historyKind === value,- onClick: () => go({ view: "history", scope, session: null, page: 1, historyKind: value }),- });- const tabs = [modeTab("conversation"), modeTab("cron")];- if (countForMode("background") > 0 || historyKind === "background") tabs.push(modeTab("background"));- if (cronSel) {- pageShell({- back: {- label: "← Crons",- onClick: () => go({ view: "history", scope, session: null, page: 1, historyKind }),- },- title: cronName(d.cron?.cron || sessions[0]?.origin?.cron, true),- context: scopeKind(scope) !== "org" ? shortName(scope) : "",- count: plural(total, "fire"),- });- } else {- pageShell({- back:- scopeKind(scope) !== "org"- ? {- label: "← Sessions",- onClick: () => go({ view: "history", scope: "org:" + orgId, session: null, page: 1, historyKind }),- }- : undefined,- title: scopeKind(scope) !== "org" ? shortName(scope) : VIEW_TITLE.history,- tabs,- });- }- const environmentEntry = (environmentDir || []).find((environment) => environment.id === scope);- if (environmentEntry && !cronSel) {- const attached = environmentEntry.attachedScopes || [];- const chips = document.createElement("div");- chips.className = "history-empty-scopes";- attached.forEach((id) => {- const button = document.createElement("button");- button.type = "button";- button.className = "history-empty-scope";- button.textContent = shortName(id);- button.title = id;- button.onclick = () => selectScope(id);- chips.appendChild(button);- });- if (!attached.length) {- const none = document.createElement("p");- none.className = "empty";- none.textContent = "No scopes attached.";- chips.appendChild(none);- }- root.appendChild(- dataCard(- "Attached scopes",- plural(attached.length, "scope") + " share this environment's computer and working memory.",- chips,- ),- );- }- const cronDeliveryChip = (delivered, label) => {- if (!delivered) return null;- const chip = document.createElement("span");- chip.className = "delivery-chip";- chip.textContent = label || "\u2713 delivered";- return chip;- };- if (historyKind === "cron" && !cronSel) {- const crons = d.crons || [];- const t = denseList(- crons,- (c) => {- const preview = document.createElement("span");- preview.appendChild(- document.createTextNode(- plural(c.sessions || 0, "fire") +- (typeof c.deliveredRuns === "number"- ? ` \u00b7 ${Number(c.deliveredRuns).toLocaleString()} delivered`- : "") +- " \u00b7 first fired " +- fmtHistoryCreated(c.createdAt, c.lastActivity),- ),- );- return {- name: cronName(c.origin?.cron, true),- preview,- time: c.lastActivity ? relTime(c.lastActivity) : "\u2014",- cls: typeof c.deliveredRuns === "number" && !c.deliveredRuns ? "history-silent" : "",- href: stateToUrl({ view: "history", scope, historyKind, cron: c.cronId }),- };- },- (c) => go({ view: "history", scope, session: null, page: 1, historyKind, cron: c.cronId }),- "No crons in this scope.",- );- root.appendChild(bareDataCard(t));- return;- }- const t = denseList(- sessions,- (s) => {- const originCron = s.origin?.kind === "cron" ? s.origin.cron : null;- const isBackground = s.category === "background";- const background = isBackground && !cronSel;- let name = s.firstMessage || s.lastMessage || "(no messages yet)";- let previewText = "";- if (background) {- name = originCron ? cronName(originCron, true) : s.origin?.label || typeLabel(s.kind || s.type);- previewText = s.result || s.lastMessage || s.firstMessage || "";- } else if (isBackground && s.result) {- name = s.result;- if (s.lastMessage && s.lastMessage !== s.result) previewText = s.lastMessage;- } else if (s.lastMessage && s.lastMessage !== name) {- previewText = s.lastMessage;- }- const preview = document.createElement("span");- if (isBackground && typeof s.delivered === "number") {- const autoChip = cronDeliveryChip(- s.delivered > 0,- s.delivered > 1 ? `\u2713 delivered \u00d7${s.delivered}` : undefined,- );- if (autoChip) preview.appendChild(autoChip);- }- if (previewText) preview.appendChild(document.createTextNode(previewText));- return {- name,- preview,- time: s.lastActivity ? relTime(s.lastActivity) : "\u2014",- cls: isBackground && typeof s.delivered === "number" && !s.delivered ? "history-silent" : "",- href: stateToUrl({ view: "history", scope, session: s.id }),- };+ governanceUI.history.history(root, d, {+ historyKind,+ historyKindMatches,+ cron: urlToState().cron,+ pageSize: HISTORY_PAGE_SIZE,+ scope,+ orgScope: "org:" + orgId,+ environments: environmentDir,+ title: VIEW_TITLE.history,+ kindLabels: KIND_LABEL,+ historyModeLabel,+ go,+ pageShell,+ cronName,+ scopeKind,+ shortName,+ plural,+ selectScope,+ fmtHistoryCreated,+ relTime,+ stateToUrl,+ titleCase,+ errorStripBox,+ adminErrorCount,+ adminErrors,+ correctPage: (next, cron) => {+ if (next === page) return;+ page = next;+ const st = { view: "history", scope, session: null, page, historyKind, cron };+ history.replaceState(st, "", stateToUrl(st));},- (s) => go({ view: "history", scope, session: s.id, historyKind }),- `No ${modeLabel.toLowerCase()} in this scope.`,- );- root.appendChild(bareDataCard(t));- root.appendChild(- pager(total, limit, offset, (n) =>- go({ view: "history", scope, session: null, page: n, historyKind, cron: cronSel }),- ),- );- if (scopeKind(scope) !== "org" && !cronSel) {- const errNote = document.createElement("div");- root.appendChild(errNote);- void (async () => {- const q = "scope=" + encodeURIComponent(scope);- const [total, errs] = await Promise.all([adminErrorCount(q), adminErrors(q)]);- if (!total || !errs.length || !errNote.isConnected) return;- const note = document.createElement("div");- note.className = "statline";- const toggle = document.createElement("a");- toggle.href = "#";- toggle.textContent = plural(total, "error") + " logged in this scope";- note.appendChild(toggle);- errNote.appendChild(note);- let box = null;- toggle.onclick = (ev) => {- ev.preventDefault();- if (box) {- box.remove();- box = null;- return;- }- box = errorStripBox(errs, "Most recent errors", 20, (e) => {- if (!e.sessionId) return null;- const st = { view: "history", scope, session: e.sessionId, historyKind };- return { href: stateToUrl(st), go: () => go(st) };- });- errNote.appendChild(box);- };- })();- }+ });}function pager(total, limit, offset, onGo) {if (total <= limit) return document.createDocumentFragment();@@ -17159,500 +10675,39 @@return wrap;}- const GRANT_STATUS_ORDER = { active: 0, used: 1, expired: 2, revoked: 3 };- function grantStatusDot(status) {- const span = document.createElement("span");- span.className = "kc-dot kc-dot-" + (status || "unknown");- return span;- }- function grantStatusCell(status) {- const wrap = document.createElement("span");- wrap.appendChild(grantStatusDot(status));- wrap.appendChild(document.createTextNode(status || "unknown"));- return wrap;- }- async function userKeychainCards(principalId) {- const holder = document.createElement("div");- const r = await api("GET", "/api/keychain");- if (!r.ok || r.data?.enabled === false) return holder;- const d = r.data || {};- const mine = (list) => (list || []).filter((x) => x.ownerId === principalId);- const creds = mine(d.credentials);- const grants = mine(d.grants);- const credById = new Map((d.credentials || []).map((c) => [c.id, c]));- const credName = (id) => {- const c = credById.get(id);- return c ? c.service + (c.accountLabel ? " - " + c.accountLabel : "") : id;- };-- const credRows = creds- .slice()- .sort((a, b) => (b.updatedAt || b.createdAt || 0) - (a.updatedAt || a.createdAt || 0))- .map((c) => [- nodeCell(stacked(c.service, c.id), "mono"),- nodeCell(mutedText(c.kind || "unknown")),- nodeCell(mutedText(c.origin || "-")),- c.accountLabel || c.envKey || c.host || "-",- { text: c.createdAt ? fmtTime(c.createdAt) : "-", cls: "num" },- ]);- holder.appendChild(- dataCard(- "Credentials (" + creds.length + ")",- "Logins this person registered in their keychain. Metadata only — secrets are never returned.",- table(["Service", "Kind", "Origin", "Account", "Added"], credRows, "No credentials registered."),- ),- );-- let grantSort = "default";- const grantsBody = document.createElement("div");- const grantTs = (g) => g.usedAt || g.revokedAt || g.createdAt || 0;- const drawGrants = () => {- grantsBody.textContent = "";- const sorted = grants.slice().sort((a, b) => {- if (grantSort === "mode") return String(a.mode).localeCompare(String(b.mode)) || grantTs(b) - grantTs(a);- if (grantSort === "status")- return String(a.status).localeCompare(String(b.status)) || grantTs(b) - grantTs(a);- return (GRANT_STATUS_ORDER[a.status] ?? 9) - (GRANT_STATUS_ORDER[b.status] ?? 9) || grantTs(b) - grantTs(a);- });- const sortBar = document.createElement("p");- sortBar.className = "kc-sortbar";- sortBar.appendChild(document.createTextNode("Sort: "));- [- ["default", "status group"],- ["mode", "mode"],- ["status", "status A-Z"],- ].forEach(([key, label], i) => {- if (i) sortBar.appendChild(document.createTextNode(" · "));- const b = document.createElement("button");- b.type = "button";- b.className = "link" + (grantSort === key ? " kc-sort-active" : "");- b.textContent = label;- b.onclick = () => {- grantSort = key;- drawGrants();- };- sortBar.appendChild(b);- });- grantsBody.appendChild(sortBar);- grantsBody.appendChild(- table(- ["Credential", "Mode", "Status", "Audience", "Purpose", "Uses"],- sorted.map((g) => [- nodeCell(stacked(credName(g.credentialId), g.credentialId), "mono"),- nodeCell(mutedText(g.mode || "unknown")),- nodeCell(grantStatusCell(g.status)),- nodeCell(stacked(g.audienceScopeId, scopeKind(g.audienceScopeId)), "mono"),- nodeCell(stacked(g.purpose || "-", g.usedBy ? "used by " + g.usedBy : "")),- {- action: {- label: "View usage ›",- title: "Show " + String(g.useCount ?? 0) + " recorded uses of this grant",- run: () => showGrantUsage(grantsBody, g, credName(g.credentialId), drawGrants),- },- },- ]),- "No grants.",- ),- );- };- drawGrants();- holder.appendChild(- dataCard(- "Grants (" + grants.length + ")",- "Purpose-bound grants this person issued. Every use — standing or one-time — is audited.",- grantsBody,- ),- );- return holder;- }- async function showGrantUsage(container, grant, credLabel, redraw) {- container.textContent = "";- const back = document.createElement("p");- back.className = "kc-sortbar";- const b = document.createElement("button");- b.type = "button";- b.className = "link";- b.textContent = "‹ Back to grants";- container.appendChild(back);- back.appendChild(b);- const info = document.createElement("p");- info.className = "hint";- info.textContent =- credLabel + " · " + (grant.mode || "?") + " · " + (grant.status || "?") + " · grant " + grant.id;- container.appendChild(info);- const loading = document.createElement("p");- loading.className = "empty";- loading.textContent = "Loading usage…";- container.appendChild(loading);- const r = await api(- "GET",- "/api/audit?scope=org:" +- encodeURIComponent(orgId) +- "&action=keychain.materialize&resource=" +- encodeURIComponent("grant " + grant.id) +- "&limit=2000",- );- loading.remove();- const events = (r.ok && r.data?.events) || [];- container.appendChild(- table(- ["When", "Used by", "Scope"],- events.map((e) => [- { text: fmtTime(e.ts), cls: "num" },- nodeCell(stacked(e.principalId, "")),- nodeCell(mutedText(e.scopeLabel || "-")),- ]),- "No recorded uses of this grant.",- ),- );- b.onclick = redraw;- }+ let userDetailRequest = 0;async function showUserDetail(principalId) {+ const request = ++userDetailRequest;const root = $("view-data");root.textContent = "";- pageShell({ back: { label: "← Users", onClick: () => history.back() }, title: principalId || "User" });- const detail = document.createElement("div");- detail.className = "detail";- detail.textContent = "Loading…";- root.appendChild(detail);- const r = await api("GET", "/api/users/" + encodeURIComponent(principalId));- if (!r.ok) {- detail.textContent =- r.status === 403 ? "You don't have admin access." : r.data?.message || `Failed to load user (${r.status}).`;- return;- }- detail.textContent = "";- const d = r.data || {};-- pageShell({- back: { label: "← Users", onClick: () => history.back() },- title: d.displayName || d.principalId || principalId,- context: [d.admin?.isAdmin ? labelRole(d.admin.role) : "member", d.scopeId || ""].filter(Boolean).join(" · "),+ return governanceUI.userDetail.detail(root, principalId, {+ api,+ pageShell,+ labelRole,+ fmtTime,+ scopeKind,+ plural,+ stateToUrl,+ go,+ confirm,+ orgId,+ webUiAsButton,+ current: (principal) =>+ request === userDetailRequest && view === "user" && urlToState().principal === principal,+ reload: showUserDetail,});- const userActions = document.createElement("div");- userActions.style.margin = "0 0 14px";- userActions.appendChild(webUiAsButton(d.principalId || principalId));- detail.appendChild(userActions);-- const stats = d.stats || {};- detail.appendChild(- kpis([- [String(stats.sessions ?? 0), "Conversations"],- [String(stats.turns ?? 0), "Turns"],- [stats.firstSeenAt ? fmtTime(stats.firstSeenAt) : "Never", "First seen"],- [stats.lastSeenAt ? fmtTime(stats.lastSeenAt) : "Never", "Last seen"],- ]),- );-- const convs = d.conversations || [];- const convTable = openableTable(- ["Conversation", "Scope", "Volume", "Last activity"],- convs,- (s) => {- const latest = s.lastMessage || s.firstMessage || "(no messages yet)";- const started =- s.firstMessage && s.firstMessage !== latest- ? "> " + s.firstMessage- : "created " + fmtHistoryCreated(s.createdAt, s.lastActivity);- return [- nodeCell(stacked(latest, started, "history-conversation"), "history-conversation-cell"),- historyScopeCell(s.scopeId),- nodeCell(- stacked(plural(s.userTurns || 0, "turn"), plural(s.messages || 0, "entry", "entries")),- "num history-volume-cell",- ),- nodeCell(- stacked(- fmtHistoryTime(s.lastActivity),- "created " + fmtHistoryCreated(s.createdAt, s.lastActivity),- "history-activity",- ),- "history-activity-cell",- ),- ];- },- (s) => go({ view: "history", scope: s.scopeId, session: s.id }),- "No conversations yet.",- { className: "history-table", cols: ["52%", "18%", "10%", "20%"] },- );- detail.appendChild(- dataCard(- "Recent conversations",- "Every conversation this person took part in. Click a row to read the transcript.",- convTable,- ),- );-- detail.appendChild(await userKeychainCards(d.principalId || principalId));-- const files = d.files || [];- const fileRows = files.map((f) => [- nodeCell(stacked(f.name || fileName(f.path), f.path || "")),- { text: fileKind(f.path || f.name), cls: "mono" },- { text: fmtBytes(f.size || 0), cls: "num" },- nodeCell(mutedText(f.direction === "out" ? "agent" : "upload")),- { text: f.createdAt ? fmtTime(f.createdAt) : "Never", cls: "num" },- f.openable- ? { action: { label: "Download", run: () => downloadFile({ ...f, openable: true }) } }- : { text: "n/a", cls: "num" },- ]);- detail.appendChild(- dataCard(- "Files",- "Documents in this person's personal workspace, saved by the agent or uploaded.",- table(["Name", "Kind", "Size", "Source", "Created", ""], fileRows, "No files in their personal workspace."),- ),- );-- const deployments = d.deployments || [];- const depRows = deployments.map((dep) => [- nodeCell(- deploymentHref(dep)- ? linkedStacked(deploymentHref(dep), dep.name || dep.id, dep.name ? dep.id : "")- : stacked(dep.name || dep.id, dep.name ? dep.id : ""),- ),- nodeCell(statusBadge(dep.status)),- nodeCell(- stacked(dep.currentVersion || "None", (dep.versions || 0) + " version" + (dep.versions === 1 ? "" : "s")),- ),- { text: dep.lastAccessAt ? fmtTime(dep.lastAccessAt) : "Never", cls: "num" },- ]);- detail.appendChild(- dataCard(- "Apps",- "Apps this person published from their personal workspace.",- table(["App", "Status", "Version", "Last access"], depRows, "No apps."),- ),- );-- const crons = d.crons || [];- const cronRows = crons.map((c) => [- nodeCell(- stacked(- c.title || c.action || c.message || "(empty)",- c.title ? c.action || c.message || shortId(c.id) : shortId(c.id),- ),- ),- { text: fmtSchedule(c.schedule), cls: "num" },- { text: c.lastFiredAt ? fmtTime(c.lastFiredAt) : "never", cls: "num" },- nodeCell(mutedText(cronStatusText(c))),- ]);- detail.appendChild(- dataCard(- "Crons",- "Scheduled prompts and reminders this person owns.",- table(["What", "Schedule", "Last fired", "Status"], cronRows, "No crons."),- ),- );-- const cfg = d.config || null;- const cfgWrap = document.createElement("div");- if (!cfg)- cfgWrap.appendChild(- Object.assign(document.createElement("p"), {- className: "empty",- textContent: "Config store not available.",- }),- );- else {- const ruleN = (cfg.commandPolicy?.rules || []).length;- const allowN = (cfg.egress?.allowedHosts || []).length;- const denyN = (cfg.egress?.deniedHosts || []).length;- cfgWrap.appendChild(- table(- ["Setting", "Value"],- [- ["Custom soul", { node: mutedText(cfg.hasSoul ? "set · v" + (cfg.soulVersion || 1) : "default") }],- [- "Command policy",- cfg.commandPolicy- ? ruleN + " rule" + (ruleN === 1 ? "" : "s") + " · " + (cfg.commandPolicy.mode || "denylist")- : "default",- ],- ["Security posture", cfg.securityPosture || "auto"],- ["Sharing posture", cfg.sharingPosture || "isolated"],- ["Egress overrides", allowN || denyN ? allowN + " allow · " + denyN + " deny" : "none"],- ["Base model", cfg.baseModel || "org default"],- ["Connectors linked", String((cfg.connectors || []).length)],- ],- "No config.",- ),- );- }- const OB_KIND = { completed: "ok", dismissed: "muted", pending: "warn", not_started: "info" };- const OB_LABEL = {- completed: "completed",- dismissed: "dismissed",- pending: "pending",- not_started: "not started",- };- const obWrap = document.createElement("div");- const obStatusRow = document.createElement("div");- obStatusRow.className = "obstatus";- const obHint = document.createElement("p");- obHint.className = "hint";- function paintOb(status) {- obStatusRow.textContent = "Current status: ";- obStatusRow.appendChild(badge(OB_LABEL[status] || status, OB_KIND[status] || "muted"));- }- async function applyOb(status) {- obButtons.forEach((b) => (b.disabled = true));- obHint.textContent = "Saving…";- try {- const r = await api("PUT", "/api/users/" + encodeURIComponent(principalId) + "/onboarding", { status });- if (!r.ok) {- obHint.textContent = r.data?.message || "Failed (" + r.status + ").";- return;- }- paintOb(r.data?.status || status);- obHint.textContent =- status === "not_started" ? "Reset. Onboarding will run on this person's next DM." : "Saved.";- } catch {- obHint.textContent = "Network error. Try again.";- } finally {- obButtons.forEach((b) => (b.disabled = false));- }- }- const mkOb = (label, status, primary) => {- const b = document.createElement("button");- b.type = "button";- if (primary) b.className = "primary";- b.textContent = label;- b.onclick = () => applyOb(status);- return b;- };- const obButtons = [- mkOb("Reset (re-run on next DM)", "not_started", true),- mkOb("Mark completed", "completed"),- mkOb("Mark dismissed", "dismissed"),- ];- const obActions = document.createElement("div");- obActions.className = "obactions";- obButtons.forEach((b) => obActions.appendChild(b));- const resetBtn = document.createElement("button");- resetBtn.type = "button";- resetBtn.className = "danger-link";- resetBtn.textContent = "Reset to brand-new (delete this person's DMs) →";- const resetHint = document.createElement("p");- resetHint.className = "hint";- resetBtn.onclick = async () => {- if (- !confirm(- "Delete this person's personal DM sessions (transcripts included) and clear their onboarding?\n\nThis is irreversible. Their channel history is untouched. On their next web visit they'll see the new-user welcome greeting, then onboarding.",- )- )- return;- resetBtn.disabled = true;- obButtons.forEach((b) => (b.disabled = true));- resetHint.textContent = "Resetting…";- try {- const r = await api("POST", "/api/users/" + encodeURIComponent(principalId) + "/reset");- if (!r.ok) {- resetHint.textContent = r.data?.message || "Failed (" + r.status + ").";- return;- }-- showUserDetail(principalId);- } catch {- resetHint.textContent = "Network error. Try again.";- } finally {- resetBtn.disabled = false;- obButtons.forEach((b) => (b.disabled = false));- }- };- const obDivider = document.createElement("div");- obDivider.className = "obdivider";- paintOb(d.onboarding || "not_started");- obWrap.append(obStatusRow, obActions, obHint, obDivider, resetBtn, resetHint);- detail.appendChild(- dataCard(- "Onboarding",- "Personal-DM onboarding state. Reset to re-trigger the flow on this person's next DM, or wipe their DMs to replay the full new-user experience.",- obWrap,- ),- );-- const cfgCard = dataCard("Configuration", "Policy and connectors for this person's personal scope.", cfgWrap);- const manage = document.createElement("button");- manage.type = "button";- manage.className = "link";- manage.textContent = "Manage in Governance →";- manage.onclick = () => go({ view: "governance", scope: d.scopeId || "personal:" + principalId, session: null });- cfgCard.querySelector(".body").appendChild(manage);- detail.appendChild(cfgCard);}async function showContextPage(sessionId, turnSeq) {- const root = $("view-data");- root.textContent = "";- pageShell({ back: { label: "← Back to transcript", onClick: () => history.back() }, title: "Sent to model" });- const detail = document.createElement("div");- detail.className = "detail";- detail.textContent = "Loading…";- root.appendChild(detail);-- const lr = await api(- "GET",- "/api/sessions/" +- encodeURIComponent(sessionId) +- "/llm?turnSeq=" +- encodeURIComponent(turnSeq) +- "&scope=" +- encodeURIComponent(scope),- );- if (!lr.ok) {- detail.textContent = lr.data?.message || `Failed to load context (${lr.status}).`;- return;- }- const reqs = (lr.data.requests || []).slice().sort((a, b) => (a.step || 0) - (b.step || 0));- const turnLabel = turnSeq === "orphan" ? "unattributed context" : `turn #${turnSeq}`;- detail.textContent = "";- const head = document.createElement("div");- head.className = "context-page-head";- const title = document.createElement("h2");- title.textContent =- reqs.length > 1 ? `Sent to model · ${turnLabel} · ${reqs.length} steps` : `Sent to model · ${turnLabel}`;- head.appendChild(title);- if (!reqs.length) {- detail.appendChild(head);- const p = document.createElement("p");- p.className = "context-empty";- p.textContent = "No context was captured for this turn.";- detail.appendChild(p);- return;- }- const turnCache = sumCacheUsage(reqs);- const stats = document.createElement("div");- stats.className = "context-stats";- const latest = reqs[reqs.length - 1];- const latestSections = contextSections(requestBody(latest), latest.transport);- stats.append(metaChip((latest.model || "?") + " · " + fmtContextSize(latest, latestSections)));- cacheMetaItems(turnCache).forEach((b) => stats.appendChild(b));- stats.appendChild(rawJsonLink(reqs));- head.appendChild(stats);- detail.appendChild(head);- const panel = renderLlmRequests(reqs, { embedded: true, latestSections });- panel.classList.add("context-page");- panel.querySelector(".who")?.remove();- detail.appendChild(panel);-- for (const reqEl of panel.querySelectorAll(".context-request")) {- const segs = [...reqEl.querySelectorAll(".context-segment")];- if (segs.length)- segs- .reduce((a, b) => ((parseFloat(b.style.flexGrow) || 0) > (parseFloat(a.style.flexGrow) || 0) ? b : a))- .click();- }+ return governanceUI.transcript.contextPage(sessionId, turnSeq, transcriptServices());}- const SLACK_MIRROR_PAGE = 200;function emptyPara(text) {const p = document.createElement("p");p.className = "empty";p.textContent = text;return p;}- let slackReq = 0;let slackContainers = null;let slackContainersTruncated = false;async function loadSlackContainers() {@@ -17832,12 +10887,6 @@function slackUnescape(s) {return s.replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");}- function slackAvatar(m) {- const av = document.createElement("span");- av.className = "sm-avatar";- av.textContent = (slackAuthorLabel(m).trim()[0] || "?").toUpperCase();- return av;- }function slackMentionSpan(text) {const s = document.createElement("span");s.className = "sm-mention";@@ -17845,1635 +10894,227 @@return s;}- function slackEntityNode(inner, mentions) {- const u = slackUnescape(inner);- if (u[0] === "@") {- const [id, label] = u.slice(1).split("|");- return slackMentionSpan("@" + (label || (mentions && mentions[id]) || id));- }- if (u[0] === "#") {- const [id, label] = u.slice(1).split("|");- return slackMentionSpan("#" + (label || id));- }- if (u[0] === "!") {- const [cmd, label] = u.slice(1).split("|");- return slackMentionSpan("@" + (label || cmd.split("^")[0]));- }- const bar = u.indexOf("|");- const url = bar === -1 ? u : u.slice(0, bar);- const label = bar === -1 ? url : u.slice(bar + 1);-- if (!/^(https?:|mailto:|tel:)/i.test(url)) return document.createTextNode(label);- const a = document.createElement("a");- a.href = url;- a.target = "_blank";- a.rel = "noopener";- a.textContent = label;- return a;- }-- function slackAppendMrkdwn(raw, parent) {- const text = slackUnescape(raw);- const re = /\*([^*\n]+)\*|(?<!\w)_([^_\n]+)_(?!\w)|~([^~\n]+)~|(https?:\/\/[^\s<>]+)/g;- let last = 0,- m;- while ((m = re.exec(text))) {- if (m.index > last) parent.appendChild(document.createTextNode(text.slice(last, m.index)));- let el;- if (m[1] != null) {- el = document.createElement("strong");- el.textContent = m[1];- } else if (m[2] != null) {- el = document.createElement("em");- el.textContent = m[2];- } else if (m[3] != null) {- el = document.createElement("s");- el.textContent = m[3];- } else {- let url = m[4].replace(/[.,;!?]+$/, "");- while (url.endsWith(")") && (url.match(/\)/g) || []).length > (url.match(/\(/g) || []).length)- url = url.slice(0, -1);- el = slackEntityNode(url);- parent.appendChild(el);- parent.appendChild(document.createTextNode(m[4].slice(url.length)));- last = re.lastIndex;- continue;- }- parent.appendChild(el);- last = re.lastIndex;- }- if (last < text.length) parent.appendChild(document.createTextNode(text.slice(last)));- }-- function slackParseInline(text, parent, mentions) {- const re = /`([^`\n]+)`|<([^>\n]+)>|:([a-z0-9_+'-]+):/g;- let last = 0,- m;- while ((m = re.exec(text))) {- if (m.index > last) slackAppendMrkdwn(text.slice(last, m.index), parent);- if (m[1] != null) {- const c = document.createElement("code");- c.className = "sm-code";- c.textContent = slackUnescape(m[1]);- parent.appendChild(c);- } else if (m[2] != null) parent.appendChild(slackEntityNode(m[2], mentions));- else if (SLACK_EMOJI[m[3]]) parent.appendChild(document.createTextNode(SLACK_EMOJI[m[3]]));- else slackAppendMrkdwn(m[0], parent);- last = re.lastIndex;- }- if (last < text.length) slackAppendMrkdwn(text.slice(last), parent);- }-- function slackParseText(raw, mentions) {- const frag = document.createDocumentFragment();- if (!raw) return frag;- raw.split("```").forEach((part, i) => {- if (i % 2 === 1) {- const pre = document.createElement("pre"),- code = document.createElement("code");- code.textContent = slackUnescape(part.replace(/^\n/, "").replace(/\n$/, ""));- pre.appendChild(code);- frag.appendChild(pre);- } else {- let quote = null;- part.split("\n").forEach((line, lineIndex) => {- const quoted = /^(?:>|>) ?/.test(line);- if (quoted) {- if (!quote) {- quote = document.createElement("blockquote");- frag.appendChild(quote);- } else quote.appendChild(document.createTextNode("\n"));- slackParseInline(line.replace(/^(?:>|>) ?/, ""), quote, mentions);- } else {- if (lineIndex && !quote) frag.appendChild(document.createTextNode("\n"));- quote = null;- slackParseInline(line, frag, mentions);- }- });- }- });- return frag;- }- function slackAuthorLabel(m) {- return m.self ? brandSelfLabel() : m.authorName || m.authorId || "unknown";- }- function slackSearchBox(container) {- let timer = null;- return {- placeholder: container ? "Search this channel…" : "Search all mirrored messages…",- onInput: (value) => {- clearTimeout(timer);- timer = setTimeout(() => renderSlackSearchResults(value.trim(), container), 250);- },- };- }-- function slackGroupKey(m) {- return (m.authorId || m.authorName || m.ts) + "|" + (m.sub && m.sub !== m.ts ? m.sub : "root");- }- function slackMessageRow(m, opts = {}) {- const cont = !!opts.cont;- const row = document.createElement("div");- row.className =- "sm-msg" +- (cont ? " sm-cont" : "") +- (m.self ? " sm-self" : "") +- (m.sub && m.sub !== m.ts ? " sm-reply" : "") +- (m.deleted ? " sm-deleted" : "") +- (opts.target ? " sm-target" : "");- row.dataset.ts = m.ts;- const gutter = document.createElement("div");- gutter.className = "sm-gutter";- if (cont) {- const g = document.createElement("span");- g.className = "sm-guttertime";- g.textContent = new Date(m.createdAt).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });- gutter.appendChild(g);- } else {- gutter.appendChild(slackAvatar(m));- }- const body = document.createElement("div");- body.className = "sm-body";- if (!cont) {- const head = document.createElement("div");- head.className = "sm-head";- const author = document.createElement("span");- author.className = "sm-author";- author.textContent = slackAuthorLabel(m);- head.appendChild(author);- if (m.self) {- const t = document.createElement("span");- t.className = "sm-tag sm-tag-agent";- t.textContent = "agent";- head.appendChild(t);- } else if (m.bot) {- const t = document.createElement("span");- t.className = "sm-tag";- t.textContent = "bot";- head.appendChild(t);- }- if (m.sub && m.sub !== m.ts) {- const t = document.createElement("span");- t.className = "sm-tag";- t.textContent = "Thread reply";- t.title = "Reply in the thread rooted at " + m.sub;- head.appendChild(t);- }- if (opts.containerLabel) {- const c = document.createElement("span");- c.className = "sm-tag";- c.textContent = opts.containerLabel;- head.appendChild(c);- }- const when = document.createElement("span");- when.className = "sm-when";- when.textContent =- view === "slack" && !opts.onOpen- ? new Date(m.createdAt).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })- : relTime(m.createdAt);- when.title = fmtTime(m.createdAt) + " · ts " + m.ts;- head.appendChild(when);- body.appendChild(head);- }- const text = document.createElement("div");- text.className = "sm-text";- text.appendChild(slackParseText(m.text || "", m.mentions));- if (m.editedAt) {- const e = document.createElement("span");- e.className = "sm-flag";- e.textContent = "(edited)";- e.title = fmtTime(m.editedAt);- text.appendChild(e);- }- if (m.deleted) {- const e = document.createElement("span");- e.className = "sm-flag";- e.textContent = "(deleted in Slack)";- text.appendChild(e);- }- body.appendChild(text);- row.append(gutter, body);- if (opts.onOpen) {- row.classList.add("sm-openable");- row.onclick = () => opts.onOpen(m);- }- return row;- }- async function renderSlackSearchResults(q, container) {- const reqId = ++slackReq;- if (!q) return void renderSlackMirror({ ...urlToState(), ts: null });- const root = $("view-data");- root.textContent = "";- const path =- "/api/slack-mirror/messages?q=" +- encodeURIComponent(q) +- (container ? "&container=" + encodeURIComponent(container) : "");- const r = await api("GET", path);- if (reqId !== slackReq || view !== "slack") return;- if (!r.ok) return void root.appendChild(emptyPara(r.data?.message || `Search failed (${r.status}).`));- const messages = r.data.messages || [];- if (!messages.length) return void root.appendChild(emptyPara("No matches in the mirror."));- const list = document.createElement("div");- list.className = "sm-stream";- for (const m of messages) {- list.appendChild(- slackMessageRow(m, {- containerLabel: container ? null : slackContainerLabel(m.container),- onOpen: (msg) => go({ view: "slack", container: msg.container, ts: msg.ts }),- }),- );- }- root.appendChild(list);- if (r.data.hasMore) {- root.appendChild(- emptyPara(`First ${messages.length.toLocaleString()} matches shown. Refine the search to see the rest.`),- );- }- }- async function renderSlackMirror(st) {- ++slackReq;- const root = $("view-data");- root.textContent = "";- if (!st.container) {- pageShell({ title: "Slack", search: slackSearchBox(null) });- const loading = document.createElement("div");- loading.className = "loadingline";- loading.textContent = "Loading Slack mirror...";- root.appendChild(loading);- const r = await loadSlackContainers();- if (view !== "slack" || urlToState().container) return;- root.textContent = "";- if (!r.ok)- return void root.appendChild(- emptyPara(- r.status === 403- ? "Only an org admin can read the Slack mirror."- : r.data?.message || `Failed to load (${r.status}).`,- ),- );- viewLoadedAt.slack = Date.now();- const containers = slackContainers || [];- pageShell({- title: "Slack",- count:- (slackContainersTruncated ? containers.length.toLocaleString() + "+" : containers.length) +- " conversations",- search: slackSearchBox(null),- });- root.appendChild(- denseList(- containers,- (c) => {- return {- icon: null,- name: slackContainerLabel(c.container),- preview: `${Number(c.messageCount).toLocaleString()} mirrored · ${plural((c.members || []).length, "member")}`,- time: relTime(c.updatedAt),- href: stateToUrl({ view: "slack", container: c.container }),- };- },- (c) => go({ view: "slack", container: c.container }),- "Nothing mirrored yet. The surface pushes messages here as it sees them.",- ),- );- if (slackContainersTruncated) {- root.appendChild(- emptyPara(`Showing the ${containers.length.toLocaleString()} most recently active conversations.`),- );- }- return;- }-- if (!slackContainers) await loadSlackContainers();- const container = st.container;- const scopeGo = slackContainerScope(container);- pageShell({- back: { label: "← Slack", onClick: () => go({ view: "slack", container: null, ts: null }) },- title: slackContainerLabel(container),- context: container,- search: slackSearchBox(container),- actions: [- navLink("Judgments →", { view: "judgments", container }),- ...(scopeGo ? [navLink("Governance →", { view: "governance", scope: scopeGo, session: null })] : []),- ],- });- const bar = $("shellbar");- const toolbar = document.createElement("div");- toolbar.className = "sm-toolbar";- toolbar.append(bar.querySelector(".back"), ...bar.querySelectorAll(".link"));- const heading = document.createElement("div");- heading.className = "sm-channel-heading";- heading.append(bar.querySelector(".shell-title"), bar.querySelector(".shell-context"));- bar.querySelector(".shell-spacer")?.remove();- bar.prepend(toolbar, heading);- const loading = document.createElement("div");- loading.className = "loadingline";- loading.textContent = "Loading messages...";- root.appendChild(loading);- const fetchPage = (before) =>- api(- "GET",- "/api/slack-mirror/messages?container=" +- encodeURIComponent(container) +- "&limit=" +- SLACK_MIRROR_PAGE +- (before ? "&before=" + encodeURIComponent(before) : ""),- );- let r = await fetchPage(null);- if (!r.ok) {- root.textContent = "";- return void root.appendChild(emptyPara(r.data?.message || `Failed to load (${r.status}).`));- }- let messages = r.data.messages || [];- let hasMore = !!r.data.hasMore;- for (let hops = 0; st.ts && hasMore && messages.length && messages[0].ts > st.ts && hops < 10; hops++) {- const older = await fetchPage(messages[0].ts);- if (!older.ok) break;- messages = (older.data.messages || []).concat(messages);- hasMore = !!older.data.hasMore;- }- const stateNow = urlToState();- if (view !== "slack" || stateNow.container !== container) return;- root.textContent = "";- const rawLink = document.createElement("a");- rawLink.href = "/api/slack-mirror/messages?container=" + encodeURIComponent(container);- rawLink.target = "_blank";- rawLink.rel = "noopener";- rawLink.textContent = "Raw feed ↗";- rawLink.title = "Open the raw mirrored JSON rows for this container in a new tab";- $("shellbar").querySelector(".sm-toolbar").appendChild(rawLink);- const stream = document.createElement("div");- stream.className = "sm-stream";- const dayOf = (m) => new Date(m.createdAt).toDateString();- const daySep = (m) => {- const sep = document.createElement("div");- sep.className = "sm-day";- sep.textContent =- dayOf(m) === new Date().toDateString()- ? "Today"- : new Date(m.createdAt).toLocaleDateString([], { month: "short", day: "numeric", year: "numeric" });- return sep;- };-- const buildRows = (msgs, target) => {- let lastDay = "",- lastKey = "";- for (const m of msgs) {- const day = dayOf(m);- if (day !== lastDay) {- lastDay = day;- lastKey = "";- target.appendChild(daySep(m));- }- const key = slackGroupKey(m);- target.appendChild(slackMessageRow(m, { target: st.ts === m.ts, cont: key === lastKey && st.ts !== m.ts }));- lastKey = key;- }- };- const renderInto = (msgs) => {- stream.textContent = "";- if (!msgs.length) return void stream.appendChild(emptyPara("Nothing mirrored for this channel yet."));- buildRows(msgs, stream);- };- if (hasMore) {- const older = document.createElement("button");- older.type = "button";- older.className = "load-earlier more";- older.textContent = "Load earlier messages";- older.onclick = async () => {- older.disabled = true;- const prev = await fetchPage(messages[0]?.ts);- older.disabled = false;- if (!prev.ok) return;- const page = prev.data.messages || [];- if (page.length) {- const existingFirst = messages[0];- const frag = document.createDocumentFragment();- buildRows(page, frag);-- const sameDay = !!existingFirst && dayOf(page[page.length - 1]) === dayOf(existingFirst);- const leadSep = stream.firstChild;- if (sameDay && leadSep && leadSep.classList && leadSep.classList.contains("sm-day")) {- stream.removeChild(leadSep);- }-- const seamRow = stream.firstChild;- if (- sameDay &&- seamRow &&- seamRow.classList &&- seamRow.classList.contains("sm-msg") &&- !seamRow.classList.contains("sm-cont") &&- st.ts !== existingFirst.ts &&- slackGroupKey(page[page.length - 1]) === slackGroupKey(existingFirst)- ) {- seamRow.replaceWith(slackMessageRow(existingFirst, { target: st.ts === existingFirst.ts, cont: true }));- }- stream.insertBefore(frag, stream.firstChild);- messages = page.concat(messages);- }- if (!prev.data.hasMore) older.remove();- };- root.appendChild(older);- }- root.appendChild(stream);- renderInto(messages);- if (st.ts) {- const target = stream.querySelector(".sm-target");- if (target) requestAnimationFrame(() => target.scrollIntoView({ block: "center" }));- else {- const note = document.createElement("div");- note.className = "sm-day";- note.textContent =- "Message " +- st.ts +- " isn't in the loaded window. It may be older than what's shown (use “Load earlier messages”) or was never mirrored.";- root.insertBefore(note, root.firstChild);- }- } else {- requestAnimationFrame(() => window.scrollTo({ top: document.body.scrollHeight }));- }- }-- function deliverySurfaceLabel(event) {- const type = event?.destination?.type;- if (type === "principal") return "Slack DM";- if (type === "slack") return "Slack";- if (type === "web") return "Web";- return type || "Unknown surface";- }-- function deliveryLabel(event) {- if (event.shadow) return "Shadow delivery";- return `${deliverySurfaceLabel(event)} delivery`;- }-- function slackMirrorRef(event) {- const d = event?.destination || {};- if (d.type !== "slack" || !d.editRef || typeof d.target !== "string" || !d.target) return null;- return { container: d.target.split(":")[0], ts: d.editRef };- }-- const JUDGMENT_TABS = [- { key: "act,ignore", label: "Judged", counts: ["act", "ignore"] },- { key: "act", label: "Woke", counts: ["act"] },- { key: "ignore", label: "Silent", counts: ["ignore"] },- { key: "fastlane", label: "Fastlane", counts: ["fastlane"] },- ];- function judgmentBadge(d) {- if (d === "act") return badge("woke", "ok");- if (d === "ignore") return badge("silent", "muted");- return badge("fastlane", "accent");- }- async function renderAmbientJudgments(st) {- const root = $("view-data");- root.textContent = "";- if (!slackContainers) await loadSlackContainers();- if (st.jid) return void showJudgmentDetail(st);- const decision = st.decision || "act,ignore";- const backTo = (over) => go({ view: "judgments", container: null, decision: st.decision, jid: null, ...over });- const shell = (extra) =>- pageShell({- title: "Judgments",- ...(st.container- ? {- back: { label: "← Judgments", onClick: () => backTo({}) },- context: slackContainerLabel(st.container),- contextGo: { view: "slack", container: st.container },- }- : {}),- actions: [navLink("Ack emoji →", { view: "ackemoji" })],- ...extra,- });- shell({});- const loading = document.createElement("div");- loading.className = "loadingline";- loading.textContent = "Loading judgments…";- root.appendChild(loading);- const path =- "/api/ambient-judgments?decision=" +- encodeURIComponent(decision) +- (st.container ? "&container=" + encodeURIComponent(st.container) : "");- const r = await api("GET", path);- if (view !== "judgments" || urlToState().jid) return;- root.textContent = "";- if (!r.ok)- return void root.appendChild(- emptyPara(- r.status === 403- ? "Only an org admin can read ambient judgments."- : r.data?.message || `Failed to load (${r.status}).`,- ),- );- const counts = r.data.counts || { act: 0, ignore: 0, fastlane: 0 };- shell({- tabs: JUDGMENT_TABS.map((t) => ({- label: t.label,- count: t.counts.reduce((n, k) => n + (counts[k] || 0), 0),- active: t.key === decision,- onClick: () =>- go({- view: "judgments",- container: st.container,- decision: t.key === "act,ignore" ? null : t.key,- jid: null,- }),- })),- });- let judgments = r.data.judgments || [];- if (!judgments.length) return void root.appendChild(emptyPara("No judgments recorded for this filter yet."));- const open = (j) =>- go({ view: "judgments", container: st.container, decision: st.decision, jid: String(j.id) });- const rowOf = (j) => {- const prev = document.createElement("span");- prev.className = "badges";- prev.appendChild(judgmentBadge(j.decision));- const txt = document.createElement("span");- txt.className = "pill judgment-reason";- txt.textContent = j.reason || (j.decision === "fastlane" ? "@mention, routed past the judge" : "None");- prev.appendChild(txt);- if (j.latencyMs != null) {- const l = document.createElement("span");- l.className = "dense-time";- l.textContent = j.latencyMs + "ms";- prev.appendChild(l);- }- return {- name: slackContainerLabel(j.container),- preview: prev,- time: relTime(j.createdAt),- href: stateToUrl({ view: "judgments", container: st.container, decision: st.decision, jid: String(j.id) }),- };- };- const list = document.createElement("div");- const paint = () => {- list.textContent = "";- list.appendChild(denseList(judgments, rowOf, open, ""));- };- paint();- root.appendChild(list);- if (r.data.hasMore) {- const more = document.createElement("button");- more.type = "button";- more.className = "load-earlier more";- more.textContent = "Load earlier judgments";- more.onclick = async () => {- more.disabled = true;- const last = judgments[judgments.length - 1];- const older = await api("GET", path + "&before=" + last.createdAt + "&beforeId=" + last.id);- more.disabled = false;- if (!older.ok) return;- judgments = judgments.concat(older.data.judgments || []);- paint();- if (!older.data.hasMore) more.remove();- };- root.appendChild(more);- }- }-- function judgmentSlackHref(workspaceUrl, container, ts) {- if (!workspaceUrl || !container || !ts || !container.startsWith("C")) return null;- return workspaceUrl.replace(/\/$/, "") + "/archives/" + container + "/p" + ts.replace(".", "");- }- function judgmentMirrorPane(j, workspaceUrl) {- const wrap = document.createElement("div");- const title = document.createElement("div");- title.className = "judg-pane-title";- title.appendChild(document.createTextNode("Slack mirror"));- const href = judgmentSlackHref(workspaceUrl, j.container, j.tsFrom);- if (href) {- const a = document.createElement("a");- a.href = href;- a.target = "_blank";- a.rel = "noopener";- a.className = "judg-extlink";- a.setAttribute("aria-label", "Open in Slack");- a.title = "Jump to this moment in Slack to scroll up for more context";- a.innerHTML =- '<svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6.5 3.5H3.5a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1v-3"/><path d="M9.5 2.5h4v4"/><path d="M7 9 13.5 2.5"/></svg>';- title.appendChild(a);- }- wrap.appendChild(title);- const box = document.createElement("div");- box.className = "judg-mirror";- wrap.appendChild(box);-- void (async () => {- const before = j.tsTo ? (Number(j.tsTo) + 1).toString() : undefined;- const r = await api(- "GET",- "/api/slack-mirror/messages?container=" +- encodeURIComponent(j.container) +- "&limit=" +- SLACK_MIRROR_PAGE +- (before ? "&before=" + encodeURIComponent(before) : ""),- );- if (view !== "judgments" || urlToState().jid !== String(j.id)) return;- box.textContent = "";- if (!r.ok) return void box.appendChild(emptyPara(r.data?.message || `Failed to load mirror (${r.status}).`));- const from = j.tsFrom,- to = j.tsTo;-- const messages = (r.data.messages || []).filter((m) => !to || m.ts <= to);- if (!messages.length) return void box.appendChild(emptyPara("Nothing mirrored for this window."));- const stream = document.createElement("div");- stream.className = "sm-stream";- for (const m of messages) {- const inWindow = from && to && m.ts >= from && m.ts <= to;- stream.appendChild(slackMessageRow(m, { target: inWindow }));- }- box.appendChild(stream);- const delta = stream.querySelector(".sm-target");- if (delta) requestAnimationFrame(() => delta.scrollIntoView({ block: "center" }));- })();- return wrap;- }- function judgmentPromptPane(j) {- const wrap = document.createElement("div");- const title = document.createElement("div");- title.className = "judg-pane-title";- title.textContent = "Judge context";- wrap.appendChild(title);- const box = document.createElement("div");- box.className = "judg-prompt";- const pre = document.createElement("pre");- pre.textContent =- j.prompt ||- (j.decision === "fastlane"- ? "Routed past the judge (formal @mention). No prompt was rendered."- : "(prompt not recorded)");- box.appendChild(pre);- wrap.appendChild(box);- return wrap;- }- async function showJudgmentDetail(st) {- const root = $("view-data");- root.textContent = "";- const back = {- label: "← Judgments",- onClick: () => go({ view: "judgments", container: st.container, decision: st.decision, jid: null }),- };- pageShell({ back, title: "Judgment" });- const detail = document.createElement("div");- detail.className = "detail judg-detail";- detail.textContent = "Loading…";- root.appendChild(detail);- const r = await api("GET", "/api/ambient-judgments?id=" + encodeURIComponent(st.jid));- if (view !== "judgments" || urlToState().jid !== st.jid) return;- detail.textContent = "";- if (!r.ok) return void detail.appendChild(emptyPara(r.data?.message || `Failed to load (${r.status}).`));- const j = r.data.judgment;- const scopeGo = slackContainerScope(j.container);- pageShell({- back,- title: "Judgment",- context: slackContainerLabel(j.container),- contextGo: { view: "slack", container: j.container, ts: j.tsFrom },- actions: scopeGo ? [navLink("Governance →", { view: "governance", scope: scopeGo, session: null })] : [],- });- const split = document.createElement("div");- split.className = "judg-split";- split.appendChild(judgmentMirrorPane(j, r.data.workspaceUrl));- split.appendChild(judgmentPromptPane(j));- detail.appendChild(split);- const dec = document.createElement("div");- dec.className = "judg-decision";- const head = document.createElement("div");- head.className = "badges";- head.appendChild(judgmentBadge(j.decision));- if (j.askedBy) head.appendChild(badge("asked by " + j.askedBy, "accent"));- const meta = document.createElement("span");- meta.className = "shell-context";- meta.textContent = [j.model, j.latencyMs != null ? j.latencyMs + "ms" : null, fmtTime(j.createdAt)]- .filter(Boolean)- .join(" · ");- head.appendChild(meta);- dec.appendChild(head);- const p = document.createElement("p");- let reason = "None";- if (j.decision === "ignore") reason = "Stayed silent.";- else if (j.decision === "fastlane") reason = "@mention, routed past the judge.";- p.textContent = j.reason || reason;- dec.appendChild(p);- detail.appendChild(dec);- }-- const ACK_PICK_TABS = [- { key: null, label: "All", counts: ["picked", "declined"] },- { key: "picked", label: "Picked", counts: ["picked"] },- { key: "declined", label: "Declined", counts: ["declined"] },- ];-- function ackEmojiTag(name, icon) {- if (icon && /^https?:\/\//.test(icon)) {- const img = document.createElement("img");- img.className = "ack-emoji-img";- img.src = icon;- img.alt = ":" + name + ":";- img.title = ":" + name + ":";- return img;- }- const s = document.createElement("span");- if (icon) {- s.className = "ack-emoji-glyph";- s.textContent = icon;- s.title = ":" + name + ":";- } else {- s.className = "pill";- s.textContent = name ? ":" + name + ":" : "None";- }- return s;- }- function ackPickBadge(o) {- return o === "picked" ? badge("picked", "ok") : badge("declined", "muted");- }- async function renderAckEmojiPicks(st) {- const root = $("view-data");- root.textContent = "";- if (!slackContainers) await loadSlackContainers();- if (st.jid) return void showAckPickDetail(st);- const outcome = st.decision || null;- const shell = (extra) =>- pageShell({- title: "Ack emoji",- ...(st.container- ? {- back: {- label: "← Ack emoji",- onClick: () => go({ view: "ackemoji", container: null, decision: st.decision, jid: null }),- },- context: slackContainerLabel(st.container),- contextGo: { view: "slack", container: st.container },- }- : {- back: {- label: "← Judgments",- onClick: () => go({ view: "judgments", container: null, decision: null, jid: null }),- },- }),- ...extra,- });- shell({});- const loading = document.createElement("div");- loading.className = "loadingline";- loading.textContent = "Loading ack-emoji picks…";- root.appendChild(loading);- const path =- "/api/ack-emoji-picks?" +- (outcome ? "outcome=" + encodeURIComponent(outcome) : "") +- (st.container ? "&container=" + encodeURIComponent(st.container) : "");- const r = await api("GET", path);- if (view !== "ackemoji" || urlToState().jid) return;- root.textContent = "";- if (!r.ok)- return void root.appendChild(- emptyPara(- r.status === 403- ? "Only an org admin can read ack-emoji picks."- : r.data?.message || `Failed to load (${r.status}).`,- ),- );- const counts = r.data.counts || { picked: 0, declined: 0 };- shell({- tabs: ACK_PICK_TABS.map((t) => ({- label: t.label,- count: t.counts.reduce((n, k) => n + (counts[k] || 0), 0),- active: (t.key || null) === outcome,- onClick: () => go({ view: "ackemoji", container: st.container, decision: t.key, jid: null }),- })),- });- let picks = r.data.picks || [];- if (!picks.length) return void root.appendChild(emptyPara("No ack-emoji picks recorded for this filter yet."));- const open = (p) => go({ view: "ackemoji", container: st.container, decision: st.decision, jid: String(p.id) });- const rowOf = (p) => {- const prev = document.createElement("span");- prev.className = "badges";- prev.appendChild(p.outcome === "picked" ? ackEmojiTag(p.picked, p.icon) : ackPickBadge("declined"));- const txt = document.createElement("span");- txt.className = "pill";- txt.textContent = p.message || "None";- prev.appendChild(txt);- if (p.latencyMs != null) {- const l = document.createElement("span");- l.className = "dense-time";- l.textContent = p.latencyMs + "ms";- prev.appendChild(l);- }- return {- name: slackContainerLabel(p.channel),- preview: prev,- time: relTime(p.createdAt),- href: stateToUrl({ view: "ackemoji", container: st.container, decision: st.decision, jid: String(p.id) }),- };- };- const list = document.createElement("div");- const paint = () => {- list.textContent = "";- list.appendChild(denseList(picks, rowOf, open, ""));- };- paint();- root.appendChild(list);- if (r.data.hasMore) {- const more = document.createElement("button");- more.type = "button";- more.className = "load-earlier more";- more.textContent = "Load earlier picks";- more.onclick = async () => {- more.disabled = true;- const last = picks[picks.length - 1];- const older = await api("GET", path + "&before=" + last.createdAt + "&beforeId=" + last.id);- more.disabled = false;- if (!older.ok) return;- picks = picks.concat(older.data.picks || []);- paint();- if (!older.data.hasMore) more.remove();- };- root.appendChild(more);- }- }- async function showAckPickDetail(st) {- const root = $("view-data");- root.textContent = "";- const back = {- label: "← Ack emoji",- onClick: () => go({ view: "ackemoji", container: st.container, decision: st.decision, jid: null }),- };- pageShell({ back, title: "Ack emoji" });- const detail = document.createElement("div");- detail.className = "detail judg-detail";- detail.textContent = "Loading…";- root.appendChild(detail);- const r = await api("GET", "/api/ack-emoji-picks?id=" + encodeURIComponent(st.jid));- if (view !== "ackemoji" || urlToState().jid !== st.jid) return;- detail.textContent = "";- if (!r.ok) return void detail.appendChild(emptyPara(r.data?.message || `Failed to load (${r.status}).`));- const p = r.data.pick;- const href = judgmentSlackHref(r.data.workspaceUrl, p.channel, p.ts);- pageShell({- back,- title: "Ack emoji",- context: slackContainerLabel(p.channel),- contextGo: { view: "slack", container: p.channel, ts: p.ts },- });- const dec = document.createElement("div");- dec.className = "judg-decision";- const head = document.createElement("div");- head.className = "badges";- head.appendChild(p.outcome === "picked" ? ackEmojiTag(p.picked, p.icon) : ackPickBadge("declined"));- const meta = document.createElement("span");- meta.className = "shell-context";- meta.textContent = [p.model, p.latencyMs != null ? p.latencyMs + "ms" : null, fmtTime(p.createdAt)]- .filter(Boolean)- .join(" · ");- head.appendChild(meta);- if (href) {- const a = document.createElement("a");- a.href = href;- a.target = "_blank";- a.rel = "noopener";- a.className = "judg-extlink";- a.textContent = "Open in Slack ↗";- head.appendChild(a);- }- dec.appendChild(head);- const msgTitle = document.createElement("div");- msgTitle.className = "judg-pane-title";- msgTitle.textContent = "Message";- detail.appendChild(dec);- detail.appendChild(msgTitle);- const msg = document.createElement("div");- msg.className = "judg-prompt";- const mpre = document.createElement("pre");- mpre.textContent = p.message || "(not recorded)";- msg.appendChild(mpre);- detail.appendChild(msg);- const candTitle = document.createElement("div");- candTitle.className = "judg-pane-title";- candTitle.textContent = "Candidate slate";- detail.appendChild(candTitle);- const cand = document.createElement("div");- cand.className = "badges";- for (const name of (p.candidates || "").split(" ").filter(Boolean)) {- const tag = ackEmojiTag(name);- if (name === p.picked) tag.classList.add("accent");- cand.appendChild(tag);- }- if (!(p.candidates || "").trim()) cand.appendChild(emptyPara("(candidate slate not recorded)"));- detail.appendChild(cand);- }- async function showTranscript(sessionId, limit, expand) {- const reqLimit = limit || TRANSCRIPT_PAGE_SIZE;- let applyTranscriptControls = () => {};- const backToList = (sessionScope) => () => {- if (history.state?.deepLink)- go({ view: "history", scope: sessionScope || scope, session: null, historyKind });- else history.back();- };- const root = $("view-data");- root.textContent = "";- pageShell({- back: { label: "← Conversations", onClick: backToList() },- title: "Conversation",- context: shortName(scope),- });- renderTranscriptHeaderControls(() => applyTranscriptControls());- const detail = document.createElement("div");- detail.className = "detail";- detail.textContent = "Loading…";- root.appendChild(detail);-- const llmPromise = api(- "GET",- "/api/sessions/" + encodeURIComponent(sessionId) + "/llm?scope=" + encodeURIComponent(scope),- );- const r = await api(- "GET",- "/api/sessions/" +- encodeURIComponent(sessionId) +- "?scope=" +- encodeURIComponent(scope) +- "&limit=" +- reqLimit,- );- if (!r.ok) {- detail.textContent = r.data?.message || `Failed to load transcript (${r.status}).`;- return;- }- detail.textContent = "";- const session = r.data.session || {};- const entries = r.data.entries || [];- const serverHasMore = !!r.data.hasMore;- const deliveryEvents = r.data.deliveryEvents || [];- const origin = r.data.origin || null;-- const ownerPrincipal =- typeof session.scopeId === "string" && session.scopeId.startsWith("personal:")- ? session.scopeId.slice("personal:".length)- : null;- pageShell({- back: { label: "← Conversations", onClick: backToList(session.scopeId) },- title: origin?.label || "Conversation",- context:- shortName(session.scopeId || scope) + (session.createdAt ? " · created " + relTime(session.createdAt) : ""),- actions: ownerPrincipal ? [webUiAsButton(ownerPrincipal)] : [],- });- const errStrip = document.createElement("div");- detail.appendChild(errStrip);- void (async () => {- const errs = await adminErrors(- "scope=" + encodeURIComponent(scope) + "&sessionId=" + encodeURIComponent(sessionId),- );- if (!errs.length || !errStrip.isConnected) return;- errStrip.appendChild(errorStripBox(errs, plural(errs.length, "error") + " logged in this session", 5));- })();-- const originPromptSeq = origin && !serverHasMore ? entries.find((e) => e.type === "user")?.seq : null;-- const minLoadedSeq = entries.length ? entries[0].seq : 0;-- const llmByTurn = new Map();- try {- const lr = await llmPromise;- if (lr.ok)- for (const req of lr.data.requests || []) {- const k = req.turnSeq == null ? "_orphan" : req.turnSeq;- if (!llmByTurn.has(k)) llmByTurn.set(k, []);- llmByTurn.get(k).push(req);- }- } catch (_e) {}- if (!entries.length && !deliveryEvents.length) {- const p = document.createElement("p");- p.className = "empty";- p.textContent = "No entries.";- detail.appendChild(p);- return;- }- const llmByEntrySeq = new Map();-- const durBySeq = new Map();- for (let i = 1; i < entries.length; i++) {- const d = (entries[i].createdAt || 0) - (entries[i - 1].createdAt || 0);- if (d >= 0) durBySeq.set(entries[i].seq, d);- }- const addLlmForEntry = (seq, req) => {- if (!llmByEntrySeq.has(seq)) llmByEntrySeq.set(seq, []);- llmByEntrySeq.get(seq).push(req);- };-- const seqToIndex = new Map();- entries.forEach((e, i) => seqToIndex.set(e.seq, i));- const nextUserIndex = Array.from({ length: entries.length });- for (let i = entries.length - 1, next = -1; i >= 0; i--) {- nextUserIndex[i] = next;- if (entries[i].type === "user") next = i;- }- for (const [turnSeq, reqs] of llmByTurn.entries()) {- if (turnSeq === "_orphan") continue;-- if (turnSeq < minLoadedSeq) continue;- const start = seqToIndex.has(turnSeq) ? seqToIndex.get(turnSeq) : -1;- if (start < 0) {- const orphaned = llmByTurn.get("_orphan") || [];- orphaned.push(...reqs);- llmByTurn.set("_orphan", orphaned);- continue;- }- const end = nextUserIndex[start];- const stop = end < 0 ? entries.length : end;-- let anchor = start;- for (let i = stop - 1; i > start; i--) {- if (entries[i].type === "assistant") {- anchor = i;- break;- }- }- for (const req of [...reqs].sort((a, b) => (a.step || 0) - (b.step || 0))) {- addLlmForEntry(entries[anchor].seq, req);- }- }- const entryBlocks = [];- applyTranscriptControls = () => {- entryBlocks.forEach(({ block, entry, types, hasDelivery, sync }) => {- const entryTypes = types || [entry.type];- block.classList.toggle("filtered", transcriptEntryHidden(entryTypes, hasDelivery));- if (sync) sync();- });- };- const stream = document.createElement("div");- stream.className = "transcript-stream";- detail.appendChild(stream);-- const resultByCallId = new Map();- for (const e of entries) {- if (e.type !== "tool_result") continue;- const callId = e.payload && typeof e.payload === "object" ? e.payload.callId : null;- if (callId && !resultByCallId.has(callId)) resultByCallId.set(callId, e);- }- const pairedResultSeqs = new Set();-- const outboundByDeliveryId = new Map();-- const principalDeliveryIds = new Set();- for (const event of deliveryEvents) {- if (!event.deliveryId) continue;- if (event.type === "outbound_delivery" && !outboundByDeliveryId.has(event.deliveryId)) {- outboundByDeliveryId.set(event.deliveryId, event);- }- if (event.type === "principal_delivery") principalDeliveryIds.add(event.deliveryId);+ function slackEntityNode(inner, mentions) {+ const u = slackUnescape(inner);+ if (u[0] === "@") {+ const [id, label] = u.slice(1).split("|");+ return slackMentionSpan("@" + (label || (mentions && mentions[id]) || id));}- const mergedDeliveryIds = new Set();- let units = [];- for (let i = 0; i < entries.length; i++) {- const e = entries[i];-- if (e.type === "soul") continue;- if (e.type === "tool_call" || e.type === "tool_result") {- if (e.type === "tool_result" && pairedResultSeqs.has(e.seq)) continue;- const callId = e.payload && typeof e.payload === "object" ? e.payload.callId : null;- let paired = null;- if (e.type === "tool_call") {- if (callId) paired = resultByCallId.get(callId) || null;- else if (entries[i + 1]?.type === "tool_result") paired = entries[i + 1];- }- if (paired) pairedResultSeqs.add(paired.seq);- const resultPayload = (e.type === "tool_result" ? e : paired)?.payload;- const resultDeliveryId =- resultPayload && typeof resultPayload === "object" ? resultPayload.deliveryId : null;- const delivery = resultDeliveryId ? outboundByDeliveryId.get(resultDeliveryId) || null : null;- if (delivery) mergedDeliveryIds.add(resultDeliveryId);- units.push({ kind: "tool", primary: e, paired, delivery, llmReqs: llmByEntrySeq.get(e.seq) || null });- continue;- }- units.push({ kind: "entry", entry: e, llmReqs: llmByEntrySeq.get(e.seq) || null });+ if (u[0] === "#") {+ const [id, label] = u.slice(1).split("|");+ return slackMentionSpan("#" + (label || id));}- for (const event of deliveryEvents) {- if (event.deliveryId && mergedDeliveryIds.has(event.deliveryId)) continue;- units.push({ kind: "delivery_event", event });+ if (u[0] === "!") {+ const [cmd, label] = u.slice(1).split("|");+ return slackMentionSpan("@" + (label || cmd.split("^")[0]));}- units.sort((a, b) => {- let at = a.primary?.createdAt || 0;- if (a.kind === "delivery_event") at = a.event.createdAt || 0;- else if (a.kind === "entry") at = a.entry.createdAt || 0;- let bt = b.primary?.createdAt || 0;- if (b.kind === "delivery_event") bt = b.event.createdAt || 0;- else if (b.kind === "entry") bt = b.entry.createdAt || 0;- return at - bt;- });+ const bar = u.indexOf("|");+ const url = bar === -1 ? u : u.slice(0, bar);+ const label = bar === -1 ? url : u.slice(bar + 1);- const orphans = llmByTurn.get("_orphan");- if (orphans && orphans.length) units.push({ kind: "llm", reqs: orphans });+ if (!/^(https?:|mailto:|tel:)/i.test(url)) return document.createTextNode(label);+ const a = document.createElement("a");+ a.href = url;+ a.target = "_blank";+ a.rel = "noopener";+ a.textContent = label;+ return a;+ }- const messageEntryLabel = (e) => {- if (e.type === "assistant") return brandSelfLabel();- if (e.type !== "user") return titleCase(e.type || "entry");- return payloadName(e.payload) || "User";- };- const entryLabel = (e) => {- const s = document.createElement("span");- s.className = "entry-label";- if (origin && e.type === "user" && e.seq === originPromptSeq) {- s.textContent = origin.label || wakeOriginLabel(origin.trigger);- s.classList.add("important");- } else if (e.type === "user" || e.type === "assistant") {- s.textContent = messageEntryLabel(e);+ function slackAppendMrkdwn(raw, parent) {+ const text = slackUnescape(raw);+ const re = /\*([^*\n]+)\*|(?<!\w)_([^_\n]+)_(?!\w)|~([^~\n]+)~|(https?:\/\/[^\s<>]+)/g;+ let last = 0,+ m;+ while ((m = re.exec(text))) {+ if (m.index > last) parent.appendChild(document.createTextNode(text.slice(last, m.index)));+ let el;+ if (m[1] != null) {+ el = document.createElement("strong");+ el.textContent = m[1];+ } else if (m[2] != null) {+ el = document.createElement("em");+ el.textContent = m[2];+ } else if (m[3] != null) {+ el = document.createElement("s");+ el.textContent = m[3];} else {- s.textContent = titleCase(e.type || "entry");- }- return s;- };- const cronLinkForEntry = (e) => {- if (!(origin?.kind === "cron" && e.type === "user" && e.seq === originPromptSeq)) return null;- const cron = origin.cron || null;- const link = document.createElement("button");- link.type = "button";- link.className = "link";- link.textContent = "View cron";- link.onclick = () =>- go({- view: "crons",- scope: cron?.ownerScopeId || session.scopeId || scope,- session: null,- cron: origin.cronId,- });- return link;- };- const originNodeForDeliveryEvent = (event) => {- const provenance = event?.provenance || null;- const label = event?.origin?.label || wakeOriginLabel(provenance?.trigger || provenance?.surface);- if (event?.sourceSession?.id) {- const link = document.createElement("button");- link.type = "button";- link.className = "origin-link";- link.textContent = label;- link.title = `Open origin session ${shortId(event.sourceSession.id)} · ${provenance?.fireKey || event.idempotencyKey || ""}`;- link.onclick = () => go({ view: "history", scope, session: event.sourceSession.id });- return link;- }- if (!provenance) return null;- const chip = metaChip(label);- chip.title = provenance.fireKey || "";- return chip;- };- const cronLinkForDeliveryEvent = (event) => {- if (event?.origin?.kind !== "cron") return null;- const link = document.createElement("button");- link.type = "button";- link.className = "link";- link.textContent = "View cron";- const cron = event.origin.cron || null;- link.onclick = () =>- go({ view: "crons", scope: cron?.ownerScopeId || scope, session: null, cron: event.origin.cronId });- return link;- };- const contextButton = (requests, panel) => {- const btn = document.createElement("button");- btn.type = "button";- btn.className = "context-icon";- btn.innerHTML =- '<svg viewBox="0 0 24 24" fill="none" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 4.5c-2.1 0-3.7 1.3-3.7 3.1 0 .2 0 .4.1.6A3.6 3.6 0 0 0 6 11.5c0 1 .4 2 1.1 2.6-.1.3-.1.5-.1.8 0 2 1.8 3.6 4 3.6h1.9c2.2 0 4-1.6 4-3.6 0-.3 0-.6-.1-.8.7-.7 1.1-1.6 1.1-2.6 0-1.5-.9-2.8-2.3-3.3 0-.2.1-.4.1-.6 0-1.8-1.6-3.1-3.7-3.1Z"/><path d="M9.2 9.2c.9.1 1.6.6 2 1.4"/><path d="M14.8 9.2c-.9.1-1.6.6-2 1.4"/><path d="M12 10.7v7.8"/></svg>';- const sync = () => {- const open = !panel.classList.contains("collapsed");- btn.classList.toggle("active", open);- btn.setAttribute("aria-expanded", String(open));- btn.setAttribute("aria-label", (open ? "Hide" : "Show") + " context");- btn.title = `${open ? "Hide" : "Show"} context · ${requests.length} request${requests.length === 1 ? "" : "s"}`;- };- btn.onclick = () => {- panel.classList.toggle("collapsed");- sync();- };- sync();- return { btn, sync };- };-- const contextNavButton = (turnSeq, count) => {- const btn = document.createElement("button");- btn.type = "button";- btn.className = "context-icon";- btn.innerHTML =- '<svg viewBox="0 0 24 24" fill="none" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 4.5c-2.1 0-3.7 1.3-3.7 3.1 0 .2 0 .4.1.6A3.6 3.6 0 0 0 6 11.5c0 1 .4 2 1.1 2.6-.1.3-.1.5-.1.8 0 2 1.8 3.6 4 3.6h1.9c2.2 0 4-1.6 4-3.6 0-.3 0-.6-.1-.8.7-.7 1.1-1.6 1.1-2.6 0-1.5-.9-2.8-2.3-3.3 0-.2.1-.4.1-.6 0-1.8-1.6-3.1-3.7-3.1Z"/><path d="M9.2 9.2c.9.1 1.6.6 2 1.4"/><path d="M14.8 9.2c-.9.1-1.6.6-2 1.4"/><path d="M12 10.7v7.8"/></svg>';- btn.setAttribute("aria-label", "View context sent to the model");- btn.title = `View context sent to the model · ${count} request${count === 1 ? "" : "s"}`;- btn.onclick = (ev) => {- ev.stopPropagation();- go({ view: "history", scope, session: sessionId, turn: turnSeq });- };- return btn;- };- function buildToolUnit(unit) {- {- const e = unit.primary;- const ctxBtn = unit.llmReqs?.length ? contextNavButton(unit.llmReqs[0].turnSeq, unit.llmReqs.length) : null;- const callEntry = e.type === "tool_call" ? e : null;- const resultEntry = e.type === "tool_result" ? e : unit.paired;-- let timingSegs = null;- if (callEntry && resultEntry) {- timingSegs = [- [durBySeq.get(callEntry.seq), "model"],- [(resultEntry.createdAt || 0) - (callEntry.createdAt || 0), "exec"],- ];- } else {- timingSegs = [[durBySeq.get((callEntry || resultEntry)?.seq)]];- }- const rendered = renderToolEntry(- callEntry,- resultEntry,- ctxBtn,- stepDurEl(timingSegs),- unit.delivery || null,- );-- const toolTypes = unit.paired ? ["tool_call", "tool_result"] : [e.type];- if (unit.delivery) {- toolTypes.push("outbound_delivery");- if (principalDeliveryIds.has(unit.delivery.deliveryId)) toolTypes.push("principal_delivery");- }- return {- node: rendered.block,- meta: {- block: rendered.block,- entry: e,- types: toolTypes,- hasDelivery: !!unit.delivery,- sync: rendered.sync,- },- };+ let url = m[4].replace(/[.,;!?]+$/, "");+ while (url.endsWith(")") && (url.match(/\)/g) || []).length > (url.match(/\(/g) || []).length)+ url = url.slice(0, -1);+ el = slackEntityNode(url);+ parent.appendChild(el);+ parent.appendChild(document.createTextNode(m[4].slice(url.length)));+ last = re.lastIndex;+ continue;}+ parent.appendChild(el);+ last = re.lastIndex;}+ if (last < text.length) parent.appendChild(document.createTextNode(text.slice(last)));+ }- function buildCompactToolUnit(unit) {- const full = buildToolUnit(unit);- const e = unit.primary;- const callEntry = e.type === "tool_call" ? e : null;- const resultEntry = e.type === "tool_result" ? e : unit.paired;- const callPayload = callEntry?.payload,- resultPayload = resultEntry?.payload;- const block = document.createElement("div");- block.className = "entry tool-entry tool-line-entry";- const row = document.createElement("div");- row.className = "who tool-line";- const caret = document.createElement("span");- caret.className = "tool-line-caret";- caret.textContent = "▸";- const label = document.createElement("span");- label.className = "tool-label";- label.textContent = toolLabelText(toolName(callPayload, resultPayload), callPayload, resultPayload);- const preview = document.createElement("span");- preview.className = "tool-line-preview";- preview.textContent = firstLine(- toolPrimaryText(callPayload, resultPayload, !!callEntry, !!resultEntry) || "",- 240,- );- const timingSegs =- callEntry && resultEntry- ? [- [durBySeq.get(callEntry.seq), "model"],- [(resultEntry.createdAt || 0) - (callEntry.createdAt || 0), "exec"],- ]- : [[durBySeq.get((callEntry || resultEntry)?.seq)]];- const timing = stepDurEl(timingSegs);- const when = document.createElement("span");- when.className = "when";- when.textContent =- resultEntry && callEntry- ? `#${callEntry.seq}→#${resultEntry.seq} · ${fmtTime(callEntry.createdAt)}`- : `#${e.seq} · ${fmtTime(e.createdAt)}`;- row.append(caret, label, preview);- const status = document.createElement("div");- status.className = "meta-row";- toolStatusMeta(toolName(callPayload, resultPayload), resultPayload, !!resultEntry).forEach((item) =>- status.appendChild(item),- );- if (timing) row.appendChild(timing);- row.append(- when,- status,- copyButton("Copy", () => toolCopyText(callEntry, resultEntry)),- );- const sync = () => {- const open = block.classList.contains("open");- caret.textContent = open ? "▾" : "▸";- row.setAttribute("aria-expanded", String(open));- };- row.tabIndex = 0;- row.setAttribute("role", "button");- row.title = "Toggle full tool card";- row.onclick = (ev) => {- if (ev.target.closest(".copy")) return;- block.classList.toggle("open");- sync();- };- row.onkeydown = (ev) => {- if (ev.key === "Enter" || ev.key === " ") {- ev.preventDefault();- block.classList.toggle("open");- sync();- }- };- sync();- block.append(row, full.node);- return { node: block, meta: { ...full.meta, block } };+ function slackParseInline(text, parent, mentions) {+ const re = /`([^`\n]+)`|<([^>\n]+)>|:([a-z0-9_+'-]+):/g;+ let last = 0,+ m;+ while ((m = re.exec(text))) {+ if (m.index > last) slackAppendMrkdwn(text.slice(last, m.index), parent);+ if (m[1] != null) {+ const c = document.createElement("code");+ c.className = "sm-code";+ c.textContent = slackUnescape(m[1]);+ parent.appendChild(c);+ } else if (m[2] != null) parent.appendChild(slackEntityNode(m[2], mentions));+ else if (SLACK_EMOJI[m[3]]) parent.appendChild(document.createTextNode(SLACK_EMOJI[m[3]]));+ else slackAppendMrkdwn(m[0], parent);+ last = re.lastIndex;}- function buildUnit(unit) {- if (unit.kind === "tool") {- return unit.delivery || unit.llmReqs?.length ? buildToolUnit(unit) : buildCompactToolUnit(unit);- }- if (unit.kind === "llm") {- const block = document.createElement("div");- block.className = "entry llm";- const who = document.createElement("div");- who.className = "who";- const role = document.createElement("span");- role.className = "role";- role.textContent = "captured context";- who.append(contextNavButton("orphan", unit.reqs.length), role);- block.appendChild(who);- return { node: block, meta: null };- }- if (unit.kind === "delivery_event") {- const event = unit.event;- const block = document.createElement("div");- block.className = "entry delivery-event-entry";- const who = document.createElement("div");- who.className = "who";- const outbound = event.type === "outbound_delivery";- const isDelivery = outbound || event.type === "principal_delivery";- const label = document.createElement("span");- label.className = "entry-label important";- label.textContent = event.shadow || isDelivery ? deliveryLabel(event) : "Delivery event";- const when = document.createElement("span");- when.className = "when";- let deliveryState = "delivery";- if (event.shadow) deliveryState = "shadow";- else if (event.expiredAt) deliveryState = "dropped";- else if (isDelivery) deliveryState = "delivered";- when.textContent = `${deliveryState} · ${fmtTime(event.createdAt)}`;- const text = event.text || "";- who.append(label);- if (event.shadow) {- const sb = document.createElement("span");- sb.className = "entry-label";- sb.title = "Recorded for observability, never sent to the human (shadow-mode rollout)";- sb.textContent = "not sent";- who.append(sb);- } else if (event.expiredAt) {- const xb = document.createElement("span");- xb.className = "entry-label";- xb.title = "Dropped undelivered — the destination failed permanently or the message aged out";- xb.textContent = "never sent";- who.append(xb);- }- if (isDelivery) who.appendChild(badge(deliverySurfaceLabel(event), "info"));- const provenanceLink = originNodeForDeliveryEvent(event);- if (!outbound && provenanceLink) who.appendChild(provenanceLink);- const originLink = cronLinkForDeliveryEvent(event);- if (originLink) who.appendChild(originLink);- const mirror = slackMirrorRef(event);- if (mirror) {- const ml = navLink("View in Slack mirror ↗", {- view: "slack",- container: mirror.container,- ts: mirror.ts,- });- ml.title = "Jump to this message in the mirrored Slack channel " + mirror.container;- who.appendChild(ml);- }- let contextPanel = null;- let syncContext = null;- if (event.llmRequests?.length) {- contextPanel = renderLlmRequests(event.llmRequests, { embedded: true });- contextPanel.classList.add("inline-context", "collapsed");- const context = contextButton(event.llmRequests, contextPanel);- syncContext = context.sync;- who.insertBefore(context.btn, who.firstChild);- }- who.append(- when,- copyButton("Copy", () => text),- );- const body = document.createElement("pre");- const from = event.destination?.onBehalfOf ? `from ${event.destination.onBehalfOf}\n` : "";- const to = outbound && event.destination?.target ? `to ${event.destination.target}\n` : "";- const originLine =- event.provenance?.fireKey || event.origin?.fireKey- ? `origin ${event.provenance?.fireKey || event.origin.fireKey}\n`- : "";- const recipientLine =- outbound && event.recipientThreadRef ? `recipient thread ${event.recipientThreadRef}\n` : "";- body.textContent = `${from}${to}${originLine}${recipientLine}${text}`.trim();- block.appendChild(who);- if (contextPanel) block.appendChild(contextPanel);- block.appendChild(body);- const files = deliveryFileBadges(event.attachments);- if (files) block.appendChild(files);- return {- node: block,- meta: {- block,- entry: { type: outbound ? "outbound_delivery" : "principal_delivery" },- types: [outbound ? "outbound_delivery" : "principal_delivery"],- sync: syncContext,- },- };- }- const e = unit.entry;- const block = document.createElement("div");- block.className = "entry";- const who = document.createElement("div");- who.className = "who";- const when = document.createElement("span");- when.className = "when";- when.textContent = `#${e.seq} · ${fmtTime(e.createdAt)}`;- const text = payloadText(e.payload);- let body = document.createElement("pre");- if (e.type === "user" && isXmlishText(text)) body = renderXmlish(text);- else if (e.type === "user" || e.type === "assistant") body = renderMarkdown(text);- if (body.tagName === "PRE") body.textContent = text;- if (entryIsNoise(e)) block.classList.add("noise");- if (e.type === "thinking") block.classList.add("thinking-entry");- if (e.type === "user" || e.type === "assistant") block.classList.add("message-entry", e.type + "-entry");- if (origin && e.type === "user" && e.seq === originPromptSeq) block.classList.add("cron-prompt-entry");- if (e.type === "soul" || e.type === "system") block.classList.add("system-entry");- const label = entryLabel(e);- const cronLink = cronLinkForEntry(e);- let syncDisclosure = null;- if (entryIsNoise(e)) {- block.classList.add("collapsed");- const tog = document.createElement("button");- tog.type = "button";- tog.className = "disclosure";- const sync = () => {- const open = !block.classList.contains("collapsed");- tog.textContent = open ? "▾" : "▸";- tog.setAttribute("aria-expanded", String(open));- tog.setAttribute("aria-label", open ? "Collapse entry" : "Expand entry");- tog.title = open ? "Collapse entry" : "Expand entry";- };- syncDisclosure = sync;- tog.onclick = () => {- block.classList.toggle("collapsed");- sync();- };- sync();- who.append(tog, label);+ if (last < text.length) slackAppendMrkdwn(text.slice(last), parent);+ }++ function slackParseText(raw, mentions) {+ const frag = document.createDocumentFragment();+ if (!raw) return frag;+ raw.split("```").forEach((part, i) => {+ if (i % 2 === 1) {+ const pre = document.createElement("pre"),+ code = document.createElement("code");+ code.textContent = slackUnescape(part.replace(/^\n/, "").replace(/\n$/, ""));+ pre.appendChild(code);+ frag.appendChild(pre);} else {- who.append(label);- }- if (cronLink) who.appendChild(cronLink);- who.append(- when,- copyButton("Copy", () => text),- );- if (unit.llmReqs?.length) {- who.insertBefore(contextNavButton(unit.llmReqs[0].turnSeq, unit.llmReqs.length), who.firstChild);+ let quote = null;+ part.split("\n").forEach((line, lineIndex) => {+ const quoted = /^(?:>|>) ?/.test(line);+ if (quoted) {+ if (!quote) {+ quote = document.createElement("blockquote");+ frag.appendChild(quote);+ } else quote.appendChild(document.createTextNode("\n"));+ slackParseInline(line.replace(/^(?:>|>) ?/, ""), quote, mentions);+ } else {+ if (lineIndex && !quote) frag.appendChild(document.createTextNode("\n"));+ quote = null;+ slackParseInline(line, frag, mentions);+ }+ });}+ });+ return frag;+ }+ governanceUI.slackActivity.configure({+ api,+ go,+ urlToState,+ stateToUrl,+ pageShell,+ navLink,+ relTime,+ fmtTime,+ brandSelfLabel,+ slackParseText,+ slackContainerLabel,+ slackContainerScope,+ loadSlackContainers,+ containers: () => slackContainers,+ truncated: () => slackContainersTruncated,+ view: () => view,+ loaded: () => {+ viewLoadedAt.slack = Date.now();+ },+ });+ async function renderSlackMirror(st) {+ return governanceUI.slackActivity.renderSlackMirror(st);+ }+ function deliverySurfaceLabel(event) {+ const type = event?.destination?.type;+ if (type === "principal") return "Slack DM";+ if (type === "slack") return "Slack";+ if (type === "web") return "Web";+ return type || "Unknown surface";+ }- if (e.type !== "user") {- const dur = stepDurEl([[durBySeq.get(e.seq)]]);- if (dur) who.insertBefore(dur, when);- }- block.appendChild(who);- block.appendChild(body);- const carriesFiles =- e.type === "delivery" ||- (e.type === "tool_result" && e.payload && typeof e.payload === "object" && e.payload.tool === "attach");- if (carriesFiles) {- const filesPayload = e.payload && typeof e.payload === "object" ? e.payload.files || [] : [];- const files = deliveryFileBadges(filesPayload);- if (files) block.appendChild(files);- }- return {- node: block,- meta: {- block,- entry: e,- types: [e.type],- sync: () => {- if (syncDisclosure) syncDisclosure();- },- },- };- }+ function deliveryLabel(event) {+ if (event.shadow) return "Shadow delivery";+ return `${deliverySurfaceLabel(event)} delivery`;+ }- const RENDER_WINDOW = 60;+ function slackMirrorRef(event) {+ const d = event?.destination || {};+ if (d.type !== "slack" || !d.editRef || typeof d.target !== "string" || !d.target) return null;+ return { container: d.target.split(":")[0], ts: d.editRef };+ }- const snapStart = (idx) => {- while (idx > 0 && units[idx].kind === "llm") idx--;- return idx;+ async function renderAmbientJudgments(st) {+ return governanceUI.slackActivity.renderAmbientJudgments(st);+ }+ async function renderAckEmojiPicks(st) {+ return governanceUI.slackActivity.renderAckEmojiPicks(st);+ }+ function transcriptServices() {+ return {+ api,+ scope,+ historyKind,+ pageSize: TRANSCRIPT_PAGE_SIZE,+ visibility: transcriptVisibility,+ go,+ stateToUrl,+ pageShell,+ shortName,+ relTime,+ fmtTime,+ webUiAsButton,+ adminErrors,+ errorStripBox,+ plural,+ entryHidden: transcriptEntryHidden,+ renderToolEntry,+ stepDurEl,+ toolName,+ toolLabelText,+ toolPrimaryText,+ toolStatusMeta,+ toolCopyText,+ firstLine,+ copyButton,+ payloadText,+ payloadName,+ isXmlishText,+ renderXmlish,+ renderMarkdown,+ entryIsNoise,+ titleCase,+ brandSelfLabel,+ wakeOriginLabel,+ deliveryLabel,+ deliverySurfaceLabel,+ slackMirrorRef,+ shortId,+ metaChip,+ deliveryFileBadges,+ contextSections,+ requestBody,+ sumCacheUsage,+ cacheMetaItems,+ rawJsonLink,+ fmtContextSize,+ fmtTokens,+ isStablePrefixMiss,+ current: (id, turn) => {+ const st = urlToState();+ return (+ view === "history" && st.session === id && (turn == null ? !st.turn : String(st.turn) === String(turn))+ );+ },+ setObserver: (observer) => {+ transcriptObserver = observer;+ },};- const sentinel = document.createElement("div");- sentinel.className = "load-earlier";- sentinel.setAttribute("aria-hidden", "true");- sentinel.textContent = "Loading earlier messages…";- stream.appendChild(sentinel);- let firstRendered = units.length;-- function finishTop() {- io && io.disconnect();- if (!serverHasMore) {- sentinel.remove();- return;- }- sentinel.classList.add("more");- sentinel.removeAttribute("aria-hidden");- sentinel.textContent = "Load earlier messages";- sentinel.setAttribute("role", "button");- sentinel.tabIndex = 0;- const load = () => showTranscript(sessionId, reqLimit * 4, true);- sentinel.onclick = load;- sentinel.onkeydown = (ev) => {- if (ev.key === "Enter" || ev.key === " ") {- ev.preventDefault();- load();- }- };- }- function materialize(from, to, prepend) {- const frag = document.createDocumentFragment();- for (let i = from; i < to; i++) {- const built = buildUnit(units[i]);- frag.appendChild(built.node);- if (built.meta) entryBlocks.push(built.meta);- }- if (prepend) stream.insertBefore(frag, sentinel.nextSibling);- else stream.appendChild(frag);- }- const io =- "IntersectionObserver" in window- ? new IntersectionObserver(- (obs) => {- if (obs.some((o) => o.isIntersecting)) revealEarlier();- },- { rootMargin: "800px 0px" },- )- : null;- transcriptObserver = io;- function pauseFilteredReveal() {- sentinel.classList.add("more");- sentinel.removeAttribute("aria-hidden");- sentinel.textContent = "Load earlier messages";- sentinel.setAttribute("role", "button");- sentinel.tabIndex = 0;- sentinel.onclick = revealEarlier;- sentinel.onkeydown = (ev) => {- if (ev.key === "Enter" || ev.key === " ") {- ev.preventDefault();- revealEarlier();- }- };- }- function revealEarlier() {- if (firstRendered <= 0) return;- if (io) io.unobserve(sentinel);- sentinel.classList.remove("more");- sentinel.setAttribute("aria-hidden", "true");- sentinel.removeAttribute("role");- sentinel.removeAttribute("tabindex");- sentinel.textContent = "Loading earlier messages…";- sentinel.onclick = null;- sentinel.onkeydown = null;- const from = snapStart(Math.max(0, firstRendered - RENDER_WINDOW));- const prevHeight = document.body.scrollHeight,- prevTop = window.scrollY;- materialize(from, firstRendered, true);- firstRendered = from;- applyTranscriptControls();- const addedHeight = document.body.scrollHeight - prevHeight;- window.scrollTo({ top: prevTop + addedHeight });- if (firstRendered <= 0) finishTop();- else if (io) {- if (addedHeight > 1) io.observe(sentinel);- else pauseFilteredReveal();- }- }- function ensureAllRendered() {- if (firstRendered <= 0) return;- materialize(0, firstRendered, true);- firstRendered = 0;- finishTop();- }- if (io) {- const start = snapStart(Math.max(0, units.length - RENDER_WINDOW));- materialize(start, units.length, false);- firstRendered = start;- if (firstRendered <= 0) finishTop();- else io.observe(sentinel);- } else {- materialize(0, units.length, false);- firstRendered = 0;- finishTop();- }-- if (expand) {- ensureAllRendered();- applyTranscriptControls();- requestAnimationFrame(() => window.scrollTo({ top: 0 }));- } else {- applyTranscriptControls();- requestAnimationFrame(() => window.scrollTo({ top: document.body.scrollHeight }));- }+ }+ async function showTranscript(sessionId, limit, expand) {+ return governanceUI.transcript.show(sessionId, limit, expand, transcriptServices());}function estimateTokens(text) {@@ -19601,60 +11242,6 @@function contextTotal(sections) {return sections.reduce((n, s) => n + s.tokens, 0);}- function contextSectionView(section) {- const wrap = document.createElement("div");- wrap.className = "context-section-view";- const head = document.createElement("div");- head.className = "context-section-head";- const title = document.createElement("strong");- title.textContent = section.label;- const meta = document.createElement("span");- meta.textContent = fmtTokens(section.tokens) + (section.note ? " · " + section.note : "");- const pre = document.createElement("pre");- pre.textContent = section.text || "(empty)";- head.append(title, meta);- wrap.append(head, pre);- return wrap;- }- function showContextSection(host, buttons, section, activeButton) {- buttons.forEach((button) => {- const active = button === activeButton;- button.classList.toggle("active", active);- button.setAttribute("aria-pressed", String(active));- });- host.replaceChildren(contextSectionView(section));- }- function contextOverview(sections, label, onSelect) {- const total = contextTotal(sections);- const root = document.createElement("div");- root.className = "context-overview";- const stack = document.createElement("div");- stack.className = "context-stack";- stack.setAttribute("role", "group");- stack.setAttribute("aria-label", label);- const buttons = [];- sections.forEach((s) => {- const segment = document.createElement("button");- segment.type = "button";- segment.className = "context-segment ctx-" + (s.colorKey || s.key);- segment.style.flexGrow = String(Math.max(s.tokens, 1));- segment.style.flexBasis = total ? Math.max(2, Math.round((s.tokens / total) * 100)) + "%" : "1%";- segment.dataset.tiny = total && s.tokens / total < 0.12 ? "true" : "false";- segment.title = s.label + " · " + fmtTokens(s.tokens) + (s.note ? " · " + s.note : "");- segment.setAttribute("aria-label", segment.title);- segment.setAttribute("aria-pressed", "false");- const name = document.createElement("span");- name.textContent = s.label;- const count = document.createElement("small");- count.textContent = "~" + fmtTokens(s.tokens);- segment.append(name, count);- segment.onclick = () => onSelect(s, segment, buttons);- buttons.push(segment);- stack.appendChild(segment);- });- root.appendChild(stack);- return { node: root, buttons };- }function callCacheUsage(q) {const u = q && q.usage;if (!u || typeof u !== "object") return null;@@ -19771,195 +11358,12 @@});return a;}- function renderContextRequest(q, i, totalRequests) {- const sections = contextSections(requestBody(q), q.transport);- const wrap = document.createElement("div");- wrap.className = "context-request";- const selection = document.createElement("div");- selection.className = "context-selection";- const selectButtons = [];- if (totalRequests > 1) {- const head = document.createElement("div");- head.className = "context-request-head";- const title = document.createElement("strong");- title.textContent = "Request " + (i + 1);- const meta = document.createElement("span");- meta.textContent = (q.model || "?") + " · " + fmtContextSize(q, sections);- head.append(title, meta);- wrap.appendChild(head);- }- if (q.truncated) {- const note = document.createElement("p");- note.className = "context-note";- note.textContent = "Stored payload was truncated.";- wrap.appendChild(note);- }- const renderedOverview = contextOverview(sections, "request context", (section, button, buttons) => {- showContextSection(selection, buttons, section, button);- });- selectButtons.push(...renderedOverview.buttons);- wrap.append(renderedOverview.node, selection);- return { node: wrap };- }function renderLlmRequests(requests, opts = {}) {- const embedded = !!opts.embedded;- const block = document.createElement("div");- block.className = embedded ? "llm context-turn" : "entry collapsed llm context-turn";- const who = document.createElement("div");- who.className = "who";- const tog = document.createElement("button");- tog.type = "button";- tog.className = "disclosure";- const role = document.createElement("span");- role.className = "role";- role.textContent = "sent to model";- const latest = requests[requests.length - 1] || { request: {} };- const latestSections = opts.latestSections || contextSections(requestBody(latest), latest.transport);- const sync = () => {- const open = !block.classList.contains("collapsed");- tog.textContent = open ? "▾" : "▸";- tog.setAttribute("aria-expanded", String(open));- tog.setAttribute("aria-label", open ? "Collapse model context" : "Expand model context");- tog.title = open ? "Collapse model context" : "Expand model context";- };- tog.onclick = () => {- block.classList.toggle("collapsed");- sync();- };- if (!embedded) sync();- if (!embedded) {- who.appendChild(role);- who.insertBefore(tog, who.firstChild);- }- const turnCache = sumCacheUsage(requests);- const stats = document.createElement("div");- stats.className = "context-stats";- stats.append(metaChip((latest.model || "?") + " · " + fmtContextSize(latest, latestSections)));- cacheMetaItems(turnCache).forEach((b) => stats.appendChild(b));- stats.appendChild(rawJsonLink(requests));- who.appendChild(stats);- if (turnCache) block.classList.toggle("cache-miss", isStablePrefixMiss(turnCache));- const details = document.createElement("div");- details.className = "context-details";- requests.forEach((q, i) => {- const rendered = renderContextRequest(q, i, requests.length);- details.appendChild(rendered.node);- });- block.append(who, details);- return block;+ return governanceUI.transcript.requestsPanel(requests, transcriptServices(), opts);}function renderFiles(root, d) {- const all = (d.files || []).slice().sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));- const capped = all.length >= 2000;- const index = orgWideView() && !orgOwnView();-- const files = orgOwnView() ? all.filter((f) => scopeKind(f.scopeId) === "org") : all;- const names = files.map((f) => (f.name || fileName(f.path)).toLowerCase());- const fileRowOf = (f) => ({- icon: fileThumb(f),- name: f.name || fileName(f.path),- preview: index ? shortName(f.scopeId) : "",- time: fmtBytes(f.size || 0) + " · " + relTime(f.createdAt),- });- const list = denseList(files, fileRowOf, downloadFile, "No documents saved yet.");- const noMatch = document.createElement("p");- noMatch.className = "empty hidden";- noMatch.textContent = "No files match.";-- let searchWrap = null;- let searchAllFiles = null;- if (capped) {- searchWrap = document.createElement("div");- searchWrap.className = "hidden";- let timer = 0;- let reqId = 0;- searchAllFiles = (q) => {- clearTimeout(timer);- reqId += 1;- if (!q) {- searchWrap.classList.add("hidden");- searchWrap.textContent = "";- list.classList.remove("hidden");- return;- }- const req = reqId;- timer = setTimeout(async () => {- const r = await api(- "GET",- "/api/files?scope=" + encodeURIComponent(scope) + "&q=" + encodeURIComponent(q),- ).catch(() => null);- if (req !== reqId) return;- if (!r || !r.ok) {- searchWrap.classList.add("hidden");- searchWrap.textContent = "";- list.classList.remove("hidden");- const anyLocalHit = [...list.children].some((el) => !el.classList.contains("hidden"));- noMatch.classList.toggle("hidden", !list.children.length || anyLocalHit);- return;- }- const matched = ((r.data && r.data.files) || [])- .slice()- .sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));- const shown = orgOwnView() ? matched.filter((f) => scopeKind(f.scopeId) === "org") : matched;- searchWrap.textContent = "";- searchWrap.appendChild(denseList(shown, fileRowOf, downloadFile, "No files match."));- searchWrap.classList.remove("hidden");- list.classList.add("hidden");- noMatch.classList.add("hidden");- }, 250);- };- }-- let scopeWrap = null;- if (index) {- scopeWrap = document.createElement("div");- scopeWrap.className = "file-scope-index";- scopeWrap.appendChild(- scopeIndexList(all, {- latestOf: (f) => f.createdAt || 0,- noun: "file",- empty: "No documents saved yet.",- }),- );- if (capped) {- const note = document.createElement("p");- note.className = "empty";- note.textContent =- "Only the newest 2,000 files are indexed, so a scope with only older files won't appear.";- scopeWrap.appendChild(note);- }- }- const fileWrap = document.createElement("div");- fileWrap.append(list, ...(searchWrap ? [searchWrap] : []), noMatch);- const uploadBox = fileUploadBox();- wireScopeSearch({- key: "files",- indexWrap: scopeWrap,- listWrap: fileWrap,- rows: [...list.children],- names,- noMatch,- total: files.length,- ...(searchAllFiles ? { onQuery: searchAllFiles } : {}),- shell: {- ...(index- ? {}- : {- back: {- label: "← Files",- onClick: () => go({ view: "files", scope: "org:" + orgId, own: null, session: null, page: 1 }),- },- }),- title: index ? VIEW_TITLE.files : shortName(scope),- actions: [uploadBox],- count: files.length ? plural(files.length, "file") : "",- },- placeholder: index ? "Search all files…" : "Search files…",- });- const card = bareDataCard(fileWrap);- if (scopeWrap) card.querySelector(".body").prepend(scopeWrap);- root.appendChild(card);+ governanceUI.artifacts.files(root, d, artifactContext());}function fileThumb(f) {const box = document.createElement("span");@@ -20005,44 +11409,7 @@}function renderLive(root, d) {- const runs = d.runs || [];- const failed = runs.filter((r) => r.status === "failed").length;- const done = runs.filter((r) => r.status === "done").length;- root.appendChild(- kpis([- [d.active ?? 0, "Active now"],- [runs.length, "Recent runs"],- [failed, "Failed"],- [done, "Done"],- ]),- );- const rows = runs.map((r) => [- { node: stacked("Run " + shortId(r.id), r.threadRef || "no thread"), cls: "mono" },- nodeCell(statusBadge(r.status)),- r.sessionScope ? scopeCell(r.sessionScope) : { text: "-", cls: "mono" },- nodeCell(typeBadge(r.sessionType)),- nodeCell(- badge(`${r.attempts}/${r.maxAttempts}`, r.status === "failed" || r.attempts > 1 ? "warn" : "muted"),- "num",- ),- { text: r.workerId || "-", cls: "mono" },- { text: fmtDuration(r.startedAt || r.createdAt, r.finishedAt), cls: "num" },- {- text:- r.leaseExpiresAt && (r.status === "running" || r.status === "pending") ? fmtTime(r.leaseExpiresAt) : "-",- cls: "num",- },- { text: r.startedAt ? fmtTime(r.startedAt) : "-", cls: "num" },- ]);- root.appendChild(- bareDataCard(- table(- ["Run", "Status", "Scope", "Type", "Attempts", "Worker", "Duration", "Lease", "Started"],- rows,- "No runs.",- ),- ),- );+ governanceUI.artifacts.live(root, d, artifactContext());}refresh();diff --git a/plugins/admin/src/governance-bundle.ts b/plugins/admin/src/governance-bundle.tsnew file mode 100644index 000000000..512045ed3--- /dev/null+++ b/plugins/admin/src/governance-bundle.ts@@ -0,0 +1,17 @@+import { buildSync } from "esbuild";+import { fileURLToPath } from "node:url";++export function buildGovernanceUI(): string {+ const result = buildSync({+ entryPoints: [fileURLToPath(new URL("../ui/admin.ts", import.meta.url))],+ bundle: true,+ write: false,+ format: "iife",+ globalName: "governanceUI",+ platform: "browser",+ target: "es2022",+ minify: true,+ legalComments: "none",+ });+ return result.outputFiles[0]!.text.replace(/<\/script/gi, "<\\/script");+}diff --git a/plugins/admin/src/index.ts b/plugins/admin/src/index.tsindex cc1ed2640..c81d5a8a9 100644--- a/plugins/admin/src/index.ts+++ b/plugins/admin/src/index.ts@@ -1,3 +1,4 @@+import { buildGovernanceUI } from "./governance-bundle.ts";import { reportBackendError } from "../../chassis/src/error-reporting.ts";import "./instrument.ts";import { createServer, type IncomingMessage, type ServerResponse } from "node:http";@@ -32,6 +33,7 @@ function signedHeaders(method: string, corePath: string, rawBody: string): Recorconst BASE_HTML = readFileSync(join(dirname(fileURLToPath(import.meta.url)), "../public/index.html"), "utf8").replaceAll("__ADMIN_BASE__", () => ADMIN_BASE_PATH)+ .replace('"__GOVERNANCE_UI__";', () => buildGovernanceUI()).replace("<style data-admin-components></style>",() =>diff --git a/plugins/admin/test/admin-source.ts b/plugins/admin/test/admin-source.tsnew file mode 100644index 000000000..ea913b369--- /dev/null+++ b/plugins/admin/test/admin-source.ts@@ -0,0 +1,30 @@+import { readFileSync } from "node:fs";+import { JSDOM } from "jsdom";+import { buildGovernanceUI } from "../src/governance-bundle.ts";++export function readAdminSource(): string {+ const shell = readFileSync(new URL("../public/index.html", import.meta.url), "utf8");+ const dom = new JSDOM(shell, { runScripts: "outside-only" });+ dom.window.structuredClone = structuredClone;+ try {+ dom.window.eval(buildGovernanceUI() + ";window.governanceUI = governanceUI; governanceUI.mountCards();");+ return (+ shell+ .replace(/<template data-onboarding-ui="([^"]+)"><\/template>/g, (_, kind) => {+ const selectors: Record<string, string> = {+ steps: ".setup-grid",+ provider: "#onboarding-model-save",+ registry: "#model-registry-save",+ };+ const element = dom.window.document.querySelector(selectors[kind])!;+ return (kind === "steps" ? element : element.closest("section")!).outerHTML;+ })+ .replace(/<template data-(?:governance|settings|integrations)-card="([^"]+)"><\/template>/g, (_, id) => {+ const card = dom.window.document.getElementById(id)!;+ return card.outerHTML.replace(/class="\s+/g, 'class="').replace(/\s+" id=/g, '" id=');+ }) + dom.window.eval('governanceUI.createCard("card-governance-org-ambient").outerHTML')+ );+ } finally {+ dom.window.close();+ }+}diff --git a/plugins/admin/test/artifacts-lit.test.ts b/plugins/admin/test/artifacts-lit.test.tsnew file mode 100644index 000000000..dbab7c63c--- /dev/null+++ b/plugins/admin/test/artifacts-lit.test.ts@@ -0,0 +1,352 @@+import assert from "node:assert/strict";+import test from "node:test";+import { buildSync } from "esbuild";+import { JSDOM } from "jsdom";++const source = buildSync({+ entryPoints: [new URL("../ui/artifacts.ts", import.meta.url).pathname],+ bundle: true,+ write: false,+ format: "iife",+ globalName: "artifacts",+ platform: "browser",+}).outputFiles[0].text;+const packsSource = buildSync({+ entryPoints: [new URL("../ui/artifacts-skills.ts", import.meta.url).pathname],+ bundle: true,+ write: false,+ format: "iife",+ globalName: "skillUI",+ platform: "browser",+}).outputFiles[0].text;+function fixture() {+ const dom = new JSDOM('<div id="shellbar"></div><main></main>', {+ runScripts: "outside-only",+ url: "http://localhost/admin/files",+ pretendToBeVisual: true,+ });+ dom.window.eval(source + ";window.artifacts = artifacts;");+ dom.window.eval(packsSource + ";window.skillUI = skillUI;");+ dom.window.HTMLElement.prototype.scrollIntoView = () => {};+ const root = dom.window.document.querySelector("main")!;+ const c: Record<string, any> = {+ scope: "personal:alice",+ orgId: "acme",+ view: "files",+ index: false,+ own: false,+ apiBase: "",+ scopeKind: (s: string) => s.split(":")[0],+ shortName: (s: string) => s,+ dirLabel: (s: string) => s,+ plural: (n: number, noun: string) => `${n} ${noun}${n === 1 ? "" : "s"}`,+ relTime: () => "just now",+ fmtTime: () => "Today",+ fmtHistoryTime: () => "Today",+ fmtBytes: (n: number) => `${n} B`,+ fileKind: () => "file",+ fileName: (s: string) => s,+ pageShell: (value: any) => {+ c.shell = value;+ },+ memoryDraft: () => c.draft ?? null,+ setMemoryDraft: (draft: string | null) => {+ c.draft = draft;+ },+ api: async () => ({ ok: true, data: {} }),+ go: () => {},+ reload: () => {},+ invalidate: () => {},+ stateToUrl: (s: any) => "/admin/" + s.view + "?scope=" + s.scope,+ shortId: (s: string) => s,+ titleCase: (s: string) => s,+ openScopeRow: () => {},+ fileSha256: async () => "hash",+ uploadErrorMessage: (s: string) => s,+ firstLine: (s: string) => s,+ cronName: (s: any) => s.title || s.id,+ shortSchedule: () => "Daily",+ fmtSchedule: () => "Every day",+ destinationSummary: () => "None",+ destinationDetails: () => "",+ setCronEditing: () => {},+ scopeRows: () => [],+ packRepoLabel: (s: string) => s,+ buildScopeMultiSelect: (_choices: any, selected: Set<string>, onChange: () => void) => {+ c.selectedScopes = selected;+ c.changeScopes = onChange;+ return dom.window.document.createElement("div");+ },+ };+ return { dom, root, c, ui: (dom.window as any).artifacts, skills: (dom.window as any).skillUI };+}+const tick = () => new Promise((resolve) => setTimeout(resolve, 0));++test("memory drafts preserve newer edits through an in-flight save", async () => {+ const { dom, root, c, ui } = fixture();+ let complete: (value: any) => void = () => {};+ const calls: any[] = [];+ c.api = (...args: any[]) => {+ calls.push(args);+ return new Promise((resolve) => {+ complete = resolve;+ });+ };+ ui.memory(root, { content: "saved" }, c);+ const input = root.querySelector("textarea")!;+ input.value = "submitted";+ input.dispatchEvent(new dom.window.Event("input"));+ root.querySelector("button")!.click();+ input.value = "newer draft";+ input.dispatchEvent(new dom.window.Event("input"));+ complete({ ok: true });+ await tick();+ assert.equal(calls[0][1], "/api/memory?scope=personal%3Aalice");+ assert.equal(calls[0][2].content, "submitted");+ assert.equal(c.draft, "newer draft");+ assert.equal(root.querySelector("textarea"), input);+ assert.equal(root.querySelector("#st-memory")!.textContent, "Unsaved changes");+ dom.window.close();+});++test("files search renders from query data and preserves keyboard opening", () => {+ const { dom, root, c, ui } = fixture();+ let opened = "";+ c.downloadFile = (row: any) => {+ opened = row.id;+ };+ ui.files(+ root,+ {+ files: [+ { id: "a", name: "alpha.txt", createdAt: 1 },+ { id: "b", name: "beta.txt", createdAt: 2 },+ ],+ },+ c,+ );+ c.shell.search.onInput("alpha");+ assert.equal(root.querySelectorAll(".dense-row").length, 1);+ root.querySelector(".dense-row")!.dispatchEvent(new dom.window.KeyboardEvent("keydown", { key: "Enter" }));+ assert.equal(opened, "a");+ c.shell.search.onInput("missing");+ assert.match(root.textContent!, /No files match/);+ dom.window.close();+});++test("scope indexes hide full artifact lists until searching", () => {+ const { dom, root, c, ui } = fixture();+ c.index = true;+ c.deploymentHref = () => "https://example.com/app";+ ui.deployments(root, { deployments: [{ id: "app", name: "App", ownerScopeId: "personal:alice" }] }, c);+ assert.equal(root.querySelectorAll(".dense-list").length, 2);+ c.shell.search.onInput("App");+ const link = root.querySelector<HTMLAnchorElement>('.dense-row[target="_blank"]')!;+ assert.equal(link.href, "https://example.com/app");+ assert.equal(link.rel, "noopener");+ dom.window.close();+});++test("cron destination draft derives placeholders, disabled fields and API payload", async () => {+ const { dom, root, c, ui } = fixture();+ c.cron = "job";+ const calls: any[] = [];+ c.api = async (...args: any[]) => {+ calls.push(args);+ return { ok: true, data: { sessions: [] } };+ };+ ui.crons(root, { crons: [{ id: "job", title: "Daily", ownerScopeId: c.scope }] }, c);+ [...root.querySelectorAll("button")].find((b) => b.textContent?.trim() === "Edit destination")!.click();+ const select = root.querySelector("select")!;+ select.value = "principal";+ select.dispatchEvent(new dom.window.Event("change"));+ const inputs = root.querySelectorAll<HTMLInputElement>("input");+ assert.equal(inputs[0].placeholder, "principal id");+ assert.equal(inputs[2].disabled, false);+ inputs[0].value = "alice";+ inputs[0].dispatchEvent(new dom.window.Event("input"));+ inputs[2].value = "bob";+ inputs[2].dispatchEvent(new dom.window.Event("input"));+ [...root.querySelectorAll("button")].find((b) => b.textContent?.trim() === "Save destination")!.click();+ await tick();+ const put = calls.find((args) => args[0] === "PUT");+ assert.equal(+ JSON.stringify(put[2]),+ JSON.stringify({ destination: { type: "principal", target: "alice", onBehalfOf: "bob" } }),+ );+ dom.window.close();+});++test("stale async cron renders cannot replace a different page", async () => {+ const { dom, root, c, ui } = fixture();+ c.cron = "job";+ let complete: (value: any) => void = () => {};+ c.api = () =>+ new Promise((resolve) => {+ complete = resolve;+ });+ ui.crons(root, { crons: [{ id: "job", title: "Daily", ownerScopeId: c.scope }] }, c);+ root.replaceChildren(dom.window.document.createTextNode("New page"));+ complete({ ok: true, data: { sessions: [] } });+ await tick();+ assert.equal(root.textContent, "New page");+ dom.window.close();+});++test("pack registration draft is collected from state with advanced fields", async () => {+ const { dom, root, c, skills } = fixture();+ const calls: any[] = [];+ c.api = async (...args: any[]) => {+ calls.push(args);+ return { ok: true };+ };+ skills.packs(root, [], c);+ const fields = root.querySelectorAll<HTMLInputElement>("input");+ for (const [i, value] of ["https://example.com/skills", "main", "private/*, drafts/*", "deploy-token"].entries()) {+ fields[i].value = value;+ fields[i].dispatchEvent(new dom.window.Event("input"));+ }+ assert.match(root.querySelector(".linkish")!.textContent!, /Advanced •/);+ [...root.querySelectorAll("button")].find((b) => b.textContent?.trim() === "Register")!.click();+ await tick();+ assert.equal(calls[0][2].ref, "main");+ assert.equal(JSON.stringify(calls[0][2].config.exclude), '["private/*","drafts/*"]');+ dom.window.close();+});++test("pack selection follows target scopes and supports partial imports", async () => {+ const { dom, root, c, skills } = fixture();+ const calls: any[] = [];+ c.api = async (...args: any[]) => {+ calls.push(args);+ return args[0] === "GET"+ ? {+ ok: true,+ data: {+ candidates: [+ { upstreamName: "a", eligible: true, importedScopes: ["org:acme"] },+ { upstreamName: "b", eligible: true, importedScopes: [] },+ ],+ },+ }+ : { ok: true, data: { imported: [] } };+ };+ await skills.browsePack({ id: "pack", url: "example" }, root, c);+ assert.equal(root.querySelector<HTMLInputElement>('[data-name="a"]')!.disabled, true);+ c.selectedScopes.add("personal:alice");+ c.changeScopes();+ assert.equal(root.querySelector<HTMLInputElement>('[data-name="a"]')!.disabled, false);+ const b = root.querySelector<HTMLInputElement>('[data-name="b"]')!;+ b.checked = false;+ b.dispatchEvent(new dom.window.Event("change"));+ [...root.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Import selected")!.click();+ await tick();+ const post = calls.find((args) => args[0] === "POST");+ assert.equal(JSON.stringify(post[2].selected), '["a"]');+ assert.equal(JSON.stringify(post[2].scopeIds), '["org:acme","personal:alice"]');+ dom.window.close();+});++test("cancelled cron destination edits restore the saved destination on reopen", () => {+ const { dom, root, c, ui } = fixture();+ c.cron = "job";+ ui.crons(+ root,+ {+ crons: [+ { id: "job", title: "Daily", ownerScopeId: c.scope, destination: { type: "principal", target: "alice" } },+ ],+ },+ c,+ );+ const click = (text: string) =>+ [...root.querySelectorAll("button")].find((button) => button.textContent?.trim() === text)!.click();+ click("Edit destination");+ assert.equal(root.querySelector("select")!.value, "principal");+ const target = root.querySelector<HTMLInputElement>('input[name="cron-target"]')!;+ target.value = "bob";+ target.dispatchEvent(new dom.window.Event("input"));+ click("Cancel");+ click("Edit destination");+ assert.equal(root.querySelector<HTMLInputElement>('input[name="cron-target"]')!.value, "alice");+ dom.window.close();+});++test("cron destination saves preserve edits made while the request is pending", async () => {+ const { dom, root, c, ui } = fixture();+ c.cron = "job";+ let complete: (value: any) => void = () => {};+ let reloads = 0;+ c.reload = () => {+ reloads++;+ };+ c.api = async (method: string) =>+ method === "PUT"+ ? new Promise((resolve) => {+ complete = resolve;+ })+ : { ok: true, data: { sessions: [] } };+ ui.crons(root, { crons: [{ id: "job", title: "Daily", ownerScopeId: c.scope }] }, c);+ [...root.querySelectorAll("button")].find((b) => b.textContent?.trim() === "Edit destination")!.click();+ const target = root.querySelector<HTMLInputElement>('input[name="cron-target"]')!;+ target.value = "submitted";+ target.dispatchEvent(new dom.window.Event("input"));+ [...root.querySelectorAll("button")].find((b) => b.textContent?.trim() === "Save destination")!.click();+ target.value = "newer";+ target.dispatchEvent(new dom.window.Event("input"));+ complete({ ok: true });+ await tick();+ assert.equal(root.querySelector<HTMLInputElement>('input[name="cron-target"]')!.value, "newer");+ assert.equal(reloads, 0);+ assert.equal(+ [...root.querySelectorAll("button")].find((b) => b.textContent?.trim() === "Save destination")!.disabled,+ false,+ );+ dom.window.close();+});++test("skill removal network failures keep the current view and report an error", async () => {+ const { dom, c, skills } = fixture();+ let reloads = 0;+ let message = "";+ dom.window.confirm = () => true;+ dom.window.alert = (value) => {+ message = String(value);+ };+ c.reload = () => {+ reloads++;+ };+ c.api = async () => {+ throw new Error("offline");+ };+ await skills.removeSkill({ id: "skill", ownerScopeId: c.scope }, c);+ assert.equal(reloads, 0);+ assert.equal(message, "Could not remove skill.");+ dom.window.close();+});++test("pack registration preserves newer edits after its request completes", async () => {+ const { dom, root, c, skills } = fixture();+ let complete: (value: any) => void = () => {};+ let reloads = 0;+ c.reload = () => {+ reloads++;+ };+ c.api = () =>+ new Promise((resolve) => {+ complete = resolve;+ });+ skills.packs(root, [], c);+ const input = root.querySelector<HTMLInputElement>("input")!;+ input.value = "https://example.com/submitted";+ input.dispatchEvent(new dom.window.Event("input"));+ [...root.querySelectorAll("button")].find((b) => b.textContent?.trim() === "Register")!.click();+ input.value = "https://example.com/newer";+ input.dispatchEvent(new dom.window.Event("input"));+ complete({ ok: true });+ await tick();+ assert.equal(root.querySelector<HTMLInputElement>("input")!.value, "https://example.com/newer");+ assert.equal(reloads, 0);+ assert.match(root.querySelector(".status")!.textContent!, /newer changes/);+ dom.window.close();+});diff --git a/plugins/admin/test/auto-flagger.test.ts b/plugins/admin/test/auto-flagger.test.tsindex 8301a6bd7..69987821e 100644--- a/plugins/admin/test/auto-flagger.test.ts+++ b/plugins/admin/test/auto-flagger.test.ts@@ -1,13 +1,14 @@+import { load, states } from "../ui/governance-state.ts";import assert from "node:assert/strict";-import { readFileSync } from "node:fs";+import { readAdminSource } from "./admin-source.ts";import test from "node:test";import vm from "node:vm";-const html = readFileSync(new URL("../public/index.html", import.meta.url), "utf8");+const html = readAdminSource();test("org governance exposes the Auto quarantine rubric and replay controls", () => {assert.ok(html.includes('id="card-auto-flagger"'), "Auto flagger editor must exist");- assert.match(html, /class="card sv-governance hidden" id="card-auto-flagger"/);+ assert.match(html, /id="card-auto-flagger"/);for (const id of ["auto-flagger-harness","auto-flagger-model",@@ -19,9 +20,8 @@ test("org governance exposes the Auto quarantine rubric and replay controls", ()]) {assert.ok(html.includes(`id="${id}"`), `${id} must exist`);}- assert.match(html, /scope\.startsWith\("org:"\) && "autoFlagger" in/);- assert.match(html, /r\.data\.autoFlagger \|\| r\.data\.autoFlaggerDefault/);- assert.match(html, /"auto-flagger": \(\) => \(\{/);++ assert.match(html, /governanceUI.collect\(key\)/);assert.match(html, /"auto-flagger": "st-auto-flagger"/);assert.match(html, /function autoFlaggerTestSummary\(data\)/);});@@ -66,6 +66,8 @@ class Element {function fixture(data: Record<string, unknown> = {}, scope = "org:example") {const elements: Record<string, Element> = {};const context = vm.createContext({+ governanceReq: 1,+ governanceUI: { collect: () => ({ harnessId: "pi", modelId: "model-a", rubric: "Default rubric" }) },refreshModelChoices: [],scope,scopeChanged: true,@@ -91,54 +93,40 @@ const loadData = {claude: [{ id: "model-c", name: "C" }],},};-const loadSource = slice("const showAutoFlagger =", "const showGrantModes =");+const handlersSource = slice('$("auto-flagger-test").onclick =', 'document.querySelectorAll("[data-save]").forEach');const summarySource = slice("function autoFlaggerTestSummary(data)", "function sectionButton(key)");-test("loading or restoring defaults replaces a previous model selection", () => {- const { elements, context } = fixture(loadData);- vm.runInContext(`{${loadSource}}`, context);- assert.equal(elements["auto-flagger-model"].value, "model-a");- elements["auto-flagger-model"].value = "model-b";- vm.runInContext(`{${loadSource}}`, context);- assert.equal(elements["auto-flagger-model"].value, "model-a");- assert.equal(elements["auto-flagger-rubric"].value, "Default rubric");- elements["auto-flagger-harness"].value = "claude";- elements["auto-flagger-harness"].oninput!();- assert.equal(elements["auto-flagger-model"].value, "model-c");+test("loading defaults replaces a previous model and harness selection", () => {+ load(loadData, "org:example");+ const state = states.get("auto-flagger")!;+ state.change("auto-flagger-model", "model-b");+ load(loadData, "org:example");+ assert.equal(state.draft.modelId, "model-a");+ state.change("auto-flagger-harness", "claude");+ assert.equal(state.draft.modelId, "model-c");});--test("a saved flagger outside the current catalog is displayed, not silently replaced", () => {- const { elements, context } = fixture({- ...loadData,- autoFlagger: { harnessId: "codex", modelId: "saved-model", rubric: "Saved rubric" },- });- vm.runInContext(`{${loadSource}}`, context);- assert.equal(elements["auto-flagger-harness"].value, "codex");- assert.ok(elements["auto-flagger-harness"].options.some((o) => o.value === "codex"));- assert.equal(elements["auto-flagger-model"].value, "saved-model");- assert.ok(elements["auto-flagger-model"].options.some((o) => o.value === "saved-model"));- assert.equal(elements["auto-flagger-rubric"].value, "Saved rubric");+test("unavailable configured flagger stays selectable", () => {+ load({ ...loadData, autoFlagger: { harnessId: "codex", modelId: "saved-model", rubric: "Saved" } }, "org:example");+ const state = states.get("auto-flagger")!;+ assert.equal(state.draft.modelId, "saved-model");+ assert.ok(state.models.some((model) => model.id === "saved-model"));});--test("the card is org-only and follows the current governance layout", () => {- for (const [scope, data] of [- ["personal:example", loadData],- ["org:example", {}],- ] as const) {- const { elements, context } = fixture(data, scope);- vm.runInContext(`{${loadSource}}`, context);- assert.ok(elements["card-auto-flagger"].classes.has("hidden"));- }- assert.match(- html,- /\$\("card-security-posture"\),\s*\$\("card-auto-flagger"\),\s*\$\("card-sharing-posture"\),\s*governanceAmbient/,- );+test("flagger is visible only for org payloads that support it", () => {+ load(loadData, "personal:example");+ assert.equal(states.get("auto-flagger")!.available, false);+ load({}, "org:example");+ assert.equal(states.get("auto-flagger")!.available, false);});test("test sends an unsaved draft and comparison window without saving it", async () => {const { elements, context } = fixture(loadData);- vm.runInContext(`{${loadSource}}\n${summarySource}\n${handlersSource}`, context);+ vm.runInContext(`${summarySource}\n${handlersSource}`, context);+ elements["auto-flagger-harness"] = new Element();+ elements["auto-flagger-harness"].value = "pi";+ elements["auto-flagger-model"] = new Element();+ elements["auto-flagger-model"].value = "model-a";+ elements["auto-flagger-rubric"] = new Element();elements["auto-flagger-window"] = new Element();elements["auto-flagger-window"].value = "25";elements["auto-flagger-compare"] = new Element();@@ -176,8 +164,15 @@ test("reset clears the override and does not reload a different scope after naviconst { elements, context } = fixture(loadData);vm.runInContext(handlersSource, context);let reloads = 0;- context.loadScope = async () => {+ context.refreshPolicySetting = async (+ _key: string,+ _scope: string,+ _generation: number,+ _draft: string,+ message: string,+ ) => {reloads++;+ (elements["st-auto-flagger"] ??= new Element()).textContent = message;};context.api = async (method: string, path: string, body: unknown) => {assert.equal(method, "PUT");diff --git a/plugins/admin/test/branding.test.ts b/plugins/admin/test/branding.test.tsindex 51b37717a..b4d4b1162 100644--- a/plugins/admin/test/branding.test.ts+++ b/plugins/admin/test/branding.test.ts@@ -1,3 +1,4 @@+import { readAdminSource } from "./admin-source.ts";import { test } from "node:test";import { createHash } from "node:crypto";import assert from "node:assert/strict";@@ -88,8 +89,12 @@ test("the brand icon is a CSS variable the org can point at its own image", () =/var\(--brand-mark-image, url\("\.\/brand-mark\.svg"\)\)/,"the badge paints from the variable and falls back to the shipped mark",);- assert.match(shell, /id="branding-mark-url"/, "the admin form can set it");- assert.match(shell, /markUrl: \$\("branding-mark-url"\)\.value\.trim\(\)/, "and saves it with the rest of branding");+ assert.match(readAdminSource(), /id="branding-mark-url"/, "the admin form can set it");+ assert.match(+ shell,+ /governanceUI.settings.load\(r.data, scope, "branding"\)/,+ "loads the state-driven branding editor",+ );});test("design system routes embed the shared component library and retain the script CSP", async () => {diff --git a/plugins/admin/test/default-view.test.ts b/plugins/admin/test/default-view.test.tsindex a3f5c0526..c87ae8ac0 100644--- a/plugins/admin/test/default-view.test.ts+++ b/plugins/admin/test/default-view.test.ts@@ -1,9 +1,12 @@+import { SettingsState, load as loadSettings, states as settingsStates } from "../ui/settings.ts";+import { CredentialState } from "../ui/settings-credentials.ts";+import { GovernanceState, load, states } from "../ui/governance-state.ts";import assert from "node:assert/strict";-import { readFileSync } from "node:fs";+import { readAdminSource } from "./admin-source.ts";import test from "node:test";import vm from "node:vm";-const html = readFileSync(new URL("../public/index.html", import.meta.url), "utf8");+const html = readAdminSource();function resolvedDisplay(classes: string[]) {const styles = [...html.matchAll(/<style>([\s\S]*?)<\/style>/g)].map((m) => m[1]).join("\n");@@ -51,7 +54,7 @@ test("admin shell groups control, logs, and artifacts like the reorganization",assert.ok(sections);const actual = JSON.parse(JSON.stringify(vm.runInNewContext(sections)));assert.deepEqual(actual, [- { views: ["governance", "models", "credentials", "connectors", "customize", "users"] },+ { views: ["governance", "models", "credentials", "connectors", "slack-settings", "customize", "users"] },{ label: "Logs", views: ["history", "slack", "judgments", "errors", "audit", "egress"] },{ label: "Artifacts", views: ["files", "skills", "memory", "deployments", "crons"] },{ views: ["design-system"] },@@ -65,7 +68,7 @@ test("admin shell groups control, logs, and artifacts like the reorganization",test("deployment management is presented as Apps", () => {assert.match(html, /deployments: "Apps"/);- assert.match(html, /Search all apps…/);+ assert.match(html, /governanceUI\.artifacts\.deployments\(root, d, artifactContext\(\)\)/);assert.doesNotMatch(html, /deployments: "Deployments"/);});@@ -78,26 +81,20 @@ test("admin shell defaults bare admin URLs to org history", () => {);});-test("connector setup uses the live catalog and shows exact provider and callback links", () => {- assert.match(html, /api\("GET", "\/api\/connector-catalog"\)/);- assert.match(html, /setupGuide\.url/);- assert.match(html, /location\.origin \+ "\/v1\/connectors\/oauth\/" \+ connector\.redirectPath/);- assert.match(html, /target="_blank"/);- assert.match(html, /Configured by deployment secrets/);- assert.match(html, /item\.configured/);- assert.doesNotMatch(html, /const CONNECTOR_CATALOG = \[/);+test("connector setup uses reactive forms with write-only Slack credentials", () => {+ assert.match(html, /governanceUI.integrations.configure/);+ assert.match(html, /id="conn-client-secret"/);+ assert.match(html, /type="password"/);assert.match(html, /id="slack-bot-token"/);- assert.match(html, /api\("PUT", "\/api\/slack-installation"/);- assert.match(html, /Use your own Slack app/);+ assert.match(html, /Set up Slack/);});test("temporary onboarding covers model credentials, Slack, and OAuth setup", () => {assert.match(html, /view-onboarding/);assert.match(html, /Model provider/);assert.match(html, /OpenRouter/);- assert.match(html, /api\("GET", "\/api\/model-providers"\)/);- assert.match(html, /api\("PUT", "\/api\/model-providers\/" \+ encodeURIComponent\(provider\)/);- assert.match(html, /models\.data\.models/);+ assert.match(html, /governanceUI\.onboarding\.configure/);+ assert.match(html, /return governanceUI\.onboarding\.load\(\)/);assert.doesNotMatch(html, /const ONBOARDING_MODELS/);assert.match(html, /viewLoadedAt\.onboarding = Date\.now\(\)/);assert.match(html, /data-onboarding-target="slack"/);@@ -109,7 +106,7 @@ test("admin shell addresses views by path, not a ?view= query param", () => {assert.doesNotMatch(html, /p\.set\("view", st\.view\)/);assert.match(html,- /const raw = p\.get\("setup"\) === "slack" \|\| slackStep \? "connectors" : p\.get\("view"\) \|\| fromPath;/,+ /const raw = p\.get\("setup"\) === "slack" \|\| slackStep \? "slack-settings" : p\.get\("view"\) \|\| fromPath;/,);assert.doesNotMatch(html, /st\.view !== "governance"/);});@@ -134,24 +131,9 @@ test("mobile admin navigation keeps the active section visible and controls toucassert.match(html, /safe-area-inset-bottom/);});-test("admin history previews quote the first message instead of saying started", () => {- assert.equal((html.match(/\?\s*"> "\s*\+\s*s\.firstMessage\s*:\s*"created "/g) || []).length, 1);- assert.doesNotMatch(html, /\? "started " \+ s\.firstMessage : "created "/);-});-test("transcript visibility controls stay in the sticky header and filter lazy-rendered entries", () => {- const transcript = html.slice(html.indexOf("async function showTranscript("));assert.match(html, /id="header-controls" aria-label="Page controls"/);- assert.match(html, /checkbox\("thinking", "thinking"\)/);- assert.match(html, /checkbox\("tool results", "toolResults"\)/);- assert.match(html, /materialize\(from, firstRendered, true\);[\s\S]*applyTranscriptControls\(\);/);- assert.match(html, /applyTranscriptControls\(\);\s*const addedHeight = document\.body\.scrollHeight - prevHeight;/);- assert.match(html, /if \(addedHeight > 1\) io\.observe\(sentinel\);\s*else pauseFilteredReveal\(\);/);- assert.ok(- transcript.indexOf("renderTranscriptHeaderControls(() => applyTranscriptControls());") <- transcript.indexOf("const r = await api("),- "controls render before the transcript request",- );+ assert.match(html, /governanceUI.transcript.show/);assert.match(html, /\.header-check \{[^}]*min-height: 44px/);assert.match(html,@@ -175,19 +157,24 @@ test("transcript filters hide diagnostics without hiding folded delivery evidenc});test("governance posture saves refresh only the saved card", () => {- const reloads = html.match(/const SAVE_RELOADS = new Set\(\[[^\n]+/)?.[0] ?? "";- assert.doesNotMatch(reloads, /security-posture|ambient-policy/);- assert.match(html, /if \(key === "security-posture" \|\| key === "sharing-posture" \|\| key === "ambient-policy"\)/);-});--test("compact ambient reply policy tracks the value after each save", () => {- assert.match(html, /if \(key === "org-ambient"\) \{/);- assert.match(html, /governanceOrgAmbientSaved = body\.on \? "on" : "off"/);- assert.match(html, /\$\("governance-org-ambient-save"\)\.disabled = true/);- assert.match(- html,- /orgAmbientStatus\.classList\.contains\("err"\)[\s\S]*\$\("governance-org-ambient-save"\)\.disabled = false/,- );+ assert.match(html, /governanceUI.commit\(key, body\)/);+ assert.match(html, /governanceUI.load\(fresh.data, requestedScope, key\)/);+ load({ securityPosture: "auto", sharingPosture: "isolated" }, "org:test");+ states.get("sharing-posture")!.change("sharing-posture", "open");+ load({ securityPosture: "strict", sharingPosture: "isolated" }, "org:test", "security-posture");+ assert.equal(states.get("sharing-posture")!.draft.posture, "open");+ assert.equal(states.get("sharing-posture")!.dirty, true);+});++test("ambient reply policy saves directly from Governance without a duplicate control", () => {+ const state = new GovernanceState("org-ambient");+ state.load({ on: true });+ for (const on of [false, true]) {+ state.change("governance-org-ambient", on);+ assert.deepEqual(state.collect(), { on });+ }+ assert.match(html, /id="governance-org-ambient-save"\s+data-save="org-ambient"/);+ assert.doesNotMatch(html, /id="card-org-ambient"|id="org-ambient"/);});test("governance retains scoped effective-state data behind the compact reference layout", () => {@@ -225,9 +212,9 @@ test("control-plane pages use the shared web UI canvas without redundant page inassert.match(html, /data-choice-for="security-posture"/);assert.match(html, /data-choice-for="sharing-posture"/);assert.match(html, /data-checkbox-for="external-slack-participants"/);- assert.match(html, /governanceAmbient\.id = "card-governance-org-ambient"/);+ assert.match(html, /governanceUI\.createCard\("card-governance-org-ambient"\)/);assert.match(html, /id="sc-editor"/);- assert.match(html, /id="sc-add">\+ Add credential/);+ assert.match(html, /id="sc-add"[^>]*>\s*\+ Add credential/);assert.match(html, /id="conn-editor"/);assert.match(html, /id="slack-token-editor"/);assert.match(html, /id="soul-preview"/);@@ -240,33 +227,34 @@ test("control-plane pages use the shared web UI canvas without redundant page in});test("governance renders simple settings as compact rows with contextual actions", () => {- for (const id of [- "card-security-posture",- "card-sharing-posture",- "card-external-slack",- "card-people-directory",- "card-turn-wall-clock",- ]) {- assert.match(html, new RegExp(`class="card(?: sv-[a-z]+)? setting-row(?: hidden)?" id="${id}"`));+ for (const id of ["card-security-posture", "card-sharing-posture", "card-external-slack"]) {+ assert.match(html, new RegExp(`<section(?=[^>]*class="[^"]*setting-row)(?=[^>]*id="${id}")`));}assert.match(html, /class="setting-toggle"/);- assert.match(html, /class="setting-switch" aria-hidden="true"/);- assert.match(html, /data-save="external-slack-participants">\s*Apply\s*<\/button\s*>/);- assert.match(html, /"turnWallClockSec" in r\.data/);+ assert.match(html, /data-save="external-slack-participants"/);});test("default runtime controls save reasoning level and fast mode", () => {- assert.match(html, /id="base-effort"/);- assert.match(html, /id="base-fast-mode"/);- assert.match(html, /id="base-fast-mode-control"/);- assert.match(html, /thinkingLevelsByHarness/);- assert.match(html, /fastModeModelIds/);- assert.match(html, /fastModeHarnessIds/);- assert.match(html, /base-fast-mode-control"\)\.style\.display = fastCapable \? "" : "none"/);- assert.match(- html,- /runtime: \(\) => \(\{[\s\S]*effortLevel: \$\("base-effort"\)\.value,[\s\S]*fastMode: \$\("base-fast-mode"\)\.checked/,+ for (const id of ["base-effort", "base-fast-mode", "base-fast-mode-control"])+ assert.match(html, new RegExp(`id="${id}"`));+ loadSettings(+ {+ baseModelOptions: [{ id: "a" }],+ baseModelDefault: "a",+ runtime: { harnessId: "pi", modelId: "a", effortLevel: "high", fastMode: true },+ thinkingLevelsByHarness: { pi: ["auto", "high"] },+ fastModeHarnessIds: ["pi"],+ fastModeModelIds: ["a"],+ },+ "org:test",+ "runtime",);+ assert.deepEqual(settingsStates.get("runtime")!.collect(), {+ harnessId: "pi",+ modelId: "a",+ effortLevel: "high",+ fastMode: true,+ });});test("compact governance rows preserve policy detail and collapse before they overflow", () => {@@ -298,35 +286,15 @@ test("governance reviews high-impact changes in product and preserves drafts", (});test("governance disables egress controls when agent computers cannot enforce them", () => {- assert.match(html, /id="egress-capability"/);- assert.doesNotMatch(html, /View deployment/);- assert.match(html, /id="egress-deny-editor"/);- assert.match(html, /id="egress-allow-editor"/);- assert.match(html, /class="egress-empty-state"/);- assert.match(html, /id="egress-add-deny">\+ Denylist/);- assert.match(html, /id="egress-add-allow">\+ Allowlist/);- assert.match(html, /data\.egressEnforcement/);- assert.match(html, /egressCard\.classList\.toggle\("egress-disabled", !enforcement\.active\)/);- assert.match(html, /capability\.classList\.toggle\("hidden", !!enforcement\.active\)/);- assert.match(html, /control\.disabled = !enforcement\.active/);- assert.match(html, /enforcement\.reason === "control_plane_unconfigured"/);- assert.match(html, /Egress enforcement has not been activated for agent computers/);- assert.match(html, /Backend supports policy; control plane inactive/);- assert.match(html, /Backend cannot enforce host policy/);- assert.doesNotMatch(html, /fidelity, which cannot enforce outbound host policy/);- assert.doesNotMatch(html, /Agents still have open outbound access/);- assert.match(html, /Agent computer egress policy unavailable/);- assert.match(html, /"Agent computers use "\s*\+\s*titleCase\(enforcement.backend\)/);- assert.match(html, /cannot enforce host restrictions on all outbound traffic/);- assert.match(html, /A configured egress proxy still applies policy to traffic sent through it/);- assert.doesNotMatch(html, /This deployment’s|The deployment backend cannot enforce/);+ load({ egress: {}, egressEnforcement: { active: false } }, "org:test");+ assert.equal(states.get("egress")!.disabled, true);+ load({ egress: {}, egressEnforcement: { active: true } }, "org:test");+ assert.equal(states.get("egress")!.disabled, false);});test("governance keeps effective-state summaries synchronized after focused saves", () => {- assert.match(html, /renderGovernanceOverview\(fresh\.data\)/);- assert.match(html, /renderGovernanceOverview\(\{ \.\.\.governanceOverviewData, egress: body \}\)/);+ assert.match(html, /governanceUI.load\(fresh.data, requestedScope, key\)/);assert.match(html, /btn\.dataset\.saveRequest === saveRequest/);- assert.match(html, /setStatus\(SAVE_ST\[key\], "", ""\)/);});test("stale governance reads cannot overwrite a newer scope", () => {@@ -335,37 +303,37 @@ test("stale governance reads cannot overwrite a newer scope", () => {html,/if \(requestId !== governanceReq \|\| requestedScope !== scope \|\| requestedView !== view\) return;/,);- assert.match(html, /encodeURIComponent\(requestedScope\) \+ "\/" \+ key/);+ assert.match(html, /encodeURIComponent\(requestedScope\) \+ "\/" \+ \(isBranding \? "branding" : key\)/);});test("egress omits the backend enforcement summary and hides empty editors", () => {assert.doesNotMatch(html, /class="egress-state"/);- assert.doesNotMatch(html, /id="egress-backend"|id="egress-enforcement"|id="egress-effective"/);- assert.doesNotMatch(html, /Policy is enforced|enforces this policy/);- assert.match(html, /Denylist: hosts the agent may never reach/);- assert.match(html, /Allowlist: when present, only these outbound hosts may be reached/);- assert.match(html, /const hasRules = allowedHosts\.length > 0 \|\| deniedHosts\.length > 0/);- assert.match(html, /\$\("egress-deny-editor"\)\.classList\.toggle\("hidden", deniedHosts\.length === 0\)/);- assert.match(html, /\$\("egress-allow-editor"\)\.classList\.toggle\("hidden", allowedHosts\.length === 0\)/);+ const state = new GovernanceState("egress");+ state.load({ allowedHosts: [], deniedHosts: [] });+ assert.equal(state.allowEditor, false);+ assert.equal(state.denyEditor, false);+ state.load({ allowedHosts: ["example.com"], deniedHosts: [] });+ assert.equal(state.allowEditor, true);+ assert.equal(state.denyEditor, false);});test("egress validation follows programmatic reloads and successful saves", () => {- assert.match(html, /populateEgress\(r\.data\.egress\)/);- assert.match(html, /function populateEgress\(policy\)[\s\S]*renderEgressValidation\(\)/);- assert.match(html, /if \(key === "egress"\)[\s\S]*renderGovernanceOverview[\s\S]*populateEgress\(body\)/);+ const state = new GovernanceState("egress");+ state.load({ allowedHosts: ["https://invalid"], deniedHosts: [] });+ assert.equal(state.warnings.length, 1);+ state.load({ allowedHosts: ["example.com"], deniedHosts: [] });+ assert.deepEqual(state.warnings, []);+ state.change("egress-deny", "example.com");+ assert.match(state.warnings[0], /both lists/);});test("command policy uses compact sentence rows and a modal tester", () => {assert.doesNotMatch(html, /id="mode"|class="policy-mode"/);- assert.match(html, /commandPolicyMode = cp\?\.mode \|\| "denylist"/);- assert.match(html, /return \{ mode: commandPolicyMode, rules \}/);- assert.match(html, /row\.append\(sel, pat, rsn, del\)/);- assert.match(html, /\$\("rules"\)\.prepend\(row\)/);- assert.match(html, /slice\(3\)/);assert.match(html, /id="policy-test-dialog"/);assert.match(html, /\$\("policy-test-dialog"\)\.showModal\(\)/);- assert.doesNotMatch(html, /Patterns matched against each executed command/);- assert.doesNotMatch(html, /Priority<\/th>|Order<\/th>|Move rule up|Move rule down/);+ const state = new GovernanceState("command-policy");+ state.load({ mode: "allowlist", rules: [{ pattern: "^safe$", decision: "allow" }] });+ assert.deepEqual(state.collect(), { mode: "allowlist", rules: [{ pattern: "^safe$", decision: "allow" }] });});test("the removed config-transfer surface stays gone", () => {@@ -406,8 +374,10 @@ test("governance credential editor previews effective capability and uses an in-assert.match(html, /function renderServiceCredentialCapability\(\)/);assert.match(html, /expectedUpdatedAt: c\.updatedAt/);assert.match(html, /function refreshServiceCredentialConflict\(\)/);- assert.match(html, /if \(refreshedEditing\) scEditVersion = refreshedEditing\.updatedAt/);- assert.match(html, /scEditing && scEditVersion != null \? \{ expectedUpdatedAt: scEditVersion \}/);+ assert.match(html, /credentialState.version = scEditVersion/);+ const state = new CredentialState();+ state.begin({ slug: "test", name: "Test", host: "example.com", updatedAt: 42 });+ assert.equal(state.collect().expectedUpdatedAt, 42);assert.match(html, /it remains an edit and cannot recreate the credential/);assert.match(html, /latest state could not be loaded\. Refresh the page before deleting/);assert.match(html, /latest revision could not be loaded\. Your draft is preserved/);@@ -416,12 +386,10 @@ test("governance credential editor previews effective capability and uses an in-html,/catch \{\s*updateScFormDirty\(\);\s*setStatus\(\s*"st-service-credentials",\s*"Save failed because the admin service could not be reached/,);- assert.match(html, /usageTruncated \? "at least "/);+assert.match(html, /Recent users in the retained window/);assert.doesNotMatch(html, /serviceCredList\.find\(\(c\) => c\.slug === scEditing\)\?\.updatedAt/);- assert.match(html, /personal\|team\|org\|channel\|group/);- assert.match(html, /unsupported legacy grant/);- assert.match(html, /matches multiple people/);+assert.match(html, /reviewGovernanceChange/);assert.doesNotMatch(html, /confirm\("Delete shared credential/);});@@ -430,7 +398,9 @@ test("governance SOUL workbench shows draft diff, history, and conflict-safe resassert.match(html, /id="soul-saved"/);assert.match(html, /id="soul-draft"/);assert.match(html, /id="soul-history"/);- assert.match(html, /expectedVersion: soulVersion/);+ const state = new SettingsState("soul");+ state.draft = { content: "test", expectedVersion: 4 };+ assert.equal(state.collect().expectedVersion, 4);assert.match(html, /function refreshSoulConflict\(\)/);assert.match(html, /Restore SOUL version/);});@@ -457,14 +427,12 @@ test("admin parity views expose the requested card groups and real navigation ac"Custom providers","Enabled models","Organization SOUL",- "Branding",- "People directory",- "Channel defaults",- "Turn budget",+ "Theme",+ "Pinned channel message","Feature flags","Shared service credentials","Personal keychains",- "Slack installation",+ "Slack","OAuth apps","Built-in connectors",]) {@@ -478,15 +446,15 @@ test("admin parity views expose the requested card groups and real navigation ac"+ Add flag","View usage ›","View users ›",- "Use your own Slack app",+ "Set up Slack","+ Add OAuth app",]) {assert.ok(html.includes(action), `missing ${action}`);}assert.match(html, /button\.onclick = \(\) => setView\(button\.dataset\.viewlink\)/);assert.match(html, /id="model-custom-provider-rows"/);- assert.match(html, /provider\.models\.length/);- assert.match(html, /function renderBuiltInConnectors\(\)/);+ assert.match(html, /governanceUI.settings.loadProviders/);+ assert.match(html, /governanceUI.integrations/);assert.match(html, /function loadPersonalKeychainSummary\(requestId, requestedScope\)/);assert.doesNotMatch(html, /Enabled harnesses/);assert.doesNotMatch(html, /id="card-browsing"/);@@ -495,27 +463,29 @@ test("admin parity views expose the requested card groups and real navigation actest("enabled models uses the runtime default and an explicit add interaction", () => {assert.doesNotMatch(html, /id="webui-models-default"/);- assert.match(html, /id="webui-models-add">\s*<option value="">Choose a model…<\/option>/);- assert.match(html, /id="webui-models-add-button" disabled>\+ Add model<\/button>/);- assert.match(html, /className = "model-chip"/);- assert.match(html, /updateSectionDirty\("webui-models"\)/);- assert.match(html, /"webui-models": \(\) => \(\{ ids: webuiModelIds \}\)/);+ assert.match(html, /id="webui-models-add"/);+ assert.match(html, /id="webui-models-add-button"/);+ const state = new SettingsState("webui-models");+ state.draft = { ids: [] };+ state.baseline = JSON.stringify(state.draft);+ state.selected = "model-a";+ state.add();+ assert.deepEqual(state.collect(), { ids: ["model-a"] });+ assert.equal(state.dirty, true);+ state.remove("model-a");+ assert.equal(state.dirty, false);});test("custom providers share one in-place editor instead of linking to onboarding", () => {assert.match(html, /id="custom-provider-dialog"/);assert.match(html, /class="project-dialog-head"/);assert.match(html, /class="project-dialog-actions"/);- assert.match(html, /id="custom-provider-close" aria-label="Close"/);+ assert.match(html, /id="custom-provider-close"[^>]*aria-label="Close"/);assert.match(html, /dialog\.custom-provider-dialog[\s\S]*padding: 20px;[\s\S]*border-radius: 10px;/);assert.match(html, /\$\("add-custom-provider"\)\.onclick = \(\) => openCustomProviderEditor\(\)/);assert.match(html, /\$\("onboarding-add-custom-provider"\)\.onclick = \(\) => openCustomProviderEditor\(\)/);- assert.match(html, /edit\.onclick = \(\) => openCustomProviderEditor\(provider\)/);assert.match(html, /<option value="openai-responses">OpenAI Responses<\/option>/);- assert.match(html, /CUSTOM_PROVIDER_PROTOCOL_LABELS\[provider\.protocol\] \|\| provider\.protocol/);- assert.match(html, /\$\("custom-provider-protocol"\)\.value = provider\?\.protocol \|\| "openai"/);- assert.match(html, /actions\.append\(edit, customProviderRemoveButton\(provider\)\)/);- assert.match(html, /if \(view === "models"\) await loadScope\(\)/);+ assert.match(html, /governanceUI.settings.configureProviders/);assert.doesNotMatch(html, /\$\("add-custom-provider"\)\.onclick = \(\) => \{[\s\S]*?setView\("onboarding"\)/);});@@ -532,11 +502,6 @@ test("all admin data views receive the shared flat cards and custom dropdowns",assert.match(html, /\.observe\(\$\("app-view"\), \{ childList: true, subtree: true \}\)/);});-test("grouped parity cards keep each setting bound to its own save action", () => {- assert.match(html, /card\.dataset\.saveScope = save\.dataset\.save/);- assert.match(html, /const subsection = target\.closest\("\[data-save-scope\]"\)/);-});-test("admin follows the main UI theme preference", () => {assert.match(html, /localStorage\.getItem\("theme"\)/);assert.match(html, /--warn-surface: oklch\(0\.25 0\.035 85\)/);@@ -557,11 +522,13 @@ test("governance follows the neutral web UI interaction palette", () => {});test("Open sharing explains the benefit and privacy risk in plain language", () => {- const card = html.slice(html.indexOf('id="card-sharing-posture"'), html.indexOf('id="card-egress"'));+ const card = html+ .slice(html.indexOf('id="card-sharing-posture"'), html.indexOf('id="card-egress"'))+ .replace(/\s+/g, " ");assert.match(card,- /QM can use your saved memories, files, and skills across conversations when you ask it for\s+help/,+ /QM can use your saved memories, files, and skills across conversations when you ask it\s+for\s+help/,);- assert.match(card, /In a group conversation, this could risk revealing private information to\s+others/);+ assert.match(card, /In a group conversation, this could risk revealing private\s+information to\s+others/);assert.doesNotMatch(card, /live internal speaker|entitled resources|opted-in contexts/);});diff --git a/plugins/admin/test/delivery-labels.test.ts b/plugins/admin/test/delivery-labels.test.tsindex 87819224e..aab89af91 100644--- a/plugins/admin/test/delivery-labels.test.ts+++ b/plugins/admin/test/delivery-labels.test.ts@@ -31,7 +31,8 @@ for (const [type, surface] of [test("tool-associated and standalone deliveries use the same surface labels", () => {assert.match(html, /dlabel.textContent = deliveryLabel\(delivery\)/);assert.match(html, /badge\(deliverySurfaceLabel\(delivery\), "info"\)/);- assert.match(html, /label.textContent = event.shadow \|\| isDelivery \? deliveryLabel\(event\)/);- assert.match(html, /badge\(deliverySurfaceLabel\(event\), "info"\)/);+ const transcript = readFileSync(new URL("../ui/transcript.ts", import.meta.url), "utf8");+ assert.match(transcript, /s.deliveryLabel\(event\)/);+ assert.match(transcript, /badge\(s.deliverySurfaceLabel\(event\), "info"\)/);assert.doesNotMatch(html, /"Slack delivery"|const slackDelivery/);});diff --git a/plugins/admin/test/design-lit.test.ts b/plugins/admin/test/design-lit.test.tsnew file mode 100644index 000000000..1461add55--- /dev/null+++ b/plugins/admin/test/design-lit.test.ts@@ -0,0 +1,29 @@+import assert from "node:assert/strict";+import test from "node:test";+import { renderDesign } from "./design-source.ts";+test("Design examples render the complete catalog and reactive save feedback", () => {+ const dom = renderDesign();+ try {+ const doc = dom.window.document;+ assert.equal(doc.querySelectorAll(".design-group").length, 10);+ assert.equal(doc.querySelectorAll(".design-contents a").length, 10);+ const input = doc.getElementById("design-name") as HTMLInputElement;+ input.focus();+ input.value = "Edited";+ input.dispatchEvent(new dom.window.Event("input", { bubbles: true }));+ assert.equal(doc.activeElement, input);+ assert.equal(doc.getElementById("design-status")!.textContent!.trim(), "Unsaved changes");+ const button = doc.getElementById("design-apply") as HTMLButtonElement;+ assert.equal(button.disabled, false);+ button.click();+ assert.equal(button.disabled, true);+ assert.equal(doc.getElementById("design-status")!.textContent!.trim(), "Saved in this example");+ doc.getElementById("design-advanced")!.click();+ assert.equal(doc.getElementById("design-pack-advanced")!.classList.contains("hidden"), false);+ doc.getElementById("design-remove-chip")!.click();+ assert.equal(doc.getElementById("design-remove-chip"), null);+ assert.match(doc.getElementById("design-chip-status")!.textContent!, /removed/);+ } finally {+ dom.window.close();+ }+});diff --git a/plugins/admin/test/design-source.ts b/plugins/admin/test/design-source.tsnew file mode 100644index 000000000..3d8532782--- /dev/null+++ b/plugins/admin/test/design-source.ts@@ -0,0 +1,21 @@+import { buildSync } from "esbuild";+import { JSDOM } from "jsdom";+const bundle = buildSync({+ entryPoints: [new URL("../ui/design.ts", import.meta.url).pathname],+ bundle: true,+ write: false,+ format: "iife",+ globalName: "designUI",+}).outputFiles[0].text;+export function renderDesign(+ stateToUrl: (state: any) => string = (state) => "/admin/" + state.view,+ scope = "org:test",+) {+ const dom = new JSDOM('<div id="view-design"></div>', { runScripts: "outside-only", url: "http://localhost/" });+ Object.assign(dom.window, { route: stateToUrl, scopeId: scope });+ dom.window.eval(+ bundle ++ ';designUI.show({stateToUrl:route,scope:()=>scopeId,searchField:()=>document.createElement("input"),twoWayToggle:()=>document.createElement("div"),fileThumb:()=>document.createElement("span"),initCustomDropdowns:()=>{}});',+ );+ return dom;+}diff --git a/plugins/admin/test/environments.test.ts b/plugins/admin/test/environments.test.tsindex 3ec8c9fb8..1844816ed 100644--- a/plugins/admin/test/environments.test.ts+++ b/plugins/admin/test/environments.test.ts@@ -6,7 +6,7 @@ import { join } from "node:path";const html = readFileSync(join(import.meta.dirname, "../public/index.html"), "utf8");test("the admin UI lists named environments and links attachment warnings", () => {- assert.match(html, /Named environments/);+ assert.match(readFileSync(join(import.meta.dirname, "../ui/history.ts"), "utf8"), /Named environments/);assert.match(html, /id="environment-notice"/);assert.match(html, /Uses named environment/);assert.match(html, /scope: attachment\.environmentId/);diff --git a/plugins/admin/test/errors-view.test.ts b/plugins/admin/test/errors-view.test.tsindex 24d69f7d5..162253f09 100644--- a/plugins/admin/test/errors-view.test.ts+++ b/plugins/admin/test/errors-view.test.ts@@ -1,111 +1,79 @@import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";+import { litFixture } from "./lit-fixture.ts";-const html = readFileSync(new URL("../public/index.html", import.meta.url), "utf8");-const source = html.match(/function renderErrors\(root, d\) \{[\s\S]*?\n {6}\}/)?.[0];-assert.ok(source);--function render(all: boolean, errors: unknown[]) {- let result: { headers: string[]; rows: any[][]; empty: string };- const element = (tag: string) => ({- tag,- children: [] as any[],- append(...nodes: any[]) {- this.children.push(...nodes);- },- });- new Function(- "orgWideView",- "defaultShell",- "plural",- "document",- "firstLine",- "timeCell",- "nodeCell",- "navLink",- "shortName",- "bareDataCard",- "table",- "scope",- "ERRORS_PAGE_SIZE",- "pager",- `${source}; renderErrors({appendChild() {}}, arguments[14]);`,- )(- () => all,- () => {},- (n: number) => String(n),- { createElement: element },- (s: string, max: number) => s.split("\n")[0].slice(0, max),- (ts: number) => ts,- (node: unknown) => ({ node }),- (label: string, target: unknown) => ({ label, target }),- (scope: string) => scope,- (node: unknown) => node,- (headers: string[], rows: any[][], empty: string) => {- result = { headers, rows, empty };- return { classList: { add() {} } };- },- "org:acme",- 50,- () => ({}),+function fixture(all: boolean, errors: unknown[]) {+ const f = litFixture();+ f.ui.activity.errors(+ f.root,{ errors },+ {+ all,+ scope: "org:acme",+ errorsPageSize: 50,+ defaultShell() {},+ plural: String,+ firstLine: (s: string, max: number) => s.split("\n")[0].slice(0, max),+ shortName: String,+ relTime: String,+ fmtTime: String,+ navLink: (label: string, target: any) => {+ const a = f.document.createElement("a");+ a.textContent = label;+ a.href = "/" + target.view + "?scope=" + target.scope + (target.session ? "&session=" + target.session : "");+ return a;+ },+ },);- return result!;+ return f;}-test("error rows preserve full text and link to the owning scope and session", () => {+test("error rows escape full diagnostics and preserve scoped session links", () => {const message = "<img src=x onerror=alert(1)>\nfull diagnostic";- const result = render(true, [+ const f = fixture(true, [{ ts: 123, category: "turn", code: "failed", message, scopeLabel: "personal:alice", sessionId: "session-1" },]);- assert.deepEqual(result.headers, ["Category", "Code", "Message", "Scope", "Session", "Time"]);- const details = result.rows[0][2].node;- assert.equal(details.tag, "details");- const [preview, full] = details.children[0].children;- assert.equal(preview.textContent, message.split("\n")[0]);- assert.equal(full.tag, "span");- assert.equal(full.textContent, message);- assert.equal(full.innerHTML, undefined);- assert.deepEqual(result.rows[0][3].node.target, { view: "errors", scope: "personal:alice" });- assert.deepEqual(result.rows[0][4].node.target, { view: "history", scope: "personal:alice", session: "session-1" });-});--test("scope errors omit the scope column and errors without sessions have no session link", () => {- const result = render(false, [{ ts: 123, scopeLabel: "org:acme", message: "failure" }]);- assert.equal(result.headers.includes("Scope"), false);- assert.deepEqual(result.rows[0].at(-2), { text: "—" });- assert.equal(render(false, []).empty, "No errors recorded for this scope.");- assert.equal(render(true, []).empty, "No errors recorded.");-});--test("system attribution stays readable without creating an invalid scope link", () => {- const result = render(true, [{ ts: 123, scopeLabel: "runs:reaper", message: "requeued", sessionId: "s1" }]);- assert.deepEqual(result.rows[0][3], { text: "runs:reaper" });- assert.deepEqual(result.rows[0][4].node.target, { view: "history", scope: "org:acme", session: "s1" });-});--test("short and long messages retain an expandable full value", () => {- const short = render(true, [{ message: "Timed out" }]).rows[0][2].node;- assert.equal(short.tag, "details");- assert.equal(short.children[0].children[1].textContent, "Timed out");- const message = "x".repeat(200);- const long = render(true, [{ message }]).rows[0][2].node;- assert.equal(long.tag, "details");- assert.equal(long.children[0].children[1].textContent, message);+ assert.equal(f.root.querySelector("img"), null);+ assert.equal(f.root.querySelector(".error-preview")!.textContent, message.split("\n")[0]);+ assert.equal(f.root.querySelector(".error-full")!.textContent, message);+ assert.deepEqual(+ [...f.root.querySelectorAll("th")].map((e) => e.textContent),+ ["Category", "Code", "Message", "Scope", "Session", "Time"],+ );+ assert.match(f.root.querySelectorAll("a")[0].href, /errors\?scope=personal:alice/);+ assert.match(f.root.querySelectorAll("a")[1].href, /history\?scope=personal:alice&session=session-1/);+ f.dom.window.close();});-test("compact messages retain an expandable full value even below the character limit", () => {- const message = "A message that may wrap beyond two lines in a narrow column.";- const details = render(true, [{ message }]).rows[0][2].node;- assert.equal(details.tag, "details");- assert.equal(details.children[0].children[1].textContent, message);+test("scoped and system error tables preserve attribution, empty states and timestamp placement", () => {+ for (const all of [true, false]) {+ const f = fixture(all, [+ { ts: 123, scopeLabel: "runs:reaper", message: "requeued", sessionId: "s1" },+ { ts: 124, message: "failure" },+ ]);+ assert.equal(f.root.querySelectorAll("th").length, all ? 6 : 5);+ assert.equal(f.root.querySelector("tbody tr")!.lastElementChild!.textContent, "123");+ assert.match(f.root.querySelector("a")!.href, /history\?scope=org:acme&session=s1/);+ assert.equal(f.root.querySelectorAll("a").length, 1);+ if (all) assert.ok(f.root.textContent!.includes("runs:reaper"));+ f.dom.window.close();+ const empty = fixture(all, []);+ assert.equal(+ empty.root.querySelector(".empty")!.textContent,+ all ? "No errors recorded." : "No errors recorded for this scope.",+ );+ empty.dom.window.close();+ }});-test("compact errors place timestamps last for org and scoped tables", () => {- for (const all of [true, false]) {- const result = render(all, [{ ts: 123, message: "Failed" }]);- assert.deepEqual(result.headers, ["Category", "Code", "Message", ...(all ? ["Scope"] : []), "Session", "Time"]);- assert.equal(result.rows[0].at(-1), 123);+test("all message lengths retain an expandable full value", () => {+ for (const message of [+ "Timed out",+ "A message that may wrap beyond two lines in a narrow column.",+ "x".repeat(200),+ ]) {+ const f = fixture(true, [{ message }]);+ assert.equal(f.root.querySelector("details .error-full")!.textContent, message);+ f.dom.window.close();}});diff --git a/plugins/admin/test/governance-lit.test.ts b/plugins/admin/test/governance-lit.test.tsnew file mode 100644index 000000000..2ebbd8583--- /dev/null+++ b/plugins/admin/test/governance-lit.test.ts@@ -0,0 +1,139 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { JSDOM } from "jsdom";+import { buildGovernanceUI } from "../src/governance-bundle.ts";+import { GovernanceState } from "../ui/governance-state.ts";+const bundle = buildGovernanceUI();+function setup() {+ const dom = new JSDOM(readFileSync(new URL("../public/index.html", import.meta.url), "utf8"), {+ runScripts: "outside-only",+ });+ dom.window.structuredClone = structuredClone;+ dom.window.eval(bundle + ";window.governanceUI = governanceUI; governanceUI.mountCards();");+ return dom;+}+test("Lit mounts Governance without wrappers or duplicate ids", () => {+ const dom = setup();+ try {+ for (const id of [+ "security-posture",+ "auto-flagger",+ "sharing-posture",+ "command-policy",+ "egress",+ "ambient-policy",+ ]) {+ const card = dom.window.document.getElementById(`card-${id}`)!;+ assert.equal(card.tagName, "SECTION");+ assert.equal(card.parentElement?.className, "governance-content");+ assert.ok(card.querySelector(`[data-save="${id}"]`));+ }+ const ids = [...dom.window.document.querySelectorAll("[id]")].map((node) => node.id);+ assert.equal(new Set(ids).size, ids.length);+ } finally {+ dom.window.close();+ }+});+test("editing and reverting a posture drives radio, dirty state and save button", () => {+ const dom = setup();+ try {+ dom.window.eval('governanceUI.load({securityPosture:"auto"},"org:test")');+ const doc = dom.window.document;+ const button = doc.querySelector<HTMLButtonElement>('[data-save="security-posture"]')!;+ const input = doc.querySelector<HTMLInputElement>('[name="security-posture-choice"][value="strict"]')!;+ input.click();+ assert.equal(button.disabled, false);+ assert.equal(doc.getElementById("st-security-posture")!.textContent, "Unsaved changes");+ assert.equal(dom.window.eval('governanceUI.collect("security-posture").posture'), "strict");+ doc.querySelector<HTMLInputElement>('[name="security-posture-choice"][value="auto"]')!.click();+ assert.equal(button.disabled, true);+ assert.equal(doc.getElementById("st-security-posture")!.textContent, "");+ } finally {+ dom.window.close();+ }+});+test("loading another scope resets posture radios after both choices were clicked", () => {+ const dom = setup();+ try {+ dom.window.eval('governanceUI.load({securityPosture:"auto"},"org:first")');+ const doc = dom.window.document;+ const strict = doc.querySelector<HTMLInputElement>('[name="security-posture-choice"][value="strict"]')!;+ const auto = doc.querySelector<HTMLInputElement>('[name="security-posture-choice"][value="auto"]')!;+ strict.click();+ auto.click();+ dom.window.eval('governanceUI.load({securityPosture:"strict"},"org:second")');+ assert.equal(strict.checked, true);+ assert.equal(auto.checked, false);+ assert.equal(dom.window.eval('governanceUI.collect("security-posture").posture'), "strict");+ assert.equal(doc.querySelector<HTMLButtonElement>('[data-save="security-posture"]')!.disabled, true);+ } finally {+ dom.window.close();+ }+});+test("keyed Lit rules preserve focus, escape values, validate and remove from state", () => {+ const dom = setup();+ try {+ dom.window.eval('governanceUI.load({commandPolicy:{mode:"denylist",rules:[]}},"org:test")');+ const doc = dom.window.document;+ doc.getElementById("add-rule")!.click();+ const input = doc.querySelector<HTMLInputElement>(".policy-pattern")!;+ input.value = "<img src=x onerror=alert(1)>";+ input.dispatchEvent(new dom.window.Event("input", { bubbles: true }));+ assert.equal(doc.activeElement, input);+ assert.equal(doc.querySelectorAll("#rules img, #rules script").length, 0);+ assert.equal(dom.window.eval('governanceUI.collect("command-policy").rules[0].pattern'), input.value);+ input.value = "[";+ input.dispatchEvent(new dom.window.Event("input", { bubbles: true }));+ assert.equal(input.getAttribute("aria-invalid"), "true");+ assert.throws(() => dom.window.eval('governanceUI.collect("command-policy")'), /regular expression/);+ doc.querySelector<HTMLButtonElement>('[aria-label="Remove command policy rule"]')!.click();+ assert.equal(doc.querySelectorAll(".policy-rule").length, 0);+ assert.equal(doc.getElementById("rules-empty")!.classList.contains("hidden"), false);+ } finally {+ dom.window.close();+ }+});+test("bot ledger changes derive rollup enablement and payload from state", () => {+ const dom = setup();+ try {+ dom.window.eval('governanceUI.load({ambientPolicy:{bots:{Build:{mode:"rollup",rollupHours:12}}}},"channel:test")');+ const doc = dom.window.document;+ const hours = doc.querySelector<HTMLInputElement>('#ambient-bots input[type="number"]')!;+ assert.equal(hours.disabled, false);+ const select = doc.querySelector<HTMLSelectElement>("#ambient-bots select")!;+ select.value = "ignore";+ select.dispatchEvent(new dom.window.Event("change", { bubbles: true }));+ assert.equal(hours.disabled, true);+ assert.equal(dom.window.eval('governanceUI.collect("ambient-policy").bots.Build.mode'), "ignore");+ doc.querySelector<HTMLButtonElement>('[aria-label="Remove bot ledger entry"]')!.click();+ assert.equal(doc.querySelectorAll("#ambient-bots tr").length, 0);+ } finally {+ dom.window.close();+ }+});+test("saving an older submitted draft preserves edits made during the request", () => {+ const state = new GovernanceState("security-posture");+ state.load({ posture: "auto" });+ state.change("security-posture", "strict");+ const submitted = state.collect();+ state.saving = true;+ state.change("security-posture", "auto");+ state.commit(submitted);+ assert.equal(state.draft.posture, "auto");+ assert.equal(state.dirty, true);+ assert.equal(state.message, "Unsaved changes");+});+test("policy validation detects duplicate bots and overlapping hosts", () => {+ const bots = new GovernanceState("ambient-policy");+ bots.load({ bots: { Build: { mode: "ignore" } } });+ bots.bots.push({ id: -1, name: "build", mode: "ignore", hours: "" });+ assert.throws(() => bots.collect(), /Duplicate bot/);+ const egress = new GovernanceState("egress");+ egress.load({ allowedHosts: ["example.com"], deniedHosts: ["example.com"] });+ assert.throws(() => egress.collect(), /both lists/);+});+test("Governance bundle stays inline-script safe without external runtime imports", () => {+ assert.doesNotMatch(bundle, /<\/script/i);+ assert.doesNotMatch(bundle, /\bimport\s*\(/);+});diff --git a/plugins/admin/test/history-urls.test.ts b/plugins/admin/test/history-urls.test.tsindex 3a378292b..b555bc450 100644--- a/plugins/admin/test/history-urls.test.ts+++ b/plugins/admin/test/history-urls.test.ts@@ -1,3 +1,5 @@+import { litFixture } from "./lit-fixture.ts";+import { renderDesign } from "./design-source.ts";import assert from "node:assert/strict";import { readFileSync } from "node:fs";import test from "node:test";@@ -29,6 +31,7 @@ function routerAt(pathname: string, search = "", base = "/admin") {new Function(`${html.match(/const SCOPED = new Set\(\[[\s\S]*?\]\);/)?.[0]}; return SCOPED;`)(),["connectors",+ "slack-settings","history","files","memory",@@ -130,11 +133,7 @@ test("a mangled ?scopecom link still lands on the session and canonicalizes", ()test("session deep-link entries synthesize a list back-stop and repair it from the session's own scope", () => {assert.match(html, /history\.pushState\(\{ \.\.\.st, deepLink: true \}, "", stateToUrl\(st\)\);/);- assert.match(- html,- /if \(history\.state\?\.deepLink\)\s*go\(\{ view: "history", scope: sessionScope \|\| scope, session: null, historyKind \}\);\s*else history\.back\(\);/,- );- assert.match(html, /onClick: backToList\(session\.scopeId\)/);+ assert.match(html, /governanceUI.transcript.show/);});test("a scope whose encoding the portal would reject stays in the query form", () => {@@ -153,11 +152,39 @@ test("an undecodable scope segment falls back instead of throwing", () => {assert.equal(st.scope, "org:acme");});-test("cron fire rows surface the fire's result digest and keep the silent styling", () => {- assert.match(html, /\} else if \(isBackground && s\.result\) \{\s*name = s\.result;/);- assert.match(html, /previewText = s\.result \|\| s\.lastMessage \|\| s\.firstMessage \|\| "";/);- assert.match(html, /s\.result \|\| "\(no messages\)"/);- assert.match(html, /isBackground && typeof s\.delivered === "number" && !s\.delivered \? "history-silent" : ""/);+test("cron fire rows surface the result digest and retain silent styling", () => {+ const f = litFixture();+ f.ui.history.history(+ f.root,+ {+ sessions: [+ { id: "fire1", category: "background", result: "Digest result", lastMessage: "Tool chatter", delivered: 0 },+ ],+ total: 1,+ },+ {+ historyKind: "cron",+ cron: "job1",+ scope: "org:acme",+ orgScope: "org:acme",+ environments: [],+ historyKindMatches: () => true,+ pageSize: 50,+ correctPage() {},+ historyModeLabel: () => "Crons",+ kindLabels: { conversation: "Conversations", cron: "Crons" },+ pageShell() {},+ cronName: () => "Job",+ scopeKind: () => "org",+ plural: String,+ stateToUrl: () => "/session/fire1",+ go() {},+ },+ );+ assert.equal(f.root.querySelector(".dense-name")!.textContent, "Digest result");+ assert.equal(f.root.querySelector(".dense-preview")!.textContent, "Tool chatter");+ assert.ok(f.root.querySelector(".history-silent"));+ f.dom.window.close();});test("a bare history URL is the org scope, not whatever scope was viewed last", () => {@@ -184,13 +211,13 @@ test("Errors pagination round-trips arbitrary pages without losing scope", () =>);});-test("Slack setup links select connectors and preserve the guide through canonical routing", () => {+test("Slack setup links select Slack settings and preserve the guide through canonical routing", () => {for (const pathname of ["/admin", "/admin/", "/admin/connectors"]) {const { stateToUrl, urlToState } = routerAt(pathname, "?setup=slack");const state = urlToState();- assert.equal(state.view, "connectors");+ assert.equal(state.view, "slack-settings");assert.equal(state.setup, "slack");- assert.equal(stateToUrl(state), "/admin/connectors?setup=slack");+ assert.equal(stateToUrl(state), "/admin/slack-settings?setup=slack");}const { stateToUrl } = routerAt("/admin/connectors", "?setup=slack");assert.equal(stateToUrl({ view: "connectors" }), "/admin/connectors");@@ -208,36 +235,15 @@ test("navigation drops retired design parameters while retaining route state", (for (const base of ["", "/admin", "/control"]) {test(`catalog live links use the configured base (${base || "root"})`, () => {- const root = { innerHTML: "" };- const helpers = html.slice(- html.indexOf(" function designSpec("),- html.indexOf(" let designLibraryRendered"),- );- const start = html.indexOf(' const root = $("view-design");');- const end = html.indexOf(' const contents = document.createElement("nav");', start);- assert.ok(start >= 0 && end > start);- new Function("$", "DESIGN_TOKENS", helpers + html.slice(start, end))(() => root, []);- const section = root.innerHTML.match(/<div class="design-page-links">([\s\S]*?)<\/div>/)?.[1];- assert.ok(section);- const links = [...section.matchAll(/<a data-design-view="([^"]+)">/g)].map((match) => ({- dataset: { designView: match[1] },- href: "",- }));+ const { stateToUrl } = routerAt(`${base}/design-system`, "", base);+ const dom = renderDesign(stateToUrl, SCOPE);+ const links = [...dom.window.document.querySelectorAll<HTMLAnchorElement>(".design-page-links a")];assert.deepEqual(links.map((link) => link.dataset.designView),["governance", "skills", "files", "history", "audit", "egress"],);- const bindStart = html.indexOf(' root.querySelectorAll(".design-page-links a")');- const bindEnd = html.indexOf(" });", bindStart) + " });".length;- assert.ok(bindStart >= 0 && bindEnd > bindStart);- const { stateToUrl } = routerAt(`${base}/design-system`, "", base);- new Function("root", "stateToUrl", "scope", html.slice(bindStart, bindEnd))(- { querySelectorAll: () => links },- stateToUrl,- SCOPE,- );assert.deepEqual(- links.map((link) => link.href),+ links.map((link) => link.getAttribute("href")),[`${base}/governance?scope=${SCOPE_ENC}`,`${base}/skills?scope=${SCOPE_ENC}`,@@ -247,5 +253,6 @@ for (const base of ["", "/admin", "/control"]) {`${base}/egress?scope=${SCOPE_ENC}`,],);+ dom.window.close();});}diff --git a/plugins/admin/test/integrations-lit.test.ts b/plugins/admin/test/integrations-lit.test.tsnew file mode 100644index 000000000..fa2bfcd3e--- /dev/null+++ b/plugins/admin/test/integrations-lit.test.ts@@ -0,0 +1,143 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { buildSync } from "esbuild";+import { JSDOM } from "jsdom";+import { configure, ConnectorsState, SlackSetting, SlackInstallationState } from "../ui/integrations-state.ts";+const bundle = buildSync({+ entryPoints: [new URL("../ui/integrations.ts", import.meta.url).pathname],+ bundle: true,+ write: false,+ format: "iife",+ globalName: "integrationsUI",+}).outputFiles[0].text;+function setup() {+ const dom = new JSDOM(readFileSync(new URL("../public/index.html", import.meta.url), "utf8"), {+ runScripts: "outside-only",+ url: "http://localhost/admin/slack-settings",+ });+ dom.window.eval(+ bundle ++ ';window.ui=integrationsUI;ui.mountCards();ui.configure({api:async()=>({ok:true,data:{}}),orgScope:()=>"org:test",connectorName:id=>id,fmtTime:x=>x});',+ );+ dom.window.HTMLElement.prototype.scrollIntoView = () => {};+ return dom;+}+test("Slack settings are state driven and preserve newer drafts when committing", () => {+ const dom = setup();+ try {+ dom.window.eval(+ 'ui.loadScope({externalSlackParticipants:false,internalMemberOverrides:[],channelHeaderPinDefault:false,ackEmoji:[]},"org:test")',+ );+ const doc = dom.window.document;+ const radio = doc.querySelector<HTMLInputElement>('[name="external-slack-choice"][value="on"]')!;+ radio.click();+ assert.equal(dom.window.eval('ui.collect("external-slack-participants").on'), true);+ assert.equal(doc.querySelector<HTMLButtonElement>('[data-save="external-slack-participants"]')!.disabled, false);+ dom.window.eval('ui.status("external-slack-participants","Saving","saving")');+ doc.querySelector<HTMLInputElement>('[name="external-slack-choice"][value="off"]')!.click();+ dom.window.eval('ui.commit("external-slack-participants",{on:true})');+ assert.equal(doc.getElementById("st-external-slack-participants")!.textContent, "Unsaved changes");+ assert.equal(doc.querySelector<HTMLInputElement>("#external-slack-participants")!.checked, false);+ } finally {+ dom.window.close();+ }+});+test("Slack member overrides normalize from the draft and update the count", () => {+ const s = new SlackSetting("internal-member-overrides");+ s.load([], "org:test", true);+ s.change({ text: " [email protected],[email protected]\n U123 " });+ assert.deepEqual(s.collect(), { members: ["[email protected]", "u123"] });+ assert.equal(s.dirty, true);+});+test("Connector editor renders guides and keeps fields and focus stable while typing", () => {+ const dom = setup();+ try {+ dom.window.eval(+ 'ui.connectors.catalog=[{provider:"github",setupGuide:{url:"https://example.com",console:"GitHub",steps:["Create app"]},redirectPath:"github",scopes:["repo"]}];ui.connectors.render()',+ );+ const doc = dom.window.document;+ doc.getElementById("add-oauth-app")!.click();+ const input = doc.getElementById("conn-client-id") as HTMLInputElement;+ input.value = "my client";+ input.dispatchEvent(new dom.window.Event("input", { bubbles: true }));+ assert.equal(doc.activeElement, input);+ assert.equal(dom.window.eval("ui.connectors.draft.clientId"), "my client");+ assert.match(+ doc.getElementById("conn-guide")!.textContent!,+ /Callback URL: http:\/\/localhost\/v1\/connectors\/oauth\/github/,+ );+ assert.equal(doc.getElementById("conn-editor")!.classList.contains("hidden"), false);+ doc.getElementById("conn-reset")!.click();+ assert.equal(doc.getElementById("conn-editor")!.classList.contains("hidden"), true);+ } finally {+ dom.window.close();+ }+});+test("Connector saves use captured payloads and retain edits made during a request", async () => {+ let resolve!: (value: any) => void;+ const bodies: unknown[] = [];+ configure({+ orgScope: () => "org:test",+ connectorName: (x) => x,+ fmtTime: (x) => x,+ api: async (method, _path, body) => {+ if (method === "PUT") {+ bodies.push(body);+ return new Promise((r) => (resolve = r));+ }+ return { ok: true, data: { catalog: [], connectors: [] } };+ },+ });+ const s = new ConnectorsState();+ s.edit({ provider: "github" });+ s.change("clientId", "first");+ s.change("clientSecret", "secret");+ const saving = s.save();+ s.change("clientId", "newer");+ resolve({ ok: true, data: {} });+ await saving;+ assert.deepEqual(bodies, [{ provider: "github", clientId: "first", clientSecret: "secret", enabled: true }]);+ assert.equal(s.draft.clientId, "newer");+ assert.equal(s.editor, true);+ assert.equal(s.saving, false);+});+test("Connector load ignores out of order responses and preserves the open editor", async () => {+ const pending: Array<(value: any) => void> = [];+ configure({+ orgScope: () => "org:test",+ connectorName: (x) => x,+ fmtTime: (x) => x,+ api: () => new Promise((r) => pending.push(r)),+ });+ const s = new ConnectorsState();+ const old = s.load();+ const latest = s.load();+ pending[2]({ ok: true, data: { catalog: [{ provider: "new" }] } });+ pending[3]({ ok: true, data: { connectors: [] } });+ await latest;+ s.edit({ provider: "new" });+ s.change("clientId", "draft");+ pending[0]({ ok: true, data: { catalog: [{ provider: "stale" }] } });+ pending[1]({ ok: true, data: { connectors: [] } });+ await old;+ assert.equal(s.catalog[0].provider, "new");+ assert.equal(s.draft.clientId, "draft");+});+test("Slack connection validates token drafts before submitting", async () => {+ let called = false;+ configure({+ orgScope: () => "org:test",+ connectorName: (x) => x,+ fmtTime: (x) => x,+ api: async () => {+ called = true;+ return { ok: true, data: {} };+ },+ });+ const s = new SlackInstallationState();+ s.botToken = "xoxb-example";+ await s.save();+ assert.equal(called, false);+ assert.equal(s.message, "Both Slack tokens are required.");+});diff --git a/plugins/admin/test/internal-member-overrides.test.ts b/plugins/admin/test/internal-member-overrides.test.tsindex a5f835360..43de06ed8 100644--- a/plugins/admin/test/internal-member-overrides.test.ts+++ b/plugins/admin/test/internal-member-overrides.test.ts@@ -2,6 +2,8 @@ import test from "node:test";import assert from "node:assert/strict";import { readFileSync } from "node:fs";import vm from "node:vm";+import { readAdminSource } from "./admin-source.ts";+import { loadScope, states, SlackSetting } from "../ui/integrations-state.ts";import { createServer, type IncomingMessage } from "node:http";import type { AddressInfo } from "node:net";@@ -35,11 +37,11 @@ test.after(() => {});test("the org page ships an Internal member overrides card wired to the save machinery", () => {- const shell = readFileSync(new URL("../public/index.html", import.meta.url), "utf8");+ const shell = readAdminSource();assert.match(shell, /id="card-internal-member-overrides"/, "card exists");assert.match(shell, /<textarea[^>]*id="internal-member-overrides"/, "one-per-line textarea");assert.match(shell, /data-save="internal-member-overrides"/, "save button keyed to the core resource id");- assert.match(shell, /"internalMemberOverrides" in r\.data/, "shown only when the org scope carries the key");+ assert.match(shell, /governanceUI.integrations.loadScope/, "loads through the reactive scope model");assert.match(shell, /"internal-member-overrides": "st-internal-member-overrides"/, "status target registered");assert.match(shell, /key === "internal-member-overrides"/, "changes go through the governance review dialog");});@@ -107,43 +109,29 @@ test("editor is visible only for org payloads that support overrides", () => {["personal:demo", { internalMemberOverrides: ["u123abc"] }, true, "", ""],["channel:test", { internalMemberOverrides: [] }, true, "", ""],] as const) {- let actualHidden: boolean | undefined;- const input = { value: "" };- const label = { textContent: "" };- vm.runInNewContext(slice(" const showInternalOverrides =", " const showOrgAmbient ="), {- scope,- r: { data },- $: (id: string) => {- if (id === "internal-member-overrides") return input;- if (id.endsWith("-count")) return label;- return {- classList: {- toggle: (_name: string, on: boolean) => {- actualHidden = on;- },- },- };- },- });- assert.equal(actualHidden, hidden);- assert.equal(input.value, value);- assert.equal(label.textContent, count);+ loadScope(data, scope);+ const state = states.get("internal-member-overrides")!;+ assert.equal(!state.available, hidden);+ if (!hidden) {+ assert.equal(state.draft.text, value);+ assert.equal(state.collect().members?.length || 0, count === "No overrides configured." ? 0 : parseInt(count));+ }}});test("collector trims, lowercases, deduplicates and supports clearing", () => {- const collector = slice(' "internal-member-overrides": () =>', ' "org-ambient": () =>');for (const [value, expected] of [[" ,\n ", []],] as const) {- const body = vm.runInNewContext(`({${collector}})["internal-member-overrides"]()`, { $: () => ({ value }) });- assert.deepEqual(JSON.parse(JSON.stringify(body)), { members: expected });+ const state = new SlackSetting("internal-member-overrides");+ state.change({ text: value });+ assert.deepEqual(state.collect(), { members: expected });}});test("confirmation shows added/removed members, unique total, and returns the user's decision", async () => {- const review = slice(" function governanceSaveReview(", " function renderSharingPosture(");+ const review = slice(" function governanceSaveReview(", ' $("sharing-posture-inherit").onclick');for (const accepted of [false, true]) {let shown: { facts: [string, string][]; warning: string; danger: boolean } | undefined;const result = await vm.runInNewContext(@@ -171,7 +159,7 @@ test("confirmation shows added/removed members, unique total, and returns the us});test("clearing reviews removals, while a normalized unchanged list needs no review", async () => {- const review = slice(" function governanceSaveReview(", " function renderSharingPosture(");+ const review = slice(" function governanceSaveReview(", ' $("sharing-posture-inherit").onclick');let reviews = 0;const context = vm.createContext({sectionSnapshots: new Map([["internal-member-overrides", JSON.stringify({ members: ["[email protected]"] })]]),diff --git a/plugins/admin/test/lit-fixture.ts b/plugins/admin/test/lit-fixture.tsnew file mode 100644index 000000000..f6bf3bf2e--- /dev/null+++ b/plugins/admin/test/lit-fixture.ts@@ -0,0 +1,18 @@+import { JSDOM } from "jsdom";+import { buildGovernanceUI } from "../src/governance-bundle.ts";++export function litFixture() {+ const dom = new JSDOM('<!doctype html><body><main id="root"></main></body>', {+ runScripts: "outside-only",+ url: "http://localhost/admin",+ });+ dom.window.structuredClone = structuredClone;+ dom.window.eval(buildGovernanceUI() + ";window.ui = governanceUI;");+ return {+ dom,+ window: dom.window,+ document: dom.window.document,+ root: dom.window.document.getElementById("root")!,+ ui: (dom.window as any).ui,+ };+}diff --git a/plugins/admin/test/metrics-lit.test.ts b/plugins/admin/test/metrics-lit.test.tsnew file mode 100644index 000000000..672f6daaa--- /dev/null+++ b/plugins/admin/test/metrics-lit.test.ts@@ -0,0 +1,88 @@+import assert from "node:assert/strict";+import test from "node:test";+import { litFixture } from "./lit-fixture.ts";++test("metric phase rows preserve percentile values and navigate to their detail", () => {+ const f = litFixture();+ let target: any;+ f.ui.metrics.metrics(+ f.root,+ { phases: [{ phase: "queue", p50: 10, p95: 20, p99: 30, count: 4 }] },+ {+ scope: "org:test",+ defaultShell() {},+ plural: String,+ phaseLabel: String,+ phaseDesc: () => "Queue delay",+ fmtMs: (n: number) => `${n}ms`,+ sparkline: () => f.document.createElement("span"),+ go: (value: any) => {+ target = value;+ },+ },+ );+ assert.deepEqual(+ [...f.root.querySelectorAll("th")].map((e) => e.textContent),+ ["Phase", "p50", "p95", "p99", "Turns", "Trend"],+ );+ assert.ok(f.root.textContent!.includes("10ms"));+ f.root.querySelector<HTMLTableRowElement>("tbody tr")!.click();+ assert.deepEqual(JSON.parse(JSON.stringify(target)), {+ view: "metrics",+ scope: "org:test",+ session: null,+ phase: "queue",+ });+ f.window.close();+});++test("phase detail preserves distribution, daily values and scoped transcript links", () => {+ const f = litFixture();+ let target: any;+ f.ui.metrics.metrics(+ f.root,+ {+ phases: [+ {+ phase: "queue",+ p50: 10,+ p95: 20,+ p99: 30,+ count: 2,+ dist: [+ { le: 10, count: 2 },+ { le: 20, count: 0 },+ ],+ worst: [{ ms: 20, scopeLabel: "personal:alex", sessionId: "s1", turnSeq: 4 }],+ },+ ],+ },+ {+ phase: "queue",+ scope: "org:test",+ pageShell() {},+ phaseLabel: String,+ phaseDesc: String,+ fmtMs: String,+ shortName: String,+ turnKindWords: () => "",+ relTime: String,+ go: (value: any) => {+ target = value;+ },+ },+ );+ assert.equal(f.root.querySelectorAll(".dist-row").length, 1);+ assert.deepEqual(+ [...f.root.querySelectorAll("h2")].map((e) => e.textContent),+ ["Distribution", "By day", "Worst recent turns"],+ );+ f.root.querySelector<HTMLTableRowElement>("tr.openable")!.click();+ assert.deepEqual(JSON.parse(JSON.stringify(target)), {+ view: "history",+ scope: "personal:alex",+ session: "s1",+ turn: 4,+ });+ f.window.close();+});diff --git a/plugins/admin/test/onboarding-view.test.ts b/plugins/admin/test/onboarding-view.test.tsindex b40ec9343..ee7e9de34 100644--- a/plugins/admin/test/onboarding-view.test.ts+++ b/plugins/admin/test/onboarding-view.test.ts@@ -2,6 +2,8 @@ import assert from "node:assert/strict";import { readFileSync } from "node:fs";import test from "node:test";import vm from "node:vm";+import { buildSync } from "esbuild";+import { JSDOM } from "jsdom";const html = readFileSync(new URL("../public/index.html", import.meta.url), "utf8");@@ -14,7 +16,7 @@ function slice(from: string, to: string): string {function resolveView(pathname: string, search: string): string {const src = [- slice("const SECTIONS = [", "function paritySubsection"),+ slice("const SECTIONS = [", "function prepareParityCards"),slice("const DEFAULT_VIEW = ", ";") + ";",slice("function decodePathSegment(seg) {", "let transcriptObserver"),"urlToState().view;",@@ -29,55 +31,53 @@ function resolveView(pathname: string, search: string): string {return vm.runInContext(src, context);}-interface FakeElement {- textContent: string;- className: string;- value: string;- placeholder: string;- disabled: boolean;- href: string;- options: Array<{ value?: string; textContent?: string }>;- appendChild(option: { value?: string; textContent?: string }): void;+const bundle = buildSync({+ entryPoints: [new URL("../ui/onboarding.ts", import.meta.url).pathname],+ bundle: true,+ write: false,+ format: "iife",+ globalName: "onboarding",+ platform: "browser",+}).outputFiles[0].text;+function fixture() {+ const dom = new JSDOM(+ '<template data-onboarding-ui="steps"></template><template data-onboarding-ui="provider"></template><template data-onboarding-ui="registry"></template>',+ { runScripts: "outside-only", url: "http://localhost/admin/onboarding" },+ );+ dom.window.eval(bundle + ";window.Onboarding = onboarding.Onboarding;");+ const controller = new (dom.window as any).Onboarding({+ api: async () => ({ ok: true, data: {} }),+ orgScope: () => "org:default-org",+ connectorName: (id: string) => id,+ view: () => "onboarding",+ loaded: () => {},+ loadCustomProviders: async () => {},+ navigate: () => {},+ });+ controller.mount();+ return { dom, controller };}async function runLoadOnboarding(modelProviders: unknown,scopeConfig: unknown = { baseModel: "claude-opus-5" },-): Promise<Record<string, FakeElement>> {- const src = slice("let onboardingModels = {};", '$("onboarding-model-provider").onchange') + "\nloadOnboarding();";- const elements: Record<string, FakeElement> = {};+): Promise<Record<string, any>> {+ const { dom, controller } = fixture();const fixtures: Record<string, unknown> = {"/api/model-providers?catalog=cached": modelProviders,"/api/slack-installation": { configured: false },"/api/connector-catalog": { catalog: [] },"/api/scopes/org%3Adefault-org?view=onboarding": scopeConfig,};- const context = vm.createContext({- $: (id: string) =>- (elements[id] ??= {- textContent: "",- className: "",- value: "",- placeholder: "",- disabled: false,- href: "",- options: [],- appendChild(option) {- this.options.push(option);- },- }),- api: async (_method: string, path: string) => ({ ok: true, data: fixtures[path] ?? {} }),- loadModelRegistry: async () => {},- orgScope: () => "org:default-org",- encodeURIComponent,- setStatus: () => {},- connectorName: (id: string) => id,- viewLoadedAt: {},- view: "onboarding",- Date,- document: { createElement: () => ({}) },- });- await vm.runInContext(src, context);+ controller.context.api = async (_method: string, path: string) => ({ ok: true, data: fixtures[path] ?? {} });+ await controller.load();+ const elements = Object.fromEntries(+ [...dom.window.document.querySelectorAll<HTMLElement>("[id]")].map((el) => [+ el.id,+ { textContent: el.textContent?.trim(), className: el.className, value: (el as HTMLInputElement).value },+ ]),+ );+ dom.window.close();return elements;}@@ -86,7 +86,10 @@ const UNCONFIGURED_PROVIDERS = [{ provider: "openai", configured: false, source: "absent" },{ provider: "openrouter", configured: false, source: "absent" },];-const ANTHROPIC_MODELS = [{ id: "claude-opus-5", name: "Claude Opus 5", provider: "anthropic" }];+const ANTHROPIC_MODELS = [+ { id: "first-option", name: "First model", provider: "anthropic" },+ { id: "claude-opus-5", name: "Claude Opus 5", provider: "anthropic" },+];test("harness-carried auth shows the model step as ready without a stored key", async () => {const elements = await runLoadOnboarding({@@ -96,6 +99,7 @@ test("harness-carried auth shows the model step as ready without a stored key",});assert.equal(elements["onboarding-model-badge"]!.textContent, "Ready");assert.equal(elements["onboarding-model-badge"]!.className, "badge ok");+ assert.equal(elements["onboarding-model-id"]!.value, "claude-opus-5");assert.equal(elements["onboarding-model-summary"]!.textContent,"claude-opus-5 · authenticated by the claude harness — no API key needed.",@@ -138,35 +142,71 @@ test("unknown views still fall back to the default view", () => {assert.equal(resolveView("/admin/no-such-view", ""), "history");});-test("model registry verification makes charges and credential scope explicit", () => {- assert.match(html, /id="model-registry-save" disabled>Verify and enable/);- const notice = slice('id="model-registry-verification-notice"', "</p>");+test("model registry verification makes charges and credential scope explicit", async () => {+ const { dom, controller } = fixture();+ const button = dom.window.document.querySelector<HTMLButtonElement>("#model-registry-save")!;+ assert.equal(button.disabled, true);+ const notice = dom.window.document.querySelector("#model-registry-verification-notice")!.textContent!;assert.match(notice, /provider charge/);assert.match(notice, /personal-key access/);- const save = slice('$("model-registry-save").onclick', "let customProvidersLoaded");- assert.match(save, /verify: true/);- assert.match(save, /el.disabled = true/);- assert.match(save, /Verifying…/);- assert.match(save, /finally/);- assert.match(save, /el.disabled = disabled/);- assert.match(html, /Verified with organization credentials/);+ controller.registryId = "known";+ controller.showLookup({+ kind: "builtin",+ spec: { name: "Known", id: "known", contextWindow: 1000, maxTokens: 100, cost: { input: 1, output: 2 } },+ source: "catalog",+ missing: [],+ });+ let complete: (response: unknown) => void = () => {};+ const calls: any[] = [];+ controller.context.api = (...args: any[]) => {+ calls.push(args);+ return new Promise((resolve) => {+ complete = resolve;+ });+ };+ controller.draw();+ const saving = controller.verify();+ assert.equal(button.disabled, true);+ assert.match(button.textContent!, /Verifying/);+ assert.equal(calls[0][0], "POST");+ assert.equal(calls[0][1], "/api/model-registry/known/enable");+ assert.equal(calls[0][2].verify, true);+ complete({ ok: false, data: { message: "Access denied" } });+ await saving;+ assert.equal(button.disabled, false);+ assert.match(dom.window.document.querySelector("#st-model-registry")!.textContent!, /Access denied/);+ dom.window.close();});-test("model setup starts with two inputs, separates missing fields and discards stale lookups", () => {- const form = slice(- '<label\n >Provider\n <select id="model-registry-provider">',- 'id="model-registry-result"',- );- assert.match(form, /model-registry-id/);- assert.doesNotMatch(form, /model-registry-contextWindow|model-registry-input/);- assert.match(html, /<summary>Advanced overrides<\/summary>/);- assert.match(html, /id="model-registry-missing-fields"/);- const code = slice("let modelRegistryTemplates = []", "let customProvidersLoaded");- assert.match(code, /request !== modelRegistryLookupRequest/);- assert.match(code, /\$\("model-registry-id"\)\.oninput = resetRegistryLookup/);- assert.match(code, /JSON\.stringify\(identity\) !== JSON\.stringify\(lookup.identity\)/);- assert.match(code, /Choose a compatible template/);- assert.match(code, /source/);+test("model setup separates missing fields and discards stale lookups", async () => {+ const { dom, controller } = fixture();+ assert.equal(dom.window.document.querySelector<HTMLDivElement>("#model-registry-result")!.hidden, true);+ controller.registryId = "first";+ let complete: (response: unknown) => void = () => {};+ controller.context.api = () =>+ new Promise((resolve) => {+ complete = resolve;+ });+ const pending = controller.lookupModel();+ const input = dom.window.document.querySelector<HTMLInputElement>("#model-registry-id")!;+ input.value = "second";+ input.dispatchEvent(new dom.window.Event("input"));+ complete({ ok: true, data: { spec: { id: "first" }, source: "catalog" } });+ await pending;+ assert.equal(controller.lookup, null);+ controller.showLookup({+ kind: "custom",+ spec: { id: "second", name: "Second", cost: {} },+ source: "provider",+ missing: ["template", "contextWindow"],+ });+ controller.draw();+ assert.ok(dom.window.document.querySelector("#model-registry-missing-fields #model-registry-template"));+ assert.ok(dom.window.document.querySelector("#model-registry-advanced-fields #model-registry-name"));+ assert.equal(dom.window.document.querySelector<HTMLInputElement>("#model-registry-name")!.value, "Second");+ controller.registryId = "third";+ assert.throws(() => controller.collect(), /current model/);+ dom.window.close();});test("cold catalog preserves the configured dynamic model and its provider", async () => {@@ -179,8 +219,41 @@ test("cold catalog preserves the configured dynamic model and its provider", asyassert.equal(elements["onboarding-model-id"].value, model.id);});-test("upfront Slack links select connectors before launching, including completion", () => {+test("upfront Slack links select Slack settings before launching, including completion", () => {for (const step of ["setup", "install", "connected"])- assert.equal(resolveView("/admin", `?slack=${step}`), "connectors");+ assert.equal(resolveView("/admin", `?slack=${step}`), "slack-settings");assert.equal(resolveView("/admin", "?slack=unknown"), "history");});++test("pending onboarding reads preserve the provider associated with a newly entered key", async () => {+ const { dom, controller } = fixture();+ let complete: (response: unknown) => void = () => {};+ controller.context.api = async (_method: string, path: string) => {+ if (path === "/api/model-providers?catalog=cached")+ return new Promise((resolve) => {+ complete = resolve;+ });+ if (path.includes("?view=onboarding")) return { ok: true, data: { baseModel: "claude-opus-5" } };+ return { ok: true, data: {} };+ };+ const pending = controller.load();+ const select = dom.window.document.querySelector<HTMLSelectElement>("#onboarding-model-provider")!;+ select.value = "openai";+ select.dispatchEvent(new dom.window.Event("change"));+ const key = dom.window.document.querySelector<HTMLInputElement>("#onboarding-model-key")!;+ key.value = "test-only-key";+ key.dispatchEvent(new dom.window.Event("input"));+ complete({+ ok: true,+ data: {+ providers: UNCONFIGURED_PROVIDERS,+ models: [...ANTHROPIC_MODELS, { id: "gpt-test", name: "GPT test", provider: "openai" }],+ },+ });+ await pending;+ assert.equal(controller.provider, "openai");+ assert.equal(controller.model, "gpt-test");+ assert.equal(select.value, "openai");+ assert.equal(key.value, "test-only-key");+ dom.window.close();+});diff --git a/plugins/admin/test/setting-state.test.ts b/plugins/admin/test/setting-state.test.tsnew file mode 100644index 000000000..adb621cb2--- /dev/null+++ b/plugins/admin/test/setting-state.test.ts@@ -0,0 +1,45 @@+import assert from "node:assert/strict";+import { test } from "node:test";+import { SettingState, settingRegistry } from "../ui/setting-state.ts";++test("shared settings keep edits made while a save is pending", () => {+ const state = new SettingState("example");+ const registry = settingRegistry(new Map([[state.key, state]]));+ state.draft = { value: "initial" };+ registry.capture(state.key);+ state.draft.value = "submitted";+ const submitted = registry.collect(state.key);+ registry.status(state.key, "Saving…", "saving");+ state.draft.value = "newer edit";+ state.changed();+ assert.equal(state.message, "Saving…");+ registry.commit(state.key, submitted);+ assert.equal(state.draft.value, "newer edit");+ assert.equal(state.dirty, true);+ assert.equal(state.saving, false);+ assert.equal(state.message, "Unsaved changes");+ state.draft.value = "submitted";+ state.changed();+ assert.equal(state.dirty, false);+});++test("shared settings compare normalized payloads and validate before saving", () => {+ class NormalizedSetting extends SettingState {+ collect(validate = true) {+ const value = this.draft.value.trim();+ if (validate && !value) throw new Error("Required");+ return { value };+ }+ }+ const state = new NormalizedSetting("example");+ const registry = settingRegistry(new Map([[state.key, state]]));+ state.draft = { value: "initial" };+ registry.capture(state.key);+ state.draft.value = " initial ";+ assert.equal(state.dirty, false);+ state.draft.value = " ";+ assert.equal(state.dirty, true);+ assert.throws(() => registry.collect(state.key), /Required/);+ assert.equal(registry.statusKey("st-example"), state.key);+ assert.equal(registry.statusKey("st-missing"), undefined);+});diff --git a/plugins/admin/test/settings-lit.test.ts b/plugins/admin/test/settings-lit.test.tsnew file mode 100644index 000000000..cd19c2181--- /dev/null+++ b/plugins/admin/test/settings-lit.test.ts@@ -0,0 +1,138 @@+import assert from "node:assert/strict";+import test from "node:test";+import { readFileSync } from "node:fs";+import { buildSync } from "esbuild";+import { JSDOM } from "jsdom";+const bundle = buildSync({+ entryPoints: [new URL("../ui/settings.ts", import.meta.url).pathname],+ bundle: true,+ write: false,+ format: "iife",+ globalName: "settingsUI",+ platform: "browser",+}).outputFiles[0]!.text;+function setup() {+ const dom = new JSDOM(readFileSync(new URL("../public/index.html", import.meta.url), "utf8"), {+ runScripts: "outside-only",+ });+ dom.window.structuredClone = structuredClone;+ dom.window.eval(bundle + "; window.settingsUI=settingsUI; settingsUI.mountCards();");+ return dom;+}+const models = {+ baseModelDefault: "a",+ baseModelOptions: [{ id: "a", name: "Alpha" }],+ harnessDefault: "pi",+ harnessOptions: ["pi", "codex"],+ modelsByHarness: { pi: [{ id: "a", name: "Alpha" }], codex: [{ id: "b", name: "Beta" }] },+ thinkingLevelsByHarness: { pi: ["auto", "high"], codex: ["low"] },+ runtime: { harnessId: "pi", modelId: "a", effortLevel: "high", fastMode: true },+ fastModeHarnessIds: ["pi"],+ fastModeModelIds: ["a"],+ webuiModels: [],+};+test("runtime selection derives compatible model, reasoning, and fast mode from state", () => {+ const dom = setup();+ try {+ dom.window.eval("settingsUI.load(" + JSON.stringify(models) + ',"org:test","runtime")');+ const input = dom.window.document.getElementById("base-harness") as HTMLSelectElement;+ input.value = "codex";+ input.dispatchEvent(new dom.window.Event("change", { bubbles: true }));+ assert.deepEqual(JSON.parse(String(dom.window.eval('JSON.stringify(settingsUI.collect("runtime"))'))), {+ harnessId: "codex",+ modelId: "b",+ effortLevel: "low",+ fastMode: false,+ });+ assert.equal((dom.window.document.querySelector('[data-save="runtime"]') as HTMLButtonElement).disabled, false);+ } finally {+ dom.window.close();+ }+});+test("model chips add and remove with stable keyed rendering", () => {+ const dom = setup();+ try {+ dom.window.eval("settingsUI.load(" + JSON.stringify(models) + ',"org:test","webui-models")');+ const select = dom.window.document.getElementById("webui-models-add") as HTMLSelectElement;+ select.value = "b";+ select.dispatchEvent(new dom.window.Event("change"));+ dom.window.document.getElementById("webui-models-add-button")!.click();+ assert.equal(dom.window.eval('settingsUI.collect("webui-models").ids.join()'), "b");+ dom.window.document.querySelector<HTMLButtonElement>('[aria-label="Remove b"]')!.click();+ assert.equal(dom.window.eval('settingsUI.states.get("webui-models").dirty'), false);+ } finally {+ dom.window.close();+ }+});+test("SOUL conflict keeps draft while replacing saved revision and version", () => {+ const dom = setup();+ try {+ dom.window.eval('settingsUI.load({soul:"old",soulVersion:1},"org:test","soul")');+ dom.window.document.getElementById("soul-edit")!.click();+ const input = dom.window.document.getElementById("soul") as HTMLTextAreaElement;+ input.value = "draft <img src=x>";+ input.dispatchEvent(new dom.window.Event("input"));+ dom.window.eval('settingsUI.refreshSoul({soul:"other",soulVersion:2})');+ assert.equal(input.value, "draft <img src=x>");+ assert.equal(dom.window.document.getElementById("soul-saved")!.textContent, "other");+ assert.equal(dom.window.eval('settingsUI.collect("soul").expectedVersion'), 2);+ assert.equal(dom.window.document.querySelector("#card-soul img"), null);+ } finally {+ dom.window.close();+ }+});++test("credential editor derives broker capabilities and preserves write-only secrets", () => {+ const dom = setup();+ try {+ dom.window.eval(+ 'settingsUI.configureCredentials({label: id => id,formatTime:String,edit(){},remove(){}}); settingsUI.loadCredentials([],[],[],[],"org:test"); settingsUI.credentialState.begin({slug:"service",name:"Service",host:"api.example.com",updatedAt:10,hasSecret:true,injection:{actor:true},grantees:["org:test"]})',+ );+ const doc = dom.window.document;+ const secret = doc.getElementById("sc-secret") as HTMLInputElement;+ assert.equal(secret.value, "");+ assert.equal(dom.window.eval('"secret" in settingsUI.credentialState.collect()'), false);+ assert.equal(dom.window.eval("settingsUI.credentialState.collect().injection.actor"), true);+ const host = doc.getElementById("sc-host") as HTMLInputElement;+ host.value = "changed.example.com";+ host.dispatchEvent(new dom.window.Event("input"));+ assert.equal(doc.getElementById("sc-cap-host")!.textContent, "changed.example.com and its subdomains");+ assert.equal((doc.getElementById("sc-save") as HTMLButtonElement).disabled, false);+ assert.equal(dom.window.eval("settingsUI.credentialState.collect().expectedUpdatedAt"), 10);+ } finally {+ dom.window.close();+ }+});++test("credential delivery transitions exclude narrower broker grants from env payloads", () => {+ const dom = setup();+ try {+ dom.window.eval(+ 'settingsUI.loadCredentials([],[],[],[],"org:test"); settingsUI.credentialState.begin(null); settingsUI.credentialState.change("name","Example");settingsUI.credentialState.change("slug","example");settingsUI.credentialState.change("org",false);settingsUI.credentialState.change("people","[email protected]");settingsUI.credentialState.change("delivery","env");settingsUI.credentialState.change("envkey","EXAMPLE_KEY")',+ );+ assert.equal(dom.window.eval("settingsUI.credentialState.collect().grantees.join()"), "org:test");+ assert.equal(dom.window.eval("settingsUI.credentialState.collect().host"), "");+ assert.equal(dom.window.eval("settingsUI.credentialState.validate(settingsUI.credentialState.collect())"), "");+ dom.window.eval('settingsUI.credentialState.change("envkey","AGENT_SECRET")');+ assert.match(+ String(dom.window.eval("settingsUI.credentialState.validate(settingsUI.credentialState.collect())")),+ /reserved/,+ );+ } finally {+ dom.window.close();+ }+});++test("credential save acknowledges its submitted snapshot and retains newer edits", () => {+ const dom = setup();+ try {+ dom.window.eval(+ 'settingsUI.loadCredentials([],[],[],[],"org:test"); settingsUI.credentialState.begin({slug:"test",name:"Old",host:"example.com",updatedAt:1,grantees:["org:test"]});settingsUI.credentialState.change("name","Submitted");window.submitted=settingsUI.credentialState.collect();settingsUI.credentialState.change("name","Newer draft");settingsUI.loadCredentials([{slug:"test",updatedAt:2}],[],[],[],"org:test");settingsUI.credentialState.commit(submitted)',+ );+ assert.equal(dom.window.eval("settingsUI.credentialState.collect().name"), "Newer draft");+ assert.equal(dom.window.eval("settingsUI.credentialState.collect().expectedUpdatedAt"), 2);+ assert.equal(dom.window.eval("settingsUI.credentialState.dirty"), true);+ } finally {+ dom.window.close();+ }+});diff --git a/plugins/admin/test/settings-load.test.ts b/plugins/admin/test/settings-load.test.tsindex ba174cb60..ead314621 100644--- a/plugins/admin/test/settings-load.test.ts+++ b/plugins/admin/test/settings-load.test.ts@@ -1,3 +1,4 @@+import { litFixture } from "./lit-fixture.ts";import assert from "node:assert/strict";import { readFileSync } from "node:fs";import test from "node:test";@@ -19,9 +20,14 @@ test("settings navigation never starts the all-scopes history scan", () => {let settings = 0;const node = { classList: { toggle() {} } };const context = vm.createContext({+ governanceUI: { transcript: { cancel() {} } },transcriptObserver: null,+ adminPreviewTheme: null,+ syncAdminTheme() {},+ governanceReadyScope: "org:example",+ setGovernancePending() {},scopeDir: null,- document: { body: { dataset: {}, ...node } },+ document: { body: { dataset: {}, ...node }, documentElement: { style: { removeProperty() {} } } },$: () => node,isGovLike: (view: string) => ["customize", "models", "credentials", "governance"].includes(view),loadScopeDirectory: () => {@@ -96,45 +102,92 @@ test("catalog completion appends options only to the requesting settings view",}});-test("branding reload clears only the committed draft and preserves other unsaved settings", () => {- const source = extract('} else if (key === "branding") {', "} else if (SAVE_RELOADS");- const block = source.slice(source.indexOf("{") + 1);+test("branding saves commit the Lit draft and preserve unrelated settings", async () => {+ const source = extract(+ 'document.querySelectorAll("[data-save]").forEach',+ '$("view-governance").addEventListener("input"',+ );for (const otherDraft of [false, true]) {- const snapshots = new Map();- let reloads = 0;- let recorded = false;- const context = vm.createContext({- key: "branding",- body: { selfLabel: "Saved name" },- sectionSnapshots: snapshots,- updateSectionDirty: () => {- recorded = snapshots.has("branding");- },- SAVE_ST: { branding: "st-branding" },- setStatus() {},- hasGovernanceDraft: () => otherDraft,- location: {- reload: () => {- reloads++;+ const f = litFixture();+ try {+ f.ui.settings.load(+ { branding: { selfLabel: "Saved name", accent: "#111111" }, soul: "Original SOUL" },+ "org:test",+ );+ f.ui.settings.states.get("branding").change("accent", "#123456");+ if (otherDraft) f.ui.settings.states.get("soul").change("content", "Unsaved SOUL");+ const body = f.ui.collect("branding");+ const snapshots = new Map();+ const requests: any[] = [];+ let reloads = 0;+ const button = f.document.createElement("button");+ button.dataset.save = "branding";+ f.root.append(button);+ const context = vm.createContext({+ document: f.document,+ governanceUI: f.ui,+ scope: "org:test",+ governanceReq: 1,+ governanceSaveSeq: 0,+ SAVE: { branding: () => f.ui.collect("branding") },+ SAVE_ST: { branding: "st-branding" },+ governanceSaveReview: async () => true,+ setStatus: (_id: string, message: string, tone: string) => f.ui.status("branding", message, tone),+ savedBranding: { selfLabel: "Saved name", accent: "#111111", iconUrl: "https://example.com/icon.png" },+ sectionSnapshots: snapshots,+ api: async (...args: any[]) => {+ requests.push(args);+ return { ok: true };},- },- });- vm.runInContext(`(() => {${block}})()`, context);- assert.equal(recorded, true);- assert.equal(snapshots.get("branding"), JSON.stringify({ selfLabel: "Saved name" }));- assert.equal(reloads, otherDraft ? 0 : 1);+ hasGovernanceDraft: () => [...f.ui.settings.states.values()].some((state: any) => state.dirty),+ location: { reload: () => reloads++ },+ });+ vm.runInContext(source, context);+ await button.onclick!(new f.window.PointerEvent("click"));+ assert.equal(requests.length, 1);+ assert.equal(requests[0][0], "PUT");+ assert.equal(requests[0][1], "/api/scopes/org%3Atest/branding");+ assert.equal(requests[0][2].selfLabel, "Saved name");+ assert.equal(requests[0][2].iconUrl, "https://example.com/icon.png");+ assert.equal(requests[0][2].accent, "#123456");+ assert.equal(context.savedBranding, requests[0][2]);+ assert.equal(snapshots.get("branding"), JSON.stringify(body));+ assert.equal(f.ui.states.get("branding").dirty, false);+ assert.equal(f.ui.states.get("soul").dirty, otherDraft);+ assert.equal(f.ui.collect("soul").content, otherDraft ? "Unsaved SOUL" : "Original SOUL");+ assert.equal(reloads, otherDraft ? 0 : 1);+ } finally {+ f.dom.window.close();+ }+ }+});++test("other settings projections leave the loaded Governance cards intact", () => {+ const load = html.slice(html.indexOf("async function loadScope()"));+ const start = load.indexOf('if (requestedView === "governance") {');+ const end = load.indexOf('if (requestedView === "customize")', start);+ const source = load.slice(start, end);+ for (const requestedView of ["customize", "models", "credentials", "slack-settings"]) {+ vm.runInNewContext(source, { requestedView });}});test("credential usage distinguishes loading, failure, and confirmed zero", () => {- const context = vm.createContext({ plural: (n: number, word: string) => `${n} ${word}s`, fmtTime: String });- vm.runInContext(extract("function serviceCredentialUsageLabel(", "function renderServiceCreds("), context);- assert.equal(vm.runInContext("serviceCredentialUsageLabel({})", context), "Loading usage…");- assert.equal(vm.runInContext("serviceCredentialUsageLabel({usageUnavailable:true})", context), "Usage unavailable");- assert.equal(- vm.runInContext("serviceCredentialUsageLabel({usageCount:0})", context),- "0 successful uses in retained broker history",- );+ const f = litFixture();+ try {+ f.root.innerHTML = '<template data-settings-card="card-service-credentials"></template>';+ f.ui.settings.mountCards();+ for (const [usage, message] of [+ [{}, "Loading usage…"],+ [{ usageUnavailable: true }, "Usage unavailable"],+ [{ usageCount: 0 }, "0 successful uses in retained broker history"],+ ] as const) {+ f.ui.settings.loadCredentials([{ slug: "test", host: "example.com", ...usage }], [], [], [], "org:test");+ assert.ok(f.document.querySelector("#sc-list")!.textContent!.includes(message));+ }+ } finally {+ f.dom.window.close();+ }});test("usage completion preserves credentials on failure and ignores stale scope, view, and reload responses", async () => {@@ -153,7 +206,7 @@ test("usage completion preserves credentials on failure and ignores stale scope,},});vm.runInContext(- extract("async function loadServiceCredentialUsage(", "function serviceCredentialUsageLabel("),+ extract("async function loadServiceCredentialUsage(", "governanceUI.settings.configureCredentials("),context,);const work = vm.runInContext('loadServiceCredentialUsage("org:example", 1)', context);@@ -175,30 +228,38 @@ test("usage completion preserves credentials on failure and ignores stale scope,});test("credential request displays loading, then a visible retry on failure", async () => {- const pending = Promise.withResolvers<unknown>();- const messages: unknown[] = [];- const add = { disabled: false };- const context = vm.createContext({- scope: "org:example",- view: "credentials",- governanceReq: 0,- loadedGovernanceScope: null,- serviceCredList: [{ slug: "stale" }],- setServiceCredentialState: (...args: unknown[]) => messages.push(args),- $: () => add,- loadPersonalKeychainSummary() {},- setStatus() {},- api: () => pending.promise,- });- const source = extract("async function loadScope() {", " const refreshModelChoices = [];");- vm.runInContext(source + "}", context);- const work = vm.runInContext("loadScope()", context);- assert.deepEqual(messages, [["Loading credentials…"]]);- assert.equal(add.disabled, true);- assert.equal(context.serviceCredList.length, 0);- pending.resolve({ ok: false, status: 500 });- await work;- assert.deepEqual(messages.at(-1), ["Could not load credentials.", true]);+ const f = litFixture();+ try {+ f.root.innerHTML = '<template data-settings-card="card-service-credentials"></template>';+ f.ui.settings.mountCards();+ const pending = Promise.withResolvers<unknown>();+ let retries = 0;+ f.ui.settings.configureCredentials({ reload: () => retries++, label: String, formatTime: String });+ const context = vm.createContext({+ scope: "org:example",+ view: "credentials",+ governanceReq: 0,+ loadedGovernanceScope: null,+ serviceCredList: [{ slug: "stale" }],+ governanceUI: f.ui,+ loadPersonalKeychainSummary() {},+ setStatus() {},+ api: () => pending.promise,+ });+ const source = extract("async function loadScope() {", " const refreshModelChoices = [];");+ vm.runInContext(source + "}", context);+ const work = vm.runInContext("loadScope()", context);+ assert.equal(f.document.querySelector("#sc-list")!.textContent!.trim(), "Loading credentials…");+ assert.equal((f.document.querySelector("#sc-add") as HTMLButtonElement).disabled, true);+ assert.equal(context.serviceCredList.length, 0);+ pending.resolve({ ok: false, status: 500 });+ await work;+ assert.ok(f.document.querySelector("#sc-list")!.textContent!.includes("Could not load credentials."));+ f.document.querySelector<HTMLButtonElement>("#sc-list button")!.click();+ assert.equal(retries, 1);+ } finally {+ f.dom.window.close();+ }});test("admin requests convert rejected fetches and interrupted bodies into failure states", async () => {@@ -220,3 +281,20 @@ test("admin requests convert rejected fetches and interrupted bodies into failurassert.equal(result.data.message, "Network request failed.");}});++test("admin shell calls resolve against the shipped Lit bundle", () => {+ const f = litFixture();+ try {+ const calls = [...html.matchAll(/governanceUI((?:\.[A-Za-z_$][\w$]*)+)\s*\(/g)];+ assert.ok(calls.length > 0);+ for (const [, path] of calls) {+ const value = path!+ .slice(1)+ .split(".")+ .reduce((owner: any, key) => owner?.[key], f.ui);+ assert.equal(typeof value, "function", `governanceUI${path}`);+ }+ } finally {+ f.dom.window.close();+ }+});diff --git a/plugins/admin/test/settings-provider-races.test.ts b/plugins/admin/test/settings-provider-races.test.tsnew file mode 100644index 000000000..cc41d4941--- /dev/null+++ b/plugins/admin/test/settings-provider-races.test.ts@@ -0,0 +1,80 @@+import assert from "node:assert/strict";+import test from "node:test";+import { buildSync } from "esbuild";+import { JSDOM } from "jsdom";+const bundle = buildSync({+ entryPoints: [new URL("../ui/settings-providers.ts", import.meta.url).pathname],+ bundle: true,+ write: false,+ format: "iife",+ globalName: "providers",+ platform: "browser",+}).outputFiles[0].text;+function fixture() {+ const dom = new JSDOM('<template data-settings-card="custom-provider-dialog"></template>', {+ runScripts: "outside-only",+ });+ dom.window.HTMLDialogElement.prototype.showModal = function () {+ this.open = true;+ };+ dom.window.HTMLDialogElement.prototype.close = function () {+ this.open = false;+ };+ dom.window.eval(bundle + ";window.providers = providers;");+ const ui = (dom.window as any).providers;+ const requests: Array<{ resolve: (value: any) => void; reject: (reason: unknown) => void }> = [];+ let refreshes = 0;+ ui.configureProviders({+ api: () => new Promise((resolve, reject) => requests.push({ resolve, reject })),+ refresh: async () => {+ refreshes++;+ },+ });+ ui.mountProviders();+ const open = (name: string) =>+ ui.openProvider({+ id: name,+ name,+ baseUrl: "https://api.example.com",+ protocol: "openai",+ models: [{ id: "test" }],+ });+ return { dom, ui, requests, open, refreshes: () => refreshes };+}+const tick = () => new Promise((resolve) => setTimeout(resolve, 0));++test("custom provider save reports persisted snapshot while retaining newer edits", async () => {+ const { dom, ui, requests, open, refreshes } = fixture();+ open("first");+ dom.window.document.getElementById("custom-provider-save")!.click();+ const input = dom.window.document.getElementById("custom-provider-name") as HTMLInputElement;+ input.value = "Newer name";+ input.dispatchEvent(new dom.window.Event("input"));+ requests[0].resolve({ ok: true });+ await tick();+ assert.equal(ui.provider.draft.name, "Newer name");+ assert.equal(ui.provider.saving, false);+ assert.equal(refreshes(), 1);+ assert.match(ui.provider.message, /newer edits are not saved/);+ assert.equal((dom.window.document.getElementById("custom-provider-dialog") as HTMLDialogElement).open, true);+ dom.window.close();+});++test("old provider save cannot clear pending state in a reopened dialog", async () => {+ const { dom, ui, requests, open } = fixture();+ open("first");+ dom.window.document.getElementById("custom-provider-save")!.click();+ dom.window.document.getElementById("custom-provider-cancel")!.click();+ open("second");+ dom.window.document.getElementById("custom-provider-save")!.click();+ requests[0].reject(new Error("old error"));+ await tick();+ assert.equal(ui.provider.saving, true);+ assert.equal(ui.provider.draft.id, "second");+ assert.equal(ui.provider.message, "Saving…");+ requests[1].resolve({ ok: true });+ await tick();+ assert.equal(ui.provider.saving, false);+ assert.equal((dom.window.document.getElementById("custom-provider-dialog") as HTMLDialogElement).open, false);+ dom.window.close();+});diff --git a/plugins/admin/test/slack-activity-lit.test.ts b/plugins/admin/test/slack-activity-lit.test.tsnew file mode 100644index 000000000..00d13f89e--- /dev/null+++ b/plugins/admin/test/slack-activity-lit.test.ts@@ -0,0 +1,92 @@+import assert from "node:assert/strict";+import test from "node:test";+import { buildSync } from "esbuild";+import { JSDOM } from "jsdom";+const bundle = buildSync({+ entryPoints: [new URL("../ui/slack-activity.ts", import.meta.url).pathname],+ bundle: true,+ write: false,+ format: "iife",+ globalName: "slackUI",+}).outputFiles[0].text;+function setup() {+ const dom = new JSDOM('<div id="shellbar"></div><div id="view-data"></div>', {+ runScripts: "outside-only",+ url: "http://localhost/admin/slack",+ });+ dom.window.HTMLElement.prototype.scrollIntoView = () => {};+ dom.window.scrollTo = () => {};+ dom.window.requestAnimationFrame = () => 0;+ dom.window.eval(+ bundle ++ `;window.ui=slackUI;window.currentView='slack';window.state={container:'C1'};window.calls=[];window.responses=[];window.shells=[];ui.configure({api:async(method,path)=>{calls.push(path);return responses.shift();},go:st=>{state=st;currentView=st.view},urlToState:()=>state,stateToUrl:st=>'/admin/'+st.view,pageShell:s=>{shells.push(s);document.getElementById('shellbar').innerHTML='<button class="back">Back</button><span class="shell-title">Title</span><span class="shell-context">Context</span><span class="shell-spacer"></span>';},navLink:()=>document.createElement('a'),relTime:x=>x,fmtTime:x=>x,brandSelfLabel:()=>"QM",slackParseText:text=>document.createTextNode(text),slackContainerLabel:x=>x,slackContainerScope:()=>null,loadSlackContainers:async()=>({ok:true,data:{}}),containers:()=>[],truncated:()=>false,view:()=>currentView,loaded:()=>{}});`,+ );+ return dom;+}+const first = { ts: "2", authorId: "u", text: "second", createdAt: "2026-01-01T00:02:00Z" };+const older = { ts: "1", authorId: "u", text: "first", createdAt: "2026-01-01T00:01:00Z" };+test("Slack paging preserves keyed message nodes and recomputes the grouping seam", async () => {+ const dom = setup();+ try {+ dom.window.eval(+ `responses.push({ok:true,data:{messages:[${JSON.stringify(first)}],hasMore:true}},{ok:true,data:{messages:[${JSON.stringify(older)}],hasMore:false}})`,+ );+ await dom.window.eval("ui.renderSlackMirror(state)");+ const original = dom.window.document.querySelector('[data-ts="2"]')!;+ await dom.window.eval("ui.activity.earlierMessages()");+ assert.equal(dom.window.document.querySelector('[data-ts="2"]'), original);+ assert.equal(original.classList.contains("sm-cont"), true);+ assert.equal(dom.window.document.querySelectorAll(".sm-day").length, 1);+ assert.equal(dom.window.document.querySelector(".load-earlier"), null);+ assert.equal(dom.window.document.querySelectorAll(".sm-msg").length, 2);+ } finally {+ dom.window.close();+ }+});+test("Slack search ignores responses from superseded queries", async () => {+ const dom = setup();+ try {+ dom.window.eval(+ 'window.pending=[];ui.configure({...{} ,api:()=>new Promise(resolve=>pending.push(resolve)),view:()=>"slack",urlToState:()=>state,slackParseText:text=>document.createTextNode(text),slackContainerLabel:x=>x,brandSelfLabel:()=>"QM",fmtTime:x=>x,relTime:x=>x});window.first=ui.activity.search("old",null);window.second=ui.activity.search("new",null);pending[1]({ok:true,data:{messages:[]}})',+ );+ await dom.window.eval("second");+ dom.window.eval('pending[0]({ok:false,status:500,data:{message:"obsolete"}})');+ await dom.window.eval("first");+ assert.equal(dom.window.document.getElementById("view-data")!.textContent, "No matches in the mirror.");+ } finally {+ dom.window.close();+ }+});+test("Judgment pagination updates from state and escapes untrusted reasons", async () => {+ const dom = setup();+ try {+ dom.window.eval(+ `currentView='judgments';state={};responses.push({ok:true,data:{judgments:[{id:1,container:'C1',decision:'ignore',reason:'<img src=x>',createdAt:'now'}],counts:{ignore:1},hasMore:true}},{ok:true,data:{judgments:[{id:2,container:'C1',decision:'act',createdAt:'before'}],hasMore:false}})`,+ );+ await dom.window.eval("ui.renderAmbientJudgments(state)");+ assert.equal(dom.window.document.querySelectorAll("img").length, 0);+ assert.match(dom.window.document.querySelector(".dense-preview")!.textContent!, /<img src=x>/);+ await dom.window.eval('ui.activity.earlierLog("judgments","/api/ambient-judgments?decision=act%2Cignore")');+ assert.equal(dom.window.document.querySelectorAll(".dense-row").length, 2);+ assert.equal(dom.window.document.querySelector(".load-earlier"), null);+ } finally {+ dom.window.close();+ }+});+test("Ack detail renders its message, candidate slate and Slack link from fetched data", async () => {+ const dom = setup();+ try {+ dom.window.eval(+ `currentView='ackemoji';state={jid:'7'};responses.push({ok:true,data:{workspaceUrl:'https://acme.slack.com/',pick:{id:7,channel:'C1',ts:'12.34',outcome:'picked',picked:'eyes',message:'hello',candidates:'eyes wave',createdAt:'today'}}})`,+ );+ await dom.window.eval("ui.renderAckEmojiPicks(state)");+ assert.equal(dom.window.document.querySelector("pre")!.textContent, "hello");+ assert.equal(dom.window.document.querySelector(".pill.accent")!.textContent, ":eyes:");+ assert.equal(+ dom.window.document.querySelector<HTMLAnchorElement>(".judg-extlink")!.href,+ "https://acme.slack.com/archives/C1/p1234",+ );+ } finally {+ dom.window.close();+ }+});diff --git a/plugins/admin/test/slack-installation-view.test.ts b/plugins/admin/test/slack-installation-view.test.tsindex 1a068ee93..816c4dc89 100644--- a/plugins/admin/test/slack-installation-view.test.ts+++ b/plugins/admin/test/slack-installation-view.test.ts@@ -1,34 +1,30 @@import assert from "node:assert/strict";import { readFileSync } from "node:fs";import test from "node:test";-import vm from "node:vm";--const html = readFileSync(new URL("../public/index.html", import.meta.url), "utf8");+import { JSDOM } from "jsdom";+import { buildSync } from "esbuild";+const bundle = buildSync({+ entryPoints: [new URL("../ui/integrations.ts", import.meta.url).pathname],+ bundle: true,+ write: false,+ format: "iife",+ globalName: "ui",+}).outputFiles[0].text;async function render(data: Record<string, unknown>) {- const elements = new Map<string, any>();- const start = html.indexOf("async function loadSlackInstallation() {");- const end = html.indexOf('$("slack-installation-start").onclick', start);- await vm.runInNewContext(html.slice(start, end) + "loadSlackInstallation()", {- $: (id: string) => {- assert.ok(html.includes(`id="${id}"`), `missing ${id}`);- if (!elements.has(id)) {- const hidden = new Set<string>();- elements.set(id, {- open: false,- classList: {- toggle: (name: string, value: boolean) => (value ? hidden.add(name) : hidden.delete(name)),- contains: (name: string) => hidden.has(name),- },- });- }- return elements.get(id);- },- api: async () => ({ ok: true, data }),- slackLinkStarted: false,- URLSearchParams,- location: { search: "" },+ const dom = new JSDOM(readFileSync(new URL("../public/index.html", import.meta.url), "utf8"), {+ runScripts: "outside-only",+ url: "http://localhost/admin/slack-settings",});- return (id: string) => elements.get(id);+ dom.window.eval(+ bundle ++ ";window.ui=ui;ui.mountCards();ui.configure({api:async()=>({ok:true,data:" ++ JSON.stringify(data) ++ '}),orgScope:()=>"org:test",connectorName:x=>x,fmtTime:x=>x});',+ );+ await dom.window.eval("ui.loadSlackInstallation()");+ const result = (id: string) => dom.window.document.getElementById(id) as any;+ test.after(() => dom.window.close());+ return result;}test("public QM leads with manifest setup and hides hosted actions and instructions", async () => {@@ -39,30 +35,40 @@ test("public QM leads with manifest setup and hides hosted actions and instructi});assert.equal(el("slack-installation-start").classList.contains("hidden"), true);assert.equal(el("slack-own-app-guide").open, true);- assert.equal(el("slack-own-app-label").textContent, "Set up Slack");+ assert.equal(el("slack-own-app-label").textContent.trim(), "Set up Slack");assert.equal(el("slack-hosted-switch").classList.contains("hidden"), true);- assert.match(el("slack-installation-description").textContent, /manifest/);+ assert.match(el("slack-installation-description").textContent.trim(), /manifest/);assert.match(el("slack-installation-create").href, /manifest_json/);});test("hosted connection offers re-add and keeps custom setup secondary", async () => {const el = await render({ configured: true, source: "service", installAvailable: true, teamName: "Development YC" });- assert.equal(el("slack-installation-start-label").textContent, "Re-add to Slack");+ assert.equal(el("slack-installation-start-label").textContent.trim(), "Re-add to Slack");assert.equal(el("slack-installation-start").disabled, false);- assert.equal(el("slack-installation-state").textContent, "Development YC");- assert.equal(el("slack-own-app-label").textContent, "Use your own Slack app");- assert.equal(el("slack-own-app-guide"), undefined);+ assert.equal(el("slack-installation-state").textContent.trim(), "Development YC");+ assert.equal(el("slack-own-app-label").textContent.trim(), "Use your own Slack app");+ assert.equal(el("slack-own-app-guide").open, false);});test("custom connection cannot be replaced by hosted OAuth without disconnecting", async () => {const el = await render({ configured: true, source: "admin", installAvailable: true });assert.equal(el("slack-installation-start").disabled, true);- assert.equal(el("slack-installation-description").textContent, "Custom app");+ assert.equal(el("slack-installation-description").textContent.trim(), "Custom app");});-test("managed credentials alone do not block retry of an unfinished route activation", () => {- assert.match(- html,- /r\.data\.configured && !\(r\.data\.source === "service" && r\.data\.setup\?\.connected === false\)/,- );+test("managed credentials alone do not block retry of an unfinished route activation", async () => {+ const dom = new JSDOM('<template data-integrations-card="card-slack-installation"></template>', {+ runScripts: "outside-only",+ url: "http://localhost/admin/slack-settings?slack=install",+ });+ try {+ dom.window.eval(+ bundle ++ ';window.ui=ui;window.methods=[];ui.mountCards();ui.configure({api:async(method)=>{methods.push(method);return {ok:true,data:{configured:true,source:"service",installAvailable:true,setup:{connected:false}}}},orgScope:()=>"org:test"});',+ );+ await dom.window.eval("ui.loadSlackInstallation()");+ assert.deepEqual(JSON.parse(String(dom.window.eval("JSON.stringify(methods)"))), ["GET", "POST"]);+ } finally {+ dom.window.close();+ }});diff --git a/plugins/admin/test/slack-rendering.test.ts b/plugins/admin/test/slack-rendering.test.tsindex 1445c4c2f..4e4eae14d 100644--- a/plugins/admin/test/slack-rendering.test.ts+++ b/plugins/admin/test/slack-rendering.test.ts@@ -6,7 +6,7 @@ import vm from "node:vm";const html = readFileSync(new URL("../public/index.html", import.meta.url), "utf8");const source = html.slice(html.indexOf(" function slackUnescape("),- html.indexOf(" function slackAuthorLabel("),+ html.indexOf(" governanceUI.slackActivity.configure("),);class RenderNode {diff --git a/plugins/admin/test/transcript-lit.test.ts b/plugins/admin/test/transcript-lit.test.tsnew file mode 100644index 000000000..b4290d8c2--- /dev/null+++ b/plugins/admin/test/transcript-lit.test.ts@@ -0,0 +1,128 @@+import assert from "node:assert/strict";+import test from "node:test";+import { buildSync } from "esbuild";+import { JSDOM } from "jsdom";+import { prepare } from "../ui/transcript.ts";+const bundle = buildSync({+ entryPoints: [new URL("../ui/transcript.ts", import.meta.url).pathname],+ bundle: true,+ write: false,+ format: "iife",+ globalName: "transcriptUI",+}).outputFiles[0].text;+function setup() {+ const dom = new JSDOM('<div id="header-controls"></div><div id="view-data"></div>', { runScripts: "outside-only" });+ dom.window.requestAnimationFrame = () => 0;+ dom.window.scrollTo = () => {};+ dom.window.eval(+ bundle ++ `;window.ui=transcriptUI;window.data={entries:[]};window.visible={thinking:true,toolResults:true};window.textNode=text=>{const p=document.createElement('pre');p.textContent=text;return p;};window.services={api:async(method,path)=>({ok:true,data:path.includes('/llm?')?{requests:[]}:data}),scope:'org:test',pageSize:60,visibility:visible,current:()=>true,pageShell:()=>{},shortName:x=>x,relTime:x=>x,fmtTime:x=>x,adminErrors:async()=>[],setObserver:()=>{},entryHidden:types=>!visible.thinking&&types.includes('thinking'),payloadText:x=>x,payloadName:()=>'',isXmlishText:()=>false,renderMarkdown:textNode,entryIsNoise:e=>e.type==='thinking',titleCase:x=>x,brandSelfLabel:()=>"QM",stepDurEl:()=>null,copyButton:()=>document.createElement('button'),deliveryFileBadges:()=>null};`,+ );+ return dom;+}+test("transcript grouping pairs tools, folds deliveries and anchors model requests on final assistant", () => {+ const data = {+ entries: [+ { seq: 1, type: "user", createdAt: 1 },+ { seq: 2, type: "tool_call", payload: { callId: "a" }, createdAt: 2 },+ { seq: 3, type: "tool_result", payload: { callId: "a", deliveryId: "d" }, createdAt: 3 },+ { seq: 4, type: "assistant", createdAt: 4 },+ ],+ deliveryEvents: [+ { type: "outbound_delivery", deliveryId: "d", createdAt: 3 },+ { type: "principal_delivery", deliveryId: "d", createdAt: 3 },+ ],+ };+ const result = prepare(data, [+ { turnSeq: 1, step: 2 },+ { turnSeq: 1, step: 1 },+ ]);+ assert.equal(result.units.length, 3);+ assert.equal(result.units[1].paired.seq, 3);+ assert.equal(result.units[1].delivery.deliveryId, "d");+ assert.equal(result.principalIds.has("d"), true);+ assert.deepEqual(+ result.units[2].llmReqs.map((r: any) => r.step),+ [1, 2],+ );+});+test("transcript controls filter state and preserve disclosure state without rebuilding message nodes", async () => {+ const dom = setup();+ try {+ dom.window.eval(+ `data={entries:[{seq:1,type:'user',payload:'hello',createdAt:1},{seq:2,type:'thinking',payload:'private thought',createdAt:2},{seq:3,type:'assistant',payload:'reply',createdAt:3}]}`,+ );+ await dom.window.eval('ui.show("session",60,false,services)');+ const doc = dom.window.document,+ thinking = doc.querySelector(".thinking-entry")!;+ thinking.querySelector<HTMLButtonElement>(".disclosure")!.click();+ assert.equal(thinking.classList.contains("collapsed"), false);+ doc.querySelector<HTMLInputElement>('[aria-label="Show thinking"]')!.click();+ assert.equal(thinking.classList.contains("filtered"), true);+ assert.equal(thinking.classList.contains("collapsed"), false);+ assert.equal(doc.querySelector(".thinking-entry"), thinking);+ } finally {+ dom.window.close();+ }+});+test("header controls appear while transcript requests are pending and stale replies are ignored", async () => {+ const dom = setup();+ try {+ dom.window.eval(+ 'window.resolve=null;services.api=async()=>new Promise(r=>resolve=r);window.pending=ui.show("session",60,false,services)',+ );+ assert.equal(dom.window.document.querySelectorAll(".header-check").length, 2);+ dom.window.eval("ui.cancel();resolve({ok:true,data:{entries:[]}})");+ await dom.window.eval("pending");+ assert.match(dom.window.document.getElementById("view-data")!.textContent!, /Loading/);+ } finally {+ dom.window.close();+ }+});+test("model context selection and disclosure render from state and escape captured content", () => {+ const dom = setup();+ try {+ dom.window.eval(+ `Object.assign(services,{contextSections:()=>[{key:'system',label:'System',text:'<script>bad</script>',tokens:20,note:''},{key:'messages',label:'Messages',text:'hello',tokens:1,note:''}],requestBody:x=>x,fmtContextSize:()=> '21 tokens',sumCacheUsage:()=>null,metaChip:()=>document.createElement('span'),cacheMetaItems:()=>[],rawJsonLink:()=>document.createElement('a'),fmtTokens:x=>String(x)});document.getElementById('view-data').append(ui.requestsPanel([{}],services,{embedded:true,page:true,selectLargest:true}))`,+ );+ const doc = dom.window.document;+ assert.equal(doc.querySelector("pre")!.textContent, "<script>bad</script>");+ assert.equal(doc.querySelectorAll("script").length, 0);+ doc.querySelector<HTMLButtonElement>(".ctx-messages")!.click();+ assert.equal(doc.querySelector("pre")!.textContent, "hello");+ assert.equal(doc.querySelector(".ctx-messages")!.getAttribute("aria-pressed"), "true");+ } finally {+ dom.window.close();+ }+});+test("deep-link back navigation uses the fetched session scope", async () => {+ const dom = setup();+ try {+ dom.window.history.replaceState({ deepLink: true }, "");+ dom.window.eval(+ 'window.shell=null;window.destination=null;services.pageShell=value=>shell=value;services.go=value=>destination=value;data={session:{scopeId:"channel:actual"},entries:[]}',+ );+ await dom.window.eval('ui.show("session",60,false,services)');+ dom.window.eval("shell.back.onClick()");+ assert.equal(dom.window.eval("destination.scope"), "channel:actual");+ assert.equal(dom.window.eval("destination.session"), null);+ } finally {+ dom.window.close();+ }+});+test("standalone delivery retains destination labels and never renders text as HTML", async () => {+ const dom = setup();+ try {+ dom.window.eval(+ 'services.deliveryLabel=()=>"Web delivery";services.deliverySurfaceLabel=()=>"Web";services.wakeOriginLabel=()=>"Manual";services.slackMirrorRef=()=>null;data={entries:[],deliveryEvents:[{type:"outbound_delivery",destination:{type:"web",target:"channel"},text:"<img src=x>",createdAt:1}]}',+ );+ await dom.window.eval('ui.show("session",60,false,services)');+ const doc = dom.window.document;+ assert.equal(doc.querySelector(".entry-label")!.textContent, "Web delivery");+ assert.equal(doc.querySelector(".badge")!.textContent, "Web");+ assert.equal(doc.querySelectorAll("img").length, 0);+ assert.match(doc.querySelector("pre")!.textContent!, /<img src=x>/);+ } finally {+ dom.window.close();+ }+});diff --git a/plugins/admin/test/user-admin-actions.test.ts b/plugins/admin/test/user-admin-actions.test.tsnew file mode 100644index 000000000..b108790a2--- /dev/null+++ b/plugins/admin/test/user-admin-actions.test.ts@@ -0,0 +1,45 @@+import assert from "node:assert/strict";+import test from "node:test";+import { litFixture } from "./lit-fixture.ts";++for (const revoke of [false, true])+ test(`user-row ${revoke ? "revoke" : "promotion"} confirms and sends exact grant target`, async () => {+ const f = litFixture();+ const calls: any[] = [];+ let accepted = false;+ const user = {+ principalId: "[email protected]",+ admin: { isAdmin: revoke, scopeId: "org:test", role: "org_admin" },+ };+ const controller = f.ui.users.users(+ f.root,+ { users: [user], grants: [{ role: "org_admin" }, { role: "org_admin" }] },+ {+ defaultShell() {},+ orgScope: "org:test",+ labelRole: () => "admin",+ confirm: (message: string) => {+ assert.ok(message.includes(user.principalId));+ return accepted;+ },+ clearCache() {},+ api: async (method: string, path: string, body: any) => {+ if (method !== "GET") calls.push([method, path, ...(body ? [body] : [])]);+ return { ok: true, data: path === "/api/users" ? { users: [user], grants: [] } : {} };+ },+ },+ );+ const event = new f.window.Event("click");+ await controller.admin(user, event);+ assert.equal(calls.length, 0);+ accepted = true;+ await controller.admin(user, event);+ assert.deepEqual(+ JSON.parse(JSON.stringify(calls[0])),+ revoke+ ? ["DELETE", "/api/grants/alex%2Badmin%40example.com?scope=org%3Atest&role=org_admin"]+ : ["POST", "/api/grants", { principalId: user.principalId, role: "org_admin", scopeId: "org:test" }],+ );+ assert.equal(controller.pending.size, 0);+ f.dom.window.close();+ });diff --git a/plugins/admin/test/user-detail.test.ts b/plugins/admin/test/user-detail.test.tsnew file mode 100644index 000000000..528ccca07--- /dev/null+++ b/plugins/admin/test/user-detail.test.ts@@ -0,0 +1,46 @@+import assert from "node:assert/strict";+import test from "node:test";+import { litFixture } from "./lit-fixture.ts";++test("user controls render before credentials and artifacts are scoped links", async () => {+ const f = litFixture();+ let finish!: (value: any) => void;+ const keychain = new Promise((resolve) => {+ finish = resolve;+ });+ const pending = f.ui.userDetail.detail(f.root, "[email protected]", {+ pageShell() {},+ current: () => true,+ labelRole: () => "member",+ scopeKind: () => "personal",+ fmtTime: String,+ plural: (n: number, noun: string) => `${n} ${noun}s`,+ stateToUrl: ({ view, scope }: any) => `/admin/${view}?scope=${encodeURIComponent(scope)}`,+ webUiAsButton: () => f.document.createElement("button"),+ api: (_method: string, path: string) =>+ path.startsWith("/api/keychain")+ ? keychain+ : Promise.resolve({+ ok: true,+ data: { principalId: "[email protected]", scopeId: "personal:[email protected]", stats: { sessions: 42 } },+ }),+ });+ await new Promise((resolve) => setImmediate(resolve));+ assert.deepEqual(+ [...f.root.querySelectorAll("h2")].map((e) => e.textContent),+ ["Configuration", "Onboarding"],+ );+ const links = [...f.root.querySelectorAll<HTMLAnchorElement>(".user-resource-links a")];+ assert.deepEqual(+ links.map((e) => e.textContent),+ ["42 conversations →", "Files →", "Apps →", "Crons →", "Skills →", "Memory →"],+ );+ assert.ok(links.every((a) => a.href.endsWith("scope=personal%3Aalex%40example.com")));+ finish({ ok: true, data: { credentials: [], grants: [] } });+ await pending;+ assert.deepEqual(+ [...f.root.querySelectorAll("h2")].map((e) => e.textContent),+ ["Credentials (0)", "Grants (0)", "Configuration", "Onboarding"],+ );+ f.dom.window.close();+});diff --git a/plugins/admin/test/user-invite-placement.test.ts b/plugins/admin/test/user-invite-placement.test.tsindex 48be0ffcb..7e6e8f1ac 100644--- a/plugins/admin/test/user-invite-placement.test.ts+++ b/plugins/admin/test/user-invite-placement.test.ts@@ -1,57 +1,33 @@import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import vm from "node:vm";+import { litFixture } from "./lit-fixture.ts";-const html = readFileSync(new URL("../public/index.html", import.meta.url), "utf8");--class Container {- children: unknown[] = [];- append(...children: unknown[]) {- this.children.push(...children);- }- appendChild(child: unknown) {- this.append(child);- }- prepend(child: unknown) {- this.children.unshift(child);- }-}--test("external invitation controls stay in External users", () => {- const start = html.indexOf("const usersCard = dataCard(");- const end = html.indexOf("\n };\n drawLists();", start);- assert.ok(start >= 0 && end > start);- const cards = new Map<string, { heading: Container; body: Container }>();- const addBtn = {};- const invite = {};- const externalSt = {};- vm.runInNewContext(html.slice(start, end), {- dataCard(title: string, _description: string, content: unknown) {- const heading = new Container();- const body = new Container();- body.append(content);- cards.set(title, { heading, body });- return {- classList: { add() {} },- querySelector: (selector: string) => (selector === ".head h2" || selector === ".head" ? heading : body),- };- },- actionTable: () => ({}),- lists: new Container(),- roster: {},- addBtn,- invite,- externalSt,- filteredExternal: [],- externalUsers: [],+test("external invitation form stays in External users and preserves draft through async counts", async () => {+ const f = litFixture();+ let resolve!: (v: any) => void;+ const pending = new Promise((r) => {+ resolve = r;});- const users = cards.get("Users")!;- const external = cards.get("External users")!;- assert.ok(external.heading.children.includes(addBtn), "invite control is on External users");- assert.ok(external.body.children.includes(invite), "form is on External users");- assert.ok(external.body.children.includes(externalSt), "feedback is on External users");- assert.ok(!users.heading.children.includes(addBtn));- assert.ok(!users.body.children.includes(invite));- assert.ok(!users.body.children.includes(externalSt));+ const controller = f.ui.users.users(+ f.root,+ { users: [], grants: [], externalUsers: [] },+ { defaultShell() {}, api: () => pending },+ );+ assert.deepEqual(+ [...f.root.querySelectorAll("h2")].map((e) => e.textContent),+ ["External users", "Users"],+ );+ const invite = f.root.querySelector<HTMLButtonElement>('[aria-label="Invite external user"]')!;+ invite.click();+ const input = f.root.querySelector<HTMLInputElement>("#users-email")!;+ input.value = "[email protected]";+ input.dispatchEvent(new f.window.Event("input", { bubbles: true }));+ resolve({ ok: true, data: { people: [] } });+ await pending;+ await Promise.resolve();+ assert.equal(controller.email, "[email protected]");+ assert.equal(input, f.root.querySelector("#users-email"));+ assert.equal(input.value, "[email protected]");+ assert.equal(input.closest("section")!.querySelector("h2")!.textContent, "External users");+ f.dom.window.close();});diff --git a/plugins/admin/test/users-state.test.ts b/plugins/admin/test/users-state.test.tsnew file mode 100644index 000000000..7b7c01349--- /dev/null+++ b/plugins/admin/test/users-state.test.ts@@ -0,0 +1,98 @@+import assert from "node:assert/strict";+import test from "node:test";+import { litFixture } from "./lit-fixture.ts";+import { UsersView } from "../ui/users.ts";+function model() {+ const view = Object.create(UsersView.prototype) as UsersView;+ Object.assign(view, {+ pending: new Set(),+ refreshRequest: 0,+ root: { isConnected: true },+ draw: () => {},+ renderShell: () => {},+ data: {},+ email: "[email protected]",+ role: "member",+ expires: "2026-12-01",+ inviteOpen: true,+ });+ return view;+}+test("user invitation keeps newer edited fields open when the submitted invitation succeeds", async () => {+ const view = model();+ let resolve!: (value: any) => void;+ view.services = {+ api: async (method: string) => (method === "POST" ? new Promise((r) => (resolve = r)) : { ok: true, data: {} }),+ clearCache: () => {},+ fmtTime: () => "",+ labelRole: () => "",+ };+ const pending = view.invite();+ view.email = "[email protected]";+ resolve({ ok: true, data: { member: { email: "[email protected]" }, emailSent: true } });+ await pending;+ assert.equal(view.inviteOpen, true);+ assert.equal(view.email, "[email protected]");+});+test("overlapping roster refreshes cannot restore an older snapshot", async () => {+ const view = model();+ const pending: Array<(value: any) => void> = [];+ view.services = { api: () => new Promise((r) => pending.push(r)), clearCache: () => {} };+ const first = view.refresh(),+ second = view.refresh();+ pending[1]({ ok: true, data: { value: "latest" } });+ await second;+ pending[0]({ ok: true, data: { value: "older" } });+ await first;+ assert.equal(view.data.value, "latest");+});++test("roster refresh updates shell counts while retaining search focus and invitation drafts", async () => {+ const f = litFixture();+ const bar = f.document.createElement("div");+ bar.id = "shellbar";+ f.document.body.prepend(bar);+ const shells: any[] = [];+ let data = { users: [], grants: [], externalUsers: [] } as any;+ const view = f.ui.users.users(f.root, data, {+ defaultShell(shell: any) {+ shells.push(shell);+ bar.replaceChildren();+ const search = f.document.createElement("div");+ search.className = "shell-search";+ const input = f.document.createElement("input");+ input.value = shell.search.value;+ input.oninput = () => shell.search.onInput(input.value);+ search.append(input);+ bar.append(search);+ },+ api: async (_method: string, path: string) => ({ ok: true, data: path === "/api/users" ? data : { people: [] } }),+ clearCache() {},+ labelRole: String,+ });+ f.root.querySelector<HTMLButtonElement>('[aria-label="Invite external user"]')!.click();+ const email = f.root.querySelector<HTMLInputElement>("#users-email")!;+ email.value = "[email protected]";+ email.dispatchEvent(new f.window.Event("input"));+ const search = bar.querySelector("input")!;+ search.value = "admin";+ search.dispatchEvent(new f.window.Event("input"));+ search.focus();+ search.setSelectionRange(2, 4);+ data = { users: [], grants: [{ role: "org_admin" }], externalUsers: [] };+ await view.refresh();+ view.draw();+ assert.equal(shells.at(-1).stats[1][0], 1);+ assert.equal(bar.querySelector("input"), search);+ assert.equal(f.document.activeElement, search);+ assert.equal(search.value, "admin");+ assert.equal(search.selectionStart, 2);+ assert.equal(search.selectionEnd, 4);+ assert.equal(f.root.querySelector("#users-email"), email);+ assert.equal(email.value, "[email protected]");+ assert.equal(view.inviteOpen, true);+ bar.replaceChildren(f.document.createTextNode("Another view"));+ await view.refresh();+ assert.equal(bar.textContent, "Another view");+ f.dom.window.close();+});diff --git a/plugins/admin/tsconfig.json b/plugins/admin/tsconfig.jsonindex ff71a63ef..37bf9d2c5 100644--- a/plugins/admin/tsconfig.json+++ b/plugins/admin/tsconfig.json@@ -3,7 +3,7 @@"target": "esnext","module": "nodenext","moduleResolution": "nodenext",- "lib": ["esnext"],+ "lib": ["esnext", "dom", "dom.iterable"],"types": ["node"],"strict": true,"verbatimModuleSyntax": true,@@ -16,5 +16,5 @@"@sentry/node": ["./node_modules/@sentry/node/build/types/index.d.ts"]}},- "include": ["src/**/*.ts", "test/**/*.ts"]+ "include": ["src/**/*.ts", "test/**/*.ts", "ui/**/*.ts"]}diff --git a/plugins/admin/ui/activity.ts b/plugins/admin/ui/activity.tsnew file mode 100644index 000000000..5052291bc--- /dev/null+++ b/plugins/admin/ui/activity.ts@@ -0,0 +1,113 @@+import { html } from "lit";+import { bareCard, table, pager, mount } from "./shared.ts";++export function errors(root: HTMLElement, data: any, s: Record<string, any>) {+ const rows = data.errors || [];+ const total = data.total ?? rows.length;+ const limit = data.limit || s.errorsPageSize;+ const offset = data.offset || 0;+ s.defaultShell({ count: s.plural(total, "error") });+ const content = table(+ ["Category", "Code", "Message", ...(s.all ? ["Scope"] : []), "Session", "Time"],+ rows.map((e: any) => {+ const scope = /^(personal|channel|team|org|group):.+/.test(e.scopeLabel || "") ? e.scopeLabel : null;+ const text = e.message || "(no message)";+ return [+ e.category || "uncategorized",+ { text: e.code || "—", cls: "mono" },+ {+ node: html`<details class="error-message">+ <summary>+ <span class="error-preview">${s.firstLine(text, 160)}</span><span class="error-full">${text}</span>+ </summary>+ </details>`,+ },+ ...(s.all+ ? [scope ? { node: s.navLink(s.shortName(scope), { view: "errors", scope }) } : e.scopeLabel || "System"]+ : []),+ e.sessionId+ ? { node: s.navLink("View session", { view: "history", scope: scope || s.scope, session: e.sessionId }) }+ : "—",+ time(e.ts, s),+ ];+ }),+ s.all ? "No errors recorded." : "No errors recorded for this scope.",+ undefined,+ { wrapClass: "errors-table " + (s.all ? "errors-all" : "errors-scoped") },+ );+ const pages = () => pager(total, limit, offset, (page) => s.go({ view: "errors", scope: s.scope, page }));+ mount(root, html`${pages()}${bareCard(content)}${pages()}`);+}++export function audit(root: HTMLElement, data: any, s: Record<string, any>) {+ const events = data.events || [];+ s.defaultShell({ count: s.plural(events.length, "event") });+ mount(+ root,+ bareCard(+ table(+ ["Admin", "Action", "Resource", ...(s.all ? ["Scope"] : []), "Time"],+ events.map((e: any) => [+ { text: e.principalId, cls: "mono" },+ {+ node: html`<span class=${/revoke|delete|deny|fail/.test(String(e.action || "")) ? "flag-err" : "subline"}+ >${e.action || "event"}</span+ >`,+ },+ { text: e.status ? e.resource + " (" + e.status + ")" : e.resource || "", cls: "mono" },+ ...(s.all ? [s.shortName(e.scopeLabel)] : []),+ time(e.ts, s),+ ]),+ s.all ? "No admin activity yet." : "No admin activity for this scope.",+ ),+ ),+ );+}++export function egress(root: HTMLElement, data: any, s: Record<string, any>) {+ const rows = data.records || [];+ const sources = data.bySource || {};+ s.defaultShell({+ stats: [+ [String(data.total ?? rows.length), "Calls"],+ [String(data.denied ?? 0), "denied requests"],+ [String(data.hosts ?? 0), "Hosts"],+ [String(sources.broker ?? 0), "broker requests"],+ [String(sources.firewall ?? 0), "firewall requests"],+ ],+ });+ mount(+ root,+ bareCard(+ table(+ ["Host", "Status", "Source", ...(s.all ? ["Scope"] : []), "Principal", "Detail", "Time"],+ rows.map((r: any) => [+ { text: r.host, cls: "mono" },+ {+ node: egressStatus(r),+ },+ { node: html`<span class="subline">${r.source || "firewall"}</span>` },+ ...(s.all ? [s.shortName(r.scopeLabel)] : []),+ { text: r.principalId || "None", cls: "mono" },+ { text: s.egressDetail(r), cls: "mono" },+ time(r.ts, s),+ ]),+ "No egress in this scope yet.",+ ),+ ),+ );+}++function egressStatus(row: any) {+ let tone = row.status === "error" ? "flag-err" : "subline";+ let label = row.status && row.status !== "ok" ? row.status : "allowed";+ if (row.allowed === false) {+ tone = "flag-warn";+ label = row.status || "denied";+ }+ return html`<span class=${tone}>${label}</span>`;+}++function time(ts: number, s: Record<string, any>) {+ return { node: html`<span title=${s.fmtTime(ts)}>${s.relTime(ts)}</span>`, cls: "num" };+}diff --git a/plugins/admin/ui/admin.ts b/plugins/admin/ui/admin.tsnew file mode 100644index 000000000..5f6fe925e--- /dev/null+++ b/plugins/admin/ui/admin.ts@@ -0,0 +1,36 @@+import * as governance from "./governance.ts";+import * as settings from "./settings.ts";+import * as integrations from "./integrations.ts";+import * as onboarding from "./onboarding.ts";+import type { GovernanceState } from "./governance-state.ts";+import type { SlackSetting } from "./integrations-state.ts";+export * from "./governance.ts";+export { settings, integrations };+export { onboarding };+export * as users from "./users.ts";+export * as userDetail from "./user-detail.ts";+export * as keychain from "./keychain.ts";+export * as metrics from "./metrics.ts";+export * as transcript from "./transcript.ts";+export * as design from "./design.ts";+export * as activity from "./activity.ts";+export * as history from "./history.ts";+export * as artifacts from "./artifacts.ts";+export * as slackActivity from "./slack-activity.ts";+export * as shared from "./shared.ts";++const modules = [governance, settings, integrations];+export const states = new Map<string, GovernanceState | settings.SettingsState | SlackSetting>(+ modules.flatMap((module) => [...module.states]),+);+const owner = (key: string) => modules.find((module) => module.owns(key));+export const owns = (key: string) => !!owner(key);+export const collect = (key: string) => owner(key)!.collect(key);+export const capture = (key: string) => owner(key)!.capture(key);+export const commit = (key: string, body: any) => owner(key)!.commit(key, body);+export const status = (key: string, message: string, tone: string) => owner(key)!.status(key, message, tone);+export const statusKey = (id: string) => modules.map((module) => module.statusKey(id)).find(Boolean);+export function mountCards() {+ modules.forEach((module) => module.mountCards());+ onboarding.mount();+}diff --git a/plugins/admin/ui/artifacts-skills.ts b/plugins/admin/ui/artifacts-skills.tsnew file mode 100644index 000000000..1a49349fd--- /dev/null+++ b/plugins/admin/ui/artifacts-skills.ts@@ -0,0 +1,709 @@+import { html, nothing } from "lit";+import { ifDefined } from "lit/directives/if-defined.js";+import { card, table, renderer } from "./shared.ts";+import type { Context, Data } from "./artifacts.ts";+const badge = (text: unknown, tone = "muted", title = "") =>+ html`<span class=${"badge " + tone} title=${ifDefined(title || undefined)}>${text}</span>`;+const stacked = (name: unknown, desc: unknown) =>+ html`<div>+ <div class="primaryline">${name}</div>+ ${desc ? html`<div class="subline">${desc}</div>` : nothing}+ </div>`;+export async function removeSkill(s: Data, c: Context) {+ if (+ !confirm(+ "Remove '" ++ (s.name || s.id) ++ "' from " ++ (c.dirLabel(s.ownerScopeId) || s.ownerScopeId) ++ "? It stops being available to agents (kept for audit).",+ )+ )+ return;+ try {+ const response = await c.api(+ "DELETE",+ "/api/skills/" + encodeURIComponent(s.id) + "?scope=" + encodeURIComponent(s.ownerScopeId || c.scope),+ );+ if (!response.ok) {+ alert(response.data?.message || "1 scope(s) could not be removed.");+ return;+ }+ c.invalidate();+ await c.reload();+ } catch {+ alert("Could not remove skill.");+ }+}+export async function skillDetail(root: HTMLElement, rep: Data, group: Data[], c: Context) {+ root.replaceChildren();+ const paint = renderer(root);+ paint(html`<div class="loadingline">${"Loading " + (rep.name || rep.id) + "…"}</div>`);+ const response = await c.api(+ "GET",+ "/api/skills/" + encodeURIComponent(rep.id) + "?scope=" + encodeURIComponent(rep.ownerScopeId || c.scope),+ );+ if (!response.ok || !response.data) {+ paint(+ html`<p class="empty">+ ${response.status === 403 ? "You don't administer this skill's scope." : "Couldn't load this skill."}+ </p>`,+ );+ return;+ }+ const k = response.data;+ const by = (() => {+ if (k.pack) return "from " + (c.packRepoLabel(k.pack.url) || "pack " + c.shortId(k.pack.id, 8));+ return k.createdBy?.startsWith("system:") ? "built-in" : "by " + (k.createdBy || "None");+ })();+ paint(+ card(+ k.name || k.id,+ "",+ html`<div>+ <div class="badges">+ ${c.statusBadge(k.status)}${badge("v" + k.version)}${badge(by)}${badge("skill " + c.shortId(k.id, 16))}+ </div>+ ${k.description ? html`<p class="metric-note">${k.description}</p>` : nothing}${card(+ "Scopes (" + group.length + ")",+ "Every scope this skill is installed in. Remove takes it out of that scope only.",+ table(+ ["Scope", "Status", "Version", ""],+ [...group]+ .sort((a, b) =>+ (() => {+ if (c.scopeKind(a.ownerScopeId) === "org") return -1;+ return c.scopeKind(b.ownerScopeId) === "org"+ ? 1+ : (a.ownerScopeId || "").localeCompare(b.ownerScopeId || "");+ })(),+ )+ .map((g) => [+ c.scopeCell(g.ownerScopeId),+ { node: c.statusBadge(g.status) },+ { text: g.version != null ? "v" + g.version : "None", cls: "num" },+ {+ node:+ g.status === "archived"+ ? badge("archived")+ : html`<button type="button" class="rowbtn danger" @click=${() => removeSkill(g, c)}>+ Remove+ </button>`,+ },+ ]),+ "None",+ ),+ )}${card(+ "Capabilities",+ "What the skill is allowed to reach. Granted at review time.",+ table(+ ["Capability", "Status"],+ (k.requiredCapabilities || []).map((cap: string) => [+ { text: cap, cls: "mono" },+ {+ node: (k.grantedCapabilities || []).includes(cap)+ ? badge("granted", "ok")+ : badge("not granted", "warn"),+ },+ ]),+ "Requires no capabilities.",+ ),+ )}${+ k.approvals?.length+ ? card(+ "Approvals",+ "Reviewers who signed off on this skill.",+ table(+ ["Reviewer"],+ k.approvals.map((a: string) => [{ text: a, cls: "mono" }]),+ "",+ ),+ )+ : nothing+ }${card("Instructions", "The SKILL.md the agent reads when this skill is in play.", html`<pre class="skillbody" style="white-space:pre-wrap;font-family:ui-monospace, SFMono-Regular, Menlo, monospace;font-size:12px;margin:0">${k.body || "(empty)"}</pre>`)}+ </div>`,+ ),+ );+ root.scrollIntoView({ behavior: "smooth", block: "nearest" });+}+export async function mountPacks(root: HTMLElement, c: Context) {+ const response = await c.api("GET", "/api/skill-packs");+ if (!root.isConnected) return;+ packs(root, (response.ok && response.data?.packs) || [], c);+}+export function packs(root: HTMLElement, rows: Data[], c: Context) {+ const paint = renderer(root);+ const detail = document.createElement("div");+ const draft = { url: "", ref: "", exclude: "", slug: "", tier: "third-party" };+ let advanced = false,+ registering = false,+ message = "",+ tone = "",+ menu: string | null = null,+ menuTop = 0,+ menuLeft = 0;+ const statuses = new Map<string, Data>();+ const pending = new Set<string>();+ const closeMenu = () => {+ if (menu) {+ menu = null;+ draw();+ }+ };+ const abort = new AbortController();+ document.addEventListener("click", closeMenu, { signal: abort.signal });+ document.addEventListener("scroll", closeMenu, { signal: abort.signal, capture: true });+ window.addEventListener("resize", closeMenu, { signal: abort.signal });+ const observer = new MutationObserver(() => {+ if (!root.isConnected) {+ abort.abort();+ observer.disconnect();+ }+ });+ observer.observe(document.body, { childList: true, subtree: true });+ const change = (key: keyof typeof draft) => (e: Event) => {+ draft[key] = (e.target as HTMLInputElement).value;+ draw();+ };+ const register = async () => {+ if (registering) return;+ if (!draft.url.trim()) {+ message = "A repo URL is required.";+ tone = "err";+ draw();+ return;+ }+ const submitted = JSON.stringify(draft);+ registering = true;+ message = "Registering…";+ tone = "";+ draw();+ const excluded = draft.exclude+ .split(",")+ .map((x) => x.trim())+ .filter(Boolean);+ try {+ const response = await c.api("POST", "/api/skill-packs", {+ url: draft.url.trim(),+ ...(draft.ref.trim() ? { ref: draft.ref.trim() } : {}),+ ...(excluded.length ? { config: { exclude: excluded } } : {}),+ ...(draft.slug.trim() ? { authCredentialSlug: draft.slug.trim() } : {}),+ ...(draft.tier !== "third-party" ? { trustTier: draft.tier } : {}),+ });+ if (!response.ok) {+ message = response.data?.message || "Failed (" + response.status + ").";+ tone = "err";+ } else {+ c.invalidate();+ if (JSON.stringify(draft) === submitted) await c.reload();+ else {+ message = "Pack registered. Your newer changes have not been registered.";+ tone = "ok";+ }+ }+ } catch {+ message = "Registration failed.";+ tone = "err";+ } finally {+ registering = false;+ draw();+ }+ };+ const act = async (s: Data, action: string) => {+ menu = null;+ if (action === "browse") {+ draw();+ void browsePack(s, detail, c);+ return;+ }+ if (pending.has(s.id)) return;+ if (action === "remove" && !confirm("Remove this pack and archive its imported skills?")) {+ draw();+ return;+ }+ pending.add(s.id);+ if (action === "sync") statuses.set(s.id, { text: "syncing…", tone: "saving" });+ draw();+ try {+ const path = "/api/skill-packs/" + encodeURIComponent(s.id);+ const response = await c.api(+ (() => {+ if (action === "remove") return "DELETE";+ return action === "sync" ? "POST" : "PATCH";+ })(),+ path + (action === "sync" ? "/sync" : ""),+ (() => {+ if (action === "sync") return {};+ return action === "track" ? { syncMode: s.syncMode === "tracked" ? "pinned" : "tracked" } : undefined;+ })(),+ );+ if (!response.ok) {+ statuses.set(s.id, {+ text: (action === "sync" ? "sync failed: " : "Failed: ") + (response.data?.message || response.status),+ tone: "err",+ });+ return;+ }+ if (action === "sync") {+ const data = response.data || {},+ n = (data.imported || []).length,+ u = (data.updated || []).length,+ a = (data.archived || []).length;+ statuses.set(s.id, {+ text:+ n || u || a+ ? "✓ " + n + " new" + (u ? " · " + u + " updated" : "") + (a ? " · " + a + " removed" : "")+ : "✓ up to date",+ tone: "ok",+ });+ setTimeout(() => {+ c.invalidate();+ if (root.isConnected) c.reload();+ }, 1200);+ } else {+ c.invalidate();+ await c.reload();+ }+ } catch {+ statuses.set(s.id, { text: "Request failed.", tone: "err" });+ } finally {+ pending.delete(s.id);+ draw();+ }+ };+ const input = (key: keyof typeof draft, placeholder: string, title?: string) =>+ html`<input+ type="text"+ placeholder=${placeholder}+ title=${ifDefined(title)}+ aria-label=${placeholder}+ spellcheck="false"+ .value=${draft[key]}+ @input=${change(key)}+ />`;+ const draw = () =>+ paint(+ html`${card(+ "Skill packs",+ "Register a repository, then choose which skills to import into each scope.",+ html`<div>+ <div class="pack-register">+ ${input("url", "Register a pack: paste a git repo URL of SKILL.md files, then Browse it into scopes")}<button+ type="button"+ class=${"linkish" + (advanced ? " open" : "")}+ aria-expanded=${String(advanced)}+ @click=${() => {+ advanced = !advanced;+ draw();+ }}+ >+ ${"Advanced" + (!advanced && (draft.ref.trim() || draft.exclude.trim() || draft.slug.trim() || draft.tier !== "third-party") ? " •" : "")}</button+ ><button type="button" class="primary" ?disabled=${registering} @click=${register}>Register</button+ ><span class=${"status" + (tone ? " " + tone : "")}>${message}</span>+ </div>+ <div class=${"pack-adv" + (advanced ? "" : " hidden")}>+ ${input("ref", "ref (branch or SHA)", "Pin to a branch or full 40-hex commit SHA. Blank = the repo's default branch.")}${input("exclude", "exclude globs, comma-separated", "e.g. trusted/*")}${input("slug", "deploy-token slug", "Private-repo deploy-token credential slug. Blank = your connected GitHub account.")}<select+ title="Trust tier"+ .value=${draft.tier}+ @change=${change("tier")}+ >+ <option value="third-party">trust: third-party</option>+ <option value="internal">trust: internal</option>+ </select>+ </div>+ ${table(+ ["Pack", "Skills", "Trust", "Status", ""],+ rows.map((s) => {+ const li = s.lastImport,+ counts = li?.counts || {},+ tracked = s.syncMode === "tracked";+ const delta = li+ ? "last sync: " ++ (counts.imported || 0) ++ " new · " ++ (counts.updated || 0) ++ " updated · " ++ (counts.skipped || 0) ++ " skipped" ++ (counts.archived ? " · " + counts.archived + " removed" : "")+ : "";+ const status =+ statuses.get(s.id) ||+ (() => {+ if (li?.status === "error")+ return { text: "error: " + (li.error || "sync failed"), tone: "err", title: li.error || "" };+ return s.updateAvailable+ ? {+ text: "update available",+ tone: "dirty",+ title: "Upstream advanced past the imported commit. Sync now (or turn on Auto-sync) to apply.",+ }+ : { text: li ? "up to date" : "not imported", tone: "muted", title: delta };+ })();+ return [+ {+ node: html`<span class="pack-name" title=${s.url + (delta ? "\n" + delta : "")}+ ><strong>${c.packRepoLabel(s.url) || s.url}</strong+ >${s.ref ? html`<span class="subline">${" @ " + c.shortId(s.ref, 10)}</span>` : nothing}</span+ >`,+ },+ {+ node: html`<span+ title=${ifDefined(s.available != null ? (s.importedCount || 0) + " imported · " + s.available + " available (eligible) in this pack" : undefined)}+ >${s.available != null ? (s.importedCount || 0) + " of " + s.available : "n/a"}</span+ >`,+ cls: "num",+ },+ { text: s.trustTier + (tracked ? " · auto-sync" : ""), cls: "subline" },+ {+ node: html`<span class=${"status " + status.tone} title=${ifDefined(status.title || undefined)}+ >${status.text}</span+ >`,+ },+ {+ node: html`<div class="ovwrap">+ <button+ type="button"+ class="rowbtn"+ aria-label="Actions"+ aria-haspopup="menu"+ aria-expanded=${String(menu === s.id)}+ @click=${(e: MouseEvent) => {+ e.stopPropagation();+ const r = (e.currentTarget as HTMLElement).getBoundingClientRect();+ menu = menu === s.id ? null : s.id;+ menuTop = r.bottom + 4;+ menuLeft = r.right;+ draw();+ const el = root.querySelector<HTMLElement>(".ovmenu:not(.hidden)");+ if (el) {+ menuLeft = Math.max(8, r.right - el.offsetWidth);+ draw();+ }+ }}+ >+ ⋯+ </button>+ <div+ class=${"ovmenu" + (menu === s.id ? "" : " hidden")}+ role="menu"+ style=${`top:${menuTop}px;left:${menuLeft}px`}+ >+ ${[+ ["browse", "Browse skills…"],+ ["sync", "Sync now"],+ ["track", tracked ? "Turn off auto-sync" : "Turn on auto-sync"],+ ["remove", "Remove pack"],+ ].map(+ ([action, label]) =>+ html`<button+ type="button"+ class=${ifDefined(action === "remove" ? "danger" : undefined)}+ ?disabled=${pending.has(s.id)}+ @click=${(e: MouseEvent) => {+ e.stopPropagation();+ void act(s, action);+ }}+ >+ ${label}+ </button>`,+ )}+ </div>+ </div>`,+ cls: "num",+ },+ ];+ }),+ "No packs yet. Register one above.",+ )}+ </div>`,+ )}${detail}`,+ );+ draw();+}+export async function browsePack(pack: Data, root: HTMLElement, c: Context) {+ root.replaceChildren();+ const paint = renderer(root);+ paint(html`<div class="loadingline">${"Fetching " + pack.url + "…"}</div>`);+ const response = await c.api("GET", "/api/skill-packs/" + encodeURIComponent(pack.id) + "/catalog");+ if (!response.ok || !response.data) {+ paint(html`<p class="empty">${response.data?.message || "Couldn't browse (" + response.status + ")."}</p>`);+ return;+ }+ const plan = response.data,+ candidates: Data[] = plan.candidates || [],+ counts = plan.counts || {};+ const selectedScopes = new Set<string>(["org:" + c.orgId]);+ const selected = new Set<string>();+ let filter = "all",+ busy = false,+ message = "",+ tone = "",+ closed = false;+ const all = (row: Data) =>+ selectedScopes.size > 0 && [...selectedScopes].every((scope) => (row.importedScopes || []).includes(scope));+ const eligible = (row: Data) => row.eligible && !all(row);+ let previousEligible = new Set<string>();+ const recompute = () => {+ const next = new Set(candidates.filter(eligible).map((r) => r.upstreamName));+ for (const r of candidates) {+ if (!next.has(r.upstreamName)) selected.delete(r.upstreamName);+ else if (!previousEligible.has(r.upstreamName)) selected.add(r.upstreamName);+ }+ previousEligible = next;+ draw();+ };+ const reasons: Record<string, Data> = {+ all: { label: "all", tone: "muted", help: "Show every skill." },+ eligible: {+ label: "eligible",+ tone: "ok",+ help: "Eligible and not yet in the selected scope(s). Importing adds it there.",+ },+ imported: {+ label: "imported",+ tone: "info",+ help: "Already imported into the selected scope(s). Sync refreshes them; un-index to remove.",+ },+ scope: {+ label: "personal-scoped",+ tone: "muted",+ help: "Held back: declares a personal/owner scope, so it isn't imported as a shared pack skill.",+ },+ private: { label: "private", tone: "muted", help: "Held back: marked owner-only / agent-only." },+ collision: {+ label: "collision",+ tone: "muted",+ help: "Held back: the name matches an existing platform or seed skill.",+ },+ "binary-asset": {+ label: "binary files",+ tone: "muted",+ help: "Held back: contains binary files (import is text-only).",+ },+ malformed: { label: "malformed", tone: "muted", help: "Held back: missing or unreadable SKILL.md frontmatter." },+ };+ const choices = [+ { scopeId: "org:" + c.orgId, label: "org-wide" },+ ...c.scopeRows().map((r: Data) => ({ scopeId: r.scopeId, label: r.label || c.dirLabel(r.scopeId) || r.scopeId })),+ ];+ const picker = c.buildScopeMultiSelect(choices, selectedScopes, recompute);+ const importSelected = async () => {+ if (busy) return;+ if (!selectedScopes.size || !selected.size) {+ message = !selectedScopes.size ? "Pick at least one scope to add skills to." : "Select at least one skill.";+ tone = "err";+ draw();+ return;+ }+ busy = true;+ message = "Importing…";+ tone = "";+ draw();+ const scopes = [...selectedScopes],+ names = [...selected];+ try {+ const result = await c.api("POST", "/api/skill-packs/" + encodeURIComponent(pack.id) + "/import", {+ selected: names.length === candidates.filter(eligible).length ? "all" : names,+ scopeIds: scopes,+ });+ if (!result.ok) {+ message = result.data?.message || "Import failed (" + result.status + ").";+ tone = "err";+ } else {+ const added = result.data.imported?.length ?? 0;+ message =+ "✓ " ++ added ++ " skill" ++ (added === 1 ? "" : "s") ++ " added" ++ (scopes.length > 1 ? " across " + scopes.length + " scopes" : "");+ tone = "ok";+ c.invalidate();+ setTimeout(() => {+ if (root.isConnected && !closed) c.reload();+ }, 1500);+ }+ } catch {+ message = "Import failed.";+ tone = "err";+ } finally {+ busy = false;+ draw();+ }+ };+ const action = (bottom = false) =>+ html`<div+ style=${"display:flex;flex-direction:column;align-items:flex-start;gap:6px;" + (bottom ? "margin-top:10px" : "")}+ >+ <button type="button" class="primary" ?disabled=${busy} @click=${importSelected}>Import selected</button+ ><span class=${"status" + (tone ? " " + tone : "")}>${message}</span>+ </div>`;+ const draw = () => {+ if (closed) return;+ const importable = candidates.filter(eligible),+ selectedCount = importable.filter((r) => selected.has(r.upstreamName)).length;+ const shown = candidates.filter(+ (r) =>+ filter === "all" ||+ (() => {+ if (all(r)) return "imported";+ return r.eligible ? "eligible" : r.excludeReason || "excluded";+ })() === filter,+ );+ paint(+ html`<section class="card" style="position:relative">+ <div class="head">+ <h2>${"Browse: " + pack.url}</h2>+ <p>+ Choose target scopes, then import. Eligible skills are added to every selected scope; excluded skills show+ why. They appear on the Skills page once imported.+ </p>+ </div>+ <div class="body">+ <div>+ <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin:2px 0 4px">+ <span style="font-size:12px;opacity:0.7">Add to scopes:</span>${picker}+ </div>+ ${+ plan.bundlePaths?.length+ ? html`<details style="margin:8px 0">+ <summary>+ ${plan.bundlePaths.length + " shared pack file" + (plan.bundlePaths.length === 1 ? "" : "s") + " (contained under a pack-owned directory)"}+ </summary>+ <pre+ style="max-height:180px;overflow:auto;font-size:11px;padding:10px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius)"+ >+${plan.bundlePaths.join("\n")}</pre>+ </details>`+ : nothing+ }+ <div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin:10px 0 16px">+ <div class="badges" style="flex:1">+ ${Object.entries(reasons)+ .filter(+ ([key]) =>+ key === "all" ||+ key === "eligible" ||+ (key === "imported" ? candidates.some((r) => r.importedScopes?.length) : counts[key]),+ )+ .map(+ ([key, reason]) =>+ html`<span+ class=${"badge " + reason.tone}+ style=${"cursor:pointer;" + (filter === key ? "background:var(--text);color:#fff;border-color:var(--text)" : "")}+ title=${reason.help + " " + (key === "all" ? "" : "Click to show only these.")}+ @click=${() => {+ filter = key;+ draw();+ }}+ >${+ (() => {+ if (key === "all") return candidates.length;+ return (() => {+ if (key === "eligible") return importable.length;+ return key === "imported" ? candidates.filter(all).length : counts[key] || 0;+ })();+ })() ++ " " ++ reason.label+ }</span+ >`,+ )}+ </div>+ ${action()}+ </div>+ <div>+ ${table(+ [+ html`<input+ type="checkbox"+ title="Select / deselect all importable skills"+ .checked=${importable.length > 0 && selectedCount === importable.length}+ .indeterminate=${selectedCount > 0 && selectedCount < importable.length}+ @change=${(e: Event) => {+ const on = (e.target as HTMLInputElement).checked;+ for (const row of importable) {+ if (on) selected.add(row.upstreamName);+ else selected.delete(row.upstreamName);+ }+ draw();+ }}+ />`,+ "Skill",+ "",+ ],+ shown.map((row) => [+ {+ node: html`<input+ type="checkbox"+ data-name=${row.upstreamName}+ .checked=${selected.has(row.upstreamName)}+ ?disabled=${!eligible(row)}+ @change=${(e: Event) => {+ if ((e.target as HTMLInputElement).checked) selected.add(row.upstreamName);+ else selected.delete(row.upstreamName);+ draw();+ }}+ />`,+ },+ { node: stacked(row.upstreamName, row.normalized?.manifest?.description || "") },+ {+ node: (() => {+ if (all(row))+ return badge(+ "imported",+ "info",+ "Already imported into the selected scope(s): " + (row.importedScopes || []).join(", "),+ );+ return row.eligible+ ? badge(+ "eligible",+ "ok",+ [...selectedScopes].some((s) => (row.importedScopes || []).includes(s))+ ? "Imported into " ++ (row.importedScopes || []).join(", ") ++ ". Importing adds it to the other selected scope(s)."+ : "",+ )+ : badge(+ reasons[row.excludeReason]?.label || row.excludeReason || "excluded",+ "warn",+ reasons[row.excludeReason]?.help || "",+ );+ })(),+ },+ ]),+ filter === "all"+ ? "No skills found in this pack."+ : "No " + (reasons[filter]?.label || filter) + " skills.",+ )}+ </div>+ ${action(true)}+ </div>+ </div>+ <button+ type="button"+ title="Close"+ aria-label="Close browse"+ style="position:absolute;top:10px;right:12px;border:none;background:transparent;cursor:pointer;font-size:18px;line-height:1;color:var(--text);opacity:0.55;padding:4px"+ @mouseenter=${(e: Event) => {+ (e.target as HTMLElement).style.opacity = "1";+ }}+ @mouseleave=${(e: Event) => {+ (e.target as HTMLElement).style.opacity = "0.55";+ }}+ @click=${() => {+ closed = true;+ paint(nothing);+ }}+ >+ ✕+ </button>+ </section>`,+ );+ };+ recompute();+ root.scrollIntoView({ behavior: "smooth", block: "nearest" });+}diff --git a/plugins/admin/ui/artifacts.ts b/plugins/admin/ui/artifacts.tsnew file mode 100644index 000000000..8f6ec25e8--- /dev/null+++ b/plugins/admin/ui/artifacts.ts@@ -0,0 +1,1033 @@+import { html, nothing, render } from "lit";+import { repeat } from "lit/directives/repeat.js";+import { ifDefined } from "lit/directives/if-defined.js";+import { card, bareCard, table, renderer } from "./shared.ts";+import { mountPacks, skillDetail, removeSkill } from "./artifacts-skills.ts";+export type Data = Record<string, any>;+export type Context = Record<string, any>;+type Row = {+ name: unknown;+ preview?: unknown;+ time?: unknown;+ href?: string;+ target?: string;+ cls?: string;+ icon?: unknown;+};+const empty = (text: string) => html`<p class="empty">${text}</p>`;+export const badge = (text: unknown, tone = "muted") => html`<span class=${"badge " + tone}>${text}</span>`;+const queries = new Map<string, string>();+export function dense(items: Data[], rowOf: (item: Data) => Row, open: (item: Data) => void, message: string) {+ if (!items.length) return empty(message);+ return html`<div class="dense-list">+ ${repeat(+ items,+ (item) => item.id || item.scopeId || item,+ (item) => {+ const r = rowOf(item);+ const content = html`${r.icon ? html`<span class="dense-icon">${r.icon}</span>` : nothing}<span+ class="dense-name"+ >${r.name}</span+ ><span class="dense-preview">${r.preview ?? ""}</span+ >${r.time != null ? html`<span class="dense-time">${r.time}</span>` : nothing}`;+ const click = (e: MouseEvent) => {+ if (r.href && (r.target || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)) return;+ if (r.href) e.preventDefault();+ open(item);+ };+ return r.href+ ? html`<a+ class=${"dense-row" + (r.cls ? " " + r.cls : "")}+ href=${r.href}+ target=${ifDefined(r.target)}+ rel=${ifDefined(r.target ? "noopener" : undefined)}+ @click=${click}+ >${content}</a+ >`+ : html`<div+ class=${"dense-row" + (r.cls ? " " + r.cls : "")}+ tabindex="0"+ role="button"+ @click=${click}+ @keydown=${(e: KeyboardEvent) => {+ if (e.key === "Enter") open(item);+ }}+ >+ ${content}+ </div>`;+ },+ )}+ </div>`;+}+function scopeList(items: Data[], c: Context, noun: string, latest: (r: Data) => number, message: string) {+ const groups = new Map<string, Data>();+ for (const item of items) {+ const id = item.ownerScopeId || item.scopeId;+ const group = groups.get(id) || { scopeId: id, count: 0, latest: 0 };+ group.count++;+ group.latest = Math.max(group.latest, latest(item));+ groups.set(id, group);+ }+ return dense(+ [...groups.values()].sort((a, b) => b.latest - a.latest),+ (g) => ({+ name: c.shortName(g.scopeId),+ preview: c.plural(g.count, noun),+ time: c.relTime(g.latest),+ href: c.stateToUrl({ view: c.view, scope: g.scopeId, ...(c.scopeKind(g.scopeId) === "org" ? { own: "1" } : {}) }),+ }),+ (g) => c.openScopeRow(g.scopeId, c.view === "crons" ? { cron: null } : {}),+ message,+ );+}+function searchShell(c: Context, key: string, shell: Data, placeholder: string, draw: (q: string) => void) {+ const id = [key, c.scope, c.own].join("\0");+ const q = queries.get(id) || "";+ const active = document.activeElement as HTMLInputElement | null;+ const focus = !!active?.closest(".shell-search");+ const caret = focus ? active?.selectionStart : null;+ c.pageShell({+ ...shell,+ search: {+ placeholder,+ onInput: (value: string) => {+ queries.set(id, value);+ draw(value.trim().toLowerCase());+ },+ },+ });+ const input = document.querySelector<HTMLInputElement>("#shellbar .shell-search input");+ if (input) {+ input.value = q;+ if (focus) {+ input.focus();+ const pos = Math.min(caret ?? q.length, q.length);+ input.setSelectionRange(pos, pos);+ }+ }+ return q.trim().toLowerCase();+}+const listShell = (c: Context, title: string, count: string) => ({+ ...(c.index+ ? {}+ : {+ back: {+ label: "← " + title,+ onClick: () => c.go({ view: c.view, scope: "org:" + c.orgId, own: null, session: null, page: 1 }),+ },+ }),+ title: c.index ? title : c.shortName(c.scope),+ count,+});+export function files(root: HTMLElement, d: Data, c: Context) {+ const render = renderer(root);+ const all = [...(d.files || [])].sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));+ const items = c.own ? all.filter((f) => c.scopeKind(f.scopeId) === "org") : all;+ const capped = all.length >= 2000;+ let query = "",+ remote: Data[] | null = null,+ request = 0,+ timer: ReturnType<typeof setTimeout>;+ const failedImages = new Set<string>();+ const row = (f: Data): Row => {+ const kind = c.fileKind(f.name || f.path);+ const image = f.openable && /^image\/(png|jpeg|gif|webp|avif|bmp)$/.test(f.mimetype || "");+ const large = image && f.size > 200 * 1024;+ return {+ icon: html`<span+ class="file-thumb"+ title=${ifDefined(large ? "Large image. Click to preview full size" : undefined)}+ >${(() => {+ if (large) return "img";+ return kind === "file" ? "" : kind.slice(1);+ })()}${+ image && !large && !failedImages.has(f.id)+ ? html`<img+ loading="lazy"+ decoding="async"+ alt=""+ src=${c.apiBase + "/api/files/download?id=" + encodeURIComponent(f.id)}+ @error=${() => {+ failedImages.add(f.id);+ draw();+ }}+ />`+ : nothing+ }</span+ >`,+ name: f.name || c.fileName(f.path),+ preview: c.index ? c.shortName(f.scopeId) : "",+ time: c.fmtBytes(f.size || 0) + " · " + c.relTime(f.createdAt),+ };+ };+ const draw = () => {+ const local = items.filter((f) => !query || (f.name || c.fileName(f.path)).toLowerCase().includes(query));+ render(+ bareCard(+ html`${c.index ? html`<div class=${"file-scope-index" + (query ? " hidden" : "")}>${scopeList(all, c, "file", (f) => f.createdAt || 0, "No documents saved yet.")}${capped ? empty("Only the newest 2,000 files are indexed, so a scope with only older files won't appear.") : nothing}</div>` : nothing}+ <div class=${c.index && !query ? "hidden" : ""}>+ ${dense(remote ?? local, row, c.downloadFile, query ? "No files match." : "No documents saved yet.")}+ </div>`,+ ),+ );+ };+ const onQuery = (q: string) => {+ query = q;+ remote = null;+ request++;+ clearTimeout(timer);+ draw();+ if (!capped || !q) return;+ const token = request;+ timer = setTimeout(async () => {+ const response = await c+ .api("GET", "/api/files?scope=" + encodeURIComponent(c.scope) + "&q=" + encodeURIComponent(q))+ .catch(() => null);+ if (token !== request || !root.isConnected) return;+ if (response?.ok) {+ remote = [...(response.data?.files || [])]+ .filter((f) => !c.own || c.scopeKind(f.scopeId) === "org")+ .sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));+ }+ draw();+ }, 250);+ };+ query = searchShell(+ c,+ "files",+ { ...listShell(c, "Files", items.length ? c.plural(items.length, "file") : ""), actions: [uploadBox(c)] },+ c.index ? "Search all files…" : "Search files…",+ onQuery,+ );+ onQuery(query);+}+export function uploadBox(c: Context) {+ let busy = false,+ dragging = false,+ message = "",+ tone = "muted";+ const holder = document.createDocumentFragment();++ const upload = async (files: FileList | File[]) => {+ const picked = [...files].filter((f) => f && f.size >= 0);+ if (!picked.length || busy) return;+ busy = true;+ message = "Uploading " + c.plural(picked.length, "file") + "...";+ tone = "saving";+ draw();+ let uploaded = 0;+ try {+ for (const file of picked) {+ const response = await fetch(c.apiBase + "/api/files/upload?scope=" + encodeURIComponent(c.scope), {+ method: "POST",+ headers: {+ "content-type": file.type || "application/octet-stream",+ "x-file-name": encodeURIComponent(file.name || "file"),+ "x-content-sha256": await c.fileSha256(file),+ },+ body: file,+ });+ if (!response.ok)+ throw new Error(c.uploadErrorMessage(await response.text(), "Upload failed (" + response.status + ")."));+ uploaded++;+ }+ message = "Uploaded " + c.plural(picked.length, "file") + ".";+ tone = "ok";+ c.invalidate();+ await c.reload();+ } catch (error) {+ message =+ (uploaded ? "Uploaded " + uploaded + " of " + picked.length + " before failure. " : "") ++ (error instanceof Error ? error.message : "Upload failed.");+ tone = "err";+ if (uploaded) {+ c.invalidate();+ await c.reload();+ }+ } finally {+ busy = false;+ dragging = false;+ input.value = "";+ draw();+ }+ };+ const hasFiles = (e: DragEvent) => Array.from(e.dataTransfer?.types || []).includes("Files");+ const draw = () =>+ render(+ html`<div+ class=${"file-upload" + (dragging ? " dragging" : "")}+ @dragenter=${(e: DragEvent) => {+ if (hasFiles(e)) {+ e.preventDefault();+ dragging = true;+ draw();+ }+ }}+ @dragover=${(e: DragEvent) => {+ if (hasFiles(e)) e.preventDefault();+ }}+ @dragleave=${(e: DragEvent) => {+ if (!(e.relatedTarget instanceof Node) || !(e.currentTarget as Node).contains(e.relatedTarget)) {+ dragging = false;+ draw();+ }+ }}+ @drop=${(e: DragEvent) => {+ if (hasFiles(e)) {+ e.preventDefault();+ dragging = false;+ void upload(e.dataTransfer?.files || []);+ }+ }}+ >+ <div class="file-upload-actions">+ <span class=${"status " + tone}>${message}</span+ ><button type="button" class="primary upload-button" ?disabled=${busy} @click=${() => input.click()}>+ <svg+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.8"+ stroke-linecap="round"+ stroke-linejoin="round"+ aria-hidden="true"+ >+ <path d="M12 16V3m-5 5 5-5 5 5M4 15v5a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-5"></path></svg+ ><span>Upload</span></button+ ><input+ type="file"+ multiple+ class="hidden"+ @change=${(e: Event) => upload((e.target as HTMLInputElement).files || [])}+ />+ </div>+ </div>`,+ holder,+ );+ draw();+ const input = holder.querySelector("input")!;+ return holder.firstElementChild;+}+export function deployments(root: HTMLElement, d: Data, c: Context) {+ const render = renderer(root);+ const all = [...(d.deployments || [])].sort(+ (a, b) => (b.lastAccessAt || b.createdAt || 0) - (a.lastAccessAt || a.createdAt || 0),+ );+ const items = c.own ? all.filter((r) => c.scopeKind(r.ownerScopeId) === "org") : all;+ const row = (r: Data) => ({+ name: r.name || r.id,+ preview: [+ c.titleCase(r.status || "unknown"),+ r.currentVersion || "",+ c.index ? c.shortName(r.ownerScopeId) : "",+ r.createdBy || "",+ ]+ .filter(Boolean)+ .join(" · "),+ time: c.relTime(r.lastAccessAt || r.createdAt),+ href: c.deploymentHref(r) || undefined,+ target: "_blank",+ });+ const draw = (q: string) =>+ render(+ bareCard(+ html`${c.index ? html`<div class=${q ? "hidden" : ""}>${scopeList(all, c, "app", (r) => r.lastAccessAt || r.createdAt || 0, "No apps yet.")}</div>` : nothing}+ <div class=${c.index && !q ? "hidden" : ""}>+ ${dense(+ items.filter((r) => !q || (r.name || r.id).toLowerCase().includes(q)),+ row,+ (r) => {+ const href = c.deploymentHref(r);+ if (href) window.open(href, "_blank", "noopener,noreferrer");+ },+ (() => {+ if (q) return "No apps match.";+ return c.index ? "No apps yet." : "No apps in this scope.";+ })(),+ )}+ </div>`,+ ),+ );+ draw(+ searchShell(+ c,+ "deployments",+ listShell(c, "Apps", c.plural(items.length, "app")),+ c.index ? "Search all apps…" : "Search apps…",+ draw,+ ),+ );+}+export function memory(root: HTMLElement, d: Data, c: Context) {+ const render = renderer(root);+ if (Array.isArray(d.scopes)) return memoryIndex(root, d, c);+ if (c.scopeDir)+ c.pageShell({+ back: { label: "← Memory", onClick: () => c.go({ view: "memory", scope: "org:" + c.orgId, session: null }) },+ title: c.orgWide ? "Org-wide" : c.shortName(c.scope),+ });+ let baseline = d.content || "";+ let draft = c.memoryDraft() ?? baseline;+ let saving = false,+ message = draft !== baseline ? "Unsaved changes" : "",+ tone = "";+ const save = async () => {+ if (saving) return;+ saving = true;+ const submitted = draft;+ draw();+ try {+ const response = await c.api("PUT", "/api/memory?scope=" + encodeURIComponent(c.scope), { content: submitted });+ if (response.ok) {+ baseline = submitted;+ c.setMemoryDraft(draft === submitted ? null : draft);+ message = draft === submitted ? "Saved ✓" : "Unsaved changes";+ tone = draft === submitted ? "ok" : "";+ } else {+ message =+ response.status === 403 ? "You don't administer this scope." : response.data?.message || "Save failed.";+ tone = "err";+ }+ } catch {+ message = "Save failed.";+ tone = "err";+ } finally {+ saving = false;+ draw();+ }+ };+ const draw = () =>+ render(+ html`<section class="card memory-editor">+ <div class="head">+ <h2>Notebook</h2>+ <p>What the agent remembers in this scope. Changes apply when you save.</p>+ </div>+ <div class="body">+ <div>+ <label for="memory-text">Notebook contents</label+ ><textarea+ id="memory-text"+ spellcheck="false"+ aria-label="Notebook contents"+ style="min-height:340px;font-family:ui-monospace, SFMono-Regular, Menlo, monospace;font-size:12px"+ placeholder="No memory stored for this scope yet. Anything you write here, the agent will remember."+ .value=${draft}+ @input=${(e: Event) => {+ draft = (e.target as HTMLTextAreaElement).value;+ c.setMemoryDraft(draft);+ message = draft !== baseline ? "Unsaved changes" : "";+ tone = "";+ draw();+ }}+ ></textarea>+ <div class="foot">+ <button class="primary" ?disabled=${saving} @click=${save}>Save</button+ ><span class=${"status" + (tone ? " " + tone : "")} id="st-memory" role="status">${message}</span>+ </div>+ </div>+ </div>+ </section>`,+ );+ draw();+}+function memoryIndex(root: HTMLElement, d: Data, c: Context) {+ const render = renderer(root);+ const scopes = (d.scopes || []).filter((s: Data) => s.hasMemory || c.scopeKind(s.scopeId) === "org");+ const written = scopes.filter((s: Data) => s.hasMemory);+ const hasTimestamps = written.some((s: Data) => s.updatedAt);+ scopes.sort((a: Data, b: Data) =>+ hasTimestamps+ ? (b.updatedAt || 0) - (a.updatedAt || 0) || (b.bytes || 0) - (a.bytes || 0)+ : (b.bytes || 0) - (a.bytes || 0),+ );+ const state = (s: Data) => ({+ view: "memory",+ scope: s.scopeId,+ session: null,+ ...(c.scopeKind(s.scopeId) === "org" ? { mem: "edit" } : {}),+ });+ const draw = (q: string) =>+ render(+ html`<div class="memory-notebooks">+ <div class="memory-columns"><span>Notebook</span><span>Size</span><span>Last updated</span></div>+ ${dense(+ scopes.filter(+ (s: Data) => !q || [s.label, c.shortName(s.scopeId), s.scopeId].join(" ").toLowerCase().includes(q),+ ),+ (s) => ({+ name: c.scopeKind(s.scopeId) === "org" ? "org" : s.label || c.shortName(s.scopeId),+ preview: s.hasMemory ? c.fmtBytes(s.bytes || 0) : "empty",+ time: s.updatedAt ? c.relTime(s.updatedAt) : "Never",+ href: c.stateToUrl(state(s)),+ }),+ (s) => c.go(state(s)),+ q ? "No notebooks match your search." : "No notebooks yet. The agent hasn't remembered anything.",+ )}+ </div>`,+ );+ c.pageShell({+ title: "Memory",+ count: c.plural(written.length, "notebook"),+ search: { placeholder: "Search notebooks…", onInput: (value: string) => draw(value.trim().toLowerCase()) },+ context: written.length && !hasTimestamps ? "sorted by size (this backend keeps no edit history)" : "",+ });+ draw("");+}+export function skills(root: HTMLElement, d: Data, c: Context) {+ const render = renderer(root);+ const lastUse = (s: Data) => s.lastUsedAt || s.updatedAt || s.createdAt || 0;+ const all = (d.skills || [])+ .filter((s: Data) => s.status !== "archived")+ .sort((a: Data, b: Data) => lastUse(b) - lastUse(a) || (a.name || "").localeCompare(b.name || ""));+ const items = c.own ? all.filter((s: Data) => c.scopeKind(s.ownerScopeId) === "org") : all;+ const count =+ c.plural(items.length, "skill") ++ (c.index && items.length ? " · " + c.plural(new Set(items.map((s: Data) => s.ownerScopeId)).size, "scope") : "");+ const packs = document.createElement("div"),+ detail = document.createElement("div");+ const identity = (s: Data) => (s.name || s.id) + "\0" + (s.createdBy || "");+ const open = (s: Data) =>+ skillDetail(+ detail,+ s,+ all.filter((r: Data) => identity(r) === identity(s)),+ c,+ );+ const pending = new Set<string>();+ let query = "";+ const draw = (q = query) => {+ query = q;+ const shown = items.filter(+ (s: Data) => !q || ((s.name || s.id) + " " + (s.description || "")).toLowerCase().includes(q),+ );+ const rows = shown.map((s: Data) => [+ {+ node: html`<div>+ <div class="primaryline">${s.name || s.id}</div>+ <div class="subline">${s.description || c.shortId(s.id)}</div>+ </div>`,+ },+ ...(c.index ? [{ text: c.shortName(s.ownerScopeId), cls: "mono" }] : []),+ { text: c.titleCase(s.status || "unknown"), cls: "subline" },+ c.createdByCell(s),+ {+ text: (() => {+ if (s.lastUsedAt) return c.fmtHistoryTime(s.lastUsedAt);+ return lastUse(s) ? "never · imported " + c.fmtHistoryTime(lastUse(s)) : "never";+ })(),+ cls: s.lastUsedAt ? "num" : "num subline",+ },+ {+ node: html`<button+ type="button"+ class="rowbtn danger"+ ?disabled=${pending.has(s.id)}+ @click=${async (e: Event) => {+ e.stopPropagation();+ if (pending.has(s.id)) return;+ pending.add(s.id);+ draw();+ try {+ await removeSkill(s, c);+ } finally {+ pending.delete(s.id);+ draw();+ }+ }}+ >+ Remove+ </button>`,+ },+ ]);+ render(+ html`${c.index ? packs : nothing}${card(+ "Installed skills",+ "",+ html`${c.index ? html`<div class=${q ? "hidden" : ""}>${scopeList(all, c, "skill", lastUse, "No skills yet.")}</div>` : nothing}+ <div class=${c.index && !q ? "hidden" : ""}>+ ${table(+ ["Skill", ...(c.index ? ["Scope"] : []), "Status", "Created by", "Last used", ""],+ rows,+ (() => {+ if (q) return "No skills match.";+ return c.index ? "No skills yet." : "No skills in this scope.";+ })(),+ (i: number) => open(shown[i]),+ { className: "skills-table" },+ )}+ </div>`,+ )}${detail}`,+ );+ };+ query = searchShell(+ c,+ "skills",+ listShell(c, "Skills", count),+ c.index ? "Search all skills…" : "Search skills…",+ draw,+ );+ draw();+ if (c.index) void mountPacks(packs, c);+}+const cronStatus = (c: Data) =>+ (() => {+ if (c.archived) return "archived";+ return c.enabled === false ? "disabled" : "enabled";+ })();+export function crons(root: HTMLElement, d: Data, c: Context) {+ const render = renderer(root);+ const all = d.crons || [];+ if (c.cron)+ return cronDetail(+ root,+ all.find((row: Data) => row.id === c.cron),+ c.cron,+ c,+ );+ const items = c.own ? all.filter((r: Data) => c.scopeKind(r.ownerScopeId) === "org") : all;+ const sorted = [...items].sort((a, b) => (b.lastFiredAt || b.createdAt || 0) - (a.lastFiredAt || a.createdAt || 0));+ const disabled = items.filter((r: Data) => !r.archived && r.enabled === false).length;+ const archived = items.filter((r: Data) => r.archived).length;+ const row = (r: Data) => ({+ name: c.firstLine(c.cronName(r, true), 72),+ preview: [+ c.index ? c.shortName(r.ownerScopeId) : "",+ cronStatus(r) === "enabled" ? "" : cronStatus(r),+ c.firstLine(+ (() => {+ if (r.title) return r.action || r.message || "";+ return r.action && r.message ? r.action : "";+ })(),+ 200,+ ),+ ]+ .filter(Boolean)+ .join(" · "),+ time: c.shortSchedule(r.schedule) + " · " + (r.lastFiredAt ? c.relTime(r.lastFiredAt) : "never fired"),+ cls: cronStatus(r) === "enabled" ? "" : "dim",+ href: c.stateToUrl({ view: "crons", scope: c.scope, cron: r.id }),+ });+ const draw = (q: string) =>+ render(+ bareCard(+ html`${c.index ? html`<div class=${q ? "hidden" : ""}>${scopeList(all, c, "cron", (r) => r.lastFiredAt || r.createdAt || 0, "No crons yet.")}</div>` : nothing}+ <div class=${c.index && !q ? "hidden" : ""}>+ ${dense(+ sorted.filter(+ (r) => !q || (c.cronName(r, true) + " " + (r.action || r.message || "")).toLowerCase().includes(q),+ ),+ row,+ (r) => c.go({ view: "crons", scope: c.scope, session: null, cron: r.id, page: 1 }),+ (() => {+ if (q) return "No crons match.";+ return c.index ? "No crons yet." : "No crons in this scope.";+ })(),+ )}+ </div>`,+ ),+ );+ draw(+ searchShell(+ c,+ "crons",+ {+ ...listShell(c, "Crons", c.plural(items.length, "cron")),+ stats: [...(disabled ? [[disabled, "disabled"]] : []), ...(archived ? [[archived, "archived"]] : [])],+ },+ c.index ? "Search all crons…" : "Search crons…",+ draw,+ ),+ );+}+function cronDetail(root: HTMLElement, cron: Data | undefined, id: string, c: Context) {+ const render = renderer(root);+ c.pageShell({+ back: {+ label: "← Crons",+ onClick: () => c.go({ view: "crons", scope: c.scope, session: null, cron: null, page: 1 }),+ },+ title: cron ? c.firstLine(c.cronName(cron, true), 90) : "Cron",+ context: cron ? c.shortName(cron.ownerScopeId) : "",+ });+ if (!cron) {+ render(empty("Cron " + c.shortId(id) + " isn't in this scope."));+ return;+ }+ let editing = false,+ saving = false,+ expanded = false,+ needsToggle = true;+ let fires: Data[] | null = null,+ error = "",+ total = 0;+ const draft = {+ type: cron.destination?.type === "principal" ? "principal" : "slack",+ target: cron.destination?.target || "",+ audienceScopeId: cron.destination?.audienceScopeId || "",+ onBehalfOf: cron.destination?.onBehalfOf || "",+ };+ const change = (key: keyof typeof draft) => (e: Event) => {+ draft[key] = (e.target as HTMLInputElement).value;+ draw();+ };+ const save = async (clear = false) => {+ if (saving) return;+ if (!clear && !draft.target.trim()) {+ root.querySelector<HTMLInputElement>('input[name="cron-target"]')?.focus();+ alert("Target is required.");+ return;+ }+ const destination = clear+ ? null+ : {+ type: draft.type,+ target: draft.target.trim(),+ ...(draft.audienceScopeId.trim() ? { audienceScopeId: draft.audienceScopeId.trim() } : {}),+ ...(draft.type === "principal" && draft.onBehalfOf.trim() ? { onBehalfOf: draft.onBehalfOf.trim() } : {}),+ };+ const submitted = JSON.stringify(draft);+ saving = true;+ draw();+ try {+ const response = await c.api(+ "PUT",+ "/api/crons/" + encodeURIComponent(id) + "/destination?scope=" + encodeURIComponent(c.scope),+ { destination },+ );+ if (!response.ok) {+ alert(response.data?.message || "Could not update destination.");+ return;+ }+ cron.destination = destination;+ c.invalidate();+ if (JSON.stringify(draft) === submitted) {+ editing = false;+ c.setCronEditing(null);+ await c.reload();+ }+ } catch {+ alert("Could not update destination.");+ } finally {+ saving = false;+ if (root.isConnected) draw();+ }+ };+ const prompt = cron.action || cron.message || "";+ const facts = () => [+ ["Schedule", c.fmtSchedule(cron.schedule)],+ [+ "Destination",+ html`<span+ >${c.destinationSummary(cron.destination) + (c.destinationDetails(cron.destination) && cron.destination ? " · " + c.destinationDetails(cron.destination) : "")}</span+ >`,+ ],+ ["Owner", cron.owner || cron.createdBy || "None"],+ ["Status", cronStatus(cron)],+ ["Created", c.fmtTime(cron.createdAt)],+ ["Last fired", cron.lastFiredAt ? c.relTime(cron.lastFiredAt) : "never fired"],+ ["Id", cron.id],+ ];+ const draw = () =>+ render(+ html`${+ editing+ ? card(+ "Edit cron destination",+ cron.title || cron.action || cron.message || cron.id,+ html`<div>+ <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(160px, 1fr));gap:10px">+ <label+ >Type<select .value=${draft.type} @change=${change("type")}>+ <option value="slack" .selected=${draft.type === "slack"}>slack</option>+ <option value="principal" .selected=${draft.type === "principal"}>principal</option>+ </select></label+ ><label+ >Target<input+ name="cron-target"+ type="text"+ .value=${draft.target}+ placeholder=${draft.type === "principal" ? "principal id" : "Slack channel/thread id"}+ @input=${change("target")} /></label+ ><label+ >Audience scope<input+ type="text"+ .value=${draft.audienceScopeId}+ placeholder=${draft.type === "principal" ? "personal:U123" : "channel:C123"}+ @input=${change("audienceScopeId")} /></label+ ><label+ >On behalf of<input+ type="text"+ .value=${draft.onBehalfOf}+ ?disabled=${draft.type !== "principal"}+ @input=${change("onBehalfOf")}+ /></label>+ </div>+ <div class="foot">+ <button type="button" class="primary" ?disabled=${saving} @click=${() => save()}>+ Save destination</button+ ><button+ type="button"+ ?disabled=${saving}+ @click=${() => {+ editing = false;+ c.setCronEditing(null);+ draw();+ }}+ >+ Cancel+ </button>+ </div>+ </div>`,+ )+ : nothing+ }+ <div class="factlist">+ ${facts()+ .filter(([, value]) => value != null && value !== "")+ .map(+ ([label, value]) =>+ html`<div class="fk">${label}</div>+ <div class="fv">${value}</div>`,+ )}+ </div>+ <div class="credential-actions" style="margin:0 0 18px">+ <button+ type="button"+ class="rowbtn"+ ?disabled=${saving}+ @click=${() => {+ Object.assign(draft, {+ type: cron.destination?.type === "principal" ? "principal" : "slack",+ target: cron.destination?.target || "",+ audienceScopeId: cron.destination?.audienceScopeId || "",+ onBehalfOf: cron.destination?.onBehalfOf || "",+ });+ editing = true;+ c.setCronEditing(id);+ draw();+ }}+ >+ Edit destination</button+ ><button+ type="button"+ class="rowbtn danger"+ ?disabled=${saving || !cron.destination}+ @click=${() => save(true)}+ >+ Clear destination+ </button>+ </div>+ ${+ prompt+ ? card(+ cron.action ? "Prompt" : "Message",+ cron.action ? "Re-run as a fresh prompt at every fire." : "Delivered as-is at every fire.",+ html`<div>+ <p class=${"prompt-body" + (expanded ? "" : " clamped")}>${prompt}</p>+ ${+ needsToggle+ ? html`<button+ type="button"+ class="prompt-toggle"+ @click=${() => {+ expanded = !expanded;+ draw();+ }}+ >+ ${expanded ? "Show less" : "Show more"}+ </button>`+ : nothing+ }+ </div>`,+ )+ : nothing+ }${card(+ "Recent fires",+ "Each fire is a session. Click one to read its transcript. Dimmed fires delivered nothing.",+ html`<div>+ ${(() => {+ if (error) return empty(error);+ return fires === null+ ? html`<div class="loadingline">Loading fires...</div>`+ : dense(+ fires,+ (s) => ({+ name: c.relTime(s.createdAt || s.lastActivity),+ preview: [+ (() => {+ if (typeof s.delivered === "number")+ return s.delivered ? "delivered" + (s.delivered > 1 ? " ×" + s.delivered : "") : "silent";+ return "";+ })(),+ c.plural(s.turns || 0, "turn"),+ s.result || "(no messages)",+ ]+ .filter(Boolean)+ .join(" · "),+ time: c.plural(s.messages || 0, "entry", "entries"),+ cls: typeof s.delivered === "number" && !s.delivered ? "dim" : "",+ href: c.stateToUrl({ view: "history", scope: s.scopeId || c.scope, session: s.id }),+ }),+ (s) => c.go({ view: "history", scope: s.scopeId || c.scope, session: s.id }),+ "This cron has never fired.",+ );+ })()}${total > 25 ? html`<button type="button" class="prompt-toggle" @click=${() => c.go({ view: "history", scope: c.scope, session: null, page: 1, historyKind: "cron", cron: id })}>${"All " + c.plural(total, "fire") + " →"}</button>` : nothing}+ </div>`,+ )}`,+ );+ draw();+ requestAnimationFrame(() => {+ const p = root.querySelector<HTMLElement>(".prompt-body");+ if (p && p.scrollHeight > 0 && p.scrollHeight <= p.clientHeight + 1) {+ needsToggle = false;+ draw();+ }+ });+ void c+ .api(+ "GET",+ `/api/sessions?scope=${encodeURIComponent(c.scope)}&limit=25&offset=0&category=background&origin=cron&cron=${encodeURIComponent(id)}`,+ )+ .then((response: Data) => {+ if (!root.isConnected) return;+ if (response.ok) {+ fires = response.data.sessions || [];+ total = response.data.total || fires!.length;+ } else error = response.data?.message || `Failed to load fires (${response.status}).`;+ draw();+ })+ .catch(() => {+ if (root.isConnected) {+ error = "Failed to load fires.";+ draw();+ }+ });+}+const kpis = (items: unknown[][]) =>+ html`<div class="kpis">+ ${items.map(+ ([value, label]) =>+ html`<div class="kpi">+ <div class="n">${value}</div>+ <div class="k">${label}</div>+ </div>`,+ )}+ </div>`;+export function retention(root: HTMLElement, d: Data) {+ const render = renderer(root);+ const a = d.active || {},+ nvr = d.newVsReturning || {},+ pu = d.perUser || {};+ const retentionCell = (p: number) => ({+ node: badge(+ p + "%",+ (() => {+ if (p >= 40) return "ok";+ return p >= 15 ? "warn" : "muted";+ })(),+ ),+ cls: "num",+ });+ render(+ html`${kpis([+ [a.dau ?? 0, "DAU"],+ [a.wau ?? 0, "WAU"],+ [a.mau ?? 0, "MAU"],+ [(a.stickiness ?? 0) + "%", "Stickiness (DAU/MAU)"],+ ])}+ <div class="metric-note">+ Stickiness${badge(+ String(a.stickiness ?? 0) + "%",+ (() => {+ if ((a.stickiness ?? 0) >= 30) return "ok";+ return (a.stickiness ?? 0) >= 10 ? "warn" : "muted";+ })(),+ )}+ </div>+ ${card(+ "New vs returning",+ `Distinct active users in the trailing ${nvr.window || "30d"}.`,+ table(+ ["New", "Returning"],+ [+ [+ { text: String(nvr.newUsers ?? 0), cls: "num" },+ { text: String(nvr.returning ?? 0), cls: "num" },+ ],+ ],+ "No activity yet.",+ ),+ )}${card(+ "Weekly retention cohorts",+ "Of users first active in a week, the share active in following weeks. Channel attribution is approximate.",+ table(+ ["Cohort (week of)", "Users", "W0", "W1", "W2", "W3", "W4"],+ (d.cohorts || []).map((r: Data) => [+ r.week,+ { text: String(r.size), cls: "num" },+ ...(r.retained || []).map(retentionCell),+ ]),+ "No cohorts yet.",+ ),+ )}${card(+ "Per-user distribution",+ `${d.totals?.users ?? 0} users · ${d.totals?.sessions ?? 0} sessions. ${d.attribution || ""}`,+ table(+ ["Metric", "p50", "p95"],+ [+ [+ "Sessions / user",+ { text: String(pu.sessions?.p50 ?? 0), cls: "num" },+ { text: String(pu.sessions?.p95 ?? 0), cls: "num" },+ ],+ [+ "Turns / user",+ { text: String(pu.turns?.p50 ?? 0), cls: "num" },+ { text: String(pu.turns?.p95 ?? 0), cls: "num" },+ ],+ ],+ "No users yet.",+ ),+ )}`,+ );+}+export function live(root: HTMLElement, d: Data, c: Context) {+ const render = renderer(root);+ const runs = d.runs || [];+ render(+ html`${kpis([+ [d.active ?? 0, "Active now"],+ [runs.length, "Recent runs"],+ [runs.filter((r: Data) => r.status === "failed").length, "Failed"],+ [runs.filter((r: Data) => r.status === "done").length, "Done"],+ ])}${bareCard(+ table(+ ["Run", "Status", "Scope", "Type", "Attempts", "Worker", "Duration", "Lease", "Started"],+ runs.map((r: Data) => [+ { node: c.stacked("Run " + c.shortId(r.id), r.threadRef || "no thread"), cls: "mono" },+ { node: c.statusBadge(r.status) },+ r.sessionScope ? c.scopeCell(r.sessionScope) : { text: "-", cls: "mono" },+ { node: c.typeBadge(r.sessionType) },+ {+ node: badge(`${r.attempts}/${r.maxAttempts}`, r.status === "failed" || r.attempts > 1 ? "warn" : "muted"),+ cls: "num",+ },+ { text: r.workerId || "-", cls: "mono" },+ { text: c.fmtDuration(r.startedAt || r.createdAt, r.finishedAt), cls: "num" },+ {+ text:+ r.leaseExpiresAt && (r.status === "running" || r.status === "pending")+ ? c.fmtTime(r.leaseExpiresAt)+ : "-",+ cls: "num",+ },+ { text: r.startedAt ? c.fmtTime(r.startedAt) : "-", cls: "num" },+ ]),+ "No runs.",+ ),+ )}`,+ );+}diff --git a/plugins/admin/ui/design.ts b/plugins/admin/ui/design.tsnew file mode 100644index 000000000..2aafb86fd--- /dev/null+++ b/plugins/admin/ui/design.ts@@ -0,0 +1,707 @@+import { html, nothing } from "lit";+import { renderer } from "./shared.ts";+type Context = {+ stateToUrl: (state: Record<string, unknown>) => string;+ scope: () => string;+ searchField: (options: Record<string, unknown>) => Node;+ twoWayToggle: (options: Record<string, unknown>) => Node;+ fileThumb: (item: Record<string, unknown>) => Node;+ initCustomDropdowns: (root: HTMLElement) => void;+};+const DESIGN_TOKENS = [+ ["--bg", "Page behind every surface"],+ ["--surface", "Cards, dialogs, table bodies"],+ ["--subtle", "Quiet control and inset backgrounds"],+ ["--border", "Every hairline and divider"],+ ["--text", "Primary copy"],+ ["--muted", "Secondary copy and hints"],+ ["--cta", "Primary actions and selected controls"],+ ["--ok", "Confirmed and healthy"],+ ["--warn", "Needs attention"],+ ["--danger", "Destructive and failed"],+ ["--trigger", "Automation and triggers"],+];++export function show(context: Context) {+ const root = document.getElementById("view-design")!;+ if (root.dataset.litDesign) return;+ root.dataset.litDesign = "true";+ const draw = renderer(root);+ const state = {+ scopeStatus: "Choose a scope to try the row interaction.",+ fileStatus: "File names, thumbnails, sizes, and dates stay visible.",+ packStatus: "Registration is a local demonstration.",+ searchStatus: "Type to try the search field, then clear it.",+ toggleStatus: "Selected: Human activity",+ advanced: false,+ name: "Acme",+ savedName: "Acme",+ nameSaved: false,+ chip: true,+ };+ const update = (change: Partial<typeof state>) => {+ Object.assign(state, change);+ paint();+ };+ const dialog = () => document.getElementById("design-dialog") as HTMLDialogElement;+ const search = context.searchField({+ placeholder: "Search messages…",+ onInput: (value: string) =>+ update({ searchStatus: value ? "Search query: " + value : "Type to try the search field, then clear it." }),+ });+ const searchFilled = context.searchField({ placeholder: "Search messages…", value: "Product updates" });+ const searchDisabled = context.searchField({ placeholder: "Search unavailable", disabled: true });+ const options = [+ { value: "human", label: "Human activity" },+ { value: "all", label: "All activity" },+ ];+ const toggle = context.twoWayToggle({+ label: "Example activity sort",+ options,+ value: "human",+ onChange: (value: string) => update({ toggleStatus: "Selected: " + options.find((o) => o.value === value)!.label }),+ });+ const toggleDisabled = context.twoWayToggle({+ label: "Disabled activity sort",+ options,+ value: "human",+ disabled: true,+ onChange: () => {},+ });+ const scopeList = () =>+ html`<div class="dense-list">+ ${[+ { name: "Example team", preview: "12 skills", time: "5 mins ago" },+ { name: "Research", preview: "4 skills", time: "Yesterday" },+ ].map(+ (item) =>+ html`<div+ class="dense-row"+ tabindex="0"+ role="button"+ @click=${() => update({ scopeStatus: "Selected: " + item.name })}+ @keydown=${(e: KeyboardEvent) => {+ if (e.key === "Enter") update({ scopeStatus: "Selected: " + item.name });+ }}+ >+ <span class="dense-name">${item.name}</span><span class="dense-preview">${item.preview}</span+ ><span class="dense-time">${item.time}</span>+ </div>`,+ )}+ </div>`;+ const fileItems = [+ { name: "Research brief.pdf", size: "240 KB", date: "Today" },+ { name: "Project notes.md", size: "8 KB", date: "Yesterday" },+ ].map((item) => ({ ...item, thumb: context.fileThumb(item) }));+ const fileList = () =>+ html`<div class="dense-list">+ ${fileItems.map(+ (item) =>+ html`<div+ class="dense-row"+ tabindex="0"+ role="button"+ @click=${() => update({ fileStatus: "Selected: " + item.name + " (demo only)" })}+ @keydown=${(e: KeyboardEvent) => {+ if (e.key === "Enter") update({ fileStatus: "Selected: " + item.name + " (demo only)" });+ }}+ >+ <span class="dense-icon">${item.thumb}</span><span class="dense-name">${item.name}</span+ ><span class="dense-preview">Example team</span+ ><span class="dense-time">${item.size + " · " + item.date}</span>+ </div>`,+ )}+ </div>`;+ function nameStatus() {+ if (state.name !== state.savedName) return "Unsaved changes";+ return state.nameSaved ? "Saved in this example" : "No changes";+ }+ function paint() {+ const titles: string[] = [];+ const designSpec = (label: string, note: string, demo: unknown, stack = false) =>+ html`<div class="spec">+ <div class="spec-label">${label}${note ? html`<span>${note}</span>` : nothing}</div>+ <div class=${"spec-demo" + (stack ? " stack" : "")}>${demo}</div>+ </div>`;+ const sectionId = (title: string) => "design-group-" + title.toLowerCase().replace(/[^a-z0-9]+/g, "-");+ const designSection = (title: string, blurb: string, specs: unknown[]) => {+ titles.push(title);+ return html`<section class="design-group" id=${sectionId(title)}>+ <h2>${title}</h2>+ <p>${blurb}</p>+ ${specs}+ </section>`;+ };+ const swatches = DESIGN_TOKENS.map(+ (t) =>+ html`<div class="swatch">+ <div class="swatch-chip" style=${"background: var(" + t[0] + ")"}></div>+ <div class="swatch-meta"><b>${t[0]}</b>${t[1]}</div>+ </div>`,+ );+ const sections = [+ html`<p class="lead">+ Components and page patterns from the redesigned admin portal, including Skills, Files, Sessions, Metrics,+ Audit, and Egress. Examples use fictional data and do not save changes.+ </p>`,+ designSection("Foundations", "One palette, a small type scale, and consistent spacing.", [+ designSpec(+ "Semantic colors",+ "Shared theme tokens · light and dark",+ html`<div class="swatches">${swatches}</div>`,+ ),+ designSpec(+ "Type & spacing",+ "22px page title · 14px section title · 13px controls and copy",+ html`<div class="shell-title">Page title</div>+ <div class="head">+ <h2>Section title</h2>+ <p>Descriptions explain the setting.</p>+ </div>+ <label>Field label</label>+ <p class="hint">4px label gap · 8px action gap · 24px section spacing</p>`,+ true,+ ),+ ]),+ designSection(+ "Page layout",+ "Start with the shared shell. Align titles, sections, and rows to the same content edge; use whitespace and dividers instead of enclosing cards.",+ [+ designSpec(+ "Desktop and mobile",+ "Authored layout diagrams · .admin-main → .admin-inner → .shellbar",+ html`<div class="design-layouts">+ <div class="design-layout-frame">+ <div class="design-layout-nav">Sidebar<br />Independent scroll</div>+ <div class="design-layout-main">+ <div class="design-layout-content">+ <div class="design-layout-title">Title <span>Search / action</span></div>+ <div class="design-layout-section">Open section<br /><small>Heading + description</small></div>+ <div class="design-layout-lines">Compact rows<br />────────────────<br />Compact rows</div>+ </div>+ </div>+ </div>+ <div class="design-layout-frame mobile">+ <div class="design-layout-nav">Horizontal navigation</div>+ <div class="design-layout-main">+ <div class="design-layout-content">+ <div class="design-layout-title">Title</div>+ <div class="design-layout-section">Full-width search</div>+ <div class="design-layout-lines">Stacked content<br />────────────<br />Local table scroll</div>+ </div>+ </div>+ </div>+ </div>`,+ true,+ ),+ designSpec(+ "Width and page padding",+ "Current New CSS · index.html and admin-components.css",+ html`<div class="tablewrap">+ <table>+ <thead>+ <tr>+ <th>Rule</th>+ <th>Desktop</th>+ <th>Small screens</th>+ </tr>+ </thead>+ <tbody>+ <tr>+ <td>Navigation</td>+ <td>280px sidebar; independent scroll</td>+ <td>Horizontal navigation at ≤900px</td>+ </tr>+ <tr>+ <td>Content width</td>+ <td>960px maximum, centered; fluid below that</td>+ <td>Available width; min-width: 0</td>+ </tr>+ <tr>+ <td>Main padding</td>+ <td>28px top and sides</td>+ <td>At ≤900px: 18px top, 14px sides with safe-area insets</td>+ </tr>+ <tr>+ <td>Bottom clearance</td>+ <td colspan="2">110px for the fixed Original / New switch</td>+ </tr>+ <tr>+ <td>Page heading</td>+ <td colspan="2">22px / 500 weight; shared shell spacing 16px (activity pages use 24px)</td>+ </tr>+ <tr>+ <td>Sections</td>+ <td colspan="2">24px between artifact sections; 12px from section heading to content</td>+ </tr>+ <tr>+ <td>Controls</td>+ <td colspan="2">32px height · 6px radius · 8px gap · 4px label gap</td>+ </tr>+ </tbody>+ </table>+ </div>`,+ true,+ ),+ designSpec(+ "Choose a page pattern",+ "Live references · preserve the selected organization",+ html`<div class="design-page-links">+ <a+ data-design-view="governance"+ href=${context.stateToUrl({ view: "governance", scope: context.scope() })}+ >Governance / Models</a+ >+ <p>+ Descriptions beside settings, 40px column gap; stack on small screens. Keep Apply right-aligned with+ status on its left.+ </p>+ <a data-design-view="skills" href=${context.stateToUrl({ view: "skills", scope: context.scope() })}+ >Skills</a+ >+ <p>Open installed-skill and skill-pack sections; compact tables and an inline registration form.</p>+ <a data-design-view="files" href=${context.stateToUrl({ view: "files", scope: context.scope() })}+ >Files</a+ >+ <p>Search in the header, flat upload toolbar, then scopes or files with metadata.</p>+ <a data-design-view="history" href=${context.stateToUrl({ view: "history", scope: context.scope() })}+ >Sessions</a+ >+ <p>Two-way sort toggle, named environments, and a separately titled conversation list.</p>+ <a data-design-view="audit" href=${context.stateToUrl({ view: "audit", scope: context.scope() })}+ >Audit</a+ >+ ·+ <a data-design-view="egress" href=${context.stateToUrl({ view: "egress", scope: context.scope() })}+ >Egress</a+ >+ <p>Filters above plain tables; headers stay transparent and regular-weight.</p>+ </div>`,+ true,+ ),+ designSpec(+ "Responsive behavior",+ "Page-level rules",+ html`<ul class="design-rules">+ <li>At ≤900px, the sidebar becomes horizontal navigation.</li>+ <li>+ At ≤640px, Skills and Files search uses the full row; dense rows allow more height and Files metadata+ wraps below the name.+ </li>+ <li>Wide tables scroll inside .tablewrap. Never force the entire document wider than the viewport.</li>+ <li>+ Keep all actions and metadata available on mobile. Use wrapping or local scrolling rather than hiding+ content.+ </li>+ <li>Sidebar scrolling is contained; reaching its end must not scroll the main page.</li>+ </ul>`,+ true,+ ),+ ],+ ),+ designSection(+ "Artifact and reporting patterns",+ "Compositions from the recent redesigns. Shared helpers render the lists; the form and report examples are local demonstrations.",+ [+ designSpec(+ "Scope list",+ "denseList() · shared Skills / Files row styles · Enter or click selects a demo row",+ html`<div id="design-scope-list">${scopeList()}</div>+ <p class="hint" id="design-scope-status" role="status">${state.scopeStatus}</p>`,+ true,+ ),+ designSpec(+ "File list and upload toolbar",+ "denseList() + fileThumb() · .file-upload · visual upload example, no network requests",+ html`<div class="file-upload">+ <div class="file-upload-actions">+ <button+ type="button"+ class="primary upload-button"+ id="design-upload"+ @click=${() => update({ fileStatus: "On Files, this opens the file picker. This example does not upload files." })}+ >+ <svg+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.8"+ stroke-linecap="round"+ stroke-linejoin="round"+ aria-hidden="true"+ >+ <path d="M12 16V3m-5 5 5-5 5 5M4 15v5a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-5" /></svg+ ><span>Upload</span>+ </button>+ </div>+ </div>+ <div id="design-file-list">${fileList()}</div>+ <p class="hint" id="design-file-status" role="status">${state.fileStatus}</p>`,+ true,+ ),+ designSpec(+ "Skill-pack registration",+ ".pack-register · shared Skills styles · local form demonstration",+ html`<div class="pack-register">+ <input+ type="url"+ aria-label="Example skill repository"+ placeholder="https://github.com/example/skills"+ /><button+ type="button"+ id="design-register"+ @click=${() => update({ packStatus: "Example registered locally. No repository was fetched." })}+ >+ Register</button+ ><button+ type="button"+ class="linkish"+ id="design-advanced"+ @click=${() => update({ advanced: !state.advanced })}+ aria-expanded=${String(state.advanced)}+ aria-controls="design-pack-advanced"+ >+ Advanced+ </button>+ </div>+ <div class=${state.advanced ? "pack-adv" : "pack-adv hidden"} id="design-pack-advanced">+ <div>+ <label for="design-pack-name">Name</label+ ><input id="design-pack-name" type="text" placeholder="Team skills" />+ </div>+ <div>+ <label for="design-pack-ref">Ref</label><input id="design-pack-ref" type="text" placeholder="main" />+ </div>+ <div>+ <label for="design-pack-path">Path</label+ ><input id="design-pack-path" type="text" placeholder="skills/" />+ </div>+ </div>+ <p class="hint" id="design-pack-status" role="status">${state.packStatus}</p>`,+ true,+ ),+ designSpec(+ "Open report section",+ "Authored Metrics / Audit / Egress composition · statline() + shared table controls",+ html`<section class="design-open-section">+ <h3>Activity summary</h3>+ <p class="hint">Keep descriptions beside the section they explain.</p>+ <div id="design-metrics-summary">+ <div class="statline">152 requests · 2 scopes · Last 24 hours</div>+ </div>+ <div class="tablewrap">+ <table>+ <thead>+ <tr>+ <th>Scope</th>+ <th>Requests</th>+ <th>Status</th>+ </tr>+ </thead>+ <tbody>+ <tr>+ <td>Example team</td>+ <td>128</td>+ <td><span class="badge ok">Healthy</span></td>+ </tr>+ <tr>+ <td>Research</td>+ <td>24</td>+ <td><span class="badge muted">Idle</span></td>+ </tr>+ </tbody>+ </table>+ </div>+ </section>`,+ true,+ ),+ ],+ ),+ designSection("Actions", "32px controls with a 6px radius. Primary actions use the dark blue accent.", [+ designSpec(+ "Buttons",+ "button · .primary · .danger",+ html`<button type="button" class="primary">Apply</button><button type="button">Add item</button+ ><button type="button" class="danger">Delete</button><button type="button" disabled>Disabled</button+ ><button type="button" class="primary" disabled>Apply</button>`,+ ),+ designSpec(+ "Quiet actions",+ ".viewlink · .icon-button",+ html`<button type="button" class="viewlink">View history ›</button+ ><button type="button" class="icon-button" aria-label="Remove example">×</button>`,+ ),+ designSpec(+ "Save feedback",+ ".foot · .status · native input events",+ html`<section class="card">+ <div class="head">+ <h2>Example setting</h2>+ <p>Edit the name to try unsaved and saved states.</p>+ </div>+ <div class="body">+ <label for="design-name">Display name</label+ ><input+ id="design-name"+ type="text"+ .value=${state.name}+ @input=${(e: Event) => update({ name: (e.target as HTMLInputElement).value, nameSaved: false })}+ />+ </div>+ <div class="foot">+ <span class="status" id="design-status" role="status">${nameStatus()}</span+ ><button+ class="primary"+ type="button"+ id="design-apply"+ ?disabled=${state.name === state.savedName}+ @click=${() => update({ savedName: state.name, nameSaved: true })}+ >+ Apply+ </button>+ </div>+ </section>`,+ true,+ ),+ ]),+ designSection(+ "Two-way toggle",+ "Choose one of two mutually exclusive options. Tab to focus; use arrow keys to switch.",+ [+ designSpec(+ "Segmented choice",+ "twoWayToggle({ label, options, value, onChange, disabled }) · shared radio group",+ html`<div id="design-two-way-toggle">${toggle}</div>+ <p class="hint" id="design-two-way-status" role="status">${state.toggleStatus}</p>`,+ true,+ ),+ designSpec(+ "Disabled",+ "The same component with disabled: true",+ html`<div id="design-two-way-disabled">${toggleDisabled}</div>`,+ ),+ ],+ ),+ designSection(+ "Search",+ "A transparent background, subtle border, search icon, and clear action. Focus uses the shared dark blue accent.",+ [+ designSpec(+ "Search field",+ "searchField() · shared with Slack and page toolbar searches",+ html`<div id="design-search">${search}</div>+ <p class="hint" id="design-search-status" role="status">${state.searchStatus}</p>`,+ true,+ ),+ designSpec(+ "Populated and disabled",+ "The same component with value and disabled options",+ html`<div id="design-search-filled">${searchFilled}</div>+ <div id="design-search-disabled">${searchDisabled}</div>`,+ true,+ ),+ ],+ ),+ designSection("Fields", "Shared sizing, labels, hints, focus rings, validation, and disabled states.", [+ designSpec(+ "Text fields",+ "input · label · .hint",+ html`<label for="design-text">Client ID</label+ ><input id="design-text" type="text" placeholder="Enter a client ID" aria-describedby="design-text-hint" />+ <p class="hint" id="design-text-hint">A label stays visible when the field has a value.</p>+ <label for="design-number">Limit</label><input id="design-number" type="number" value="10" /><label+ for="design-disabled"+ >Inherited value</label+ ><input id="design-disabled" type="text" disabled value="Organization default" /><label for="design-invalid"+ >Required value</label+ ><input id="design-invalid" type="text" aria-invalid="true" aria-describedby="design-error" />+ <p class="status err" id="design-error">Enter a value to continue.</p>`,+ true,+ ),+ designSpec(+ "Dropdown",+ "select → shared .dd accessible dropdown",+ html`<label for="design-select">Scope</label+ ><select id="design-select">+ <option>Organization</option>+ <option>Team</option>+ <option>Personal</option>+ </select>`,+ true,+ ),+ designSpec(+ "Multiline",+ "textarea · same field border and label",+ html`<label for="design-notes">Instructions</label+ ><textarea id="design-notes" rows="3" placeholder="Write instructions…"></textarea>`,+ true,+ ),+ designSpec(+ "Choices",+ ".choice-stack · .posture-choice",+ html`<div class="choice-stack">+ <label class="posture-choice"+ ><input type="radio" name="design-choice" checked /><span+ ><strong>Automatic</strong><small>Review activity when needed.</small></span+ ></label+ ><label class="posture-choice"+ ><input type="radio" name="design-choice" /><span+ ><strong>Always review</strong><small>Review every request.</small></span+ ></label+ >+ </div>`,+ true,+ ),+ designSpec(+ "Switch & checkbox",+ ".setting-toggle · .setting-switch · input[type=checkbox]",+ html`<label class="setting-toggle"+ ><input type="checkbox" checked /><span class="setting-switch" aria-hidden="true"></span+ ><span>Enable feature</span></label+ ><label><input type="checkbox" /> Include optional details</label>`,+ true,+ ),+ ]),+ designSection(+ "Sections & lists",+ "Open sections separated by rules, with the same headings, descriptions, and row actions.",+ [+ designSpec(+ "Settings section",+ ".card > .head / .body / .foot",+ html`<section class="card">+ <div class="head">+ <h2>Section title</h2>+ <p>Explain what the setting changes.</p>+ </div>+ <div class="body">+ <label for="design-section-field">Setting label</label+ ><input id="design-section-field" type="text" value="Default value" />+ </div>+ <div class="foot">+ <span class="status">No changes</span><button class="primary" type="button" disabled>Apply</button>+ </div>+ </section>`,+ true,+ ),+ designSpec(+ "List row",+ ".credential-row · .credential-title · .credential-actions",+ html`<div class="credential-row">+ <div class="credential-main">+ <div class="credential-title">+ <strong>Example service</strong><span class="credential-slug">example</span>+ </div>+ <p class="hint">Available to the organization</p>+ </div>+ <div class="credential-actions">+ <button type="button">Edit</button><button type="button" class="danger">Delete</button>+ </div>+ </div>`,+ true,+ ),+ designSpec(+ "Model chip",+ ".model-chip · removable item",+ html`${state.chip ? html`<div class="model-chip"><span>Example model</span><button type="button" id="design-remove-chip" aria-label="Remove example model" @click=${() => update({ chip: false })}>×</button></div>` : nothing}<span+ class="hint"+ id="design-chip-status"+ role="status"+ >${state.chip ? "" : "Example model removed"}</span+ >`,+ ),+ designSpec(+ "Badges & feedback",+ ".badge · .status · semantic colors",+ html`<span class="badge muted">Inherited</span><span class="badge ok">Enabled</span+ ><span class="badge warn">Needs review</span><span class="badge err">Failed</span+ ><span class="status ok">Saved</span><span class="status err">Save failed</span>`,+ ),+ designSpec(+ "Empty state",+ ".empty",+ html`<div class="empty">No items yet. Add an item to get started.</div>`,+ true,+ ),+ ],+ ),+ designSection(+ "Dialogs",+ "The same controls in a focused, keyboard-accessible dialog. Escape closes it and returns focus.",+ [+ designSpec(+ "Review dialog",+ "dialog.review-dialog · shared fields and actions",+ html`<button type="button" id="design-dialog-open" @click=${() => dialog()?.showModal()}>+ Open example dialog+ </button>+ <dialog class="review-dialog" id="design-dialog" aria-labelledby="design-dialog-title">+ <div class="review-dialog-head">+ <h2 id="design-dialog-title">Example dialog</h2>+ <p>Try the shared controls without changing any settings.</p>+ </div>+ <div class="review-dialog-body">+ <label for="design-dialog-field">Display name</label+ ><input id="design-dialog-field" type="text" value="Example" />+ </div>+ <div class="review-dialog-foot">+ <button type="button" id="design-dialog-close" @click=${() => dialog()?.close()}>Cancel</button+ ><button type="button" class="primary" id="design-dialog-done" @click=${() => dialog()?.close()}>+ Done+ </button>+ </div>+ </dialog>`,+ ),+ ],+ ),+ designSection(+ "Tables",+ "13px cells, quiet headers, consistent padding, and scrolling inside the table on small screens.",+ [+ designSpec(+ "Data table",+ ".tablewrap > table · th · td",+ html`<div class="tablewrap">+ <table>+ <thead>+ <tr>+ <th>Name</th>+ <th>Access</th>+ <th>Status</th>+ <th>Actions</th>+ </tr>+ </thead>+ <tbody>+ <tr>+ <td>Alex Example</td>+ <td>Organization</td>+ <td><span class="badge ok">Active</span></td>+ <td><button type="button">Edit</button></td>+ </tr>+ <tr>+ <td>Sam Example</td>+ <td>Team</td>+ <td><span class="badge muted">Invited</span></td>+ <td><button type="button" disabled>Edit</button></td>+ </tr>+ </tbody>+ </table>+ </div>`,+ true,+ ),+ ],+ ),+ ];+ draw(+ html`${sections[0]}+ <nav class="design-contents" aria-label="Design system sections">+ ${titles.map((title) => html`<a href=${"#" + sectionId(title)}>${title}</a>`)}+ </nav>+ ${sections.slice(1)}`,+ );+ }+ paint();+ context.initCustomDropdowns(root);+}diff --git a/plugins/admin/ui/governance-state.ts b/plugins/admin/ui/governance-state.tsnew file mode 100644index 000000000..033f7831b--- /dev/null+++ b/plugins/admin/ui/governance-state.ts@@ -0,0 +1,235 @@+import { SettingState, settingRegistry } from "./setting-state.ts";+export type Rule = { id: number; pattern: string; decision: string; reason: string };+export type Bot = { id: number; name: string; mode: string; hours: string };+let nextId = 0;+const fieldNames: Record<string, Record<string, string>> = {+ "security-posture": { "security-posture": "posture" },+ "sharing-posture": { "sharing-posture": "posture" },+ "org-ambient": { "governance-org-ambient": "on" },+ "auto-flagger": {+ "auto-flagger-harness": "harnessId",+ "auto-flagger-model": "modelId",+ "auto-flagger-rubric": "rubric",+ },+ "approval-grant-modes": { "approval-grant-session": "session", "approval-grant-always": "always" },+ "ambient-policy": { "ambient-enabled": "ambientEnabled", "ambient-orders": "orders" },+ egress: { egress: "allowedHosts", "egress-deny": "deniedHosts" },+ "command-policy": {},+};+export class GovernanceState extends SettingState {+ rules: Rule[] = [];+ bots: Bot[] = [];+ expanded = false;+ disabled = false;+ allowEditor = false;+ denyEditor = false;+ scope = "";+ context: Record<string, any> = {};+ get dirty() {+ try {+ this.collect();+ } catch {+ return true;+ }+ return JSON.stringify(this.collect(false)) !== this.baseline;+ }+ value(id: string) {+ return this.draft[fieldNames[this.key]?.[id]] ?? "";+ }+ change(id: string, value: unknown) {+ this.draft[fieldNames[this.key][id]] = value;+ if (id === "auto-flagger-harness") {+ const options = this.models;+ if (!options.some((entry: any) => entry.id === this.draft.modelId)) this.draft.modelId = options[0]?.id || "";+ }+ this.changed();+ }+ get models(): Array<{ id: string; name: string }> {+ const options = [...(this.context.modelsByHarness?.[this.draft.harnessId] || [])];+ const configured = this.context.autoFlagger || this.context.autoFlaggerDefault;+ if (+ configured &&+ configured.harnessId === this.draft.harnessId &&+ !options.some((entry) => entry.id === configured.modelId)+ ) {+ options.push({ id: configured.modelId, name: configured.modelId + " (configured; unavailable)" });+ }+ return options;+ }+ load(body: Record<string, any>, context = this.context, scope = this.scope) {+ this.context = context;+ this.scope = scope;+ this.draft = structuredClone(body);+ this.rules = (body.rules || []).map((r: any) => ({+ id: ++nextId,+ pattern: r.pattern || "",+ decision: r.decision || "deny",+ reason: r.reason || "",+ }));+ this.bots = Object.entries(body.bots || {}).map(([name, b]: [string, any]) => ({+ id: ++nextId,+ name,+ mode: b.mode || "ignore",+ hours: b.rollupHours == null ? "" : String(b.rollupHours),+ }));+ if (this.key === "egress") {+ this.draft.allowedHosts = (body.allowedHosts || []).join("\n");+ this.draft.deniedHosts = (body.deniedHosts || []).join("\n");+ this.allowEditor = !!this.draft.allowedHosts;+ this.denyEditor = !!this.draft.deniedHosts;+ }+ this.expanded = false;+ this.baseline = JSON.stringify(this.collect(false));+ this.message = "";+ this.tone = "";+ this.saving = false;+ this.render();+ }+ collect(validate = true): Record<string, any> {+ if (this.key === "command-policy") {+ const rules = this.rules+ .filter((r) => r.pattern.trim())+ .map((r) => {+ if (validate) {+ const error = patternError(r.pattern);+ if (error) throw new Error("Fix the highlighted regular expression before saving: " + error);+ }+ return {+ pattern: r.pattern.trim(),+ decision: r.decision,+ ...(r.reason.trim() ? { reason: r.reason.trim() } : {}),+ };+ });+ return { mode: this.draft.mode || "denylist", rules };+ }+ if (this.key === "ambient-policy") {+ const bots: Record<string, any> = {};+ const seen = new Set();+ for (const bot of this.bots) {+ const name = bot.name.trim();+ if (validate && !name) throw new Error("Every bot ledger row needs a bot name.");+ if (validate && seen.has(name.toLowerCase()))+ throw new Error(`Duplicate bot "${name}". The ledger matches names case-insensitively.`);+ seen.add(name.toLowerCase());+ const entry: Record<string, any> = { mode: bot.mode };+ if (bot.mode === "rollup" && bot.hours.trim()) {+ const hours = Number(bot.hours);+ if (validate && (!Number.isFinite(hours) || hours <= 0))+ throw new Error(`Bot "${name}": rollup hours must be a positive number.`);+ entry.rollupHours = hours;+ }+ bots[name] = entry;+ }+ return {+ orders: this.draft.orders || "",+ bots,+ ambientEnabled: this.draft.ambientEnabled ?? null,+ baseUpdatedAt: this.draft.baseUpdatedAt || 0,+ };+ }+ if (this.key === "egress") {+ const parse = (raw: string, label: string) =>+ [+ ...new Set(+ (raw || "")+ .split("\n")+ .map((s) => s.trim().toLowerCase())+ .filter(Boolean),+ ),+ ].map((host) => {+ if (+ validate &&+ (/\s|:\/\/|[/@?#]/.test(host) ||+ host.startsWith(".") ||+ host.endsWith(".") ||+ !/^[a-z0-9:[\]._-]+$/.test(host))+ )+ throw new Error(label + ' contains invalid host "' + host + '". Use hostnames or IPs, not URLs.');+ return host;+ });+ const allowedHosts = parse(this.draft.allowedHosts, "Allowlist");+ const deniedHosts = parse(this.draft.deniedHosts, "Denylist");+ const overlap = allowedHosts.find((host) => deniedHosts.includes(host));+ if (validate && overlap)+ throw new Error(`Host "${overlap}" appears in both lists. Remove it from one list before saving.`);+ return { allowedHosts, deniedHosts };+ }+ return structuredClone(this.draft);+ }+ get warnings(): string[] {+ if (this.key === "egress") {+ try {+ this.collect();+ return [];+ } catch (error) {+ return [(error as Error).message];+ }+ }+ const warnings: string[] = [];+ const patterns = this.rules.map((r) => r.pattern.trim());+ patterns.forEach((pattern, i) => {+ if (!pattern) return;+ const duplicate = patterns.slice(0, i).indexOf(pattern);+ if (duplicate >= 0)+ warnings.push(`Rule ${i + 1} is unreachable because rule ${duplicate + 1} has the same pattern.`);+ const catchAll = patterns.slice(0, i).findIndex((p) => [".*", "^.*$", "[\\s\\S]*", "^[\\s\\S]*$"].includes(p));+ if (catchAll >= 0) warnings.push(`Rule ${i + 1} is shadowed by catch-all rule ${catchAll + 1}.`);+ });+ return warnings;+ }+}+export function patternError(pattern: string): string {+ try {+ new RegExp(pattern);+ return "";+ } catch (error) {+ return (error as Error).message;+ }+}+export const states = new Map(Object.keys(fieldNames).map((key) => [key, new GovernanceState(key)]));+export const { owns, collect, capture, commit, status } = settingRegistry(states);+export function loadResource(key: string, body: Record<string, any>) {+ states.get(key)!.load(body);+}+export function load(data: Record<string, any>, scope: string, only?: string) {+ const resources: Record<string, [boolean, Record<string, any>]> = {+ "security-posture": ["securityPosture" in data, { posture: data.securityPosture || "auto" }],+ "sharing-posture": ["sharingPosture" in data, { posture: data.sharingPosture || "isolated" }],+ "auto-flagger": [+ scope.startsWith("org:") && "autoFlagger" in data,+ data.autoFlagger || data.autoFlaggerDefault || {},+ ],+ "approval-grant-modes": ["approvalGrantModes" in data, data.approvalGrantModes || { session: true, always: true }],+ "command-policy": [true, data.commandPolicy || { mode: "denylist", rules: [] }],+ "org-ambient": [scope.startsWith("org:") && "orgAmbient" in data, { on: data.orgAmbient !== false }],+ "ambient-policy": [+ "ambientPolicy" in data,+ { ...data.ambientPolicy, baseUpdatedAt: data.ambientPolicy?.updatedAt || 0 },+ ],+ egress: [true, data.egress || { allowedHosts: [], deniedHosts: [] }],+ };+ for (const [key, [available, body]] of Object.entries(resources)) {+ if (only && key !== only) continue;+ const state = states.get(key)!;+ state.available = available;+ state.disabled = key === "egress" && !data.egressEnforcement?.active;+ state.load(body, data, scope);+ }+}++export function statusKey(id: string): string | undefined {+ const key = id.replace(/^st-/, "");+ if (key === "policy") return "command-policy";+ if (key === "governance-org-ambient") return "org-ambient";+ return owns(key) ? key : undefined;+}++export function updateCatalog(data: Record<string, any>) {+ const state = states.get("auto-flagger")!;+ state.context = {+ ...state.context,+ modelsByHarness: data.modelsByHarness || state.context.modelsByHarness,+ harnessOptions: data.harnessOptions || state.context.harnessOptions,+ };+ state.render();+}diff --git a/plugins/admin/ui/governance.ts b/plugins/admin/ui/governance.tsnew file mode 100644index 000000000..4231267f2--- /dev/null+++ b/plugins/admin/ui/governance.ts@@ -0,0 +1,636 @@+import { choiceGroup, saveButton, settingStatus, saveFooter } from "./setting-controls.ts";+import { html, render, type TemplateResult } from "lit";+import { classMap } from "lit/directives/class-map.js";+import { repeat } from "lit/directives/repeat.js";+import { states, patternError, type GovernanceState } from "./governance-state.ts";+export {+ owns,+ collect,+ capture,+ commit,+ status,+ statusKey,+ load,+ loadResource,+ updateCatalog,+ states,+} from "./governance-state.ts";++const cards: Record<string, (s: GovernanceState) => TemplateResult> = {+ "card-security-posture": (s) =>+ html`<section+ class=${classMap({ card: true, "sv-governance": true, "setting-row": true, hidden: !s.available, dirty: s.dirty, "egress-disabled": s.disabled })}+ id="card-security-posture"+ >+ <div class="head">+ <h2>Security posture</h2>+ <p>Choose how the agent screens external content and when it requires your approval.</p>+ </div>+ <div class="body">+ <select+ id="security-posture"+ data-choice-state+ hidden+ .value=${s.value("security-posture")}+ @change=${(event: Event) => changeField(s, "security-posture", event)}+ >+ <option value="dangerous">Dangerous — no content scans; nothing pauses between tool calls</option>+ <option value="auto">Auto — use the deployment’s configured screener</option>+ <option value="strict">Strict — approve tool actions</option>+ </select>+ ${choiceGroup(+ {+ name: "security-posture-choice",+ value: s.draft.posture,+ choiceFor: "security-posture",+ onChange: (event: Event) => changeField(s, "security-posture", event),+ },+ [+ [+ "auto",+ "Auto",+ "Default. Blocks private-network access. Screens external content when the deployment configures a screener; model screening is off by default.",+ ],+ ["dangerous", "Dangerous", "No content screening."],+ ["strict", "Strict", "Every tool action requires human approval."],+ ],+ )}+ </div>+ ${saveFooter(s, "Apply", s.disabled)}+ </section>`,+ "card-auto-flagger": (s) =>+ html`<section+ class=${classMap({ card: true, "sv-governance": true, hidden: !s.available, dirty: s.dirty, "egress-disabled": s.disabled })}+ id="card-auto-flagger"+ >+ <div class="head">+ <h2>Auto flagger</h2>+ <p>+ Model and prompt used when the deployment explicitly enables model screening in Auto mode. These settings do+ not enable screening. The security boundary and required verdict format remain fixed.+ </p>+ </div>+ <div class="body">+ <div class="screening-details">+ <div class="governance-field-grid">+ <div>+ <label for="auto-flagger-harness">Harness</label>+ <select+ id="auto-flagger-harness"+ .value=${s.value("auto-flagger-harness")}+ @change=${(event: Event) => changeField(s, "auto-flagger-harness", event)}+ >+ ${harnessOptions(s).map((id) => html`<option value=${id} ?selected=${id === s.draft.harnessId}>${({ pi: "Pi", opencode: "OpenCode", codex: "Codex", claude: "Claude Code" } as Record<string, string>)[id] || id}</option>`)}+ </select>+ </div>+ <div>+ <label for="auto-flagger-model">Model</label>+ <select+ id="auto-flagger-model"+ .value=${s.value("auto-flagger-model")}+ @change=${(event: Event) => changeField(s, "auto-flagger-model", event)}+ >+ ${s.models.map((entry) => html`<option value=${entry.id} ?selected=${entry.id === s.draft.modelId}>${entry.name} (${entry.id})</option>`)}+ </select>+ </div>+ </div>+ <div class="governance-prompt">+ <label for="auto-flagger-rubric">Quarantine prompt (classification rubric)</label>+ <textarea+ id="auto-flagger-rubric"+ rows="6"+ maxlength="20000"+ .value=${s.value("auto-flagger-rubric")}+ @input=${(event: Event) => changeField(s, "auto-flagger-rubric", event)}+ ></textarea>+ </div>+ <div class="screening-test-options">+ <h3>Test Auto flagger</h3>+ <p class="screening-test-help">+ Try the model and prompt above on recent screenings without applying changes.+ </p>+ <div class="screening-test-fields">+ <label for="auto-flagger-window">Recent screenings to test</label>+ <div class="screening-count">+ <input+ id="auto-flagger-window"+ type="number"+ inputmode="numeric"+ min="1"+ max="500"+ step="1"+ value="100"+ aria-describedby="auto-flagger-window-range"+ />+ <span id="auto-flagger-window-range">1–500</span>+ </div>+ <label+ class="screening-compare"+ title="Also replay the configuration in effect today, so the flag rates are comparable"+ >+ <input type="checkbox" id="auto-flagger-compare" />Compare with the currently applied configuration+ </label>+ <button id="auto-flagger-test" type="button">Run test</button>+ </div>+ </div>+ </div>+ </div>+ <div class="foot">+ <button id="auto-flagger-reset" type="button">Restore default</button>+ ${saveButton(s, "Apply", s.disabled)} ${settingStatus(s)}+ </div>+ <div class="foot" id="auto-flagger-test-result" hidden>+ <span class="status" id="st-auto-flagger-test"></span>+ </div>+ </section>`,+ "card-approval-grant-modes": (s) =>+ html`<section+ class=${classMap({ card: true, "sv-governance": true, "setting-row": true, hidden: !s.available, dirty: s.dirty, "egress-disabled": s.disabled })}+ id="card-approval-grant-modes"+ >+ <div class="head">+ <h2>Approval grant options</h2>+ <p>+ Which standing options an approval card offers besides "Allow once". Composes tighten-only with the org value;+ disabling a mode also suspends existing grants of that mode until it is re-enabled. Predeclared command+ approvals and strict-posture tool approvals both honor this.+ </p>+ </div>+ <div class="body">+ <label+ ><input+ type="checkbox"+ id="approval-grant-session"+ .checked=${s.value("approval-grant-session")}+ @change=${(event: Event) => changeField(s, "approval-grant-session", event)}+ />+ Offer "Allow session" (grant lasts for the conversation)</label+ >+ <label+ ><input+ type="checkbox"+ id="approval-grant-always"+ .checked=${s.value("approval-grant-always")}+ @change=${(event: Event) => changeField(s, "approval-grant-always", event)}+ />+ Offer "Allow always" (standing grant across turns)</label+ >+ </div>+ ${saveFooter(s, "Apply", s.disabled)}+ </section>`,+ "card-command-policy": (s) =>+ html`<section+ class=${classMap({ card: true, "sv-governance": true, hidden: !s.available, dirty: s.dirty, "egress-disabled": s.disabled })}+ id="card-command-policy"+ >+ <div class="head">+ <h2>Command policy</h2>+ </div>+ <div class="body">+ <div class="policy-rules" id="rules">+ ${repeat(+ s.rules,+ (r) => r.id,+ (r, index) => ruleTemplate(s, r, index),+ )}+ </div>+ <p class=${classMap({ hint: true, "rules-empty": true, hidden: s.rules.length > 0 })} id="rules-empty">+ No command rules yet.+ </p>+ <div class="policy-actions">+ <button id="add-rule" type="button" @click=${() => addRule(s)}>+ Add rule</button>+ <button+ id="policy-more"+ type="button"+ class=${classMap({ hidden: s.expanded || s.rules.length <= 3 })}+ @click=${() => {+ s.expanded = true;+ s.render();+ }}+ >+ Show ${s.rules.length - 3} more ${s.rules.length === 4 ? "rule" : "rules"}+ </button>+ <button id="policy-test-open" type="button">Test a command…</button>+ </div>+ <div class="policy-warnings" id="policy-warnings" aria-live="polite">+ ${s.warnings.map((warning) => html`<div>${warning}</div>`)}+ </div>+ </div>+ <div class="foot">${saveButton(s, "Save", s.disabled)}${settingStatus(s, "st-policy")}</div>+ </section>`,+ "card-ambient-policy": (s) =>+ html`<section+ class=${classMap({ card: true, "sv-governance": true, hidden: !s.available, dirty: s.dirty, "egress-disabled": s.disabled })}+ id="card-ambient-policy"+ >+ <div class="head">+ <h2>Ambient reply policy</h2>+ <p>+ What the agent proactively acts on in this channel. The standing order is plain prose the ambient judge weighs+ each batch of new messages against. Empty means it stays silent unless addressed. The bot ledger says how each+ automated poster is treated: <b>ignore</b> never wakes the judge, <b>rollup</b> batches its posts (judged at+ most once per the given hours), <b>action</b> marks its posts as triggers to act on, <b>user</b> reads it like+ a person.+ </p>+ </div>+ <div class="body">+ <label for="ambient-enabled">Ambient behavior</label>+ <p class="hint" style="margin: 2px 0 6px">+ When off, the agent never wakes on overheard messages in this channel; it only responds to direct @mentions.+ Default: on for channels with 8 or fewer members, off for larger ones.+ </p>+ <select+ id="ambient-enabled"+ style="margin-bottom: 14px"+ .value=${s.draft.ambientEnabled == null ? "default" : String(s.draft.ambientEnabled ? "on" : "off")}+ @change=${(event: Event) => changeField(s, "ambient-enabled", event)}+ >+ <option value="default">Default (by channel size)</option>+ <option value="on">On</option>+ <option value="off">Off</option>+ </select>+ <label for="ambient-orders">Standing order</label>+ <textarea+ id="ambient-orders"+ placeholder="(none, the agent stays silent here unless addressed)"+ .value=${s.value("ambient-orders")}+ @input=${(event: Event) => changeField(s, "ambient-orders", event)}+ ></textarea>+ <div class="tablewrap" style="margin-top: 14px">+ <table class="rules">+ <thead>+ <tr>+ <th style="width: 34%">Bot (author name)</th>+ <th style="width: 30%">Handling</th>+ <th>Rollup hours</th>+ <th></th>+ </tr>+ </thead>+ <tbody id="ambient-bots">+ ${repeat(+ s.bots,+ (b) => b.id,+ (b) => botTemplate(s, b),+ )}+ </tbody>+ </table>+ </div>+ <p class=${classMap({ hint: true, "rules-empty": true, hidden: s.bots.length > 0 })} id="ambient-bots-empty">+ No bots in the ledger yet.+ </p>+ <button id="add-bot" type="button" @click=${() => addBot(s)} style="margin-top: 10px">+ Add bot</button>+ </div>+ <div class="foot">+ <button type="button" class="viewlink" data-viewlink="judgments">View judgment log ›</button+ >${saveButton(s, "Save", s.disabled)}${settingStatus(s)}+ </div>+ </section>`,+ "card-sharing-posture": (s) =>+ html`<section+ class=${classMap({ card: true, "sv-governance": true, "setting-row": true, hidden: !s.available, dirty: s.dirty, "egress-disabled": s.disabled })}+ id="card-sharing-posture"+ >+ <div class="head">+ <h2>Sharing posture</h2>+ <p>The organization is a ceiling. Personal and room scopes can opt out, and Isolated always wins.</p>+ </div>+ <div class="body">+ <p id="sharing-posture-effective">${sharingLabel(s)}</p>+ <select+ id="sharing-posture"+ data-choice-state+ hidden+ .value=${s.value("sharing-posture")}+ @change=${(event: Event) => changeField(s, "sharing-posture", event)}+ >+ <option value="isolated">Isolated</option>+ <option value="open">Open</option>+ </select>+ ${choiceGroup(+ {+ name: "sharing-posture-choice",+ value: s.draft.posture,+ choiceFor: "sharing-posture",+ onChange: (event: Event) => changeField(s, "sharing-posture", event),+ },+ [+ ["isolated", "Isolated", "Resources stay in their own scope unless explicitly shared."],+ [+ "open",+ "Open",+ "QM can use your saved memories, files, and skills across conversations when you ask it for help. In a group conversation, this could risk revealing private information to others.",+ ],+ ],+ )}+ </div>+ <div class="foot">+ ${saveButton(s, "Apply", s.disabled)}+ <button+ type="button"+ id="sharing-posture-inherit"+ ?hidden=${s.scope.startsWith("org:") || s.context.sharingPostureOverride == null}+ >+ Follow organization+ </button>+ ${settingStatus(s)}+ </div>+ </section>`,+ "card-egress": (s) =>+ html`<section+ class=${classMap({ card: true, "sv-governance": true, hidden: !s.available, dirty: s.dirty, "egress-disabled": s.disabled })}+ id="card-egress"+ >+ <div class="head">+ <h2>Egress policy</h2>+ </div>+ <div class="body">+ <div+ class=${classMap({ "governance-capability": true, "admin-notice": true, "admin-notice--warning": true, hidden: !s.disabled })}+ id="egress-capability"+ role="status"+ >+ <div>+ <strong+ >${s.context.egressEnforcement?.reason === "control_plane_unconfigured" ? "Enforcement is not activated" : "Agent computer egress policy unavailable"}</strong+ ><span>${egressExplanation(s)}</span>+ </div>+ </div>+ <div class="egress-empty-state">+ <span class=${classMap({ hint: true, hidden: s.allowEditor || s.denyEditor })} id="egress-empty"+ >No egress rules.</span+ >+ <div class="egress-actions">+ <button+ type="button"+ id="egress-add-deny"+ ?disabled=${s.disabled}+ class=${classMap({ hidden: s.denyEditor })}+ @click=${() => {+ s.denyEditor = true;+ s.render();+ }}+ >+ + Denylist+ </button>+ <button+ type="button"+ id="egress-add-allow"+ ?disabled=${s.disabled}+ class=${classMap({ hidden: s.allowEditor })}+ @click=${() => {+ s.allowEditor = true;+ s.render();+ }}+ >+ + Allowlist+ </button>+ </div>+ </div>+ <div class=${classMap({ "egress-editor": true, hidden: !s.denyEditor })} id="egress-deny-editor">+ <label for="egress-deny">Denylist: hosts the agent may never reach</label>+ <textarea+ id="egress-deny"+ placeholder="ads.example.com pastebin.com"+ .value=${s.value("egress-deny")}+ @input=${(event: Event) => changeField(s, "egress-deny", event)}+ ?disabled=${s.disabled}+ ></textarea>+ </div>+ <div class=${classMap({ "egress-editor": true, hidden: !s.allowEditor })} id="egress-allow-editor">+ <label for="egress">Allowlist: when present, only these outbound hosts may be reached</label>+ <textarea+ id="egress"+ placeholder="example.com api.internal"+ .value=${s.value("egress")}+ @input=${(event: Event) => changeField(s, "egress", event)}+ ?disabled=${s.disabled}+ ></textarea>+ </div>+ <div class="policy-warnings" id="egress-warnings" aria-live="polite">+ ${s.warnings.map((warning) => html`<div>${warning}</div>`)}+ </div>+ </div>+ <div class="foot">+ <button type="button" class="viewlink" data-viewlink="egress">View logs ›</button+ >${saveButton(s, "Save policy", s.disabled)}${settingStatus(s)}+ </div>+ </section>`,+ "card-governance-org-ambient": (s) =>+ html`<section+ class=${classMap({ card: true, "sv-governance": true, hidden: !s.available, dirty: s.dirty, "egress-disabled": s.disabled })}+ id="card-governance-org-ambient"+ >+ <div class="head">+ <h2>Ambient reply policy</h2>+ <p>@-mentions are always answered. Each ambient decision is recorded in the judgments log.</p>+ <button type="button" class="viewlink" data-viewlink="judgments">View judgment log ›</button>+ </div>+ <div class="body">+ <select+ id="governance-org-ambient"+ data-choice-state+ hidden+ .value=${s.draft.on ? "on" : "off"}+ @change=${(event: Event) => changeField(s, "governance-org-ambient", event)}+ >+ <option value="on">Agent judges all messages and replies when useful</option>+ <option value="off">Agent does not read messages or reply unless @-mentioned</option>+ </select>+ ${choiceGroup(+ {+ name: "ambient-reply-choice",+ value: ({ true: "on", false: "off" } as Record<string, string>)[String(s.draft.on)] || "",+ choiceFor: "governance-org-ambient",+ onChange: (event: Event) => changeField(s, "governance-org-ambient", event),+ },+ [+ ["on", "Reply when useful", "Agent judges all messages and replies when useful"],+ ["off", "Only when mentioned", "Agent does not read messages or reply unless @-mentioned"],+ ],+ )}+ </div>+ <div class="foot">+ <button+ type="button"+ class=${classMap({ primary: true, dirty: s.dirty })}+ id="governance-org-ambient-save"+ data-save="org-ambient"+ ?disabled=${!s.dirty || s.saving}+ >+ Apply</button+ >${settingStatus(s, "st-governance-org-ambient")}+ </div>+ </section>`,+};++export function createCard(id: string): HTMLElement {+ const template = cards[id];+ if (!template) throw new Error(`Unknown governance card: ${id}`);+ const fragment = document.createDocumentFragment();+ const key = id === "card-governance-org-ambient" ? "org-ambient" : id.slice(5);+ const state = states.get(key)!;+ state.render = () => render(template(state), fragment);+ state.render();+ return fragment.firstElementChild as HTMLElement;+}++export function mountCards(): void {+ document.querySelectorAll<HTMLTemplateElement>("template[data-governance-card]").forEach((placeholder) => {+ placeholder.replaceWith(createCard(placeholder.dataset.governanceCard!));+ });+}++function changeField(s: GovernanceState, id: string, event: Event) {+ const input = event.currentTarget as HTMLInputElement;+ let value: unknown = input.type === "checkbox" ? input.checked : input.value;+ if (id === "governance-org-ambient") value = value === "on";+ if (id === "ambient-enabled") value = value === "default" ? null : value === "on";+ s.change(id, value);+}+function harnessOptions(s: GovernanceState): string[] {+ return [...new Set<string>([...(s.context.harnessOptions || []), s.draft.harnessId].filter(Boolean))];+}+function sharingLabel(s: GovernanceState): string {+ const title = (value: string) => value[0].toUpperCase() + value.slice(1);+ const inherited = s.scope.startsWith("org:") ? "Default" : "Following organization";+ return (+ (s.context.sharingPostureOverride == null ? inherited : "Configured: " + title(s.context.sharingPostureOverride)) ++ " · Effective: " ++ title(s.context.sharingPosture || "isolated")+ );+}+let rowId = 0;+function addRule(s: GovernanceState) {+ s.rules.unshift({ id: --rowId, pattern: "", decision: "deny", reason: "" });+ s.expanded = true;+ s.changed();+ document.querySelector<HTMLInputElement>("#rules .policy-pattern")?.focus();+}+function addBot(s: GovernanceState) {+ s.bots.push({ id: --rowId, name: "", mode: "ignore", hours: "" });+ s.changed();+ document.querySelector<HTMLInputElement>("#ambient-bots tr:last-child input")?.focus();+}+function ruleTemplate(s: GovernanceState, r: GovernanceState["rules"][number], index: number) {+ const change = (key: "pattern" | "decision" | "reason", event: Event) => {+ const input = event.currentTarget as HTMLInputElement;+ r[key] = input.value;+ if (key === "pattern") input.setCustomValidity(patternError(r.pattern));+ s.changed();+ };+ return html`<div class=${classMap({ "policy-rule": true, hidden: !s.expanded && index >= 3 })}>+ <select class=${"policy-effect effect-control effect-" + r.decision} @change=${(e: Event) => change("decision", e)}>+ ${[+ ["allow", "Allow"],+ ["deny", "Deny"],+ ["require_approval", "Require approval"],+ ].map(([value, label]) => html`<option value=${value} ?selected=${value === r.decision}>${label}</option>`)}+ </select>+ <input+ class="policy-pattern"+ type="text"+ .value=${r.pattern}+ placeholder="regex"+ spellcheck="false"+ aria-label="Command pattern"+ aria-invalid=${String(!!patternError(r.pattern))}+ @input=${(e: Event) => change("pattern", e)}+ />+ <input+ class="policy-reason"+ type="text"+ .value=${r.reason}+ placeholder="Reason (optional)"+ @input=${(e: Event) => change("reason", e)}+ />+ <button+ type="button"+ class="rowbtn danger"+ title="Remove this command policy rule"+ aria-label="Remove command policy rule"+ @click=${() => {+ s.rules = s.rules.filter((rule) => rule !== r);+ s.changed();+ }}+ >+ <svg+ width="14"+ height="14"+ viewBox="0 0 16 16"+ fill="none"+ stroke="currentColor"+ stroke-width="1.5"+ stroke-linecap="round"+ aria-hidden="true"+ >+ <path d="m4 4 8 8M12 4l-8 8" />+ </svg>+ </button>+ </div>`;+}+function botTemplate(s: GovernanceState, b: GovernanceState["bots"][number]) {+ const change = (key: "name" | "mode" | "hours", e: Event) => {+ b[key] = (e.currentTarget as HTMLInputElement).value;+ s.changed();+ };+ return html`<tr>+ <td>+ <input+ type="text"+ .value=${b.name}+ placeholder="e.g. GitHub"+ spellcheck="false"+ @input=${(e: Event) => change("name", e)}+ />+ </td>+ <td>+ <select @change=${(e: Event) => change("mode", e)}>+ ${[+ ["ignore", "ignore (never wakes the judge)"],+ ["rollup", "rollup (batch, judge periodically)"],+ ["action", "action (posts are triggers)"],+ ["user", "user (read like a person)"],+ ].map(([value, label]) => html`<option value=${value} ?selected=${b.mode === value}>${label}</option>`)}+ </select>+ </td>+ <td>+ <input+ type="number"+ min="1"+ step="1"+ placeholder="24"+ .value=${b.hours}+ ?disabled=${b.mode !== "rollup"}+ @input=${(e: Event) => change("hours", e)}+ />+ </td>+ <td class="rule-action">+ <button+ type="button"+ class="rowbtn danger"+ title="Remove this bot from the ledger"+ aria-label="Remove bot ledger entry"+ @click=${() => {+ s.bots = s.bots.filter((bot) => bot !== b);+ s.changed();+ }}+ >+ Remove+ </button>+ </td>+ </tr>`;+}++function egressExplanation(s: GovernanceState) {+ const enforcement = s.context.egressEnforcement || { backend: "unknown" };+ if (enforcement.reason === "control_plane_unconfigured")+ return "Egress enforcement has not been activated for agent computers.";+ const backend = String(enforcement.backend).replace(/(^|[-_ ])\w/g, (value) =>+ value.replace(/[-_]/, " ").toUpperCase(),+ );+ return (+ "Agent computers use " ++ backend ++ ", which cannot enforce host restrictions on all outbound traffic. A configured egress proxy still applies policy to traffic sent through it."+ );+}diff --git a/plugins/admin/ui/history.ts b/plugins/admin/ui/history.tsnew file mode 100644index 000000000..1cf608522--- /dev/null+++ b/plugins/admin/ui/history.ts@@ -0,0 +1,231 @@+import { html, nothing } from "lit";+import { bareCard, card, denseList, pager, renderer, node } from "./shared.ts";++export function history(root: HTMLElement, d: any, s: Record<string, any>) {+ const paint = renderer(root);+ const sessions = (d.sessions || []).filter((row: any) => s.historyKindMatches(row, s.historyKind));+ const counts = d.totalByCategory || {};+ const types = d.totalByType || d.byType || {};+ const cronCount = types.cron ?? types.cron_wake ?? types.cron_monologue ?? 0;+ const count = (kind: string) => {+ if (kind === "conversation") return counts.conversation ?? 0;+ if (kind === "cron") return d.distinctCrons ?? cronCount;+ if (kind === "background") return Math.max(0, (counts.background ?? 0) - cronCount);+ return d.total ?? sessions.length;+ };+ const cron = s.historyKind === "cron" ? s.cron : null;+ const total = (cron ? d.total : count(s.historyKind)) || sessions.length;+ const limit = d.limit || s.pageSize;+ const offset = d.offset || 0;+ s.correctPage(Math.floor(offset / limit) + 1, cron);+ const route = (extra: any) => ({+ view: "history",+ scope: s.scope,+ session: null,+ page: 1,+ historyKind: s.historyKind,+ ...extra,+ });+ const mode = s.historyModeLabel(s.historyKind);+ const tabs = [+ "conversation",+ "cron",+ ...(count("background") > 0 || s.historyKind === "background" ? ["background"] : []),+ ].map((kind) => ({+ label: s.kindLabels[kind],+ count: count(kind) || 0,+ active: s.historyKind === kind,+ onClick: () => s.go(route({ historyKind: kind })),+ }));+ s.pageShell(+ cron+ ? {+ back: { label: "← Crons", onClick: () => s.go(route({})) },+ title: s.cronName(d.cron?.cron || sessions[0]?.origin?.cron, true),+ context: s.scopeKind(s.scope) !== "org" ? s.shortName(s.scope) : "",+ count: s.plural(total, "fire"),+ }+ : {+ back:+ s.scopeKind(s.scope) !== "org"+ ? { label: "← Sessions", onClick: () => s.go(route({ scope: s.orgScope })) }+ : undefined,+ title: s.scopeKind(s.scope) !== "org" ? s.shortName(s.scope) : s.title,+ tabs,+ },+ );+ const environment = (s.environments || []).find((e: any) => e.id === s.scope);+ const attached = environment?.attachedScopes || [];+ let errors: any[] = [];+ let errorCount = 0;+ let errorsOpen = false;+ const draw = () =>+ paint(+ html`${environment && !cron ? card("Attached scopes", s.plural(attached.length, "scope") + " share this environment's computer and working memory.", html`<div class="history-empty-scopes">${attached.length ? attached.map((id: string) => html`<button type="button" class="history-empty-scope" title=${id} @click=${() => s.selectScope(id)}>${s.shortName(id)}</button>`) : html`<p class="empty">No scopes attached.</p>`}</div>`) : nothing}${+ s.historyKind === "cron" && !cron+ ? bareCard(+ denseList(+ d.crons || [],+ (c: any) => ({+ name: s.cronName(c.origin?.cron, true),+ preview: html`<span+ >${s.plural(c.sessions || 0, "fire") + (typeof c.deliveredRuns === "number" ? " · " + Number(c.deliveredRuns).toLocaleString() + " delivered" : "") + " · first fired " + s.fmtHistoryCreated(c.createdAt, c.lastActivity)}</span+ >`,+ time: c.lastActivity ? s.relTime(c.lastActivity) : "—",+ cls: typeof c.deliveredRuns === "number" && !c.deliveredRuns ? "history-silent" : "",+ href: s.stateToUrl(route({ cron: c.cronId })),+ }),+ (c) => s.go(route({ cron: c.cronId })),+ "No crons in this scope.",+ ),+ )+ : html`${bareCard(+ denseList(+ sessions,+ (row: any) => {+ const origin = row.origin?.kind === "cron" ? row.origin.cron : null;+ const background = row.category === "background";+ let name = row.firstMessage || row.lastMessage || "(no messages yet)";+ let preview = "";+ if (background && !cron) {+ const kind = row.kind || row.type;+ let typeLabel = s.titleCase(String(kind).replaceAll("_", " "));+ if (kind === "dm") typeLabel = "DM";+ if (["cron_monologue", "cron_wake", "cron"].includes(kind)) typeLabel = "Cron";+ name = origin ? s.cronName(origin, true) : row.origin?.label || typeLabel;+ preview = row.result || row.lastMessage || row.firstMessage || "";+ } else if (background && row.result) {+ name = row.result;+ if (row.lastMessage && row.lastMessage !== row.result) preview = row.lastMessage;+ } else if (row.lastMessage && row.lastMessage !== name) preview = row.lastMessage;+ return {+ name,+ preview: html`<span+ >${background && typeof row.delivered === "number" && row.delivered > 0 ? html`<span class="delivery-chip">${row.delivered > 1 ? "✓ delivered ×" + row.delivered : "✓ delivered"}</span>` : nothing}${preview}</span+ >`,+ time: row.lastActivity ? s.relTime(row.lastActivity) : "—",+ cls: background && typeof row.delivered === "number" && !row.delivered ? "history-silent" : "",+ href: s.stateToUrl(route({ session: row.id })),+ };+ },+ (row) => s.go(route({ session: row.id })),+ "No " + mode.toLowerCase() + " in this scope.",+ ),+ )}${pager(total, limit, offset, (page) => s.go(route({ page, cron })))}${+ s.scopeKind(s.scope) !== "org" && !cron+ ? html`<div>+ ${+ errorCount && errors.length+ ? html`<div class="statline">+ <a+ href="#"+ @click=${(e: Event) => {+ e.preventDefault();+ errorsOpen = !errorsOpen;+ draw();+ }}+ >${s.plural(errorCount, "error")} logged in this scope</a+ >+ </div>+ ${errorsOpen ? s.errorStripBox(errors, "Most recent errors", 20, (e: any) => (e.sessionId ? { href: s.stateToUrl(route({ session: e.sessionId })), go: () => s.go(route({ session: e.sessionId })) } : null)) : nothing}`+ : nothing+ }+ </div>`+ : nothing+ }`+ }`,+ );+ draw();+ if (s.scopeKind(s.scope) !== "org" && !cron) {+ const query = "scope=" + encodeURIComponent(s.scope);+ void Promise.all([s.adminErrorCount(query), s.adminErrors(query)])+ .then(([count, rows]) => {+ errorCount = count;+ errors = rows;+ draw();+ })+ .catch(() => {});+ }+}++export function scopeIndex(root: HTMLElement, s: Record<string, any>) {+ const paint = renderer(root);+ if (!s.ready) {+ s.pageShell({ title: s.title });+ paint(html`<div class="loadingline">${s.note}</div>`);+ return;+ }+ const active = s.rows.filter((r: any) => (r.sessions || 0) > 0 || (r.backgroundSessions || 0) > 0);+ const quiet = s.rows.filter((r: any) => !(r.sessions || 0) && !(r.backgroundSessions || 0));+ if (s.sort === "human")+ active.sort(+ (a: any, b: any) =>+ (b.lastConversationActivity || 0) - (a.lastConversationActivity || 0) ||+ (b.sessions || 0) - (a.sessions || 0) ||+ (b.lastActivity || 0) - (a.lastActivity || 0) ||+ a.scopeId.localeCompare(b.scopeId),+ );+ s.pageShell({+ title: s.title,+ count: s.plural(active.length, "active scope"),+ actions: [node(html`<div class="shell-sort"><span class="shell-sort-label">Sort:</span>${s.sortControl()}</div>`)],+ });+ const route = (scope: string) => ({ view: "history", scope, historyKind: s.historyKind });+ paint(+ html`${+ s.environments.length+ ? card(+ "Named environments",+ "Named computers and working memory that scopes can share.",+ denseList(+ s.environments,+ (e: any) => {+ const attached = e.attachedScopes || [];+ const names = attached.map((id: string) => s.shortName(id));+ const label = !names.length+ ? "no scopes attached"+ : names.slice(0, 4).join(", ") ++ (names.length > 4 ? " +" + s.plural(names.length - 4, "more scope") : "");+ return {+ name: e.name || s.shortName(e.id),+ preview: html`<span title=${attached.length ? names.join(", ") : ""}>${label}</span>`,+ href: s.stateToUrl(route(e.id)),+ };+ },+ (e) => s.selectScope(e.id),+ "No named environments.",+ ),+ )+ : nothing+ }${card(+ "Conversations by person or channel",+ "",+ denseList(+ active,+ (row: any) => {+ const time = s.sort === "human" ? row.lastConversationActivity || 0 : row.lastActivity || 0;+ return {+ name: s.shortName(row.scopeId),+ preview: html`<span+ ><span class="dense-tag">${s.sessionCountsLabel(row.sessions || 0, row.backgroundSessions || 0)}</span+ >${row.environmentAttachment ? html`<span class="dense-tag" title="This scope is attached to a named environment.">${"env: " + (row.environmentAttachment.environmentName || s.shortName(row.environmentAttachment.environmentId))}</span>` : nothing}${row.lastMessage || ""}</span+ >`,+ time: time ? s.relTime(time) : "Never",+ href: s.stateToUrl(route(row.scopeId)),+ };+ },+ (row) => s.selectScope(row.scopeId),+ s.rows.length ? "No conversations yet." : "No scopes yet. Nobody has talked to the agent.",+ ),+ )}${+ quiet.length+ ? html`<details class="history-quiet">+ <summary>${quiet.length} known scope${quiet.length === 1 ? "" : "s"} without conversations</summary>+ <div class="history-empty-scopes">+ ${quiet.map((row: any) => html`<button type="button" class="history-empty-scope" @click=${() => s.selectScope(row.scopeId)}>${s.scopeTitle(row.scopeId)}</button>`)}+ </div>+ </details>`+ : nothing+ }`,+ );+}diff --git a/plugins/admin/ui/integrations-state.ts b/plugins/admin/ui/integrations-state.tsnew file mode 100644index 000000000..271d2d163--- /dev/null+++ b/plugins/admin/ui/integrations-state.ts@@ -0,0 +1,330 @@+import { SettingState, settingRegistry } from "./setting-state.ts";+export type Api = (+ method: string,+ path: string,+ body?: unknown,+) => Promise<{ ok: boolean; status?: number; data?: any }>;+export type Context = {+ api: Api;+ orgScope: () => string;+ connectorName: (id: string) => string;+ fmtTime: (value: string) => string;+};+export let context: Context;+export function configure(value: Context) {+ context = value;+}+export class SlackSetting extends SettingState {+ scope = "";+ collect() {+ if (this.key === "internal-member-overrides")+ return {+ members: [+ ...new Set(+ String(this.draft.text || "")+ .split(/[\n,]/)+ .map((x) => x.trim().toLowerCase())+ .filter(Boolean),+ ),+ ],+ };+ if (this.key === "ack-emoji") return { names: [...(this.draft.names || [])] };+ return { on: !!this.draft.on };+ }+ change(value: any) {+ this.draft = { ...this.draft, ...value };+ this.changed();+ }+ load(value: any, scope: string, available: boolean) {+ this.scope = scope;+ this.available = available;+ this.draft = { on: !!value };+ if (this.key === "internal-member-overrides") this.draft = { text: (value || []).join("\n") };+ if (this.key === "ack-emoji") this.draft = { names: [...(value || [])] };+ this.baseline = JSON.stringify(this.collect());+ this.message = "";+ this.tone = "";+ this.saving = false;+ this.render();+ }+}+export const states = new Map(+ ["external-slack-participants", "internal-member-overrides", "channel-header-pin-default", "ack-emoji"].map((key) => [+ key,+ new SlackSetting(key),+ ]),+);+export const { owns, collect, capture, commit, status, statusKey } = settingRegistry(states);+export function loadScope(data: any, scope: string) {+ for (const [key, field] of Object.entries({+ "external-slack-participants": "externalSlackParticipants",+ "internal-member-overrides": "internalMemberOverrides",+ "channel-header-pin-default": "channelHeaderPinDefault",+ "ack-emoji": "ackEmoji",+ }))+ states.get(key)!.load(data[field], scope, scope.startsWith("org:") && field in data);+}+export type Connector = {+ provider: string;+ configured?: boolean;+ clientId?: string;+ enabled?: boolean;+ hasSecret?: boolean;+ updatedBy?: string;+ updatedAt?: string;+ inherited?: boolean;+ redirectPath?: string;+ scopes?: string[];+ setupGuide?: { url: string; console: string; steps: string[] };+};+export class ConnectorsState {+ catalog: Connector[] = [];+ list: Connector[] = [];+ editor = false;+ editing = "";+ draft = { provider: "", clientId: "", clientSecret: "", enabled: true };+ revision = 0;+ saving = false;+ message = "";+ tone = "";+ request = 0;+ render = () => {};+ get displayed(): Connector[] {+ return [+ ...this.list,+ ...this.catalog+ .filter((c) => c.configured && !this.list.some((e) => e.provider === c.provider))+ .map((c) => ({ provider: c.provider, inherited: true })),+ ];+ }+ change(field: string, value: string | boolean) {+ this.draft = { ...this.draft, [field]: value };+ this.revision++;+ this.render();+ }+ reset() {+ this.editor = false;+ this.editing = "";+ this.draft = { provider: this.catalog[0]?.provider || "", clientId: "", clientSecret: "", enabled: true };+ this.revision++;+ this.render();+ }+ edit(connector?: Connector) {+ this.editing = connector && !connector.inherited ? connector.provider : "";+ this.draft = {+ provider: connector?.provider || this.catalog[0]?.provider || "",+ clientId: connector?.clientId || "",+ clientSecret: "",+ enabled: connector?.enabled !== false,+ };+ this.editor = true;+ this.revision++;+ this.render();+ }+ setStatus(message: string, tone: string) {+ this.message = message;+ this.tone = tone;+ this.render();+ }+ async load() {+ const request = ++this.request,+ scope = context.orgScope();+ const [catalog, result] = await Promise.all([+ context.api("GET", "/api/connector-catalog"),+ context.api("GET", "/api/scopes/" + encodeURIComponent(scope) + "?view=connectors"),+ ]);+ if (request !== this.request || scope !== context.orgScope()) return;+ if (!catalog.ok) return this.setStatus(catalog.data?.message || "Failed to load connector setup.", "err");+ this.catalog = catalog.data.catalog || [];+ if (!result.ok)+ return this.setStatus(+ result.status === 403 ? "Only an org admin can manage connectors." : result.data?.message || "Failed to load.",+ "err",+ );+ this.list = result.data.connectors || [];+ if (!this.editor) this.draft.provider = this.catalog[0]?.provider || "";+ this.render();+ }+ async save() {+ if (this.saving) return;+ const body = { ...this.draft, clientId: this.draft.clientId.trim() };+ if (!body.provider) return this.setStatus("Choose a connector.", "err");+ if (!body.clientId) return this.setStatus("Client ID is required.", "err");+ if (!body.clientSecret) return this.setStatus("Client secret is required.", "err");+ const revision = this.revision,+ scope = context.orgScope();+ this.saving = true;+ this.setStatus("Saving...", "saving");+ try {+ const result = await context.api("PUT", "/api/scopes/" + encodeURIComponent(scope) + "/connectors", body);+ if (scope !== context.orgScope()) return;+ if (!result.ok)+ return this.setStatus(+ result.status === 403 ? "Only an org admin can manage connectors." : result.data?.message || "Save failed.",+ "err",+ );+ if (revision === this.revision) this.reset();+ await this.load();+ this.setStatus(revision + 1 === this.revision ? "Saved" : "Saved. Your newer edits are not saved.", "ok");+ } catch {+ this.setStatus("Save failed. Please try again.", "err");+ } finally {+ this.saving = false;+ this.render();+ }+ }+ async remove(provider: string) {+ if (+ !confirm(+ "Delete the OAuth client for " ++ context.connectorName(provider) ++ "? This hides the connector in everyone's web UI; existing links stop working.",+ )+ )+ return;+ const scope = context.orgScope(),+ revision = this.revision;+ const result = await context.api("PUT", "/api/scopes/" + encodeURIComponent(scope) + "/connectors", {+ provider,+ delete: true,+ });+ if (scope !== context.orgScope()) return;+ if (!result.ok) return this.setStatus(result.data?.message || "Delete failed.", "err");+ if (revision === this.revision && this.editing === provider) this.reset();+ await this.load();+ this.setStatus("Deleted", "ok");+ }+}+export const connectors = new ConnectorsState();+export class SlackInstallationState {+ data: Record<string, any> = {};+ editor = false;+ guide = false;+ botToken = "";+ appToken = "";+ revision = 0;+ busy = "";+ message = "";+ tone = "";+ request = 0;+ linkStarted = false;+ render = () => {};+ setStatus(message: string, tone: string) {+ this.message = message;+ this.tone = tone;+ this.render();+ }+ async load() {+ const request = ++this.request;+ const result = await context.api("GET", "/api/slack-installation");+ if (request !== this.request) return;+ if (!result.ok) return this.setStatus(result.data?.message || "Failed to load Slack status.", "err");+ this.data = result.data;+ const params = new URLSearchParams(location.search),+ step = params.get("slack");+ if ((!this.data.installAvailable && !this.data.configured) || params.get("setup") === "slack") this.guide = true;+ this.render();+ if (params.get("setup") === "slack")+ document.getElementById("card-slack-installation")?.scrollIntoView({ block: "start" });+ if (!this.linkStarted && this.data.installAvailable && ["setup", "install"].includes(step || "")) {+ this.linkStarted = true;+ if (this.data.configured && !(this.data.source === "service" && this.data.setup?.connected === false))+ this.setStatus("Slack is already configured. Return to your conversation.", "ok");+ else await this.start(step!);+ }+ if (step === "connected" && this.data.configured && this.data.setup?.connected)+ this.setStatus("Connected. You can return to your QM conversation.", "ok");+ }+ async start(step = "install") {+ if (this.busy) return;+ this.busy = "start";+ this.render();+ try {+ const result = await context.api("POST", "/api/slack-installation/start", { step });+ if (result.ok && result.data.url) {+ const form = document.createElement("form");+ form.method = "POST";+ form.action = result.data.url;+ document.body.appendChild(form);+ form.submit();+ } else this.setStatus("Could not start Slack installation. Please try again.", "err");+ } finally {+ this.busy = "";+ this.render();+ }+ }+ async save() {+ if (this.busy) return;+ const botToken = this.botToken.trim(),+ appToken = this.appToken.trim(),+ revision = this.revision;+ if (!botToken || !appToken) return this.setStatus("Both Slack tokens are required.", "err");+ this.busy = "save";+ this.setStatus("Validating with Slack…", "saving");+ try {+ const result = await context.api("PUT", "/api/slack-installation", { botToken, appToken });+ if (!result.ok) return this.setStatus(result.data?.message || "Slack validation failed.", "err");+ if (revision === this.revision) {+ this.botToken = "";+ this.appToken = "";+ this.editor = false;+ }+ await this.load();+ this.setStatus("Tokens verified and saved. Allow a few seconds, then test a mention and DM in Slack.", "ok");+ } catch {+ this.setStatus("Slack validation failed. Please try again.", "err");+ } finally {+ this.busy = "";+ this.render();+ }+ }+ async remove() {+ if (+ this.busy ||+ !confirm(+ "Disconnect this Slack app? QM will stop replying in Slack until you reconnect. The app will remain installed in your workspace.",+ )+ )+ return;+ this.busy = "remove";+ this.render();+ try {+ const result = await context.api("DELETE", "/api/slack-installation");+ if (!result.ok) return this.setStatus(result.data?.message || "Remove failed.", "err");+ await this.load();+ this.setStatus("Slack disconnected.", "ok");+ } finally {+ this.busy = "";+ this.render();+ }+ }+}+export const installation = new SlackInstallationState();+export const emoji = {+ open: false,+ query: "",+ catalog: {} as Record<string, string>,+ standard: [] as string[][],+ loaded: false,+ error: "",+ async load() {+ if (this.loaded) return;+ this.loaded = true;+ try {+ const result = await context.api("GET", "/api/slack-emoji");+ if (result.ok) {+ this.catalog = result.data.emoji || {};+ this.standard = result.data.standard || [];+ } else+ this.error =+ result.status === 404+ ? "Slack isn't connected on this deployment, so no emoji can be listed. Set SLACK_BOT_TOKEN on the core service (or complete the Slack installation on this page); on deployments where the token lives with the Slack plugin, the catalog appears after the plugin next starts and publishes it."+ : "Couldn't load emoji from Slack" ++ (result.data?.message ? " (" + result.data.message + ")" : "") ++ ". Check the bot token and try again.";+ } catch {+ this.error = "Couldn't reach the server to load emoji. Reload and try again.";+ }+ states.get("ack-emoji")!.render();+ },+};diff --git a/plugins/admin/ui/integrations.ts b/plugins/admin/ui/integrations.tsnew file mode 100644index 000000000..f83996dba--- /dev/null+++ b/plugins/admin/ui/integrations.ts@@ -0,0 +1,643 @@+import { choiceGroup, settingStatus, saveFooter } from "./setting-controls.ts";+import { html, render, nothing } from "lit";+import { classMap } from "lit/directives/class-map.js";+import { repeat } from "lit/directives/repeat.js";+import { states, connectors, installation, emoji, context, type SlackSetting } from "./integrations-state.ts";+export {+ configure,+ owns,+ collect,+ capture,+ commit,+ status,+ statusKey,+ states,+ connectors,+ installation,+} from "./integrations-state.ts";+import { loadScope as loadSettings } from "./integrations-state.ts";+export function loadScope(data: any, scope: string) {+ loadSettings(data, scope);+ if (states.get("ack-emoji")!.available) void emoji.load();+}+export const loadConnectors = () => connectors.load();+export const loadSlackInstallation = () => installation.load();+const cards: Record<string, () => ReturnType<typeof html>> = {};+cards["card-external-slack"] = () => {+ const s = states.get("external-slack-participants")!;+ return html`<section+ class=${classMap({ card: true, "sv-slack-settings": true, "setting-row": true, hidden: !s.available, dirty: s.dirty })}+ id="card-external-slack"+ >+ <div class="head">+ <h2>External Slack audience</h2>+ <p>+ Org-wide, default off. When on, internal members may chat with the agent in Slack rooms whose audience includes+ an external user (Connect member or guest). Its replies, and anything it reads there, are visible to those+ externals. Externals themselves still can't interact.+ </p>+ </div>+ <div class="body">+ <input+ type="checkbox"+ id="external-slack-participants"+ .checked=${!!s.draft.on}+ @change=${(e: Event) => s.change({ on: (e.target as HTMLInputElement).checked })}+ hidden+ />+ ${choiceGroup(+ {+ name: "external-slack-choice",+ value: ({ true: "on", false: "off" } as Record<string, string>)[String(s.draft.on)] || "",+ checkboxFor: "external-slack-participants",+ onChange: (event: Event) => s.change({ on: (event.target as HTMLInputElement).value === "on" }),+ },+ [+ ["off", "Internal only", "Default. The agent stays silent in Slack rooms that include an external user."],+ [+ "on",+ "Allow mixed rooms",+ "Internal members can use the agent where externals are present. Externals still cannot interact.",+ ],+ ],+ )}+ </div>+ ${saveFooter(s, "Apply", !s.available)}+ </section>`;+};+cards["card-internal-member-overrides"] = () => {+ const s = states.get("internal-member-overrides")!;+ return html`<section+ class=${classMap({ card: true, "sv-slack-settings": true, "setting-row": true, hidden: !s.available, dirty: s.dirty })}+ id="card-internal-member-overrides"+ >+ <div class="head">+ <h2 id="internal-member-overrides-title">Internal member overrides</h2>+ <p id="internal-member-overrides-help">+ Treat listed Slack users as internal members, including guests and people missing from the directory. This+ grants internal-member access, not just permission to mention the agent. Rooms containing only internal members+ may use organization credentials. Add only trusted colleagues. Enter one Slack user ID or Slack-profile email+ per line (commas also accepted).+ </p>+ </div>+ <div class="body">+ <textarea+ id="internal-member-overrides"+ .value=${s.draft.text || ""}+ @input=${(e: Event) => s.change({ text: (e.target as HTMLTextAreaElement).value })}+ rows="4"+ aria-labelledby="internal-member-overrides-title"+ aria-describedby="internal-member-overrides-help internal-member-overrides-count"+ spellcheck="false"+ placeholder="[email protected] U0123ABCDE"+ style="width: 100%; max-width: 560px; font-family: var(--mono, monospace)"+ ></textarea>+ <small class="muted" id="internal-member-overrides-count">${overrideCount(s)}</small>+ </div>+ ${saveFooter(s, "Apply", !s.available)}+ </section>`;+};+cards["card-channel-header-pin-default"] = () => {+ const s = states.get("channel-header-pin-default")!;+ return html`<section+ class=${classMap({ card: true, "sv-slack-settings": true, "setting-row": true, hidden: !s.available, dirty: s.dirty })}+ id="card-channel-header-pin-default"+ >+ <div class="head">+ <h2>Pinned channel message</h2>+ <p>+ When QM joins an internal Slack channel, it can post and pin a message showing the active model and a link to+ that channel’s settings. Turn this off to remove QM’s pinned message from channels using this default.+ Individual channels can override it on their settings page.+ </p>+ </div>+ <div class="body">+ <label class="setting-toggle">+ <input+ type="checkbox"+ id="channel-header-pin-default"+ .checked=${!!s.draft.on}+ @change=${(e: Event) => s.change({ on: (e.target as HTMLInputElement).checked })}+ />+ <span class="setting-switch" aria-hidden="true"></span>+ <span class="setting-copy"+ ><strong>Post and pin this message by default</strong+ ><small+ >Applies to channels without an explicit choice; flipping this updates existing channels within a+ moment.</small+ ></span+ >+ </label>+ <figure class="slack-message-example">+ <figcaption>Example · pinned in #product</figcaption>+ <div class="slack-example-message">+ <span class="slack-example-avatar" aria-hidden="true">Q</span>+ <div>+ <strong>QM</strong> <span class="muted">APP</span>+ <p>Using Sonnet here. <span class="slack-example-link">More settings</span></p>+ </div>+ </div>+ <p class="hint">+ “More settings” opens this channel’s settings page. The model name follows the channel’s selected model.+ </p>+ </figure>+ </div>+ ${saveFooter(s, "Apply", !s.available)}+ </section>`;+};+cards["card-ack-emoji"] = () => {+ const s = states.get("ack-emoji")!;+ return html`<section+ class=${classMap({ card: true, "sv-slack-settings": true, hidden: !s.available, dirty: s.dirty })}+ id="card-ack-emoji"+ >+ <div class="head">+ <h2>Acknowledgment emoji</h2>+ <p>+ The emoji the bot may react with to acknowledge a Slack message, org-wide. Add names from the workspace's emoji+ (custom and standard). Remove every chip to restore the built-in rotation.+ </p>+ </div>+ <div class="body">+ <div id="ack-emoji-chips" style="display: flex; flex-wrap: wrap; gap: 6px; align-items: center">+ ${emojiChips(s)}<span style="position: relative; display: inline-block">+ <button type="button" id="ack-emoji-open" @click=${() => toggleEmoji(s)} class="ghost" aria-haspopup="true">+ + Add emoji+ </button>+ <div class=${classMap({ "emoji-picker": true, hidden: !emoji.open })} id="ack-emoji-picker">+ <input+ type="text"+ id="ack-emoji-search"+ .value=${emoji.query}+ @input=${(e: Event) => {+ emoji.query = (e.target as HTMLInputElement).value;+ s.render();+ }}+ @keydown=${(e: KeyboardEvent) => emojiKey(e, s)}+ placeholder="Search emoji"+ autocomplete="off"+ />+ <div class="emoji-picker-scroll" id="ack-emoji-results">${emojiResults(s)}</div>+ </div>+ </span>+ </div>+ </div>+ ${saveFooter(s, "Save", !s.available)}+ </section>`;+};+cards["card-connectors"] = () => {+ const s = connectors;+ return html`<section class="card" id="card-connectors">+ <div class="head">+ <h2>OAuth apps</h2>+ <p>+ Each connector needs its own OAuth app's client ID and secret before anyone can link it. A connector stays+ hidden in everyone's web UI until you set its client here. The secret is write-only and never displayed. Applies+ org-wide.+ </p>+ </div>+ <div class="body">+ <div id="conn-list" class=${connectors.displayed.length ? "" : "hint"}>${connectorRows()}</div>+ </div>+ <div+ class=${classMap({ body: true, hidden: !s.editor })}+ id="conn-editor"+ style="border-top: 1px solid var(--border, #2a2a2a); padding-top: 12px"+ >+ <div class="sc-form-head">+ <p class="hint" id="conn-form-title">+ ${s.editing ? "Editing " + context.connectorName(s.editing) : "Add a connector"}+ </p>+ <span class=${"badge " + (s.editing ? "info" : "muted")} id="conn-form-mode"+ >${s.editing ? "Editing" : "New"}</span+ >+ </div>+ <label style="display: block; margin-bottom: 8px"+ >Connector+ <select id="conn-provider" style="width: 100%"></select+ ></label>+ <div id="conn-guide" class="hint" style="margin: 0 0 12px">${connectorGuide()}</div>+ <label style="display: block; margin-bottom: 8px"+ >Client ID+ <input+ type="text"+ id="conn-client-id"+ .value=${s.draft.clientId}+ @input=${(e: Event) => s.change("clientId", (e.target as HTMLInputElement).value)}+ autocomplete="off"+ placeholder="OAuth client ID"+ style="width: 100%"+ /></label>+ <label style="display: block; margin-bottom: 8px"+ >Client secret+ <input+ type="password"+ id="conn-client-secret"+ .value=${s.draft.clientSecret}+ @input=${(e: Event) => s.change("clientSecret", (e.target as HTMLInputElement).value)}+ autocomplete="off"+ placeholder=${s.editing && s.list.find((c) => c.provider === s.editing)?.hasSecret ? "•••• set (re-enter to replace)" : "(write-only)"}+ style="width: 100%"+ /></label>+ <p class="field-hint" id="conn-secret-hint">+ ${s.editing ? "Saving requires the client secret. Re-enter it to keep this connector working." : "Secret values are write-only and will not be displayed after saving."}+ </p>+ <label style="display: flex; align-items: center; gap: 10px; cursor: pointer; margin-bottom: 10px"+ ><input+ type="checkbox"+ id="conn-enabled"+ style="width: auto"+ .checked=${s.draft.enabled}+ @change=${(e: Event) => s.change("enabled", (e.target as HTMLInputElement).checked)}+ />+ Enabled</label+ >+ </div>+ <div class="foot">+ <button type="button" id="add-oauth-app" class=${s.editor ? "hidden" : ""} @click=${() => openConnector()}>+ + Add OAuth app</button+ ><button+ class=${classMap({ primary: true, hidden: !s.editor })}+ id="conn-save"+ ?disabled=${s.saving}+ @click=${() => s.save()}+ >+ ${s.editing ? "Save changes" : "Save connector"}</button+ ><button class=${s.editor ? "" : "hidden"} id="conn-reset" @click=${() => s.reset()}>Cancel</button+ >${settingStatus(s, "st-connectors")}+ </div>+ </section>`;+};+cards["card-slack-installation"] = () => {+ const s = installation,+ d = s.data;+ return html`<section class="card sv-slack-settings" id="card-slack-installation">+ <div class="head">+ <h2>Slack</h2>+ </div>+ <div class="body">+ <div class="slack-connection">+ <div class="slack-connection-info">+ <h3 id="slack-installation-state">${installationTitle(d)}</h3>+ <p class="hint" id="slack-installation-description">${installationDescription(d)}</p>+ </div>+ <div class="slack-connection-actions">+ <button+ class=${d.installAvailable ? "" : "hidden"}+ id="slack-installation-start"+ ?disabled=${!!s.busy || (d.configured && d.source === "admin")}+ title=${d.configured && d.source === "admin" ? "Remove your current connection before switching to the hosted app." : ""}+ @click=${() => s.start()}+ >+ <svg width="20" height="20" viewBox="0 0 127 127" aria-hidden="true" focusable="false">+ <path+ d="M27.2 80c0 7.3-5.9 13.2-13.2 13.2C6.7 93.2.8 87.3.8 80c0-7.3 5.9-13.2 13.2-13.2h13.2V80zm6.6 0c0-7.3 5.9-13.2 13.2-13.2 7.3 0 13.2 5.9 13.2 13.2v33c0 7.3-5.9 13.2-13.2 13.2-7.3 0-13.2-5.9-13.2-13.2V80z"+ fill="#E01E5A"+ />+ <path+ d="M47 27c-7.3 0-13.2-5.9-13.2-13.2C33.8 6.5 39.7.6 47 .6c7.3 0 13.2 5.9 13.2 13.2V27H47zm0 6.7c7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2H13.9C6.6 60.1.7 54.2.7 46.9c0-7.3 5.9-13.2 13.2-13.2H47z"+ fill="#36C5F0"+ />+ <path+ d="M99.9 46.9c0-7.3 5.9-13.2 13.2-13.2 7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2H99.9V46.9zm-6.6 0c0 7.3-5.9 13.2-13.2 13.2-7.3 0-13.2-5.9-13.2-13.2V13.8C66.9 6.5 72.8.6 80.1.6c7.3 0 13.2 5.9 13.2 13.2v33.1z"+ fill="#2EB67D"+ />+ <path+ d="M80.1 99.8c7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2-7.3 0-13.2-5.9-13.2-13.2V99.8h13.2zm0-6.6c-7.3 0-13.2-5.9-13.2-13.2 0-7.3 5.9-13.2 13.2-13.2h33.1c7.3 0 13.2 5.9 13.2 13.2 0 7.3-5.9 13.2-13.2 13.2H80.1z"+ fill="#ECB22E"+ />+ </svg>+ <span id="slack-installation-start-label">${d.configured ? "Re-add to Slack" : "Add to Slack"}</span>+ </button>+ <button+ class=${classMap({ danger: true, hidden: !d.configured })}+ id="slack-installation-delete"+ ?disabled=${!d.configured || !!s.busy}+ @click=${() => s.remove()}+ >+ Disconnect+ </button>+ </div>+ </div>+ <details+ id="slack-own-app-guide"+ .open=${s.guide}+ @toggle=${(e: Event) => {+ s.guide = (e.target as HTMLDetailsElement).open;+ }}+ >+ <summary>+ <span id="slack-own-app-label">${d.installAvailable ? "Use your own Slack app" : "Set up Slack"}</span>+ <span class="slack-guide-arrow" aria-hidden="true">›</span>+ </summary>+ <p>+ Give your bot its own name and identity. Start with our preconfigured manifest, then connect your app below.+ </p>+ <ol>+ <li>+ <a+ id="slack-installation-create"+ href=${d.createUrl || "https://api.slack.com/apps?new_app=1"}+ target="_blank"+ rel="noopener noreferrer"+ >Create your preconfigured Slack app ↗</a+ >. Choose your company workspace, review the permissions, and click <strong>Create</strong>. The manifest+ sets up the bot, message events, buttons, and Socket Mode for you.+ </li>+ <li>+ In <strong>OAuth & Permissions</strong>, click <strong>Install to Workspace</strong> and approve access.+ Copy the <strong>Bot User OAuth Token</strong> starting with <code>xoxb-</code>.+ </li>+ <li>+ In <strong>Basic Information → App-Level Tokens</strong>, click <strong>Generate Token and Scopes</strong>.+ Name it <strong>QM connection</strong>, add <code>connections:write</code>, and generate it. Copy the token+ starting with <code>xapp-</code>.+ </li>+ <li>+ Paste both tokens below and click <strong>Validate and connect</strong>. Keep this page open while you work+ in Slack. Tokens must come from the same app.+ </li>+ <li>+ Invite your new bot to a channel, mention it, then send it a DM to check both surfaces. It only sees+ conversations it can access; older history may be incomplete.+ </li>+ </ol>+ <p class="hint">+ Replacing a connected app changes the bot identity. Invite the new bot to your channels and start a new DM+ with it. The old app stays installed until a workspace admin removes it.+ <span id="slack-hosted-switch" class=${d.installAvailable ? "" : "hidden"}+ >To switch back to the QM app, disconnect here first, then choose Add to Slack.</span+ >+ </p>+ <button+ type="button"+ id="slack-enter-tokens"+ @click=${() => {+ s.editor = true;+ s.render();+ document.getElementById("slack-bot-token")?.focus();+ document.getElementById("card-slack-installation")?.scrollIntoView({ behavior: "smooth", block: "start" });+ }}+ >+ I have both tokens+ </button>+ <div class=${s.editor ? "" : "hidden"} id="slack-token-editor">+ <label style="display: block; margin-bottom: 8px"+ >Bot User OAuth Token+ <input+ type="password"+ id="slack-bot-token"+ .value=${s.botToken}+ @input=${(e: Event) => {+ s.botToken = (e.target as HTMLInputElement).value;+ s.revision++;+ }}+ autocomplete="off"+ placeholder="xoxb-…"+ style="width: 100%"+ /></label>+ <label style="display: block; margin-bottom: 8px"+ >App-Level Token+ <input+ type="password"+ id="slack-app-token"+ .value=${s.appToken}+ @input=${(e: Event) => {+ s.appToken = (e.target as HTMLInputElement).value;+ s.revision++;+ }}+ autocomplete="off"+ placeholder="xapp-…"+ style="width: 100%"+ /></label>+ <p class="field-hint">+ Use an app-level token with <code>connections:write</code>. Saving activates or reloads the Slack surface+ within a few seconds.+ </p>+ <button+ class=${classMap({ primary: true, hidden: !s.editor })}+ id="slack-installation-save"+ ?disabled=${!!s.busy}+ @click=${() => s.save()}+ >+ Validate and connect+ </button>+ </div>+ </details>+ <span class=${"status " + s.tone} role="status" id="st-slack-installation">${s.message}</span>+ </div>+ </section>`;+};+function overrideCount(s: SlackSetting) {+ const n = s.collect().members!.length;+ return n ? n + " override" + (n === 1 ? "" : "s") : "No overrides configured.";+}+function openConnector(connector?: Parameters<typeof connectors.edit>[0]) {+ connectors.edit(connector);+ document.getElementById("conn-client-id")?.focus();+ document+ .getElementById("card-connectors")+ ?.scrollIntoView({ behavior: "smooth", block: connector ? "nearest" : "start" });+}+function badge(text: string, tone: string) {+ return html`<span class=${"badge " + tone}>${text}</span>`;+}+function connectorRows() {+ if (!connectors.displayed.length) return "No connectors configured. Add one below to make it linkable in the web UI.";+ return repeat(+ connectors.displayed,+ (c) => c.provider,+ (c) =>+ html`<div class=${classMap({ "credential-row": true, "is-editing": c.provider === connectors.editing })}>+ <div class="credential-main">+ <div class="credential-title">+ <strong>${context.connectorName(c.provider)}</strong><span class="credential-slug">${c.provider}</span>+ </div>+ <div class="hint">+ ${c.inherited ? "Configured by deployment secrets" : "client " + (c.clientId || "None") + (c.updatedBy ? " · by " + c.updatedBy : "") + (c.updatedAt ? " · " + context.fmtTime(c.updatedAt) : "")}+ </div>+ <div class="credential-badges">+ ${badge(c.enabled === false ? "Disabled" : "Enabled", c.enabled === false ? "warn" : "ok")}${badge(c.inherited || c.hasSecret ? "Secret set" : "Secret missing", c.inherited || c.hasSecret ? "ok" : "err")}+ </div>+ </div>+ <div class="credential-actions">+ ${c.inherited ? html`<button type="button" @click=${() => openConnector(c)}>Override here</button>` : html`<button type="button" @click=${() => openConnector(c)}>Edit</button><button type="button" class="rowbtn danger" title="Delete connector" aria-label=${"Delete " + context.connectorName(c.provider)} @click=${() => connectors.remove(c.provider)}>Delete</button>`}+ </div>+ </div>`,+ );+}+function connectorGuide() {+ const c = connectors.catalog.find((c) => c.provider === connectors.draft.provider);+ if (!c?.setupGuide) return nothing;+ return html`<a href=${c.setupGuide.url} target="_blank" rel="noopener noreferrer"+ >${"Open " + c.setupGuide.console + " ↗"}</a+ >+ <div>${"Callback URL: " + location.origin + "/v1/connectors/oauth/" + c.redirectPath}</div>+ <div>${c.scopes?.length ? "Scopes: " + c.scopes.join(", ") : "Scopes are selected in the provider."}</div>+ <ol>+ ${c.setupGuide.steps.map((step) => html`<li>${step}</li>`)}+ </ol>`;+}+function builtIns() {+ return html`<section class="card" id="card-built-in-connectors">+ <div class="head"><h2>Built-in connectors</h2></div>+ <div class=${connectors.catalog.length ? "" : "hint"} id="built-in-connectors">+ ${+ connectors.catalog.length+ ? repeat(+ connectors.catalog,+ (c) => c.provider,+ (c) =>+ html`<div class="credential-row">+ <div class="credential-main">+ <strong>${context.connectorName(c.provider)}</strong>+ <div class="hint">${c.configured ? "Available to users" : "Requires an OAuth app"}</div>+ </div>+ ${badge(c.configured ? "Configured" : "Not configured", c.configured ? "ok" : "muted")}+ </div>`,+ )+ : "No built-in connectors are available."+ }+ </div>+ </section>`;+}+function emojiChanged(s: SlackSetting, names: string[]) {+ s.change({ names });+ (document.querySelector('[data-save="ack-emoji"]') as HTMLButtonElement | null)?.click();+}+function emojiChips(s: SlackSetting) {+ return repeat(+ s.draft.names || [],+ (name: string) => name,+ (name: string) =>+ html`<span+ data-chip=${name}+ style="display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border:1px solid var(--border, #d4d4d4);border-radius:999px;font-size:13px"+ ><span+ >${emoji.catalog[name] ? html`<img src=${emoji.catalog[name]} alt=${name} class="ack-emoji-img" style="margin-right:4px" />` : (emoji.standard.find((e) => e[0] === name)?.[1] || "") + " "}${":" + name + ":"}</span+ ><button+ type="button"+ aria-label=${"Remove " + name}+ style="border:0;background:none;cursor:pointer;padding:0;font-size:14px;line-height:1"+ @click=${() =>+ emojiChanged(+ s,+ s.draft.names.filter((v: string) => v !== name),+ )}+ >+ ×+ </button></span+ >`,+ );+}+function emojiResults(s: SlackSetting) {+ if (emoji.error) return html`<div class="emoji-picker-empty">${emoji.error}</div>`;+ const q = emoji.query.trim().toLowerCase().replace(/:/g, ""),+ taken = new Set(s.draft.names || []),+ sections = new Map<string, string[][]>();+ const custom = Object.keys(emoji.catalog)+ .filter((n) => !taken.has(n) && (!q || n.includes(q)))+ .sort();+ if (custom.length)+ sections.set(+ "Custom",+ custom.map((n) => [n, ""]),+ );+ for (const entry of emoji.standard) {+ if (taken.has(entry[0]) || emoji.catalog[entry[0]] || (q && !entry[0].includes(q))) continue;+ if (!sections.has(entry[2])) sections.set(entry[2], []);+ sections.get(entry[2])!.push(entry);+ }+ if (!sections.size)+ return html`<div class="emoji-picker-empty">${"No emoji match “" + emoji.query.trim() + "”"}</div>`;+ return [...sections].map(+ ([title, entries]) =>+ html`<div class="emoji-picker-section">${title}</div>+ <div class="emoji-picker-grid">+ ${entries.map(+ ([name, glyph]) =>+ html`<button+ type="button"+ title=${":" + name + ":"}+ aria-label=${name}+ @click=${() => {+ emoji.open = false;+ emojiChanged(s, [...s.draft.names, name]);+ }}+ >+ ${emoji.catalog[name] ? html`<img src=${emoji.catalog[name]} alt=${name} loading="lazy" />` : glyph}+ </button>`,+ )}+ </div>`,+ );+}+function toggleEmoji(s: SlackSetting) {+ emoji.open = !emoji.open;+ emoji.query = "";+ s.render();+ if (emoji.open) document.getElementById("ack-emoji-search")?.focus();+}+function emojiKey(event: KeyboardEvent, s: SlackSetting) {+ if (event.key === "Escape") {+ event.preventDefault();+ emoji.open = false;+ s.render();+ }+ if (event.key === "Enter") {+ event.preventDefault();+ (document.querySelector("#ack-emoji-results button") as HTMLButtonElement | null)?.click();+ }+}+export function mountCards() {+ for (const [id, template] of Object.entries(cards)) {+ const placeholder = document.querySelector('[data-integrations-card="' + id + '"]');+ if (!placeholder) continue;+ const fragment = document.createDocumentFragment();+ const draw = () => render(template(), fragment);+ if (id === "card-connectors") connectors.render = draw;+ else if (id === "card-slack-installation") installation.render = draw;+ else {+ const key = (+ {+ "card-external-slack": "external-slack-participants",+ "card-internal-member-overrides": "internal-member-overrides",+ "card-channel-header-pin-default": "channel-header-pin-default",+ "card-ack-emoji": "ack-emoji",+ } as Record<string, string>+ )[id];+ states.get(key)!.render = draw;+ }+ draw();+ placeholder.replaceWith(fragment);+ }+ document.addEventListener("mousedown", (event) => {+ if (emoji.open && !(event.target as Element).closest("#ack-emoji-picker, #ack-emoji-open")) {+ emoji.open = false;+ states.get("ack-emoji")!.render();+ }+ });+}+export function mountBuiltIns() {+ const target = document.getElementById("card-built-in-connectors");+ if (!target) return;+ const fragment = document.createDocumentFragment(),+ previous = connectors.render;+ const draw = () => render(builtIns(), fragment);+ draw();+ target.replaceWith(fragment);+ connectors.render = () => {+ previous();+ draw();+ };+}++function installationTitle(data: Record<string, any>) {+ if (data.configured) return data.teamName || data.teamId || "Slack workspace";+ return data.source === "invalid_environment" ? "Finish connecting your app" : "Connect your workspace";+}+function installationDescription(data: Record<string, any>) {+ if (data.configured) return data.source === "service" ? "QM app" : "Custom app";+ return data.installAvailable+ ? "Add the QM app or connect your own below."+ : "Create a Slack app from our manifest, then connect it here.";+}diff --git a/plugins/admin/ui/keychain.ts b/plugins/admin/ui/keychain.tsnew file mode 100644index 000000000..e251f6937--- /dev/null+++ b/plugins/admin/ui/keychain.ts@@ -0,0 +1,178 @@+import { html, nothing } from "lit";+import { card, table, renderer } from "./shared.ts";++export function keychain(root: HTMLElement, d: any, s: Record<string, any>) {+ const paint = renderer(root);+ if (d.enabled === false) {+ paint(+ card(+ "Keychain unavailable",+ "Stable key material is required before the core can store keychain records.",+ html`<p class="empty">Keychain is not configured for this deployment.</p>`,+ ),+ );+ return;+ }+ const people = d.people || [],+ credentials = d.credentials || [],+ grants = d.grants || [],+ asks = d.asks || [];+ let filter = "";+ const personName = (id: string) => {+ const p = people.find((p: any) => p.principalId === id);+ return p?.displayName ? `${p.displayName} (${id})` : id;+ };+ const credName = (id: string) => {+ const c = credentials.find((c: any) => c.id === id);+ return c ? c.service + (c.accountLabel ? " - " + c.accountLabel : "") : id;+ };+ const matches = (parts: any[]) => parts.join(" ").toLowerCase().includes(filter.trim().toLowerCase());+ const stacked = (primary: any, secondary: any, cls?: string) => ({+ node: html`<div>+ <div class="primaryline">${primary}</div>+ ${secondary ? html`<div class="subline">${secondary}</div>` : nothing}+ </div>`,+ cls,+ });+ const muted = (text: string, tone = "") => ({+ node: html`<span class=${({ err: "flag-err", warn: "flag-warn" } as Record<string, string>)[tone] || "subline"}+ >${text}</span+ >`,+ });+ const expiry = (ts: number) => (!ts ? "No expiry" : (ts <= Date.now() ? "Expired " : "Expires ") + s.fmtTime(ts));+ function draw() {+ paint(+ html`<div class="list-root">+ ${card(+ "People",+ "Everyone known through sessions, admin grants, keychain records, grants, or asks.",+ table(+ ["Person", "Keychain", "Active grants", "Pending asks"],+ people+ .filter((p: any) => matches([p.principalId, p.displayName || ""]))+ .map((p: any) => [+ stacked(p.displayName || p.principalId, p.displayName ? p.principalId : "", "mono"),+ ...[p.credentialCount, p.activeGrantCount].map((n) => ({+ action: {+ label: String(n || 0),+ title: "Open this person's credentials and grants",+ run: () => s.openUser(p.principalId),+ },+ })),+ { text: String(p.pendingAskCount || 0), cls: "num" },+ ]),+ "No people match.",+ ),+ )}${card(+ "Credentials",+ "Metadata only. Secret material and encrypted values are never returned to admin.",+ table(+ ["Owner", "Credential", "Delivery", "Account", "Expiry"],+ credentials+ .filter((c: any) =>+ matches([+ c.ownerId,+ personName(c.ownerId),+ c.service,+ c.kind,+ c.envKey || "",+ c.accountLabel || "",+ c.host || "",+ (c.targets || []).join(" "),+ ]),+ )+ .map((c: any) => [+ stacked(personName(c.ownerId), c.ownerId, "mono"),+ stacked(c.service, c.id, "mono"),+ muted([c.kind || "unknown", c.envKey, ...(c.targets || []).slice(0, 2)].filter(Boolean).join(" · ")),+ c.accountLabel || c.host || "-",+ { text: expiry(c.expiresAt), cls: "num" },+ ]),+ "No keychain credentials match.",+ ),+ )}${card(+ "Grants",+ "Purpose-bound keychain grants from an owner to an audience scope.",+ table(+ ["Owner", "Credential", "Audience", "Mode", "Status", "Purpose"],+ grants+ .filter((g: any) =>+ matches([+ g.ownerId,+ personName(g.ownerId),+ g.audienceScopeId,+ g.mode,+ g.status,+ g.purpose,+ credName(g.credentialId),+ ]),+ )+ .map((g: any) => {+ const expired = g.expiresAt && g.expiresAt <= Date.now() && g.status === "active";+ let tone = g.status === "revoked" ? "err" : "";+ if (expired) tone = "warn";+ let purposeDetail = g.askId ? "ask " + g.askId : "";+ if (g.usedBy) purposeDetail = "used by " + g.usedBy;+ return [+ stacked(personName(g.ownerId), g.ownerId, "mono"),+ stacked(credName(g.credentialId), g.credentialId, "mono"),+ stacked(g.audienceScopeId, s.scopeKind(g.audienceScopeId), "mono"),+ muted(g.mode || "unknown"),+ muted(expired ? "expired" : g.status || "unknown", tone),+ stacked(g.purpose || "-", purposeDetail),+ ];+ }),+ "No keychain grants match.",+ ),+ )}${card(+ "Asks",+ "Outstanding and resolved cross-conversation consent requests.",+ table(+ ["Owner", "Requester", "Credential", "Scope", "Status", "Purpose"],+ asks+ .filter((a: any) =>+ matches([+ a.ownerId,+ personName(a.ownerId),+ a.requesterId,+ personName(a.requesterId),+ a.requesterScopeId,+ a.status,+ a.purpose,+ credName(a.credentialId),+ ]),+ )+ .map((a: any) => [+ stacked(personName(a.ownerId), a.ownerId, "mono"),+ stacked(personName(a.requesterId), a.requesterId, "mono"),+ stacked(credName(a.credentialId), a.credentialId, "mono"),+ stacked(a.requesterScopeId, s.scopeKind(a.requesterScopeId), "mono"),+ muted(a.status || "unknown", a.status === "pending" ? "warn" : ""),+ stacked(a.purpose || "-", a.expiresAt ? expiry(a.expiresAt) : ""),+ ]),+ "No keychain asks match.",+ ),+ )}+ </div>`,+ );+ }+ s.defaultShell({+ stats: [+ [people.length, "People"],+ [credentials.length, "Credentials"],+ [+ grants.filter((g: any) => g.status === "active" && (!g.expiresAt || g.expiresAt > Date.now())).length,+ "Active grants",+ ],+ [asks.filter((a: any) => a.status === "pending").length, "Pending asks"],+ ],+ search: {+ placeholder: "person, service, audience, purpose",+ onInput: (value: string) => {+ filter = value;+ draw();+ },+ },+ });+ draw();+}diff --git a/plugins/admin/ui/metrics.ts b/plugins/admin/ui/metrics.tsnew file mode 100644index 000000000..5850bd708--- /dev/null+++ b/plugins/admin/ui/metrics.ts@@ -0,0 +1,172 @@+import { html, nothing } from "lit";+import { table, card, mount } from "./shared.ts";++export function metrics(root: HTMLElement, d: any, s: Record<string, any>) {+ const n = (text: any) => ({ text, cls: "num" });+ const line = (parts: any[]) => html`<div class="statline">${parts.filter(Boolean).join(" · ")}</div>`;+ const stacked = (title: string, description: string) => ({+ node: html`<div>+ <div class="primaryline">${title}</div>+ ${description ? html`<div class="subline">${description}</div>` : nothing}+ </div>`,+ });+ if (s.phase) {+ const p = (d.phases || []).find((p: any) => p.phase === s.phase);+ s.pageShell({+ back: { label: "← Metrics", onClick: () => s.go({ view: "metrics", scope: s.scope, session: null }) },+ title: s.phaseLabel(s.phase),+ context: s.phaseDesc(s.phase),+ });+ if (!p?.count) {+ mount(root, html`<p class="empty">No ${s.phaseLabel(s.phase).toLowerCase()} samples in this scope yet.</p>`);+ return;+ }+ const bins = (p.dist || []).map((b: any, i: number, all: any[]) => ({+ ...b,+ label: b.le == null ? "> " + s.fmtMs(all[i - 1]?.le) : "≤ " + s.fmtMs(b.le),+ }));+ while (bins.length && !bins[bins.length - 1].count) bins.pop();+ const max = Math.max(...bins.map((b: any) => b.count), 1);+ const worst = p.worst || [];+ mount(+ root,+ html`${line([Number(p.count).toLocaleString() + " turns", s.fmtMs(p.p50) + " p50", s.fmtMs(p.p95) + " p95", s.fmtMs(p.p99) + " p99"])}${card(+ "Distribution",+ "Where the samples land.",+ bins.length+ ? html`<div class="dist">+ ${bins.map(+ (b: any) =>+ html`<div class="dist-row">+ <span class="dist-label">${b.label}</span+ ><span class="dist-track"+ ><span+ class="dist-bar"+ style=${"width:" + Math.max((b.count / max) * 100, b.count ? 1 : 0) + "%"}+ ></span></span+ ><span class="dist-count">${b.count ? Number(b.count).toLocaleString() : ""}</span>+ </div>`,+ )}+ </div>`+ : html`<p class="empty">No samples.</p>`,+ )}${card(+ "By day",+ "Daily percentiles (UTC).",+ table(+ ["Day", "Turns", "p50", "p95", "p99"],+ (p.daily || [])+ .slice()+ .reverse()+ .map((r: any) => [+ { text: r.day, cls: "mono" },+ n(Number(r.count).toLocaleString()),+ n(s.fmtMs(r.p50)),+ n(s.fmtMs(r.p95)),+ n(s.fmtMs(r.p99)),+ ]),+ "No daily samples.",+ ),+ )}${card(+ "Worst recent turns",+ worst.some((t: any) => t.sessionId)+ ? "The slowest samples. Each opens the turn's transcript."+ : "The slowest samples.",+ table(+ [s.phaseLabel(s.phase), "Total turn", "Scope", "Machine", "Time"],+ worst.map((t: any) => [+ n(s.fmtMs(t.ms)),+ n(t.totalMs ? s.fmtMs(t.totalMs) : "n/a"),+ s.shortName(t.scopeLabel),+ { text: s.turnKindWords(t) || "None", cls: "subline" },+ n(s.relTime(t.ts)),+ ]),+ "No samples.",+ (i) => {+ const t = worst[i];+ if (t.sessionId)+ s.go({+ view: "history",+ scope: t.scopeLabel || s.scope,+ session: t.sessionId,+ ...(t.turnSeq != null ? { turn: t.turnSeq } : {}),+ });+ },+ ),+ )}`,+ );+ return;+ }+ s.defaultShell({ count: s.plural(d.throughput?.total ?? 0, "run") });+ const c = d.cache,+ phases = d.phases || [],+ tp = d.throughput || {},+ an = d.anatomy;+ const mix = () => {+ if (!an?.composite?.totalTurns) return nothing;+ const a = an.traceA || {},+ b = an.traceB || {},+ c = an.composite;+ const share = (n: number) => s.fmtPct((n || 0) / c.totalTurns);+ const fmtX = (n: number) => (n == null ? "n/a" : String(Math.round(n * 10) / 10));+ return card(+ "Turn mix",+ "How often turns provision a machine, and what each kind of turn costs.",+ table(+ ["Kind of turn", "Share", "Turns", "Median", "Model calls", "Tool calls"],+ [+ [+ stacked("Turns that never touched a machine", "pure conversation, no tools"),+ n(share(a.samples)),+ n(String(a.samples || 0)),+ n(s.fmtMs(a.total?.p50)),+ n(fmtX(a.modelCalls?.avg)),+ n(fmtX(a.toolCalls?.avg)),+ ],+ [+ stacked(+ "Turns that used a machine",+ (b.warm || 0) ++ " on a warm machine (" ++ s.fmtMs(b.provisionWarm?.p50) ++ " median resume) · " ++ (b.cold || 0) ++ " booted cold (" ++ s.fmtMs(b.provisionCold?.p50) ++ " median boot)",+ ),+ n(share(b.samples)),+ n(String(b.samples || 0)),+ n(s.fmtMs(b.total?.p50)),+ n(fmtX(b.modelCalls?.avg)),+ n(fmtX(b.toolCalls?.avg)),+ ],+ [+ stacked("All turns", "the blended average"),+ n("100%"),+ n(String(c.totalTurns || 0)),+ n(s.fmtMs(c.total?.p50)),+ n(fmtX(c.modelCalls?.avg)),+ n(fmtX(c.toolCalls?.avg)),+ ],+ ],+ "No turns sampled.",+ ),+ );+ };+ mount(+ root,+ html`${c?.samples ? line([(c.avgHitRatio == null ? "n/a" : s.fmtPct(c.avgHitRatio)) + " prompt-cache hit ratio", (c.pooledHitRatio == null ? "n/a" : s.fmtPct(c.pooledHitRatio)) + " token-weighted", (c.missRate == null ? "n/a" : s.fmtPct(c.missRate)) + " stable-prefix miss rate", (c.missTurns || 0) + " miss turns", (c.samples || 0) + " turns with cache data", s.fmtTokens(c.cacheReadTotal || 0) + " read", s.fmtTokens(c.cacheWriteTotal || 0) + " written"]) : nothing}${table(+ ["Phase", "p50", "p95", "p99", "Turns", "Trend"],+ phases.map((p: any) => [+ stacked(s.phaseLabel(p.phase), s.phaseDesc(p.phase)),+ n(s.fmtMs(p.p50)),+ n(s.fmtMs(p.p95)),+ n(s.fmtMs(p.p99)),+ n(p.count ? Number(p.count).toLocaleString() : "n/a"),+ { node: s.sparkline(p.daily), cls: "num" },+ ]),+ "No turn metrics in this scope yet.",+ (i) => s.go({ view: "metrics", scope: s.scope, session: null, phase: phases[i].phase }),+ )}${mix()}${tp.total ? line([(tp.total ?? 0) + " runs", (tp.done ?? 0) + " done", (tp.failed ?? 0) + " failed", s.fmtPct(tp.failureRate) + " failure rate"]) : nothing}`,+ );+}diff --git a/plugins/admin/ui/onboarding.ts b/plugins/admin/ui/onboarding.tsnew file mode 100644index 000000000..811573c50--- /dev/null+++ b/plugins/admin/ui/onboarding.ts@@ -0,0 +1,722 @@+import { html, nothing, render } from "lit";+type Data = Record<string, any>;+const providerLabels: Record<string, string> = {+ anthropic: "Anthropic",+ openai: "OpenAI",+ openrouter: "OpenRouter (hosted open models)",+};+const fieldLabels: Record<string, string> = {+ name: "Display name",+ template: "Compatible builtin template",+ contextWindow: "Context window (tokens)",+ maxTokens: "Maximum output (tokens)",+ input: "Input ($ / million tokens)",+ output: "Output ($ / million tokens)",+ cacheRead: "Cache read ($ / million tokens)",+ cacheWrite: "Cache write ($ / million tokens)",+};+const flagLabels: Record<string, string> = {+ base: "Offer in admin model choices",+ webui: "Offer in web picker by default",+ fastMode: "Model supports the Anthropic fast tier",+ auxiliary: "Eligible for auxiliary tasks",+};+const errorText = (error: unknown) => (error instanceof Error ? error.message : "Request failed.");+export class Onboarding {+ context: Data;+ models: Record<string, Data[]> = {};+ providers: Data[] = [];+ templates: Data[] = [];+ entries: Data[] = [];+ provider = "anthropic";+ model = "";+ apiKey = "";+ providerMessage = "";+ providerTone = "";+ providerBusy = false;+ registryProvider = "openai";+ registryId = "";+ editing = false;+ providerLocked = false;+ lookup: Data | null = null;+ draft: Data = {};+ registryBusy = false;+ lookingUp = false;+ registryMessage = "";+ registryTone = "";+ advanced = false;+ steps: Data = {+ model: { text: "Not ready", tone: "muted", summary: "Add the key the agent will use for its base model." },+ slack: {+ text: "Optional",+ tone: "muted",+ summary: "Create the Slack app, install it, then add its bot and Socket Mode tokens.",+ url: "https://api.slack.com/apps?new_app=1",+ },+ oauth: {+ text: "Optional",+ tone: "muted",+ summary: "Add Google, GitHub, Notion, or other OAuth clients to make those connectors available.",+ },+ };+ request = 0;+ lookupRequest = 0;+ registryRequest = 0;+ painters: (() => void)[] = [];+ constructor(context: Data = {}) {+ this.context = context;+ }+ mount() {+ for (const placeholder of document.querySelectorAll<HTMLTemplateElement>("template[data-onboarding-ui]")) {+ const kind = placeholder.dataset.onboardingUi!;+ const fragment = document.createDocumentFragment();+ const draw = () => render(this.template(kind), fragment);+ draw();+ placeholder.replaceWith(fragment.firstElementChild!);+ this.painters.push(draw);+ }+ }+ draw() {+ for (const paint of this.painters) paint();+ }+ label(provider: string) {+ return providerLabels[provider] || this.context.connectorName(provider);+ }+ resetLookup() {+ this.lookupRequest++;+ this.lookup = null;+ this.lookingUp = false;+ this.registryMessage = "";+ this.registryTone = "";+ this.advanced = false;+ }+ reset(spec?: Data) {+ if (this.registryBusy) return;+ this.resetLookup();+ this.editing = Boolean(spec);+ this.providerLocked = Boolean(spec?.provider);+ this.registryId = spec?.id || "";+ this.registryProvider = spec?.provider || "openai";+ if (spec)+ this.showLookup({+ kind: "saved",+ spec,+ missing: [+ ...["name", "template", "contextWindow", "maxTokens"].filter((field) => spec[field] == null),+ ...["input", "output", "cacheRead", "cacheWrite"].filter((field) => spec.cost?.[field] == null),+ ],+ source: "Saved administrator definition",+ message: "Review the saved definition under Advanced overrides. Changes require verification again.",+ });+ this.draw();+ }+ showLookup(result: Data) {+ this.lookup = { ...result, identity: { provider: this.registryProvider, id: this.registryId.trim() } };+ this.draft = {};+ for (const field of ["name", "template", "contextWindow", "maxTokens"])+ this.draft[field] = String(result.spec[field] ?? "");+ for (const field of ["input", "output", "cacheRead", "cacheWrite"])+ this.draft[field] = String(result.spec.cost?.[field] ?? "");+ for (const field of Object.keys(flagLabels))+ this.draft[field] = result.spec[field] ?? (field === "base" || field === "webui");+ this.draft.tiers = JSON.stringify(result.spec.cost?.tiers ?? [], null, 2);+ this.advanced = false;+ }+ async loadRegistry() {+ const token = ++this.registryRequest;+ const response = await this.context.api("GET", "/api/model-registry");+ if (token !== this.registryRequest) return;+ if (!response.ok) {+ this.registryMessage = "Could not load models.";+ this.registryTone = "err";+ this.draw();+ return;+ }+ this.templates = response.data.templates || [];+ this.entries = (response.data.models || []).filter((row: Data) => !row.disabled);+ this.draw();+ }+ async load() {+ const token = ++this.request,+ view = this.context.view();+ const selection = { provider: this.provider, model: this.model, apiKey: this.apiKey };+ void this.loadRegistry().catch(() => {});+ const [models, slack, catalog, config] = await Promise.all([+ this.context.api("GET", "/api/model-providers?catalog=cached"),+ this.context.api("GET", "/api/slack-installation"),+ this.context.api("GET", "/api/connector-catalog"),+ this.context.api("GET", "/api/scopes/" + encodeURIComponent(this.context.orgScope()) + "?view=onboarding"),+ ]);+ if (token !== this.request || view !== this.context.view()) return;+ if (!models.ok || !slack.ok || !catalog.ok || !config.ok) {+ this.providerMessage = "Setup status could not be loaded. Try again.";+ this.providerTone = "err";+ this.draw();+ return;+ }+ this.providers = models.data.providers || [];+ this.models = {};+ this.mergeModels([+ ...(models.data.models || []),+ ...(config.data.baseModelOptions || []),+ ...Object.values(config.data.modelsByHarness || {}).flat(),+ ]);+ const baseModel = config.data.baseModel || config.data.baseModelDefault || "";+ const provider =+ Object.entries(this.models).find(([, choices]) => choices.some((model) => model.id === baseModel))?.[0] ||+ this.providers.find((row) => row.configured)?.provider ||+ this.providers[0]?.provider ||+ "";+ const status = this.providers.find((row) => row.provider === provider);+ const harnessAuth = models.data.harnessAuth;+ const harnessReady = Boolean(harnessAuth && harnessAuth.provider === provider);+ const ready = Boolean(baseModel) && (Boolean(status?.configured) || harnessReady);+ let summary = "No base model is configured yet. Pick a provider and model below.";+ if (baseModel) {+ summary = baseModel + " cannot run until its " + this.label(provider) + " key is configured.";+ if (harnessReady)+ summary = baseModel + " · authenticated by the " + harnessAuth.harnessId + " harness — no API key needed.";+ if (status?.configured)+ summary = baseModel + " · " + (status.source === "admin" ? "admin-managed key" : "deployment key");+ }+ this.steps.model = { text: ready ? "Ready" : "Needs a key", tone: ready ? "ok" : "warn", summary };+ if (selection.provider === this.provider && selection.model === this.model && selection.apiKey === this.apiKey) {+ this.provider = provider || this.providers[0]?.provider || "anthropic";+ this.model = (this.models[this.provider] || []).some((m) => m.id === baseModel)+ ? baseModel+ : this.models[this.provider]?.[0]?.id || "";+ } else if (!this.model) this.model = this.models[this.provider]?.[0]?.id || "";+ this.steps.slack = {+ text: slack.data.configured ? "Connected" : "Optional",+ tone: slack.data.configured ? "ok" : "muted",+ summary: slack.data.configured+ ? "Connected to " + (slack.data.teamName || slack.data.teamId || "a Slack workspace") + "."+ : "Create the Slack app, install it, then add its bot and Socket Mode tokens.",+ url: slack.data.createUrl || "https://api.slack.com/apps?new_app=1",+ };+ const configured = (catalog.data.catalog || []).filter((item: Data) => item.configured);+ this.steps.oauth = {+ text: configured.length ? configured.length + " configured" : "Optional",+ tone: configured.length ? "ok" : "muted",+ summary: configured.length+ ? configured.map((item: Data) => this.context.connectorName(item.provider)).join(", ") ++ " available in the web UI."+ : "Add Google, GitHub, Notion, or other OAuth clients to make those connectors available.",+ };+ this.context.loaded();+ this.draw();+ if (models.data.modelCatalogRefreshing)+ void this.context+ .api("GET", "/api/model-providers")+ .then((fresh: Data) => {+ if (!fresh.ok || token !== this.request || view !== this.context.view()) return;+ this.mergeModels(fresh.data.models || []);+ this.draw();+ })+ .catch(() => {});+ }+ mergeModels(models: Data[]) {+ for (const model of models) {+ if (!model.provider) continue;+ const options = (this.models[model.provider] ||= []);+ if (!options.some((option) => option.id === model.id)) options.push(model);+ }+ }+ async connect() {+ if (this.providerBusy) return;+ const provider = this.provider,+ apiKey = this.apiKey.trim(),+ modelId = this.model;+ if (!apiKey) {+ this.providerMessage = "Enter the provider API key.";+ this.providerTone = "err";+ this.draw();+ return;+ }+ this.providerBusy = true;+ this.providerMessage = "Validating with " + this.context.connectorName(provider) + "…";+ this.providerTone = "saving";+ this.draw();+ try {+ const saved = await this.context.api("PUT", "/api/model-providers/" + encodeURIComponent(provider), { apiKey });+ if (!saved.ok) throw new Error(saved.data?.message || "The provider rejected this key.");+ const selected = await this.context.api(+ "PUT",+ "/api/scopes/" + encodeURIComponent(this.context.orgScope()) + "/base-model",+ { modelId },+ );+ this.apiKey = "";+ await this.load();+ await this.context.loadCustomProviders();+ this.providerMessage = selected.ok+ ? "Key and base model saved."+ : "Key saved, but the base model could not be changed.";+ this.providerTone = selected.ok ? "ok" : "err";+ } catch (error) {+ this.providerMessage = errorText(error);+ this.providerTone = "err";+ } finally {+ this.providerBusy = false;+ this.draw();+ }+ }+ async disableProvider() {+ if (this.providerBusy) return;+ const provider = this.provider;+ if (+ !confirm(+ "Disable the " ++ this.context.connectorName(provider) ++ " model key? Models from this provider will stop working.",+ )+ )+ return;+ this.providerBusy = true;+ this.draw();+ try {+ const response = await this.context.api("DELETE", "/api/model-providers/" + encodeURIComponent(provider));+ if (!response.ok) throw new Error(response.data?.message || "Could not disable this provider.");+ await this.load();+ await this.context.loadCustomProviders();+ this.providerMessage = "Provider disabled.";+ this.providerTone = "ok";+ } catch (error) {+ this.providerMessage = errorText(error);+ this.providerTone = "err";+ } finally {+ this.providerBusy = false;+ this.draw();+ }+ }+ async lookupModel() {+ if (this.registryBusy) return;+ this.resetLookup();+ const token = this.lookupRequest;+ this.lookingUp = true;+ this.registryMessage = "Looking up exact model metadata…";+ this.draw();+ try {+ const response = await this.context.api("POST", "/api/model-registry/lookup", {+ provider: this.registryProvider,+ id: this.registryId.trim(),+ });+ if (token !== this.lookupRequest) return;+ if (!response.ok) throw new Error(response.data?.message || "Lookup failed. Try again.");+ this.showLookup(response.data);+ this.registryMessage = "Metadata loaded. Review, then verify access.";+ } catch (error) {+ if (token === this.lookupRequest) {+ this.registryMessage = errorText(error);+ this.registryTone = "err";+ }+ } finally {+ if (token === this.lookupRequest) {+ this.lookingUp = false;+ this.draw();+ }+ }+ }+ async deleteModel(spec: Data) {+ if (this.registryBusy || !confirm("Delete " + spec.name + "? New uses will be refused.")) return;+ this.registryBusy = true;+ this.draw();+ try {+ const response = await this.context.api("DELETE", "/api/model-registry/" + encodeURIComponent(spec.id));+ if (!response.ok) throw new Error(response.data?.message || "Could not delete model.");+ await this.load();+ this.registryBusy = false;+ this.reset();+ this.registryMessage = "Model deleted.";+ this.registryTone = "ok";+ } catch (error) {+ this.registryMessage = errorText(error);+ this.registryTone = "err";+ } finally {+ this.registryBusy = false;+ this.draw();+ }+ }+ collect() {+ if (!this.lookup) throw new Error("Look up the model first.");+ const identity = { provider: this.registryProvider, id: this.registryId.trim() };+ if (JSON.stringify(identity) !== JSON.stringify(this.lookup.identity))+ throw new Error("Look up the current model before verifying.");+ if (this.lookup.kind === "builtin") return { provider: identity.provider, verify: true };+ const value = (field: string) => String(this.draft[field] ?? "").trim();+ const number = (field: string) => {+ if (!value(field)) throw new Error(field + " is required");+ const n = Number(value(field));+ if (!Number.isFinite(n)) throw new Error(field + " must be a number");+ return n;+ };+ if (!value("name") || !value("template")) throw new Error("Display name and a compatible template are required.");+ return {+ ...identity,+ name: value("name"),+ template: value("template"),+ contextWindow: number("contextWindow"),+ maxTokens: number("maxTokens"),+ cost: {+ ...Object.fromEntries(["input", "output", "cacheRead", "cacheWrite"].map((field) => [field, number(field)])),+ tiers: JSON.parse(value("tiers") || "[]"),+ },+ ...Object.fromEntries(Object.keys(flagLabels).map((field) => [field, this.draft[field]])),+ verify: true,+ };+ }+ async verify() {+ if (this.registryBusy || !this.lookup) return;+ try {+ const body = this.collect(),+ builtin = this.lookup.kind === "builtin",+ id = this.registryId.trim();+ this.registryBusy = true;+ this.registryMessage = "Checking the model with organization credentials…";+ this.registryTone = "";+ this.draw();+ const response = await this.context.api(+ builtin ? "POST" : "PUT",+ "/api/model-registry/" + encodeURIComponent(id) + (builtin ? "/enable" : ""),+ body,+ );+ if (!response.ok) throw new Error(response.data?.message || "Could not verify model.");+ await this.load();+ this.registryMessage = builtin+ ? response.data.message+ : "Model verified and enabled with organization credentials. Personal-key access may differ.";+ this.registryTone = "ok";+ } catch (error) {+ this.registryMessage = errorText(error);+ this.registryTone = "err";+ } finally {+ this.registryBusy = false;+ this.draw();+ }+ }+ field(name: string) {+ const change = (e: Event) => {+ this.draft[name] = (e.target as HTMLInputElement).value;+ this.draw();+ };+ let input = html`<input+ id=${"model-registry-" + name}+ type="number"+ min=${(() => {+ if (name === "contextWindow") return "2";+ return name === "maxTokens" ? "1" : "0";+ })()}+ step=${name === "contextWindow" || name === "maxTokens" ? "1" : "any"}+ required+ .value=${this.draft[name] || ""}+ ?disabled=${this.registryBusy}+ @input=${change}+ />`;+ if (name === "name")+ input = html`<input+ type="text"+ id="model-registry-name"+ autocomplete="off"+ required+ .value=${this.draft.name || ""}+ ?disabled=${this.registryBusy}+ @input=${change}+ />`;+ if (name === "template")+ input = html`<select+ id="model-registry-template"+ .value=${this.draft.template || ""}+ ?disabled=${this.registryBusy}+ @change=${change}+ >+ <option value="">Choose a compatible template</option>+ ${this.templates.filter((t) => t.provider === this.registryProvider).map((t) => html`<option value=${t.id} .selected=${t.id === this.draft.template}>${t.name}</option>`)}+ </select>`;+ return html`<label>${fieldLabels[name]} ${input}</label>`;+ }+ template(kind: string) {+ if (kind === "steps")+ return html`<div class="setup-grid">+ ${["model", "slack", "oauth"].map(+ (key, i) =>+ html`<section class="setup-step">+ <span class=${"badge " + this.steps[key].tone} id=${"onboarding-" + key + "-badge"}+ >${this.steps[key].text}</span+ >+ <h2>${["1. Model provider", "2. Slack app", "3. OAuth apps"][i]}</h2>+ <p id=${"onboarding-" + key + "-summary"}>${this.steps[key].summary}</p>+ ${key === "slack" ? html`<div class="foot"><a class="header-button" id="onboarding-slack-create" href=${this.steps.slack.url} target="_blank" rel="noopener noreferrer">Create Slack app ↗</a><button type="button" data-onboarding-target="slack" @click=${() => this.context.navigate("slack")}>Enter Slack tokens</button></div>` : nothing}${key === "oauth" ? html`<div class="foot"><button type="button" data-onboarding-target="oauth" @click=${() => this.context.navigate("oauth")}>Configure OAuth apps</button></div>` : nothing}+ </section>`,+ )}+ </div>`;+ if (kind === "provider") {+ const choices = this.providers.length+ ? this.providers+ : Object.keys(providerLabels).map((provider) => ({ provider, configured: false }));+ const status = this.providers.find((p) => p.provider === this.provider);+ return html`<section class="card">+ <div class="head">+ <h2>Base model</h2>+ <p>+ Choose a supported provider and model. Saving validates the key, stores it write-only, and makes the+ selected model the organization default.+ </p>+ </div>+ <div class="body setup-form">+ <label+ >Provider+ <select+ id="onboarding-model-provider"+ .value=${this.provider}+ ?disabled=${this.providerBusy}+ @change=${(e: Event) => {+ this.provider = (e.target as HTMLSelectElement).value;+ this.model = this.models[this.provider]?.[0]?.id || "";+ this.draw();+ }}+ >+ ${choices.map((p) => html`<option value=${p.provider} .selected=${p.provider === this.provider}>${this.label(p.provider) + (p.configured ? " (key configured)" : "")}</option>`)}+ </select></label+ ><label+ >Base model+ <select+ id="onboarding-model-id"+ .value=${this.model}+ ?disabled=${this.providerBusy}+ @change=${(e: Event) => {+ this.model = (e.target as HTMLSelectElement).value;+ this.draw();+ }}+ >+ ${(this.models[this.provider] || []).map((model) => html`<option value=${model.id} .selected=${model.id === this.model}>${model.name}</option>`)}+ </select></label+ ><label+ >API key+ <input+ type="password"+ id="onboarding-model-key"+ autocomplete="off"+ placeholder=${status?.configured ? "•••• set, enter a replacement" : "Write-only API key"}+ .value=${this.apiKey}+ ?disabled=${this.providerBusy}+ @input=${(e: Event) => {+ this.apiKey = (e.target as HTMLInputElement).value;+ this.draw();+ }}+ /></label>+ </div>+ <div class="foot">+ <button+ class="primary"+ id="onboarding-model-save"+ ?disabled=${this.providerBusy}+ @click=${() => this.connect()}+ >+ Validate and connect</button+ ><button+ class="danger"+ id="onboarding-model-delete"+ ?disabled=${this.providerBusy || !status || status.source === "absent"}+ @click=${() => this.disableProvider()}+ >+ Disable this provider</button+ ><span class=${"status" + (this.providerTone ? " " + this.providerTone : "")} id="st-onboarding-model"+ >${this.providerMessage}</span+ >+ </div>+ </section>`;+ }+ return this.registryTemplate();+ }+ registryTemplate() {+ const lookup = this.lookup,+ spec = lookup?.spec || {},+ missing: string[] = lookup?.missing || [];+ const template = this.templates.find((t) => t.id === this.draft.template);+ const identityChange = (key: "registryId" | "registryProvider") => (e: Event) => {+ this[key] = (e.target as HTMLInputElement).value;+ this.resetLookup();+ this.draw();+ };+ let summary = spec.name || spec.id;+ if (lookup?.kind === "builtin")+ summary = `${spec.name} · ${spec.contextWindow.toLocaleString()} context tokens · ${spec.maxTokens.toLocaleString()} maximum output · $${spec.cost.input} input / $${spec.cost.output} output per million tokens`;+ return html`<section class="card">+ <div class="head">+ <h2>Models on existing providers</h2>+ <p>+ Start with a provider and model ID. We look up exact catalog or provider metadata before asking for any+ missing details. Organization credentials are inherited; subscription support is not implied.+ </p>+ </div>+ <div class="body">+ <table class="table">+ <thead>+ <tr>+ <th>Model</th>+ <th>Provider</th>+ <th>Template</th>+ <th></th>+ </tr>+ </thead>+ <tbody id="model-registry-rows">+ ${this.entries.map(({ spec, unavailableReason, verifiedAt }) => {+ let verification = " — Not verified";+ if (verifiedAt)+ verification = " — Verified with organization credentials " + new Date(verifiedAt).toLocaleString();+ if (unavailableReason) verification = " — " + unavailableReason;+ return html`<tr>+ <td>${(spec.name || spec.id) + " (" + spec.id + ")" + verification}</td>+ <td>${spec.provider || "Unknown"}</td>+ <td>${spec.template || "Missing"}</td>+ <td>+ <button ?disabled=${this.registryBusy} @click=${() => this.reset(spec)}>Edit</button+ ><button class="danger" ?disabled=${this.registryBusy} @click=${() => this.deleteModel(spec)}>+ Delete+ </button>+ </td>+ </tr>`;+ })}+ </tbody>+ </table>+ <p class="muted" id="model-registry-empty" ?hidden=${this.entries.length > 0}>No additional models.</p>+ </div>+ <div class="body setup-form">+ <label+ >Provider+ <select+ id="model-registry-provider"+ .value=${this.registryProvider}+ ?disabled=${this.registryBusy || this.providerLocked}+ @change=${identityChange("registryProvider")}+ >+ <option value="openai" .selected=${this.registryProvider === "openai"}>OpenAI</option>+ <option value="anthropic" .selected=${this.registryProvider === "anthropic"}>Anthropic</option>+ </select></label+ ><label+ >Model ID+ <input+ type="text"+ id="model-registry-id"+ autocomplete="off"+ placeholder="e.g. claude-opus-4-6"+ required+ .value=${this.registryId}+ ?disabled=${this.registryBusy || this.editing}+ @input=${identityChange("registryId")}+ /></label>+ </div>+ <div class="foot">+ <button+ id="model-registry-lookup"+ class="primary"+ ?disabled=${this.registryBusy || this.lookingUp}+ @click=${() => this.lookupModel()}+ >+ Look up model+ </button>+ </div>+ <div class="body" id="model-registry-result" ?hidden=${!lookup}>+ <p id="model-registry-source" class="muted">+ ${lookup ? "Source: " + lookup.source + (lookup.catalogGeneratedAt ? " · catalog " + new Date(lookup.catalogGeneratedAt).toLocaleDateString() : "") : ""}+ </p>+ <p id="model-registry-summary">${summary}</p>+ <p id="model-registry-lookup-note" class="muted">${lookup?.message || ""}</p>+ <div id="model-registry-missing" ?hidden=${!missing.length}>+ <h3>Complete missing information</h3>+ <p class="muted">+ These fields were not available from the exact model record. Use the provider's documentation; choose a+ compatible template explicitly.+ </p>+ <div class="setup-form" id="model-registry-missing-fields">+ ${Object.keys(fieldLabels)+ .filter((key) => missing.includes(key))+ .map((key) => this.field(key))}+ </div>+ </div>+ <details+ id="model-registry-advanced"+ ?hidden=${lookup?.kind === "builtin"}+ .open=${this.advanced}+ @toggle=${(e: Event) => {+ this.advanced = (e.target as HTMLDetailsElement).open;+ }}+ >+ <summary>Advanced overrides</summary>+ <p class="muted">+ Review imported values or override them. Pricing is per million tokens. Overrides require verification+ again.+ </p>+ <div class="setup-form" id="model-registry-advanced-fields">+ ${Object.keys(fieldLabels)+ .filter((key) => !missing.includes(key))+ .map((key) => this.field(key))}+ <p class="muted" id="model-registry-capabilities">+ ${template ? `Inherited: ${template.input.join(", ")} input; reasoning ${template.reasoning ? "yes" : "no"}.` : ""}+ </p>+ ${Object.entries(flagLabels).map(+ ([key, label]) =>+ html`<label class="check"+ ><input+ id=${"model-registry-" + key}+ type="checkbox"+ .checked=${this.draft[key] ?? (key === "base" || key === "webui")}+ ?disabled=${this.registryBusy}+ @change=${(e: Event) => {+ this.draft[key] = (e.target as HTMLInputElement).checked;+ this.draw();+ }}+ />+ ${label}</label+ >`,+ )}+ <details>+ <summary>Advanced pricing tiers</summary>+ <label+ >JSON array of inputTokensAbove, input, output, cacheRead and cacheWrite<textarea+ id="model-registry-tiers"+ rows="4"+ placeholder="[]"+ .value=${this.draft.tiers || ""}+ ?disabled=${this.registryBusy}+ @input=${(e: Event) => {+ this.draft.tiers = (e.target as HTMLTextAreaElement).value;+ this.draw();+ }}+ ></textarea>+ </label>+ </details>+ </div>+ </details>+ </div>+ <p class="muted" id="model-registry-verification-notice">+ Verify and enable sends a synthetic connection check using the organization's serving credentials. It may incur+ a small provider charge (up to 128 output tokens per request; an additional check with fast mode; provider+ retries may apply). A successful check confirms access now, not pricing, maximum context, every capability, or+ personal-key access. Failed checks do not save or enable the new definition. Existing saved settings remain+ unchanged. A failed recheck of those settings removes their verification.+ </p>+ <div class="foot">+ <button+ class="primary"+ id="model-registry-save"+ ?disabled=${!lookup || this.registryBusy}+ @click=${() => this.verify()}+ >+ ${(() => {+ if (this.registryBusy) return "Verifying…";+ return lookup?.kind === "builtin" ? "Verify and enable existing model" : "Verify and enable";+ })()}</button+ ><button id="model-registry-new" ?disabled=${this.registryBusy} @click=${() => this.reset()}>New model</button+ ><span class=${"status" + (this.registryTone ? " " + this.registryTone : "")} id="st-model-registry"+ >${this.registryMessage}</span+ >+ </div>+ </section>`;+ }+}+const controller = new Onboarding();+export const mount = () => controller.mount();+export const configure = (context: Data) => {+ controller.context = context;+};+export const load = () => controller.load();diff --git a/plugins/admin/ui/setting-controls.ts b/plugins/admin/ui/setting-controls.tsnew file mode 100644index 000000000..a139a42e8--- /dev/null+++ b/plugins/admin/ui/setting-controls.ts@@ -0,0 +1,50 @@+import { ifDefined } from "lit/directives/if-defined.js";+import { html } from "lit";+import { classMap } from "lit/directives/class-map.js";+import type { SettingState } from "./setting-state.ts";++export function saveButton(s: SettingState, label = "Apply", disabled = false) {+ return html`<button+ class=${classMap({ primary: true, dirty: s.dirty })}+ data-save=${s.key}+ ?disabled=${!s.dirty || s.saving || disabled}+ >+ ${label}+ </button>`;+}++export function settingStatus(s: Pick<SettingState, "message" | "tone"> & { key?: string }, id = "st-" + s.key) {+ return html`<span class=${classMap({ status: true, [s.tone]: !!s.tone })} id=${id}>${s.message}</span>`;+}++export function saveFooter(s: SettingState, label = "Apply", disabled = false) {+ return html`<div class="foot">${saveButton(s, label, disabled)}${settingStatus(s)}</div>`;+}++export function choiceGroup(+ options: {+ name: string;+ value: string;+ onChange: (event: Event) => void;+ choiceFor?: string;+ checkboxFor?: string;+ },+ choices: [value: string, title: string, description: string][],+) {+ return html`<div class="choice-stack">+ ${choices.map(+ ([value, title, description]) =>+ html`<label class="posture-choice"+ ><input+ type="radio"+ name=${options.name}+ value=${value}+ data-choice-for=${ifDefined(options.choiceFor)}+ data-checkbox-for=${ifDefined(options.checkboxFor)}+ .checked=${options.value === value}+ @change=${options.onChange}+ /><span><strong>${title}</strong><small>${description}</small></span></label+ >`,+ )}+ </div>`;+}diff --git a/plugins/admin/ui/setting-state.ts b/plugins/admin/ui/setting-state.tsnew file mode 100644index 000000000..bbf4d6547--- /dev/null+++ b/plugins/admin/ui/setting-state.ts@@ -0,0 +1,57 @@+export class SettingState {+ key: string;+ draft: Record<string, any> = {};+ baseline = "{}";+ available = false;+ saving = false;+ message = "";+ tone = "";+ render = () => {};+ constructor(key: string) {+ this.key = key;+ }+ collect(_validate = true): Record<string, any> {+ return structuredClone(this.draft);+ }+ get dirty() {+ return JSON.stringify(this.collect(false)) !== this.baseline;+ }+ changed() {+ if (!this.saving) {+ this.message = this.dirty ? "Unsaved changes" : "";+ this.tone = this.dirty ? "dirty" : "";+ }+ this.render();+ }+ commit(body: unknown) {+ this.baseline = JSON.stringify(body);+ this.saving = false;+ this.message = this.dirty ? "Unsaved changes" : "Saved";+ this.tone = this.dirty ? "dirty" : "ok";+ this.render();+ }+}++export function settingRegistry<T extends SettingState>(states: Map<string, T>) {+ return {+ owns: (key: string) => states.has(key),+ collect: (key: string) => states.get(key)!.collect(),+ capture(key: string) {+ const state = states.get(key)!;+ state.baseline = JSON.stringify(state.collect(false));+ state.changed();+ },+ commit: (key: string, body: unknown) => states.get(key)!.commit(body),+ status(key: string, message: string, tone = "") {+ const state = states.get(key)!;+ state.message = message;+ state.tone = tone;+ state.saving = tone === "saving";+ state.render();+ },+ statusKey(id: string) {+ const key = id.replace(/^st-/, "");+ return states.has(key) ? key : undefined;+ },+ };+}diff --git a/plugins/admin/ui/settings-branding.ts b/plugins/admin/ui/settings-branding.tsnew file mode 100644index 000000000..36079c938--- /dev/null+++ b/plugins/admin/ui/settings-branding.ts@@ -0,0 +1,73 @@+import { html } from "lit";+import { classMap } from "lit/directives/class-map.js";+import { saveFooter } from "./setting-controls.ts";+import type { SettingsState } from "./settings.ts";++export function brandingCard(s: SettingsState) {+ return html`<section+ class=${classMap({ card: true, "sv-customize": true, "setting-row": true, hidden: !s.available, dirty: s.dirty })}+ id="card-branding"+ >+ <div class="head">+ <h2>Branding</h2>+ <p>+ How this org's surfaces look. Accent is the highlight color across the web UI, admin, and portal; icon is the+ square image beside the name in the top left; mark is a 1–2 character badge drawn over that icon instead; label+ is the assistant's name everywhere it introduces itself; organization name is how the assistant refers to this+ org. Leave a field blank to use the deployment default.+ </p>+ </div>+ <div class="body">+ <label for="branding-accent">Accent color</label>+ <input+ type="text"+ id="branding-accent"+ style="max-width: 200px"+ placeholder="#4f46e5"+ .value=${s.draft.accent || ""}+ @input=${(e: Event) => s.change("accent", (e.target as HTMLInputElement).value)}+ />+ <label for="branding-mark-url" style="margin-top: 12px">Brand icon (https image URL)</label>+ <input+ type="url"+ id="branding-mark-url"+ style="max-width: 420px"+ maxlength="500"+ placeholder="https://example.com/icon.png"+ .value=${s.draft.markUrl || ""}+ @input=${(e: Event) => s.change("markUrl", (e.target as HTMLInputElement).value)}+ />+ <label for="branding-mark" style="margin-top: 12px">Brand mark (1–2 chars)</label>+ <input+ type="text"+ id="branding-mark"+ style="max-width: 200px"+ maxlength="2"+ placeholder="A"+ .value=${s.draft.mark || ""}+ @input=${(e: Event) => s.change("mark", (e.target as HTMLInputElement).value)}+ />+ <label for="branding-self-label" style="margin-top: 12px">Assistant label</label>+ <input+ type="text"+ id="branding-self-label"+ style="max-width: 320px"+ maxlength="40"+ placeholder="Agent"+ .value=${s.draft.selfLabel || ""}+ @input=${(e: Event) => s.change("selfLabel", (e.target as HTMLInputElement).value)}+ />+ <label for="branding-org-name" style="margin-top: 12px">Organization name</label>+ <input+ type="text"+ id="branding-org-name"+ style="max-width: 320px"+ maxlength="40"+ placeholder="Acme Corp"+ .value=${s.draft.orgName || ""}+ @input=${(e: Event) => s.change("orgName", (e.target as HTMLInputElement).value)}+ />+ </div>+ ${saveFooter(s)}+ </section>`;+}diff --git a/plugins/admin/ui/settings-credentials.ts b/plugins/admin/ui/settings-credentials.tsnew file mode 100644index 000000000..e4a62e6f7--- /dev/null+++ b/plugins/admin/ui/settings-credentials.ts@@ -0,0 +1,684 @@+import { mountTemplate } from "./shared.ts";+import { html, render } from "lit";+import { classMap } from "lit/directives/class-map.js";+import { repeat } from "lit/directives/repeat.js";+let config: any = { label: (id: string) => id, formatTime: String, edit: () => {}, remove: () => {} };+type Data = Record<string, any>;+export class CredentialState {+ draft: Data = {};+ rows: Data[] = [];+ listMessage = "Loading credentials…";+ listRetry = false;+ directory: Data[] = [];+ channels: Data[] = [];+ scopes: Data[] = [];+ scope = "";+ editing: string | null = null;+ version: number | null = null;+ original: Data | null = null;+ open = false;+ saving = false;+ message = "";+ tone = "";+ baseline = "";+ query = "";+ picker = false;+ resolutionError = "";+ render = () => {};+ constructor() {+ this.reset();+ }+ reset() {+ this.editing = null;+ this.version = null;+ this.original = null;+ this.open = false;+ this.query = "";+ this.picker = false;+ this.saving = false;+ this.message = "";+ this.tone = "";+ this.draft = {+ slug: "",+ name: "",+ delivery: "broker",+ envkey: "",+ host: "",+ secret: "",+ header: "",+ scheme: "",+ methods: "",+ paths: "",+ enabled: true,+ deployments: true,+ org: true,+ people: "",+ };+ this.baseline = JSON.stringify(this.collect());+ this.render();+ }+ begin(c: Data | null) {+ this.reset();+ this.open = true;+ if (c) {+ this.editing = c.slug;+ this.version = c.updatedAt;+ this.original = c;+ const org = (c.grantees || []).some((g: string) => g.startsWith("org:"));+ this.draft = {+ slug: c.slug,+ name: c.name,+ delivery: c.delivery || "broker",+ envkey: c.envKey || "",+ host: c.host || "",+ secret: "",+ header: c.injection?.header || "",+ scheme: c.injection?.scheme || "",+ methods: (c.allowedMethods || []).join(", "),+ paths: (c.allowedPathPrefixes || []).join("\n"),+ enabled: c.enabled !== false,+ deployments: c.deployments !== false,+ org,+ people: org+ ? ""+ : (c.grantees || []).map((g: string) => (g.startsWith("personal:") ? g.slice(9) : g)).join(", "),+ };+ }+ this.baseline = JSON.stringify(this.collect());+ this.render();+ }+ commit(body: Data) {+ const fresh = this.rows.find((row) => row.slug === body.slug);+ if (fresh) {+ if (this.draft.slug.trim() === body.slug) this.editing = body.slug;+ this.version = fresh.updatedAt;+ this.original = fresh;+ }+ const saved = { ...body };+ if (this.editing && this.version != null) saved.expectedUpdatedAt = this.version;+ if (this.draft.secret === body.secret) this.draft.secret = "";+ delete saved.secret;+ this.baseline = JSON.stringify(saved);+ this.saving = false;+ this.changed();+ }+ change(key: string, value: unknown) {+ this.draft[key] = value;+ this.changed();+ }+ changed() {+ if (!this.saving) {+ this.message = this.dirty ? "Unsaved changes" : "";+ this.tone = "";+ }+ this.render();+ }+ get dirty() {+ return JSON.stringify(this.collect()) !== this.baseline;+ }+ get selected(): string[] {+ return this.draft.people+ .split(",")+ .map((x: string) => x.trim())+ .filter(Boolean);+ }+ grantees(): string[] {+ this.resolutionError = "";+ if (this.draft.org) return [this.scope];+ return this.selected.map((id) => {+ if (/^(personal|team|org|channel|group):/.test(id)) return id;+ const q = id.toLowerCase();+ const exact = this.directory.filter((m) => m.principalId.toLowerCase() === q || m.slackId?.toLowerCase() === q);+ if (exact.length === 1) return "personal:" + exact[0].principalId;+ const names = this.directory.filter((m) => m.displayName.toLowerCase() === q);+ if (names.length === 1) return "personal:" + names[0].principalId;+ if (names.length > 1 || exact.length > 1)+ this.resolutionError = "“" + id + "” matches multiple people. Use an exact principal ID.";+ return "personal:" + id;+ });+ }+ collect() {+ const d = this.draft;+ const env = d.delivery === "env";+ const actor = this.original?.injection?.actor;+ return {+ slug: d.slug.trim(),+ name: d.name.trim(),+ delivery: env ? "env" : "broker",+ ...(env ? { envKey: d.envkey.trim() } : {}),+ host: env ? "" : d.host.trim(),+ ...(d.secret ? { secret: d.secret } : {}),+ injection: {+ ...(typeof actor === "boolean" ? { actor } : {}),+ ...(d.header.trim() ? { header: d.header.trim() } : {}),+ ...(d.scheme ? { scheme: d.scheme } : {}),+ },+ allowedMethods: d.methods+ .split(",")+ .map((x: string) => x.trim())+ .filter(Boolean),+ allowedPathPrefixes: d.paths+ .split("\n")+ .map((x: string) => x.trim())+ .filter(Boolean),+ enabled: d.enabled,+ deployments: env ? true : d.deployments,+ grantees: env ? [this.scope] : this.grantees(),+ ...(this.editing && this.version != null ? { expectedUpdatedAt: this.version } : {}),+ };+ }+ validate(body: Data) {+ if (!body.slug) return "Slug is required.";+ if (!body.name) return "Name is required.";+ if (body.delivery === "env") {+ if (!body.envKey) return "Env delivery needs an env var name.";+ if (!/^[A-Z][A-Z0-9_]*$/.test(body.envKey)) return "Env var must be UPPER_SNAKE_CASE.";+ if (body.envKey.startsWith("AGENT_")) return "AGENT_* env vars are reserved for the platform.";+ } else if (!body.host) return "Host is required.";+ if (body.delivery !== "env" && !this.draft.org && !body.grantees.length)+ return "Add at least one person or choose org-wide access.";+ if (body.delivery !== "env" && this.resolutionError) return this.resolutionError;+ const unsupported = body.grantees.find((g: string) => g.startsWith("group:") || /^personal:[^,]*:/.test(g));+ if (unsupported)+ return (+ "Remove unsupported legacy grant “" ++ unsupported ++ "” before saving. Shared credentials support people, teams, channels, or the organization."+ );+ return "";+ }+ capability() {+ const d = this.draft;+ const env = d.delivery === "env";+ const b = this.collect();+ const disabled = env ? "Disabled: never injected" : "Disabled: broker requests refused";+ const envHost = d.envkey.trim() ? "Sandbox env $" + d.envkey.trim() : "Env var not set";+ const brokerHost = d.host.trim() ? d.host.trim() + " and its subdomains" : "Not set";+ const brokerPaths = b.allowedPathPrefixes.length ? b.allowedPathPrefixes.join(", ") : "Any path on this host";+ const storedSecret = this.original?.hasSecret ? "Stored secret retained" : "Required before first save";+ return {+ state: d.enabled ? "Enabled" : disabled,+ host: env ? envHost : brokerHost,+ auth: env+ ? "Injected into all-internal conversations; rooms with externals get nothing"+ : (d.header.trim() || "Authorization") + " header · prefix “" + (d.scheme || "Bearer") + "”",+ methods: env+ ? "None"+ : (b.allowedMethods.length ? b.allowedMethods.map((m: string) => m.toUpperCase()) : ["GET"]).join(", "),+ paths: env ? "Never served by the credential broker" : brokerPaths,+ principals: env+ ? "Every all-internal conversation; grants don't gate env delivery"+ : (b.grantees.map(config.label).join(", ") || "No principal selected") ++ (d.deployments ? " · published apps, acting as their publisher" : " · switched off for published apps"),+ secret: d.secret ? "Will replace the stored secret" : storedSecret,+ };+ }+}+export const credentialState = new CredentialState();+export function configureCredentials(options: any) {+ config = options;+}+export function credentialStatus(message: string, tone: string) {+ credentialState.message = message;+ credentialState.tone = tone;+ credentialState.saving = tone === "saving";+ credentialState.render();+}+export function credentialLoading(message = "Loading credentials…", retry = false) {+ credentialState.rows = [];+ credentialState.listMessage = message;+ credentialState.listRetry = retry;+ credentialState.render();+}+export function loadCredentials(rows: Data[], directory: Data[], channels: Data[], scopes: Data[], scope: string) {+ Object.assign(credentialState, { rows, directory, channels, scopes, scope, listMessage: "", listRetry: false });+ if (!credentialState.open) credentialState.baseline = JSON.stringify(credentialState.collect());+ credentialState.render();+}+const plural = (n: number, label: string) => n + " " + label + (n === 1 ? "" : "s");+const badge = (text: string, tone: string) => html`<span class=${"badge " + tone}>${text}</span>`;+function credentialUsage(c: Data) {+ if (c.usageUnavailable) return "Usage unavailable";+ if (c.usageCount == null) return "Loading usage…";+ return (+ (c.usageTruncated ? "at least " : "") ++ plural(c.usageCount, "successful use") ++ (c.usageCount ? " since " + config.formatTime(c.usageSince) : " in retained broker history")+ );+}+function credentialRows() {+ if (credentialState.listMessage)+ return html`${credentialState.listMessage}${credentialState.listRetry ? html`<button type="button" style="margin-inline-start: 8px" @click=${() => config.reload()}>Retry</button>` : null}`;+ return credentialState.rows.length+ ? repeat(+ credentialState.rows,+ (c) => c.slug,+ (c) => {+ const org = (c.grantees || []).some((g: string) => g.startsWith("org:"));+ const target =+ c.delivery === "env"+ ? "sandbox env $" + (c.envKey || "?")+ : c.host + " · " + (c.allowedMethods?.length ? c.allowedMethods.join("/") : "GET");+ return html`<div+ class=${classMap({ "credential-row": true, "is-editing": c.slug === credentialState.editing })}+ >+ <div class="credential-main">+ <div class="credential-title">+ <strong>${c.name || c.slug}</strong><span class="credential-slug">${c.slug}</span>+ </div>+ <div class="hint">${target + " · " + credentialUsage(c)}</div>+ <div class="credential-badges">+ ${badge(c.delivery === "env" ? "Env" : "Broker", "info")}${badge(c.enabled === false ? "Disabled" : "Enabled", c.enabled === false ? "warn" : "ok")}${badge(c.hasSecret ? "Secret set" : "Secret missing", c.hasSecret ? "ok" : "err")}${badge(org ? "Organization-wide" : plural((c.grantees || []).length, "principal"), org ? "info" : "muted")}${c.delivery !== "env" && c.deployments === false ? badge("No apps", "muted") : null}+ </div>+ </div>+ <div class="credential-actions">+ <button type="button" @click=${() => config.edit(c)}>Edit</button+ ><button+ type="button"+ class="rowbtn danger"+ title="Delete credential"+ aria-label=${"Delete " + (c.name || c.slug)}+ @click=${() => config.remove(c)}+ >+ Delete+ </button>+ </div>+ </div>`;+ },+ )+ : "No credentials configured.";+}+function pickerRows() {+ const s = credentialState;+ const selected = s.selected;+ const q = s.query.trim().toLowerCase();+ const people = s.directory.filter(+ (m) =>+ !selected.includes(m.principalId) &&+ (!q || [m.principalId, m.displayName || "", m.slackId || ""].some((v) => v.toLowerCase().includes(q))),+ );+ const channelMap = new Map(s.scopes.map((row) => [row.scopeId, row]));+ s.channels.forEach((c) =>+ channelMap.set("channel:" + c.channelId, { scopeId: "channel:" + c.channelId, label: c.name }),+ );+ const channels = [...channelMap.values()].filter(+ (c) =>+ c.scopeId.startsWith("channel:") &&+ !selected.includes(c.scopeId) &&+ (!q || [c.scopeId, c.label || ""].some((v) => v.toLowerCase().includes(q))),+ );+ const item = (id: string, label: string, checked: boolean) =>+ html`<div+ class="sc-picker-item"+ @mousedown=${(e: MouseEvent) => {+ e.preventDefault();+ s.change("people", (checked ? selected.filter((x) => x !== id) : [...selected, id]).join(", "));+ }}+ >+ <input type="checkbox" .checked=${checked} /><span>${label}</span>+ </div>`;+ return html`${+ selected.length+ ? html`<div class="sc-picker-group">Has access</div>+ ${selected.map((id) => item(id, config.label(id), true))}`+ : null+ }${+ people.length+ ? html`<div class="sc-picker-group">People</div>+ ${people.slice(0, 30).map((m) => item(m.principalId, m.displayName + " (" + m.principalId + ")", false))}`+ : null+ }${people.length > 30 ? html`<div class="sc-picker-more">${"…" + (people.length - 30) + " more — keep typing"}</div>` : null}${+ channels.length+ ? html`<div class="sc-picker-group">Channels</div>+ ${channels.slice(0, 15).map((c) => item(c.scopeId, c.label ? "#" + c.label.replace(/^#/, "") + " (" + c.scopeId + ")" : c.scopeId, false))}`+ : null+ }${channels.length > 15 ? html`<div class="sc-picker-more">${"…" + (channels.length - 15) + " more channels — keep typing"}</div>` : null}`;+}++function template() {+ const env = credentialState.draft.delivery === "env";+ const cap = credentialState.capability();+ return html` <section+ class=${classMap({ card: true, "sv-credentials": true, dirty: credentialState.dirty })}+ id="card-service-credentials"+ >+ <div class="head">+ <h2>Shared service credentials</h2>+ <p>+ The agent calls these services by proxy such that secrets never reach a sandbox. Review the complete effective+ capability (destination, authentication, methods, paths, and principals) before saving.+ </p>+ </div>+ <div class="body">+ <div id="sc-list" role="status" aria-live="polite" class=${credentialState.rows.length ? "" : "hint"}>+ ${credentialRows()}+ </div>+ </div>+ <div+ class=${classMap({ body: true, hidden: !credentialState.open })}+ id="sc-editor"+ style="border-top: 1px solid var(--border, #2a2a2a); padding-top: 12px"+ >+ <div class="sc-form-head">+ <p class="hint" id="sc-form-title">+ ${credentialState.editing ? "Editing " + credentialState.editing : "Add a credential"}+ </p>+ <span class=${"badge " + (credentialState.editing ? "info" : "muted")} id="sc-form-mode"+ >${credentialState.editing ? "Editing" : "New"}</span+ >+ </div>+ <div class="sc-semantics" aria-label="Blank value semantics">+ <div><strong>Blank secret</strong><span id="sc-secret-semantics">${secretSemantics()}</span></div>+ <div><strong>Blank method</strong><span>Uses the broker default: GET only.</span></div>+ <div><strong>Blank paths</strong><span>Allows every path on the selected host.</span></div>+ </div>+ <div class="editor-grid">+ <div>+ <label style="display: block; margin-bottom: 8px"+ >Slug <span class="hint">lowercase identifier</span+ ><input+ type="text"+ id="sc-slug"+ .value=${credentialState.draft.slug || ""}+ @input=${(e: Event) => credentialState.change("slug", (e.target as HTMLInputElement).value)}+ ?disabled=${!!credentialState.editing}+ placeholder="credential-name"+ autocomplete="off"+ style="width: 100%"+ /></label>+ <label style="display: block; margin-bottom: 8px"+ >Display name+ <input+ type="text"+ id="sc-name"+ .value=${credentialState.draft.name || ""}+ @input=${(e: Event) => credentialState.change("name", (e.target as HTMLInputElement).value)}+ placeholder="Credential display name"+ style="width: 100%"+ /></label>+ <label style="display: block; margin-bottom: 8px"+ >Delivery <span class="hint">how the secret is used</span>+ <select+ id="sc-delivery"+ .value=${credentialState.draft.delivery || ""}+ @input=${(e: Event) => credentialState.change("delivery", (e.target as HTMLInputElement).value)}+ style="width: 100%"+ >+ <option value="broker">+ Broker: core stamps it onto proxied HTTP calls; the secret never leaves core+ </option>+ <option value="env">+ Sandbox env: injected into all-internal conversations under an env var (e.g. a browser-provider key for+ the browse skill)+ </option>+ </select>+ </label>+ <label style="display: block; margin-bottom: 8px" class=${classMap({ "sc-env-only": true, hidden: !env })}+ >Env var <span class="hint">UPPER_SNAKE_CASE; the skill reads this</span+ ><input+ type="text"+ id="sc-envkey"+ .value=${credentialState.draft.envkey || ""}+ @input=${(e: Event) => credentialState.change("envkey", (e.target as HTMLInputElement).value)}+ placeholder="STEEL_API_KEY"+ autocomplete="off"+ style="width: 100%"+ /></label>+ <label style="display: block; margin-bottom: 8px" class=${classMap({ "sc-broker-only": true, hidden: env })}+ >Destination host <span class="hint">bare hostname only</span+ ><input+ type="text"+ id="sc-host"+ .value=${credentialState.draft.host || ""}+ @input=${(e: Event) => credentialState.change("host", (e.target as HTMLInputElement).value)}+ placeholder="service.example"+ autocomplete="off"+ style="width: 100%"+ /></label>+ <label style="display: block; margin-bottom: 8px"+ >Secret+ <input+ type="password"+ id="sc-secret"+ .value=${credentialState.draft.secret || ""}+ @input=${(e: Event) => credentialState.change("secret", (e.target as HTMLInputElement).value)}+ autocomplete="new-password"+ placeholder=${credentialState.original?.hasSecret ? "Stored secret retained when blank" : "Write-only secret"}+ style="width: 100%"+ /></label>+ <p class="field-hint" id="sc-secret-hint">${secretHint()}</p>+ <div class=${classMap({ "sc-broker-only": true, hidden: env })} style="display: flex; gap: 10px">+ <label style="display: block; margin-bottom: 8px; flex: 1"+ >Authentication header <span class="hint">blank = Authorization</span+ ><input+ type="text"+ id="sc-header"+ .value=${credentialState.draft.header || ""}+ @input=${(e: Event) => credentialState.change("header", (e.target as HTMLInputElement).value)}+ placeholder="Default: Authorization"+ style="width: 100%"+ /></label>+ <label style="display: block; margin-bottom: 8px; flex: 1"+ >Value prefix <span class="hint">blank = Bearer</span+ ><input+ type="text"+ id="sc-scheme"+ .value=${credentialState.draft.scheme || ""}+ @input=${(e: Event) => credentialState.change("scheme", (e.target as HTMLInputElement).value)}+ placeholder="Default: Bearer"+ style="width: 100%"+ /></label>+ </div>+ <label style="display: block; margin-bottom: 8px" class=${classMap({ "sc-broker-only": true, hidden: env })}+ >Allowed HTTP methods <span class="hint">comma-separated; blank = GET</span+ ><input+ type="text"+ id="sc-methods"+ .value=${credentialState.draft.methods || ""}+ @input=${(e: Event) => credentialState.change("methods", (e.target as HTMLInputElement).value)}+ placeholder="GET"+ style="width: 100%"+ /></label>+ <label style="display: block; margin-bottom: 8px" class=${classMap({ "sc-broker-only": true, hidden: env })}+ >Allowed path prefixes <span class="hint">one per line; blank = any path</span+ ><textarea+ id="sc-paths"+ .value=${credentialState.draft.paths || ""}+ @input=${(e: Event) => credentialState.change("paths", (e.target as HTMLInputElement).value)}+ placeholder="/allowed/path/"+ ></textarea>+ </label>+ <label style="display: flex; align-items: center; gap: 10px; cursor: pointer; margin-bottom: 10px"+ ><input+ type="checkbox"+ id="sc-enabled"+ .checked=${credentialState.draft.enabled !== false}+ @change=${(e: Event) => credentialState.change("enabled", (e.target as HTMLInputElement).checked)}+ style="width: auto"+ />+ Credential is enabled</label+ >+ <label+ class=${classMap({ "sc-broker-only": true, hidden: env })}+ style="display: flex; align-items: center; gap: 10px; cursor: pointer; margin-bottom: 10px"+ ><input+ type="checkbox"+ id="sc-deployments"+ .checked=${credentialState.draft.deployments !== false}+ @change=${(e: Event) => credentialState.change("deployments", (e.target as HTMLInputElement).checked)}+ style="width: auto"+ />+ Published apps may use it, acting as their publisher</label+ >+ <p class=${classMap({ hint: true, "sc-broker-only": true, hidden: env })} style="margin-bottom: 6px">+ Principals with access+ </p>+ <p class=${classMap({ hint: true, "sc-env-only": true, hidden: !env })} style="margin-bottom: 6px">+ Access: every all-internal conversation. Env delivery is not gated by grants. Rooms with externals get+ nothing, everyone else gets the env var.+ </p>+ <label+ class=${classMap({ "sc-broker-only": true, hidden: env })}+ style="display: flex; align-items: center; gap: 8px; cursor: pointer; margin-bottom: 6px"+ ><input+ type="radio"+ name="sc-share"+ id="sc-share-org"+ .checked=${!!credentialState.draft.org}+ @change=${() => credentialState.change("org", true)}+ value="org"+ style="width: auto"+ />+ Everyone in this organization</label+ >+ <label+ class=${classMap({ "sc-broker-only": true, hidden: env })}+ style="display: flex; align-items: center; gap: 8px; cursor: pointer; margin-bottom: 6px"+ ><input+ type="radio"+ name="sc-share"+ value="people"+ .checked=${!credentialState.draft.org}+ @change=${() => credentialState.change("org", false)}+ style="width: auto"+ />+ Only selected people or teams</label+ >+ <input+ type="text"+ id="sc-people"+ .value=${credentialState.draft.people || ""}+ @input=${(e: Event) => credentialState.change("people", (e.target as HTMLInputElement).value)}+ class=${classMap({ "sc-broker-only": true, hidden: env })}+ list="sc-people-options"+ placeholder="Principal IDs, comma-separated"+ style="width: 100%; display: none"+ />+ <datalist id="sc-people-options"></datalist>+ <div+ class=${classMap({ "sc-picker": true, "sc-broker-only": true, hidden: env })}+ style=${credentialState.draft.org ? "display: none" : ""}+ id="sc-picker"+ >+ <input+ type="text"+ id="sc-picker-search"+ .value=${credentialState.query}+ @input=${(e: Event) => {+ credentialState.query = (e.target as HTMLInputElement).value;+ credentialState.picker = true;+ credentialState.render();+ }}+ @focus=${() => {+ credentialState.picker = true;+ credentialState.render();+ }}+ @blur=${() =>+ setTimeout(() => {+ credentialState.picker = false;+ credentialState.render();+ }, 150)}+ placeholder="Search people to grant access…"+ autocomplete="off"+ spellcheck="false"+ />+ <div class="sc-picker-list" id="sc-picker-list" ?hidden=${!credentialState.picker}>${pickerRows()}</div>+ </div>+ <div class=${classMap({ "identity-chips": true, "sc-broker-only": true, hidden: env })} id="sc-people-chips">+ ${credentialState.draft.org ? null : credentialState.grantees().map((id) => html`<span class="identity-chip">${config.label(id)}${grantTag(id)}</span>`)}+ </div>+ </div>+ <aside class="editor-panel" aria-live="polite">+ <h3>Effective capability</h3>+ <dl class="capability-summary">+ <div>+ <dt>State</dt>+ <dd id="sc-cap-state">${cap.state}</dd>+ </div>+ <div>+ <dt>Host</dt>+ <dd id="sc-cap-host">${cap.host}</dd>+ </div>+ <div>+ <dt>Auth</dt>+ <dd id="sc-cap-auth">${cap.auth}</dd>+ </div>+ <div>+ <dt>Methods</dt>+ <dd id="sc-cap-methods">${cap.methods}</dd>+ </div>+ <div>+ <dt>Paths</dt>+ <dd id="sc-cap-paths">${cap.paths}</dd>+ </div>+ <div>+ <dt>Access</dt>+ <dd id="sc-cap-principals">${cap.principals}</dd>+ </div>+ <div>+ <dt>Secret</dt>+ <dd id="sc-cap-secret">${cap.secret}</dd>+ </div>+ </dl>+ </aside>+ </div>+ </div>+ <div class="foot">+ <button type="button" class="viewlink" data-viewlink="audit">View usage ›</button+ ><button+ type="button"+ id="sc-add"+ ?disabled=${!!credentialState.listMessage}+ class=${credentialState.open ? "hidden" : ""}+ >+ + Add credential</button+ ><button+ class=${classMap({ primary: true, hidden: !credentialState.open, dirty: credentialState.dirty })}+ id="sc-save"+ ?disabled=${!credentialState.dirty || credentialState.saving}+ >+ ${credentialState.editing ? "Save changes" : "Save credential"}</button+ ><button class=${credentialState.open ? "" : "hidden"} id="sc-reset">Cancel</button+ ><span+ class=${classMap({ status: true, [credentialState.tone]: !!credentialState.tone })}+ id="st-service-credentials"+ >${credentialState.message}</span+ >+ </div>+ </section>`;+}+export function mountCredentials() {+ credentialState.render = mountTemplate('template[data-settings-card="card-service-credentials"]', template);+}++function secretSemantics() {+ if (credentialState.original?.hasSecret) return "Keeps the stored secret unchanged.";+ return credentialState.editing ? "A secret is required before saving." : "New credentials require a secret.";+}+function secretHint() {+ if (!credentialState.editing) return "The secret is write-only. It cannot be viewed after saving.";+ return credentialState.original?.hasSecret+ ? "Stored secret is set. Leave blank to keep it; enter a new value to replace it."+ : "No stored secret yet. Enter one to make this credential usable.";+}+function grantTag(id: string) {+ if (id.startsWith("group:")) return html`<small>unsupported · remove before saving</small>`;+ if (id.startsWith("channel:")) return html`<small>channel</small>`;+ return config.label(id) === id ? html`<small>unresolved</small>` : null;+}++const summaryRoots = new WeakSet<HTMLElement>();+export function keychainSummary(data: Data | null) {+ const root = document.querySelector<HTMLElement>("#card-personal-keychains .keychain-summary");+ if (!root) return;+ if (!summaryRoots.has(root)) {+ root.replaceChildren();+ summaryRoots.add(root);+ }+ const ready = data && data.enabled !== false;+ render(+ html`<strong id="keychain-user-count">${ready ? String(data.users) : "—"}</strong> users with keychain entries ·+ <strong id="keychain-standing-count">${ready ? String(data.standing) : "—"}</strong> standing grants`,+ root,+ );+}diff --git a/plugins/admin/ui/settings-flags.ts b/plugins/admin/ui/settings-flags.tsnew file mode 100644index 000000000..20af7844e--- /dev/null+++ b/plugins/admin/ui/settings-flags.ts@@ -0,0 +1,158 @@+import { mountTemplate } from "./shared.ts";+import { html } from "lit";+import { classMap } from "lit/directives/class-map.js";+import { repeat } from "lit/directives/repeat.js";+let config: any;+const state = {+ rows: [] as any[],+ scope: "",+ available: false,+ selected: new Set<string>(),+ feature: "command_scoped_credentials",+ saving: false,+ message: "",+ choices: [] as any[],+ selector: null as Node | null,+};+let redraw = () => {};+export function configureFlags(options: any) {+ config = options;+}+function selector() {+ const choices = state.choices.filter(+ (row) => state.feature !== "persistent_subagents" || row.scopeId.startsWith("personal:"),+ );+ for (const id of state.selected) if (!choices.some((row) => row.scopeId === id)) state.selected.delete(id);+ state.selector = config.buildSelector(choices, state.selected, redraw);+ redraw();+}+export async function loadFlags(data: any, scope: string) {+ if (state.scope !== scope) {+ state.selected.clear();+ state.message = "";+ }+ state.scope = scope;+ state.available = scope.startsWith("org:") && "featureFlags" in data;+ state.rows = data.featureFlags || [];+ redraw();+ if (!state.available) return;+ const choices = await config.loadChoices();+ if (state.scope !== scope) return;+ state.choices = choices || [];+ selector();+}+async function update(scopeId: string, on: boolean, featureName: string) {+ const scope = state.scope;+ state.saving = true;+ state.message = on ? "Enabling…" : "Disabling…";+ redraw();+ let result;+ try {+ result = await config.save(scope, { featureName, scopeId, on });+ } catch {+ if (scope === state.scope) state.message = "Could not save. Your selection is preserved; try again.";+ return false;+ }+ if (scope !== state.scope) return false;+ if (!result.ok) {+ state.message = result.error || result.data?.message || "Save failed.";+ return false;+ }+ let row = state.rows.find((row) => row.featureName === featureName);+ if (!row) {+ row = { featureName, enabledScopes: [] };+ state.rows.push(row);+ }+ row.enabledScopes = on+ ? [...new Set([...row.enabledScopes, scopeId])]+ : row.enabledScopes.filter((id: string) => id !== scopeId);+ state.message = on ? "Enabled." : "Disabled.";+ return true;+}+async function remove(scopeId: string, featureName: string) {+ if (state.saving) return;+ try {+ await update(scopeId, false, featureName);+ } finally {+ state.saving = false;+ redraw();+ }+}+async function add() {+ if (state.saving || !state.selected.size) return;+ const feature = state.feature;+ const selected = [...state.selected];+ try {+ for (const id of selected) {+ if (!(await update(id, true, feature))) break;+ state.selected.delete(id);+ }+ } finally {+ state.saving = false;+ selector();+ }+}+function template() {+ const enabled = state.rows.flatMap((row) =>+ (row.enabledScopes || []).map((scopeId: string) => ({ featureName: row.featureName, scopeId })),+ );+ return html`<section+ class=${classMap({ card: true, "sv-customize": true, hidden: !state.available })}+ id="card-feature-flags"+ >+ <div class="head">+ <h2>Feature flags</h2>+ <p>Enable a feature for selected scopes. Changes apply on the next turn without a restart.</p>+ </div>+ <div class="body">+ <div id="feature-flag-list" class=${enabled.length ? "" : "hint"}>+ ${+ enabled.length+ ? repeat(+ enabled,+ (r) => r.featureName + ":" + r.scopeId,+ (r) =>+ html`<div class="setting-row">+ <code>${r.featureName + ": " + r.scopeId}</code+ ><button class="danger" ?disabled=${state.saving} @click=${() => remove(r.scopeId, r.featureName)}>+ Disable+ </button>+ </div>`,+ )+ : "No enabled scopes."+ }+ </div>+ <div class="editor-grid" style="margin-top: 16px">+ <label+ >Feature<select+ id="feature-flag-name"+ .value=${state.feature}+ ?disabled=${state.saving}+ @change=${(e: Event) => {+ state.feature = (e.target as HTMLSelectElement).value;+ selector();+ }}+ >+ <option value="command_scoped_credentials">Command-scoped credentials</option>+ <option value="persistent_subagents">Persistent subagents</option>+ </select></label+ >+ <div>+ <div id="feature-flag-scope-label">People and scopes</div>+ <div id="feature-flag-scopes" aria-labelledby="feature-flag-scope-label" ?inert=${state.saving}>+ ${state.selector || "Loading people and scopes…"}+ </div>+ <span class="hint">Persistent subagents are available for personal scopes only.</span>+ </div>+ </div>+ </div>+ <div class="foot">+ <button class="primary" id="feature-flag-enable" ?disabled=${state.saving || !state.selected.size} @click=${add}>+ + Add flag</button+ ><span class="status" id="st-feature-flags">${state.message}</span>+ </div>+ </section>`;+}+export function mountFlags() {+ redraw = mountTemplate('template[data-settings-card="card-feature-flags"]', template);+}diff --git a/plugins/admin/ui/settings-providers.ts b/plugins/admin/ui/settings-providers.tsnew file mode 100644index 000000000..4a3f55120--- /dev/null+++ b/plugins/admin/ui/settings-providers.ts@@ -0,0 +1,301 @@+import { mountTemplate } from "./shared.ts";+import { html, render } from "lit";+import { classMap } from "lit/directives/class-map.js";+import { repeat } from "lit/directives/repeat.js";+let config: any;+const labels: Record<string, string> = {+ openai: "OpenAI Chat Completions",+ "openai-responses": "OpenAI Responses",+ anthropic: "Anthropic Messages",+};+export const provider = {+ draft: {} as Record<string, any>,+ editing: false,+ originalName: "",+ saving: false,+ message: "",+ error: false,+ rows: [] as any[],+ revision: 0,+ session: 0,+};+let redraw = () => {};+const mountedSummaries = new WeakSet<HTMLElement>();+export function configureProviders(options: any) {+ config = options;+}+function changeProvider(key: string, value: unknown) {+ provider.draft[key] = value;+ provider.revision++;+}+export function openProvider(item: any = null) {+ provider.session++;+ provider.revision++;+ provider.editing = !!item;+ provider.originalName = item?.name || "";+ provider.draft = {+ id: item?.id || "",+ name: item?.name || "",+ protocol: item?.protocol || "openai",+ url: item?.baseUrl || "",+ key: "",+ models: item+ ? item.models+ .map((m: any) => [m.id, m.name, m.contextWindow, m.maxTokens].filter((x) => x != null).join(" | "))+ .join("\n")+ : "",+ validate: true,+ };+ provider.message = "";+ provider.error = false;+ provider.saving = false;+ redraw();+ (document.getElementById("custom-provider-dialog") as HTMLDialogElement).showModal();+ document.getElementById(provider.editing ? "custom-provider-name" : "custom-provider-id")?.focus();+}+function closeProvider() {+ provider.session++;+ provider.revision++;+ provider.saving = false;+ const dialog = document.getElementById("custom-provider-dialog") as HTMLDialogElement;+ if (dialog.open) dialog.close();+ provider.draft.key = "";+ redraw();+}+export function providerBody() {+ const d = provider.draft;+ const models = d.models+ .split("\n")+ .map((l: string) => l.trim())+ .filter(Boolean)+ .map((l: string) => {+ const [id, name, contextWindow, maxTokens] = l.split("|").map((p) => p.trim());+ return {+ id,+ ...(name ? { name } : {}),+ ...(contextWindow ? { contextWindow: Number(contextWindow) } : {}),+ ...(maxTokens ? { maxTokens: Number(maxTokens) } : {}),+ };+ });+ return {+ name: d.name.trim(),+ protocol: d.protocol,+ baseUrl: d.url.trim(),+ models,+ ...(d.key.trim() ? { apiKey: d.key.trim() } : {}),+ ...(d.validate ? {} : { validate: false }),+ };+}+async function saveProvider() {+ if (provider.saving) return;+ const body = providerBody();+ const id = provider.draft.id.trim();+ if (!id || !body.name || !body.baseUrl || !body.models.length) {+ provider.message = "Provider id, name, base URL, and at least one model are required.";+ provider.error = true;+ redraw();+ return;+ }+ const revision = provider.revision;+ const session = provider.session;+ provider.saving = true;+ provider.message = "Saving…";+ provider.error = false;+ redraw();+ try {+ const saved = await config.api("PUT", "/api/custom-providers/" + encodeURIComponent(id), body);+ if (session !== provider.session) return;+ if (!saved.ok) {+ provider.error = true;+ provider.message = saved.data?.message || "Could not save this provider.";+ return;+ }+ if (provider.draft.key.trim() === body.apiKey) provider.draft.key = "";+ await config.refresh();+ if (session !== provider.session) return;+ if (revision === provider.revision) closeProvider();+ else provider.message = "Provider saved. Your newer edits are not saved.";+ } catch {+ if (session === provider.session) {+ provider.error = true;+ provider.message = "Could not save this provider. Your draft is preserved.";+ }+ } finally {+ if (session === provider.session) {+ provider.saving = false;+ redraw();+ }+ }+}+async function removeProvider(item: any) {+ if (!confirm("Remove " + item.name + "? Its models leave every model picker.")) return;+ const removed = await config.api("DELETE", "/api/custom-providers/" + encodeURIComponent(item.id));+ if (!removed.ok) {+ provider.message = removed.data?.message || "Could not remove this provider.";+ provider.error = true;+ redraw();+ return;+ }+ await config.refresh();+}+export async function loadProviders() {+ const res = await config.api("GET", "/api/custom-providers");+ if (!res.ok) return;+ provider.rows = (res.data?.providers || []).filter((p: any) => !p.disabled);+ renderRows();+}+function renderRows() {+ for (const [id, compact] of [+ ["model-custom-provider-rows", true],+ ["custom-provider-rows", false],+ ] as const) {+ const root = document.getElementById(id);+ if (!root) continue;+ render(+ html`${repeat(+ provider.rows,+ (p) => p.id,+ (p) =>+ html`<tr>+ ${[p.name + " (" + p.id + ")", labels[p.protocol] || p.protocol, p.baseUrl, compact ? String(p.models.length) : p.models.map((m: any) => m.id).join(", "), keyLabel(p, compact)].map((text) => html`<td>${text}</td>`)}+ <td>+ <button type="button" @click=${() => openProvider(p)}>Edit</button+ ><button class="danger" @click=${() => removeProvider(p)}>Remove</button>+ </td>+ </tr>`,+ )}`,+ root,+ );+ }+ const table = document.getElementById("model-custom-provider-table");+ if (table) table.hidden = !provider.rows.length;+ const summary = document.getElementById("custom-provider-summary");+ if (summary) {+ if (!mountedSummaries.has(summary)) {+ summary.replaceChildren();+ mountedSummaries.add(summary);+ }+ summary.hidden = !!provider.rows.length;+ render(html`No custom providers.`, summary);+ }+ const empty = document.getElementById("custom-provider-empty");+ if (empty) empty.hidden = !!provider.rows.length;+}++function template() {+ return html`+ <dialog+ @click=${(e: MouseEvent) => {+ if (e.target === e.currentTarget) closeProvider();+ }}+ @cancel=${() => closeProvider()}+ class="custom-provider-dialog"+ id="custom-provider-dialog"+ aria-labelledby="custom-provider-title"+ >+ <div class="project-dialog-head">+ <div>+ <h2 id="custom-provider-title">+ ${provider.editing ? "Edit " + provider.originalName : "Add custom provider"}+ </h2>+ <p>Connect an OpenAI Chat Completions, OpenAI Responses, or Anthropic Messages endpoint.</p>+ </div>+ <button+ class="project-icon-button"+ type="button"+ id="custom-provider-close"+ @click=${closeProvider}+ aria-label="Close"+ >+ ×+ </button>+ </div>+ <div class="custom-provider-form">+ <label+ >Provider id (slug)<input+ id="custom-provider-id"+ .value=${provider.draft.id || ""}+ @input=${(e: Event) => changeProvider("id", (e.target as HTMLInputElement).value)}+ ?disabled=${provider.editing}+ autocomplete="off"+ placeholder="litellm"+ /></label>+ <label+ >Display name<input+ id="custom-provider-name"+ .value=${provider.draft.name || ""}+ @input=${(e: Event) => changeProvider("name", (e.target as HTMLInputElement).value)}+ autocomplete="off"+ placeholder="LiteLLM"+ /></label>+ <label+ >Protocol<select+ id="custom-provider-protocol"+ .value=${provider.draft.protocol || ""}+ @input=${(e: Event) => changeProvider("protocol", (e.target as HTMLInputElement).value)}+ >+ <option value="openai">OpenAI Chat Completions</option>+ <option value="openai-responses">OpenAI Responses</option>+ <option value="anthropic">Anthropic Messages</option>+ </select></label+ >+ <label+ >Base URL<input+ id="custom-provider-url"+ .value=${provider.draft.url || ""}+ @input=${(e: Event) => changeProvider("url", (e.target as HTMLInputElement).value)}+ autocomplete="off"+ placeholder="https://gateway.internal/v1"+ /></label>+ <label class="custom-provider-key"+ >API key<input+ type="password"+ id="custom-provider-key"+ .value=${provider.draft.key || ""}+ @input=${(e: Event) => changeProvider("key", (e.target as HTMLInputElement).value)}+ autocomplete="off"+ placeholder="Write-only; blank on edit keeps the stored key"+ /></label>+ <label class="custom-provider-models"+ >Models <span class="label-detail">one per line: id | name | context | max tokens</span+ ><textarea+ id="custom-provider-models"+ .value=${provider.draft.models || ""}+ @input=${(e: Event) => changeProvider("models", (e.target as HTMLInputElement).value)}+ rows="4"+ placeholder="deepseek-chat | DeepSeek V3.2 | 128000 | 8192"+ ></textarea>+ </label>+ <label class="inline custom-provider-validation"+ ><input+ type="checkbox"+ id="custom-provider-validate"+ .checked=${provider.draft.validate}+ @change=${(e: Event) => changeProvider("validate", (e.target as HTMLInputElement).checked)}+ />+ Validate the key against the endpoint</label+ >+ <span+ class=${classMap({ status: true, err: provider.error, saving: provider.saving })}+ id="st-custom-provider"+ aria-live="polite"+ >${provider.message}</span+ >+ </div>+ <div class="project-dialog-actions">+ <button type="button" id="custom-provider-cancel" @click=${closeProvider}>Cancel</button+ ><button class="primary" id="custom-provider-save" ?disabled=${provider.saving} @click=${saveProvider}>+ Save provider+ </button>+ </div>+ </dialog>+ `;+}+export function mountProviders() {+ redraw = mountTemplate('template[data-settings-card="custom-provider-dialog"]', template);+}++function keyLabel(p: any, compact: boolean) {+ const text = p.hasKey ? "set (write-only)" : "none";+ return compact ? text.charAt(0).toUpperCase() + text.slice(1) : text;+}diff --git a/plugins/admin/ui/settings.ts b/plugins/admin/ui/settings.tsnew file mode 100644index 000000000..c3c61d5e0--- /dev/null+++ b/plugins/admin/ui/settings.ts@@ -0,0 +1,415 @@+import { mountTemplate } from "./shared.ts";+import { saveButton, settingStatus, saveFooter } from "./setting-controls.ts";+import { SettingState, settingRegistry } from "./setting-state.ts";+import { mountCredentials } from "./settings-credentials.ts";+export {+ configureCredentials,+ credentialState,+ credentialStatus,+ credentialLoading,+ loadCredentials,+ keychainSummary,+} from "./settings-credentials.ts";+import { mountProviders } from "./settings-providers.ts";+export { configureProviders, openProvider, loadProviders } from "./settings-providers.ts";+import { mountFlags } from "./settings-flags.ts";+export { configureFlags, loadFlags } from "./settings-flags.ts";+import { brandingCard } from "./settings-branding.ts";+import { html } from "lit";+import { classMap } from "lit/directives/class-map.js";+import { repeat } from "lit/directives/repeat.js";++type Model = { id: string; name?: string };+type Data = Record<string, any>;+export class SettingsState extends SettingState {+ context: Data = {};+ selected = "";+ editing = false;+ history: Data[] = [];+ collect(_validate = true): Data {+ if (_validate && this.key === "soul" && (this.draft.content || "").length > 100000)+ throw new Error("Maximum length reached");+ if (this.key === "branding")+ return Object.fromEntries(Object.entries(this.draft).map(([key, value]) => [key, String(value).trim()]));+ return structuredClone(this.draft);+ }+ get models(): Model[] {+ return this.context.modelsByHarness?.[this.draft.harnessId] || this.context.baseModelOptions || [];+ }+ get catalog(): Model[] {+ return [+ ...Object.values(this.context.modelsByHarness || {}).flat(),+ ...(this.context.baseModelOptions || []),+ ].filter((m: any, i, all) => m?.id && all.findIndex((x: any) => x?.id === m.id) === i) as Model[];+ }+ get harnesses(): string[] {+ return this.context.harnessOptions?.length ? this.context.harnessOptions : [this.context.harnessDefault || "pi"];+ }+ get efforts(): string[] {+ return this.context.thinkingLevelsByHarness?.[this.draft.harnessId] || ["auto"];+ }+ get fastCapable() {+ return (+ (this.context.fastModeHarnessIds || []).includes(this.draft.harnessId) &&+ (this.context.fastModeModelIds || []).includes(this.draft.modelId)+ );+ }+ normalize() {+ if (this.key !== "runtime") return;+ if (!this.harnesses.includes(this.draft.harnessId)) this.draft.harnessId = this.harnesses[0];+ if (!this.models.some((m) => m.id === this.draft.modelId)) this.draft.modelId = this.models[0]?.id || "";+ if (!this.efforts.includes(this.draft.effortLevel))+ this.draft.effortLevel = this.efforts.includes("auto") ? "auto" : this.efforts[0];+ if (!this.fastCapable) this.draft.fastMode = false;+ }+ change(field: string, value: unknown) {+ this.draft[field] = value;+ this.normalize();+ this.changed();+ }+ changed() {+ this.message = this.dirty ? "Unsaved changes" : "";+ this.tone = "";+ this.render();+ }+ commit(body: Data) {+ this.baseline = JSON.stringify(body);+ this.saving = false;+ this.changed();+ }+ add() {+ if (this.selected && !this.draft.ids.includes(this.selected)) this.draft.ids.push(this.selected);+ this.selected = "";+ this.changed();+ }+ remove(id: string) {+ this.draft.ids = this.draft.ids.filter((x: string) => x !== id);+ this.changed();+ }+}+export const states = new Map(+ ["runtime", "webui-models", "soul", "branding"].map((key) => [key, new SettingsState(key)]),+);+export const { owns, collect, capture, commit, status, statusKey } = settingRegistry(states);+export function load(data: Data, scope: string, only?: string) {+ for (const [key, s] of states) {+ if (only && only !== key) continue;+ s.context = data;+ if (key === "branding") {+ s.draft = {+ accent: data.branding?.accent || "",+ mark: data.branding?.mark || "",+ selfLabel: data.branding?.selfLabel || "",+ orgName: data.branding?.orgName || "",+ markUrl: data.branding?.markUrl || "",+ };+ s.available = scope.startsWith("org:") && "branding" in data;+ s.saving = false;+ capture(key);+ continue;+ }+ if (key === "soul") {+ s.draft = { content: data.soul || "", expectedVersion: data.soulVersion || 0 };+ s.history = data.soulHistory || [];+ s.editing = false;+ s.available = true;+ s.saving = false;+ capture(key);+ continue;+ }+ s.available =+ scope.startsWith("org:") &&+ !!data.baseModelOptions?.length &&+ (key !== "runtime" || (!!data.baseModelDefault && "runtime" in data));+ s.draft =+ key === "runtime"+ ? {+ harnessId: data.runtime?.harnessId || data.harnessDefault || "pi",+ modelId: data.runtime?.modelId || data.baseModel || data.baseModelDefault || "",+ effortLevel: data.runtime?.effortLevel || "auto",+ fastMode: data.runtime?.fastMode === true,+ }+ : { ids: (data.webuiModels || []).filter(Boolean) };+ s.normalize();+ s.saving = false;+ s.selected = "";+ capture(key);+ }+}+export function updateCatalog(data: Data) {+ for (const s of states.values()) {+ s.context = { ...s.context, ...data };+ s.render();+ }+}+const harnessLabels: Record<string, string> = {+ pi: "pi (default)",+ opencode: "OpenCode",+ codex: "Codex",+ claude: "Claude Code",+};+const effortLabels: Record<string, string> = {+ auto: "Auto",+ low: "Low",+ medium: "Medium",+ high: "High",+ xhigh: "Extra high",+ max: "Max",+ ultracode: "Ultracode",+};+const value = (event: Event) => (event.target as HTMLInputElement).value;+const label = (s: SettingsState, id: string) => {+ const m = s.catalog.find((x) => x.id === id);+ return m?.name && m.name !== id ? `${m.name} (${id})` : id;+};+function card(s: SettingsState) {+ if (s.key === "soul") return soulCard(s);+ if (s.key === "branding") return brandingCard(s);+ if (s.key === "runtime")+ return html`<section+ class=${classMap({ card: true, "sv-models": true, hidden: !s.available, dirty: s.dirty })}+ id="card-base-model"+ >+ <div class="head">+ <h2>Default runtime</h2>+ <p>The harness, model, and reasoning level used across your organization unless overridden.</p>+ </div>+ <div class="body">+ <div class="model-runtime-fields">+ <div>+ <label for="base-harness">Harness</label+ ><select+ id="base-harness"+ .value=${s.draft.harnessId || ""}+ @change=${(e: Event) => s.change("harnessId", value(e))}+ >+ ${s.harnesses.map((id) => html`<option value=${id} ?selected=${id === s.draft.harnessId}>${harnessLabels[id] || id}</option>`)}+ </select>+ </div>+ <div>+ <label for="base-model">Model</label+ ><select+ id="base-model"+ .value=${s.draft.modelId || ""}+ @change=${(e: Event) => s.change("modelId", value(e))}+ >+ ${s.models.map((m) => html`<option value=${m.id} ?selected=${m.id === s.draft.modelId}>${m.name} (${m.id})</option>`)}+ </select>+ </div>+ <div>+ <label for="base-effort">Reasoning level</label+ ><select+ id="base-effort"+ .value=${s.draft.effortLevel || "auto"}+ @change=${(e: Event) => s.change("effortLevel", value(e))}+ >+ ${s.efforts.map((id) => html`<option value=${id} ?selected=${id === s.draft.effortLevel}>${effortLabels[id] || id}</option>`)}+ </select>+ </div>+ </div>+ <label class="setting-toggle" id="base-fast-mode-control" style=${s.fastCapable ? "" : "display: none"}+ ><input+ type="checkbox"+ id="base-fast-mode"+ .checked=${!!s.draft.fastMode}+ ?disabled=${!s.fastCapable}+ @change=${(e: Event) => s.change("fastMode", (e.target as HTMLInputElement).checked)}+ /><span class="setting-switch" aria-hidden="true"></span+ ><span class="setting-copy"+ ><strong>Fast mode</strong><small>Only available for supported models.</small></span+ ></label+ >+ </div>+ ${saveFooter(s)}+ </section>`;+ const ids: string[] = s.draft.ids || [];+ const available = s.catalog.filter((m) => !ids.includes(m.id));+ return html`<section+ class=${classMap({ card: true, "sv-models": true, hidden: !s.available, dirty: s.dirty })}+ id="card-webui-models"+ >+ <div class="head"><h2>Enabled models</h2></div>+ <div class="body">+ <div class="model-add-row">+ <div class="model-add-field">+ <label for="webui-models-add">Add a model</label+ ><select+ id="webui-models-add"+ .value=${s.selected}+ ?disabled=${!available.length}+ @change=${(e: Event) => {+ s.selected = value(e);+ s.render();+ }}+ >+ <option value="">Choose a model…</option>+ ${available.map((m) => html`<option value=${m.id}>${label(s, m.id)}</option>`)}+ </select>+ </div>+ <button type="button" id="webui-models-add-button" ?disabled=${!s.selected} @click=${() => s.add()}>+ + Add model+ </button>+ </div>+ <div id="webui-models-list" class="model-list">+ <p id="webui-models-empty" class=${classMap({ hint: true, hidden: !!ids.length })}>+ No additional models enabled.+ </p>+ ${repeat(+ ids,+ (id) => id,+ (id) =>+ html`<span data-chip=${id} class="model-chip"+ ><span>${label(s, id)}</span+ ><button type="button" aria-label=${"Remove " + id} @click=${() => s.remove(id)}>+ <svg+ width="12"+ height="12"+ viewBox="0 0 16 16"+ fill="none"+ stroke="currentColor"+ stroke-width="1.5"+ stroke-linecap="round"+ aria-hidden="true"+ >+ <path d="m4 4 8 8M12 4l-8 8" />+ </svg></button+ ></span>`,+ )}+ </div>+ </div>+ ${saveFooter(s)}+ </section>`;+}+export function mountCards() {+ mountFlags();+ mountProviders();+ mountCredentials();+ for (const [key, s] of states) {+ const id = (+ {+ runtime: "card-base-model",+ soul: "card-soul",+ branding: "card-branding",+ "webui-models": "card-webui-models",+ } as Record<string, string>+ )[key];+ s.render = mountTemplate(`template[data-settings-card="${id}"]`, () => card(s));+ }+}++let soulActions: { formatTime: (time: any) => string; restore: (revision: Data) => Promise<void> } = {+ formatTime: String,+ restore: async () => {},+};+export function configureSoul(actions: typeof soulActions) {+ soulActions = actions;+}+export function refreshSoul(data: Data) {+ const s = states.get("soul")!;+ s.draft.expectedVersion = data.soulVersion || 0;+ s.baseline = JSON.stringify({ content: data.soul || "", expectedVersion: s.draft.expectedVersion });+ s.history = data.soulHistory || [];+ s.changed();+}+function soulCard(s: SettingsState) {+ const saved = JSON.parse(s.baseline).content || "";+ const content = s.draft.content || "";+ return html`<section+ class=${classMap({ card: true, "sv-customize": true, "is-editing": s.editing, dirty: s.dirty })}+ id="card-soul"+ >+ <div class="head">+ <h2>Organization SOUL</h2>+ <p>+ Write the standing instructions composed into every system prompt for this scope. Saving creates a durable+ revision; restoring an older revision creates a new one.+ </p>+ </div>+ <div class="body soul-preview-body">+ <div class="soul-preview-label" id="soul-preview-label">Standing instructions</div>+ <p class="soul-preview" id="soul-preview" aria-labelledby="soul-preview-label">+ ${saved || "No saved instructions"}+ </p>+ </div>+ <div class="body soul-workbench">+ <label for="soul">Standing instructions</label+ ><textarea+ id="soul"+ maxlength="100000"+ placeholder="No scope-specific instructions"+ .value=${content}+ @input=${(e: Event) => s.change("content", value(e))}+ ></textarea>+ <div class="soul-meta">+ <span id="soul-ver"+ >${s.draft.expectedVersion ? "Saved version " + s.draft.expectedVersion : "No saved revision"}</span+ ><span id="soul-size"+ >${content.length.toLocaleString() + " characters · about " + Math.ceil(content.length / 4).toLocaleString() + " tokens"}</span+ ><span id="soul-validation">${content.length >= 100000 ? "Maximum length reached" : "Draft valid"}</span>+ </div>+ <div class="soul-diff" id="soul-diff">+ <section>+ <h3>Saved revision</h3>+ <pre id="soul-saved">${saved || "No saved instructions"}</pre>+ </section>+ <section>+ <h3>Current draft</h3>+ <pre id="soul-draft">+${content === saved ? "No draft changes" : content || "Instructions will be cleared"}</pre>+ </section>+ </div>+ <div class="soul-history" id="soul-history" aria-label="SOUL version history">+ <h3>Version history</h3>+ ${+ s.history.length+ ? repeat(+ s.history,+ (r) => r.version,+ (r) =>+ html`<div class="soul-revision">+ <p>+ Version ${r.version}<small+ >${r.updatedBy || "Author unavailable"} ·+ ${r.updatedAt ? soulActions.formatTime(r.updatedAt) : "Time unavailable"}</small+ >+ </p>+ <button+ type="button"+ ?disabled=${r.version === s.draft.expectedVersion || s.saving}+ @click=${() => soulActions.restore({ ...r })}+ >+ ${r.version === s.draft.expectedVersion ? "Current" : "Restore"}+ </button>+ </div>`,+ )+ : html`<p class="hint">History begins with the next saved revision.</p>`+ }+ </div>+ </div>+ <div class="foot">+ <button+ type="button"+ class="viewlink"+ id="soul-history-link"+ @click=${() => {+ s.editing = true;+ s.render();+ document.getElementById("soul-history")?.scrollIntoView({ behavior: "smooth", block: "center" });+ }}+ >+ View history ›</button+ ><button+ type="button"+ id="soul-edit"+ @click=${() => {+ s.editing = !s.editing;+ if (!s.editing) s.draft.content = saved;+ s.changed();+ if (s.editing) document.getElementById("soul")?.focus();+ }}+ >+ ${s.editing ? "Cancel" : "Edit"}</button+ >${saveButton(s, "Save")}${settingStatus(s)}+ </div>+ </section>`;+}diff --git a/plugins/admin/ui/shared.ts b/plugins/admin/ui/shared.tsnew file mode 100644index 000000000..0194b762c--- /dev/null+++ b/plugins/admin/ui/shared.ts@@ -0,0 +1,160 @@+import { html, render, nothing } from "lit";+import { ifDefined } from "lit/directives/if-defined.js";++export function node(template: unknown): HTMLElement {+ const fragment = document.createDocumentFragment();+ render(template, fragment);+ return fragment.firstElementChild as HTMLElement;+}++export function badge(text: unknown, kind = "") {+ return html`<span class=${"badge" + (kind ? " " + kind : "")}>${text}</span>`;+}++export function cell(value: any): unknown {+ if (value?.node) return value.node;+ if (value?.badges)+ return html`<div class="badges">+ ${value.badges.filter(Boolean).map((b: any) => b.node || (Array.isArray(b) ? badge(b[0], b[1]) : badge(b.text, b.kind)))}+ </div>`;+ if (value?.badge !== undefined) return value.badge ? badge(value.badge, value.kind || "admin") : "-";+ if (value?.action) {+ const a = value.action;+ return html`<button+ type="button"+ class=${"rowbtn" + (a.danger ? " danger" : "")}+ ?disabled=${!!a.disabled}+ title=${ifDefined(a.title || undefined)}+ @click=${a.run}+ >+ ${a.label}+ </button>`;+ }+ if (value && typeof value === "object") return value.text;+ return value == null ? "" : String(value);+}++export function table(+ headers: unknown[],+ rows: any[][],+ empty: string,+ onOpen?: (index: number) => void,+ options: { className?: string; cols?: string[]; wrapClass?: string } = {},+) {+ if (!rows.length) return html`<p class="empty">${empty}</p>`;+ return html`<div class=${"tablewrap" + (options.wrapClass ? " " + options.wrapClass : "")}>+ <table class=${ifDefined(options.className)}>+ ${+ options.cols?.length+ ? html`<colgroup>+ ${options.cols.map((width) => html`<col style=${"width:" + width}></col>`)}+ </colgroup>`+ : nothing+ }+ <thead>+ <tr>+ ${headers.map((h) => html`<th>${h}</th>`)}+ </tr>+ </thead>+ <tbody>+ ${rows.map(+ (row, i) =>+ html`<tr class=${ifDefined(onOpen ? "openable" : undefined)} @click=${onOpen ? () => onOpen(i) : nothing}>+ ${row.map((value, j) => html`<td class=${ifDefined(value?.cls || (value?.badge === "" ? "num" : undefined))}>${onOpen && j === 0 ? html`<div class="open">${cell(value)}</div>` : cell(value)}</td>`)}+ </tr>`,+ )}+ </tbody>+ </table>+ </div>`;+}++export function card(title: unknown, subtitle: unknown, content: unknown, headExtra: unknown = nothing) {+ return html`<section class="card">+ <div class="head">+ <h2>${title}</h2>+ ${subtitle ? html`<p>${subtitle}</p>` : nothing}${headExtra}+ </div>+ <div class="body">${content}</div>+ </section>`;+}++export function bareCard(content: unknown) {+ return html`<section class="card"><div class="body">${content}</div></section>`;+}++export function pager(total: number, limit: number, offset: number, go: (page: number) => void) {+ if (total <= limit) return nothing;+ const current = Math.floor(offset / limit) + 1;+ return html`<div class="pager">+ <button type="button" class="page" ?disabled=${current <= 1} @click=${() => go(current - 1)}>← Prev</button+ ><span class="pageinfo">${offset + 1}–${Math.min(offset + limit, total)} of ${total}</span+ ><button+ type="button"+ class="page"+ ?disabled=${current >= Math.ceil(total / limit)}+ @click=${() => go(current + 1)}+ >+ Next →+ </button>+ </div>`;+}++export function mount(root: HTMLElement, template: unknown) {+ const end = root.appendChild(document.createComment(""));+ render(template, root, { renderBefore: end });+}++export function renderer(root: HTMLElement) {+ const end = root.appendChild(document.createComment(""));+ return (template: unknown) => {+ if (end.parentNode === root) render(template, root, { renderBefore: end });+ };+}++export function denseList(items: any[], rowOf: (item: any) => any, open: (item: any) => void, empty: string) {+ if (!items.length) return html`<p class="empty">${empty}</p>`;+ return html`<div class="dense-list">+ ${items.map((item) => {+ const r = rowOf(item);+ const content = html`${r.icon ? html`<span class="dense-icon">${r.icon}</span>` : nothing}<span class="dense-name"+ >${r.name}</span+ ><span class="dense-preview">${r.preview ?? ""}</span+ >${r.time != null ? html`<span class="dense-time">${r.time}</span>` : nothing}`;+ const click = (e: MouseEvent) => {+ if (r.href && (r.target || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)) return;+ if (r.href) e.preventDefault();+ open(item);+ };+ return r.href+ ? html`<a+ class=${"dense-row" + (r.cls ? " " + r.cls : "")}+ href=${r.href}+ target=${ifDefined(r.target)}+ rel=${ifDefined(r.target ? "noopener" : undefined)}+ @click=${click}+ >${content}</a+ >`+ : html`<div+ class=${"dense-row" + (r.cls ? " " + r.cls : "")}+ tabindex="0"+ role="button"+ @click=${click}+ @keydown=${(e: KeyboardEvent) => {+ if (e.key === "Enter") open(item);+ }}+ >+ ${content}+ </div>`;+ })}+ </div>`;+}++export function mountTemplate(selector: string, template: () => unknown) {+ const placeholder = document.querySelector(selector);+ if (!placeholder) return () => {};+ const root = document.createDocumentFragment();+ const draw = () => render(template(), root);+ draw();+ placeholder.replaceWith(root);+ return draw;+}diff --git a/plugins/admin/ui/slack-activity.ts b/plugins/admin/ui/slack-activity.tsnew file mode 100644index 000000000..bd887774c--- /dev/null+++ b/plugins/admin/ui/slack-activity.ts@@ -0,0 +1,592 @@+import { html, nothing } from "lit";+import { repeat } from "lit/directives/repeat.js";+import { classMap } from "lit/directives/class-map.js";+import { badge, renderer, node } from "./shared.ts";+import type { Api } from "./integrations-state.ts";+type Row = Record<string, any>;+type Context = {+ api: Api;+ go: (state: Row) => void;+ urlToState: () => Row;+ stateToUrl: (state: Row) => string;+ pageShell: (state: Row) => void;+ navLink: (label: string, state: Row) => Node;+ relTime: (value: string) => string;+ fmtTime: (value: string) => string;+ brandSelfLabel: () => string;+ slackParseText: (text: string, mentions?: Row) => Node;+ slackContainerLabel: (id: string) => string;+ slackContainerScope: (id: string) => string | null;+ loadSlackContainers: () => ReturnType<Api>;+ containers: () => Row[] | null;+ truncated: () => boolean;+ view: () => string;+ loaded: () => void;+};+let context: Context;+export function configure(value: Context) {+ context = value;+}+const empty = (text: string) => html`<p class="empty">${text}</p>`;+const loading = (text: string) => html`<div class="loadingline">${text}</div>`;+export const groupKey = (m: Row) =>+ (m.authorId || m.authorName || m.ts) + "|" + (m.sub && m.sub !== m.ts ? m.sub : "root");+const author = (m: Row) => (m.self ? context.brandSelfLabel() : m.authorName || m.authorId || "unknown");+const time = (m: Row) => new Date(m.createdAt).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });+export function message(m: Row, opts: Row = {}) {+ return html`<div+ class=${classMap({ "sm-msg": true, "sm-cont": !!opts.cont, "sm-self": !!m.self, "sm-reply": !!(m.sub && m.sub !== m.ts), "sm-deleted": !!m.deleted, "sm-target": !!opts.target, "sm-openable": !!opts.onOpen })}+ data-ts=${m.ts}+ @click=${opts.onOpen ? () => opts.onOpen(m) : nothing}+ >+ <div class="sm-gutter">+ ${opts.cont ? html`<span class="sm-guttertime">${time(m)}</span>` : html`<span class="sm-avatar">${(author(m).trim()[0] || "?").toUpperCase()}</span>`}+ </div>+ <div class="sm-body">+ ${opts.cont ? nothing : html`<div class="sm-head"><span class="sm-author">${author(m)}</span>${messageTag(m)}${m.sub && m.sub !== m.ts ? html`<span class="sm-tag" title=${"Reply in the thread rooted at " + m.sub}>Thread reply</span>` : nothing}${opts.containerLabel ? html`<span class="sm-tag">${opts.containerLabel}</span>` : nothing}<span class="sm-when" title=${context.fmtTime(m.createdAt) + " · ts " + m.ts}>${context.view() === "slack" && !opts.onOpen ? time(m) : context.relTime(m.createdAt)}</span></div>`}+ <div class="sm-text">+ ${context.slackParseText(m.text || "", m.mentions)}${m.editedAt ? html`<span class="sm-flag" title=${context.fmtTime(m.editedAt)}>(edited)</span>` : nothing}${m.deleted ? html`<span class="sm-flag">(deleted in Slack)</span>` : nothing}+ </div>+ </div>+ </div>`;+}+export function groupedMessages(messages: Row[], target?: string) {+ return repeat(+ messages,+ (m) => m.ts,+ (m, index) => {+ const previous = messages[index - 1],+ day = new Date(m.createdAt).toDateString(),+ sameDay = previous && new Date(previous.createdAt).toDateString() === day;+ return html`${sameDay ? nothing : html`<div class="sm-day">${day === new Date().toDateString() ? "Today" : new Date(m.createdAt).toLocaleDateString([], { month: "short", day: "numeric", year: "numeric" })}</div>`}${message(m, { target: target === m.ts, cont: !!sameDay && groupKey(previous) === groupKey(m) && target !== m.ts })}`;+ },+ );+}+function dense(items: Row[], rowOf: (item: Row) => Row, onOpen: (item: Row) => void, emptyText: string) {+ if (!items.length) return empty(emptyText);+ return html`<div class="dense-list">+ ${repeat(+ items,+ (it) => it.id || it.container,+ (it) => {+ const row = rowOf(it);+ return html`<a+ class="dense-row"+ href=${row.href}+ @click=${(event: MouseEvent) => {+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;+ event.preventDefault();+ onOpen(it);+ }}+ ><span class="dense-name">${row.name}</span><span class="dense-preview">${row.preview}</span+ ><span class="dense-time">${row.time}</span></a+ >`;+ },+ )}+ </div>`;+}+function messageTag(m: Row) {+ if (m.self) return html`<span class="sm-tag sm-tag-agent">agent</span>`;+ return m.bot ? html`<span class="sm-tag">bot</span>` : nothing;+}+function judgmentBadge(decision: string) {+ if (decision === "act") return badge("woke", "ok");+ return decision === "ignore" ? badge("silent", "muted") : badge("fastlane", "accent");+}+function ackBadge(row: Row) {+ return row.outcome === "picked" ? ackTag(row.picked, row.icon) : badge("declined", "muted");+}+function judgmentReason(item: Row) {+ if (item.reason) return item.reason;+ if (item.decision === "ignore") return "Stayed silent.";+ return item.decision === "fastlane" ? "@mention, routed past the judge." : "None";+}++function ackTag(name: string, icon?: string, accent = false) {+ if (icon && /^https?:\/\//.test(icon))+ return html`<img+ class=${"ack-emoji-img" + (accent ? " accent" : "")}+ src=${icon}+ alt=${":" + name + ":"}+ title=${":" + name + ":"}+ />`;+ return icon+ ? html`<span class=${"ack-emoji-glyph" + (accent ? " accent" : "")} title=${":" + name + ":"}>${icon}</span>`+ : html`<span class=${"pill" + (accent ? " accent" : "")}>${name ? ":" + name + ":" : "None"}</span>`;+}+export function slackHref(workspace: string, container: string, ts: string) {+ return workspace && container?.startsWith("C") && ts+ ? workspace.replace(/\/$/, "") + "/archives/" + container + "/p" + ts.replace(".", "")+ : null;+}+export class SlackActivity {+ generation = 0;+ state: Row = {};+ messages: Row[] = [];+ rows: Row[] = [];+ hasMore = false;+ busy = false;+ error = "";+ draw: (value: unknown) => void = () => {};+ root!: HTMLElement;+ current(view: string, generation = this.generation) {+ return generation === this.generation && context.view() === view;+ }+ begin(state: Row) {+ this.generation++;+ this.state = state;+ this.messages = [];+ this.rows = [];+ this.hasMore = false;+ this.busy = false;+ this.error = "";+ this.root = document.getElementById("view-data")!;+ this.root.replaceChildren();+ this.draw = renderer(this.root);+ return this.generation;+ }+ searchBox(container: string | null) {+ let timer: ReturnType<typeof setTimeout>;+ return {+ placeholder: container ? "Search this channel…" : "Search all mirrored messages…",+ onInput: (value: string) => {+ clearTimeout(timer);+ timer = setTimeout(() => {+ if (context.view() === "slack" && (context.urlToState().container || null) === container)+ void this.search(value.trim(), container);+ }, 250);+ },+ };+ }+ async search(query: string, container: string | null) {+ if (context.view() !== "slack") return;+ if (!query) return this.mirror({ ...context.urlToState(), ts: null });+ const generation = this.begin({ ...context.urlToState(), query });+ const result = await context.api(+ "GET",+ "/api/slack-mirror/messages?q=" ++ encodeURIComponent(query) ++ (container ? "&container=" + encodeURIComponent(container) : ""),+ );+ if (!this.current("slack", generation)) return;+ if (!result.ok) return this.draw(empty(result.data?.message || `Search failed (${result.status}).`));+ this.messages = result.data.messages || [];+ this.draw(+ this.messages.length+ ? html`<div class="sm-stream">+ ${repeat(+ this.messages,+ (m) => m.container + ":" + m.ts,+ (m) =>+ message(m, {+ containerLabel: container ? null : context.slackContainerLabel(m.container),+ onOpen: (msg: Row) => context.go({ view: "slack", container: msg.container, ts: msg.ts }),+ }),+ )}+ </div>+ ${result.data.hasMore ? empty(`First ${this.messages.length.toLocaleString()} matches shown. Refine the search to see the rest.`) : nothing}`+ : empty("No matches in the mirror."),+ );+ }+ async mirror(st: Row) {+ const generation = this.begin(st);+ if (!st.container) {+ context.pageShell({ title: "Slack", search: this.searchBox(null) });+ this.draw(loading("Loading Slack mirror..."));+ const result = await context.loadSlackContainers();+ if (!this.current("slack", generation)) return;+ if (!result.ok)+ return this.draw(+ empty(+ result.status === 403+ ? "Only an org admin can read the Slack mirror."+ : result.data?.message || `Failed to load (${result.status}).`,+ ),+ );+ context.loaded();+ const containers = context.containers() || [];+ context.pageShell({+ title: "Slack",+ count: (context.truncated() ? containers.length.toLocaleString() + "+" : containers.length) + " conversations",+ search: this.searchBox(null),+ });+ this.draw(+ html`${dense(+ containers,+ (c) => ({+ name: context.slackContainerLabel(c.container),+ preview: `${Number(c.messageCount).toLocaleString()} mirrored · ${(c.members || []).length} ${(c.members || []).length === 1 ? "member" : "members"}`,+ time: context.relTime(c.updatedAt),+ href: context.stateToUrl({ view: "slack", container: c.container }),+ }),+ (c) => context.go({ view: "slack", container: c.container }),+ "Nothing mirrored yet. The surface pushes messages here as it sees them.",+ )}${context.truncated() ? empty(`Showing the ${containers.length.toLocaleString()} most recently active conversations.`) : nothing}`,+ );+ return;+ }+ if (!context.containers()) await context.loadSlackContainers();+ if (!this.current("slack", generation)) return;+ const container = st.container,+ scope = context.slackContainerScope(container);+ context.pageShell({+ back: { label: "← Slack", onClick: () => context.go({ view: "slack", container: null, ts: null }) },+ title: context.slackContainerLabel(container),+ context: container,+ search: this.searchBox(container),+ actions: [+ context.navLink("Judgments →", { view: "judgments", container }),+ ...(scope ? [context.navLink("Governance →", { view: "governance", scope, session: null })] : []),+ ],+ });+ const bar = document.getElementById("shellbar")!;+ const toolbar = node(+ html`<div class="sm-toolbar">${bar.querySelector(".back")}${[...bar.querySelectorAll(".link")]}</div>`,+ );+ const heading = node(+ html`<div class="sm-channel-heading">+ ${bar.querySelector(".shell-title")}${bar.querySelector(".shell-context")}+ </div>`,+ );+ bar.querySelector(".shell-spacer")?.remove();+ bar.prepend(toolbar, heading);+ this.draw(loading("Loading messages..."));+ const result = await this.fetchMessages(container);+ if (!this.current("slack", generation)) return;+ if (!result.ok) return this.draw(empty(result.data?.message || `Failed to load (${result.status}).`));+ this.messages = result.data.messages || [];+ this.hasMore = !!result.data.hasMore;+ for (+ let hops = 0;+ st.ts && this.hasMore && this.messages.length && this.messages[0].ts > st.ts && hops < 10;+ hops+++ ) {+ const older = await this.fetchMessages(container, this.messages[0].ts);+ if (!this.current("slack", generation)) return;+ if (!older.ok) break;+ this.messages = [...(older.data.messages || []), ...this.messages];+ this.hasMore = !!older.data.hasMore;+ }+ toolbar.appendChild(+ node(+ html`<a+ href=${"/api/slack-mirror/messages?container=" + encodeURIComponent(container)}+ target="_blank"+ rel="noopener"+ title="Open the raw mirrored JSON rows for this container in a new tab"+ >Raw feed ↗</a+ >`,+ ),+ );+ this.paintMessages();+ requestAnimationFrame(() => {+ if (!this.current("slack", generation)) return;+ if (st.ts) this.root.querySelector(".sm-target")?.scrollIntoView({ block: "center" });+ else window.scrollTo({ top: document.body.scrollHeight });+ });+ }+ fetchMessages(container: string, before?: string) {+ return context.api(+ "GET",+ "/api/slack-mirror/messages?container=" ++ encodeURIComponent(container) ++ "&limit=200" ++ (before ? "&before=" + encodeURIComponent(before) : ""),+ );+ }+ paintMessages() {+ this.draw(+ html`${this.state.ts && !this.messages.some((m) => m.ts === this.state.ts) ? html`<div class="sm-day">${"Message " + this.state.ts + " isn't in the loaded window. It may be older than what's shown (use “Load earlier messages”) or was never mirrored."}</div>` : nothing}${this.hasMore ? html`<button type="button" class="load-earlier more" ?disabled=${this.busy} @click=${() => this.earlierMessages()}>Load earlier messages</button>` : nothing}${this.error ? empty(this.error) : nothing}+ <div class="sm-stream">+ ${this.messages.length ? groupedMessages(this.messages, this.state.ts) : empty("Nothing mirrored for this channel yet.")}+ </div>`,+ );+ }+ async earlierMessages() {+ if (this.busy) return;+ const generation = this.generation;+ this.busy = true;+ this.paintMessages();+ const result = await this.fetchMessages(this.state.container, this.messages[0]?.ts);+ if (!this.current("slack", generation)) return;+ this.busy = false;+ if (result.ok) {+ this.messages = [...(result.data.messages || []), ...this.messages];+ this.hasMore = !!result.data.hasMore;+ } else this.error = result.data?.message || "Failed to load earlier messages.";+ this.paintMessages();+ }+ async log(st: Row, kind: "judgments" | "ackemoji") {+ const generation = this.begin(st);+ if (!context.containers()) await context.loadSlackContainers();+ if (!this.current(kind, generation)) return;+ if (st.jid) return this.detail(st, kind, generation);+ const ack = kind === "ackemoji",+ title = ack ? "Ack emoji" : "Judgments",+ decision = st.decision || (ack ? null : "act,ignore");+ let navigation: Row = {};+ if (st.container)+ navigation = {+ back: {+ label: "← " + title,+ onClick: () => context.go({ view: kind, container: null, decision: st.decision, jid: null }),+ },+ context: context.slackContainerLabel(st.container),+ contextGo: { view: "slack", container: st.container },+ };+ else if (ack)+ navigation = {+ back: {+ label: "← Judgments",+ onClick: () => context.go({ view: "judgments", container: null, decision: null, jid: null }),+ },+ };+ const shell = (extra: Row) =>+ context.pageShell({+ title,+ ...navigation,+ ...(ack ? {} : { actions: [context.navLink("Ack emoji →", { view: "ackemoji" })] }),+ ...extra,+ });+ shell({});+ this.draw(loading(ack ? "Loading ack-emoji picks…" : "Loading judgments…"));+ const path = ack+ ? "/api/ack-emoji-picks?" ++ (decision ? "outcome=" + encodeURIComponent(decision) : "") ++ (st.container ? "&container=" + encodeURIComponent(st.container) : "")+ : "/api/ambient-judgments?decision=" ++ encodeURIComponent(decision) ++ (st.container ? "&container=" + encodeURIComponent(st.container) : "");+ const result = await context.api("GET", path);+ if (!this.current(kind, generation)) return;+ if (!result.ok)+ return this.draw(+ empty(result.status === 403 ? deniedLog(ack) : result.data?.message || `Failed to load (${result.status}).`),+ );+ const counts = result.data.counts || {},+ tabs = ack+ ? [+ { key: null, label: "All", counts: ["picked", "declined"] },+ { key: "picked", label: "Picked", counts: ["picked"] },+ { key: "declined", label: "Declined", counts: ["declined"] },+ ]+ : [+ { key: "act,ignore", label: "Judged", counts: ["act", "ignore"] },+ { key: "act", label: "Woke", counts: ["act"] },+ { key: "ignore", label: "Silent", counts: ["ignore"] },+ { key: "fastlane", label: "Fastlane", counts: ["fastlane"] },+ ];+ shell({+ tabs: tabs.map((t) => ({+ label: t.label,+ count: t.counts.reduce((n, key) => n + (counts[key] || 0), 0),+ active: t.key === decision,+ onClick: () =>+ context.go({+ view: kind,+ container: st.container,+ decision: t.key === "act,ignore" ? null : t.key,+ jid: null,+ }),+ })),+ });+ this.rows = result.data[ack ? "picks" : "judgments"] || [];+ this.hasMore = !!result.data.hasMore;+ this.paintLog(kind, path);+ }+ paintLog(kind: "judgments" | "ackemoji", path: string) {+ const ack = kind === "ackemoji",+ st = this.state;+ if (!this.rows.length)+ return this.draw(+ empty(ack ? "No ack-emoji picks recorded for this filter yet." : "No judgments recorded for this filter yet."),+ );+ const target = (r: Row) => ({ view: kind, container: st.container, decision: st.decision, jid: String(r.id) });+ this.draw(+ html`<div>+ ${dense(+ this.rows,+ (r) => ({+ name: context.slackContainerLabel(ack ? r.channel : r.container),+ preview: html`<span class="badges"+ >${ack ? ackBadge(r) : judgmentBadge(r.decision)}<span class=${ack ? "pill" : "pill judgment-reason"}+ >${ack ? r.message || "None" : r.reason || (r.decision === "fastlane" ? "@mention, routed past the judge" : "None")}</span+ >${r.latencyMs != null ? html`<span class="dense-time">${r.latencyMs + "ms"}</span>` : nothing}</span+ >`,+ time: context.relTime(r.createdAt),+ href: context.stateToUrl(target(r)),+ }),+ (r) => context.go(target(r)),+ "",+ )}+ </div>+ ${this.hasMore ? html`<button type="button" class="load-earlier more" ?disabled=${this.busy} @click=${() => this.earlierLog(kind, path)}>${ack ? "Load earlier picks" : "Load earlier judgments"}</button>` : nothing}${this.error ? empty(this.error) : nothing}`,+ );+ }+ async earlierLog(kind: "judgments" | "ackemoji", path: string) {+ if (this.busy) return;+ const generation = this.generation,+ last = this.rows[this.rows.length - 1];+ this.busy = true;+ this.paintLog(kind, path);+ const result = await context.api(+ "GET",+ path + "&before=" + encodeURIComponent(last.createdAt) + "&beforeId=" + encodeURIComponent(last.id),+ );+ if (!this.current(kind, generation)) return;+ this.busy = false;+ if (result.ok) {+ this.rows = [...this.rows, ...(result.data[kind === "ackemoji" ? "picks" : "judgments"] || [])];+ this.hasMore = !!result.data.hasMore;+ } else this.error = result.data?.message || "Failed to load earlier entries.";+ this.paintLog(kind, path);+ }+ async detail(st: Row, kind: "judgments" | "ackemoji", generation: number) {+ const ack = kind === "ackemoji",+ title = ack ? "Ack emoji" : "Judgment",+ back = {+ label: ack ? "← Ack emoji" : "← Judgments",+ onClick: () => context.go({ view: kind, container: st.container, decision: st.decision, jid: null }),+ };+ context.pageShell({ back, title });+ this.draw(html`<div class="detail judg-detail">Loading…</div>`);+ const result = await context.api(+ "GET",+ (ack ? "/api/ack-emoji-picks?id=" : "/api/ambient-judgments?id=") + encodeURIComponent(st.jid),+ );+ if (!this.current(kind, generation)) return;+ if (!result.ok)+ return this.draw(+ html`<div class="detail judg-detail">+ ${empty(result.data?.message || `Failed to load (${result.status}).`)}+ </div>`,+ );+ const item = result.data[ack ? "pick" : "judgment"],+ container = ack ? item.channel : item.container,+ ts = ack ? item.ts : item.tsFrom,+ scope = context.slackContainerScope(container);+ context.pageShell({+ back,+ title,+ context: context.slackContainerLabel(container),+ contextGo: { view: "slack", container, ts },+ ...(!ack+ ? { actions: scope ? [context.navLink("Governance →", { view: "governance", scope, session: null })] : [] }+ : {}),+ });+ if (ack) return this.draw(ackDetail(item, result.data.workspaceUrl));+ this.draw(judgmentDetail(item, result.data.workspaceUrl, nothing));+ const before = item.tsTo ? (Number(item.tsTo) + 1).toString() : undefined;+ const mirror = await this.fetchMessages(container, before);+ if (!this.current(kind, generation)) return;+ const messages = (mirror.data?.messages || []).filter((m: Row) => !item.tsTo || m.ts <= item.tsTo);+ let mirrorContent: unknown = empty("Nothing mirrored for this window.");+ if (messages.length)+ mirrorContent = html`<div class="sm-stream">+ ${repeat(+ messages,+ (m: Row) => m.ts,+ (m: Row) => message(m, { target: item.tsFrom && item.tsTo && m.ts >= item.tsFrom && m.ts <= item.tsTo }),+ )}+ </div>`;+ if (!mirror.ok) mirrorContent = empty(mirror.data?.message || `Failed to load mirror (${mirror.status}).`);+ this.draw(judgmentDetail(item, result.data.workspaceUrl, mirrorContent));+ requestAnimationFrame(() => {+ if (this.current(kind, generation)) this.root.querySelector(".sm-target")?.scrollIntoView({ block: "center" });+ });+ }+}+function meta(item: Row) {+ return [item.model, item.latencyMs != null ? item.latencyMs + "ms" : null, context.fmtTime(item.createdAt)]+ .filter(Boolean)+ .join(" · ");+}+function judgmentDetail(item: Row, workspace: string, mirror: unknown) {+ const href = slackHref(workspace, item.container, item.tsFrom);+ return html`<div class="detail judg-detail">+ <div class="judg-split">+ <div>+ <div class="judg-pane-title">+ Slack+ mirror${+ href+ ? html`<a+ href=${href}+ target="_blank"+ rel="noopener"+ class="judg-extlink"+ aria-label="Open in Slack"+ title="Jump to this moment in Slack to scroll up for more context"+ ><svg+ width="13"+ height="13"+ viewBox="0 0 16 16"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+ aria-hidden="true"+ >+ <path d="M6.5 3.5H3.5a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1v-3" />+ <path d="M9.5 2.5h4v4" />+ <path d="M7 9 13.5 2.5" /></svg+ ></a>`+ : nothing+ }+ </div>+ <div class="judg-mirror">${mirror}</div>+ </div>+ <div>+ <div class="judg-pane-title">Judge context</div>+ <div class="judg-prompt">+ <pre>+${item.prompt || (item.decision === "fastlane" ? "Routed past the judge (formal @mention). No prompt was rendered." : "(prompt not recorded)")}</pre>+ </div>+ </div>+ </div>+ <div class="judg-decision">+ <div class="badges">+ ${judgmentBadge(item.decision)}${item.askedBy ? badge("asked by " + item.askedBy, "accent") : nothing}<span+ class="shell-context"+ >${meta(item)}</span+ >+ </div>+ <p>${judgmentReason(item)}</p>+ </div>+ </div>`;+}+function ackDetail(item: Row, workspace: string) {+ const href = slackHref(workspace, item.channel, item.ts);+ return html`<div class="detail judg-detail">+ <div class="judg-decision">+ <div class="badges">+ ${item.outcome === "picked" ? ackTag(item.picked, item.icon) : badge("declined", "muted")}<span+ class="shell-context"+ >${meta(item)}</span+ >${href ? html`<a href=${href} target="_blank" rel="noopener" class="judg-extlink">Open in Slack ↗</a>` : nothing}+ </div>+ </div>+ <div class="judg-pane-title">Message</div>+ <div class="judg-prompt"><pre>${item.message || "(not recorded)"}</pre></div>+ <div class="judg-pane-title">Candidate slate</div>+ <div class="badges">+ ${+ (item.candidates || "").trim()+ ? (item.candidates || "")+ .split(" ")+ .filter(Boolean)+ .map((name: string) => ackTag(name, undefined, name === item.picked))+ : empty("(candidate slate not recorded)")+ }+ </div>+ </div>`;+}+export const activity = new SlackActivity();+export const renderSlackMirror = (state: Row) => activity.mirror(state);+export const renderAmbientJudgments = (state: Row) => activity.log(state, "judgments");+export const renderAckEmojiPicks = (state: Row) => activity.log(state, "ackemoji");++function deniedLog(ack: boolean) {+ return ack ? "Only an org admin can read ack-emoji picks." : "Only an org admin can read ambient judgments.";+}diff --git a/plugins/admin/ui/transcript.ts b/plugins/admin/ui/transcript.tsnew file mode 100644index 000000000..b6c897822--- /dev/null+++ b/plugins/admin/ui/transcript.ts@@ -0,0 +1,640 @@+import { html, nothing } from "lit";+import { classMap } from "lit/directives/class-map.js";+import { repeat } from "lit/directives/repeat.js";+import { node, renderer, badge } from "./shared.ts";+type Row = Record<string, any>;+let generation = 0;+export function cancel() {+ generation++;+}+const brain = html`<svg+ viewBox="0 0 24 24"+ fill="none"+ stroke-width="1.8"+ stroke-linecap="round"+ stroke-linejoin="round"+ aria-hidden="true"+>+ <path+ d="M12 4.5c-2.1 0-3.7 1.3-3.7 3.1 0 .2 0 .4.1.6A3.6 3.6 0 0 0 6 11.5c0 1 .4 2 1.1 2.6-.1.3-.1.5-.1.8 0 2 1.8 3.6 4 3.6h1.9c2.2 0 4-1.6 4-3.6 0-.3 0-.6-.1-.8.7-.7 1.1-1.6 1.1-2.6 0-1.5-.9-2.8-2.3-3.3 0-.2.1-.4.1-.6 0-1.8-1.6-3.1-3.7-3.1Z"+ />+ <path d="M9.2 9.2c.9.1 1.6.6 2 1.4" />+ <path d="M14.8 9.2c-.9.1-1.6.6-2 1.4" />+ <path d="M12 10.7v7.8" />+</svg>`;+export function prepare(data: Row, requests: Row[]) {+ const entries: Row[] = data.entries || [],+ events: Row[] = data.deliveryEvents || [],+ llm = new Map<any, Row[]>(),+ byEntry = new Map<any, Row[]>(),+ dur = new Map<number, number>();+ for (const req of requests) {+ const key = req.turnSeq ?? "_orphan";+ if (!llm.has(key)) llm.set(key, []);+ llm.get(key)!.push(req);+ }+ for (let i = 1; i < entries.length; i++) {+ const delta = (entries[i].createdAt || 0) - (entries[i - 1].createdAt || 0);+ if (delta >= 0) dur.set(entries[i].seq, delta);+ }+ const seqIndex = new Map(entries.map((e, i) => [e.seq, i]));+ for (const [turn, reqs] of llm) {+ if (turn === "_orphan" || turn < (entries[0]?.seq || 0)) continue;+ const start = seqIndex.get(turn);+ if (start === undefined) {+ llm.set("_orphan", [...(llm.get("_orphan") || []), ...reqs]);+ continue;+ }+ let stop = entries.findIndex((e, i) => i > start && e.type === "user");+ if (stop < 0) stop = entries.length;+ let anchor = start;+ for (let i = stop - 1; i > start; i--)+ if (entries[i].type === "assistant") {+ anchor = i;+ break;+ }+ byEntry.set(entries[anchor].seq, [+ ...(byEntry.get(entries[anchor].seq) || []),+ ...reqs.slice().sort((a, b) => (a.step || 0) - (b.step || 0)),+ ]);+ }+ const results = new Map<any, Row>(),+ outbound = new Map<any, Row>(),+ principalIds = new Set(),+ pairedSeqs = new Set(),+ merged = new Set();+ for (const e of entries)+ if (e.type === "tool_result" && e.payload?.callId && !results.has(e.payload.callId))+ results.set(e.payload.callId, e);+ for (const e of events) {+ if (e.deliveryId && e.type === "outbound_delivery" && !outbound.has(e.deliveryId)) outbound.set(e.deliveryId, e);+ if (e.deliveryId && e.type === "principal_delivery") principalIds.add(e.deliveryId);+ }+ const units: Row[] = [];+ for (let i = 0; i < entries.length; i++) {+ const e = entries[i];+ if (e.type === "soul") continue;+ if (e.type === "tool_call" || e.type === "tool_result") {+ if (e.type === "tool_result" && pairedSeqs.has(e.seq)) continue;+ let paired: Row | undefined;+ if (e.type === "tool_call") {+ if (e.payload?.callId) paired = results.get(e.payload.callId);+ else if (entries[i + 1]?.type === "tool_result") paired = entries[i + 1];+ }+ if (paired) pairedSeqs.add(paired.seq);+ const deliveryId = (e.type === "tool_result" ? e : paired)?.payload?.deliveryId,+ delivery = outbound.get(deliveryId);+ if (delivery) merged.add(deliveryId);+ units.push({ kind: "tool", primary: e, paired, delivery, llmReqs: byEntry.get(e.seq) });+ } else units.push({ kind: "entry", entry: e, llmReqs: byEntry.get(e.seq) });+ }+ for (const event of events)+ if (!event.deliveryId || !merged.has(event.deliveryId)) units.push({ kind: "delivery_event", event });+ units.sort(+ (a, b) => ((a.primary || a.entry || a.event)?.createdAt || 0) - ((b.primary || b.entry || b.event)?.createdAt || 0),+ );+ if (llm.get("_orphan")?.length) units.push({ kind: "llm", reqs: llm.get("_orphan") });+ return {+ units,+ dur,+ principalIds,+ originPromptSeq: data.origin && !data.hasMore ? entries.find((e) => e.type === "user")?.seq : null,+ };+}+export function requestsPanel(requests: Row[], s: Row, opts: Row = {}) {+ const host = document.createDocumentFragment(),+ draw = renderer(host as unknown as HTMLElement);+ let open = !!opts.embedded;+ const sections = requests.map((q) => s.contextSections(s.requestBody(q), q.transport));+ const selected = sections.map((list: Row[]) =>+ opts.selectLargest && list.length ? list.reduce((a, b) => (b.tokens > a.tokens ? b : a)).key : null,+ );+ const latest = requests.at(-1) || { request: {} },+ latestSections = opts.latestSections || sections.at(-1) || [],+ cache = s.sumCacheUsage(requests);+ const stats = () =>+ html`<div class="context-stats">+ ${s.metaChip((latest.model || "?") + " · " + s.fmtContextSize(latest, latestSections))}${s.cacheMetaItems(cache)}${s.rawJsonLink(requests)}+ </div>`;+ function paint() {+ draw(+ html`<div+ class=${classMap({ entry: !opts.embedded, collapsed: !open, llm: true, "context-turn": true, "context-page": !!opts.page, "cache-miss": !!cache && s.isStablePrefixMiss(cache) })}+ >+ ${+ opts.page+ ? nothing+ : html`<div class="who">+ ${+ opts.embedded+ ? nothing+ : html`<button+ type="button"+ class="disclosure"+ aria-expanded=${String(open)}+ aria-label=${open ? "Collapse model context" : "Expand model context"}+ title=${open ? "Collapse model context" : "Expand model context"}+ @click=${() => {+ open = !open;+ paint();+ }}+ >+ ${open ? "▾" : "▸"}</button+ ><span class="role">sent to model</span>`+ }${stats()}+ </div>`+ }+ <div class="context-details">+ ${requests.map((q, index) => {+ const list: Row[] = sections[index],+ total = list.reduce((n, section) => n + section.tokens, 0),+ chosen = list.find((section) => section.key === selected[index]);+ return html`<div class="context-request">+ ${requests.length > 1 ? html`<div class="context-request-head"><strong>${"Request " + (index + 1)}</strong><span>${(q.model || "?") + " · " + s.fmtContextSize(q, list)}</span></div>` : nothing}${q.truncated ? html`<p class="context-note">Stored payload was truncated.</p>` : nothing}+ <div class="context-overview">+ <div class="context-stack" role="group" aria-label="request context">+ ${list.map((section) => {+ const title =+ section.label + " · " + s.fmtTokens(section.tokens) + (section.note ? " · " + section.note : "");+ return html`<button+ type="button"+ class=${"context-segment ctx-" + (section.colorKey || section.key) + (chosen === section ? " active" : "")}+ style=${"flex-grow:" + Math.max(section.tokens, 1) + ";flex-basis:" + (total ? Math.max(2, Math.round((section.tokens / total) * 100)) + "%" : "1%")}+ data-tiny=${total && section.tokens / total < 0.12 ? "true" : "false"}+ title=${title}+ aria-label=${title}+ aria-pressed=${String(chosen === section)}+ @click=${() => {+ selected[index] = section.key;+ paint();+ }}+ >+ <span>${section.label}</span><small>${"~" + s.fmtTokens(section.tokens)}</small>+ </button>`;+ })}+ </div>+ </div>+ <div class="context-selection">+ ${+ chosen+ ? html`<div class="context-section-view">+ <div class="context-section-head">+ <strong>${chosen.label}</strong+ ><span>${s.fmtTokens(chosen.tokens) + (chosen.note ? " · " + chosen.note : "")}</span>+ </div>+ <pre>${chosen.text || "(empty)"}</pre>+ </div>`+ : nothing+ }+ </div>+ </div>`;+ })}+ </div>+ </div>`,+ );+ }+ paint();+ return host.firstElementChild as HTMLElement;+}+export async function contextPage(sessionId: string, turnSeq: string, s: Row) {+ const request = ++generation,+ root = document.getElementById("view-data")!;+ root.replaceChildren();+ const draw = renderer(root);+ s.pageShell({ back: { label: "← Back to transcript", onClick: () => history.back() }, title: "Sent to model" });+ draw(html`<div class="detail">Loading…</div>`);+ const result = await s.api(+ "GET",+ "/api/sessions/" ++ encodeURIComponent(sessionId) ++ "/llm?turnSeq=" ++ encodeURIComponent(turnSeq) ++ "&scope=" ++ encodeURIComponent(s.scope),+ );+ if (request !== generation || !s.current(sessionId, turnSeq)) return;+ if (!result.ok)+ return draw(+ html`<div class="detail">${result.data?.message || `Failed to load context (${result.status}).`}</div>`,+ );+ const requests = (result.data.requests || []).slice().sort((a: Row, b: Row) => (a.step || 0) - (b.step || 0)),+ label = turnSeq === "orphan" ? "unattributed context" : `turn #${turnSeq}`,+ latest = requests.at(-1),+ sections = latest ? s.contextSections(s.requestBody(latest), latest.transport) : [];+ draw(+ html`<div class="detail">+ <div class="context-page-head">+ <h2>${"Sent to model · " + label + (requests.length > 1 ? " · " + requests.length + " steps" : "")}</h2>+ ${requests.length ? html`<div class="context-stats">${s.metaChip((latest.model || "?") + " · " + s.fmtContextSize(latest, sections))}${s.cacheMetaItems(s.sumCacheUsage(requests))}${s.rawJsonLink(requests)}</div>` : nothing}+ </div>+ ${requests.length ? requestsPanel(requests, s, { embedded: true, page: true, selectLargest: true, latestSections: sections }) : html`<p class="context-empty">No context was captured for this turn.</p>`}+ </div>`,+ );+}+export async function show(sessionId: string, limit: number | undefined, expand: boolean | undefined, s: Row) {+ const request = ++generation,+ root = document.getElementById("view-data")!,+ reqLimit = limit || s.pageSize;+ root.replaceChildren();+ const draw = renderer(root),+ current = () => request === generation && s.current(sessionId);+ const back = (sessionScope?: string) => () => {+ if (history.state?.deepLink)+ s.go({ view: "history", scope: sessionScope || s.scope, session: null, historyKind: s.historyKind });+ else history.back();+ };+ s.pageShell({+ back: { label: "← Conversations", onClick: back() },+ title: "Conversation",+ context: s.shortName(s.scope),+ });+ let applyVisibility = () => {};+ const header = document.getElementById("header-controls")!;+ header.replaceChildren();+ const paintHeader = renderer(header);+ function controls() {+ paintHeader(+ html`${[+ ["thinking", "thinking"],+ ["tool results", "toolResults"],+ ].map(+ ([label, key]) =>+ html`<label class="header-check"+ ><input+ type="checkbox"+ .checked=${!!s.visibility[key]}+ aria-label=${"Show " + label}+ @change=${(e: Event) => {+ s.visibility[key] = (e.target as HTMLInputElement).checked;+ applyVisibility();+ }}+ /><span class="header-check-prefix">Show </span>${label}</label+ >`,+ )}`,+ );+ }+ controls();+ draw(html`<div class="detail">Loading…</div>`);+ const llmPromise = s.api(+ "GET",+ "/api/sessions/" + encodeURIComponent(sessionId) + "/llm?scope=" + encodeURIComponent(s.scope),+ );+ const result = await s.api(+ "GET",+ "/api/sessions/" + encodeURIComponent(sessionId) + "?scope=" + encodeURIComponent(s.scope) + "&limit=" + reqLimit,+ );+ if (!current()) return;+ if (!result.ok)+ return draw(+ html`<div class="detail">${result.data?.message || `Failed to load transcript (${result.status}).`}</div>`,+ );+ const data = result.data,+ session = data.session || {},+ origin = data.origin,+ owner = session.scopeId?.startsWith("personal:") ? session.scopeId.slice(9) : null;+ s.pageShell({+ back: { label: "← Conversations", onClick: back(session.scopeId) },+ title: origin?.label || "Conversation",+ context:+ s.shortName(session.scopeId || s.scope) + (session.createdAt ? " · created " + s.relTime(session.createdAt) : ""),+ actions: owner ? [s.webUiAsButton(owner)] : [],+ });+ let requests: Row[] = [];+ try {+ const llm = await llmPromise;+ if (llm.ok) requests = llm.data.requests || [];+ } catch {+ requests = [];+ }+ if (!current()) return;+ const { units, dur, principalIds, originPromptSeq } = prepare(data, requests),+ open = new Set<Row>(),+ bodyNodes = new Map<Row, Node>(),+ toolNodes = new Map<Row, Row>(),+ panels = new Map<Row, Node>();+ let errors: Row[] = [],+ first = 0,+ paused = false;+ const observer =+ "IntersectionObserver" in window+ ? new IntersectionObserver(+ (entries) => {+ if (entries.some((e) => e.isIntersecting)) reveal();+ },+ { rootMargin: "800px 0px" },+ )+ : null;+ s.setObserver(observer);+ if (observer && !expand) {+ first = Math.max(0, units.length - 60);+ while (first > 0 && units[first].kind === "llm") first--;+ }+ const contextButton = (turn: any, count: number) =>+ html`<button+ type="button"+ class="context-icon"+ aria-label="View context sent to the model"+ title=${"View context sent to the model · " + count + " request" + (count === 1 ? "" : "s")}+ @click=${(e: Event) => {+ e.stopPropagation();+ s.go({ view: "history", scope: s.scope, session: sessionId, turn });+ }}+ >+ ${brain}+ </button>`;+ const timing = (unit: Row) => {+ const call = unit.primary.type === "tool_call" ? unit.primary : null,+ res = unit.primary.type === "tool_result" ? unit.primary : unit.paired;+ return call && res+ ? [+ [dur.get(call.seq), "model"],+ [(res.createdAt || 0) - (call.createdAt || 0), "exec"],+ ]+ : [[dur.get((call || res)?.seq)]];+ };+ function fullTool(unit: Row) {+ if (!toolNodes.has(unit)) {+ const call = unit.primary.type === "tool_call" ? unit.primary : null,+ res = unit.primary.type === "tool_result" ? unit.primary : unit.paired;+ toolNodes.set(+ unit,+ s.renderToolEntry(+ call,+ res,+ unit.llmReqs?.length ? node(contextButton(unit.llmReqs[0].turnSeq, unit.llmReqs.length)) : null,+ s.stepDurEl(timing(unit)),+ unit.delivery || null,+ ),+ );+ }+ const built = toolNodes.get(unit)!;+ built.sync?.();+ return built.block;+ }+ const cronLink = (cronOrigin: Row | null, ownerScope?: string) =>+ cronOrigin?.kind === "cron"+ ? html`<button+ type="button"+ class="link"+ @click=${() => s.go({ view: "crons", scope: cronOrigin.cron?.ownerScopeId || ownerScope || s.scope, session: null, cron: cronOrigin.cronId })}+ >+ View cron+ </button>`+ : nothing;+ function body(entry: Row) {+ if (!bodyNodes.has(entry)) {+ const text = s.payloadText(entry.payload);+ let value: Node;+ if (entry.type === "user" && s.isXmlishText(text)) value = s.renderXmlish(text);+ else if (entry.type === "user" || entry.type === "assistant") value = s.renderMarkdown(text);+ else value = node(html`<pre>${text}</pre>`);+ if ((value as Element).tagName === "PRE") value.textContent = text;+ bodyNodes.set(entry, value);+ }+ return bodyNodes.get(entry);+ }+ function unitTemplate(unit: Row) {+ if (unit.kind === "llm")+ return html`<div class="entry llm">+ <div class="who">${contextButton("orphan", unit.reqs.length)}<span class="role">captured context</span></div>+ </div>`;+ if (unit.kind === "tool") {+ const e = unit.primary,+ call = e.type === "tool_call" ? e : null,+ res = e.type === "tool_result" ? e : unit.paired,+ types = unit.paired ? ["tool_call", "tool_result"] : [e.type];+ if (unit.delivery) {+ types.push("outbound_delivery");+ if (principalIds.has(unit.delivery.deliveryId)) types.push("principal_delivery");+ }+ const hidden = s.entryHidden(types, !!unit.delivery),+ full = fullTool(unit);+ full.classList.toggle("filtered", hidden);+ if (unit.delivery || unit.llmReqs?.length) return full;+ const cp = call?.payload,+ rp = res?.payload,+ name = s.toolName(cp, rp),+ toggle = () => {+ if (open.has(unit)) open.delete(unit);+ else open.add(unit);+ paint();+ };+ return html`<div+ class=${classMap({ entry: true, "tool-entry": true, "tool-line-entry": true, open: open.has(unit), filtered: hidden })}+ >+ <div+ class="who tool-line"+ tabindex="0"+ role="button"+ title="Toggle full tool card"+ aria-expanded=${String(open.has(unit))}+ @click=${(e: MouseEvent) => {+ if (!(e.target as Element).closest(".copy")) toggle();+ }}+ @keydown=${(e: KeyboardEvent) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ toggle();+ }+ }}+ >+ <span class="tool-line-caret">${open.has(unit) ? "▾" : "▸"}</span+ ><span class="tool-label">${s.toolLabelText(name, cp, rp)}</span+ ><span class="tool-line-preview">${s.firstLine(s.toolPrimaryText(cp, rp, !!call, !!res) || "", 240)}</span+ >${s.stepDurEl(timing(unit))}<span class="when"+ >${call && res ? `#${call.seq}→#${res.seq} · ${s.fmtTime(call.createdAt)}` : `#${e.seq} · ${s.fmtTime(e.createdAt)}`}</span+ >+ <div class="meta-row">${s.toolStatusMeta(name, rp, !!res)}</div>+ ${s.copyButton("Copy", () => s.toolCopyText(call, res))}+ </div>+ ${full}+ </div>`;+ }+ if (unit.kind === "delivery_event") {+ const event = unit.event,+ outbound = event.type === "outbound_delivery",+ delivery = outbound || event.type === "principal_delivery",+ provenance = event.provenance,+ label = event.origin?.label || s.wakeOriginLabel(provenance?.trigger || provenance?.surface),+ mirror = s.slackMirrorRef(event),+ text = event.text || "";+ let deliveryState = "delivery";+ if (event.shadow) deliveryState = "shadow";+ else if (event.expiredAt) deliveryState = "dropped";+ else if (delivery) deliveryState = "delivered";+ const bodyText = [+ event.destination?.onBehalfOf ? "from " + event.destination.onBehalfOf : null,+ outbound && event.destination?.target ? "to " + event.destination.target : null,+ event.provenance?.fireKey || event.origin?.fireKey+ ? "origin " + (event.provenance?.fireKey || event.origin.fireKey)+ : null,+ outbound && event.recipientThreadRef ? "recipient thread " + event.recipientThreadRef : null,+ text,+ ]+ .filter((x) => x != null)+ .join("\n")+ .trim();+ if (event.llmRequests?.length && !panels.has(unit))+ panels.set(unit, requestsPanel(event.llmRequests, s, { embedded: true }));+ let originLink: unknown = nothing;+ if (provenance) originLink = s.metaChip(label);+ if (event.sourceSession?.id)+ originLink = html`<button+ type="button"+ class="origin-link"+ title=${`Open origin session ${s.shortId(event.sourceSession.id)} · ${provenance?.fireKey || event.idempotencyKey || ""}`}+ @click=${() => s.go({ view: "history", scope: s.scope, session: event.sourceSession.id })}+ >+ ${label}+ </button>`;+ const toggle = () => {+ if (open.has(unit)) open.delete(unit);+ else open.add(unit);+ paint();+ };+ return html`<div+ class=${classMap({ entry: true, "delivery-event-entry": true, filtered: s.entryHidden([outbound ? "outbound_delivery" : "principal_delivery"], false) })}+ >+ <div class="who">+ ${event.llmRequests?.length ? html`<button type="button" class=${"context-icon" + (open.has(unit) ? " active" : "")} aria-expanded=${String(open.has(unit))} aria-label=${(open.has(unit) ? "Hide" : "Show") + " context"} title=${(open.has(unit) ? "Hide" : "Show") + " context · " + event.llmRequests.length + " request" + (event.llmRequests.length === 1 ? "" : "s")} @click=${toggle}>${brain}</button>` : nothing}<span+ class="entry-label important"+ >${event.shadow || delivery ? s.deliveryLabel(event) : "Delivery event"}</span+ >${event.shadow ? html`<span class="entry-label" title="Recorded for observability, never sent to the human (shadow-mode rollout)">not sent</span>` : nothing}${!event.shadow && event.expiredAt ? html`<span class="entry-label" title="Dropped undelivered — the destination failed permanently or the message aged out">never sent</span>` : nothing}${delivery ? badge(s.deliverySurfaceLabel(event), "info") : nothing}${outbound ? nothing : originLink}${cronLink(event.origin)}${+ mirror+ ? html`<a+ class="link"+ href=${s.stateToUrl({ view: "slack", container: mirror.container, ts: mirror.ts })}+ title=${"Jump to this message in the mirrored Slack channel " + mirror.container}+ @click=${(e: MouseEvent) => {+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;+ e.preventDefault();+ s.go({ view: "slack", container: mirror.container, ts: mirror.ts });+ }}+ >View in Slack mirror ↗</a+ >`+ : nothing+ }<span class="when">${deliveryState + " · " + s.fmtTime(event.createdAt)}</span+ >${s.copyButton("Copy", () => text)}+ </div>+ ${panels.has(unit) ? panelVisibility(panels.get(unit)!, open.has(unit)) : nothing}+ <pre>${bodyText}</pre>+ ${s.deliveryFileBadges(event.attachments)}+ </div>`;+ }+ const e = unit.entry,+ noise = s.entryIsNoise(e),+ isOrigin = origin && e.type === "user" && e.seq === originPromptSeq,+ text = s.payloadText(e.payload);+ let label = s.titleCase(e.type || "entry");+ if (e.type === "assistant") label = s.brandSelfLabel();+ else if (e.type === "user") label = s.payloadName(e.payload) || "User";+ if (isOrigin) label = origin.label || s.wakeOriginLabel(origin.trigger);+ const toggle = () => {+ if (open.has(unit)) open.delete(unit);+ else open.add(unit);+ paint();+ };+ const files =+ e.type === "delivery" || (e.type === "tool_result" && e.payload?.tool === "attach")+ ? s.deliveryFileBadges(e.payload?.files || [])+ : nothing;+ return html`<div+ class=${classMap({ entry: true, noise, collapsed: noise && !open.has(unit), "thinking-entry": e.type === "thinking", "message-entry": e.type === "user" || e.type === "assistant", "user-entry": e.type === "user", "assistant-entry": e.type === "assistant", "cron-prompt-entry": !!isOrigin, "system-entry": e.type === "soul" || e.type === "system", filtered: s.entryHidden([e.type], false) })}+ >+ <div class="who">+ ${unit.llmReqs?.length ? contextButton(unit.llmReqs[0].turnSeq, unit.llmReqs.length) : nothing}${noise ? html`<button type="button" class="disclosure" aria-expanded=${String(open.has(unit))} aria-label=${open.has(unit) ? "Collapse entry" : "Expand entry"} title=${open.has(unit) ? "Collapse entry" : "Expand entry"} @click=${toggle}>${open.has(unit) ? "▾" : "▸"}</button>` : nothing}<span+ class=${"entry-label" + (isOrigin ? " important" : "")}+ >${label}</span+ >${isOrigin ? cronLink(origin, session.scopeId) : nothing}${e.type !== "user" ? s.stepDurEl([[dur.get(e.seq)]]) : nothing}<span+ class="when"+ >${"#" + e.seq + " · " + s.fmtTime(e.createdAt)}</span+ >${s.copyButton("Copy", () => text)}+ </div>+ ${body(e)}${files}+ </div>`;+ }+ function panelVisibility(panel: Node, visible: boolean) {+ (panel as HTMLElement).classList.add("inline-context");+ (panel as HTMLElement).classList.toggle("collapsed", !visible);+ return panel;+ }+ const load = () => {+ if (first > 0) reveal();+ else void show(sessionId, reqLimit * 4, true, s);+ };+ function paint() {+ if (!current()) return;+ controls();+ const more = first === 0 || paused;+ draw(+ html`<div class="detail">+ <div>+ ${errors.length ? s.errorStripBox(errors, s.plural(errors.length, "error") + " logged in this session", 5) : nothing}+ </div>+ ${+ units.length+ ? html`<div class="transcript-stream">+ ${+ first > 0 || data.hasMore+ ? html`<div+ class=${"load-earlier" + (more ? " more" : "")}+ aria-hidden=${String(!more)}+ role=${more ? "button" : "presentation"}+ tabindex=${more ? 0 : -1}+ @click=${more ? load : nothing}+ @keydown=${(e: KeyboardEvent) => {+ if (more && (e.key === "Enter" || e.key === " ")) {+ e.preventDefault();+ load();+ }+ }}+ >+ ${more ? "Load earlier messages" : "Loading earlier messages…"}+ </div>`+ : nothing+ }${repeat(units.slice(first), (unit) => unit, unitTemplate)}+ </div>`+ : html`<p class="empty">No entries.</p>`+ }+ </div>`,+ );+ }+ function reveal() {+ if (!current() || first <= 0) return;+ observer?.disconnect();+ const height = document.body.scrollHeight,+ top = window.scrollY;+ first = Math.max(0, first - 60);+ while (first > 0 && units[first].kind === "llm") first--;+ paused = false;+ paint();+ const added = document.body.scrollHeight - height;+ window.scrollTo({ top: top + added });+ if (first > 0 && observer) {+ if (added > 1) observe();+ else {+ paused = true;+ paint();+ }+ }+ }+ function observe() {+ const sentinel = root.querySelector(".load-earlier");+ if (sentinel && first > 0) observer?.observe(sentinel);+ }+ applyVisibility = paint;+ paint();+ observe();+ void s+ .adminErrors("scope=" + encodeURIComponent(s.scope) + "&sessionId=" + encodeURIComponent(sessionId))+ .then((rows: Row[]) => {+ if (current()) {+ errors = rows;+ paint();+ }+ })+ .catch(() => {});+ requestAnimationFrame(() => {+ if (current()) window.scrollTo({ top: expand ? 0 : document.body.scrollHeight });+ });+}diff --git a/plugins/admin/ui/user-detail.ts b/plugins/admin/ui/user-detail.tsnew file mode 100644index 000000000..0eca1da52--- /dev/null+++ b/plugins/admin/ui/user-detail.ts@@ -0,0 +1,323 @@+import { html, nothing } from "lit";+import { card, table, badge, renderer } from "./shared.ts";++export async function detail(root: HTMLElement, principal: string, s: Record<string, any>) {+ const paint = renderer(root);+ const back = { label: "← Users", onClick: () => window.history.back() };+ s.pageShell({ back, title: principal || "User" });+ paint(html`<div class="detail">Loading…</div>`);+ const r = await s.api("GET", "/api/users/" + encodeURIComponent(principal));+ if (!s.current(principal)) return;+ if (!r.ok) {+ paint(+ html`<div class="detail">+ ${r.status === 403 ? "You don't have admin access." : r.data?.message || `Failed to load user (${r.status}).`}+ </div>`,+ );+ return;+ }+ const d = r.data || {};+ s.pageShell({+ back,+ title: d.displayName || d.principalId || principal,+ context: [d.admin?.isAdmin ? s.labelRole(d.admin.role) : "member", d.scopeId || ""].filter(Boolean).join(" · "),+ });+ const personalScope = d.scopeId || "personal:" + principal;+ let onboarding = d.onboarding || "not_started";+ let busy = false;+ let hint = "";+ let resetHint = "";+ let credentials: any = null;+ let credentialError = "";+ let sort = "default";+ let selectedGrant: any = null;+ let usage: any = null;+ let usageRequest = 0;+ const stacked = (primary: any, secondary: any) =>+ html`<div>+ <div class="primaryline">${primary}</div>+ ${secondary ? html`<div class="subline">${secondary}</div>` : nothing}+ </div>`;+ const muted = (text: string) => html`<span class="subline">${text}</span>`;+ const credName = (id: string) => {+ const c = credentials?.credentials?.find((c: any) => c.id === id);+ return c ? c.service + (c.accountLabel ? " - " + c.accountLabel : "") : id;+ };+ async function setOnboarding(status: string) {+ busy = true;+ hint = "Saving…";+ draw();+ try {+ const result = await s.api("PUT", "/api/users/" + encodeURIComponent(principal) + "/onboarding", { status });+ if (!result.ok) hint = result.data?.message || "Failed (" + result.status + ").";+ else {+ onboarding = result.data?.status || status;+ hint = status === "not_started" ? "Reset. Onboarding will run on this person's next DM." : "Saved.";+ }+ } catch {+ hint = "Network error. Try again.";+ } finally {+ busy = false;+ draw();+ }+ }+ async function reset() {+ if (+ !s.confirm(+ "Delete this person's personal DM sessions (transcripts included) and clear their onboarding?\n\nThis is irreversible. Their channel history is untouched. On their next web visit they'll see the new-user welcome greeting, then onboarding.",+ )+ )+ return;+ busy = true;+ resetHint = "Resetting…";+ draw();+ try {+ const result = await s.api("POST", "/api/users/" + encodeURIComponent(principal) + "/reset");+ if (!result.ok) resetHint = result.data?.message || "Failed (" + result.status + ").";+ else if (s.current(principal)) {+ s.reload(principal);+ return;+ }+ } catch {+ resetHint = "Network error. Try again.";+ } finally {+ busy = false;+ draw();+ }+ }+ async function showUsage(grant: any) {+ const request = ++usageRequest;+ selectedGrant = grant;+ usage = null;+ draw();+ const result = await s.api(+ "GET",+ "/api/audit?scope=org:" ++ encodeURIComponent(s.orgId) ++ "&action=keychain.materialize&resource=" ++ encodeURIComponent("grant " + grant.id) ++ "&limit=2000",+ );+ if (request !== usageRequest) return;+ usage = result.ok ? result.data?.events || [] : [];+ draw();+ }+ function keychain() {+ if (credentialError) return credentialError;+ if (!credentials) return "Loading credentials and grants…";+ if (credentials.enabled === false) return html`<div><p class="empty">Keychain is not enabled.</p></div>`;+ const creds = credentials.credentials || [];+ const grants = credentials.grants || [];+ const group: Record<string, number> = { active: 0, used: 1, expired: 2, revoked: 3 };+ const timestamp = (g: any) => g.usedAt || g.revokedAt || g.createdAt || 0;+ const sorted = grants.slice().sort((a: any, b: any) => {+ if (sort === "mode") return String(a.mode).localeCompare(String(b.mode)) || timestamp(b) - timestamp(a);+ if (sort === "status") return String(a.status).localeCompare(String(b.status)) || timestamp(b) - timestamp(a);+ return (group[a.status] ?? 9) - (group[b.status] ?? 9) || timestamp(b) - timestamp(a);+ });+ return html`<div>+ ${card(+ "Credentials (" + creds.length + ")",+ "Logins this person registered in their keychain. Metadata only — secrets are never returned.",+ table(+ ["Service", "Kind", "Origin", "Account", "Added"],+ creds+ .slice()+ .sort((a: any, b: any) => (b.updatedAt || b.createdAt || 0) - (a.updatedAt || a.createdAt || 0))+ .map((c: any) => [+ { node: stacked(c.service, c.id), cls: "mono" },+ { node: muted(c.kind || "unknown") },+ { node: muted(c.origin || "-") },+ c.accountLabel || c.envKey || c.host || "-",+ { text: c.createdAt ? s.fmtTime(c.createdAt) : "-", cls: "num" },+ ]),+ "No credentials registered.",+ ),+ )}${card(+ "Grants (" + grants.length + ")",+ "Purpose-bound grants this person issued. Every use — standing or one-time — is audited.",+ html`<div>+ ${+ selectedGrant+ ? html`<p class="kc-sortbar">+ <button+ type="button"+ class="link"+ @click=${() => {+ ++usageRequest;+ selectedGrant = null;+ draw();+ }}+ >+ ‹ Back to grants+ </button>+ </p>+ <p class="hint">+ ${credName(selectedGrant.credentialId) + " · " + (selectedGrant.mode || "?") + " · " + (selectedGrant.status || "?") + " · grant " + selectedGrant.id}+ </p>+ ${+ usage === null+ ? html`<p class="empty">Loading usage…</p>`+ : table(+ ["When", "Used by", "Scope"],+ usage.map((e: any) => [+ { text: s.fmtTime(e.ts), cls: "num" },+ { node: stacked(e.principalId, "") },+ { node: muted(e.scopeLabel || "-") },+ ]),+ "No recorded uses of this grant.",+ )+ }`+ : html`<p class="kc-sortbar">+ Sort:+ ${[+ ["default", "status group"],+ ["mode", "mode"],+ ["status", "status A-Z"],+ ].map(+ ([key, label], i) =>+ html`${i ? " · " : ""}<button+ type="button"+ class=${"link" + (sort === key ? " kc-sort-active" : "")}+ @click=${() => {+ sort = key;+ draw();+ }}+ >+ ${label}+ </button>`,+ )}+ </p>+ ${table(+ ["Credential", "Mode", "Status", "Audience", "Purpose", "Uses"],+ sorted.map((g: any) => [+ { node: stacked(credName(g.credentialId), g.credentialId), cls: "mono" },+ { node: muted(g.mode || "unknown") },+ {+ node: html`<span+ ><span class=${"kc-dot kc-dot-" + (g.status || "unknown")}></span+ >${g.status || "unknown"}</span+ >`,+ },+ { node: stacked(g.audienceScopeId, s.scopeKind(g.audienceScopeId)), cls: "mono" },+ { node: stacked(g.purpose || "-", g.usedBy ? "used by " + g.usedBy : "") },+ {+ action: {+ label: "View usage ›",+ title: "Show recorded uses of this grant",+ run: () => showUsage(g),+ },+ },+ ]),+ "No grants.",+ )}`+ }+ </div>`,+ )}+ </div>`;+ }+ function draw() {+ if (!s.current(principal)) return;+ const cfg = d.config;+ const ruleN = cfg?.commandPolicy?.rules?.length || 0,+ allowN = cfg?.egress?.allowedHosts?.length || 0,+ denyN = cfg?.egress?.deniedHosts?.length || 0;+ const kinds: Record<string, string> = { completed: "ok", dismissed: "muted", pending: "warn", not_started: "info" };+ paint(+ html`<div class="detail">+ <div style="margin:0 0 14px">${s.webUiAsButton(d.principalId || principal)}</div>+ <div class="user-resource-links" aria-label="Personal workspace">+ ${[+ ["history", s.plural(d.stats?.sessions ?? 0, "conversation")],+ ["files", "Files"],+ ["deployments", "Apps"],+ ["crons", "Crons"],+ ["skills", "Skills"],+ ["memory", "Memory"],+ ].map(([view, label]) => html`<a href=${s.stateToUrl({ view, scope: personalScope })}>${label} →</a>`)}+ </div>+ <div>${keychain()}</div>+ ${card(+ "Configuration",+ "Policy and connectors for this person's personal scope.",+ html`<div>+ ${+ !cfg+ ? html`<p class="empty">Config store not available.</p>`+ : table(+ ["Setting", "Value"],+ [+ ["Custom soul", { node: muted(cfg.hasSoul ? "set · v" + (cfg.soulVersion || 1) : "default") }],+ [+ "Command policy",+ cfg.commandPolicy+ ? ruleN ++ " rule" ++ (ruleN === 1 ? "" : "s") ++ " · " ++ (cfg.commandPolicy.mode || "denylist")+ : "default",+ ],+ ["Security posture", cfg.securityPosture || "auto"],+ ["Sharing posture", cfg.sharingPosture || "isolated"],+ ["Egress overrides", allowN || denyN ? allowN + " allow · " + denyN + " deny" : "none"],+ ["Base model", cfg.baseModel || "org default"],+ ["Connectors linked", String((cfg.connectors || []).length)],+ ],+ "No config.",+ )+ }+ </div>+ <button+ type="button"+ class="link"+ @click=${() => s.go({ view: "governance", scope: personalScope, session: null })}+ >+ Manage in Governance →+ </button>`,+ )}${card(+ "Onboarding",+ "Personal-DM onboarding state. Reset to re-trigger the flow on this person's next DM, or wipe their DMs to replay the full new-user experience.",+ html`<div>+ <div class="obstatus">+ Current status:+ ${badge(onboarding === "not_started" ? "not started" : onboarding, kinds[onboarding] || "muted")}+ </div>+ <div class="obactions">+ ${[+ ["Reset (re-run on next DM)", "not_started"],+ ["Mark completed", "completed"],+ ["Mark dismissed", "dismissed"],+ ].map(+ ([label, status], i) =>+ html`<button+ type="button"+ class=${i === 0 ? "primary" : ""}+ ?disabled=${busy}+ @click=${() => setOnboarding(status)}+ >+ ${label}+ </button>`,+ )}+ </div>+ <p class="hint">${hint}</p>+ <div class="obdivider"></div>+ <button type="button" class="danger-link" ?disabled=${busy} @click=${reset}>+ Reset to brand-new (delete this person's DMs) →+ </button>+ <p class="hint">${resetHint}</p>+ </div>`,+ )}+ </div>`,+ );+ }+ draw();+ try {+ const result = await s.api("GET", "/api/keychain?principal=" + encodeURIComponent(d.principalId || principal));+ if (!result.ok) throw new Error(result.data?.message || "Failed to load credentials and grants.");+ credentials = result.data || {};+ } catch (error) {+ credentialError = (error as Error).message || "Failed to load credentials and grants.";+ }+ draw();+}diff --git a/plugins/admin/ui/users.ts b/plugins/admin/ui/users.tsnew file mode 100644index 000000000..260338c2b--- /dev/null+++ b/plugins/admin/ui/users.ts@@ -0,0 +1,358 @@+import { html } from "lit";+import { table, card, renderer } from "./shared.ts";++type Services = Record<string, any>;+export class UsersView {+ root: HTMLElement;+ data: any;+ services: Services;+ paint: (template: unknown) => void;+ filter = "";+ inviteOpen = false;+ email = "";+ role = "member";+ expires = new Date(Date.now() + 30 * 86400000).toISOString().slice(0, 10);+ counts = new Map<string, number[]>();+ pending = new Set<string>();+ refreshRequest = 0;+ message = "";+ tone = "";+ externalMessage = "";+ externalTone = "";+ search: HTMLElement | null = null;+ constructor(root: HTMLElement, data: any, services: Services) {+ this.root = root;+ this.data = data;+ this.services = services;+ this.paint = renderer(root);+ this.renderShell();+ this.draw();+ void services+ .api("GET", "/api/keychain")+ .then((r: any) => {+ if (!root.isConnected || !r.ok || r.data?.enabled === false) return;+ this.counts = new Map(+ (r.data?.people || []).map((p: any) => [p.principalId, [p.credentialCount || 0, p.activeGrantCount || 0]]),+ );+ this.draw();+ })+ .catch(() => {});+ }+ renderShell() {+ const document = this.root.ownerDocument;+ const previous = this.search;+ if (previous && !previous.isConnected) return;+ const active = document.activeElement as HTMLElement | null;+ const focused = !!active && !!previous?.contains(active);+ this.services.defaultShell({+ stats: [+ [(this.data.users || []).length, "Users"],+ [(this.data.grants || []).length, "Admins"],+ ],+ search: {+ value: this.filter,+ placeholder: "principal, role, or scope",+ onInput: (value: string) => {+ this.filter = value;+ this.draw();+ },+ },+ });+ const search = document.querySelector<HTMLElement>("#shellbar .shell-search");+ if (previous && search) {+ search.replaceWith(previous);+ if (focused) active?.focus({ preventScroll: true });+ } else this.search = search;+ }+ async action(key: string, work: () => Promise<void>, external = false) {+ if (this.pending.has(key)) return;+ this.pending.add(key);+ if (external) this.externalMessage = "";+ else this.message = "";+ this.draw();+ try {+ await work();+ } catch {+ this.feedback("Network error. Try again.", "err", external);+ } finally {+ this.pending.delete(key);+ if (this.root.isConnected) this.draw();+ }+ }+ feedback(message: string, tone: string, external = false) {+ if (external) {+ this.externalMessage = message;+ this.externalTone = tone;+ } else {+ this.message = message;+ this.tone = tone;+ }+ }+ async refresh() {+ const request = ++this.refreshRequest;+ const r = await this.services.api("GET", "/api/users");+ if (request !== this.refreshRequest) return;+ if (r.ok) {+ this.data = r.data;+ this.renderShell();+ }+ this.services.clearCache();+ }+ async admin(user: any, event: Event) {+ event.stopPropagation();+ const revoke = user.admin?.isAdmin;+ if (!this.services.confirm((revoke ? "Revoke admin access for " : "Make admin: ") + user.principalId + "?")) return;+ await this.action(user.principalId, async () => {+ const r = revoke+ ? await this.services.api(+ "DELETE",+ "/api/grants/" ++ encodeURIComponent(user.principalId) ++ "?scope=" ++ encodeURIComponent(user.admin.scopeId) ++ "&role=" ++ encodeURIComponent(user.admin.role),+ )+ : await this.services.api("POST", "/api/grants", {+ principalId: user.principalId,+ role: "org_admin",+ scopeId: this.services.orgScope,+ });+ if (r.ok) await this.refresh();+ else this.feedback(r.data?.message || "Could not update admin access.", "err");+ });+ }+ async revoke(member: any) {+ if (+ !this.services.confirm(+ member.status === "active"+ ? 'Revoke access for "' + member.email + '"? They will no longer be able to sign in.'+ : 'Remove "' + member.email + '" from the list?',+ )+ )+ return;+ await this.action(+ member.email,+ async () => {+ const r = await this.services.api("DELETE", "/api/external-users/" + encodeURIComponent(member.email));+ if (r.ok) await this.refresh();+ else+ this.feedback(+ r.status === 403 ? "Only an admin may revoke." : r.data?.message || "Revoke failed.",+ "err",+ true,+ );+ },+ true,+ );+ }+ async invite() {+ const body = { email: this.email.trim(), role: this.role, expiresAt: this.expires };+ if (!body.email || !body.expiresAt) {+ this.feedback(!body.email ? "Email required." : "Expiry date required.", "err", true);+ this.draw();+ return;+ }+ await this.action(+ "invite",+ async () => {+ const r = await this.services.api("POST", "/api/external-users", body);+ if (!r.ok)+ return this.feedback(+ r.status === 403 ? "Only an admin may invite." : r.data?.message || "Invite failed.",+ "err",+ true,+ );+ const member = r.data.member;+ const expiry = " (expires " + this.services.fmtTime(member.expiresAt) + ")";+ await this.refresh();+ let message = "Updated " + member.email + " — " + this.services.labelRole(member.role) + expiry;+ if (r.data.emailSent) message = "Invite sent to " + member.email + expiry;+ else if (r.data.emailProblem)+ message =+ "Added " ++ member.email ++ ", but no invitation email was sent: " ++ r.data.emailProblem ++ "." ++ (r.data.signInUrl ? " Portal: " + r.data.signInUrl + ". A working sign-in method is required." : "");+ this.feedback(message, r.data.emailSent || !r.data.emailProblem ? "ok" : "dirty", true);+ if (this.email.trim() === body.email && this.role === body.role && this.expires === body.expiresAt)+ this.inviteOpen = false;+ },+ true,+ );+ }+ draw() {+ const s = this.services;+ const matches = (parts: unknown[]) => parts.join(" ").toLowerCase().includes(this.filter.trim().toLowerCase());+ const users = (this.data.users || []).filter((u: any) =>+ matches([u.principalId, u.admin?.role || "", u.admin?.scopeId || "member"]),+ );+ const externals = (this.data.externalUsers || []).filter((m: any) =>+ matches([m.email, m.role, m.invitedBy || "", m.status]),+ );+ const admins = (this.data.grants || []).filter((g: any) => g.role === "org_admin").length;+ const inviteEmail = this.data.inviteEmail || {};+ const field = (label: string, input: unknown, cls = "") =>+ html`<div class=${"f" + (cls ? " " + cls : "")}>+ <label for=${"users-" + label.toLowerCase()}>${label}</label>${input}+ </div>`;+ const invite = html`<div class=${this.inviteOpen ? "" : "hidden"} style="margin:0 0 14px">+ <div class="grant-form">+ ${field(+ "Email",+ html`<input+ id="users-email"+ type="email"+ placeholder="[email protected]"+ spellcheck="false"+ autocapitalize="none"+ .value=${this.email}+ @input=${(e: Event) => {+ this.email = (e.target as HTMLInputElement).value;+ }}+ />`,+ "grow",+ )}${field(+ "Role",+ html`<select+ id="users-role"+ .value=${this.role}+ @change=${(e: Event) => {+ this.role = (e.target as HTMLSelectElement).value;+ }}+ >+ <option value="member">Member</option>+ <option value="org_admin">Admin</option>+ </select>`,+ )}${field(+ "Expires",+ html`<input+ id="users-expires"+ type="date"+ min=${new Date().toISOString().slice(0, 10)}+ .value=${this.expires}+ @input=${(e: Event) => {+ this.expires = (e.target as HTMLInputElement).value;+ }}+ />`,+ )}<button type="button" class="primary" ?disabled=${this.pending.has("invite")} @click=${() => this.invite()}>+ ${inviteEmail.configured === false ? "Add user" : "Send invite"}+ </button>+ </div>+ <p class=${inviteEmail.configured === false ? "hint flag-warn" : "hint"}>+ ${inviteEmail.configured === false ? (inviteEmail.problem || "Invitation emails are not configured") + ". Users can still be added, but need a configured sign-in method before they can log in." + (inviteEmail.signInUrl ? " Sign-in link to share: " + inviteEmail.signInUrl : "") : "Invitation emails go out through Resend — core needs RESEND_API_KEY and AUTH_EMAIL_FROM. Without them users can still be added, but need a configured sign-in method before they can log in."}+ </p>+ </div>`;+ const externalTable = table(+ ["Email", "Role", "Expires", "Invited by", "Status", ""],+ externals.map((m: any) => [+ { text: m.email, cls: "mono" },+ { node: html`<span class="subline">${s.labelRole(m.role)}</span>` },+ (m.status === "active" ? "Ends " : "Ended ") + new Date(m.expiresAt).toISOString().slice(0, 10) + " (UTC)",+ m.invitedBy || "-",+ { badge: m.status === "active" ? "Active" : "Expired", kind: m.status === "active" ? "ok" : "warn" },+ m.status === "active" || Date.now() - m.expiresAt >= 86400000+ ? {+ action: {+ label: m.status === "active" ? "Revoke" : "Remove",+ danger: m.status === "active",+ disabled: this.pending.has(m.email),+ run: () => this.revoke(m),+ },+ }+ : "",+ ]),+ this.data.externalUsers?.length+ ? "No external users match."+ : "No external users. Use Invite external user to invite an outside collaborator.",+ );+ const roster = table(+ ["Principal", "Role", "Last seen", "Sessions", "Turns", "Credentials", "Grants", "", ""],+ users.map((u: any) => [+ { text: u.principalId, cls: "mono" },+ { node: html`<span class="subline">${u.admin?.isAdmin ? s.labelRole(u.admin.role) : "member"}</span>` },+ u.lastSeenAt+ ? { node: html`<span title=${s.fmtTime(u.lastSeenAt)}>${s.relTime(u.lastSeenAt)}</span>`, cls: "num" }+ : { text: "-", cls: "num" },+ { text: String(u.sessionCount), cls: "num" },+ { text: String(u.turnCount), cls: "num" },+ ...[0, 1].map((i) => ({+ text: this.counts.has(u.principalId) ? String(this.counts.get(u.principalId)![i]) : "-",+ cls: "num",+ })),+ {+ action: {+ label: "Impersonate ↗",+ run: (event: Event) => {+ event.stopPropagation();+ s.openWebUiAs(u.principalId);+ },+ },+ },+ {+ action: {+ label: u.admin?.isAdmin ? "Revoke" : "Make admin",+ danger: !!u.admin?.isAdmin,+ disabled: this.pending.has(u.principalId) || (u.admin?.isAdmin && admins <= 1),+ title: u.admin?.isAdmin && admins <= 1 ? "The last admin cannot be revoked." : "",+ run: (event: Event) => this.admin(u, event),+ },+ },+ ]),+ "No users match.",+ (i) => s.openUser(users[i].principalId),+ );+ this.paint(+ html`<div class="users-layout">+ <div class="list-root">+ <section class="card users-roster">+ <div class="head">+ <h2>External users</h2>+ <p>+ Outside collaborators invited by email until an expiry date. Org members do not need an external invite.+ </p>+ <button+ type="button"+ class="rowbtn"+ title="Invite external user"+ aria-label="Invite external user"+ aria-expanded=${String(this.inviteOpen)}+ @click=${() => {+ this.inviteOpen = !this.inviteOpen;+ this.draw();+ if (this.inviteOpen) this.root.querySelector<HTMLInputElement>("#users-email")?.focus();+ }}+ >+ Invite external user+ </button>+ </div>+ <div class="body">+ ${invite}${externalTable}+ <p+ id="st-external"+ class=${"status" + (this.externalTone ? " " + this.externalTone : "")}+ style="margin:10px 0 0"+ >+ ${this.externalMessage}+ </p>+ </div>+ </section>+ ${card(+ "Users",+ "Everyone who has used the agent — click a row for their activity, artifacts, and config.",+ html`<p class=${"status" + (this.tone ? " " + this.tone : "")} id="st-users" role="status">+ ${this.message}+ </p>+ ${roster}`,+ )}+ </div>+ </div>`,+ );+ }+}++export function users(root: HTMLElement, data: any, services: Services) {+ return new UsersView(root, data, services);+}diff --git a/plugins/web-ui/README.md b/plugins/web-ui/README.mdindex 7d085ec9d..7d026866f 100644--- a/plugins/web-ui/README.md+++ b/plugins/web-ui/README.md@@ -28,6 +28,7 @@ no run bearer is exposed to browser code or placed in a URL. The active-run resu(`/api/runs/active`) is per-process best-effort with a durable core fallback for personal threads.```+npm install --prefix ../adminnpm installnpm run buildnpm run servediff --git a/plugins/web-ui/src/onboarding-slack.ts b/plugins/web-ui/src/onboarding-slack.tsindex 53014ea09..e68a80648 100644--- a/plugins/web-ui/src/onboarding-slack.ts+++ b/plugins/web-ui/src/onboarding-slack.ts@@ -82,7 +82,7 @@ export class OnboardingSlack extends LitElement {}popup.opener = null;if (this.installAvailable === false) {- popup.location.href = `${this.adminBase}/connectors?setup=slack`;+ popup.location.href = `${this.adminBase}/slack-settings?setup=slack`;return;}popup.document.title = "Connecting Slack";diff --git a/plugins/web-ui/test/onboarding-slack.test.ts b/plugins/web-ui/test/onboarding-slack.test.tsindex 290c6eb06..a8682eed6 100644--- a/plugins/web-ui/test/onboarding-slack.test.ts+++ b/plugins/web-ui/test/onboarding-slack.test.ts@@ -106,7 +106,7 @@ test("Slack onboarding launches directly and verifies connection on return", asyconst count = launches.length;element.querySelector<HTMLButtonElement>(".welcome-slack")!.click();await settle();- assert.equal(fallback.location.href, "/admin/connectors?setup=slack");+ assert.equal(fallback.location.href, "/admin/slack-settings?setup=slack");assert.equal(launches.length, count);} finally {releaseStatus();diff --git a/scripts/dev/lib/deps.ts b/scripts/dev/lib/deps.tsindex e61469d3b..d706f1fb7 100644--- a/scripts/dev/lib/deps.ts+++ b/scripts/dev/lib/deps.ts@@ -19,6 +19,11 @@ export async function ensureDeps(): Promise<void> {if (!existsSync(join(worktree, "node_modules/emoji-datasource"))) await npmInstall(worktree, "core", log);if (opts.web === false) return;+ if (+ !existsSync(join(worktree, "plugins/admin/node_modules/lit")) ||+ !existsSync(join(worktree, "plugins/admin/node_modules/esbuild"))+ )+ await npmInstall(join(worktree, "plugins/admin"), "admin plugin", log);if (!existsSync(join(worktree, "plugins/web-ui/node_modules/vite")))await npmInstall(join(worktree, "plugins/web-ui"), "web-ui plugin", log);if (!opts.watch) {diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.tsindex d8369b126..d773449c9 100644--- a/src/api/agent-api-catalog.ts+++ b/src/api/agent-api-catalog.ts@@ -824,7 +824,7 @@ const FAMILIES: AgentApiFamily[] = [method: "GET",path: "/v1/admin/users",summary:- "org roster with admin status plus externalUsers (invited outside collaborators with role, expiry, status); /v1/admin/users/:id for one user's activity, conversations, and personal-scope artifacts (DM or effective Open sharing)",+ "org roster with admin status plus externalUsers (invited outside collaborators with role, expiry, status); /v1/admin/users/:id for one user's personal conversation count, admin status, configuration, and onboarding (DM or effective Open sharing)",},{method: "POST",diff --git a/src/api/routes/admin/scope-config.ts b/src/api/routes/admin/scope-config.tsindex 62c8085e2..29e835f4c 100644--- a/src/api/routes/admin/scope-config.ts+++ b/src/api/routes/admin/scope-config.ts@@ -250,20 +250,10 @@ const SETTINGS_RESOURCES = {"commandPolicy","ambientPolicy","egress",- "externalSlackParticipants",- "internalMemberOverrides","orgAmbient",],- customize: [- "soul",- "branding",- "peopleDirectoryUrl",- "ackEmoji",- "turnWallClockSec",- "featureFlags",- "orgAmbient",- "channelHeaderPinDefault",- ],+ customize: ["soul", "branding", "featureFlags"],+ "slack-settings": ["externalSlackParticipants", "internalMemberOverrides", "channelHeaderPinDefault", "ackEmoji"],models: ["baseModel","runtime",diff --git a/src/api/routes/admin/users.ts b/src/api/routes/admin/users.tsindex 36f08d536..43bdbf2fc 100644--- a/src/api/routes/admin/users.ts+++ b/src/api/routes/admin/users.ts@@ -1,11 +1,9 @@import { scopeId as makeScopeId } from "../../../types.ts";-import { publicUrlOf } from "../../../deploy/deploy-store.ts";import { adminStatusFromGrants, AdminError } from "../../../admin/admin-service.ts";import { personKey, samePerson } from "../../../directory/person.ts";import type { AdminRole } from "../../../admin/admin-grant-store.ts";import type { DirectoryMember } from "../../../directory/directory-store.ts";import { computeUsers } from "../../../admin/users.ts";-import { forEachAttributedTurn } from "../../../admin/attribution.ts";import { INVITE_EMAIL_NOT_CONFIGURED, renderInviteEmail } from "../../../admin/invite-email.ts";import { externalMemberActive, validEmail, type ExternalMember } from "../../../identity/external-members.ts";import { resolveBranding } from "../../../resolution/branding.ts";@@ -15,14 +13,11 @@ import { detectOnboardingStatus, setOnboardingStatus, type OnboardingStatus } frimport { sendJson } from "../../http.ts";import { audit, authorizeAdmin, isObj, orgScope } from "../shared.ts";import { type ApiCtx } from "../route.ts";-import { FILES_PAGE_SIZE } from "./common.ts";-const USER_CONVERSATIONS_MAX = 100;-const USER_FILES_MAX = 200;const EXTERNAL_ORG_ADMIN_PORTAL_ONLY ="granting or removing org admin for an external user is portal-only — the agent cannot manage who governs the org";const ALREADY_A_MEMBER =- "that address already belongs to a member of the org and does not need an external invite. To make them an admin, use Grant org admin in the admin dashboard and enter their email as the principal ID.";+ "that address already belongs to a member of the org and does not need an external invite. To make them an admin, use Make admin on their row in the admin Users page.";const HOLDS_OWN_GRANT ="that address holds an org admin grant of its own — revoke it under Admins first, or re-invite with role org_admin";const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;@@ -238,6 +233,15 @@ export async function listKeychainStatus(ctx: ApiCtx): Promise<void> {if (!deps.keychain)return sendJson(res, 200, { scopeId: scope, people: [], credentials: [], grants: [], asks: [], enabled: false });+ const principalId = ctx.url.searchParams.get("principal")?.trim();+ if (principalId) {+ const [credentials, grants] = await Promise.all([+ deps.keychain.listByOwner(principalId),+ deps.keychain.listGrants({ ownerId: principalId }),+ ]);+ return sendJson(res, 200, { scopeId: scope, credentials, grants, enabled: true });+ }+if (ctx.url.searchParams.get("summary") === "1") {const [credentials, grants] = await Promise.all([deps.keychain.listAllMetadata(), deps.keychain.listGrants({})]);return sendJson(res, 200, {@@ -298,124 +302,25 @@ export async function listKeychainStatus(ctx: ApiCtx): Promise<void> {return sendJson(res, 200, { scopeId: scope, people, credentials, grants: grantsWithUse, asks, enabled: true });}+async function resolveAdminUser(deps: ApiCtx["deps"], requestedPrincipal: string) {+ const member = await deps.directory?.get(requestedPrincipal);+ return { member, principalId: member?.principalId ?? personKey(requestedPrincipal) };+}+export async function getUserDetail(ctx: ApiCtx): Promise<void> {- const { res, app, deps, params } = ctx;+ const { res, deps, params } = ctx;const org = orgScope(deps);const actor = await authorizeAdmin(ctx, org);if (!actor) return;- const principalId = params.principalId!;+ const { member, principalId } = await resolveAdminUser(deps, params.principalId!);const personal = makeScopeId("personal", principalId);audit(deps, { principalId: actor.id, action: "user.read", resource: principalId, scopeLabel: org });- const grants = (await deps.admin?.listGrants()) ?? [];- const member = await app.directoryMember(principalId);-- const participants = (await deps.sessions?.listParticipants()) ?? [];- const attributed = (await deps.sessions?.attributedTurns()) ?? [];- const mySessionIds = new Set<string>();- const turnsBySession = new Map<string, number>();- let firstSeenAt: number | null = null;- let lastSeenAt: number | null = null;- const mark = (t: number) => {- if (firstSeenAt == null || t < firstSeenAt) firstSeenAt = t;- if (lastSeenAt == null || t > lastSeenAt) lastSeenAt = t;- };- forEachAttributedTurn(- { participants, turns: attributed },- {- onWindow(sessionId, w) {- if (!samePerson(w.principalId, principalId)) return;- mySessionIds.add(sessionId);- mark(w.validFrom);- },- onTurn(w, turn) {- if (!samePerson(w.principalId, principalId)) return;- turnsBySession.set(w.sessionId, (turnsBySession.get(w.sessionId) ?? 0) + turn.turns);- mark(turn.firstAt);- mark(turn.lastAt);- },- },- );- const turns = [...turnsBySession.values()].reduce((a, b) => a + b, 0);-- const summaries = mySessionIds.size- ? ((await deps.sessions?.scopeSessionSummaries(org, true, undefined, [...mySessionIds])) ?? [])- : [];- const conversations = summaries- .sort((a, b) => b.lastActivity - a.lastActivity)- .slice(0, USER_CONVERSATIONS_MAX)- .map((s) => ({- id: s.id,- type: s.type,- scopeId: s.scopeId,- turns: s.turns,- messages: s.messages,- userTurns: turnsBySession.get(s.id) ?? 0,- lastActivity: s.lastActivity,- createdAt: s.createdAt,- firstMessage: s.firstMessage,- lastMessage: s.lastMessage,- }));-- const files: Array<{- id: string;- name: string;- path: string;- mimetype: string;- size: number;- direction: string;- createdAt: number;- openable: boolean;- }> = [];- if (deps.files) {- let cursor: string | undefined;- do {- const page = await deps.files.listOwnedByScopes([personal], {- limit: FILES_PAGE_SIZE,- ...(cursor ? { cursor } : {}),- });- for (const a of page.files) {- files.push({- id: a.id,- name: a.name,- path: a.path,- mimetype: a.mimetype,- size: a.sizeBytes,- direction: a.direction,- createdAt: a.createdAt,- openable: a.blobKey != null,- });- }- cursor = page.nextCursor;- } while (cursor && files.length < USER_FILES_MAX);- }- const crons = (await app.listCrons())- .filter((c) => c.ownerScopeId === personal)- .map((c) => ({- id: c.id,- title: c.title,- action: c.action,- message: c.message,- owner: c.owner,- createdBy: c.createdBy,- enabled: c.enabled,- archived: c.archived,- schedule: c.schedule,- createdAt: c.createdAt,- lastFiredAt: c.lastFiredAt,- }));- const deployments = (await app.listDeployments())- .filter((d) => d.ownerScopeId === personal)- .map((d) => ({- id: d.id,- name: d.displayName || d.name,- status: d.status,- currentVersion: d.currentVersion,- versions: d.versions.length,- createdBy: d.createdBy,- lastAccessAt: d.lastAccessAt,- publicUrl: publicUrlOf(d.endpoint),- }));+ const [grants, stats, onboarding] = await Promise.all([+ deps.admin?.listGrants() ?? [],+ deps.sessions?.scopeSessionStats(personal, false, "conversation"),+ deps.memory ? deps.memory.read(personal).then(detectOnboardingStatus) : null,+ ]);const config = deps.config? {hasSoul: !!deps.config.getSoul(personal),@@ -427,18 +332,13 @@ export async function getUserDetail(ctx: ApiCtx): Promise<void> {connectors: await deps.config.listConnectorClients(personal),}: null;- const onboarding = deps.memory ? detectOnboardingStatus(await deps.memory.read(personal)) : null;return sendJson(res, 200, {principalId,scopeId: personal,...(member?.displayName ? { displayName: member.displayName } : {}),admin: adminStatusFromGrants(grants, principalId),- stats: { sessions: mySessionIds.size, turns, firstSeenAt, lastSeenAt },- conversations,- files,- deployments,- crons,+ stats: { sessions: stats?.total ?? 0 },config,onboarding,});@@ -474,7 +374,7 @@ export async function setUserOnboarding(ctx: ApiCtx): Promise<void> {const actor = await authorizeAdmin(ctx, orgScope(deps));if (!actor) return;if (!deps.memory) return sendJson(res, 404, { error: "not_found" });- const principalId = params.principalId!;+ const { principalId } = await resolveAdminUser(deps, params.principalId!);const status = (body as { status?: unknown }).status;if (typeof status !== "string" || !ONBOARDING_STATUSES.has(status as OnboardingStatus)) {return sendJson(res, 400, {@@ -500,7 +400,7 @@ export async function resetUserToBrandNew(ctx: ApiCtx): Promise<void> {const actor = await authorizeAdmin(ctx, orgScope(deps));if (!actor) return;if (!deps.memory) return sendJson(res, 404, { error: "not_found" });- const principalId = params.principalId!;+ const { principalId } = await resolveAdminUser(deps, params.principalId!);const personal = makeScopeId("personal", principalId);const today = new Date().toISOString().slice(0, 10);await deps.memory.replace(diff --git a/src/credentials/keychain.ts b/src/credentials/keychain.tsindex 33aaf2df3..d9b6dcd26 100644--- a/src/credentials/keychain.ts+++ b/src/credentials/keychain.ts@@ -1064,7 +1064,11 @@ export function createKeychain(deps: {},async listGrants(filter) {- return (await deps.grants.all()).filter(+ const grants =+ filter.ownerId === undefined+ ? await deps.grants.all()+ : await deps.grants.select({ where: byOwners([filter.ownerId]) });+ return grants.filter((g) =>(filter.ownerId === undefined || samePerson(g.ownerId, filter.ownerId)) &&(filter.audienceScopeId === undefined || g.audienceScopeId === filter.audienceScopeId),diff --git a/test/admin-external-users.test.ts b/test/admin-external-users.test.tsindex 8fcb829d9..68bf931f5 100644--- a/test/admin-external-users.test.ts+++ b/test/admin-external-users.test.ts@@ -224,7 +224,7 @@ test("an address that already belongs to an org member cannot be invited", async]) {const r = await invite(s.base, { email, expiresAt });assert.equal(r.status, 409, email);- assert.match(((await r.json()) as any).message, /already belongs to a member.*Grant org admin.*email/s);+ assert.match(((await r.json()) as any).message, /already belongs to a member.*Make admin.*Users page/s);assert.equal(s.built.identity.externalMember(email), undefined, email);}assert.equal(adminStatusFromGrants(await s.built.admin.listGrants(), "[email protected]").isAdmin, true);diff --git a/test/admin-keychain.test.ts b/test/admin-keychain.test.tsindex d584dccb3..fe2145940 100644--- a/test/admin-keychain.test.ts+++ b/test/admin-keychain.test.ts@@ -127,3 +127,55 @@ test("credentials-page summary avoids unrelated history and exposes counts only"});assert.equal(denied.status, 403);});++test("user keychain reads only the selected owner's metadata and grants", async (t) => {+ const s = start();+ t.after(s.close);+ const credential = await s.keychain.save({+ ownerId: "[email protected]",+ service: "github",+ secret: "private-user-secret",+ envKey: "GITHUB_TOKEN",+ });+ await s.keychain.save({+ ownerId: "[email protected]",+ service: "github",+ secret: "other-user-secret",+ envKey: "GITHUB_TOKEN",+ });+ const grant = await s.keychain.createGrant({+ credentialId: credential.id,+ ownerId: "[email protected]",+ audienceScopeId: scopeId("channel", "C1"),+ mode: "standing",+ purpose: "test",+ });+ const fail = () => {+ throw new Error("User keychain must not load unrelated org data");+ };+ t.mock.method(s.keychain, "listAllMetadata", fail);+ t.mock.method(s.keychain, "listAsks", fail);+ t.mock.method(s.built.sessions, "distinctParticipants", fail);+ t.mock.method(s.built.app, "directoryMembers", fail);+ if (s.built.auditLog.tallyByResource)+ t.mock.method(s.built.auditLog as Required<typeof s.built.auditLog>, "tallyByResource", fail);+ const response = await fetch(s.base + "/v1/admin/keychain?principal=Alice%40example.com", {+ headers: { "x-admin-actor": "admin-alice@default-org" },+ });+ assert.equal(response.status, 200);+ const data = (await response.json()) as any;+ assert.deepEqual(+ data.credentials.map((c: { id: string }) => c.id),+ [credential.id],+ );+ assert.deepEqual(+ data.grants.map((g: { id: string }) => g.id),+ [grant.id],+ );+ assert.equal(JSON.stringify(data).includes("private-user-secret"), false);+ assert.equal(JSON.stringify(data).includes("[email protected]"), false);+ const denied = await fetch(s.base + "/v1/admin/keychain?principal=alice%40example.com", {+ headers: { "x-admin-actor": "nobody@default-org" },+ });+ assert.equal(denied.status, 403);+});diff --git a/test/admin-settings-load.test.ts b/test/admin-settings-load.test.tsindex 477ffe93e..d2810d322 100644--- a/test/admin-settings-load.test.ts+++ b/test/admin-settings-load.test.ts@@ -31,7 +31,15 @@ test("settings projections preserve values while excluding unrelated payloads",await srv.built.config.flushScope("org:default-org");await srv.built.directory.replaceChannels([{ channelId: "C-settings", name: "settings-test" }]);const full = (await (await fetch(srv.base + scopePath, { headers: ADMIN })).json()) as Record<string, unknown>;- for (const view of ["customize", "governance", "models", "credentials", "connectors", "onboarding"]) {+ for (const view of [+ "customize",+ "governance",+ "models",+ "credentials",+ "connectors",+ "slack-settings",+ "onboarding",+ ]) {const response = await fetch(srv.base + scopePath + "?view=" + view, { headers: ADMIN });assert.equal(response.status, 200, view);const projected = (await response.json()) as Record<string, unknown> & { branding: { selfLabel: string } };@@ -41,9 +49,16 @@ test("settings projections preserve values while excluding unrelated payloads",assert.match(response.headers.get("server-timing") ?? "", /authorize;dur=/);if (["customize", "credentials", "connectors"].includes(view))assert.equal("modelsByHarness" in projected, false, view);+ if (view === "slack-settings") {+ for (const key of ["externalSlackParticipants", "internalMemberOverrides", "channelHeaderPinDefault", "ackEmoji"])+ assert.equal(key in projected, true);+ assert.equal("orgAmbient" in projected, false);+ }if (view === "customize") {assert.equal(projected.branding.selfLabel, "Test assistant");- assert.equal(projected.turnWallClockSec, 120);+ assert.equal("turnWallClockSec" in projected, false);+ assert.equal("orgAmbient" in projected, false);+ assert.equal("channelHeaderPinDefault" in projected, false);assert.equal("soulHistory" in projected, true);assert.equal("connectors" in projected, false);}@@ -106,7 +121,15 @@ test("each settings projection retains authorization before reading configuratiot.mock.method(srv.built.config, "refreshScope", async () => {reads++;});- for (const view of ["customize", "governance", "models", "credentials", "connectors", "onboarding"]) {+ for (const view of [+ "customize",+ "governance",+ "models",+ "credentials",+ "connectors",+ "slack-settings",+ "onboarding",+ ]) {const response = await fetch(srv.base + scopePath + "?view=" + view, {headers: { "x-admin-actor": "nobody@default-org" },});diff --git a/test/admin-users.test.ts b/test/admin-users.test.tsindex e009003e1..9bcdb284d 100644--- a/test/admin-users.test.ts+++ b/test/admin-users.test.ts@@ -66,6 +66,8 @@ function start() {const server = createInsecureTestServer(built.app, {admin: built.admin,sessions: built.sessions,+ files: built.files,+ directory: built.directory,memory: built.memory,auditLog: built.auditLog,});@@ -106,7 +108,7 @@ test("/v1/admin/users: org_admin sees the roster + grants; a non-admin is denied}});-test("/v1/admin/users/:principalId: per-user detail — stats, conversations, personal-scope artifacts; non-admin denied; audited", async () => {+test("/v1/admin/users/:principalId: per-user detail counts personal conversations without loading org history or artifacts; non-admin denied; audited", async (t) => {const s = start();try {const dm: TurnRequest = {@@ -117,20 +119,25 @@ test("/v1/admin/users/:principalId: per-user detail — stats, conversations, pe};assert.equal((await s.built.app.turn(dm)).status, "ok");+ await s.built.app.turn({ ...dm, actor: { externalId: "U2" }, conversation: { kind: "dm", threadRef: "dm:U2:t1" } });+ await s.built.app.turn({ ...dm, conversation: { kind: "channel", channelRef: "C1", threadRef: "channel:C1:t1" } });+ const fail = () => {+ throw new Error("User detail must not load org history or artifact lists");+ };+ t.mock.method(s.built.sessions, "listParticipants", fail);+ t.mock.method(s.built.sessions, "attributedTurns", fail);+ t.mock.method(s.built.sessions, "scopeSessionSummaries", fail);+ t.mock.method(s.built.files, "listOwnedByScopes", fail);+ t.mock.method(s.built.app, "listCrons", fail);+ t.mock.method(s.built.app, "listDeployments", fail);+const r = await fetch(`${s.base}/v1/admin/users/U1`, { headers: { "x-admin-actor": "admin-alice@default-org" } });assert.equal(r.status, 200);const d: any = await r.json();assert.equal(d.principalId, "U1");assert.equal(d.scopeId, "personal:U1");assert.equal(d.stats.sessions, 1);- assert.equal(d.stats.turns, 1);- assert.equal(typeof d.stats.lastSeenAt, "number");- assert.equal(d.conversations.length, 1, "the DM appears as a conversation");- assert.equal(d.conversations[0].scopeId, "personal:U1");- assert.equal(d.conversations[0].userTurns, 1);- assert.deepEqual(d.files, []);- assert.deepEqual(d.crons, []);- assert.deepEqual(d.deployments, []);+ for (const key of ["conversations", "files", "crons", "deployments"]) assert.equal(key in d, false);const denied = await fetch(`${s.base}/v1/admin/users/U1`, { headers: { "x-admin-actor": "user-uma@default-org" } });assert.equal(denied.status, 403);@@ -213,7 +220,7 @@ test("/v1/admin/users/:principalId/reset: deletes the user's personal sessions +d = await detail();assert.equal(d.stats.sessions, 0, "session wiped → user looks brand-new");- assert.deepEqual(d.conversations, []);+ assert.equal("conversations" in d, false);assert.equal(d.onboarding, "not_started", "onboarding marker cleared");assert.ok((await s.built.auditLog.events()).some((e) => e.action === "user.reset"));@@ -233,7 +240,7 @@ test("/v1/admin/users/:principalId: a grant-holder with no sessions still resolvassert.equal(d.principalId, "admin-alice");assert.equal(d.admin.isAdmin, true);assert.equal(d.stats.sessions, 0);- assert.deepEqual(d.conversations, []);+ assert.equal("conversations" in d, false);} finally {await s.close();}@@ -318,3 +325,60 @@ test("/v1/admin/users: a freshly promoted user shows as admin in the roster", asawait s.close();}});++test("user detail resolves mixed-case email links to the canonical personal scope", async (t) => {+ const s = start();+ try {+ const stats = await s.built.sessions.scopeSessionStats("personal:[email protected]", false, "conversation");+ t.mock.method(s.built.sessions, "scopeSessionStats", async (scope: string) => {+ assert.equal(scope, "personal:[email protected]");+ return { ...stats, total: 3 };+ });+ const response = await fetch(`${s.base}/v1/admin/users/Alice%40example.com`, {+ headers: { "x-admin-actor": "admin-alice@default-org" },+ });+ assert.equal(response.status, 200);+ const data = (await response.json()) as any;+ assert.equal(data.principalId, "[email protected]");+ assert.equal(data.scopeId, "personal:[email protected]");+ assert.equal(data.stats.sessions, 3);+ } finally {+ await s.close();+ }+});++for (const canonicalPrincipal of ["[email protected]", "[email protected]"]) {+ test(`mixed-case user mutations target canonical scope ${canonicalPrincipal}`, async () => {+ const s = start();+ try {+ if (canonicalPrincipal === "[email protected]")+ await s.built.directory.replace([{ principalId: canonicalPrincipal, displayName: "Alice", type: "internal" }]);+ const scope = "personal:" + canonicalPrincipal;+ const session = await s.built.sessions.getOrCreateByThread("dm:case-test", "dm", scope);+ await s.built.sessions.addParticipant(session.id, canonicalPrincipal);+ const other = await s.built.sessions.getOrCreateByThread("channel:case-test", "channel", "channel:C1");+ await s.built.sessions.addParticipant(other.id, canonicalPrincipal);+ const base = `${s.base}/v1/admin/users/ALICE%40example.com`;+ const headers = { "x-admin-actor": "admin-alice@default-org", "content-type": "application/json" };+ const detail = async () => (await (await fetch(base, { headers })).json()) as any;+ const update = await fetch(base + "/onboarding", {+ method: "PUT",+ headers,+ body: JSON.stringify({ status: "completed" }),+ });+ assert.equal(update.status, 200);+ assert.equal(((await update.json()) as any).scopeId, scope);+ assert.equal((await detail()).onboarding, "completed");+ const reset = await fetch(base + "/reset", { method: "POST", headers });+ assert.equal(reset.status, 200);+ assert.equal(((await reset.json()) as any).deletedSessions, 1);+ assert.equal((await detail()).onboarding, "not_started");+ assert.equal((await detail()).stats.sessions, 0);+ assert.equal(await s.built.sessions.get(session.id), null);+ assert.ok(await s.built.sessions.get(other.id));+ assert.equal(await s.built.memory.read("personal:[email protected]"), "");+ } finally {+ await s.close();+ }+ });+}