@agent-native/core 0.12.12 → 0.12.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/workspace-dev.js +30 -2
- package/dist/cli/workspace-dev.js.map +1 -1
- package/dist/client/NewWorkspaceAppFlow.d.ts +9 -0
- package/dist/client/NewWorkspaceAppFlow.d.ts.map +1 -1
- package/dist/client/NewWorkspaceAppFlow.js +50 -4
- package/dist/client/NewWorkspaceAppFlow.js.map +1 -1
- package/dist/client/settings/SettingsPanel.d.ts.map +1 -1
- package/dist/client/settings/SettingsPanel.js +20 -16
- package/dist/client/settings/SettingsPanel.js.map +1 -1
- package/dist/client/settings/useBuilderStatus.d.ts +7 -7
- package/dist/client/settings/useBuilderStatus.d.ts.map +1 -1
- package/dist/client/settings/useBuilderStatus.js +1 -6
- package/dist/client/settings/useBuilderStatus.js.map +1 -1
- package/dist/server/auth.d.ts +2 -1
- package/dist/server/auth.d.ts.map +1 -1
- package/dist/server/auth.js.map +1 -1
- package/dist/server/builder-browser.d.ts +4 -4
- package/dist/server/builder-browser.d.ts.map +1 -1
- package/dist/server/builder-browser.js +1 -0
- package/dist/server/builder-browser.js.map +1 -1
- package/dist/server/core-routes-plugin.d.ts.map +1 -1
- package/dist/server/core-routes-plugin.js +33 -59
- package/dist/server/core-routes-plugin.js.map +1 -1
- package/dist/server/credential-provider.d.ts +20 -14
- package/dist/server/credential-provider.d.ts.map +1 -1
- package/dist/server/credential-provider.js +32 -45
- package/dist/server/credential-provider.js.map +1 -1
- package/dist/server/onboarding-html.d.ts +2 -1
- package/dist/server/onboarding-html.d.ts.map +1 -1
- package/dist/server/onboarding-html.js +105 -3
- package/dist/server/onboarding-html.js.map +1 -1
- package/dist/transcription/builder-transcription.d.ts.map +1 -1
- package/dist/transcription/builder-transcription.js +10 -3
- package/dist/transcription/builder-transcription.js.map +1 -1
- package/docs/content/template-mail.md +4 -0
- package/package.json +1 -1
|
@@ -96,8 +96,12 @@ function pipeAppOutput(prefix, chunk, write) {
|
|
|
96
96
|
function syncApps() {
|
|
97
97
|
const discovered = discoverApps();
|
|
98
98
|
for (const app of discovered) {
|
|
99
|
-
|
|
99
|
+
const existing = appById.get(app.id);
|
|
100
|
+
if (existing) {
|
|
101
|
+
existing.name = app.name;
|
|
102
|
+
existing.dir = app.dir;
|
|
100
103
|
continue;
|
|
104
|
+
}
|
|
101
105
|
const usedPorts = new Set(apps.map((existing) => existing.port));
|
|
102
106
|
let port = appPortStart;
|
|
103
107
|
while (usedPorts.has(port))
|
|
@@ -153,6 +157,12 @@ function appForRequest(req) {
|
|
|
153
157
|
: null;
|
|
154
158
|
}
|
|
155
159
|
function startApp(app) {
|
|
160
|
+
if (app.process && !app.process.killed)
|
|
161
|
+
return;
|
|
162
|
+
if (app.restartTimer) {
|
|
163
|
+
clearTimeout(app.restartTimer);
|
|
164
|
+
app.restartTimer = undefined;
|
|
165
|
+
}
|
|
156
166
|
const basePath = `/${app.id}`;
|
|
157
167
|
const workspaceAppsJson = JSON.stringify(apps.map((workspaceApp) => ({
|
|
158
168
|
id: workspaceApp.id,
|
|
@@ -187,6 +197,10 @@ function startApp(app) {
|
|
|
187
197
|
});
|
|
188
198
|
app.process = child;
|
|
189
199
|
const prefix = `[${app.id}]`;
|
|
200
|
+
const stableTimer = setTimeout(() => {
|
|
201
|
+
app.restartAttempts = 0;
|
|
202
|
+
}, 5_000);
|
|
203
|
+
stableTimer.unref();
|
|
190
204
|
child.stdout?.on("data", (chunk) => {
|
|
191
205
|
pipeAppOutput(prefix, chunk, (value) => process.stdout.write(value));
|
|
192
206
|
});
|
|
@@ -194,9 +208,19 @@ function startApp(app) {
|
|
|
194
208
|
pipeAppOutput(prefix, chunk, (value) => process.stderr.write(value));
|
|
195
209
|
});
|
|
196
210
|
child.on("exit", (code) => {
|
|
211
|
+
clearTimeout(stableTimer);
|
|
212
|
+
app.process = undefined;
|
|
213
|
+
app.ready = false;
|
|
197
214
|
if (code === 0 || shuttingDown)
|
|
198
215
|
return;
|
|
199
|
-
|
|
216
|
+
app.restartAttempts = (app.restartAttempts ?? 0) + 1;
|
|
217
|
+
const delay = appRestartDelay(app.restartAttempts);
|
|
218
|
+
console.error(`${prefix} exited with code ${code}; retrying in ${Math.round(delay / 1000)}s`);
|
|
219
|
+
app.restartTimer = setTimeout(() => {
|
|
220
|
+
app.restartTimer = undefined;
|
|
221
|
+
startApp(app);
|
|
222
|
+
}, delay);
|
|
223
|
+
app.restartTimer.unref();
|
|
200
224
|
});
|
|
201
225
|
}
|
|
202
226
|
function renderIndex() {
|
|
@@ -235,6 +259,10 @@ function renderIndex() {
|
|
|
235
259
|
// startup is invisible for the common case (small/no body, slow boot).
|
|
236
260
|
const PROXY_READY_TIMEOUT_MS = Number(process.env.WORKSPACE_PROXY_READY_TIMEOUT_MS ?? 30_000);
|
|
237
261
|
const PROXY_READY_RETRY_DELAY_MS = 250;
|
|
262
|
+
const APP_RESTART_MAX_DELAY_MS = 10_000;
|
|
263
|
+
function appRestartDelay(attempts) {
|
|
264
|
+
return Math.min(1_000 * 2 ** Math.max(0, attempts - 1), APP_RESTART_MAX_DELAY_MS);
|
|
265
|
+
}
|
|
238
266
|
function probePort(port, timeoutMs = 1_000) {
|
|
239
267
|
return new Promise((resolve) => {
|
|
240
268
|
const socket = new net.Socket();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workspace-dev.js","sourceRoot":"","sources":["../../src/cli/workspace-dev.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,KAAK,EAAqB,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,GAAG,MAAM,UAAU,CAAC;AAC3B,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,OAAO,KAAK,MAAM,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAgBlE,M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CAAC;AAED,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;AAC/B,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;AAEhC,MAAM,CAAC,aAAa,CAAC,CAAC","sourcesContent":["#!/usr/bin/env tsx\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport http from \"node:http\";\nimport net from \"node:net\";\nimport path from \"node:path\";\nimport type { Duplex } from \"node:stream\";\nimport * as Sentry from \"@sentry/node\";\nimport { extractOAuthStateAppId } from \"../shared/oauth-state.js\";\n\ninterface WorkspaceApp {\n id: string;\n name: string;\n dir: string;\n port: number;\n process?: ChildProcess;\n /**\n * Set true once we've successfully connected to the upstream. After that we\n * skip the readiness probe on every request — the child server stays\n * listening for the rest of the dev session.\n */\n ready?: boolean;\n}\n\nconst root = process.cwd();\nconst appsDir = path.join(root, \"apps\");\nfs.mkdirSync(path.join(root, \"data\"), { recursive: true });\nconst gatewayHost = process.env.WORKSPACE_HOST || \"127.0.0.1\";\nconst requestedPort = Number(\n process.env.WORKSPACE_PORT || process.env.PORT || 8080,\n);\nconst appPortStart = Number(process.env.WORKSPACE_APP_PORT_START || 8100);\nconst forceVite = process.env.WORKSPACE_VITE_FORCE === \"1\";\nlet gatewayUrl = `http://${gatewayHost}:${requestedPort}`;\n\nfunction readJson(file: string): any {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch {\n return null;\n }\n}\n\nfunction discoverApps(): WorkspaceApp[] {\n if (!fs.existsSync(appsDir)) return [];\n // existsSync → readdirSync is a TOCTOU race — appsDir can vanish between\n // the two calls (e.g. user running `git checkout` on the workspace mid-dev).\n // Treat ENOENT as \"no apps right now\" and let the next 2s sync recover.\n // Other errors get surfaced to Sentry so we learn about new failure modes.\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(appsDir, { withFileTypes: true });\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== \"ENOENT\") {\n console.warn(\n `[workspace] Could not read ${appsDir} (${code ?? \"unknown\"}): ` +\n `${(err as Error).message}`,\n );\n Sentry.captureException(err, {\n tags: { handled: \"dev-discover-readdir\" },\n level: \"warning\",\n });\n }\n return [];\n }\n return entries\n .filter((entry) => entry.isDirectory())\n .map((entry) => {\n const dir = path.join(appsDir, entry.name);\n const pkg = readJson(path.join(dir, \"package.json\"));\n if (!pkg) return null;\n return {\n id: entry.name,\n name: pkg.displayName || pkg.name || entry.name,\n dir,\n port: appPortStart,\n } satisfies WorkspaceApp;\n })\n .filter((app): app is WorkspaceApp => !!app)\n .sort((a, b) => {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.id.localeCompare(b.id);\n })\n .map((app, index) => ({ ...app, port: appPortStart + index }));\n}\n\nconst apps = discoverApps();\nif (apps.length === 0) {\n console.error(\"[workspace] No apps found under ./apps\");\n process.exit(1);\n}\n\nconst appById = new Map(apps.map((app) => [app.id, app]));\nconst defaultApp =\n process.env.WORKSPACE_DEFAULT_APP &&\n appById.has(process.env.WORKSPACE_DEFAULT_APP)\n ? process.env.WORKSPACE_DEFAULT_APP\n : appById.has(\"dispatch\")\n ? \"dispatch\"\n : apps[0].id;\n\nfunction isChildDevServerUrlLine(line: string): boolean {\n return /^\\s*➜\\s+(?:Local|Network):\\s+https?:\\/\\/(?:localhost|127\\.0\\.0\\.1|\\[::1\\]):\\d+(?:\\/\\S*)?\\s*$/i.test(\n line,\n );\n}\n\nfunction pipeAppOutput(\n prefix: string,\n chunk: unknown,\n write: (value: string) => void,\n): void {\n const lines = String(chunk)\n .split(/\\r?\\n/)\n .filter(Boolean)\n .filter((line) => !isChildDevServerUrlLine(line));\n if (lines.length === 0) return;\n write(lines.map((line) => `${prefix} ${line}`).join(\"\\n\") + \"\\n\");\n}\n\nfunction syncApps(): void {\n const discovered = discoverApps();\n for (const app of discovered) {\n if (appById.has(app.id)) continue;\n const usedPorts = new Set(apps.map((existing) => existing.port));\n let port = appPortStart;\n while (usedPorts.has(port)) port++;\n const next = { ...app, port };\n apps.push(next);\n apps.sort((a, b) => {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.id.localeCompare(b.id);\n });\n appById.set(next.id, next);\n console.log(`[workspace] Detected new app: /${next.id}`);\n startApp(next);\n }\n}\n\nlet syncTimer: NodeJS.Timeout | undefined;\nfunction scheduleSync(): void {\n if (syncTimer) clearTimeout(syncTimer);\n syncTimer = setTimeout(syncApps, 400);\n}\n\nfunction firstPathSegment(url: string | undefined): string | null {\n if (!url) return null;\n try {\n const parsed = new URL(url, \"http://workspace.local\");\n const [segment] = parsed.pathname.split(\"/\").filter(Boolean);\n return segment || null;\n } catch {\n return null;\n }\n}\n\nfunction appForRequest(req: http.IncomingMessage): WorkspaceApp | null {\n const params = new URL(req.url || \"/\", \"http://workspace.local\").searchParams;\n const explicit = params.get(\"_app\");\n if (explicit && appById.has(explicit)) return appById.get(explicit) ?? null;\n\n const direct = firstPathSegment(req.url);\n if (direct && appById.has(direct)) return appById.get(direct) ?? null;\n\n const fromState = extractOAuthStateAppId(params.get(\"state\"));\n if (fromState && appById.has(fromState)) {\n return appById.get(fromState) ?? null;\n }\n\n const referer = req.headers.referer;\n const fromReferer =\n typeof referer === \"string\" ? firstPathSegment(referer) : null;\n return fromReferer && appById.has(fromReferer)\n ? (appById.get(fromReferer) ?? null)\n : null;\n}\n\nfunction startApp(app: WorkspaceApp): void {\n const basePath = `/${app.id}`;\n const workspaceAppsJson = JSON.stringify(\n apps.map((workspaceApp) => ({\n id: workspaceApp.id,\n name: workspaceApp.name,\n path: `/${workspaceApp.id}`,\n })),\n );\n const child = spawn(\n \"pnpm\",\n [\n \"--dir\",\n app.dir,\n \"exec\",\n \"vite\",\n \"--host\",\n \"127.0.0.1\",\n \"--port\",\n String(app.port),\n \"--strictPort\",\n ...(forceVite ? [\"--force\"] : []),\n ],\n {\n cwd: root,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: {\n ...process.env,\n APP_NAME: app.id,\n AGENT_NATIVE_WORKSPACE: \"1\",\n AGENT_NATIVE_WORKSPACE_APPS_JSON: workspaceAppsJson,\n APP_BASE_PATH: basePath,\n VITE_AGENT_NATIVE_WORKSPACE: \"1\",\n VITE_APP_BASE_PATH: basePath,\n PORT: String(app.port),\n WORKSPACE_GATEWAY_URL: gatewayUrl,\n },\n },\n );\n app.process = child;\n\n const prefix = `[${app.id}]`;\n child.stdout?.on(\"data\", (chunk) => {\n pipeAppOutput(prefix, chunk, (value) => process.stdout.write(value));\n });\n child.stderr?.on(\"data\", (chunk) => {\n pipeAppOutput(prefix, chunk, (value) => process.stderr.write(value));\n });\n child.on(\"exit\", (code) => {\n if (code === 0 || shuttingDown) return;\n console.error(`${prefix} exited with code ${code}`);\n });\n}\n\nfunction renderIndex(): string {\n return `<!doctype html>\n<html>\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>Agent-Native Workspace</title>\n <style>\n body { font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif; margin: 0; padding: 32px; background: #fafafa; color: #171717; }\n main { max-width: 760px; margin: 0 auto; }\n a { color: inherit; text-decoration: none; }\n .grid { display: grid; gap: 12px; margin-top: 20px; }\n .card { display: flex; justify-content: space-between; border: 1px solid #d4d4d4; border-radius: 8px; padding: 14px 16px; background: white; }\n .muted { color: #737373; }\n </style>\n </head>\n <body>\n <main>\n <h1>Agent-Native Workspace</h1>\n <p class=\"muted\">Open an app below. Dispatch is the workspace control plane.</p>\n <div class=\"grid\">\n ${apps\n .map(\n (app) =>\n `<a class=\"card\" href=\"/${app.id}\"><strong>${app.name}</strong><span class=\"muted\">/${app.id}</span></a>`,\n )\n .join(\"\")}\n </div>\n </main>\n </body>\n</html>`;\n}\n\n// On `pnpm dev` the gateway answers requests immediately, but each app's vite\n// server takes a beat to bind its port. Without retry, the user sees an\n// \"App is not ready yet: ECONNREFUSED\" banner on the first page load and has\n// to refresh manually. We do a quick pre-flight TCP connect with retry so\n// startup is invisible for the common case (small/no body, slow boot).\nconst PROXY_READY_TIMEOUT_MS = Number(\n process.env.WORKSPACE_PROXY_READY_TIMEOUT_MS ?? 30_000,\n);\nconst PROXY_READY_RETRY_DELAY_MS = 250;\n\nfunction probePort(port: number, timeoutMs = 1_000): Promise<boolean> {\n return new Promise((resolve) => {\n const socket = new net.Socket();\n let settled = false;\n const finish = (ok: boolean) => {\n if (settled) return;\n settled = true;\n socket.destroy();\n resolve(ok);\n };\n socket.setTimeout(timeoutMs);\n socket.once(\"connect\", () => finish(true));\n socket.once(\"error\", () => finish(false));\n socket.once(\"timeout\", () => finish(false));\n socket.connect(port, \"127.0.0.1\");\n });\n}\n\nasync function waitForPort(port: number, deadline: number): Promise<boolean> {\n while (Date.now() < deadline) {\n if (await probePort(port)) return true;\n await new Promise((r) => setTimeout(r, PROXY_READY_RETRY_DELAY_MS));\n }\n return false;\n}\n\nfunction proxyHttp(\n app: WorkspaceApp,\n req: http.IncomingMessage,\n res: http.ServerResponse,\n): void {\n const dispatch = () => {\n const headers = { ...req.headers, host: `127.0.0.1:${app.port}` };\n const proxyReq = http.request(\n {\n hostname: \"127.0.0.1\",\n port: app.port,\n method: req.method,\n path: req.url,\n headers,\n },\n (proxyRes) => {\n app.ready = true;\n res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);\n proxyRes.pipe(res);\n },\n );\n\n proxyReq.on(\"error\", (err) => {\n if (res.headersSent) {\n res.end();\n return;\n }\n res.writeHead(502, { \"content-type\": \"text/plain\" });\n res.end(`App \"${app.id}\" is not ready yet: ${err.message}`);\n });\n\n req.pipe(proxyReq);\n };\n\n // Fast path: the upstream has accepted at least one request before, so it's\n // listening. Skip the probe so steady-state requests stay zero-latency.\n if (app.ready) {\n dispatch();\n return;\n }\n\n // Cold path: hold the request open while the child server boots. Node\n // keeps the request body in paused mode until a consumer attaches via\n // pipe(), so awaiting waitForPort() doesn't lose data.\n void waitForPort(app.port, Date.now() + PROXY_READY_TIMEOUT_MS).then(\n (ready) => {\n if (!ready) {\n if (!res.headersSent) {\n res.writeHead(502, { \"content-type\": \"text/plain\" });\n res.end(\n `App \"${app.id}\" is not ready yet: connect ECONNREFUSED 127.0.0.1:${app.port}`,\n );\n } else {\n res.end();\n }\n return;\n }\n app.ready = true;\n dispatch();\n },\n );\n}\n\nfunction proxyUpgrade(\n app: WorkspaceApp,\n req: http.IncomingMessage,\n socket: Duplex,\n head: Buffer,\n): void {\n const target = net.connect(app.port, \"127.0.0.1\", () => {\n const headers = Object.entries({\n ...req.headers,\n host: `127.0.0.1:${app.port}`,\n })\n .flatMap(([key, value]) =>\n Array.isArray(value)\n ? value.map((item) => `${key}: ${item}`)\n : [`${key}: ${value ?? \"\"}`],\n )\n .join(\"\\r\\n\");\n target.write(\n `${req.method} ${req.url} HTTP/${req.httpVersion}\\r\\n${headers}\\r\\n\\r\\n`,\n );\n if (head.length) target.write(head);\n socket.pipe(target).pipe(socket);\n });\n\n target.on(\"error\", () => socket.destroy());\n}\n\nlet shuttingDown = false;\nlet workspaceStarted = false;\n\nfunction handleWatcherError(err: NodeJS.ErrnoException): void {\n // ENOSPC: system inotify watcher limit hit (Linux). Userland-fixable;\n // capture as a warning so we still see frequency in Sentry but don't get\n // paged. Print actionable guidance and continue without watching — the\n // 2s polling interval below keeps app discovery working.\n if (err.code === \"ENOSPC\") {\n console.warn(\n `[workspace] Recursive file watcher hit the system limit (ENOSPC). ` +\n `New apps will still be detected via polling every ~2s. ` +\n `On Linux you can raise the limit with ` +\n `\\`sudo sysctl fs.inotify.max_user_watches=524288\\` ` +\n `(persist via /etc/sysctl.d/*.conf). On macOS/Windows this usually ` +\n `means too many other watchers are running.`,\n );\n Sentry.captureException(err, {\n tags: { handled: \"dev-watch-enospc\" },\n level: \"warning\",\n });\n return;\n }\n // ENOENT: a watched directory disappeared (or a transient subdir under\n // appsDir vanished mid-enumeration). Benign — the polling fallback and\n // future scheduleSync calls will re-establish state. Don't capture.\n if (err.code === \"ENOENT\") {\n console.debug(\n `[workspace] Recursive file watcher saw a directory disappear ` +\n `(ENOENT: ${err.path ?? \"unknown\"}). Polling fallback will recover.`,\n );\n return;\n }\n // Unknown failure mode — keep the dev experience alive (polling still\n // runs) but surface to Sentry as a warning so we learn about new cases.\n console.warn(\n `[workspace] Recursive file watcher failed (${err.code ?? \"unknown\"}): ${err.message}. ` +\n `Falling back to polling.`,\n );\n Sentry.captureException(err, {\n tags: { handled: \"dev-watch-unknown\" },\n level: \"warning\",\n });\n}\n\nfunction startWorkspaceProcesses(): void {\n if (workspaceStarted) return;\n workspaceStarted = true;\n for (const app of apps) startApp(app);\n try {\n const watcher = fs.watch(appsDir, { recursive: true }, scheduleSync);\n // Async errors (e.g. ENOENT when a subdir vanishes mid-watch) surface on\n // the watcher rather than the original call site. Without an `error`\n // listener, Node would treat them as uncaught and crash the dev process.\n watcher.on(\"error\", (err) => {\n handleWatcherError(err as NodeJS.ErrnoException);\n });\n } catch (err) {\n handleWatcherError(err as NodeJS.ErrnoException);\n }\n setInterval(syncApps, 2_000).unref();\n}\n\nfunction openBrowser(url: string): void {\n if (process.env.WORKSPACE_NO_OPEN === \"1\") return;\n const command =\n process.platform === \"darwin\"\n ? \"open\"\n : process.platform === \"win32\"\n ? \"cmd\"\n : \"xdg-open\";\n const args = process.platform === \"win32\" ? [\"/c\", \"start\", \"\", url] : [url];\n const child = spawn(command, args, {\n stdio: \"ignore\",\n detached: true,\n });\n child.unref();\n}\n\nconst server = http.createServer((req, res) => {\n if (req.url === \"/\" || req.url === \"/index.html\") {\n res.writeHead(302, { location: `/${defaultApp}` });\n res.end();\n return;\n }\n\n if (req.url === \"/_workspace/apps\") {\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(\n JSON.stringify(\n apps.map((app) => ({\n id: app.id,\n name: app.name,\n path: `/${app.id}`,\n port: app.port,\n })),\n ),\n );\n return;\n }\n\n const app = appForRequest(req);\n if (!app) {\n res.writeHead(404, { \"content-type\": \"text/html\" });\n res.end(renderIndex());\n return;\n }\n proxyHttp(app, req, res);\n});\n\nserver.on(\"upgrade\", (req, socket, head) => {\n const app = appForRequest(req);\n if (!app) {\n socket.destroy();\n return;\n }\n proxyUpgrade(app, req, socket, head);\n});\n\nfunction listen(port: number, attempts = 20): void {\n server.once(\"error\", (err: NodeJS.ErrnoException) => {\n if (err.code === \"EADDRINUSE\" && attempts > 0) {\n listen(port + 1, attempts - 1);\n return;\n }\n console.error(`[workspace] Could not start gateway: ${err.message}`);\n process.exit(1);\n });\n server.listen(port, gatewayHost, () => {\n const address = server.address();\n const actualPort =\n typeof address === \"object\" && address ? address.port : port;\n gatewayUrl = `http://${gatewayHost}:${actualPort}`;\n console.log(\n `[workspace] Default: http://${gatewayHost}:${actualPort}/${defaultApp}`,\n );\n console.log(`[workspace] Gateway: http://${gatewayHost}:${actualPort}`);\n for (const app of apps) {\n console.log(`[workspace] ${app.id}: /${app.id} -> 127.0.0.1:${app.port}`);\n }\n startWorkspaceProcesses();\n openBrowser(`http://${gatewayHost}:${actualPort}/${defaultApp}`);\n });\n}\n\nfunction shutdown(): void {\n if (shuttingDown) return;\n shuttingDown = true;\n server.close();\n for (const app of apps) {\n app.process?.kill(\"SIGTERM\");\n }\n setTimeout(() => process.exit(0), 300).unref();\n}\n\nprocess.on(\"SIGINT\", shutdown);\nprocess.on(\"SIGTERM\", shutdown);\n\nlisten(requestedPort);\n"]}
|
|
1
|
+
{"version":3,"file":"workspace-dev.js","sourceRoot":"","sources":["../../src/cli/workspace-dev.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,KAAK,EAAqB,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,GAAG,MAAM,UAAU,CAAC;AAC3B,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,OAAO,KAAK,MAAM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vB,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IAC/B,CAAC;IACD,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,KAAK,EAAE,CAAC;AACjD,CAAC;AAED,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;AAC/B,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;AAEhC,MAAM,CAAC,aAAa,CAAC,CAAC","sourcesContent":["#!/usr/bin/env tsx\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport http from \"node:http\";\nimport net from \"node:net\";\nimport path from \"node:path\";\nimport type { Duplex } from \"node:stream\";\nimport * as Sentry from \"@sentry/node\";\nimport { extractOAuthStateAppId } from \"../shared/oauth-state.js\";\n\ninterface WorkspaceApp {\n id: string;\n name: string;\n dir: string;\n port: number;\n process?: ChildProcess;\n restartTimer?: NodeJS.Timeout;\n restartAttempts?: number;\n /**\n * Set true once we've successfully connected to the upstream. After that we\n * skip the readiness probe on every request — the child server stays\n * listening for the rest of the dev session.\n */\n ready?: boolean;\n}\n\nconst root = process.cwd();\nconst appsDir = path.join(root, \"apps\");\nfs.mkdirSync(path.join(root, \"data\"), { recursive: true });\nconst gatewayHost = process.env.WORKSPACE_HOST || \"127.0.0.1\";\nconst requestedPort = Number(\n process.env.WORKSPACE_PORT || process.env.PORT || 8080,\n);\nconst appPortStart = Number(process.env.WORKSPACE_APP_PORT_START || 8100);\nconst forceVite = process.env.WORKSPACE_VITE_FORCE === \"1\";\nlet gatewayUrl = `http://${gatewayHost}:${requestedPort}`;\n\nfunction readJson(file: string): any {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch {\n return null;\n }\n}\n\nfunction discoverApps(): WorkspaceApp[] {\n if (!fs.existsSync(appsDir)) return [];\n // existsSync → readdirSync is a TOCTOU race — appsDir can vanish between\n // the two calls (e.g. user running `git checkout` on the workspace mid-dev).\n // Treat ENOENT as \"no apps right now\" and let the next 2s sync recover.\n // Other errors get surfaced to Sentry so we learn about new failure modes.\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(appsDir, { withFileTypes: true });\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== \"ENOENT\") {\n console.warn(\n `[workspace] Could not read ${appsDir} (${code ?? \"unknown\"}): ` +\n `${(err as Error).message}`,\n );\n Sentry.captureException(err, {\n tags: { handled: \"dev-discover-readdir\" },\n level: \"warning\",\n });\n }\n return [];\n }\n return entries\n .filter((entry) => entry.isDirectory())\n .map((entry) => {\n const dir = path.join(appsDir, entry.name);\n const pkg = readJson(path.join(dir, \"package.json\"));\n if (!pkg) return null;\n return {\n id: entry.name,\n name: pkg.displayName || pkg.name || entry.name,\n dir,\n port: appPortStart,\n } satisfies WorkspaceApp;\n })\n .filter((app): app is WorkspaceApp => !!app)\n .sort((a, b) => {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.id.localeCompare(b.id);\n })\n .map((app, index) => ({ ...app, port: appPortStart + index }));\n}\n\nconst apps = discoverApps();\nif (apps.length === 0) {\n console.error(\"[workspace] No apps found under ./apps\");\n process.exit(1);\n}\n\nconst appById = new Map(apps.map((app) => [app.id, app]));\nconst defaultApp =\n process.env.WORKSPACE_DEFAULT_APP &&\n appById.has(process.env.WORKSPACE_DEFAULT_APP)\n ? process.env.WORKSPACE_DEFAULT_APP\n : appById.has(\"dispatch\")\n ? \"dispatch\"\n : apps[0].id;\n\nfunction isChildDevServerUrlLine(line: string): boolean {\n return /^\\s*➜\\s+(?:Local|Network):\\s+https?:\\/\\/(?:localhost|127\\.0\\.0\\.1|\\[::1\\]):\\d+(?:\\/\\S*)?\\s*$/i.test(\n line,\n );\n}\n\nfunction pipeAppOutput(\n prefix: string,\n chunk: unknown,\n write: (value: string) => void,\n): void {\n const lines = String(chunk)\n .split(/\\r?\\n/)\n .filter(Boolean)\n .filter((line) => !isChildDevServerUrlLine(line));\n if (lines.length === 0) return;\n write(lines.map((line) => `${prefix} ${line}`).join(\"\\n\") + \"\\n\");\n}\n\nfunction syncApps(): void {\n const discovered = discoverApps();\n for (const app of discovered) {\n const existing = appById.get(app.id);\n if (existing) {\n existing.name = app.name;\n existing.dir = app.dir;\n continue;\n }\n const usedPorts = new Set(apps.map((existing) => existing.port));\n let port = appPortStart;\n while (usedPorts.has(port)) port++;\n const next = { ...app, port };\n apps.push(next);\n apps.sort((a, b) => {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.id.localeCompare(b.id);\n });\n appById.set(next.id, next);\n console.log(`[workspace] Detected new app: /${next.id}`);\n startApp(next);\n }\n}\n\nlet syncTimer: NodeJS.Timeout | undefined;\nfunction scheduleSync(): void {\n if (syncTimer) clearTimeout(syncTimer);\n syncTimer = setTimeout(syncApps, 400);\n}\n\nfunction firstPathSegment(url: string | undefined): string | null {\n if (!url) return null;\n try {\n const parsed = new URL(url, \"http://workspace.local\");\n const [segment] = parsed.pathname.split(\"/\").filter(Boolean);\n return segment || null;\n } catch {\n return null;\n }\n}\n\nfunction appForRequest(req: http.IncomingMessage): WorkspaceApp | null {\n const params = new URL(req.url || \"/\", \"http://workspace.local\").searchParams;\n const explicit = params.get(\"_app\");\n if (explicit && appById.has(explicit)) return appById.get(explicit) ?? null;\n\n const direct = firstPathSegment(req.url);\n if (direct && appById.has(direct)) return appById.get(direct) ?? null;\n\n const fromState = extractOAuthStateAppId(params.get(\"state\"));\n if (fromState && appById.has(fromState)) {\n return appById.get(fromState) ?? null;\n }\n\n const referer = req.headers.referer;\n const fromReferer =\n typeof referer === \"string\" ? firstPathSegment(referer) : null;\n return fromReferer && appById.has(fromReferer)\n ? (appById.get(fromReferer) ?? null)\n : null;\n}\n\nfunction startApp(app: WorkspaceApp): void {\n if (app.process && !app.process.killed) return;\n if (app.restartTimer) {\n clearTimeout(app.restartTimer);\n app.restartTimer = undefined;\n }\n\n const basePath = `/${app.id}`;\n const workspaceAppsJson = JSON.stringify(\n apps.map((workspaceApp) => ({\n id: workspaceApp.id,\n name: workspaceApp.name,\n path: `/${workspaceApp.id}`,\n })),\n );\n const child = spawn(\n \"pnpm\",\n [\n \"--dir\",\n app.dir,\n \"exec\",\n \"vite\",\n \"--host\",\n \"127.0.0.1\",\n \"--port\",\n String(app.port),\n \"--strictPort\",\n ...(forceVite ? [\"--force\"] : []),\n ],\n {\n cwd: root,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: {\n ...process.env,\n APP_NAME: app.id,\n AGENT_NATIVE_WORKSPACE: \"1\",\n AGENT_NATIVE_WORKSPACE_APPS_JSON: workspaceAppsJson,\n APP_BASE_PATH: basePath,\n VITE_AGENT_NATIVE_WORKSPACE: \"1\",\n VITE_APP_BASE_PATH: basePath,\n PORT: String(app.port),\n WORKSPACE_GATEWAY_URL: gatewayUrl,\n },\n },\n );\n app.process = child;\n\n const prefix = `[${app.id}]`;\n const stableTimer = setTimeout(() => {\n app.restartAttempts = 0;\n }, 5_000);\n stableTimer.unref();\n\n child.stdout?.on(\"data\", (chunk) => {\n pipeAppOutput(prefix, chunk, (value) => process.stdout.write(value));\n });\n child.stderr?.on(\"data\", (chunk) => {\n pipeAppOutput(prefix, chunk, (value) => process.stderr.write(value));\n });\n child.on(\"exit\", (code) => {\n clearTimeout(stableTimer);\n app.process = undefined;\n app.ready = false;\n if (code === 0 || shuttingDown) return;\n app.restartAttempts = (app.restartAttempts ?? 0) + 1;\n const delay = appRestartDelay(app.restartAttempts);\n console.error(\n `${prefix} exited with code ${code}; retrying in ${Math.round(\n delay / 1000,\n )}s`,\n );\n app.restartTimer = setTimeout(() => {\n app.restartTimer = undefined;\n startApp(app);\n }, delay);\n app.restartTimer.unref();\n });\n}\n\nfunction renderIndex(): string {\n return `<!doctype html>\n<html>\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>Agent-Native Workspace</title>\n <style>\n body { font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif; margin: 0; padding: 32px; background: #fafafa; color: #171717; }\n main { max-width: 760px; margin: 0 auto; }\n a { color: inherit; text-decoration: none; }\n .grid { display: grid; gap: 12px; margin-top: 20px; }\n .card { display: flex; justify-content: space-between; border: 1px solid #d4d4d4; border-radius: 8px; padding: 14px 16px; background: white; }\n .muted { color: #737373; }\n </style>\n </head>\n <body>\n <main>\n <h1>Agent-Native Workspace</h1>\n <p class=\"muted\">Open an app below. Dispatch is the workspace control plane.</p>\n <div class=\"grid\">\n ${apps\n .map(\n (app) =>\n `<a class=\"card\" href=\"/${app.id}\"><strong>${app.name}</strong><span class=\"muted\">/${app.id}</span></a>`,\n )\n .join(\"\")}\n </div>\n </main>\n </body>\n</html>`;\n}\n\n// On `pnpm dev` the gateway answers requests immediately, but each app's vite\n// server takes a beat to bind its port. Without retry, the user sees an\n// \"App is not ready yet: ECONNREFUSED\" banner on the first page load and has\n// to refresh manually. We do a quick pre-flight TCP connect with retry so\n// startup is invisible for the common case (small/no body, slow boot).\nconst PROXY_READY_TIMEOUT_MS = Number(\n process.env.WORKSPACE_PROXY_READY_TIMEOUT_MS ?? 30_000,\n);\nconst PROXY_READY_RETRY_DELAY_MS = 250;\nconst APP_RESTART_MAX_DELAY_MS = 10_000;\n\nfunction appRestartDelay(attempts: number): number {\n return Math.min(\n 1_000 * 2 ** Math.max(0, attempts - 1),\n APP_RESTART_MAX_DELAY_MS,\n );\n}\n\nfunction probePort(port: number, timeoutMs = 1_000): Promise<boolean> {\n return new Promise((resolve) => {\n const socket = new net.Socket();\n let settled = false;\n const finish = (ok: boolean) => {\n if (settled) return;\n settled = true;\n socket.destroy();\n resolve(ok);\n };\n socket.setTimeout(timeoutMs);\n socket.once(\"connect\", () => finish(true));\n socket.once(\"error\", () => finish(false));\n socket.once(\"timeout\", () => finish(false));\n socket.connect(port, \"127.0.0.1\");\n });\n}\n\nasync function waitForPort(port: number, deadline: number): Promise<boolean> {\n while (Date.now() < deadline) {\n if (await probePort(port)) return true;\n await new Promise((r) => setTimeout(r, PROXY_READY_RETRY_DELAY_MS));\n }\n return false;\n}\n\nfunction proxyHttp(\n app: WorkspaceApp,\n req: http.IncomingMessage,\n res: http.ServerResponse,\n): void {\n const dispatch = () => {\n const headers = { ...req.headers, host: `127.0.0.1:${app.port}` };\n const proxyReq = http.request(\n {\n hostname: \"127.0.0.1\",\n port: app.port,\n method: req.method,\n path: req.url,\n headers,\n },\n (proxyRes) => {\n app.ready = true;\n res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);\n proxyRes.pipe(res);\n },\n );\n\n proxyReq.on(\"error\", (err) => {\n if (res.headersSent) {\n res.end();\n return;\n }\n res.writeHead(502, { \"content-type\": \"text/plain\" });\n res.end(`App \"${app.id}\" is not ready yet: ${err.message}`);\n });\n\n req.pipe(proxyReq);\n };\n\n // Fast path: the upstream has accepted at least one request before, so it's\n // listening. Skip the probe so steady-state requests stay zero-latency.\n if (app.ready) {\n dispatch();\n return;\n }\n\n // Cold path: hold the request open while the child server boots. Node\n // keeps the request body in paused mode until a consumer attaches via\n // pipe(), so awaiting waitForPort() doesn't lose data.\n void waitForPort(app.port, Date.now() + PROXY_READY_TIMEOUT_MS).then(\n (ready) => {\n if (!ready) {\n if (!res.headersSent) {\n res.writeHead(502, { \"content-type\": \"text/plain\" });\n res.end(\n `App \"${app.id}\" is not ready yet: connect ECONNREFUSED 127.0.0.1:${app.port}`,\n );\n } else {\n res.end();\n }\n return;\n }\n app.ready = true;\n dispatch();\n },\n );\n}\n\nfunction proxyUpgrade(\n app: WorkspaceApp,\n req: http.IncomingMessage,\n socket: Duplex,\n head: Buffer,\n): void {\n const target = net.connect(app.port, \"127.0.0.1\", () => {\n const headers = Object.entries({\n ...req.headers,\n host: `127.0.0.1:${app.port}`,\n })\n .flatMap(([key, value]) =>\n Array.isArray(value)\n ? value.map((item) => `${key}: ${item}`)\n : [`${key}: ${value ?? \"\"}`],\n )\n .join(\"\\r\\n\");\n target.write(\n `${req.method} ${req.url} HTTP/${req.httpVersion}\\r\\n${headers}\\r\\n\\r\\n`,\n );\n if (head.length) target.write(head);\n socket.pipe(target).pipe(socket);\n });\n\n target.on(\"error\", () => socket.destroy());\n}\n\nlet shuttingDown = false;\nlet workspaceStarted = false;\n\nfunction handleWatcherError(err: NodeJS.ErrnoException): void {\n // ENOSPC: system inotify watcher limit hit (Linux). Userland-fixable;\n // capture as a warning so we still see frequency in Sentry but don't get\n // paged. Print actionable guidance and continue without watching — the\n // 2s polling interval below keeps app discovery working.\n if (err.code === \"ENOSPC\") {\n console.warn(\n `[workspace] Recursive file watcher hit the system limit (ENOSPC). ` +\n `New apps will still be detected via polling every ~2s. ` +\n `On Linux you can raise the limit with ` +\n `\\`sudo sysctl fs.inotify.max_user_watches=524288\\` ` +\n `(persist via /etc/sysctl.d/*.conf). On macOS/Windows this usually ` +\n `means too many other watchers are running.`,\n );\n Sentry.captureException(err, {\n tags: { handled: \"dev-watch-enospc\" },\n level: \"warning\",\n });\n return;\n }\n // ENOENT: a watched directory disappeared (or a transient subdir under\n // appsDir vanished mid-enumeration). Benign — the polling fallback and\n // future scheduleSync calls will re-establish state. Don't capture.\n if (err.code === \"ENOENT\") {\n console.debug(\n `[workspace] Recursive file watcher saw a directory disappear ` +\n `(ENOENT: ${err.path ?? \"unknown\"}). Polling fallback will recover.`,\n );\n return;\n }\n // Unknown failure mode — keep the dev experience alive (polling still\n // runs) but surface to Sentry as a warning so we learn about new cases.\n console.warn(\n `[workspace] Recursive file watcher failed (${err.code ?? \"unknown\"}): ${err.message}. ` +\n `Falling back to polling.`,\n );\n Sentry.captureException(err, {\n tags: { handled: \"dev-watch-unknown\" },\n level: \"warning\",\n });\n}\n\nfunction startWorkspaceProcesses(): void {\n if (workspaceStarted) return;\n workspaceStarted = true;\n for (const app of apps) startApp(app);\n try {\n const watcher = fs.watch(appsDir, { recursive: true }, scheduleSync);\n // Async errors (e.g. ENOENT when a subdir vanishes mid-watch) surface on\n // the watcher rather than the original call site. Without an `error`\n // listener, Node would treat them as uncaught and crash the dev process.\n watcher.on(\"error\", (err) => {\n handleWatcherError(err as NodeJS.ErrnoException);\n });\n } catch (err) {\n handleWatcherError(err as NodeJS.ErrnoException);\n }\n setInterval(syncApps, 2_000).unref();\n}\n\nfunction openBrowser(url: string): void {\n if (process.env.WORKSPACE_NO_OPEN === \"1\") return;\n const command =\n process.platform === \"darwin\"\n ? \"open\"\n : process.platform === \"win32\"\n ? \"cmd\"\n : \"xdg-open\";\n const args = process.platform === \"win32\" ? [\"/c\", \"start\", \"\", url] : [url];\n const child = spawn(command, args, {\n stdio: \"ignore\",\n detached: true,\n });\n child.unref();\n}\n\nconst server = http.createServer((req, res) => {\n if (req.url === \"/\" || req.url === \"/index.html\") {\n res.writeHead(302, { location: `/${defaultApp}` });\n res.end();\n return;\n }\n\n if (req.url === \"/_workspace/apps\") {\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(\n JSON.stringify(\n apps.map((app) => ({\n id: app.id,\n name: app.name,\n path: `/${app.id}`,\n port: app.port,\n })),\n ),\n );\n return;\n }\n\n const app = appForRequest(req);\n if (!app) {\n res.writeHead(404, { \"content-type\": \"text/html\" });\n res.end(renderIndex());\n return;\n }\n proxyHttp(app, req, res);\n});\n\nserver.on(\"upgrade\", (req, socket, head) => {\n const app = appForRequest(req);\n if (!app) {\n socket.destroy();\n return;\n }\n proxyUpgrade(app, req, socket, head);\n});\n\nfunction listen(port: number, attempts = 20): void {\n server.once(\"error\", (err: NodeJS.ErrnoException) => {\n if (err.code === \"EADDRINUSE\" && attempts > 0) {\n listen(port + 1, attempts - 1);\n return;\n }\n console.error(`[workspace] Could not start gateway: ${err.message}`);\n process.exit(1);\n });\n server.listen(port, gatewayHost, () => {\n const address = server.address();\n const actualPort =\n typeof address === \"object\" && address ? address.port : port;\n gatewayUrl = `http://${gatewayHost}:${actualPort}`;\n console.log(\n `[workspace] Default: http://${gatewayHost}:${actualPort}/${defaultApp}`,\n );\n console.log(`[workspace] Gateway: http://${gatewayHost}:${actualPort}`);\n for (const app of apps) {\n console.log(`[workspace] ${app.id}: /${app.id} -> 127.0.0.1:${app.port}`);\n }\n startWorkspaceProcesses();\n openBrowser(`http://${gatewayHost}:${actualPort}/${defaultApp}`);\n });\n}\n\nfunction shutdown(): void {\n if (shuttingDown) return;\n shuttingDown = true;\n server.close();\n for (const app of apps) {\n app.process?.kill(\"SIGTERM\");\n }\n setTimeout(() => process.exit(0), 300).unref();\n}\n\nprocess.on(\"SIGINT\", shutdown);\nprocess.on(\"SIGTERM\", shutdown);\n\nlisten(requestedPort);\n"]}
|
|
@@ -5,6 +5,15 @@ export interface VaultSecretOption {
|
|
|
5
5
|
provider?: string | null;
|
|
6
6
|
description?: string | null;
|
|
7
7
|
}
|
|
8
|
+
export interface WorkspaceResourceOption {
|
|
9
|
+
id: string;
|
|
10
|
+
kind: "skill" | "instruction" | "agent" | "knowledge";
|
|
11
|
+
name: string;
|
|
12
|
+
description?: string | null;
|
|
13
|
+
path: string;
|
|
14
|
+
scope: "all" | "selected";
|
|
15
|
+
updatedAt?: number;
|
|
16
|
+
}
|
|
8
17
|
export interface NewWorkspaceAppFlowProps {
|
|
9
18
|
sourceApp?: string;
|
|
10
19
|
className?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NewWorkspaceAppFlow.d.ts","sourceRoot":"","sources":["../../src/client/NewWorkspaceAppFlow.tsx"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"NewWorkspaceAppFlow.d.ts","sourceRoot":"","sources":["../../src/client/NewWorkspaceAppFlow.tsx"],"names":[],"mappings":"AAgBA,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B;AAED,MAAM,WAAW,uBAAuB;IACtC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,OAAO,GAAG,aAAa,GAAG,OAAO,GAAG,WAAW,CAAC;IACtD,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,KAAK,GAAG,UAAU,CAAC;IAC1B,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,wBAAwB;IACvC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAClC;AA+FD,wBAAgB,mBAAmB,CAAC,EAClC,SAAqB,EACrB,SAAc,EACd,gBAAgB,GACjB,EAAE,wBAAwB,2CAwV1B"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
2
|
import { useEffect, useMemo, useState } from "react";
|
|
3
|
-
import { IconArrowUpRight, IconCheck, IconChevronDown, IconKey, } from "@tabler/icons-react";
|
|
3
|
+
import { IconArrowUpRight, IconBook, IconCheck, IconChevronDown, IconFileText, IconKey, } from "@tabler/icons-react";
|
|
4
4
|
import { agentNativePath, appBasePath } from "./api-path.js";
|
|
5
5
|
import { sendToAgentChat } from "./agent-chat.js";
|
|
6
6
|
import { isInBuilderFrame } from "./builder-frame.js";
|
|
@@ -50,6 +50,11 @@ function buildNewWorkspaceAppPrompt(input) {
|
|
|
50
50
|
const grantRequest = keyList
|
|
51
51
|
? `Requested Dispatch vault key grants for this app: ${keyList}`
|
|
52
52
|
: `Requested Dispatch vault key grants for this app: none`;
|
|
53
|
+
const resourceList = input.selectedResources.length
|
|
54
|
+
? input.selectedResources
|
|
55
|
+
.map((resource) => `- ${resource.name} (${resource.kind}, ${resource.path})`)
|
|
56
|
+
.join("\n")
|
|
57
|
+
: "none";
|
|
53
58
|
return [
|
|
54
59
|
`Create a new agent-native app in this workspace.`,
|
|
55
60
|
`This is a new workspace app request, not a feature request for the current app.`,
|
|
@@ -57,6 +62,7 @@ function buildNewWorkspaceAppPrompt(input) {
|
|
|
57
62
|
`Suggested app name: ${input.appId} (you may adjust the slug if it conflicts)`,
|
|
58
63
|
`User prompt: ${input.prompt.trim()}`,
|
|
59
64
|
grantRequest,
|
|
65
|
+
`Requested Dispatch workspace resources for this app:\n${resourceList}`,
|
|
60
66
|
``,
|
|
61
67
|
`Pick a starter template that fits the user's prompt — analytics, calendar, content, design, dispatch, forms, mail, slides, clips, or starter when none of the others fit.`,
|
|
62
68
|
`Use the workspace app layout: create it under apps/${input.appId}, mount it at /${input.appId}, keep it on the shared workspace database/hosting model, and avoid table-name collisions by namespacing any new domain tables to the app.`,
|
|
@@ -68,6 +74,9 @@ function buildNewWorkspaceAppPrompt(input) {
|
|
|
68
74
|
keyList
|
|
69
75
|
? `After the app exists, grant the selected Dispatch vault keys to appId "${input.appId}" and sync them once the app server is available. Treat these as requested grants, not active grants before creation succeeds.`
|
|
70
76
|
: `Do not grant any Dispatch vault keys unless the user asks later.`,
|
|
77
|
+
input.selectedResources.length
|
|
78
|
+
? `After the app exists, grant the selected Dispatch workspace resources to appId "${input.appId}" and sync them once the app server is available. Add a short note to apps/${input.appId}/AGENTS.md telling the app agent to read relevant shared resources under context/ or the selected resource paths before doing GTM/domain work.`
|
|
79
|
+
: `Do not grant any Dispatch workspace resources unless the user asks later.`,
|
|
71
80
|
``,
|
|
72
81
|
`App readiness requirements before handing off:`,
|
|
73
82
|
`- Ensure apps/${input.appId}/package.json exists with displayName/name metadata so Dispatch and the workspace gateway discover it from the filesystem. There is no separate workspace app registry to edit.`,
|
|
@@ -79,8 +88,11 @@ function buildNewWorkspaceAppPrompt(input) {
|
|
|
79
88
|
}
|
|
80
89
|
export function NewWorkspaceAppFlow({ sourceApp = "starter", className = "", dispatchBasePath, }) {
|
|
81
90
|
const [selectedSecretIds, setSelectedSecretIds] = useState([]);
|
|
91
|
+
const [selectedResourceIds, setSelectedResourceIds] = useState([]);
|
|
82
92
|
const [secrets, setSecrets] = useState([]);
|
|
93
|
+
const [resources, setResources] = useState([]);
|
|
83
94
|
const [secretsError, setSecretsError] = useState(null);
|
|
95
|
+
const [resourcesError, setResourcesError] = useState(null);
|
|
84
96
|
const [statusMessage, setStatusMessage] = useState(null);
|
|
85
97
|
const [branchUrl, setBranchUrl] = useState(null);
|
|
86
98
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
|
@@ -90,8 +102,9 @@ export function NewWorkspaceAppFlow({ sourceApp = "starter", className = "", dis
|
|
|
90
102
|
: dispatchBasePath;
|
|
91
103
|
useEffect(() => {
|
|
92
104
|
let cancelled = false;
|
|
93
|
-
const
|
|
94
|
-
|
|
105
|
+
const secretsUrl = actionUrl(effectiveDispatchBasePath, "list-vault-secret-options");
|
|
106
|
+
const resourcesUrl = actionUrl(effectiveDispatchBasePath, "list-workspace-resource-options");
|
|
107
|
+
fetchJson(secretsUrl)
|
|
95
108
|
.then((data) => {
|
|
96
109
|
if (cancelled)
|
|
97
110
|
return;
|
|
@@ -104,14 +117,31 @@ export function NewWorkspaceAppFlow({ sourceApp = "starter", className = "", dis
|
|
|
104
117
|
setSecrets([]);
|
|
105
118
|
setSecretsError(err?.message || "Could not load Dispatch keys");
|
|
106
119
|
});
|
|
120
|
+
fetchJson(resourcesUrl)
|
|
121
|
+
.then((data) => {
|
|
122
|
+
if (cancelled)
|
|
123
|
+
return;
|
|
124
|
+
setResources(Array.isArray(data) ? data : []);
|
|
125
|
+
setResourcesError(null);
|
|
126
|
+
})
|
|
127
|
+
.catch((err) => {
|
|
128
|
+
if (cancelled)
|
|
129
|
+
return;
|
|
130
|
+
setResources([]);
|
|
131
|
+
setResourcesError(err?.message || "Could not load Dispatch resources");
|
|
132
|
+
});
|
|
107
133
|
return () => {
|
|
108
134
|
cancelled = true;
|
|
109
135
|
};
|
|
110
136
|
}, [effectiveDispatchBasePath]);
|
|
111
137
|
const selectedSecrets = useMemo(() => secrets.filter((secret) => selectedSecretIds.includes(secret.id)), [secrets, selectedSecretIds]);
|
|
138
|
+
const selectedResources = useMemo(() => resources.filter((resource) => selectedResourceIds.includes(resource.id)), [resources, selectedResourceIds]);
|
|
112
139
|
const selectedSecretLabel = selectedSecretIds.length === 0
|
|
113
140
|
? "No keys selected"
|
|
114
141
|
: `${selectedSecretIds.length} key${selectedSecretIds.length === 1 ? "" : "s"} selected`;
|
|
142
|
+
const selectedResourceLabel = selectedResourceIds.length === 0
|
|
143
|
+
? "No resources selected"
|
|
144
|
+
: `${selectedResourceIds.length} resource${selectedResourceIds.length === 1 ? "" : "s"} selected`;
|
|
115
145
|
async function submit(rawPrompt) {
|
|
116
146
|
const prompt = rawPrompt.trim();
|
|
117
147
|
if (!prompt || isSubmitting)
|
|
@@ -126,6 +156,7 @@ export function NewWorkspaceAppFlow({ sourceApp = "starter", className = "", dis
|
|
|
126
156
|
appId,
|
|
127
157
|
prompt,
|
|
128
158
|
selectedKeys: selectedSecrets.map((s) => s.credentialKey),
|
|
159
|
+
selectedResources,
|
|
129
160
|
});
|
|
130
161
|
setIsSubmitting(true);
|
|
131
162
|
setStatusMessage(null);
|
|
@@ -147,6 +178,7 @@ export function NewWorkspaceAppFlow({ sourceApp = "starter", className = "", dis
|
|
|
147
178
|
prompt,
|
|
148
179
|
appId,
|
|
149
180
|
secretIds: selectedSecretIds,
|
|
181
|
+
resourceIds: selectedResourceIds,
|
|
150
182
|
}),
|
|
151
183
|
});
|
|
152
184
|
if (result?.mode === "builder") {
|
|
@@ -171,7 +203,12 @@ export function NewWorkspaceAppFlow({ sourceApp = "starter", className = "", dis
|
|
|
171
203
|
? current.filter((existing) => existing !== id)
|
|
172
204
|
: [...current, id]);
|
|
173
205
|
}
|
|
174
|
-
|
|
206
|
+
function toggleResource(id) {
|
|
207
|
+
setSelectedResourceIds((current) => current.includes(id)
|
|
208
|
+
? current.filter((existing) => existing !== id)
|
|
209
|
+
: [...current, id]);
|
|
210
|
+
}
|
|
211
|
+
return (_jsx("section", { className: `mx-auto flex w-full max-w-5xl flex-col gap-5 px-4 py-6 ${className}`, children: _jsxs("div", { className: "grid gap-5 lg:grid-cols-[minmax(0,1fr)_320px]", children: [_jsxs("div", { className: "flex flex-col gap-3", children: [_jsx(PromptComposer, { autoFocus: true, disabled: isSubmitting, placeholder: "Describe the app your teammate should be able to use...", draftScope: "dispatch:new-app", onSubmit: (text) => submit(text) }), statusMessage ? (_jsxs("div", { className: "rounded-md border border-border bg-muted/40 px-3 py-2 text-sm text-muted-foreground", children: [statusMessage, branchUrl ? (_jsxs("a", { href: branchUrl, target: "_blank", rel: "noreferrer", className: "ml-2 inline-flex items-center gap-1 font-medium text-foreground underline", children: ["Open branch ", _jsx(IconArrowUpRight, { className: "h-3 w-3" })] })) : null] })) : null] }), _jsxs("aside", { className: "overflow-hidden rounded-lg border border-border bg-card", children: [_jsx("div", { className: "border-b border-border px-4 py-3", children: _jsxs("div", { className: "flex items-center justify-between gap-3", children: [_jsxs("div", { className: "flex items-center gap-2 text-sm font-medium", children: [_jsx(IconKey, { className: "h-4 w-4" }), "Dispatch keys"] }), _jsx("span", { className: "shrink-0 rounded border border-border bg-background/40 px-2 py-0.5 text-[11px] text-muted-foreground", children: selectedSecretLabel })] }) }), _jsx("div", { className: "max-h-[220px] space-y-2 overflow-y-auto p-3", children: secretsError ? (_jsx("p", { className: "rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground", children: secretsError })) : secrets.length === 0 ? (_jsx("p", { className: "rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground", children: "No Dispatch vault keys found yet." })) : (secrets.map((secret) => {
|
|
175
212
|
const selected = selectedSecretIds.includes(secret.id);
|
|
176
213
|
return (_jsxs("div", { className: `group rounded-md border text-sm transition ${selected
|
|
177
214
|
? "border-primary/45 bg-primary/5 text-foreground shadow-[inset_0_0_0_1px_hsl(var(--primary)/0.08)]"
|
|
@@ -180,6 +217,15 @@ export function NewWorkspaceAppFlow({ sourceApp = "starter", className = "", dis
|
|
|
180
217
|
: "border-muted-foreground/35 text-transparent group-hover:border-muted-foreground/60"}`, children: selected ? _jsx(IconCheck, { className: "h-3 w-3" }) : null }), _jsxs("span", { className: "min-w-0 flex-1", children: [_jsx("span", { className: "block truncate font-medium", children: secret.credentialKey }), _jsx("span", { className: "block truncate text-xs text-muted-foreground/70", children: selected
|
|
181
218
|
? "Will be requested for this app"
|
|
182
219
|
: "Click to request" })] })] }), _jsxs("details", { className: "group/details border-t border-border/60 px-3 py-1.5 text-xs text-muted-foreground/75 open:bg-background/10", children: [_jsxs("summary", { className: "flex cursor-pointer list-none items-center gap-1.5 text-[11px] hover:text-muted-foreground [&::-webkit-details-marker]:hidden", children: [_jsx(IconChevronDown, { className: "h-3 w-3 transition-transform group-open/details:rotate-180" }), "Details"] }), _jsxs("div", { className: "mt-1.5 space-y-1 pb-0.5 pl-4", children: [_jsxs("div", { className: "truncate", children: ["Provider: ", secret.provider || "Not specified"] }), _jsxs("div", { className: "truncate", children: ["Name: ", secret.name] })] })] })] }, secret.id));
|
|
220
|
+
})) }), _jsx("div", { className: "border-y border-border px-4 py-3", children: _jsxs("div", { className: "flex items-center justify-between gap-3", children: [_jsxs("div", { className: "flex items-center gap-2 text-sm font-medium", children: [_jsx(IconBook, { className: "h-4 w-4" }), "Resource packs"] }), _jsx("span", { className: "shrink-0 rounded border border-border bg-background/40 px-2 py-0.5 text-[11px] text-muted-foreground", children: selectedResourceLabel })] }) }), _jsx("div", { className: "max-h-[220px] space-y-2 overflow-y-auto p-3", children: resourcesError ? (_jsx("p", { className: "rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground", children: resourcesError })) : resources.length === 0 ? (_jsx("p", { className: "rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground", children: "No Dispatch resource packs found yet." })) : (resources.map((resource) => {
|
|
221
|
+
const selected = selectedResourceIds.includes(resource.id);
|
|
222
|
+
return (_jsxs("div", { className: `group rounded-md border text-sm transition ${selected
|
|
223
|
+
? "border-primary/45 bg-primary/5 text-foreground shadow-[inset_0_0_0_1px_hsl(var(--primary)/0.08)]"
|
|
224
|
+
: "border-border bg-background/25 text-foreground hover:border-muted-foreground/40 hover:bg-accent/35"}`, children: [_jsxs("button", { type: "button", "aria-pressed": selected, onClick: () => toggleResource(resource.id), className: "flex w-full cursor-pointer items-start gap-3 rounded-md px-3 py-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30", children: [_jsx("span", { className: `mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border transition ${selected
|
|
225
|
+
? "border-primary/60 bg-primary/10 text-primary"
|
|
226
|
+
: "border-muted-foreground/35 text-transparent group-hover:border-muted-foreground/60"}`, children: selected ? _jsx(IconCheck, { className: "h-3 w-3" }) : null }), _jsxs("span", { className: "min-w-0 flex-1", children: [_jsxs("span", { className: "flex min-w-0 items-center gap-1.5", children: [_jsx(IconFileText, { className: "h-3.5 w-3.5 shrink-0 text-muted-foreground/70" }), _jsx("span", { className: "block truncate font-medium", children: resource.name })] }), _jsxs("span", { className: "block truncate text-xs text-muted-foreground/70", children: [resource.kind, " \u00B7 ", resource.path] })] })] }), _jsxs("details", { className: "group/details border-t border-border/60 px-3 py-1.5 text-xs text-muted-foreground/75 open:bg-background/10", children: [_jsxs("summary", { className: "flex cursor-pointer list-none items-center gap-1.5 text-[11px] hover:text-muted-foreground [&::-webkit-details-marker]:hidden", children: [_jsx(IconChevronDown, { className: "h-3 w-3 transition-transform group-open/details:rotate-180" }), "Details"] }), _jsxs("div", { className: "mt-1.5 space-y-1 pb-0.5 pl-4", children: [_jsxs("div", { className: "truncate", children: ["Scope:", " ", resource.scope === "all"
|
|
227
|
+
? "All apps"
|
|
228
|
+
: "Selected apps"] }), resource.description ? (_jsx("div", { className: "line-clamp-2", children: resource.description })) : null] })] })] }, resource.id));
|
|
183
229
|
})) })] })] }) }));
|
|
184
230
|
}
|
|
185
231
|
//# sourceMappingURL=NewWorkspaceAppFlow.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NewWorkspaceAppFlow.js","sourceRoot":"","sources":["../../src/client/NewWorkspaceAppFlow.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACrD,OAAO,EACL,gBAAgB,EAChB,SAAS,EACT,eAAe,EACf,OAAO,GACR,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAgB9D,SAAS,OAAO,CAAC,KAAa;IAC5B,OAAO,KAAK;SACT,WAAW,EAAE;SACb,OAAO,CAAC,aAAa,EAAE,GAAG,CAAC;SAC3B,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC;SACvB,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC;SACvB,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAClB,CAAC;AAED,SAAS,eAAe,CAAC,MAAc;IACrC,MAAM,OAAO,GAAG,MAAM;SACnB,OAAO,CAAC,sDAAsD,EAAE,GAAG,CAAC;SACpE,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC;SACpB,IAAI,EAAE,CAAC;IACV,OAAO,OAAO,CAAC,OAAO,IAAI,SAAS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E,GAAG,EAAE,CAAC,YAAY,CAAC,MAAM,CAAC,EAAE,CAAC,EACtC,SAAS,EAAC,wJAAwJ,aAElK,eACE,SAAS,EAAE,sFACT,QAAQ;wDACN,CAAC,CAAC,8CAA8C;wDAChD,CAAC,CAAC,oFACN,EAAE,YAED,QAAQ,CAAC,CAAC,CAAC,KAAC,SAAS,IAAC,SAAS,EAAC,SAAS,GAAG,CAAC,CAAC,CAAC,IAAI,GAC/C,EACP,gBAAM,SAAS,EAAC,gBAAgB,aAC9B,eAAM,SAAS,EAAC,4BAA4B,YACzC,MAAM,CAAC,aAAa,GAChB,EACP,eAAM,SAAS,EAAC,iDAAiD,YAC9D,QAAQ;gEACP,CAAC,CAAC,gCAAgC;gEAClC,CAAC,CAAC,kBAAkB,GACjB,IACF,IACA,EACT,mBAAS,SAAS,EAAC,4GAA4G,aAC7H,mBAAS,SAAS,EAAC,+HAA+H,aAChJ,KAAC,eAAe,IAAC,SAAS,EAAC,4DAA4D,GAAG,eAElF,EACV,eAAK,SAAS,EAAC,8BAA8B,aAC3C,eAAK,SAAS,EAAC,UAAU,2BACZ,MAAM,CAAC,QAAQ,IAAI,eAAe,IACzC,EACN,eAAK,SAAS,EAAC,UAAU,uBAAQ,MAAM,CAAC,IAAI,IAAO,IAC/C,IACE,KA5CL,MAAM,CAAC,EAAE,CA6CV,CACP,CAAC;4BACJ,CAAC,CAAC,CACH,GACG,IACA,IACJ,GACE,CACX,CAAC;AACJ,CAAC","sourcesContent":["import { useEffect, useMemo, useState } from \"react\";\nimport {\n IconArrowUpRight,\n IconCheck,\n IconChevronDown,\n IconKey,\n} from \"@tabler/icons-react\";\nimport { agentNativePath, appBasePath } from \"./api-path.js\";\nimport { sendToAgentChat } from \"./agent-chat.js\";\nimport { isInBuilderFrame } from \"./builder-frame.js\";\nimport { useDevMode } from \"./use-dev-mode.js\";\nimport { getWorkspaceAppIdValidationError } from \"../shared/workspace-app-id.js\";\nimport { PromptComposer } from \"./composer/PromptComposer.js\";\n\nexport interface VaultSecretOption {\n id: string;\n name: string;\n credentialKey: string;\n provider?: string | null;\n description?: string | null;\n}\n\nexport interface NewWorkspaceAppFlowProps {\n sourceApp?: string;\n className?: string;\n dispatchBasePath?: string | null;\n}\n\nfunction slugify(value: string): string {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .replace(/^[^a-z]+/, \"\")\n .slice(0, 48);\n}\n\nfunction titleFromPrompt(prompt: string): string {\n const cleaned = prompt\n .replace(/\\b(build|create|make|an?|the|app|tool|dashboard)\\b/gi, \" \")\n .replace(/\\s+/g, \" \")\n .trim();\n return slugify(cleaned || \"new-app\") || \"new-app\";\n}\n\nfunction actionUrl(basePath: string | null, action: string): string {\n const path = `/_agent-native/actions/${action}`;\n if (basePath === null) return agentNativePath(path);\n const normalized = basePath.replace(/\\/+$/, \"\");\n return `${normalized}${path}`;\n}\n\nfunction defaultDispatchBasePath(sourceApp?: string): string | null {\n if (sourceApp === \"dispatch\") return null;\n const base = appBasePath();\n if (base === \"/dispatch\") return null;\n return \"/dispatch\";\n}\n\nasync function fetchJson(url: string, init?: RequestInit): Promise<any> {\n const res = await fetch(url, init);\n const data = await res.json().catch(() => null);\n if (!res.ok) {\n throw new Error(\n data?.error || data?.message || `Request failed ${res.status}`,\n );\n }\n return data;\n}\n\nfunction buildNewWorkspaceAppPrompt(input: {\n appId: string;\n prompt: string;\n selectedKeys: string[];\n}): string {\n const keyList = input.selectedKeys.join(\", \");\n const grantRequest = keyList\n ? `Requested Dispatch vault key grants for this app: ${keyList}`\n : `Requested Dispatch vault key grants for this app: none`;\n\n return [\n `Create a new agent-native app in this workspace.`,\n `This is a new workspace app request, not a feature request for the current app.`,\n ``,\n `Suggested app name: ${input.appId} (you may adjust the slug if it conflicts)`,\n `User prompt: ${input.prompt.trim()}`,\n grantRequest,\n ``,\n `Pick a starter template that fits the user's prompt — analytics, calendar, content, design, dispatch, forms, mail, slides, clips, or starter when none of the others fit.`,\n `Use the workspace app layout: create it under apps/${input.appId}, mount it at /${input.appId}, keep it on the shared workspace database/hosting model, and avoid table-name collisions by namespacing any new domain tables to the app.`,\n `If the user's prompt mentions sibling apps like Mail, Calendar, Dispatch, or other templates, treat them as existing workspace neighbors or integrations. Do not scaffold those sibling apps inside apps/${input.appId} unless the user explicitly asks to create them too.`,\n `Do not satisfy this by adding a route, page, component, or file inside apps/starter or another existing app unless the user explicitly asks to modify that existing app.`,\n `Use relative workspace links like /${input.appId}. Do not hardcode localhost, 127.0.0.1, 8080, 8100, or any dev port; the active workspace gateway/browser origin owns the port.`,\n `Use the framework/template UI stack: shadcn/ui components and @tabler/icons-react. Do not add lucide-react or another icon library for standard UI.`,\n `Ensure the React Router client entry preserves APP_BASE_PATH/VITE_APP_BASE_PATH via appBasePath().`,\n keyList\n ? `After the app exists, grant the selected Dispatch vault keys to appId \"${input.appId}\" and sync them once the app server is available. Treat these as requested grants, not active grants before creation succeeds.`\n : `Do not grant any Dispatch vault keys unless the user asks later.`,\n ``,\n `App readiness requirements before handing off:`,\n `- Ensure apps/${input.appId}/package.json exists with displayName/name metadata so Dispatch and the workspace gateway discover it from the filesystem. There is no separate workspace app registry to edit.`,\n `- Update the app manifest/package/deploy metadata needed by the existing workspace deployment model; do not leave the app relying only on local discovery.`,\n `- Verify the app's agent card/A2A metadata is ready so Dispatch can discover and delegate to the app after deployment.`,\n `- Include a final verification note covering filesystem discovery, manifest/deploy metadata, relative same-origin routing, and agent-card readiness.`,\n `When it is ready, start or update the workspace dev server and navigate the user to /${input.appId}.`,\n ].join(\"\\n\");\n}\n\nexport function NewWorkspaceAppFlow({\n sourceApp = \"starter\",\n className = \"\",\n dispatchBasePath,\n}: NewWorkspaceAppFlowProps) {\n const [selectedSecretIds, setSelectedSecretIds] = useState<string[]>([]);\n const [secrets, setSecrets] = useState<VaultSecretOption[]>([]);\n const [secretsError, setSecretsError] = useState<string | null>(null);\n const [statusMessage, setStatusMessage] = useState<string | null>(null);\n const [branchUrl, setBranchUrl] = useState<string | null>(null);\n const [isSubmitting, setIsSubmitting] = useState(false);\n const { isDevMode } = useDevMode();\n\n const effectiveDispatchBasePath =\n dispatchBasePath === undefined\n ? defaultDispatchBasePath(sourceApp)\n : dispatchBasePath;\n\n useEffect(() => {\n let cancelled = false;\n const url = actionUrl(\n effectiveDispatchBasePath,\n \"list-vault-secret-options\",\n );\n fetchJson(url)\n .then((data) => {\n if (cancelled) return;\n setSecrets(Array.isArray(data) ? data : []);\n setSecretsError(null);\n })\n .catch((err) => {\n if (cancelled) return;\n setSecrets([]);\n setSecretsError(err?.message || \"Could not load Dispatch keys\");\n });\n return () => {\n cancelled = true;\n };\n }, [effectiveDispatchBasePath]);\n\n const selectedSecrets = useMemo(\n () => secrets.filter((secret) => selectedSecretIds.includes(secret.id)),\n [secrets, selectedSecretIds],\n );\n const selectedSecretLabel =\n selectedSecretIds.length === 0\n ? \"No keys selected\"\n : `${selectedSecretIds.length} key${selectedSecretIds.length === 1 ? \"\" : \"s\"} selected`;\n\n async function submit(rawPrompt: string) {\n const prompt = rawPrompt.trim();\n if (!prompt || isSubmitting) return;\n const appId = titleFromPrompt(prompt);\n const validationError = getWorkspaceAppIdValidationError(appId);\n if (validationError) {\n setStatusMessage(validationError);\n return;\n }\n\n const message = buildNewWorkspaceAppPrompt({\n appId,\n prompt,\n selectedKeys: selectedSecrets.map((s) => s.credentialKey),\n });\n setIsSubmitting(true);\n setStatusMessage(null);\n setBranchUrl(null);\n\n try {\n if (isInBuilderFrame()) {\n sendToAgentChat({ message, submit: true, type: \"code\" });\n setStatusMessage(\"Sent to Builder chat.\");\n } else if (isDevMode) {\n sendToAgentChat({ message, submit: true, type: \"code\", newTab: true });\n setStatusMessage(\"Sent to the local agent.\");\n } else {\n const result = await fetchJson(\n actionUrl(effectiveDispatchBasePath, \"start-workspace-app-creation\"),\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n prompt,\n appId,\n secretIds: selectedSecretIds,\n }),\n },\n );\n if (result?.mode === \"builder\") {\n setBranchUrl(result?.url || null);\n setStatusMessage(\"Builder branch created.\");\n } else {\n setStatusMessage(\n result?.message ||\n \"Builder app creation is coming soon here. Open this workspace in Builder to create an app from this prompt.\",\n );\n }\n }\n } catch (err: any) {\n setStatusMessage(err?.message || \"Could not start the new app flow.\");\n } finally {\n setIsSubmitting(false);\n }\n }\n\n function toggleSecret(id: string) {\n setSelectedSecretIds((current) =>\n current.includes(id)\n ? current.filter((existing) => existing !== id)\n : [...current, id],\n );\n }\n\n return (\n <section\n className={`mx-auto flex w-full max-w-5xl flex-col gap-5 px-4 py-6 ${className}`}\n >\n <div className=\"grid gap-5 lg:grid-cols-[minmax(0,1fr)_320px]\">\n <div className=\"flex flex-col gap-3\">\n <PromptComposer\n autoFocus\n disabled={isSubmitting}\n placeholder=\"Describe the app your teammate should be able to use...\"\n draftScope=\"dispatch:new-app\"\n onSubmit={(text) => submit(text)}\n />\n\n {statusMessage ? (\n <div className=\"rounded-md border border-border bg-muted/40 px-3 py-2 text-sm text-muted-foreground\">\n {statusMessage}\n {branchUrl ? (\n <a\n href={branchUrl}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"ml-2 inline-flex items-center gap-1 font-medium text-foreground underline\"\n >\n Open branch <IconArrowUpRight className=\"h-3 w-3\" />\n </a>\n ) : null}\n </div>\n ) : null}\n </div>\n\n <aside className=\"rounded-lg border border-border bg-card\">\n <div className=\"border-b border-border px-4 py-3\">\n <div className=\"flex items-center justify-between gap-3\">\n <div className=\"flex items-center gap-2 text-sm font-medium\">\n <IconKey className=\"h-4 w-4\" />\n Dispatch keys\n </div>\n <span className=\"shrink-0 rounded border border-border bg-background/40 px-2 py-0.5 text-[11px] text-muted-foreground\">\n {selectedSecretLabel}\n </span>\n </div>\n </div>\n <div className=\"max-h-[440px] space-y-2 overflow-y-auto p-3\">\n {secretsError ? (\n <p className=\"rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground\">\n {secretsError}\n </p>\n ) : secrets.length === 0 ? (\n <p className=\"rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground\">\n No Dispatch vault keys found yet.\n </p>\n ) : (\n secrets.map((secret) => {\n const selected = selectedSecretIds.includes(secret.id);\n return (\n <div\n key={secret.id}\n className={`group rounded-md border text-sm transition ${\n selected\n ? \"border-primary/45 bg-primary/5 text-foreground shadow-[inset_0_0_0_1px_hsl(var(--primary)/0.08)]\"\n : \"border-border bg-background/25 text-foreground hover:border-muted-foreground/40 hover:bg-accent/35\"\n }`}\n >\n <button\n type=\"button\"\n aria-pressed={selected}\n onClick={() => toggleSecret(secret.id)}\n className=\"flex w-full cursor-pointer items-start gap-3 rounded-md px-3 py-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30\"\n >\n <span\n className={`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border transition ${\n selected\n ? \"border-primary/60 bg-primary/10 text-primary\"\n : \"border-muted-foreground/35 text-transparent group-hover:border-muted-foreground/60\"\n }`}\n >\n {selected ? <IconCheck className=\"h-3 w-3\" /> : null}\n </span>\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate font-medium\">\n {secret.credentialKey}\n </span>\n <span className=\"block truncate text-xs text-muted-foreground/70\">\n {selected\n ? \"Will be requested for this app\"\n : \"Click to request\"}\n </span>\n </span>\n </button>\n <details className=\"group/details border-t border-border/60 px-3 py-1.5 text-xs text-muted-foreground/75 open:bg-background/10\">\n <summary className=\"flex cursor-pointer list-none items-center gap-1.5 text-[11px] hover:text-muted-foreground [&::-webkit-details-marker]:hidden\">\n <IconChevronDown className=\"h-3 w-3 transition-transform group-open/details:rotate-180\" />\n Details\n </summary>\n <div className=\"mt-1.5 space-y-1 pb-0.5 pl-4\">\n <div className=\"truncate\">\n Provider: {secret.provider || \"Not specified\"}\n </div>\n <div className=\"truncate\">Name: {secret.name}</div>\n </div>\n </details>\n </div>\n );\n })\n )}\n </div>\n </aside>\n </div>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CAA8C;wDAChD,CAAC,CAAC,oFACN,EAAE,YAED,QAAQ,CAAC,CAAC,CAAC,KAAC,SAAS,IAAC,SAAS,EAAC,SAAS,GAAG,CAAC,CAAC,CAAC,IAAI,GAC/C,EACP,gBAAM,SAAS,EAAC,gBAAgB,aAC9B,gBAAM,SAAS,EAAC,mCAAmC,aACjD,KAAC,YAAY,IAAC,SAAS,EAAC,+CAA+C,GAAG,EAC1E,eAAM,SAAS,EAAC,4BAA4B,YACzC,QAAQ,CAAC,IAAI,GACT,IACF,EACP,gBAAM,SAAS,EAAC,iDAAiD,aAC9D,QAAQ,CAAC,IAAI,cAAK,QAAQ,CAAC,IAAI,IAC3B,IACF,IACA,EACT,mBAAS,SAAS,EAAC,4GAA4G,aAC7H,mBAAS,SAAS,EAAC,+HAA+H,aAChJ,KAAC,eAAe,IAAC,SAAS,EAAC,4DAA4D,GAAG,eAElF,EACV,eAAK,SAAS,EAAC,8BAA8B,aAC3C,eAAK,SAAS,EAAC,UAAU,uBAChB,GAAG,EACT,QAAQ,CAAC,KAAK,KAAK,KAAK;oEACvB,CAAC,CAAC,UAAU;oEACZ,CAAC,CAAC,eAAe,IACf,EACL,QAAQ,CAAC,WAAW,CAAC,CAAC,CAAC,CACtB,cAAK,SAAS,EAAC,cAAc,YAC1B,QAAQ,CAAC,WAAW,GACjB,CACP,CAAC,CAAC,CAAC,IAAI,IACJ,IACE,KApDL,QAAQ,CAAC,EAAE,CAqDZ,CACP,CAAC;4BACJ,CAAC,CAAC,CACH,GACG,IACA,IACJ,GACE,CACX,CAAC;AACJ,CAAC","sourcesContent":["import { useEffect, useMemo, useState } from \"react\";\nimport {\n IconArrowUpRight,\n IconBook,\n IconCheck,\n IconChevronDown,\n IconFileText,\n IconKey,\n} from \"@tabler/icons-react\";\nimport { agentNativePath, appBasePath } from \"./api-path.js\";\nimport { sendToAgentChat } from \"./agent-chat.js\";\nimport { isInBuilderFrame } from \"./builder-frame.js\";\nimport { useDevMode } from \"./use-dev-mode.js\";\nimport { getWorkspaceAppIdValidationError } from \"../shared/workspace-app-id.js\";\nimport { PromptComposer } from \"./composer/PromptComposer.js\";\n\nexport interface VaultSecretOption {\n id: string;\n name: string;\n credentialKey: string;\n provider?: string | null;\n description?: string | null;\n}\n\nexport interface WorkspaceResourceOption {\n id: string;\n kind: \"skill\" | \"instruction\" | \"agent\" | \"knowledge\";\n name: string;\n description?: string | null;\n path: string;\n scope: \"all\" | \"selected\";\n updatedAt?: number;\n}\n\nexport interface NewWorkspaceAppFlowProps {\n sourceApp?: string;\n className?: string;\n dispatchBasePath?: string | null;\n}\n\nfunction slugify(value: string): string {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .replace(/^[^a-z]+/, \"\")\n .slice(0, 48);\n}\n\nfunction titleFromPrompt(prompt: string): string {\n const cleaned = prompt\n .replace(/\\b(build|create|make|an?|the|app|tool|dashboard)\\b/gi, \" \")\n .replace(/\\s+/g, \" \")\n .trim();\n return slugify(cleaned || \"new-app\") || \"new-app\";\n}\n\nfunction actionUrl(basePath: string | null, action: string): string {\n const path = `/_agent-native/actions/${action}`;\n if (basePath === null) return agentNativePath(path);\n const normalized = basePath.replace(/\\/+$/, \"\");\n return `${normalized}${path}`;\n}\n\nfunction defaultDispatchBasePath(sourceApp?: string): string | null {\n if (sourceApp === \"dispatch\") return null;\n const base = appBasePath();\n if (base === \"/dispatch\") return null;\n return \"/dispatch\";\n}\n\nasync function fetchJson(url: string, init?: RequestInit): Promise<any> {\n const res = await fetch(url, init);\n const data = await res.json().catch(() => null);\n if (!res.ok) {\n throw new Error(\n data?.error || data?.message || `Request failed ${res.status}`,\n );\n }\n return data;\n}\n\nfunction buildNewWorkspaceAppPrompt(input: {\n appId: string;\n prompt: string;\n selectedKeys: string[];\n selectedResources: WorkspaceResourceOption[];\n}): string {\n const keyList = input.selectedKeys.join(\", \");\n const grantRequest = keyList\n ? `Requested Dispatch vault key grants for this app: ${keyList}`\n : `Requested Dispatch vault key grants for this app: none`;\n const resourceList = input.selectedResources.length\n ? input.selectedResources\n .map(\n (resource) =>\n `- ${resource.name} (${resource.kind}, ${resource.path})`,\n )\n .join(\"\\n\")\n : \"none\";\n\n return [\n `Create a new agent-native app in this workspace.`,\n `This is a new workspace app request, not a feature request for the current app.`,\n ``,\n `Suggested app name: ${input.appId} (you may adjust the slug if it conflicts)`,\n `User prompt: ${input.prompt.trim()}`,\n grantRequest,\n `Requested Dispatch workspace resources for this app:\\n${resourceList}`,\n ``,\n `Pick a starter template that fits the user's prompt — analytics, calendar, content, design, dispatch, forms, mail, slides, clips, or starter when none of the others fit.`,\n `Use the workspace app layout: create it under apps/${input.appId}, mount it at /${input.appId}, keep it on the shared workspace database/hosting model, and avoid table-name collisions by namespacing any new domain tables to the app.`,\n `If the user's prompt mentions sibling apps like Mail, Calendar, Dispatch, or other templates, treat them as existing workspace neighbors or integrations. Do not scaffold those sibling apps inside apps/${input.appId} unless the user explicitly asks to create them too.`,\n `Do not satisfy this by adding a route, page, component, or file inside apps/starter or another existing app unless the user explicitly asks to modify that existing app.`,\n `Use relative workspace links like /${input.appId}. Do not hardcode localhost, 127.0.0.1, 8080, 8100, or any dev port; the active workspace gateway/browser origin owns the port.`,\n `Use the framework/template UI stack: shadcn/ui components and @tabler/icons-react. Do not add lucide-react or another icon library for standard UI.`,\n `Ensure the React Router client entry preserves APP_BASE_PATH/VITE_APP_BASE_PATH via appBasePath().`,\n keyList\n ? `After the app exists, grant the selected Dispatch vault keys to appId \"${input.appId}\" and sync them once the app server is available. Treat these as requested grants, not active grants before creation succeeds.`\n : `Do not grant any Dispatch vault keys unless the user asks later.`,\n input.selectedResources.length\n ? `After the app exists, grant the selected Dispatch workspace resources to appId \"${input.appId}\" and sync them once the app server is available. Add a short note to apps/${input.appId}/AGENTS.md telling the app agent to read relevant shared resources under context/ or the selected resource paths before doing GTM/domain work.`\n : `Do not grant any Dispatch workspace resources unless the user asks later.`,\n ``,\n `App readiness requirements before handing off:`,\n `- Ensure apps/${input.appId}/package.json exists with displayName/name metadata so Dispatch and the workspace gateway discover it from the filesystem. There is no separate workspace app registry to edit.`,\n `- Update the app manifest/package/deploy metadata needed by the existing workspace deployment model; do not leave the app relying only on local discovery.`,\n `- Verify the app's agent card/A2A metadata is ready so Dispatch can discover and delegate to the app after deployment.`,\n `- Include a final verification note covering filesystem discovery, manifest/deploy metadata, relative same-origin routing, and agent-card readiness.`,\n `When it is ready, start or update the workspace dev server and navigate the user to /${input.appId}.`,\n ].join(\"\\n\");\n}\n\nexport function NewWorkspaceAppFlow({\n sourceApp = \"starter\",\n className = \"\",\n dispatchBasePath,\n}: NewWorkspaceAppFlowProps) {\n const [selectedSecretIds, setSelectedSecretIds] = useState<string[]>([]);\n const [selectedResourceIds, setSelectedResourceIds] = useState<string[]>([]);\n const [secrets, setSecrets] = useState<VaultSecretOption[]>([]);\n const [resources, setResources] = useState<WorkspaceResourceOption[]>([]);\n const [secretsError, setSecretsError] = useState<string | null>(null);\n const [resourcesError, setResourcesError] = useState<string | null>(null);\n const [statusMessage, setStatusMessage] = useState<string | null>(null);\n const [branchUrl, setBranchUrl] = useState<string | null>(null);\n const [isSubmitting, setIsSubmitting] = useState(false);\n const { isDevMode } = useDevMode();\n\n const effectiveDispatchBasePath =\n dispatchBasePath === undefined\n ? defaultDispatchBasePath(sourceApp)\n : dispatchBasePath;\n\n useEffect(() => {\n let cancelled = false;\n const secretsUrl = actionUrl(\n effectiveDispatchBasePath,\n \"list-vault-secret-options\",\n );\n const resourcesUrl = actionUrl(\n effectiveDispatchBasePath,\n \"list-workspace-resource-options\",\n );\n\n fetchJson(secretsUrl)\n .then((data) => {\n if (cancelled) return;\n setSecrets(Array.isArray(data) ? data : []);\n setSecretsError(null);\n })\n .catch((err) => {\n if (cancelled) return;\n setSecrets([]);\n setSecretsError(err?.message || \"Could not load Dispatch keys\");\n });\n\n fetchJson(resourcesUrl)\n .then((data) => {\n if (cancelled) return;\n setResources(Array.isArray(data) ? data : []);\n setResourcesError(null);\n })\n .catch((err) => {\n if (cancelled) return;\n setResources([]);\n setResourcesError(err?.message || \"Could not load Dispatch resources\");\n });\n\n return () => {\n cancelled = true;\n };\n }, [effectiveDispatchBasePath]);\n\n const selectedSecrets = useMemo(\n () => secrets.filter((secret) => selectedSecretIds.includes(secret.id)),\n [secrets, selectedSecretIds],\n );\n const selectedResources = useMemo(\n () =>\n resources.filter((resource) => selectedResourceIds.includes(resource.id)),\n [resources, selectedResourceIds],\n );\n const selectedSecretLabel =\n selectedSecretIds.length === 0\n ? \"No keys selected\"\n : `${selectedSecretIds.length} key${selectedSecretIds.length === 1 ? \"\" : \"s\"} selected`;\n const selectedResourceLabel =\n selectedResourceIds.length === 0\n ? \"No resources selected\"\n : `${selectedResourceIds.length} resource${selectedResourceIds.length === 1 ? \"\" : \"s\"} selected`;\n\n async function submit(rawPrompt: string) {\n const prompt = rawPrompt.trim();\n if (!prompt || isSubmitting) return;\n const appId = titleFromPrompt(prompt);\n const validationError = getWorkspaceAppIdValidationError(appId);\n if (validationError) {\n setStatusMessage(validationError);\n return;\n }\n\n const message = buildNewWorkspaceAppPrompt({\n appId,\n prompt,\n selectedKeys: selectedSecrets.map((s) => s.credentialKey),\n selectedResources,\n });\n setIsSubmitting(true);\n setStatusMessage(null);\n setBranchUrl(null);\n\n try {\n if (isInBuilderFrame()) {\n sendToAgentChat({ message, submit: true, type: \"code\" });\n setStatusMessage(\"Sent to Builder chat.\");\n } else if (isDevMode) {\n sendToAgentChat({ message, submit: true, type: \"code\", newTab: true });\n setStatusMessage(\"Sent to the local agent.\");\n } else {\n const result = await fetchJson(\n actionUrl(effectiveDispatchBasePath, \"start-workspace-app-creation\"),\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n prompt,\n appId,\n secretIds: selectedSecretIds,\n resourceIds: selectedResourceIds,\n }),\n },\n );\n if (result?.mode === \"builder\") {\n setBranchUrl(result?.url || null);\n setStatusMessage(\"Builder branch created.\");\n } else {\n setStatusMessage(\n result?.message ||\n \"Builder app creation is coming soon here. Open this workspace in Builder to create an app from this prompt.\",\n );\n }\n }\n } catch (err: any) {\n setStatusMessage(err?.message || \"Could not start the new app flow.\");\n } finally {\n setIsSubmitting(false);\n }\n }\n\n function toggleSecret(id: string) {\n setSelectedSecretIds((current) =>\n current.includes(id)\n ? current.filter((existing) => existing !== id)\n : [...current, id],\n );\n }\n\n function toggleResource(id: string) {\n setSelectedResourceIds((current) =>\n current.includes(id)\n ? current.filter((existing) => existing !== id)\n : [...current, id],\n );\n }\n\n return (\n <section\n className={`mx-auto flex w-full max-w-5xl flex-col gap-5 px-4 py-6 ${className}`}\n >\n <div className=\"grid gap-5 lg:grid-cols-[minmax(0,1fr)_320px]\">\n <div className=\"flex flex-col gap-3\">\n <PromptComposer\n autoFocus\n disabled={isSubmitting}\n placeholder=\"Describe the app your teammate should be able to use...\"\n draftScope=\"dispatch:new-app\"\n onSubmit={(text) => submit(text)}\n />\n\n {statusMessage ? (\n <div className=\"rounded-md border border-border bg-muted/40 px-3 py-2 text-sm text-muted-foreground\">\n {statusMessage}\n {branchUrl ? (\n <a\n href={branchUrl}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"ml-2 inline-flex items-center gap-1 font-medium text-foreground underline\"\n >\n Open branch <IconArrowUpRight className=\"h-3 w-3\" />\n </a>\n ) : null}\n </div>\n ) : null}\n </div>\n\n <aside className=\"overflow-hidden rounded-lg border border-border bg-card\">\n <div className=\"border-b border-border px-4 py-3\">\n <div className=\"flex items-center justify-between gap-3\">\n <div className=\"flex items-center gap-2 text-sm font-medium\">\n <IconKey className=\"h-4 w-4\" />\n Dispatch keys\n </div>\n <span className=\"shrink-0 rounded border border-border bg-background/40 px-2 py-0.5 text-[11px] text-muted-foreground\">\n {selectedSecretLabel}\n </span>\n </div>\n </div>\n <div className=\"max-h-[220px] space-y-2 overflow-y-auto p-3\">\n {secretsError ? (\n <p className=\"rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground\">\n {secretsError}\n </p>\n ) : secrets.length === 0 ? (\n <p className=\"rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground\">\n No Dispatch vault keys found yet.\n </p>\n ) : (\n secrets.map((secret) => {\n const selected = selectedSecretIds.includes(secret.id);\n return (\n <div\n key={secret.id}\n className={`group rounded-md border text-sm transition ${\n selected\n ? \"border-primary/45 bg-primary/5 text-foreground shadow-[inset_0_0_0_1px_hsl(var(--primary)/0.08)]\"\n : \"border-border bg-background/25 text-foreground hover:border-muted-foreground/40 hover:bg-accent/35\"\n }`}\n >\n <button\n type=\"button\"\n aria-pressed={selected}\n onClick={() => toggleSecret(secret.id)}\n className=\"flex w-full cursor-pointer items-start gap-3 rounded-md px-3 py-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30\"\n >\n <span\n className={`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border transition ${\n selected\n ? \"border-primary/60 bg-primary/10 text-primary\"\n : \"border-muted-foreground/35 text-transparent group-hover:border-muted-foreground/60\"\n }`}\n >\n {selected ? <IconCheck className=\"h-3 w-3\" /> : null}\n </span>\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate font-medium\">\n {secret.credentialKey}\n </span>\n <span className=\"block truncate text-xs text-muted-foreground/70\">\n {selected\n ? \"Will be requested for this app\"\n : \"Click to request\"}\n </span>\n </span>\n </button>\n <details className=\"group/details border-t border-border/60 px-3 py-1.5 text-xs text-muted-foreground/75 open:bg-background/10\">\n <summary className=\"flex cursor-pointer list-none items-center gap-1.5 text-[11px] hover:text-muted-foreground [&::-webkit-details-marker]:hidden\">\n <IconChevronDown className=\"h-3 w-3 transition-transform group-open/details:rotate-180\" />\n Details\n </summary>\n <div className=\"mt-1.5 space-y-1 pb-0.5 pl-4\">\n <div className=\"truncate\">\n Provider: {secret.provider || \"Not specified\"}\n </div>\n <div className=\"truncate\">Name: {secret.name}</div>\n </div>\n </details>\n </div>\n );\n })\n )}\n </div>\n\n <div className=\"border-y border-border px-4 py-3\">\n <div className=\"flex items-center justify-between gap-3\">\n <div className=\"flex items-center gap-2 text-sm font-medium\">\n <IconBook className=\"h-4 w-4\" />\n Resource packs\n </div>\n <span className=\"shrink-0 rounded border border-border bg-background/40 px-2 py-0.5 text-[11px] text-muted-foreground\">\n {selectedResourceLabel}\n </span>\n </div>\n </div>\n <div className=\"max-h-[220px] space-y-2 overflow-y-auto p-3\">\n {resourcesError ? (\n <p className=\"rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground\">\n {resourcesError}\n </p>\n ) : resources.length === 0 ? (\n <p className=\"rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground\">\n No Dispatch resource packs found yet.\n </p>\n ) : (\n resources.map((resource) => {\n const selected = selectedResourceIds.includes(resource.id);\n return (\n <div\n key={resource.id}\n className={`group rounded-md border text-sm transition ${\n selected\n ? \"border-primary/45 bg-primary/5 text-foreground shadow-[inset_0_0_0_1px_hsl(var(--primary)/0.08)]\"\n : \"border-border bg-background/25 text-foreground hover:border-muted-foreground/40 hover:bg-accent/35\"\n }`}\n >\n <button\n type=\"button\"\n aria-pressed={selected}\n onClick={() => toggleResource(resource.id)}\n className=\"flex w-full cursor-pointer items-start gap-3 rounded-md px-3 py-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30\"\n >\n <span\n className={`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border transition ${\n selected\n ? \"border-primary/60 bg-primary/10 text-primary\"\n : \"border-muted-foreground/35 text-transparent group-hover:border-muted-foreground/60\"\n }`}\n >\n {selected ? <IconCheck className=\"h-3 w-3\" /> : null}\n </span>\n <span className=\"min-w-0 flex-1\">\n <span className=\"flex min-w-0 items-center gap-1.5\">\n <IconFileText className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground/70\" />\n <span className=\"block truncate font-medium\">\n {resource.name}\n </span>\n </span>\n <span className=\"block truncate text-xs text-muted-foreground/70\">\n {resource.kind} · {resource.path}\n </span>\n </span>\n </button>\n <details className=\"group/details border-t border-border/60 px-3 py-1.5 text-xs text-muted-foreground/75 open:bg-background/10\">\n <summary className=\"flex cursor-pointer list-none items-center gap-1.5 text-[11px] hover:text-muted-foreground [&::-webkit-details-marker]:hidden\">\n <IconChevronDown className=\"h-3 w-3 transition-transform group-open/details:rotate-180\" />\n Details\n </summary>\n <div className=\"mt-1.5 space-y-1 pb-0.5 pl-4\">\n <div className=\"truncate\">\n Scope:{\" \"}\n {resource.scope === \"all\"\n ? \"All apps\"\n : \"Selected apps\"}\n </div>\n {resource.description ? (\n <div className=\"line-clamp-2\">\n {resource.description}\n </div>\n ) : null}\n </div>\n </details>\n </div>\n );\n })\n )}\n </div>\n </aside>\n </div>\n </section>\n );\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SettingsPanel.d.ts","sourceRoot":"","sources":["../../../src/client/settings/SettingsPanel.tsx"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"SettingsPanel.d.ts","sourceRoot":"","sources":["../../../src/client/settings/SettingsPanel.tsx"],"names":[],"mappings":"AA2+CA,MAAM,WAAW,kBAAkB;IACjC,SAAS,EAAE,OAAO,CAAC;IACnB,eAAe,EAAE,MAAM,IAAI,CAAC;IAC5B,aAAa,EAAE,OAAO,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAoHD,wBAAgB,aAAa,CAAC,EAC5B,SAAS,EACT,eAAe,EACf,aAAa,EACb,SAAS,GACV,EAAE,kBAAkB,2CAuUpB"}
|