Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Search skills, crons, apps, and projects from Cmd+K (#1281)

Regan Bell80b87a19fd90
diff --git a/docs/qa/resource-search-demo.md b/docs/qa/resource-search-demo.md
new file mode 100644
index 000000000..46b4e56e1
--- /dev/null
+++ b/docs/qa/resource-search-demo.md
@@ -0,0 +1,22 @@
+# Cmd+K resource search demo
+
+Build two self-contained HTML demos without starting the application:
+
+```sh
+npm ci
+npm --prefix plugins/web-ui ci
+node docs/qa/resource-search-demo.mjs
+open /tmp/qm-resource-search-demo/resource-search-after.html
+```
+
+The files include all scripts and styles and work directly from disk. The Before and After links switch between the original chat-only palette and the current palette. Search for `release`, `dashboard`, or `digest`; use arrow keys and Enter, or click a result. Escape closes the palette; the Open search button reopens it.
+
+The demo bundles the real search component, shared result formatting, icons, and palette CSS. Synthetic responses provide a release-review skill, weekly release digest cron, release dashboard app, release planning project, and a release-readiness conversation. API calls, session access, relative recency, and navigation are mocked; selecting a resource displays its destination instead of opening the application. Asking QM displays a local status message. No backend or network access is involved.
+
+The default before source is commit `e0966ba8`. Optional arguments choose the output directory and before revision:
+
+```sh
+node docs/qa/resource-search-demo.mjs /tmp/search-review e0966ba8
+```
+
+For the PR, link this document and attach the generated HTML pair if the review host allows HTML attachments. The generated bundles stay outside Git. DOM checks verified four resource results plus a conversation, before/after differences, and resource navigation. Browser verification confirmed the rendered demo and Enter navigation to `/skills/demo-skill`.
diff --git a/docs/qa/resource-search-demo.mjs b/docs/qa/resource-search-demo.mjs
new file mode 100644
index 000000000..a5120bab9
--- /dev/null
+++ b/docs/qa/resource-search-demo.mjs
@@ -0,0 +1,102 @@
+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { resolve } from "node:path";
+import { execFileSync } from "node:child_process";
+import { createRequire } from "node:module";
+const root = fileURLToPath(new URL("../../", import.meta.url));
+const plugin = resolve(root, "plugins/web-ui");
+const require = createRequire(import.meta.url);
+const { build, transform } = require("esbuild");
+const output = resolve(process.argv[2] ?? "/tmp/qm-resource-search-demo");
+mkdirSync(output, { recursive: true });
+const sourceDir = `${root}/plugins/web-ui/src`;
+const resources = [
+ {
+ id: "demo-skill",
+ kind: "skills",
+ title: "release-review",
+ snippet: "Review release notes, check rollout readiness, and prepare the launch checklist.",
+ },
+ {
+ id: "demo-cron",
+ kind: "crons",
+ title: "Weekly release digest",
+ snippet: "Summarize release progress every Monday at 9:00 AM for the launch team.",
+ },
+ { id: "demo-app", kind: "deploys", title: "Release dashboard", snippet: "release-dashboard" },
+ { id: "group:demo-release", kind: "contexts", title: "Release planning", snippet: "Project" },
+];
+const chat = {
+ sessionId: "demo-chat",
+ title: "Release readiness review",
+ scopeId: "personal:demo",
+ seq: 1,
+ entryType: "assistant",
+ snippet: "The release checklist is ready. The remaining action is the staged rollout review.",
+ createdAt: 1789473600000,
+};
+const stubs = {
+ "./core-bridge": `export const userSendMessage=x=>x; export async function api(path) { const q=new URL(path,'http://demo').searchParams.get('q').toLowerCase(); const rows=path.includes('/resources/')?DEMO_RESOURCES:[DEMO_CHAT]; return {hits:rows.filter(r=>(r.title+' '+r.snippet).toLowerCase().includes(q)),failed:[],limited:[]}; }`,
+ "./sessions": `export const sessionsState={list:[{id:'demo-chat',title:'Release readiness review'}]}; export const sessionTitle=s=>s.title; export async function refreshSessions(){} export async function openSession(){document.querySelector('#demo-status').textContent='Demo: opened Release readiness review';} export function startNewChat(){return {state:{agent:{prompt(){document.querySelector('#demo-status').textContent='Demo: QM would receive your search request';}}}}}`,
+ "./session-list": `export const recencyGroup=()=> 'This week';`,
+ "./browse": `export const destinations=()=>[{label:'Skills',blurb:'Browse reusable skills',href:'#skills'},{label:'Crons',blurb:'Browse scheduled work',href:'#crons'},{label:'Apps',blurb:'Browse deployed apps',href:'#apps'},{label:'Projects',blurb:'Browse shared projects',href:'#projects'}];`,
+ "./ui": `import {createElement} from 'lucide'; export const icon=(node,size=18)=>createElement(node,{class:'icon',width:size,height:size,'aria-hidden':'true',focusable:'false','stroke-width':1.9});`,
+};
+const css = readFileSync(`${sourceDir}/shell.css`, "utf8");
+const paletteCss = css.slice(css.indexOf(".chat-search-overlay {"), css.indexOf(".nav-badge {"));
+const variables = css.slice(css.indexOf(":root {"), css.indexOf(".layout {"));
+const reset = `:root{--background:white;--foreground:#171717;--border:#e5e5e5;--muted-foreground:#737373;--primary:#171717;--primary-foreground:white}*{box-sizing:border-box}button,input{font:inherit}h1{font-size:22px}main{padding:30px;max-width:900px;margin:auto}a{color:#4338ca}#demo-status{position:fixed;bottom:20px;left:24px}nav{display:flex;gap:16px;margin:15px 0}.chat-search-cancel{display:none}`;
+const style = (await transform(reset + variables + paletteCss, { loader: "css", minify: true, legalComments: "none" }))
+ .code;
+for (const mode of ["after", "before"]) {
+ const source =
+ mode === "after"
+ ? readFileSync(`${sourceDir}/search.ts`, "utf8")
+ : execFileSync("git", ["show", `${process.argv[3] ?? "e0966ba8"}:plugins/web-ui/src/search.ts`], {
+ cwd: root,
+ encoding: "utf8",
+ });
+ const result = await build({
+ stdin: {
+ contents:
+ source.replace(
+ "location.assign(hit.href);",
+ "document.querySelector('#demo-status').textContent = 'Demo navigation: ' + hit.href;",
+ ) +
+ `\nregisterChatSearchHotkey();document.querySelector('#open').onclick=openChatSearch;openChatSearch();const input=document.querySelector('.chat-search-input');input.value='release';input.dispatchEvent(new Event('input',{bubbles:true}));`,
+ resolveDir: sourceDir,
+ loader: "ts",
+ },
+ bundle: true,
+ write: false,
+ format: "iife",
+ define: { "import.meta": "{}", DEMO_RESOURCES: JSON.stringify(resources), DEMO_CHAT: JSON.stringify(chat) },
+ minify: true,
+ legalComments: "none",
+ nodePaths: [resolve(plugin, "node_modules")],
+ plugins: [
+ {
+ name: "demo-services",
+ setup(b) {
+ b.onResolve({ filter: /^\.\/(core-bridge|sessions|session-list|browse|ui)$/ }, (a) => ({
+ path: a.path,
+ namespace: "demo",
+ }));
+ b.onLoad({ filter: /.*/, namespace: "demo" }, (a) => ({
+ contents: stubs[a.path],
+ resolveDir: sourceDir,
+ loader: "js",
+ }));
+ },
+ },
+ ],
+ });
+ const js = result.outputFiles[0].text.replace(/<\/script/gi, "<\\/script");
+ const title = mode === "after" ? "After: resource and chat search" : "Before: chat search";
+ writeFileSync(
+ `${output}/resource-search-${mode}.html`,
+ `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title}</title><style>${style}</style><main><h1>${title}</h1><p>Interactive demo using the actual search component and synthetic data. No network requests, backend, or production identifiers.</p><nav><a href="resource-search-before.html">Before</a><a href="resource-search-after.html">After</a><button id="open">Open search</button></nav><p>Search for “release”, “dashboard”, or “digest”. Use arrow keys to select results. Escape closes the palette.</p></main><div id="demo-status" role="status"></div><script>${js}</script></html>`,
+ );
+}
+
+console.log(`Open ${output}/resource-search-after.html in a browser.`);
diff --git a/knip.json b/knip.json
index 0cb2469aa..b0d00d855 100644
--- a/knip.json
+++ b/knip.json
@@ -31,7 +31,8 @@
"scripts/migrate-principals-to-email.mjs",
"scripts/mine-slack-scenarios.ts",
"scripts/skills-materialize-smoke.ts",
- "scripts/slack-user-token.ts"
+ "scripts/slack-user-token.ts",
+ "docs/qa/resource-search-demo.mjs"
]
},
"cli": {
diff --git a/package-lock.json b/package-lock.json
index 63f37cfc7..b9f7fbdea 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -60,7 +60,8 @@
"oxlint": "^1.74.0",
"prettier": "3.9.1",
"typescript": "^5.8.2",
- "typescript-eslint": "^8.61.0"
+ "typescript-eslint": "^8.61.0",
+ "esbuild": "0.28.1"
},
"engines": {
"node": ">=24.15.0",
@@ -2931,6 +2932,448 @@
"tslib": "^2.4.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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "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"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/@eslint-community/eslint-utils": {
"version": "4.10.1",
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz",
@@ -6593,6 +7036,48 @@
"node": ">= 0.4"
}
},
+ "node_modules/esbuild": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
+ "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",
+ "dev": true,
+ "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/escalade": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
diff --git a/package.json b/package.json
index ad0f46c15..4dbecdbb3 100644
--- a/package.json
+++ b/package.json
@@ -44,7 +44,7 @@
"sandbox:local:build": "bash scripts/local-sandbox-build.sh",
"sandbox:porter:build": "docker build --platform linux/amd64 -t \"${PORTER_SANDBOX_IMAGE:?Set PORTER_SANDBOX_IMAGE to the registry tag to publish}\" porter && docker push \"$PORTER_SANDBOX_IMAGE\"",
"deploy:porter-runner-image": "docker build --platform linux/amd64 -t \"${PORTER_DEPLOY_RUNNER_IMAGE:?Set PORTER_DEPLOY_RUNNER_IMAGE to the registry tag to publish}\" -f deploy/porter-runner/Dockerfile . && docker push \"$PORTER_DEPLOY_RUNNER_IMAGE\"",
- "test:pg": "node --test --test-concurrency=1 test/postgres-swarms.test.ts test/postgres-store.test.ts test/postgres-grant-store.test.ts test/postgres-admin-grants.test.ts test/postgres-file-artifact-store.test.ts test/postgres-file-upload-store.test.ts test/postgres-directory-store.test.ts test/postgres-map.test.ts test/deploy-store-pg.test.ts test/postgres-cron-fires.test.ts test/postgres-migration-adoption.test.ts test/postgres-migrations.test.ts test/postgres-migration-startup.test.ts test/cron-queue.test.ts test/postgres-metrics-sink.test.ts test/postgres-error-log.test.ts test/postgres-audit-log.test.ts test/postgres-budget.test.ts test/postgres-rate-limiter.test.ts test/postgres-credential-usage-sink.test.ts test/postgres-config-store.test.ts test/postgres-delivery-store.test.ts test/postgres-replay-dedupe.test.ts test/postgres-broker-sessions.test.ts test/postgres-egress-audit-sink.test.ts test/postgres-memory-service.test.ts test/run-signal-store.test.ts test/postgres-listener.test.ts test/postgres-run-activity-store.test.ts test/leader-lease.test.ts test/advisory-lock.test.ts test/persistence-init-retry.test.ts test/migrate-principals.test.ts test/postgres-surface-cache.test.ts test/slack-mirror-fidelity.test.ts test/postgres-instance-registry.test.ts test/run-retry-delay.test.ts test/postgres-run-stream.test.ts test/migrate-main.test.ts",
+ "test:pg": "node --test --test-concurrency=1 test/postgres-swarms.test.ts test/postgres-store.test.ts test/postgres-grant-store.test.ts test/postgres-admin-grants.test.ts test/postgres-file-artifact-store.test.ts test/postgres-file-upload-store.test.ts test/postgres-directory-store.test.ts test/postgres-map.test.ts test/postgres-resource-search.test.ts test/deploy-store-pg.test.ts test/postgres-cron-fires.test.ts test/postgres-migration-adoption.test.ts test/postgres-migrations.test.ts test/postgres-migration-startup.test.ts test/cron-queue.test.ts test/postgres-metrics-sink.test.ts test/postgres-error-log.test.ts test/postgres-audit-log.test.ts test/postgres-budget.test.ts test/postgres-rate-limiter.test.ts test/postgres-credential-usage-sink.test.ts test/postgres-config-store.test.ts test/postgres-delivery-store.test.ts test/postgres-replay-dedupe.test.ts test/postgres-broker-sessions.test.ts test/postgres-egress-audit-sink.test.ts test/postgres-memory-service.test.ts test/run-signal-store.test.ts test/postgres-listener.test.ts test/postgres-run-activity-store.test.ts test/leader-lease.test.ts test/advisory-lock.test.ts test/persistence-init-retry.test.ts test/migrate-principals.test.ts test/postgres-surface-cache.test.ts test/slack-mirror-fidelity.test.ts test/postgres-instance-registry.test.ts test/run-retry-delay.test.ts test/postgres-run-stream.test.ts test/migrate-main.test.ts",
"livetest": "node scripts/api-livetest.ts",
"bench:memory": "node --env-file-if-exists=.env scripts/memory-bench.ts",
"prepare": "node .husky/install.mjs",
@@ -121,6 +121,7 @@
"@types/pg": "^8.11.10",
"@types/tar-stream": "^3.1.4",
"@yc-software/qm": "file:./cli",
+ "esbuild": "0.28.1",
"eslint": "^10.4.1",
"globals": "^17.6.0",
"husky": "9.1.7",
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.ts
index f9b438c49..8e47a8ee1 100644
--- a/plugins/web-ui/server/index.ts
+++ b/plugins/web-ui/server/index.ts
@@ -1226,6 +1226,16 @@ const apiRoutes: readonly WebRoute[] = [
);
},
},
+ {
+ method: "GET",
+ path: "/api/resources/search",
+ handle: (c) =>
+ relayCore(
+ c.res,
+ "GET",
+ `/v1/resources/search?principalId=${encodeURIComponent(c.user)}&q=${encodeURIComponent((c.url.searchParams.get("q") ?? "").slice(0, 500))}`,
+ ),
+ },
{
method: "GET",
path: "/api/search",
diff --git a/plugins/web-ui/src/browse.ts b/plugins/web-ui/src/browse.ts
index 4b4dcc80f..173f1b23b 100644
--- a/plugins/web-ui/src/browse.ts
+++ b/plugins/web-ui/src/browse.ts
@@ -21,7 +21,7 @@ const browseState = { open: false, sel: 0 };
let host: HTMLDivElement | null = null;
-function destinations(): Destination[] {
+export function destinations(): Destination[] {
const to = (view: View, glyph: IconNode, label: string, blurb: string): Destination => ({
view,
href: deepLinkPath(UI_BASE, view, null),
diff --git a/plugins/web-ui/src/deploys.ts b/plugins/web-ui/src/deploys.ts
index 7ce0b2ea5..f5933a200 100644
--- a/plugins/web-ui/src/deploys.ts
+++ b/plugins/web-ui/src/deploys.ts
@@ -35,6 +35,7 @@ import {
type DeploymentView,
} from "./deploy-view";
import { tip } from "./tooltip";
+import { deepLinkPath, UI_BASE } from "./deep-link";
const DEPLOY_TABS: Array<{ value: DeploymentTab; label: string }> = [
{ value: "yours", label: "Yours" },
@@ -226,11 +227,18 @@ function drawDeploysPage(): void {
);
}
+let pendingDeployId: string | null = null;
+
+export function openDeployById(id: string): void {
+ pendingDeployId = id;
+}
+
async function openDeploy(d: DeploymentView): Promise<void> {
editingDeploy = null;
deployDraft = "";
deployNotices = withoutDeploymentDetailNotice(deployNotices);
activeDeploy = d;
+ history.replaceState(null, "", deepLinkPath(UI_BASE, "deploys", null, null, d.id));
drawDeployDetail(d, true);
try {
const response = await api<{ deployment?: DeploymentView }>(`/api/deployments/${encodeURIComponent(d.id)}`);
@@ -405,6 +413,7 @@ function returnToDeploysList(): void {
deployDraft = "";
deployNotices = withoutDeploymentDetailNotice(deployNotices);
activeDeploy = null;
+ history.replaceState(null, "", deepLinkPath(UI_BASE, "deploys", null));
drawDeploysPage();
}
@@ -735,6 +744,8 @@ async function refreshDeployments(): Promise<"updated" | "failed" | "superseded"
export async function renderDeploys(): Promise<void> {
if (appState.currentView !== "deploys") return;
+ const requestedId = pendingDeployId;
+ pendingDeployId = null;
archiveCandidate = null;
restoreArchiveFocus = false;
setDeployBackgroundInert(false);
@@ -754,5 +765,7 @@ export async function renderDeploys(): Promise<void> {
drawDeploysPage();
await refreshDeployments();
if (seq !== appState.viewRenderSeq || appState.currentView !== "deploys") return;
- if (deploymentListRefreshCanRedraw(activeDeploy?.id)) drawDeploysPage();
+ if (requestedId) {
+ await openDeploy(deployList.find((d) => d.id === requestedId) ?? { id: requestedId });
+ } else if (deploymentListRefreshCanRedraw(activeDeploy?.id)) drawDeploysPage();
}
diff --git a/plugins/web-ui/src/search-resources.ts b/plugins/web-ui/src/search-resources.ts
new file mode 100644
index 000000000..748cc82c6
--- /dev/null
+++ b/plugins/web-ui/src/search-resources.ts
@@ -0,0 +1,55 @@
+import { deepLinkPath } from "./deep-link.ts";
+
+export interface ResourceHit {
+ title: string;
+ description: string;
+ group: string;
+ href: string;
+}
+export interface ResourceSearchResponse {
+ hits: Array<{
+ id: string;
+ kind: "skills" | "crons" | "deploys" | "webhooks" | "contexts";
+ title: string;
+ snippet: string;
+ }>;
+ failed: string[];
+ limited?: string[];
+}
+const labels: Record<string, string> = {
+ skills: "Skills",
+ crons: "Crons",
+ deploys: "Apps",
+ webhooks: "Webhooks",
+ contexts: "Projects",
+};
+
+export function resourceResults(
+ result: ResourceSearchResponse,
+ base: string,
+): { hits: ResourceHit[]; failed: string[] } {
+ return {
+ hits: result.hits.map((hit) => ({
+ title: hit.title,
+ description: hit.snippet,
+ group: labels[hit.kind]!,
+ href: deepLinkPath(
+ base,
+ hit.kind,
+ null,
+ hit.kind === "contexts" ? hit.id : null,
+ hit.kind === "contexts" ? null : hit.id,
+ ),
+ })),
+ failed: result.failed.map((kind) => labels[kind] ?? kind),
+ };
+}
+
+export function matchResources(hits: ResourceHit[], query: string): ResourceHit[] {
+ const terms = query.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean);
+ if (!terms.length) return [];
+ return hits.filter((h) => {
+ const text = `${h.title} ${h.description} ${h.group}`.toLocaleLowerCase();
+ return terms.every((term) => text.includes(term));
+ });
+}
diff --git a/plugins/web-ui/src/search.ts b/plugins/web-ui/src/search.ts
index 73a2bf843..2307c830d 100644
--- a/plugins/web-ui/src/search.ts
+++ b/plugins/web-ui/src/search.ts
@@ -6,6 +6,9 @@ import { recencyGroup } from "./session-list";
import { searchGroup } from "./search-group";
import { slackWireToPlain, stripSlackDirectives } from "./slack-text";
import { openSession, refreshSessions, sessionsState, sessionTitle } from "./sessions";
+import { destinations } from "./browse";
+import { UI_BASE } from "./deep-link";
+import { resourceResults, matchResources, type ResourceHit, type ResourceSearchResponse } from "./search-resources";
import { icon } from "./ui";
interface ChatSearchHit {
@@ -30,9 +33,14 @@ const searchState = {
open: false,
query: "",
hits: [] as ChatSearchHit[],
+ resources: [] as ResourceHit[],
+ resourceFailures: [] as string[],
+ resourcesLoading: false,
+ resourcesLimited: false,
failed: false,
loading: false,
sel: 0,
+ selectionMoved: false,
};
let host: HTMLDivElement | null = null;
@@ -58,6 +66,11 @@ export function openChatSearch(): void {
searchState.loading = false;
searchState.failed = false;
searchState.sel = 0;
+ searchState.selectionMoved = false;
+ searchState.resources = [];
+ searchState.resourceFailures = [];
+ searchState.resourcesLimited = false;
+ searchState.resourcesLoading = false;
draw();
requestAnimationFrame(() => host?.querySelector<HTMLInputElement>(".chat-search-input")?.focus());
}
@@ -86,8 +99,18 @@ function draw(): void {
render(searchState.open ? paletteTpl() : nothing, ensureHost());
}
+function resourceHits(): ResourceHit[] {
+ const shortcuts = destinations().map((d) => ({ title: d.label, description: d.blurb, group: "Go to", href: d.href }));
+ return [...matchResources(shortcuts, searchState.query), ...searchState.resources];
+}
+
+function openResource(hit: ResourceHit): void {
+ closeChatSearch();
+ location.assign(hit.href);
+}
+
function rowCount(): number {
- return searchState.hits.length + (askRowShown() ? 1 : 0);
+ return resourceHits().length + searchState.hits.length + (askRowShown() ? 1 : 0);
}
function askRowShown(): boolean {
@@ -101,12 +124,17 @@ function clampSel(): void {
function onQueryInput(e: InputEvent): void {
searchState.query = (e.currentTarget as HTMLInputElement).value;
searchState.sel = 0;
+ searchState.selectionMoved = false;
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = null;
fetchSeq++;
inflight?.abort();
inflight = null;
searchState.hits = [];
+ searchState.resources = [];
+ searchState.resourceFailures = [];
+ searchState.resourcesLimited = false;
+ searchState.resourcesLoading = false;
searchState.failed = false;
const q = searchState.query.trim();
if (q.length < MIN_QUERY_LEN) {
@@ -115,6 +143,7 @@ function onQueryInput(e: InputEvent): void {
return;
}
searchState.loading = true;
+ searchState.resourcesLoading = true;
draw();
debounceTimer = setTimeout(() => void runSearch(q), DEBOUNCE_MS);
}
@@ -124,10 +153,15 @@ async function runSearch(q: string): Promise<void> {
const ctl = new AbortController();
inflight = ctl;
const seq = ++fetchSeq;
+ void runResourceSearch(q, ctl, seq);
try {
const r = await api<{ hits: ChatSearchHit[] }>(`/api/search?q=${encodeURIComponent(q)}`, { signal: ctl.signal });
if (seq !== fetchSeq || !searchState.open) return;
- searchState.hits = groupHitsBySession(r.hits ?? []);
+ const hits = groupHitsBySession(r.hits ?? []);
+ if (searchState.selectionMoved && searchState.sel === resourceHits().length + searchState.hits.length) {
+ searchState.sel += hits.length - searchState.hits.length;
+ }
+ searchState.hits = hits;
searchState.failed = false;
} catch {
if (seq !== fetchSeq || ctl.signal.aborted) return;
@@ -139,6 +173,32 @@ async function runSearch(q: string): Promise<void> {
draw();
}
+async function runResourceSearch(q: string, ctl: AbortController, seq: number): Promise<void> {
+ try {
+ const response = await api<ResourceSearchResponse>(`/api/resources/search?q=${encodeURIComponent(q)}`, {
+ signal: ctl.signal,
+ });
+ if (seq !== fetchSeq || !searchState.open) return;
+ const result = resourceResults(response, UI_BASE);
+ const resourceCount = resourceHits().length;
+ if (
+ searchState.sel >= resourceCount &&
+ (searchState.selectionMoved || searchState.sel < resourceCount + searchState.hits.length)
+ ) {
+ searchState.sel += result.hits.length - searchState.resources.length;
+ }
+ searchState.resources = result.hits;
+ searchState.resourcesLimited = Boolean(response.limited?.length);
+ searchState.resourceFailures = result.failed;
+ } catch {
+ if (seq !== fetchSeq || ctl.signal.aborted) return;
+ searchState.resourceFailures = ["resources"];
+ }
+ searchState.resourcesLoading = false;
+ clampSel();
+ draw();
+}
+
function groupHitsBySession(hits: ChatSearchHit[]): ChatSearchHit[] {
const order: string[] = [];
const bySession = new Map<string, ChatSearchHit[]>();
@@ -165,6 +225,7 @@ function onPaletteKeydown(e: KeyboardEvent): void {
e.preventDefault();
const count = rowCount();
if (!count) return;
+ searchState.selectionMoved = true;
searchState.sel = (searchState.sel + (e.key === "ArrowDown" ? 1 : count - 1)) % count;
draw();
scrollSelectedIntoView();
@@ -173,10 +234,18 @@ function onPaletteKeydown(e: KeyboardEvent): void {
if (e.key === "Enter") {
e.preventDefault();
if (e.metaKey || e.ctrlKey) return void askQm();
+ const resources = resourceHits();
+ const resource = resources[searchState.sel];
+ if (resource) return openResource(resource);
if (searchState.loading) return;
- const hit = searchState.hits[searchState.sel];
+ const hit = searchState.hits[searchState.sel - resources.length];
if (hit) return void openHit(hit);
- if (askRowShown() && searchState.sel === searchState.hits.length) return void askQm();
+ if (
+ !searchState.resourcesLoading &&
+ askRowShown() &&
+ searchState.sel === resources.length + searchState.hits.length
+ )
+ return void askQm();
}
}
@@ -203,7 +272,7 @@ function askQm(): void {
const conv = startNewChat();
void conv?.state.agent?.prompt(
userSendMessage(
- `Find my previous session based on the following search query, give me a link when you've identified it: ${q}`,
+ `Find the chat, skill, cron, app, or other resource matching this search query and give me a link: ${q}`,
),
);
}
@@ -232,7 +301,8 @@ function hitTitle(hit: ChatSearchHit): string {
function resultRows(): TemplateResult[] {
const rows: TemplateResult[] = [];
let lastSession: string | null = null;
- searchState.hits.forEach((hit, i) => {
+ searchState.hits.forEach((hit, index) => {
+ const i = resourceHits().length + index;
if (hit.sessionId !== lastSession) {
lastSession = hit.sessionId;
rows.push(searchGroup(hitTitle(hit), Boolean(hit.archived), recencyGroup(hit.createdAt)));
@@ -244,6 +314,7 @@ function resultRows(): TemplateResult[] {
@click=${() => void openHit(hit)}
@pointermove=${() => {
if (searchState.sel !== i) {
+ searchState.selectionMoved = true;
searchState.sel = i;
draw();
}
@@ -265,8 +336,37 @@ function resultRows(): TemplateResult[] {
return rows;
}
+function resourceRows(): TemplateResult[] {
+ let group = "";
+ return resourceHits().flatMap((hit, i) => {
+ const heading = group !== hit.group ? [searchGroup(hit.group, false, "")] : [];
+ group = hit.group;
+ return [
+ ...heading,
+ html`<button
+ type="button"
+ class="chat-search-row ${i === searchState.sel ? "selected" : ""}"
+ @click=${() => openResource(hit)}
+ @pointermove=${() => {
+ if (searchState.sel !== i) {
+ searchState.selectionMoved = true;
+ searchState.sel = i;
+ draw();
+ }
+ }}
+ >
+ <span class="chat-search-who">${icon(Search, 14)}</span>
+ <span class="chat-search-text"
+ ><span class="chat-search-snippet">${highlight(hit.title)}</span>
+ <span class="chat-search-meta chat-search-snippet">${highlight(hit.description)}</span></span
+ >
+ </button>`,
+ ];
+ });
+}
+
function askRow(): TemplateResult {
- const i = searchState.hits.length;
+ const i = resourceHits().length + searchState.hits.length;
return html`
<button
type="button"
@@ -274,6 +374,7 @@ function askRow(): TemplateResult {
@click=${() => askQm()}
@pointermove=${() => {
if (searchState.sel !== i) {
+ searchState.selectionMoved = true;
searchState.sel = i;
draw();
}
@@ -282,7 +383,7 @@ function askRow(): TemplateResult {
<span class="chat-search-who ask">+</span>
<span class="chat-search-text">
<span class="chat-search-snippet">Ask QM to find it: <b dir="auto">“${searchState.query.trim()}”</b></span>
- <span class="chat-search-meta">starts a new chat where QM hunts down the matching session and links it</span>
+ <span class="chat-search-meta">starts a new chat where QM finds the matching resource and links it</span>
</span>
<span class="chat-search-kbd">${isMac ? "⌘" : "Ctrl"}${icon(CornerDownLeft, 11)}</span>
</button>
@@ -298,8 +399,10 @@ function paletteTpl(): TemplateResult {
body = html`<div class="chat-search-empty">Searching…</div>`;
} else if (searchState.failed) {
body = html`<div class="chat-search-empty chat-search-failed">Search failed. Try again.</div>`;
+ } else if (resourceHits().length || searchState.resourcesLoading) {
+ body = html`${resultRows()}`;
} else if (!searchState.hits.length) {
- body = html`<div class="chat-search-empty">No messages match “${q}”.</div>`;
+ body = html`<div class="chat-search-empty">No results match “${q}”.</div>`;
} else {
body = html`${resultRows()}`;
}
@@ -310,13 +413,13 @@ function paletteTpl(): TemplateResult {
if (e.target === e.currentTarget) closeChatSearch();
}}
>
- <div class="chat-search-palette" role="dialog" aria-label="Search your chats" @keydown=${onPaletteKeydown}>
+ <div class="chat-search-palette" role="dialog" aria-label="Search QM" @keydown=${onPaletteKeydown}>
<div class="chat-search-inputrow">
${icon(Search, 16)}
<input
class="chat-search-input"
type="text"
- placeholder="Search your chats…"
+ placeholder="Search chats, skills, crons, apps…"
autocomplete="off"
spellcheck="false"
.value=${searchState.query}
@@ -325,11 +428,17 @@ function paletteTpl(): TemplateResult {
<span class="chat-search-kbd">esc</span>
<button class="chat-search-cancel" type="button" @click=${closeChatSearch}>Cancel</button>
</div>
- <div class="chat-search-results">${body}</div>
+ <div class="chat-search-results">
+ ${resourceRows()}
+ ${searchState.resourcesLoading ? html`<div class="chat-search-empty">Loading resources…</div>` : nothing}
+ ${searchState.resourceFailures.length ? html`<div class="chat-search-empty chat-search-failed">Could not search: ${searchState.resourceFailures.join(", ")}. Try searching again.</div>` : nothing}
+ ${searchState.resourcesLimited ? html`<div class="chat-search-empty">Refine your search to see more resource matches.</div>` : nothing}
+ ${body}
+ </div>
${askRowShown() ? html`<div class="chat-search-askbar">${askRow()}</div>` : nothing}
<div class="chat-search-foot">
<span><span class="chat-search-kbd">↑↓</span> navigate</span>
- <span><span class="chat-search-kbd">↵</span> open chat</span>
+ <span><span class="chat-search-kbd">↵</span> open</span>
<span><span class="chat-search-kbd">${isMac ? "⌘↵" : "Ctrl+↵"}</span> ask QM in a new chat</span>
</div>
</div>
diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.ts
index be1a83154..818716229 100644
--- a/plugins/web-ui/src/shell.ts
+++ b/plugins/web-ui/src/shell.ts
@@ -82,7 +82,7 @@ import { openChatSearch } from "./search";
import { closeBrowse, openBrowse } from "./browse";
import { attachTooltip, hideTooltip, tip } from "./tooltip";
import { clearConnectorNotice, noteConnectorResult, renderConnectors, resetKeychainState } from "./connectors";
-import { renderDeploys } from "./deploys";
+import { openDeployById, renderDeploys } from "./deploys";
import { renderMemory, resetMemoryState } from "./memory";
import {
inboxOpenCount,
@@ -1067,6 +1067,7 @@ export async function boot(): Promise<void> {
params.get("scope") ?? (wantedItem ? resolveProjectScope(await ensureContexts(), wantedItem) : null);
if (scope) contextsState.selected = scope;
}
+ if (wanted === "deploys" && wantedItem) openDeployById(wantedItem);
if (wanted === "crons" && wantedItem) openCronById(wantedItem);
if (wanted === "webhooks" && wantedItem) openWebhookById(wantedItem);
if (wanted === "inbox" && wantedItem) openInboxItemById(wantedItem);
diff --git a/plugins/web-ui/test/deploys-source.test.ts b/plugins/web-ui/test/deploys-source.test.ts
index d3457335e..2028d3116 100644
--- a/plugins/web-ui/test/deploys-source.test.ts
+++ b/plugins/web-ui/test/deploys-source.test.ts
@@ -1,6 +1,15 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
+import { stripTypeScriptTypes } from "node:module";
+import { createContext, runInContext } from "node:vm";
+import { deploymentListRefreshCanRedraw, type DeploymentView } from "../src/deploy-view.ts";
+import {
+ withDeploymentListNotice,
+ withDeploymentDetailNotice,
+ withoutDeploymentDetailNotice,
+} from "../src/deploy-notices.ts";
+import { deepLinkPath } from "../src/deep-link.ts";
const source = readFileSync(new URL("../src/deploys.ts", import.meta.url), "utf8");
const css = readFileSync(new URL("../src/shell.css", import.meta.url), "utf8");
@@ -97,14 +106,110 @@ test("list refreshes cannot clear detail-scoped errors", () => {
assert.doesNotMatch(source, /deployDetailNotice|deployListNotice/);
});
-test("the initial list refresh leaves an opened detail and its loading state untouched", () => {
- const source = readFileSync(new URL("../src/deploys.ts", import.meta.url), "utf8");
- assert.match(
- source,
- /await refreshDeployments\(\);\s+if \(seq !== appState\.viewRenderSeq \|\| appState\.currentView !== "deploys"\) return;\s+if \(deploymentListRefreshCanRedraw\(activeDeploy\?\.id\)\) drawDeploysPage\(\);/,
- );
+function renderHarness(requestedId: string | null = null) {
+ const requests: Array<{ path: string; resolve: (response: unknown) => void }> = [];
+ const frames: Array<{ view: "list" | "detail"; id?: string; loading?: boolean }> = [];
+ const context = createContext({
+ appState: { currentView: "deploys", viewRenderSeq: 1 },
+ pendingDeployId: requestedId,
+ archiveCandidate: null,
+ restoreArchiveFocus: false,
+ scopedSession: { active: null },
+ contextsState: { selected: null },
+ deployScope: null,
+ deployList: [],
+ deployLoading: false,
+ deployNotices: { list: "", detail: null },
+ activeDeploy: null,
+ editingDeploy: null,
+ deployDraft: "",
+ deployRefreshSeq: 0,
+ setDeployBackgroundInert() {},
+ async ensureContexts() {},
+ withDeploymentListNotice,
+ withDeploymentDetailNotice,
+ withoutDeploymentDetailNotice,
+ deploymentListRefreshCanRedraw,
+ deepLinkPath,
+ UI_BASE: "",
+ history: { replaceState() {} },
+ errMessage: (error: Error) => error.message,
+ drawDeploysPage() {
+ frames.push({ view: "list" });
+ },
+ drawDeployDetail(deployment: DeploymentView, loading = false) {
+ frames.push({ view: "detail", id: deployment.id, loading });
+ },
+ api: (path: string) => new Promise((resolve) => requests.push({ path, resolve })),
+ });
+ const open = source.slice(source.indexOf("async function openDeploy("), source.indexOf("function drawDeployDetail("));
+ const refreshAndRender = source
+ .slice(source.indexOf("async function refreshDeployments("))
+ .replace("export async function", "async function");
+ runInContext(stripTypeScriptTypes(open + refreshAndRender), context);
+ return {
+ context,
+ requests,
+ frames,
+ render: () => runInContext("renderDeploys()", context) as Promise<void>,
+ open: () => runInContext('openDeploy({id: "opened-app"})', context) as Promise<void>,
+ };
+}
+
+test("the initial list refresh redraws the list when no detail was opened", async () => {
+ const h = renderHarness();
+ const rendering = h.render();
+ await new Promise((resolve) => setImmediate(resolve));
+ h.requests[0]!.resolve({ deployments: [{ id: "app" }] });
+ await rendering;
+ assert.deepEqual(h.frames, [{ view: "list" }, { view: "list" }]);
});
+test("the initial list refresh leaves an opened detail and its loading state untouched", async () => {
+ const h = renderHarness();
+ const rendering = h.render();
+ await new Promise((resolve) => setImmediate(resolve));
+ const opening = h.open();
+ assert.equal(h.requests[0]!.path, "/api/deployments");
+ assert.equal(h.requests[1]!.path, "/api/deployments/opened-app");
+ h.requests[0]!.resolve({ deployments: [] });
+ await rendering;
+ assert.deepEqual(h.frames, [{ view: "list" }, { view: "detail", id: "opened-app", loading: true }]);
+ h.requests[1]!.resolve({ deployment: { id: "opened-app" } });
+ await opening;
+ assert.deepEqual(h.frames.at(-1), { view: "detail", id: "opened-app", loading: false });
+});
+
+for (const listed of [false, true]) {
+ test(`app deep links load details when the requested app is ${listed ? "in" : "absent from"} the list`, async () => {
+ const h = renderHarness("linked-app");
+ const rendering = h.render();
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(h.context.pendingDeployId, null);
+ h.requests[0]!.resolve({ deployments: listed ? [{ id: "linked-app", displayName: "Linked app" }] : [] });
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(h.requests[1]!.path, "/api/deployments/linked-app");
+ assert.deepEqual(h.frames.at(-1), { view: "detail", id: "linked-app", loading: true });
+ h.requests[1]!.resolve({ deployment: { id: "linked-app" } });
+ await rendering;
+ assert.deepEqual(h.frames.at(-1), { view: "detail", id: "linked-app", loading: false });
+ });
+}
+
+for (const supersede of ["view", "render"] as const) {
+ test(`a pending app deep link cannot open after another ${supersede}`, async () => {
+ const h = renderHarness("linked-app");
+ const rendering = h.render();
+ await new Promise((resolve) => setImmediate(resolve));
+ if (supersede === "view") h.context.appState.currentView = "skills";
+ else h.context.appState.viewRenderSeq++;
+ h.requests[0]!.resolve({ deployments: [{ id: "linked-app" }] });
+ await rendering;
+ assert.equal(h.requests.length, 1);
+ assert.deepEqual(h.frames, [{ view: "list" }]);
+ });
+}
+
test("the empty Yours tab does not imply the account has no deployments", () => {
const source = readFileSync(new URL("../src/deploys.ts", import.meta.url), "utf8");
assert.match(source, /deploymentTabEmptyMessage\(deployTab\)/);
diff --git a/plugins/web-ui/test/search-race.test.ts b/plugins/web-ui/test/search-race.test.ts
index 6eac16b81..3fa05335e 100644
--- a/plugins/web-ui/test/search-race.test.ts
+++ b/plugins/web-ui/test/search-race.test.ts
@@ -6,6 +6,7 @@ import { createContext, runInContext } from "node:vm";
const source = readFileSync(new URL("../src/search.ts", import.meta.url), "utf8");
const handlers = source.slice(source.indexOf("function onQueryInput("), source.indexOf("function groupHitsBySession("));
+const selection = source.slice(source.indexOf("function rowCount("), source.indexOf("function onQueryInput("));
const lifecycle = source
.slice(source.indexOf("export function openChatSearch("), source.indexOf("function ensureHost("))
.replace("export function", "function");
@@ -16,10 +17,21 @@ const keyboard = source.slice(
);
function harness() {
- const state = { open: true, query: "", hits: [] as unknown[], loading: false, failed: false, sel: 0 };
+ const state = {
+ open: true,
+ query: "",
+ hits: [] as unknown[],
+ resources: [] as unknown[],
+ loading: false,
+ failed: false,
+ sel: 0,
+ selectionMoved: false,
+ };
const requests: Array<{ signal: AbortSignal; resolve: (value: unknown) => void; reject: (error: Error) => void }> =
[];
+ const resourceRequests: typeof requests = [];
let asks = 0;
+ const opened: unknown[] = [];
let timer: (() => void) | undefined;
const context = createContext({
searchState: state,
@@ -30,11 +42,15 @@ function harness() {
fetchSeq: 0,
AbortController,
draw() {},
- clampSel() {},
+ resourceResults: (r: unknown) => r,
+ UI_BASE: "",
+ resourceHits: () => state.resources,
+ openResource: (hit: unknown) => opened.push(hit),
+ openHit: (hit: unknown) => opened.push(hit),
+ scrollSelectedIntoView() {},
askQm() {
asks++;
},
- askRowShown: () => true,
requestAnimationFrame() {},
groupHitsBySession: (hits: unknown[]) => hits,
clearTimeout() {
@@ -45,15 +61,27 @@ function harness() {
return 1;
},
api: (_path: string, { signal }: { signal: AbortSignal }) =>
- new Promise((resolve, reject) => {
- requests.push({ signal, resolve, reject });
- }),
+ _path.startsWith("/api/resources/")
+ ? new Promise((resolve, reject) => {
+ resourceRequests.push({ signal, resolve, reject });
+ })
+ : new Promise((resolve, reject) => {
+ requests.push({ signal, resolve, reject });
+ }),
});
- runInContext(stripTypeScriptTypes(handlers + lifecycle + keyboard), context);
+ runInContext(stripTypeScriptTypes(selection + handlers + lifecycle + keyboard), context);
return {
state,
requests,
+ resourceRequests,
asks: () => asks,
+ opened,
+ resources(hits: unknown[]) {
+ state.resources = hits;
+ },
+ down() {
+ runInContext("onPaletteKeydown({key: 'ArrowDown', preventDefault(){}})", context);
+ },
enter() {
runInContext("onPaletteKeydown({key: 'Enter', preventDefault(){}})", context);
},
@@ -137,3 +165,101 @@ test("Enter while searching does not start an unintended agent conversation", ()
h.enter();
assert.equal(h.asks(), 0);
});
+
+test("Enter opens resources before chats and offsets chat selection correctly", () => {
+ const h = harness();
+ h.input("skill");
+ const resource = { title: "Skill", href: "/skills/1" };
+ const chat = { sessionId: "chat1" };
+ h.resources([resource]);
+ h.state.hits = [chat];
+ h.state.loading = true;
+ h.enter();
+ assert.deepEqual(h.opened, [resource]);
+ h.state.loading = false;
+ h.state.sel = 1;
+ h.enter();
+ assert.deepEqual(h.opened, [resource, chat]);
+ h.state.sel = 2;
+ Object.assign(h.state, { resourcesLoading: false });
+ h.enter();
+ assert.equal(h.asks(), 1);
+});
+
+test("chat results do not wait for resource results, and stale resource replies are ignored", async () => {
+ const h = harness();
+ h.input("old");
+ h.fire();
+ h.requests[0]!.resolve({ hits: [{ sessionId: "old" }] });
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(h.state.loading, false);
+ assert.equal(h.state.hits.length, 1);
+ h.input("new");
+ h.fire();
+ h.resourceRequests[0]!.resolve({ hits: [{ title: "Old" }], failed: [] });
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(JSON.stringify((h.state as unknown as { resources: unknown[] }).resources), "[]");
+ h.resourceRequests[1]!.resolve({ hits: [{ title: "New" }], failed: [] });
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(JSON.stringify((h.state as unknown as { resources: unknown[] }).resources), '[{"title":"New"}]');
+ assert.equal(h.state.loading, true);
+});
+
+test("closing search aborts both requests and prevents old resources reappearing after reopen", async () => {
+ const h = harness();
+ h.input("old");
+ h.fire();
+ h.close();
+ h.open();
+ assert.equal(h.resourceRequests[0]!.signal.aborted, true);
+ h.resourceRequests[0]!.resolve({ hits: [{ title: "Old" }], failed: [] });
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(JSON.stringify((h.state as unknown as { resources: unknown[] }).resources), "[]");
+});
+
+for (const navigate of [false, true]) {
+ test(`late resources preserve the ${navigate ? "keyboard-selected" : "first"} chat`, async () => {
+ const h = harness();
+ h.input("document");
+ h.fire();
+ const chats = [{ sessionId: "first" }, { sessionId: "second" }];
+ h.requests[0]!.resolve({ hits: chats });
+ await new Promise((resolve) => setImmediate(resolve));
+ if (navigate) h.down();
+ h.resourceRequests[0]!.resolve({ hits: [{ title: "One" }, { title: "Two" }], failed: [] });
+ await new Promise((resolve) => setImmediate(resolve));
+ h.enter();
+ assert.deepEqual(h.opened, [chats[navigate ? 1 : 0]]);
+ });
+}
+
+for (const first of ["chats", "resources"] as const) {
+ test(`late ${first === "chats" ? "resources" : "chats"} preserve the explicitly selected ask row`, async () => {
+ const h = harness();
+ h.input("document");
+ h.fire();
+ const chats = { hits: [{ sessionId: "chat" }] };
+ const resources = { hits: [{ title: "Resource" }], failed: [] };
+ if (first === "chats") h.requests[0]!.resolve(chats);
+ else h.resourceRequests[0]!.resolve(resources);
+ await new Promise((resolve) => setImmediate(resolve));
+ h.down();
+ if (first === "chats") h.resourceRequests[0]!.resolve(resources);
+ else h.requests[0]!.resolve(chats);
+ await new Promise((resolve) => setImmediate(resolve));
+ h.enter();
+ assert.equal(h.asks(), 1);
+ assert.deepEqual(h.opened, []);
+ });
+}
+
+test("initial resources select the first result instead of retaining the default ask row", async () => {
+ const h = harness();
+ h.input("document");
+ h.fire();
+ const resource = { title: "Resource" };
+ h.resourceRequests[0]!.resolve({ hits: [resource], failed: [] });
+ await new Promise((resolve) => setImmediate(resolve));
+ h.enter();
+ assert.deepEqual(h.opened, [resource]);
+});
diff --git a/plugins/web-ui/test/search-resources.test.ts b/plugins/web-ui/test/search-resources.test.ts
new file mode 100644
index 000000000..ad9a4a7f3
--- /dev/null
+++ b/plugins/web-ui/test/search-resources.test.ts
@@ -0,0 +1,31 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { resourceResults, matchResources } from "../src/search-resources.ts";
+
+test("compact server results link to each resource without downloading lists", () => {
+ const result = resourceResults(
+ {
+ hits: [
+ { id: "skill/1", kind: "skills", title: "Review", snippet: "Changes" },
+ { id: "cron1", kind: "crons", title: "Daily", snippet: "Digest" },
+ { id: "app1", kind: "deploys", title: "Sales", snippet: "Tracker" },
+ { id: "group:team", kind: "contexts", title: "Team", snippet: "Project" },
+ { id: "hook1", kind: "webhooks", title: "Review", snippet: "GitHub" },
+ ],
+ failed: ["crons"],
+ },
+ "/chat",
+ );
+ assert.deepEqual(
+ result.hits.map((hit) => hit.href),
+ [
+ "/chat/skills/skill%2F1",
+ "/chat/crons/cron1",
+ "/chat/apps/app1",
+ "/chat/contexts?scope=group%3Ateam",
+ "/chat/webhooks/hook1",
+ ],
+ );
+ assert.deepEqual(result.failed, ["Crons"]);
+ assert.equal(matchResources(result.hits, "review skills").length, 1);
+});
diff --git a/src/api/app-helpers.ts b/src/api/app-helpers.ts
index a3fc597dd..214b57973 100644
--- a/src/api/app-helpers.ts
+++ b/src/api/app-helpers.ts
@@ -473,7 +473,7 @@ export function createAppHelpers(deps: AppDeps, app: App) {
return undefined;
}
- function canManageSkill(skill: Skill, principalId: string): Promise<boolean> {
+ function canManageSkill(skill: Pick<Skill, "scopeId" | "createdBy">, principalId: string): Promise<boolean> {
return principalManagesArtifactHome(skill.scopeId, skill.createdBy, principalId);
}
@@ -511,7 +511,10 @@ export function createAppHelpers(deps: AppDeps, app: App) {
return (await effectiveDeploymentPermission(d, principalId)) != null;
}
- async function principalGitPermission(d: Deployment, principalId: string): Promise<"read" | "write" | null> {
+ async function principalGitPermission(
+ d: Pick<Deployment, "id" | "ownerScopeId" | "createdBy" | "createdInScope">,
+ principalId: string,
+ ): Promise<"read" | "write" | null> {
if (!principalId) return null;
const { kind } = parseScopeId(d.ownerScopeId);
if (await principalManagesArtifactHome(d.ownerScopeId, d.createdBy, principalId)) return "write";
diff --git a/src/api/app-messaging.ts b/src/api/app-messaging.ts
index 2124537b5..85f6f202e 100644
--- a/src/api/app-messaging.ts
+++ b/src/api/app-messaging.ts
@@ -27,6 +27,32 @@ import { CONTEXT_REQUEST_EXPIRY_MS } from "./app-types.ts";
import type { AppHelpers } from "./app-helpers.ts";
import type { AmbientHelpers } from "./app-ambient.ts";
+export async function cronVisibility(deps: AppDeps, h: AppHelpers, principalId: string) {
+ const viewerKeys = personKeys(await deps.directory.get(principalId).catch(() => null), principalId);
+ const viewersOwn = (id: string): boolean => viewerKeys.has(personKey(id));
+ const scopeNames = new Map<ScopeId, string | null>([[scopeId("org", orgIdOf()), null]]);
+ if (deps.identity.isInternal(deps.identity.classify(principalId))) {
+ for (const c of await deps.directory.listChannelsFor(principalId)) {
+ scopeNames.set(scopeId("channel", c.channelId), c.name);
+ }
+ }
+ for (const project of await h.projectsForViewer(principalId)) scopeNames.set(project.scopeId, project.name);
+ const allowed = (ownerScopeId: ScopeId): boolean => {
+ const { kind, ref } = parseScopeId(ownerScopeId);
+ return kind !== "group" || deps.projects?.recognizes(ref) !== true || scopeNames.has(ownerScopeId);
+ };
+ return {
+ viewersOwn,
+ scopeNames,
+ canSee: (c: Pick<import("../types.ts").Cron, "ownerScopeId" | "owner" | "members" | "destination">): boolean =>
+ allowed(c.ownerScopeId) &&
+ (viewersOwn(c.owner) ||
+ scopeNames.has(c.ownerScopeId) ||
+ c.members?.some((m) => viewersOwn(m.id)) === true ||
+ (c.destination?.type === "principal" && viewersOwn(c.destination.target))),
+ };
+}
+
export function createMessagingMethods(
deps: AppDeps,
h: AppHelpers,
@@ -92,7 +118,7 @@ export function createMessagingMethods(
| "reachNow"
| "resolveReachTarget"
> {
- const { adminBase, projectsForViewer, resolveReachTargetFor } = h;
+ const { adminBase, resolveReachTargetFor } = h;
const { judgeAmbientContainer, ambientSelf } = ambient;
const contextRequests = deps.contextRequests ?? createMemoryMap<SurfaceContextRequest>();
const contextRequestListeners = new Set<(request: SurfaceContextRequest) => void>();
@@ -165,29 +191,11 @@ export function createMessagingMethods(
},
async listCronsForViewer(principalId) {
const all = await deps.crons.list();
- const viewerKeys = personKeys(await deps.directory.get(principalId).catch(() => null), principalId);
- const viewersOwn = (id: string): boolean => viewerKeys.has(personKey(id));
- const scopeNames = new Map<ScopeId, string | null>([[scopeId("org", orgIdOf()), null]]);
- if (deps.identity.isInternal(deps.identity.classify(principalId))) {
- for (const c of await deps.directory.listChannelsFor(principalId)) {
- scopeNames.set(scopeId("channel", c.channelId), c.name);
- }
- }
- for (const project of await projectsForViewer(principalId)) scopeNames.set(project.scopeId, project.name);
- const allowed = (ownerScopeId: ScopeId): boolean => {
- const { kind, ref } = parseScopeId(ownerScopeId);
- return kind !== "group" || deps.projects?.recognizes(ref) !== true || scopeNames.has(ownerScopeId);
- };
- const owned = all.filter((c) => viewersOwn(c.owner) && allowed(c.ownerScopeId));
+ const { viewersOwn, scopeNames, canSee } = await cronVisibility(deps, h, principalId);
+ const owned = all.filter((c) => viewersOwn(c.owner) && canSee(c));
const visible = all
.filter((c) => !viewersOwn(c.owner))
- .filter((c) => allowed(c.ownerScopeId))
- .filter(
- (c) =>
- scopeNames.has(c.ownerScopeId) ||
- c.members?.some((m) => viewersOwn(m.id)) === true ||
- (c.destination?.type === "principal" && viewersOwn(c.destination.target)),
- )
+ .filter(canSee)
.map((c) => {
const name = scopeNames.get(c.ownerScopeId);
return name ? { ...c, scopeName: name } : c;
diff --git a/src/api/app-resource-search.ts b/src/api/app-resource-search.ts
new file mode 100644
index 000000000..08fe3d277
--- /dev/null
+++ b/src/api/app-resource-search.ts
@@ -0,0 +1,132 @@
+import { skillVisibilityContext } from "./app-skills.ts";
+import { visibleSkillRows } from "../skills/skill-store.ts";
+import type { App, AppDeps } from "./app-types.ts";
+import type { AppHelpers } from "./app-helpers.ts";
+import { cronVisibility } from "./app-messaging.ts";
+import { canAdministerWebhook } from "./control-service.ts";
+import {
+ createMemoryResourceSearch,
+ resourceHit,
+ type ResourceCandidate,
+ type ResourceKind,
+ type ResourceSearchHit,
+} from "../search/resource-search.ts";
+import { matchesSearchTerms, searchTerms } from "../sessions/entry-search.ts";
+import { scopeId } from "../types.ts";
+
+export function createResourceSearchMethods(
+ deps: AppDeps,
+ app: App,
+ helpers: AppHelpers,
+): Pick<App, "searchResources"> {
+ const store =
+ deps.resourceSearch ??
+ createMemoryResourceSearch(async (kind) => {
+ const defaults = { scopeId: scopeId("org", ""), ownerScopeId: scopeId("org", ""), createdBy: "", owner: "" };
+ switch (kind) {
+ case "skills":
+ return (await deps.skills.list()).map((s) => ({
+ ...defaults,
+ ...s,
+ title: s.manifest.name,
+ description: s.manifest.description,
+ }));
+ case "crons":
+ return (await deps.crons.list()).map((c) => ({
+ ...defaults,
+ ...c,
+ title: c.title ?? "",
+ description: `${c.action ?? ""} ${c.message ?? ""}`,
+ }));
+ case "deploys":
+ return (await deps.deploy.listDeployments()).map((d) => ({
+ ...defaults,
+ ...d,
+ title: d.displayName ?? d.name ?? "",
+ description: d.name ?? "",
+ }));
+ case "webhooks":
+ return (await deps.webhooks.list()).map((w) => ({
+ ...defaults,
+ ...w,
+ title: w.action,
+ description: w.verification.scheme,
+ }));
+ }
+ });
+ return {
+ async searchResources(principalId, query) {
+ query = query.slice(0, 500);
+ if (query.trim().length < 2 || !searchTerms(query).length) return { hits: [], failed: [], limited: [] };
+ let visibleSkills = new Set<string>();
+ let crons: ReturnType<typeof cronVisibility> | undefined;
+ let person: ReturnType<App["personMatcher"]> | undefined;
+ const canSee = async (kind: ResourceKind, row: ResourceCandidate): Promise<boolean> => {
+ switch (kind) {
+ case "skills":
+ if (await helpers.canManageSkill(row, principalId)) return true;
+ if (row.status !== "published") return false;
+ return visibleSkills.has(row.id);
+ case "crons":
+ crons ??= cronVisibility(deps, helpers, principalId);
+ return (await crons).canSee(row);
+ case "deploys":
+ return (await helpers.principalGitPermission(row, principalId)) !== null;
+ case "webhooks":
+ person ??= app.personMatcher(principalId);
+ return canAdministerWebhook(app, row, principalId, await person);
+ }
+ };
+ const kinds: ResourceKind[] = ["skills", "crons", "deploys", "webhooks"];
+ const limited: string[] = [];
+ const search = async (kind: ResourceKind): Promise<ResourceSearchHit[]> => {
+ const hits: ResourceSearchHit[] = [];
+ const candidates = await store.search(kind, query, 201);
+ const rows = candidates.slice(0, 200);
+ if (kind === "skills" && rows.length) {
+ const { skills, homes } = await store.skillMetadata([...new Set(rows.map((r) => r.title))]);
+ const { ordered, granted } = await skillVisibilityContext(deps, helpers, principalId, homes);
+ visibleSkills = new Set(visibleSkillRows(skills, ordered, granted).map((r) => r.skill.id));
+ }
+ for (let i = 0; i < rows.length; i += 20) {
+ const batch = rows.slice(i, i + 20);
+ const allowed = await Promise.all(batch.map((row) => canSee(kind, row)));
+ for (const [j, row] of batch.entries()) {
+ if (allowed[j]) hits.push(resourceHit(kind, row, query));
+ if (hits.length === 8) {
+ if (!limited.includes(kind)) limited.push(kind);
+ return hits;
+ }
+ }
+ }
+ return hits;
+ };
+ const projects = async (): Promise<ResourceSearchHit[]> => {
+ const [projects, channels] = await Promise.all([
+ helpers.projectsForViewer(principalId),
+ deps.identity.isInternal(deps.identity.classify(principalId))
+ ? deps.directory.listChannelsFor(principalId)
+ : Promise.resolve([]),
+ ]);
+ return [
+ { id: scopeId("personal", principalId), title: "Personal", description: "Personal project" },
+ ...projects.map((p) => ({ id: p.scopeId, title: p.name, description: "Project" })),
+ ...channels.map((c) => ({
+ id: scopeId("channel", c.channelId),
+ title: c.name ?? c.channelId,
+ description: "Channel project",
+ })),
+ ]
+ .filter((r) => matchesSearchTerms(`${r.title} ${r.description}`, searchTerms(query)))
+ .slice(0, 8)
+ .map((r) => resourceHit("contexts", r, query));
+ };
+ const results = await Promise.allSettled([...kinds.map(search), projects()]);
+ return {
+ hits: results.flatMap((r) => (r.status === "fulfilled" ? r.value : [])),
+ limited,
+ failed: results.flatMap((r, i) => (r.status === "rejected" ? [[...kinds, "contexts"][i]!] : [])),
+ };
+ },
+ };
+}
diff --git a/src/api/app-skills.ts b/src/api/app-skills.ts
index 5ed775256..c652ee38a 100644
--- a/src/api/app-skills.ts
+++ b/src/api/app-skills.ts
@@ -15,6 +15,36 @@ import { principalEntitledToScope } from "../resolution/context-filter.ts";
import type { Principal } from "../types.ts";
import type { AppHelpers } from "./app-helpers.ts";
+export async function skillVisibilityContext(
+ deps: AppDeps,
+ h: AppHelpers,
+ principalId: string,
+ homes: readonly ScopeId[],
+) {
+ const actor = deps.identity.classify(principalId);
+ const sharedHomes = [
+ ...new Set(
+ homes.filter((sid) => {
+ const k = parseScopeId(sid).kind;
+ return k === "channel" || k === "group";
+ }),
+ ),
+ ];
+ const accessibleScopes = new Set(await h.currentResourceScopesForViewer(principalId));
+ const member = sharedHomes.map((sid) => (accessibleScopes.has(sid) ? sid : null));
+ const shared = member.filter((sid): sid is ScopeId => sid !== null);
+ const teams = (actor.teamIds ?? []).map((t) => scopeId("team", t));
+ const ordered = [...new Set([scopeId("personal", principalId), ...shared, ...teams, scopeId("org", orgIdOf())])];
+ const entitled = (p: Principal, label: ScopeId, sess: ScopeId, org: ScopeId) =>
+ principalEntitledToScope(p, label, sess, org) || accessibleScopes.has(label);
+ const granted = (
+ await deps.acl
+ .sharedOfKindForAudience("skill", [actor], scopeId("personal", principalId), scopeId("org", orgIdOf()), entitled)
+ .catch(() => [])
+ ).map((g) => ({ id: parseRef(g.ref).id, ownerScopeId: g.ownerScopeId }));
+ return { ordered, granted };
+}
+
function requireRegistry(deps: AppDeps): { packs: SkillPackStore; fetcher: SkillPackFetcher } {
if (!deps.skillPacks || !deps.skillFetcher) throw new Error("skill registry not configured");
return { packs: deps.skillPacks, fetcher: deps.skillFetcher };
@@ -209,7 +239,7 @@ export function createSkillMethods(
| "createOwnedSkill"
| "deleteOwnedSkill"
> {
- const { canManageSkill, republishIfShared, currentResourceScopesForViewer } = h;
+ const { canManageSkill, republishIfShared } = h;
return {
listSkills() {
return deps.skills.list();
@@ -221,35 +251,12 @@ export function createSkillMethods(
return deps.skills.archive(id);
},
async listVisibleSkills(principalId) {
- const actor = deps.identity.classify(principalId);
- const sharedHomes = [
- ...new Set(
- (await deps.skills.list())
- .map((s) => s.scopeId)
- .filter((sid) => {
- const k = parseScopeId(sid).kind;
- return k === "channel" || k === "group";
- }),
- ),
- ];
- const accessibleScopes = new Set(await currentResourceScopesForViewer(principalId));
- const member = sharedHomes.map((sid) => (accessibleScopes.has(sid) ? sid : null));
- const shared = member.filter((sid): sid is ScopeId => sid !== null);
- const teams = (actor.teamIds ?? []).map((t) => scopeId("team", t));
- const ordered = [...new Set([scopeId("personal", principalId), ...shared, ...teams, scopeId("org", orgIdOf())])];
- const entitled = (p: Principal, label: ScopeId, sess: ScopeId, org: ScopeId) =>
- principalEntitledToScope(p, label, sess, org) || accessibleScopes.has(label);
- const granted = (
- await deps.acl
- .sharedOfKindForAudience(
- "skill",
- [actor],
- scopeId("personal", principalId),
- scopeId("org", orgIdOf()),
- entitled,
- )
- .catch(() => [])
- ).map((g) => ({ id: parseRef(g.ref).id, ownerScopeId: g.ownerScopeId }));
+ const { ordered, granted } = await skillVisibilityContext(
+ deps,
+ h,
+ principalId,
+ (await deps.skills.list()).map((s) => s.scopeId),
+ );
return deps.skills.visibleFor(ordered, granted);
},
canManageSkill(skill, principalId) {
diff --git a/src/api/app-types.ts b/src/api/app-types.ts
index 2998c938a..65827997b 100644
--- a/src/api/app-types.ts
+++ b/src/api/app-types.ts
@@ -1,5 +1,6 @@
import type { EventBus } from "../util/event-bus.ts";
import type { RunStreamEvent } from "../runs/run-stream-events.ts";
+import type { ResourceSearchStore, ResourceSearchHit } from "../search/resource-search.ts";
import type { ModelOverlayStore } from "../model/model-overlay-store.ts";
import type { SwarmService } from "../swarms/swarm-service.ts";
import type {
@@ -327,6 +328,10 @@ export interface App {
listConversationPins(threadRef: string, reader: string): Promise<SessionPinView[] | null>;
unpinConversationItem(threadRef: string, pinId: string): Promise<boolean | null>;
listSessions(principalId: string): Promise<Session[]>;
+ searchResources(
+ principalId: string,
+ query: string,
+ ): Promise<{ hits: ResourceSearchHit[]; failed: string[]; limited: string[] }>;
searchSessions(principalId: string, query: string, limit?: number): Promise<SessionSearchHit[]>;
search(
query: string,
@@ -563,6 +568,7 @@ export interface App {
}
export interface AppDeps {
+ resourceSearch?: ResourceSearchStore;
swarms?: SwarmService;
identity: IdentityService;
publicWebUrl?: string;
diff --git a/src/api/app.ts b/src/api/app.ts
index 2dd72d612..e8e7e5022 100644
--- a/src/api/app.ts
+++ b/src/api/app.ts
@@ -1,3 +1,4 @@
+import { createResourceSearchMethods } from "./app-resource-search.ts";
import type { App, AppDeps } from "./app-types.ts";
import { createAppHelpers } from "./app-helpers.ts";
import { createAmbientHelpers } from "./app-ambient.ts";
@@ -25,5 +26,5 @@ export function createApp(deps: AppDeps): App {
...createSkillMethods(deps, helpers),
};
Object.assign(app, methods);
- return Object.assign(app, createSearchMethods(deps, app, helpers));
+ return Object.assign(app, createSearchMethods(deps, app, helpers), createResourceSearchMethods(deps, app, helpers));
}
diff --git a/src/api/control-service.ts b/src/api/control-service.ts
index 6b70c26f6..735f760ea 100644
--- a/src/api/control-service.ts
+++ b/src/api/control-service.ts
@@ -189,7 +189,7 @@ export async function canAdministerCron(
export async function canAdministerWebhook(
app: Pick<App, "membershipControlsScope" | "managesScope" | "samePerson">,
- webhook: Webhook,
+ webhook: Pick<Webhook, "ownerScopeId" | "owner">,
actorId: string,
isActor?: (id: string) => Promise<boolean>,
): Promise<boolean> {
diff --git a/src/api/routes/surface.ts b/src/api/routes/surface.ts
index f78f23bcd..85c95adc5 100644
--- a/src/api/routes/surface.ts
+++ b/src/api/routes/surface.ts
@@ -480,6 +480,13 @@ async function listSessions(ctx: ApiCtx): Promise<void> {
return sendJson(res, 200, { sessions: await app.listSessions(principalId) });
}
+async function searchResources(ctx: ApiCtx): Promise<void> {
+ const principalId = ctx.actor?.p ?? ctx.url.searchParams.get("principalId");
+ if (!principalId) return sendJson(ctx.res, 400, { error: "bad_request" });
+ const query = (ctx.url.searchParams.get("q") ?? "").slice(0, 500);
+ return sendJson(ctx.res, 200, await ctx.app.searchResources(principalId, query));
+}
+
async function searchSessions(ctx: ApiCtx): Promise<void> {
const { res, app, url } = ctx;
const principalId = url.searchParams.get("principalId");
@@ -1287,6 +1294,7 @@ export const surfaceRoutes: ReadonlyArray<Route<ApiCtx>> = [
...sessionSharingRoutes,
...suggestedActivityRoutes,
{ method: "POST", path: "/v1/session-cap", auth: "source", handle: sessionCapability },
+ { method: "GET", path: "/v1/resources/search", auth: "source", handle: searchResources },
{ method: "GET", path: "/v1/sessions/search", auth: "source", handle: searchSessions },
{ method: "POST", path: "/v1/sessions/:id/title", auth: "source", handle: regenerateSessionTitle },
{ method: "POST", path: "/v1/sessions/:id/fork", auth: "source", handle: forkSession },
diff --git a/src/api/user-scoped-routes.ts b/src/api/user-scoped-routes.ts
index 9f1b17b48..7425cacae 100644
--- a/src/api/user-scoped-routes.ts
+++ b/src/api/user-scoped-routes.ts
@@ -49,6 +49,7 @@ const USER_SCOPED: Rule[] = [
pat("POST", "/v1/sessions/:id/title", { in: "body", name: "principalId" }),
pat("POST", "/v1/sessions/:id/fork", { in: "body", name: "principalId" }),
pat("GET", "/v1/sessions", { in: "query", name: "principalId" }),
+ pat("GET", "/v1/resources/search", { in: "query", name: "principalId" }),
pat("GET", "/v1/contexts", { in: "query", name: "principalId" }),
pat("GET", "/v1/projects", { in: "query", name: "principalId" }),
pat("POST", "/v1/projects", { in: "body", name: "principalId" }),
diff --git a/src/search/resource-search.ts b/src/search/resource-search.ts
new file mode 100644
index 000000000..ed99ed1e1
--- /dev/null
+++ b/src/search/resource-search.ts
@@ -0,0 +1,161 @@
+import type { SkillSummary } from "../skills/skill-store.ts";
+import type { PgPool } from "../persistence/pg-pool.ts";
+import { matchesSearchTerms, searchSnippet, searchTerms, tsPrefixQuery } from "../sessions/entry-search.ts";
+import type { Cron, ScopeId } from "../types.ts";
+
+export type ResourceKind = "skills" | "crons" | "deploys" | "webhooks";
+export interface ResourceCandidate {
+ id: string;
+ title: string;
+ description: string;
+ scopeId: ScopeId;
+ ownerScopeId: ScopeId;
+ createdInScope?: ScopeId;
+ createdBy: string;
+ owner: string;
+ status?: string;
+ members?: Cron["members"];
+ destination?: Cron["destination"];
+}
+export interface ResourceSearchHit {
+ id: string;
+ kind: ResourceKind | "contexts";
+ title: string;
+ snippet: string;
+}
+export interface ResourceSearchStore {
+ skillMetadata(names: readonly string[]): Promise<{ skills: SkillSummary[]; homes: ScopeId[] }>;
+ search(kind: ResourceKind, query: string, limit: number): Promise<ResourceCandidate[]>;
+}
+
+const sources = {
+ skills: {
+ table: "skills",
+ title: "coalesce(json->'manifest'->>'name', '')",
+ description: "coalesce(json->'manifest'->>'description', '')",
+ },
+ crons: {
+ table: "crons",
+ title: "coalesce(json->>'title', '')",
+ description: "coalesce(json->>'action', '') || ' ' || coalesce(json->>'message', '')",
+ },
+ deploys: {
+ table: "deployments",
+ title: "coalesce(json->>'displayName', json->>'name', '')",
+ description: "coalesce(json->>'name', '')",
+ },
+ webhooks: {
+ table: "webhooks",
+ title: "coalesce(json->>'action', '')",
+ description: "coalesce(json->'verification'->>'scheme', '')",
+ },
+} satisfies Record<ResourceKind, { table: string; title: string; description: string }>;
+
+export function createPostgresResourceSearch(pg: PgPool): ResourceSearchStore {
+ const migrations = Object.entries(sources).map(([kind, source]) => ({
+ id: `resource-search/${kind}/0001`,
+ statements: [
+ "SET LOCAL lock_timeout = '2s'",
+ "SET LOCAL statement_timeout = '15s'",
+ `CREATE TABLE IF NOT EXISTS ${source.table} (id TEXT PRIMARY KEY, json JSONB NOT NULL)`,
+ `CREATE INDEX IF NOT EXISTS ${source.table}_resource_search_gin ON ${source.table} USING GIN (to_tsvector('simple', ${source.title} || ' ' || ${source.description}))`,
+ ...(kind === "skills"
+ ? ["CREATE INDEX IF NOT EXISTS skills_resource_name_idx ON skills ((json->'manifest'->>'name'))"]
+ : []),
+ ],
+ }));
+ for (const migration of migrations) pg.registerMigration(migration);
+ const ready = new Map<ResourceKind, Promise<void>>();
+ const ensure = (kind: ResourceKind): Promise<void> => {
+ let pending = ready.get(kind);
+ if (!pending) {
+ pending = pg.migrate(migrations[Object.keys(sources).indexOf(kind)]!).catch((error) => {
+ ready.delete(kind);
+ throw error;
+ });
+ ready.set(kind, pending);
+ }
+ return pending;
+ };
+ return {
+ async skillMetadata(names) {
+ await ensure("skills");
+ const [rows, homes] = await Promise.all([
+ pg.q(
+ "SELECT id, json->>'scopeId' AS scope, json->>'status' AS status, json->'manifest'->>'name' AS name FROM skills WHERE json->'manifest'->>'name' = ANY($1::text[]) ORDER BY id",
+ [[...names]],
+ ),
+ pg.q("SELECT json->>'scopeId' AS scope FROM skills GROUP BY json->>'scopeId' ORDER BY min(id)"),
+ ]);
+ return {
+ skills: rows.map((r) => ({
+ id: String(r.id),
+ scopeId: r.scope as ScopeId,
+ status: r.status as SkillSummary["status"],
+ manifest: { name: String(r.name) },
+ })),
+ homes: homes.map((r) => r.scope as ScopeId),
+ };
+ },
+ async search(kind, query, limit) {
+ const terms = tsPrefixQuery(query);
+ if (!terms) return [];
+ const source = sources[kind];
+ await ensure(kind);
+ const vector = `to_tsvector('simple', ${source.title} || ' ' || ${source.description})`;
+ const rows = await pg.q(
+ `SELECT id, ${source.title} AS title, ${source.description} AS description,
+ json->>'scopeId' AS "scopeId", json->>'ownerScopeId' AS "ownerScopeId",
+ json->>'createdInScope' AS "createdInScope", json->>'createdBy' AS "createdBy",
+ json->>'owner' AS owner, json->>'status' AS status,
+ json->'members' AS members, json->'destination' AS destination
+ FROM ${source.table} WHERE ${vector} @@ to_tsquery('simple', $1)
+ ORDER BY ts_rank(${vector}, to_tsquery('simple', $1)) DESC, id
+ LIMIT $2`,
+ [terms, limit],
+ );
+ return rows as unknown as ResourceCandidate[];
+ },
+ };
+}
+
+export function createMemoryResourceSearch(
+ list: (kind: ResourceKind) => Promise<ResourceCandidate[]>,
+): ResourceSearchStore {
+ return {
+ async skillMetadata(names) {
+ const rows = await list("skills");
+ return {
+ homes: rows.map((r) => r.scopeId),
+ skills: rows
+ .filter((r) => names.includes(r.title))
+ .map((r) => ({
+ id: r.id,
+ scopeId: r.scopeId,
+ status: r.status as SkillSummary["status"],
+ manifest: { name: r.title },
+ })),
+ };
+ },
+ async search(kind, query, limit) {
+ const terms = searchTerms(query);
+ return (await list(kind))
+ .filter((row) => matchesSearchTerms(`${row.title} ${row.description}`, terms))
+ .sort((a, b) => a.id.localeCompare(b.id))
+ .slice(0, limit);
+ },
+ };
+}
+
+export function resourceHit(
+ kind: ResourceSearchHit["kind"],
+ row: Pick<ResourceCandidate, "id" | "title" | "description">,
+ query: string,
+): ResourceSearchHit {
+ return {
+ id: row.id,
+ kind,
+ title: searchSnippet(row.title || row.description || row.id, [], 120),
+ snippet: searchSnippet(row.description, searchTerms(query), 240),
+ };
+}
diff --git a/src/skills/skill-store.ts b/src/skills/skill-store.ts
index 13ce6c18c..9fe8692a4 100644
--- a/src/skills/skill-store.ts
+++ b/src/skills/skill-store.ts
@@ -101,8 +101,10 @@ function scopeKind(scopeId: ScopeId): string {
return parseScopeId(scopeId).kind ?? scopeId;
}
-function publishedByScopeAndName(all: Skill[]): Map<string, Skill> {
- const index = new Map<string, Skill>();
+export type SkillSummary = Pick<Skill, "id" | "scopeId" | "status"> & { manifest: Pick<SkillManifest, "name"> };
+
+function publishedByScopeAndName<T extends SkillSummary>(all: T[]): Map<string, T> {
+ const index = new Map<string, T>();
for (const s of all) {
if (s.status !== "published") continue;
const key = `${s.scopeId}\u0000${s.manifest.name}`;
@@ -111,13 +113,57 @@ function publishedByScopeAndName(all: Skill[]): Map<string, Skill> {
return index;
}
-function resolveFromIndex(index: Map<string, Skill>, name: string, orderedScopes: ScopeId[]): SkillResolution {
+function resolveFromIndex<T extends SkillSummary>(
+ index: Map<string, T>,
+ name: string,
+ orderedScopes: ScopeId[],
+): { skill: T | null; shadowed: T[] } {
if (!isSafeSkillName(name)) return { skill: null, shadowed: [] };
- const published = orderedScopes.map((sc) => index.get(`${sc}\u0000${name}`)).filter((s): s is Skill => Boolean(s));
+ const published = orderedScopes.map((sc) => index.get(`${sc}\u0000${name}`)).filter((s): s is T => Boolean(s));
const [skill, ...shadowed] = published;
return { skill: skill ?? null, shadowed };
}
+export function visibleSkillRows<T extends SkillSummary>(
+ all: T[],
+ orderedScopes: ScopeId[],
+ granted?: readonly GrantedSkillRef[],
+): Array<{ skill: T; shadowed: T[] }> {
+ const index = publishedByScopeAndName(all);
+ const inScope = new Set(orderedScopes);
+ const names = [
+ ...new Set(
+ all
+ .filter((s) => s.status === "published" && inScope.has(s.scopeId) && isSafeSkillName(s.manifest.name))
+ .map((s) => s.manifest.name),
+ ),
+ ];
+ const visible = names
+ .map((n) => resolveFromIndex(index, n, orderedScopes))
+ .filter((r): r is { skill: T; shadowed: T[] } => r.skill !== null);
+ if (granted?.length) {
+ const byId = new Map(all.map((skill) => [skill.id, skill]));
+ const byName = new Map(visible.map((r) => [r.skill.manifest.name, r]));
+ const seen = new Set<string>();
+ for (const ref of granted) {
+ if (seen.has(ref.id)) continue;
+ seen.add(ref.id);
+ const s = byId.get(ref.id);
+ if (!s || s.status !== "published" || s.scopeId !== ref.ownerScopeId || !isSafeSkillName(s.manifest.name))
+ continue;
+ const existing = byName.get(s.manifest.name);
+ if (existing) {
+ if (existing.skill.id !== s.id && !existing.shadowed.some((x) => x.id === s.id)) existing.shadowed.push(s);
+ continue;
+ }
+ const r = { skill: s, shadowed: [] as T[] };
+ byName.set(s.manifest.name, r);
+ visible.push(r);
+ }
+ }
+ return visible;
+}
+
export function createSkillStore(opts: SkillStoreOptions = {}): SkillStore {
const skills = opts.backing ?? createMemoryMap<Skill>();
const secret = opts.signingSecret ?? randomUUID();
@@ -231,39 +277,7 @@ export function createSkillStore(opts: SkillStoreOptions = {}): SkillStore {
async visibleFor(orderedScopes, granted) {
const all = await skills.all();
- const index = publishedByScopeAndName(all);
- const inScope = new Set(orderedScopes);
- const names = [
- ...new Set(
- all
- .filter((s) => s.status === "published" && inScope.has(s.scopeId) && isSafeSkillName(s.manifest.name))
- .map((s) => s.manifest.name),
- ),
- ];
- const visible = names
- .map((n) => resolveFromIndex(index, n, orderedScopes))
- .filter((r): r is SkillResolution & { skill: Skill } => r.skill !== null);
- if (granted?.length) {
- const byId = new Map(all.map((skill) => [skill.id, skill]));
- const byName = new Map(visible.map((r) => [r.skill.manifest.name, r]));
- const seen = new Set<string>();
- for (const ref of granted) {
- if (seen.has(ref.id)) continue;
- seen.add(ref.id);
- const s = byId.get(ref.id);
- if (!s || s.status !== "published" || s.scopeId !== ref.ownerScopeId || !isSafeSkillName(s.manifest.name))
- continue;
- const existing = byName.get(s.manifest.name);
- if (existing) {
- if (existing.skill.id !== s.id && !existing.shadowed.some((x) => x.id === s.id)) existing.shadowed.push(s);
- continue;
- }
- const r = { skill: s, shadowed: [] as Skill[] };
- byName.set(s.manifest.name, r);
- visible.push(r);
- }
- }
- return visible;
+ return visibleSkillRows(all, orderedScopes, granted);
},
async promote(id, targetScopeId) {
diff --git a/src/wiring.ts b/src/wiring.ts
index 698578712..82947b73e 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -4,6 +4,7 @@ import type { FlyPeerClaim } from "./deploy/fly-peer-claims.ts";
import { createMemoryEventBus } from "./util/event-bus.ts";
import { createPostgresNotifyBus } from "./persistence/postgres-notify-bus.ts";
import { emitRunText, type RunStreamEvent } from "./runs/run-stream-events.ts";
+import { createPostgresResourceSearch } from "./search/resource-search.ts";
import { createGatewayCatalog } from "./model/gateway-catalog.ts";
import { createSuggestedActivityService, type SuggestedActivityProfile } from "./suggestions/activities.ts";
import { createRuntimeService } from "./harness/runtime-control.ts";
@@ -1780,6 +1781,7 @@ export function buildApp(
})
: undefined;
const app = createApp({
+ ...(pgArtifactMap ? { resourceSearch: createPostgresResourceSearch(pgArtifactMap.pool) } : {}),
swarms,
identity,
...(config.publicWebUrl ? { publicWebUrl: config.publicWebUrl } : {}),
diff --git a/test/postgres-resource-search.test.ts b/test/postgres-resource-search.test.ts
new file mode 100644
index 000000000..cd5e32c68
--- /dev/null
+++ b/test/postgres-resource-search.test.ts
@@ -0,0 +1,101 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { randomUUID } from "node:crypto";
+import { createPgPool } from "../src/persistence/pg-pool.ts";
+import { createPostgresResourceSearch } from "../src/search/resource-search.ts";
+
+const database = process.env.DATABASE_URL;
+test(
+ "resource GIN indexes match real queries, exclude heavy fields, and track writes",
+ { skip: !database },
+ async () => {
+ const admin = createPgPool(database!);
+ const schema = `search_${randomUUID().replaceAll("-", "")}`;
+ await admin.q(`CREATE SCHEMA ${schema}`);
+ const url = new URL(database!);
+ url.searchParams.set("options", `-c search_path=${schema}`);
+ const pg = createPgPool(url.toString());
+ try {
+ let searchSql = "";
+ let searchParams: unknown[] = [];
+ const store = createPostgresResourceSearch({
+ ...pg,
+ q: async (sql, params, options) => {
+ if (sql.includes("@@ to_tsquery")) {
+ searchSql = sql;
+ searchParams = params ?? [];
+ }
+ return pg.q(sql, params, options);
+ },
+ });
+ for (const kind of ["skills", "crons", "deploys", "webhooks"] as const) await store.search(kind, "zanzibar", 50);
+ for (const [table, record] of [
+ [
+ "skills",
+ {
+ manifest: {
+ name: "zanzibar-review",
+ description: "release checklist",
+ body: "privatebody ".repeat(10000),
+ files: [{ content: "asset".repeat(10000) }],
+ },
+ },
+ ],
+ [
+ "crons",
+ { title: "zanzibar digest", action: "release checklist", fireLog: [{ note: "history ".repeat(10000) }] },
+ ],
+ [
+ "deployments",
+ {
+ name: "zanzibar",
+ displayName: "Release checklist",
+ versions: [{ files: "version ".repeat(10000) }],
+ endpoint: { secret: "never return" },
+ },
+ ],
+ [
+ "webhooks",
+ { action: "zanzibar release checklist", verification: { scheme: "github", secret: "never return" } },
+ ],
+ ] as const) {
+ await pg.q(`INSERT INTO ${table} (id, json) VALUES ($1, $2)`, [
+ "hit",
+ JSON.stringify({ id: "hit", ...record, owner: "U1", ownerScopeId: "personal:U1", scopeId: "personal:U1" }),
+ ]);
+ const kind = table === "deployments" ? "deploys" : table;
+ const rows = await store.search(kind, "zanz release", 50);
+ const actualSql = searchSql;
+ const actualParams = searchParams;
+ assert.equal(rows.length, 1);
+ assert.ok(JSON.stringify(rows).length < 1000);
+ assert.equal(JSON.stringify(rows).includes("never return"), false);
+ assert.equal((await store.search(kind, "privatebody", 50)).length, 0);
+ assert.equal((await store.search(kind, "' | &", 50)).length, 0);
+ const indexes = await pg.q(
+ "SELECT indexdef FROM pg_indexes WHERE schemaname=$1 AND tablename=$2 AND indexname LIKE '%resource_search_gin'",
+ [schema, table],
+ );
+ assert.equal(indexes.length, 1);
+ const client = await (await pg.pool()).connect();
+ try {
+ await client.query("BEGIN");
+ await client.query("SET LOCAL enable_seqscan=off");
+ const plan = await client.query(`EXPLAIN (FORMAT JSON) ${actualSql}`, actualParams);
+ assert.match(JSON.stringify(plan.rows), /resource_search_gin/);
+ await client.query("ROLLBACK");
+ } finally {
+ client.release();
+ }
+ await pg.q(`UPDATE ${table} SET json = $1 WHERE id = 'hit'`, [
+ JSON.stringify({ id: "hit", title: "other", action: "other", name: "other", manifest: { name: "other" } }),
+ ]);
+ assert.equal((await store.search(kind, "zanzibar", 50)).length, 0);
+ }
+ } finally {
+ await pg.close();
+ await admin.q(`DROP SCHEMA ${schema} CASCADE`);
+ await admin.close();
+ }
+ },
+);
diff --git a/test/resource-search.test.ts b/test/resource-search.test.ts
new file mode 100644
index 000000000..5309bb158
--- /dev/null
+++ b/test/resource-search.test.ts
@@ -0,0 +1,179 @@
+import "./support/auto-fake-sprites.ts";
+import assert from "node:assert/strict";
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { buildApp } from "../src/wiring.ts";
+import { testConfig } from "./support/test-config.ts";
+
+function fresh() {
+ return buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "resource-search-")), seedSkills: false }));
+}
+
+test("resource search filters private data, includes owned drafts, and bounds snippets", async () => {
+ const { app, skills } = fresh();
+ const owned = await skills.create({
+ scopeId: "personal:U1",
+ createdBy: "U1",
+ manifest: {
+ name: "zanzibar-review",
+ description: "zanzibar ".repeat(1000),
+ body: "not searchable private body",
+ requiredCapabilities: [],
+ },
+ });
+ await skills.create({
+ scopeId: "personal:U2",
+ createdBy: "U2",
+ manifest: {
+ name: "zanzibar-secret",
+ description: "secret",
+ body: "secret",
+ requiredCapabilities: [],
+ },
+ });
+ const cron = await app.createCron({
+ owner: "U1",
+ createdBy: "U1",
+ ownerScopeId: "personal:U1",
+ action: "zanzibar ".repeat(200),
+ schedule: { everyMs: 60000 },
+ });
+ await app.createCron({
+ owner: "U2",
+ createdBy: "U2",
+ ownerScopeId: "personal:U2",
+ action: "zanzibar private",
+ schedule: { everyMs: 60000 },
+ });
+ const result = await app.searchResources("U1", "zanzibar");
+ assert.deepEqual(result.failed, []);
+ assert.deepEqual(new Set(result.hits.map((h) => h.id)), new Set([owned.id, cron.id]));
+ assert.ok(result.hits.every((h) => h.title.length <= 121 && h.snippet.length <= 242));
+ assert.ok(result.hits.every((h) => Object.keys(h).sort().join() === "id,kind,snippet,title"));
+ assert.deepEqual(await app.searchResources("U1", " "), { hits: [], failed: [], limited: [] });
+ assert.deepEqual(await app.searchResources("U1", "not searchable private body"), {
+ hits: [],
+ failed: [],
+ limited: [],
+ });
+});
+
+test("revoked project membership removes both project and cron hits, even for the creator", async () => {
+ const { app } = fresh();
+ await app.upsertDirectory([
+ { principalId: "owner", displayName: "Owner", type: "internal" },
+ { principalId: "member", displayName: "Member", type: "internal" },
+ ]);
+ const project = await app.createProject("owner", "Zanzibar launch");
+ assert.ok(project);
+ await app.addProjectMember(project.id, "owner", "member");
+ const cron = await app.createCron({
+ owner: "member",
+ createdBy: "member",
+ ownerScopeId: project.scopeId,
+ action: "zanzibar work",
+ schedule: { everyMs: 60000 },
+ });
+ let result = await app.searchResources("member", "zanzibar");
+ assert.ok(result.hits.some((h) => h.id === cron.id));
+ assert.ok(result.hits.some((h) => h.id === project.scopeId));
+ await app.removeProjectMember(project.id, "owner", "member");
+ result = await app.searchResources("member", "zanzibar");
+ assert.equal(result.hits.length, 0);
+});
+
+test("private matches within the candidate cap are filtered and authorized hits are bounded", async () => {
+ const { app } = fresh();
+ for (let i = 0; i < 65; i++)
+ await app.createCron({
+ owner: "U2",
+ createdBy: "U2",
+ ownerScopeId: "personal:U2",
+ title: `zanzibar private ${i}`,
+ action: `zanzibar private ${i}`,
+ schedule: { everyMs: 60000 },
+ });
+ const ids = new Set<string>();
+ for (let i = 0; i < 12; i++)
+ ids.add(
+ (
+ await app.createCron({
+ owner: "U1",
+ createdBy: "U1",
+ ownerScopeId: "personal:U1",
+ title: `zanzibar own ${i}`,
+ action: `zanzibar own ${i}`,
+ schedule: { everyMs: 60000 },
+ })
+ ).id,
+ );
+ const result = await app.searchResources("U1", "zanzibar");
+ assert.equal(result.hits.length, 8);
+ assert.ok(result.hits.every((h) => ids.has(h.id)));
+});
+
+test("private matches beyond the candidate cap reveal no search metadata", async () => {
+ const { app } = fresh();
+ const empty = await app.searchResources("U1", "zanzibar");
+ for (let i = 0; i < 201; i++)
+ await app.createCron({
+ owner: `private${Math.floor(i / 100)}`,
+ createdBy: `private${Math.floor(i / 100)}`,
+ ownerScopeId: `personal:private${Math.floor(i / 100)}`,
+ title: `zanzibar private ${i}`,
+ action: `zanzibar private ${i}`,
+ schedule: { everyMs: 60000 },
+ });
+ assert.deepEqual(await app.searchResources("U1", "zanzibar"), empty);
+});
+
+test("published skill search resolves shadowing without calling the full visible-skills API", async () => {
+ const { app, skills } = fresh();
+ for (const home of ["org:default-org", "personal:U1"] as const) {
+ const skill = await skills.create({
+ scopeId: home,
+ createdBy: "author",
+ manifest: {
+ name: "zanzibar",
+ description: `release in ${home}`,
+ body: "x".repeat(100000),
+ requiredCapabilities: [],
+ },
+ });
+ await skills.review(skill.id, "reviewer", []);
+ await skills.publish(skill.id);
+ }
+ app.listVisibleSkills = async () => {
+ throw new Error("must not load full registry");
+ };
+ const result = await app.searchResources("U1", "zanzibar");
+ assert.deepEqual(result.failed, []);
+ assert.equal(result.hits.length, 1);
+ assert.ok(result.hits[0]!.snippet.includes("personal:U1"));
+});
+
+test("webhook search uses the existing owner and project controls without exposing verification secrets", async () => {
+ const { app } = fresh();
+ const own = await app.createWebhook({
+ owner: "U1",
+ createdBy: "U1",
+ ownerScopeId: "personal:U1",
+ action: "zanzibar event",
+ verification: { scheme: "github", secret: "private-signing-secret" },
+ });
+ await app.createWebhook({
+ owner: "U2",
+ createdBy: "U2",
+ ownerScopeId: "personal:U2",
+ action: "zanzibar hidden",
+ verification: { scheme: "github", secret: "another-secret" },
+ });
+ const result = await app.searchResources("U1", "zanzibar");
+ assert.deepEqual(
+ result.hits.map((h) => h.id),
+ [own.id],
+ );
+ assert.equal(JSON.stringify(result).includes("secret"), false);
+});