@stacksjs/buddy 0.75.643 → 0.75.648

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.
@@ -0,0 +1,744 @@
1
+ // @bun
2
+ // src/tray/run.ts
3
+ import { randomUUID } from "crypto";
4
+ import { accessSync, constants, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs";
5
+ import { join } from "path";
6
+ import process from "process";
7
+ import { daemonStatus, openProjectDashboard, startDaemon } from "@stacksjs/actions/daemon/client";
8
+ import { daemonDir } from "@stacksjs/actions/daemon/paths";
9
+ import { acquireMigrationLock } from "@stacksjs/database/migration-lock";
10
+ import { craftDevCommand, resolveCraftExecutable } from "@stacksjs/desktop-build";
11
+ import { isCompiledBinary, listProjects, projectCliEntry } from "@stacksjs/path";
12
+ import { generateCss, renderTemplateString } from "@stacksjs/stx";
13
+
14
+ // src/tray/api.ts
15
+ import { Buffer } from "buffer";
16
+ import { timingSafeEqual } from "crypto";
17
+ function traySnapshot(status, projects) {
18
+ const approvals = new Map(status?.generation?.approvals?.map(({ path, files }) => [path, files]));
19
+ const failures = new Map(status?.generation?.failures?.map(({ path, error }) => [path, error]));
20
+ return {
21
+ online: status !== null,
22
+ watched: status?.generation?.watched ?? 0,
23
+ running: status?.generation?.running != null,
24
+ failed: failures.size,
25
+ projects: projects.map(({ id, name, path }) => ({
26
+ id,
27
+ name,
28
+ path,
29
+ pending: approvals.get(path) ?? 0,
30
+ issue: failures.get(path) ?? ""
31
+ }))
32
+ };
33
+ }
34
+ function createTrayApi(token, services, documentOrigin) {
35
+ const authorization = Buffer.from(`Bearer ${token}`);
36
+ const json = (body, status = 200) => Response.json(body, {
37
+ status,
38
+ headers: {
39
+ "Cache-Control": "no-store",
40
+ "X-Content-Type-Options": "nosniff",
41
+ "Access-Control-Allow-Origin": documentOrigin
42
+ }
43
+ });
44
+ return async (request, origin) => {
45
+ const requestOrigin = request.headers.get("origin");
46
+ const path = new URL(request.url).pathname;
47
+ if (requestOrigin === documentOrigin && request.method === "OPTIONS" && path.startsWith("/api/")) {
48
+ return new Response(null, { status: 204, headers: {
49
+ "Access-Control-Allow-Origin": documentOrigin,
50
+ "Access-Control-Allow-Methods": "GET, POST",
51
+ "Access-Control-Allow-Headers": "authorization, content-type",
52
+ "Access-Control-Max-Age": "600"
53
+ } });
54
+ }
55
+ const supplied = Buffer.from(request.headers.get("authorization") ?? "");
56
+ if (requestOrigin !== null && requestOrigin !== origin && requestOrigin !== documentOrigin || supplied.length !== authorization.length || !timingSafeEqual(supplied, authorization))
57
+ return json({ error: "This request did not come from the Buddy menu bar." }, 403);
58
+ const url = new URL(request.url);
59
+ try {
60
+ if (request.method === "GET") {
61
+ if (path === "/api/status") {
62
+ const [status, system] = await Promise.all([services.status(), services.system()]);
63
+ return json({ ...traySnapshot(status, services.projects()), system });
64
+ }
65
+ if (path === "/api/pantry")
66
+ return json(await services.pantry.status());
67
+ if (path === "/api/pantry/jobs")
68
+ return json(await services.pantry.jobs());
69
+ if (path === "/api/pantry/catalog") {
70
+ const query = url.searchParams.get("q")?.trim() ?? "";
71
+ return json(query.length >= 2 && query.length <= 100 ? services.pantry.catalog(query) : []);
72
+ }
73
+ }
74
+ if (path !== "/api/action" || request.method !== "POST")
75
+ return json({ error: "Unknown Buddy tray endpoint." }, 404);
76
+ if (request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() !== "application/json")
77
+ return json({ error: "Send a JSON request." }, 415);
78
+ const input = await request.json().catch(() => null);
79
+ if (input?.action === "start") {
80
+ await services.start();
81
+ } else if (input?.action === "quit") {
82
+ services.quit();
83
+ } else if (input?.action === "pantry:pair") {
84
+ if (typeof input.code !== "string" || !/^\d{8}$/.test(input.code))
85
+ return json({ error: "Enter Pantry\u2019s eight-digit pairing code." }, 400);
86
+ await services.pantry.pair(input.code);
87
+ } else if (input?.action === "pantry:disconnect") {
88
+ await services.pantry.disconnect();
89
+ } else if (input?.action === "pantry:install" || input?.action === "pantry:uninstall") {
90
+ if (typeof input.domain !== "string" || !/^[a-z0-9][a-z0-9._/-]{0,199}$/i.test(input.domain) || typeof input.requestId !== "string" || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(input.requestId))
91
+ return json({ error: "Select a Pantry package and try again." }, 400);
92
+ const operation = input.action === "pantry:install" ? "install" : "uninstall";
93
+ return json(await services.pantry.change(operation, input.domain, input.requestId), 202);
94
+ } else if (input?.action === "dashboard" || input?.action === "review") {
95
+ const project = services.projects().find(({ id }) => id === input.project);
96
+ if (!project)
97
+ return json({ error: "This project is no longer registered with Buddy." }, 404);
98
+ if (input.action === "review") {
99
+ const pending = (await services.status())?.generation?.approvals;
100
+ if (!pending?.some((approval) => approval.path === project.path && approval.files > 0))
101
+ return json({ error: "This project has no changes awaiting review." }, 409);
102
+ await services.review(project);
103
+ } else {
104
+ await services.dashboard(project);
105
+ }
106
+ } else {
107
+ return json({ error: "Unknown Buddy tray action." }, 400);
108
+ }
109
+ return json({ ok: true });
110
+ } catch (error) {
111
+ return json({ error: error instanceof Error ? error.message : "Buddy could not complete this action." }, 500);
112
+ }
113
+ };
114
+ }
115
+
116
+ // src/tray/pantry.ts
117
+ var {secrets } = globalThis.Bun;
118
+ import { bundledPackageCatalog, createPackageCatalogSearch } from "ts-pantry/catalog";
119
+ import { PantryDesktopClient, PantryDesktopError } from "ts-pantry/desktop";
120
+ var credential = { service: "com.stacksjs.buddy.tray", name: "Pantry Desktop" };
121
+ function createTrayPantry() {
122
+ let connection;
123
+ let search;
124
+ const client = (token) => new PantryDesktopClient({
125
+ token,
126
+ fetch: (url, init) => fetch(url, { ...init, redirect: "error", signal: AbortSignal.timeout(4000) })
127
+ });
128
+ const readToken = () => connection ??= secrets.get(credential).catch((error) => {
129
+ connection = undefined;
130
+ throw error;
131
+ });
132
+ async function connected() {
133
+ const token = await readToken();
134
+ if (!token)
135
+ throw new PantryDesktopError("Pair Pantry with Buddy first.", 401);
136
+ return client(token);
137
+ }
138
+ async function jobs(bridge) {
139
+ const records = await bridge.jobs();
140
+ return records.map(({ id, domain, status, operation, error }) => ({ id, domain, status, operation, error }));
141
+ }
142
+ return {
143
+ async status() {
144
+ try {
145
+ const health = await client().health();
146
+ const capabilities = Array.isArray(health.capabilities) ? health.capabilities : [];
147
+ if (!await readToken())
148
+ return { state: "pair" };
149
+ const bridge = await connected();
150
+ const [packages, recentJobs] = await Promise.all([bridge.installed(), jobs(bridge)]);
151
+ return { state: "ready", packages, jobs: recentJobs, removal: capabilities.includes("uninstall:user") };
152
+ } catch (error) {
153
+ if (error instanceof PantryDesktopError && error.status === 401)
154
+ return { state: "pair" };
155
+ return { state: "offline", issue: error instanceof Error ? error.message : "Pantry is unavailable." };
156
+ }
157
+ },
158
+ catalog(query) {
159
+ search ??= createPackageCatalogSearch(bundledPackageCatalog());
160
+ return search(query, { limit: 8 }).map(({ domain, name }) => ({ domain, name }));
161
+ },
162
+ async jobs() {
163
+ return jobs(await connected());
164
+ },
165
+ async pair(code) {
166
+ const bridge = client();
167
+ const token = await bridge.pair(code, "Buddy");
168
+ try {
169
+ await secrets.set({ ...credential, value: token });
170
+ connection = Promise.resolve(token);
171
+ } catch (error) {
172
+ await client(token).disconnect().catch(() => {});
173
+ throw error;
174
+ }
175
+ },
176
+ async change(operation, domain, requestId) {
177
+ const bridge = await connected();
178
+ const job = await (operation === "install" ? bridge.install(domain, requestId) : bridge.uninstall(domain, requestId));
179
+ return { id: job.id, domain: job.domain, status: job.status, operation: job.operation, error: job.error };
180
+ },
181
+ async disconnect() {
182
+ const bridge = await connected();
183
+ await bridge.disconnect();
184
+ connection = Promise.resolve(null);
185
+ await secrets.delete(credential);
186
+ }
187
+ };
188
+ }
189
+
190
+ // src/tray/system.ts
191
+ import { cpus, freemem, totalmem } from "os";
192
+ function createCpuSampler(read = cpus) {
193
+ const totals = () => read().reduce(({ idle, total }, { times }) => ({
194
+ idle: idle + times.idle,
195
+ total: total + times.user + times.nice + times.sys + times.idle + times.irq
196
+ }), { idle: 0, total: 0 });
197
+ let previous = totals();
198
+ let percent = null;
199
+ return () => {
200
+ const next = totals();
201
+ const elapsed = next.total - previous.total;
202
+ const idle = next.idle - previous.idle;
203
+ previous = next;
204
+ if (elapsed > 0)
205
+ percent = Math.round(100 * Math.max(0, Math.min(1, (elapsed - idle) / elapsed)));
206
+ return percent;
207
+ };
208
+ }
209
+ function activeMemoryBytes(stats) {
210
+ const pageSize = Number(stats.match(/page size of (\d+) bytes/)?.[1]);
211
+ const active = Number(stats.match(/^Pages active:\s+(\d+)/m)?.[1]);
212
+ const wired = Number(stats.match(/^Pages wired down:\s+(\d+)/m)?.[1]);
213
+ const compressed = Number(stats.match(/^Pages occupied by compressor:\s+(\d+)/m)?.[1]);
214
+ const bytes = pageSize * (active + wired + compressed);
215
+ return Number.isSafeInteger(bytes) && bytes >= 0 ? bytes : undefined;
216
+ }
217
+ function createSystemSampler() {
218
+ const sampleCpu = createCpuSampler();
219
+ return async () => {
220
+ const cpu = sampleCpu();
221
+ const total = totalmem();
222
+ const command = Bun.spawn(["/usr/bin/vm_stat"], { stderr: "ignore", stdout: "pipe", timeout: 1500 });
223
+ const [code, stats] = await Promise.all([command.exited, new Response(command.stdout).text()]);
224
+ const active = code === 0 ? activeMemoryBytes(stats) : undefined;
225
+ const used = Math.max(0, Math.min(total, active ?? total - freemem()));
226
+ return { cpu, memory: { used, total, raw: active === undefined } };
227
+ };
228
+ }
229
+
230
+ // src/tray/view.stx
231
+ var view_default = `<script client>
232
+ type Project = { id: string, name: string, path: string, pending: number, issue: string }
233
+ type Snapshot = { online: boolean, watched: number, running: boolean, failed: number, projects: Project[], system: { cpu: number | null, memory: { used: number, total: number, raw: boolean } } }
234
+ type Package = { name: string, version: string, managed?: boolean }
235
+ type CatalogMatch = { name: string, domain: string }
236
+ type PantryJob = { id: string, domain: string, operation?: string, status: string, error?: string }
237
+ type PantryStatus = { state: 'offline' | 'pair' | 'ready', issue?: string, packages?: Package[], jobs?: PantryJob[], removal?: boolean }
238
+
239
+ const snapshot = state<Snapshot | null>(null)
240
+ const filter = state('')
241
+ const busy = state('')
242
+ const notice = state('')
243
+ const unavailable = state(false)
244
+ const pane = state<'overview' | 'pantry'>('overview')
245
+ const pantry = state<PantryStatus | null>(null)
246
+ const pairingCode = state('')
247
+ const packageSearch = state('')
248
+ const searched = state(false)
249
+ const matches = state<CatalogMatch[]>([])
250
+ const packageJobs = state<PantryJob[]>([])
251
+ const removal = state('')
252
+ const system = derived(() => snapshot()?.system)
253
+ const installed = derived(() => {
254
+ const query = packageSearch().trim().toLowerCase()
255
+ return (pantry()?.packages ?? []).filter(item => item.name.toLowerCase().includes(query)).slice(0, 10)
256
+ })
257
+ const jobInProgress = derived(() => packageJobs().some(job => job.status === 'queued' || job.status === 'running'))
258
+ const pending = derived(() => snapshot()?.projects.filter(project => project.pending > 0) ?? [])
259
+ const recent = derived(() => {
260
+ const search = filter().trim().toLowerCase()
261
+ const projects = snapshot()?.projects ?? []
262
+ return search
263
+ ? projects.filter(project => project.name.toLowerCase().includes(search) || project.path.toLowerCase().includes(search))
264
+ : projects.slice(0, 6)
265
+ })
266
+ const launch = globalThis.buddyTray
267
+ const desktop = globalThis.craft
268
+ let refreshing = false
269
+
270
+ async function call(path: string, body?: object) {
271
+ const response = await fetch(launch ? new URL(path, launch.origin) : path, {
272
+ method: body ? 'POST' : 'GET',
273
+ headers: { authorization: \`Bearer \${launch?.token ?? ''}\`, ...(body ? { 'content-type': 'application/json' } : {}) },
274
+ body: body && JSON.stringify(body),
275
+ })
276
+ const result = await response.json()
277
+ if (!response.ok) throw new Error(result.error)
278
+ return result
279
+ }
280
+
281
+ async function refreshStatus() {
282
+ if (refreshing) return
283
+ refreshing = true
284
+ try {
285
+ snapshot.set(await call('/api/status'))
286
+ unavailable.set(false)
287
+ }
288
+ catch {
289
+ unavailable.set(true)
290
+ }
291
+ finally {
292
+ refreshing = false
293
+ }
294
+ }
295
+
296
+ function gib(bytes: number) {
297
+ return new Intl.NumberFormat(undefined, { maximumFractionDigits: 1 }).format(bytes / 1024 ** 3)
298
+ }
299
+
300
+ async function refreshPantry() {
301
+ try {
302
+ const status: PantryStatus = await call('/api/pantry')
303
+ pantry.set(status)
304
+ packageJobs.set(status.jobs ?? [])
305
+ }
306
+ catch (error) {
307
+ pantry.set({ state: 'offline', issue: error.message })
308
+ }
309
+ }
310
+
311
+ async function refreshActivePane() {
312
+ if (pane() === 'overview') return refreshStatus()
313
+ if (!jobInProgress()) return
314
+ try {
315
+ const jobs: PantryJob[] = await call('/api/pantry/jobs')
316
+ packageJobs.set(jobs)
317
+ if (!jobInProgress()) await refreshPantry()
318
+ }
319
+ catch (error) {
320
+ notice.set(error.message)
321
+ }
322
+ }
323
+
324
+ function openPane(next: 'overview' | 'pantry') {
325
+ pane.set(next)
326
+ notice.set('')
327
+ removal.set('')
328
+ void (next === 'overview' ? refreshStatus() : refreshPantry())
329
+ }
330
+
331
+ async function pantryAction(fields: object) {
332
+ if (busy()) return
333
+ busy.set('pantry')
334
+ notice.set('')
335
+ try {
336
+ await call('/api/action', fields)
337
+ pairingCode.set('')
338
+ removal.set('')
339
+ await refreshPantry()
340
+ }
341
+ catch (error) {
342
+ notice.set(error.message)
343
+ }
344
+ finally {
345
+ busy.set('')
346
+ }
347
+ }
348
+
349
+ function changePackage(action: string, domain: string) {
350
+ if (packageChanging(domain)) return
351
+ return pantryAction({ action, domain, requestId: crypto.randomUUID() })
352
+ }
353
+
354
+ function packageChanging(domain: string) {
355
+ return packageJobs().some(job => job.domain === domain && (job.status === 'queued' || job.status === 'running'))
356
+ }
357
+
358
+ async function searchCatalog() {
359
+ const query = packageSearch().trim()
360
+ if (query.length < 2) return
361
+ try {
362
+ const packages = await call(\`/api/pantry/catalog?q=\${encodeURIComponent(query)}\`)
363
+ if (query === packageSearch().trim()) {
364
+ matches.set(packages)
365
+ searched.set(true)
366
+ }
367
+ }
368
+ catch (error) {
369
+ notice.set(error.message)
370
+ }
371
+ }
372
+
373
+ async function perform(action: string, project?: string) {
374
+ if (busy()) return
375
+ busy.set(project || action)
376
+ notice.set('')
377
+ try {
378
+ await call('/api/action', { action, project })
379
+ if (action === 'review') notice.set('Review opened in Terminal.')
380
+ await refreshStatus()
381
+ }
382
+ catch (error) {
383
+ notice.set(error instanceof Error ? error.message : 'Buddy could not complete this action.')
384
+ }
385
+ finally {
386
+ busy.set('')
387
+ }
388
+ }
389
+
390
+ const { pause, resume } = useInterval(() => void refreshActivePane(), 5_000, { immediate: !desktop, whileVisible: true })
391
+ const stopFocus = useEventListener(desktop ? 'craft:window:focus' : 'focus', () => {
392
+ resume()
393
+ void (pane() === 'overview' ? refreshStatus() : refreshPantry())
394
+ })
395
+ const stopBlur = useEventListener('craft:window:blur', pause)
396
+ const stopKeys = useEventListener('keydown', (event) => {
397
+ if (event.key === 'Escape') void Promise.resolve(desktop?.window?.hide?.()).catch(() => {})
398
+ })
399
+ onMount(() => {
400
+ if (desktop) pause()
401
+ void refreshStatus()
402
+ const tray = desktop?.tray
403
+ void Promise.resolve(tray?.setTooltip?.('Buddy')).catch(() => {})
404
+ void Promise.resolve(tray?.setIcon?.('terminal.fill')).catch(() => {})
405
+ })
406
+ onDestroy(() => {
407
+ pause()
408
+ stopFocus()
409
+ stopBlur()
410
+ stopKeys()
411
+ })
412
+ </script>
413
+
414
+ <style>
415
+ :root {
416
+ color-scheme: light dark;
417
+ font-family: -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
418
+ --ink: light-dark(#1e2026, #f1f0f5);
419
+ --secondary: light-dark(#555965, #aaaab5);
420
+ --surface: light-dark(#ffffffc2, #25252bd4);
421
+ --line: light-dark(#15172519, #ffffff20);
422
+ --accent: light-dark(#164bc3, #b3c9ff);
423
+ --accent-surface: light-dark(#e4ecff, #253759);
424
+ }
425
+ html, body { margin: 0; min-height: 100%; background: transparent; color: var(--ink); }
426
+ body { font-size: 13px; }
427
+ button, input { font: inherit; }
428
+ button { color: inherit; cursor: pointer; }
429
+ button:disabled { cursor: default; opacity: .65; }
430
+ button:focus-visible, input:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
431
+ h1, h2, p { margin: 0; }
432
+ .tray { height: 100dvh; }
433
+ .secondary { color: var(--secondary); }
434
+ .line { border-color: var(--line); }
435
+ .surface { background: var(--surface); }
436
+ .accent { color: var(--accent); background: var(--accent-surface); }
437
+ .plain { border: 0; background: transparent; }
438
+ .plain:hover { background: var(--line); }
439
+ .status-dot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }
440
+ .online { color: light-dark(#207442, #8bdfa9); }
441
+ .issue { color: light-dark(#875115, #f0bd83); }
442
+ .search { color: inherit; }
443
+ .tab { border: 0; }
444
+ .meter { display: block; appearance: none; width: 100%; height: 4px; border: 0; overflow: hidden; border-radius: 8px; }
445
+ .meter::-webkit-progress-bar { background: var(--accent-surface); }
446
+ .meter::-webkit-progress-value { background: var(--accent); border-radius: 8px; }
447
+ .meter::-moz-progress-bar { background: var(--accent); border-radius: 8px; }
448
+ </style>
449
+
450
+ <main class="flex flex-col tray">
451
+ <header class="flex gap-3 items-center justify-between shrink-0 px-4 py-3 border-b line">
452
+ <div class="flex gap-3 items-center">
453
+ <span class="flex items-center justify-center h-9 w-9 font-bold font-mono accent rounded-xl" aria-hidden="true">\u203A_</span>
454
+ <div>
455
+ <h1 class="font-semibold leading-tight text-base">Buddy</h1>
456
+ <p class="flex gap-1.5 items-center text-xs secondary">
457
+ @if(unavailable())
458
+ <span>Connection unavailable</span>
459
+ @elseif(snapshot()?.online)
460
+ <span class="online status-dot" aria-hidden="true"></span>
461
+ <span>{{ snapshot()?.running ? 'Generating' : 'Daemon running' }} \xB7 {{ snapshot()?.watched }} watched</span>
462
+ @elseif(snapshot())
463
+ <span class="status-dot" aria-hidden="true"></span>
464
+ <span>Daemon stopped</span>
465
+ @else
466
+ <span>Connecting\u2026</span>
467
+ @endif
468
+ </p>
469
+ </div>
470
+ </div>
471
+ <button class="px-2 py-1 text-xs rounded-lg plain secondary" type="button" @click="pane() === 'overview' ? refreshStatus() : refreshPantry()">Refresh</button>
472
+ </header>
473
+ <nav aria-label="Buddy views" class="flex gap-2 px-4 py-2 border-b line">
474
+ <button type="button" class="px-3 py-1 font-medium text-xs rounded-md tab" :class="pane() === 'overview' ? 'accent' : 'plain secondary'" :aria-pressed="pane() === 'overview'" @click="openPane('overview')">Overview</button>
475
+ <button type="button" class="px-3 py-1 font-medium text-xs rounded-md tab" :class="pane() === 'pantry' ? 'accent' : 'plain secondary'" :aria-pressed="pane() === 'pantry'" @click="openPane('pantry')">Pantry</button>
476
+ </nav>
477
+
478
+ <div class="overflow-y-auto flex-1 px-4 py-3 min-h-0">
479
+ @if(pane() === 'pantry')
480
+ @if(!pantry())
481
+ <p role="status" class="secondary">Connecting to Pantry\u2026</p>
482
+ @elseif(pantry()?.state === 'offline')
483
+ <h2 class="mb-2 font-semibold text-sm">Pantry is unavailable</h2>
484
+ <p class="mb-2 secondary">{{ pantry()?.issue }}</p>
485
+ <p>Start Pantry Desktop in Terminal with <code>pantry desktop setup --yes</code>, then refresh.</p>
486
+ @elseif(pantry()?.state === 'pair')
487
+ <h2 class="mb-2 font-semibold text-sm">Connect Pantry</h2>
488
+ <p class="mb-2 secondary">Run <code>pantry desktop pair</code> in Terminal and enter the eight-digit code.</p>
489
+ <form class="flex gap-2" @submit.prevent="pantryAction({ action: 'pantry:pair', code: pairingCode() })">
490
+ <input class="flex-1 px-2 py-1 min-w-0 border rounded-lg line search surface" aria-label="Pairing code" inputmode="numeric" maxlength="8" :value="pairingCode()" @input="pairingCode.set($event.target.value)" />
491
+ <button class="px-3 py-1 font-medium accent rounded-md tab" :disabled="pairingCode().length !== 8 || busy() !== ''">Pair</button>
492
+ </form>
493
+ @else
494
+ <form class="flex gap-2 mb-3" @submit.prevent="searchCatalog()">
495
+ <input class="flex-1 px-2 py-1 min-w-0 border rounded-lg line search surface" type="search" aria-label="Find a Pantry package" placeholder="Find a package" :value="packageSearch()" @input="packageSearch.set($event.target.value); matches.set([]); searched.set(false)" />
496
+ <button class="px-3 py-1 font-medium accent rounded-md tab" :disabled="packageSearch().trim().length < 2">Find</button>
497
+ </form>
498
+ @if(searched())
499
+ <h2 class="mb-2 font-semibold text-sm">Catalog</h2>
500
+ @foreach(matches() as pkg)
501
+ <div class="flex gap-2 items-center justify-between px-2 py-1 border-b line">
502
+ <div class="min-w-0"><p class="truncate">{{ pkg.name }}</p><p class="text-xs truncate secondary">{{ pkg.domain }}</p></div>
503
+ <button type="button" class="shrink-0 px-2 py-1 text-xs accent rounded-md tab" :disabled="busy() !== '' || packageChanging(pkg.domain)" @click="changePackage('pantry:install', pkg.domain)">Install</button>
504
+ </div>
505
+ @endforeach
506
+ @if(!matches().length)
507
+ <p class="secondary">No catalog matches.</p>
508
+ @endif
509
+ @endif
510
+ @if(packageJobs().length)
511
+ <h2 class="mb-2 mt-3 font-semibold text-sm">Activity</h2>
512
+ @foreach(packageJobs().slice(0, 3) as job)
513
+ <p class="flex gap-2 justify-between text-xs secondary" :title="job.error || ''"><span class="truncate">{{ job.domain }}</span><span>{{ job.status }}</span></p>
514
+ @endforeach
515
+ @endif
516
+ <h2 class="mb-2 mt-3 font-semibold text-sm">Installed</h2>
517
+ @foreach(installed() as pkg)
518
+ <div class="flex gap-2 items-center justify-between px-2 py-1 border-b line">
519
+ <p class="min-w-0 truncate" :title="pkg.name">{{ pkg.name }} <span class="text-xs secondary">{{ pkg.version }}</span></p>
520
+ @if(pantry()?.removal && pkg.managed)
521
+ @if(removal() === pkg.name)
522
+ <button type="button" class="shrink-0 px-2 py-1 text-xs rounded-md plain" @click="removal.set('')">Cancel</button>
523
+ <button type="button" class="shrink-0 px-2 py-1 text-xs rounded-md issue plain" :disabled="busy() !== '' || packageChanging(pkg.name)" @click="changePackage('pantry:uninstall', pkg.name)">Confirm</button>
524
+ @else
525
+ <button type="button" class="shrink-0 px-2 py-1 text-xs rounded-md plain secondary" :aria-label="'Remove ' + pkg.name" @click="removal.set(pkg.name)">Remove</button>
526
+ @endif
527
+ @endif
528
+ </div>
529
+ @endforeach
530
+ @if(!installed().length)
531
+ <p class="secondary">No installed packages match.</p>
532
+ @endif
533
+ <button type="button" class="mt-3 px-2 py-1 text-xs rounded-md plain secondary" :disabled="busy() !== ''" @click="pantryAction({ action: 'pantry:disconnect' })">Disconnect Pantry</button>
534
+ @endif
535
+ @else
536
+ @if(unavailable())
537
+ <p class="py-3 secondary" role="status">Buddy\u2019s local connection was interrupted. Refresh to reconnect.</p>
538
+ @elseif(snapshot())
539
+ @if(system())
540
+ <section aria-label="System usage" class="grid gap-2 grid-cols-2 mb-3">
541
+ <div class="p-2 border rounded-xl line surface">
542
+ <p class="flex items-center justify-between mb-1"><span class="text-xs secondary">CPU</span><strong>{{ system()?.cpu == null ? '\u2014' : system()?.cpu + '%' }}</strong></p>
543
+ <progress class="meter" aria-label="CPU utilization" max="100" :value="system()?.cpu ?? 0"></progress>
544
+ </div>
545
+ <div class="p-2 border rounded-xl line surface">
546
+ <p class="flex items-center justify-between mb-1" :title="system()?.memory.raw ? 'RAM in use, including cache' : 'Active, wired, and compressed memory'"><span class="text-xs secondary">RAM</span><strong>{{ gib(system()?.memory.used ?? 0) }} / {{ gib(system()?.memory.total ?? 0) }} GiB</strong></p>
547
+ <progress class="meter" aria-label="Memory in use" :max="system()?.memory.total" :value="system()?.memory.used"></progress>
548
+ </div>
549
+ </section>
550
+ @endif
551
+ @if(!snapshot()?.online)
552
+ <button type="button" class="mb-3 px-3 py-2 font-medium accent rounded-lg plain" :disabled="busy() !== ''" @click="perform('start')">Start daemon</button>
553
+ @endif
554
+ <section aria-labelledby="pending-heading" class="mb-4">
555
+ <div class="flex items-center justify-between mb-2">
556
+ <h2 id="pending-heading" class="font-semibold text-sm">Pending approvals</h2>
557
+ @if(pending().length)
558
+ <span class="px-2 py-0.5 font-semibold text-xs accent rounded-full">{{ pending().length }}</span>
559
+ @endif
560
+ </div>
561
+ @if(pending().length)
562
+ <ul class="m-0 p-0 list-none border divide-y rounded-xl line surface">
563
+ @foreach(pending() as project)
564
+ <li class="flex gap-3 items-center justify-between px-3 py-2">
565
+ <div class="min-w-0">
566
+ <p class="font-medium truncate" :title="project.path">{{ project.name }}</p>
567
+ <p class="text-xs secondary">{{ project.pending }} generated {{ project.pending === 1 ? 'file' : 'files' }}</p>
568
+ </div>
569
+ <button type="button" class="shrink-0 px-2.5 py-1 font-medium text-xs accent border-0 rounded-md" :disabled="busy() !== ''" @click="perform('review', project.id)">Review</button>
570
+ </li>
571
+ @endforeach
572
+ </ul>
573
+ @else
574
+ <p class="px-3 py-2.5 border rounded-xl line secondary surface">You\u2019re caught up.</p>
575
+ @endif
576
+ </section>
577
+
578
+ <section aria-labelledby="projects-heading">
579
+ <h2 id="projects-heading" class="mb-2 font-semibold text-sm">{{ filter() ? 'Matching projects' : 'Recent projects' }}</h2>
580
+ @if(snapshot()?.projects.length > 6)
581
+ <input type="search" aria-label="Find a project" placeholder="Find a project" class="mb-2 px-2.5 py-1.5 w-full border rounded-lg line search surface" :value="filter()" @input="filter.set($event.target.value)" />
582
+ @endif
583
+ @if(recent().length)
584
+ <ul class="m-0 p-0 list-none border rounded-xl line surface">
585
+ @foreach(recent() as project)
586
+ <li class="flex gap-3 items-center justify-between px-3 py-1.5 border-b last:border-b-0 line">
587
+ <div class="min-w-0">
588
+ <p class="truncate" :title="project.path">{{ project.name }}</p>
589
+ @if(project.issue)
590
+ <p class="text-xs truncate issue" :title="project.issue">{{ project.issue }}</p>
591
+ @endif
592
+ </div>
593
+ <button type="button" class="shrink-0 px-2 py-1 text-xs rounded-md plain secondary" :disabled="busy() !== ''" @click="perform('dashboard', project.id)">Dashboard \u2197</button>
594
+ </li>
595
+ @endforeach
596
+ </ul>
597
+ @else
598
+ <p class="secondary">{{ filter() ? 'No projects match your search.' : 'Run Buddy in a Stacks project to add it here.' }}</p>
599
+ @endif
600
+ </section>
601
+ @else
602
+ <p class="py-3 secondary" role="status">Loading projects\u2026</p>
603
+ @endif
604
+ @endif
605
+ </div>
606
+
607
+ <footer class="flex gap-3 items-center justify-between shrink-0 px-4 py-2 border-t line">
608
+ <p class="min-w-0 text-xs secondary" role="status">{{ notice() || (snapshot()?.failed ? snapshot()?.failed + (snapshot()?.failed === 1 ? ' generation issue' : ' generation issues') : '') }}</p>
609
+ <button type="button" class="shrink-0 px-2 py-1 text-xs rounded-md plain secondary" :disabled="busy() !== ''" @click="perform('quit')">Quit Buddy</button>
610
+ </footer>
611
+ </main>
612
+ `;
613
+
614
+ // src/tray/run.ts
615
+ function shellArgument(value) {
616
+ return `'${value.replaceAll("'", "'\\''")}'`;
617
+ }
618
+ function reviewScript(path, command) {
619
+ return `#!/bin/sh
620
+ rm -f -- "$0"
621
+ cd -- ${shellArgument(path)} || exit 1
622
+ exec ${command.map(shellArgument).join(" ")} generate:review
623
+ `;
624
+ }
625
+ function reviewCommand(project) {
626
+ const shim = join(project.path, "buddy");
627
+ try {
628
+ accessSync(shim, constants.X_OK);
629
+ return [shim];
630
+ } catch {
631
+ const entry = projectCliEntry(project.path);
632
+ if (!entry)
633
+ throw new Error("Install Stacks in this project before opening its review.");
634
+ const bun = isCompiledBinary() ? Bun.which("bun") : process.execPath;
635
+ if (!bun)
636
+ throw new Error("Install Bun before opening this project\u2019s review.");
637
+ return [bun, "--no-install", ...entry.endsWith(".ts") ? ["--conditions=development"] : [], entry];
638
+ }
639
+ }
640
+ async function openMac(...args) {
641
+ const child = Bun.spawn(["/usr/bin/open", ...args], { stdout: "ignore", stderr: "pipe" });
642
+ const [code, error] = await Promise.all([child.exited, new Response(child.stderr).text()]);
643
+ if (code !== 0)
644
+ throw new Error(error.trim() || "macOS could not open this item.");
645
+ }
646
+ async function openReview(project) {
647
+ const script = reviewScript(project.path, reviewCommand(project));
648
+ const directory = daemonDir("tray-reviews");
649
+ mkdirSync(directory, { recursive: true, mode: 448 });
650
+ const path = join(directory, `Buddy Review ${randomUUID()}.command`);
651
+ writeFileSync(path, script, { flag: "wx", mode: 448 });
652
+ try {
653
+ await openMac("-a", "Terminal", path);
654
+ } catch (error) {
655
+ rmSync(path, { force: true });
656
+ throw error;
657
+ }
658
+ }
659
+ async function renderTray() {
660
+ const path = join(import.meta.dir, "view.stx");
661
+ const [html, css] = await Promise.all([
662
+ renderTemplateString(view_default, path, { title: "Buddy", wrapInDocument: true, processClientScripts: true }),
663
+ generateCss(view_default, import.meta.dir)
664
+ ]);
665
+ return html.replace("</head>", `<style>${css}</style></head>`);
666
+ }
667
+ async function launchTray(craft) {
668
+ const document = await renderTray();
669
+ const token = randomUUID();
670
+ let child;
671
+ const quit = () => child?.kill();
672
+ const api = createTrayApi(token, {
673
+ status: daemonStatus,
674
+ projects: listProjects,
675
+ start: startDaemon,
676
+ dashboard: async ({ path }) => openMac((await openProjectDashboard(path)).url),
677
+ review: openReview,
678
+ quit: () => setTimeout(quit, 50),
679
+ system: createSystemSampler(),
680
+ pantry: createTrayPantry()
681
+ }, "http://localhost");
682
+ const server = Bun.serve({
683
+ hostname: "127.0.0.1",
684
+ port: 0,
685
+ maxRequestBodySize: 4096,
686
+ fetch(request, server) {
687
+ const url = new URL(request.url);
688
+ return url.pathname.startsWith("/api/") ? api(request, server.url.origin) : new Response("Not found", { status: 404 });
689
+ }
690
+ });
691
+ process.once("SIGINT", quit);
692
+ process.once("SIGTERM", quit);
693
+ let directory;
694
+ try {
695
+ directory = mkdtempSync(daemonDir("tray-window-"));
696
+ const htmlFile = join(directory, "index.html");
697
+ const origin = server.url.origin;
698
+ const policy = `default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval' blob:; style-src 'unsafe-inline'; img-src data:; connect-src ${origin}; base-uri 'none'; form-action 'none'`;
699
+ const launch = JSON.stringify({ origin, token });
700
+ const head = `<head><meta http-equiv="Content-Security-Policy" content="${policy}"><script>globalThis.buddyTray = ${launch}</script>`;
701
+ writeFileSync(htmlFile, document.replace("<head>", head), { flag: "wx", mode: 384 });
702
+ const command = craftDevCommand(server.port, {
703
+ craftBin: craft,
704
+ htmlFile,
705
+ title: "Buddy",
706
+ width: 376,
707
+ height: 488,
708
+ trayPopover: true,
709
+ hotReload: false,
710
+ devTools: false
711
+ });
712
+ child = Bun.spawn(command, { stdin: "ignore", stdout: "ignore", stderr: "inherit" });
713
+ const code = await child.exited;
714
+ if (code !== 0 && child.signalCode === null)
715
+ throw new Error(`Craft exited with status ${code}. Use a Craft build with --tray-popover support.`);
716
+ } finally {
717
+ process.off("SIGINT", quit);
718
+ process.off("SIGTERM", quit);
719
+ await server.stop(true);
720
+ if (directory)
721
+ rmSync(directory, { recursive: true, force: true });
722
+ }
723
+ }
724
+ async function runTray() {
725
+ if (process.platform !== "darwin")
726
+ throw new Error("Buddy\u2019s native menu-bar app requires macOS.");
727
+ const craft = resolveCraftExecutable();
728
+ mkdirSync(daemonDir(), { recursive: true, mode: 448 });
729
+ const lock = await acquireMigrationLock("sqlite", null, { sqliteLockPath: daemonDir("tray.lock"), timeoutMs: 0 }).catch((error) => {
730
+ if (error.message.includes("another migration is in progress"))
731
+ throw new Error("The Buddy menu-bar app is already running.");
732
+ throw error;
733
+ });
734
+ try {
735
+ await launchTray(craft);
736
+ } finally {
737
+ await lock.release();
738
+ }
739
+ }
740
+ export {
741
+ renderTray,
742
+ reviewScript,
743
+ runTray
744
+ };