@myrialabs/clopen 0.4.39 → 0.4.41

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.
Files changed (173) hide show
  1. package/.env.example +1 -1
  2. package/backend/artifacts/detect.ts +15 -3
  3. package/backend/artifacts/generate.ts +2 -2
  4. package/backend/artifacts/index.ts +12 -4
  5. package/backend/artifacts/markers.ts +24 -1
  6. package/backend/artifacts/matrix.ts +47 -3
  7. package/backend/artifacts/sync.test.ts +3 -3
  8. package/backend/artifacts/sync.ts +8 -20
  9. package/backend/artifacts/types.ts +9 -3
  10. package/backend/auth/permissions.ts +29 -11
  11. package/backend/auth/session-cleanup.ts +10 -1
  12. package/backend/auth/tokens.ts +9 -1
  13. package/backend/chat/stream-manager.ts +42 -0
  14. package/backend/database/crypto/secret-columns.ts +5 -1
  15. package/backend/database/migrations/078_create_worktree_branch_tables.ts +158 -0
  16. package/backend/database/migrations/079_merge_commands_into_skills.ts +222 -0
  17. package/backend/database/migrations/080_create_file_shares.ts +111 -0
  18. package/backend/database/migrations/081_create_push_subscriptions.ts +32 -0
  19. package/backend/database/migrations/index.ts +28 -0
  20. package/backend/database/queries/file-share-queries.ts +163 -0
  21. package/backend/database/queries/index.ts +12 -4
  22. package/backend/database/queries/profile-queries.ts +5 -3
  23. package/backend/database/queries/push-subscription-queries.test.ts +90 -0
  24. package/backend/database/queries/push-subscription-queries.ts +99 -0
  25. package/backend/database/queries/skill-queries.ts +96 -18
  26. package/backend/database/queries/worktree-branch-queries.ts +331 -0
  27. package/backend/db-client/cloning.test.ts +161 -0
  28. package/backend/db-client/cloning.ts +672 -0
  29. package/backend/db-client/connection-url.test.ts +117 -0
  30. package/backend/db-client/connection-url.ts +126 -0
  31. package/backend/db-client/drivers/mongodb.ts +2 -14
  32. package/backend/db-client/drivers/mysql.ts +2 -8
  33. package/backend/db-client/drivers/postgres.ts +10 -13
  34. package/backend/db-client/drivers/redis.ts +2 -6
  35. package/backend/db-client/env/detect.ts +438 -0
  36. package/backend/db-client/env/diff.ts +94 -0
  37. package/backend/db-client/env/env.test.ts +574 -0
  38. package/backend/db-client/env/index.ts +15 -0
  39. package/backend/db-client/env/naming.ts +202 -0
  40. package/backend/db-client/env/service.ts +487 -0
  41. package/backend/db-client/integrations/index.ts +7 -0
  42. package/backend/db-client/integrations/links.ts +41 -10
  43. package/backend/db-client/providers/neon/adapter.ts +522 -0
  44. package/backend/db-client/providers/neon/api-types.ts +182 -0
  45. package/backend/db-client/providers/neon/client.ts +298 -0
  46. package/backend/db-client/providers/neon/endpoints.test.ts +201 -0
  47. package/backend/db-client/providers/neon/endpoints.ts +314 -0
  48. package/backend/db-client/providers/neon/list.test.ts +181 -0
  49. package/backend/db-client/providers/supabase/adapter.ts +25 -2
  50. package/backend/db-client/providers/types.ts +57 -0
  51. package/backend/engine/adapters/claude/stream.ts +2 -1
  52. package/backend/engine/adapters/cline/stream.ts +3 -3
  53. package/backend/engine/adapters/codex/stream.ts +3 -3
  54. package/backend/engine/adapters/copilot/stream.ts +3 -3
  55. package/backend/engine/adapters/cursor/stream.ts +25 -3
  56. package/backend/engine/adapters/opencode/stream.ts +4 -6
  57. package/backend/engine/adapters/pi/stream.ts +2 -2
  58. package/backend/engine/adapters/qwen/stream.ts +2 -2
  59. package/backend/engine/artifact-sync.ts +26 -20
  60. package/backend/engine/docs/artifacts.md +81 -22
  61. package/backend/engine/docs/quick-reference.md +2 -1
  62. package/backend/engine/resolve-model.test.ts +108 -0
  63. package/backend/engine/resolve-model.ts +53 -10
  64. package/backend/engine/structured-helpers.ts +22 -0
  65. package/backend/env-files/discovery.ts +48 -0
  66. package/backend/env-files/edit.ts +213 -0
  67. package/backend/env-files/env-files.test.ts +515 -0
  68. package/backend/env-files/git.ts +27 -0
  69. package/backend/env-files/index.ts +44 -0
  70. package/backend/env-files/keys.ts +69 -0
  71. package/backend/env-files/parse.ts +157 -0
  72. package/backend/env-files/write.ts +229 -0
  73. package/backend/files/file-shares.ts +369 -0
  74. package/backend/files/path-browsing.ts +27 -21
  75. package/backend/http/files-shared.test.ts +505 -0
  76. package/backend/http/files-shared.ts +351 -0
  77. package/backend/http/push.ts +150 -0
  78. package/backend/index.ts +8 -0
  79. package/backend/instructions/index.ts +1 -1
  80. package/backend/instructions/sync.ts +30 -6
  81. package/backend/integrations/health.ts +18 -4
  82. package/backend/integrations/projections/types.ts +9 -2
  83. package/backend/integrations/registry/index.ts +3 -0
  84. package/backend/integrations/registry/providers/context7.ts +1 -0
  85. package/backend/integrations/registry/providers/firecrawl.ts +1 -0
  86. package/backend/integrations/registry/providers/github.ts +1 -0
  87. package/backend/integrations/registry/providers/neon.ts +55 -0
  88. package/backend/integrations/registry/providers/supabase.ts +1 -0
  89. package/backend/integrations/registry/providers/vercel.ts +1 -0
  90. package/backend/integrations/registry/types.ts +2 -0
  91. package/backend/memory/compose.ts +2 -2
  92. package/backend/memory/consolidate.ts +2 -2
  93. package/backend/memory/extract/episodic.ts +2 -2
  94. package/backend/memory/judge.ts +2 -2
  95. package/backend/profiles/service.ts +7 -6
  96. package/backend/push/sender.ts +172 -0
  97. package/backend/push/tags.ts +25 -0
  98. package/backend/push/vapid-keys.ts +77 -0
  99. package/backend/push/webpush-crypto.test.ts +200 -0
  100. package/backend/push/webpush-crypto.ts +231 -0
  101. package/backend/skills/detect.ts +28 -0
  102. package/backend/skills/index.ts +22 -4
  103. package/backend/skills/invoke.test.ts +114 -0
  104. package/backend/skills/invoke.ts +222 -0
  105. package/backend/skills/service.ts +194 -44
  106. package/backend/skills/spec.ts +35 -0
  107. package/backend/skills/sync.ts +85 -55
  108. package/backend/subagents/detect.ts +2 -3
  109. package/backend/subagents/sync.ts +15 -8
  110. package/backend/work/pull-requests.ts +2 -2
  111. package/backend/work/start-work.ts +4 -0
  112. package/backend/worktrees/branching/engine.ts +557 -0
  113. package/backend/worktrees/branching/index.ts +56 -0
  114. package/backend/worktrees/branching/naming.test.ts +118 -0
  115. package/backend/worktrees/branching/naming.ts +97 -0
  116. package/backend/worktrees/branching/projector.test.ts +229 -0
  117. package/backend/worktrees/branching/projector.ts +139 -0
  118. package/backend/worktrees/branching/providers/neon.ts +220 -0
  119. package/backend/worktrees/branching/registry.ts +27 -0
  120. package/backend/worktrees/branching/service.ts +620 -0
  121. package/backend/worktrees/branching/suggest.test.ts +154 -0
  122. package/backend/worktrees/branching/suggest.ts +202 -0
  123. package/backend/worktrees/branching/types.ts +88 -0
  124. package/backend/worktrees/index.ts +7 -0
  125. package/backend/worktrees/service.ts +48 -1
  126. package/backend/ws/chat/stream.ts +100 -8
  127. package/backend/ws/db-client/env.ts +142 -0
  128. package/backend/ws/db-client/index.ts +2 -0
  129. package/backend/ws/files/index.ts +4 -0
  130. package/backend/ws/files/share.ts +95 -0
  131. package/backend/ws/git/branch-name.ts +2 -2
  132. package/backend/ws/git/commit-message.ts +2 -2
  133. package/backend/ws/index.ts +3 -4
  134. package/backend/ws/profiles/crud.ts +2 -3
  135. package/backend/ws/projects/index.ts +6 -1
  136. package/backend/ws/projects/info.ts +70 -6
  137. package/backend/ws/projects/overview.test.ts +108 -0
  138. package/backend/ws/projects/overview.ts +300 -0
  139. package/backend/ws/skills/catalog.ts +5 -1
  140. package/backend/ws/skills/crud.ts +128 -22
  141. package/backend/ws/skills/index.ts +4 -1
  142. package/backend/ws/system/device-info.ts +307 -76
  143. package/backend/ws/user/crud.ts +12 -3
  144. package/backend/ws/worktrees/branching.ts +212 -0
  145. package/backend/ws/worktrees/crud.ts +33 -7
  146. package/backend/ws/worktrees/index.ts +14 -0
  147. package/dist/assets/{index-C8Gi-b6U.js → index-CeNKKSDR.js} +1 -1
  148. package/dist/assets/{index-BrF6nqld.js → index-DW89566K.js} +1 -1
  149. package/dist/assets/main-Cy5DXWPT.js +1207 -0
  150. package/dist/assets/main-DJKj_4By.css +1 -0
  151. package/dist/index.html +7 -2
  152. package/dist/sw.js +112 -0
  153. package/package.json +1 -1
  154. package/shared/constants/engine-tools.ts +31 -6
  155. package/shared/constants/notification-messages.ts +142 -0
  156. package/shared/constants/tool-icons.ts +6 -2
  157. package/shared/types/db-client/env.ts +192 -0
  158. package/shared/types/db-client/index.ts +1 -0
  159. package/shared/types/db-client/integrations.ts +30 -0
  160. package/shared/types/integrations.ts +9 -0
  161. package/shared/types/unified/stream.ts +7 -0
  162. package/shared/types/worktree-branching.ts +315 -0
  163. package/shared/utils/logger.ts +1 -0
  164. package/backend/commands/detect.ts +0 -25
  165. package/backend/commands/index.ts +0 -9
  166. package/backend/commands/service.ts +0 -178
  167. package/backend/commands/store.ts +0 -45
  168. package/backend/commands/sync.ts +0 -94
  169. package/backend/database/queries/command-queries.ts +0 -82
  170. package/backend/ws/commands/crud.ts +0 -157
  171. package/backend/ws/commands/index.ts +0 -8
  172. package/dist/assets/main-Bd3gb79F.css +0 -1
  173. package/dist/assets/main-Bo1hD7mt.js +0 -1191
@@ -24,7 +24,9 @@ import { collectProcessTree, getHostFacts, getProcessTable } from '../../host/me
24
24
  const MAX_ENTRIES = 300_000;
25
25
  /** Wall-clock ceiling — the backstop for slow disks and network mounts. */
26
26
  const WALK_DEADLINE_MS = 15_000;
27
- /** How many `stat` calls are in flight at once while walking one directory. */
27
+ /** How many `stat` calls are in flight at once while walking one directory.
28
+ * Multiplied by the number of concurrent walks, so `MAX_BACKGROUND_WALKS`
29
+ * bounds the descriptor fan-out on platforms with a low `ulimit -n`. */
28
30
  const STAT_BATCH = 64;
29
31
  /** A folder's size changes slowly; a poll should not re-walk it every tick. */
30
32
  const STORAGE_CACHE_TTL_MS = 15_000;
@@ -37,7 +39,7 @@ const PORTS_CACHE_TTL_MS = 5_000;
37
39
 
38
40
  // ── Storage ──────────────────────────────────────────────────────────────────
39
41
 
40
- interface FolderStats {
42
+ export interface FolderStats {
41
43
  sizeBytes: number;
42
44
  fileCount: number;
43
45
  dirCount: number;
@@ -49,7 +51,9 @@ const storageCache = new Map<string, { stats: FolderStats; at: number; ttl: numb
49
51
  const storageInFlight = new Map<string, Promise<FolderStats>>();
50
52
 
51
53
  /** Cached and single-flighted: a big walk outlives the poll interval, so a
52
- * result-only cache would let every tick start another one. */
54
+ * result-only cache would let every tick start another one. Callers that
55
+ * cannot afford the wait go through `peekFolderStats()` below, which shares
56
+ * this cache and this in-flight guard. */
53
57
  function getFolderStats(root: string): Promise<FolderStats> {
54
58
  const cached = storageCache.get(root);
55
59
  if (cached && Date.now() - cached.at < cached.ttl) {
@@ -83,6 +87,61 @@ function getFolderStats(root: string): Promise<FolderStats> {
83
87
  return walk;
84
88
  }
85
89
 
90
+ /** Walk slots for callers that ask about every project at once.
91
+ *
92
+ * One walk already keeps `STAT_BATCH` `stat` calls in flight; fanning out
93
+ * unbounded multiplies that by the project count, which is how a 20-project
94
+ * install reaches thousands of open descriptors — past the 256 soft limit
95
+ * macOS hands a GUI-launched process. */
96
+ const MAX_BACKGROUND_WALKS = 4;
97
+ let runningBackgroundWalks = 0;
98
+ const queuedWalks: string[] = [];
99
+ const queuedWalkPaths = new Set<string>();
100
+
101
+ function pumpBackgroundWalks(): void {
102
+ while (runningBackgroundWalks < MAX_BACKGROUND_WALKS && queuedWalks.length > 0) {
103
+ const root = queuedWalks.shift() as string;
104
+ queuedWalkPaths.delete(root);
105
+ runningBackgroundWalks++;
106
+ // `getFolderStats` turns walk failures into error stats, so a rejection
107
+ // here is a programming fault, not a slow disk — swallow it and free
108
+ // the slot either way.
109
+ void getFolderStats(root)
110
+ .catch((error) => {
111
+ debug.warn('project', 'background folder walk failed:', error);
112
+ })
113
+ .finally(() => {
114
+ runningBackgroundWalks--;
115
+ pumpBackgroundWalks();
116
+ });
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Last known stats for a folder, never a wait.
122
+ *
123
+ * `getFolderStats` blocks for the whole walk on a cold cache, which is right
124
+ * for `projects:info` (one folder, one modal) and wrong for `projects:overview`
125
+ * (every folder, polled). The overview would hold its request open for the full
126
+ * walk deadline on first open — exactly the long skeleton this panel exists to
127
+ * avoid. Instead, callers get the previous answer immediately (`null` before
128
+ * the first walk ever finished) and a refresh is queued behind a bounded pool.
129
+ */
130
+ export function peekFolderStats(root: string): FolderStats | null {
131
+ const cached = storageCache.get(root);
132
+ if (cached && Date.now() - cached.at < cached.ttl) return cached.stats;
133
+
134
+ if (!storageInFlight.has(root) && !queuedWalkPaths.has(root)) {
135
+ queuedWalkPaths.add(root);
136
+ queuedWalks.push(root);
137
+ pumpBackgroundWalks();
138
+ }
139
+
140
+ // Stale beats empty: the size a project had a minute ago is still the right
141
+ // order of magnitude, and the next poll replaces it.
142
+ return cached?.stats ?? null;
143
+ }
144
+
86
145
  async function walkFolder(root: string): Promise<FolderStats> {
87
146
  try {
88
147
  const rootStat = await stat(root);
@@ -149,7 +208,7 @@ async function walkFolder(root: string): Promise<FolderStats> {
149
208
 
150
209
  // ── Per-project slice of the host process table ──────────────────────────────
151
210
 
152
- interface ProjectProcess {
211
+ export interface ProjectProcess {
153
212
  pid: number;
154
213
  parentPid: number;
155
214
  name: string;
@@ -158,7 +217,7 @@ interface ProjectProcess {
158
217
  command: string;
159
218
  }
160
219
 
161
- interface ProcessStats {
220
+ export interface ProcessStats {
162
221
  status: 'running' | 'not_running';
163
222
  cpuPercent: number | null;
164
223
  memRssBytes: number | null;
@@ -178,7 +237,12 @@ const IDLE: ProcessStats = {
178
237
  rootPids: []
179
238
  };
180
239
 
181
- async function getProjectProcessStats(projectId: string, totalMemBytes: number): Promise<ProcessStats> {
240
+ /**
241
+ * Exported for reuse by `projects:overview` so per-project CPU/RAM there is
242
+ * measured exactly the way `projects:info` measures it — same roots, same
243
+ * shared process table, same capacity basis. No behavior change for callers.
244
+ */
245
+ export async function getProjectProcessStats(projectId: string, totalMemBytes: number): Promise<ProcessStats> {
182
246
  const rootPids = projectShellPids(projectId);
183
247
 
184
248
  // No shells means nothing is running, so zero is the truth here.
@@ -0,0 +1,108 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import {
3
+ sortByFootprint,
4
+ summarizeStorage,
5
+ type ProjectResourceEntry,
6
+ type ProjectStorage,
7
+ type StorageState
8
+ } from './overview';
9
+
10
+ function storage(state: StorageState, sizeBytes = 0, opts?: { files?: number; dirs?: number; truncated?: boolean; error?: string }): ProjectStorage {
11
+ return {
12
+ state,
13
+ sizeBytes,
14
+ fileCount: opts?.files ?? 0,
15
+ dirCount: opts?.dirs ?? 0,
16
+ truncated: opts?.truncated ?? false,
17
+ error: opts?.error ?? null
18
+ };
19
+ }
20
+
21
+ function entry(
22
+ id: string,
23
+ storageValue: ProjectStorage,
24
+ opts?: { status?: 'running' | 'idle'; lastOpened?: string; cpuPercent?: number | null }
25
+ ): ProjectResourceEntry {
26
+ return {
27
+ id,
28
+ name: id,
29
+ path: `/tmp/${id}`,
30
+ created_at: '2026-01-01T00:00:00.000Z',
31
+ last_opened_at: opts?.lastOpened ?? '2026-02-01T00:00:00.000Z',
32
+ status: opts?.status ?? 'idle',
33
+ cpuPercent: opts?.cpuPercent ?? 0,
34
+ memRssBytes: 0,
35
+ memPercent: 0,
36
+ storage: storageValue
37
+ };
38
+ }
39
+
40
+ describe('summarizeStorage', () => {
41
+ it('sums measured entries and counts the rest by state', () => {
42
+ const totals = summarizeStorage([
43
+ entry('a', storage('ready', 100, { files: 5, dirs: 1 })),
44
+ entry('b', storage('ready', 200, { files: 7, dirs: 3 })),
45
+ entry('busy', storage('ready', 500, { files: 50, dirs: 9 }), { status: 'running' }),
46
+ entry('cold', storage('measuring')),
47
+ entry('gone', storage('unavailable', 0, { error: 'ENOENT: no such file or directory' }))
48
+ ]);
49
+ expect(totals).toEqual({
50
+ measuredCount: 3,
51
+ measuringCount: 1,
52
+ unavailableCount: 1,
53
+ totalStorageBytes: 800,
54
+ totalFiles: 62,
55
+ totalDirs: 13
56
+ });
57
+ });
58
+
59
+ it('keeps a pending walk out of the totals instead of reading it as 0 B', () => {
60
+ expect(summarizeStorage([entry('cold', storage('measuring'))])).toEqual({
61
+ measuredCount: 0,
62
+ measuringCount: 1,
63
+ unavailableCount: 0,
64
+ totalStorageBytes: 0,
65
+ totalFiles: 0,
66
+ totalDirs: 0
67
+ });
68
+ });
69
+ });
70
+
71
+ describe('sortByFootprint', () => {
72
+ it('ranks by sizeBytes DESC across statuses', () => {
73
+ const sorted = sortByFootprint([
74
+ entry('s', storage('ready', 10)),
75
+ entry('xl', storage('ready', 200)),
76
+ entry('xxl', storage('ready', 500)),
77
+ entry('biggest', storage('ready', 900), { status: 'running', cpuPercent: 12.5 }),
78
+ entry('tiny', storage('ready', 1))
79
+ ]);
80
+ expect(sorted.map((e) => e.id)).toEqual(['biggest', 'xxl', 'xl', 's', 'tiny']);
81
+ expect(sorted[0].status).toBe('running');
82
+ });
83
+
84
+ it('lists measured projects first, then measuring, then unavailable', () => {
85
+ const sorted = sortByFootprint([
86
+ entry('gone', storage('unavailable', 0, { error: 'ENOENT' })),
87
+ entry('cold', storage('measuring')),
88
+ entry('partial', storage('ready', 400, { truncated: true })),
89
+ entry('full', storage('ready', 300))
90
+ ]);
91
+ expect(sorted.map((e) => e.id)).toEqual(['partial', 'full', 'cold', 'gone']);
92
+ expect(sorted[0].storage.truncated).toBe(true);
93
+ });
94
+
95
+ it('breaks size ties by oldest last_opened_at first', () => {
96
+ const sorted = sortByFootprint([
97
+ entry('newer', storage('ready', 100), { lastOpened: '2026-03-01T00:00:00.000Z' }),
98
+ entry('older', storage('ready', 100), { lastOpened: '2026-01-15T00:00:00.000Z' })
99
+ ]);
100
+ expect(sorted.map((e) => e.id)).toEqual(['older', 'newer']);
101
+ });
102
+
103
+ it('does not mutate the caller array', () => {
104
+ const entries = [entry('a', storage('ready', 1)), entry('b', storage('ready', 2))];
105
+ sortByFootprint(entries);
106
+ expect(entries.map((e) => e.id)).toEqual(['a', 'b']);
107
+ });
108
+ });
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Projects Overview — per-project resource usage for every project at once.
3
+ *
4
+ * Settings -> Device already describes the machine; this is the same question
5
+ * asked per project, so an admin can see where the machine's CPU, RAM and disk
6
+ * actually went without opening Project Info once per project.
7
+ *
8
+ * Separate from `system:device-info` (host hardware) and from `projects:info`
9
+ * (one project's storage, live CPU/RAM, process list and ports). The figures
10
+ * come from the same two sources `projects:info` reads — `peekFolderStats()`
11
+ * and `getProjectProcessStats()` in `./info` — so the panel and the modal
12
+ * cannot disagree about one project.
13
+ *
14
+ * Definitions (same as Project Info):
15
+ * - idle = `projectShellPids(projectId).length === 0` (no active PTY shell)
16
+ * - running = at least one active shell
17
+ *
18
+ * Access: scoped to the caller. Admins see every project, everyone else sees
19
+ * only the projects they are assigned to — the same rule `projects:info`
20
+ * enforces per project through `requireProjectAccess`.
21
+ *
22
+ * Cost control:
23
+ * - no port scan and no per-process list here, only the summed CPU/RAM
24
+ * - storage is read from cache and never awaited: a cold folder reports
25
+ * `measuring` and fills in on a later poll, so this handler's latency is
26
+ * the process-table probe, not a filesystem walk
27
+ * - one snapshot per scope is cached for `OVERVIEW_CACHE_TTL_MS` and
28
+ * single-flighted, and the process table underneath has its own 2s cache,
29
+ * so a fast poll costs at most one probe every couple of seconds
30
+ */
31
+
32
+ import { t } from 'elysia';
33
+ import { createRouter } from '$shared/utils/ws-server';
34
+ import { ws } from '$backend/utils/ws';
35
+ import { projectQueries } from '../../database/queries';
36
+ import { projectShellPids } from '../../projects/shell-ownership';
37
+ import { getHostFacts } from '../../host/metrics';
38
+ import { getProjectProcessStats, peekFolderStats } from './info';
39
+ import type { Project } from '$shared/types/database/schema';
40
+
41
+ export type ProjectResourceStatus = 'running' | 'idle';
42
+
43
+ /**
44
+ * `ready` — the folder was walked and the numbers below are its answer.
45
+ * `measuring` — no walk has finished yet; the numbers are zero, not a total.
46
+ * `unavailable` — the folder moved, was deleted, or cannot be read.
47
+ */
48
+ export type StorageState = 'ready' | 'measuring' | 'unavailable';
49
+
50
+ export interface ProjectStorage {
51
+ state: StorageState;
52
+ sizeBytes: number;
53
+ fileCount: number;
54
+ dirCount: number;
55
+ /** The walk hit its entry ceiling or deadline, so the size is a floor. */
56
+ truncated: boolean;
57
+ error: string | null;
58
+ }
59
+
60
+ export interface ProjectResourceEntry {
61
+ id: string;
62
+ name: string;
63
+ path: string;
64
+ created_at: string;
65
+ last_opened_at: string;
66
+ status: ProjectResourceStatus;
67
+ cpuPercent: number | null;
68
+ memRssBytes: number | null;
69
+ memPercent: number | null;
70
+ storage: ProjectStorage;
71
+ }
72
+
73
+ export interface ProjectsOverview {
74
+ totalProjects: number;
75
+ runningCount: number;
76
+ idleCount: number;
77
+ measuredCount: number;
78
+ measuringCount: number;
79
+ unavailableCount: number;
80
+ /** Summed over `ready` entries only, so a pending walk never reads as 0 B. */
81
+ totalStorageBytes: number;
82
+ totalFiles: number;
83
+ totalDirs: number;
84
+ projects: ProjectResourceEntry[];
85
+ generatedAt: string;
86
+ }
87
+
88
+ const MEASURING: ProjectStorage = {
89
+ state: 'measuring',
90
+ sizeBytes: 0,
91
+ fileCount: 0,
92
+ dirCount: 0,
93
+ truncated: false,
94
+ error: null
95
+ };
96
+
97
+ /** Sum folder stats over entries whose walk actually produced an answer. */
98
+ export function summarizeStorage(entries: Array<{ storage: ProjectStorage }>): {
99
+ measuredCount: number;
100
+ measuringCount: number;
101
+ unavailableCount: number;
102
+ totalStorageBytes: number;
103
+ totalFiles: number;
104
+ totalDirs: number;
105
+ } {
106
+ let measuredCount = 0;
107
+ let measuringCount = 0;
108
+ let unavailableCount = 0;
109
+ let totalStorageBytes = 0;
110
+ let totalFiles = 0;
111
+ let totalDirs = 0;
112
+
113
+ for (const entry of entries) {
114
+ if (entry.storage.state === 'measuring') {
115
+ measuringCount++;
116
+ continue;
117
+ }
118
+ if (entry.storage.state === 'unavailable') {
119
+ unavailableCount++;
120
+ continue;
121
+ }
122
+ measuredCount++;
123
+ totalStorageBytes += entry.storage.sizeBytes;
124
+ totalFiles += entry.storage.fileCount;
125
+ totalDirs += entry.storage.dirCount;
126
+ }
127
+
128
+ return { measuredCount, measuringCount, unavailableCount, totalStorageBytes, totalFiles, totalDirs };
129
+ }
130
+
131
+ /** Rank order for the panel: biggest first, then the ones still being measured,
132
+ * then the folders that cannot be read. Equal sizes fall back to the project
133
+ * left untouched longest, which is the one worth looking at first. */
134
+ const STATE_RANK: Record<StorageState, number> = { ready: 0, measuring: 1, unavailable: 2 };
135
+
136
+ export function sortByFootprint<T extends ProjectResourceEntry>(entries: T[]): T[] {
137
+ return entries.slice().sort((a, b) => {
138
+ if (STATE_RANK[a.storage.state] !== STATE_RANK[b.storage.state]) {
139
+ return STATE_RANK[a.storage.state] - STATE_RANK[b.storage.state];
140
+ }
141
+ if (b.storage.sizeBytes !== a.storage.sizeBytes) {
142
+ return b.storage.sizeBytes - a.storage.sizeBytes;
143
+ }
144
+ return a.last_opened_at.localeCompare(b.last_opened_at);
145
+ });
146
+ }
147
+
148
+ function readStorage(path: string): ProjectStorage {
149
+ const stats = peekFolderStats(path);
150
+ if (!stats) return MEASURING;
151
+ if (stats.error) {
152
+ return {
153
+ state: 'unavailable',
154
+ sizeBytes: 0,
155
+ fileCount: 0,
156
+ dirCount: 0,
157
+ truncated: false,
158
+ error: stats.error
159
+ };
160
+ }
161
+ return {
162
+ state: 'ready',
163
+ sizeBytes: stats.sizeBytes,
164
+ fileCount: stats.fileCount,
165
+ dirCount: stats.dirCount,
166
+ truncated: stats.truncated,
167
+ error: null
168
+ };
169
+ }
170
+
171
+ async function buildOverview(projects: Project[]): Promise<ProjectsOverview> {
172
+ const idleIds = new Set<string>();
173
+ for (const project of projects) {
174
+ if (projectShellPids(project.id).length === 0) idleIds.add(project.id);
175
+ }
176
+
177
+ // Probed once per process, so only the first caller pays.
178
+ const facts = await getHostFacts();
179
+
180
+ // Idle means no shell to attribute usage to, so the process table is never
181
+ // consulted for it — on an install where most projects sit idle this is the
182
+ // difference between one probe and none.
183
+ const resources = await Promise.all(
184
+ projects.map((project) =>
185
+ idleIds.has(project.id)
186
+ ? Promise.resolve({ cpuPercent: 0, memRssBytes: 0, memPercent: 0 })
187
+ : getProjectProcessStats(project.id, facts.totalMemBytes).then((stats) => ({
188
+ cpuPercent: stats.cpuPercent,
189
+ memRssBytes: stats.memRssBytes,
190
+ memPercent: stats.memPercent
191
+ }))
192
+ )
193
+ );
194
+
195
+ const entries: ProjectResourceEntry[] = projects.map((project, i) => ({
196
+ id: project.id,
197
+ name: project.name,
198
+ path: project.path,
199
+ created_at: project.created_at,
200
+ last_opened_at: project.last_opened_at,
201
+ status: idleIds.has(project.id) ? 'idle' : 'running',
202
+ cpuPercent: resources[i].cpuPercent,
203
+ memRssBytes: resources[i].memRssBytes,
204
+ memPercent: resources[i].memPercent,
205
+ storage: readStorage(project.path)
206
+ }));
207
+
208
+ const totals = summarizeStorage(entries);
209
+
210
+ return {
211
+ totalProjects: projects.length,
212
+ runningCount: projects.length - idleIds.size,
213
+ idleCount: idleIds.size,
214
+ ...totals,
215
+ projects: sortByFootprint(entries),
216
+ generatedAt: new Date().toISOString()
217
+ };
218
+ }
219
+
220
+ /** One snapshot per access scope. Kept below the frontend heartbeat so a poll
221
+ * is never answered with the payload it already has, while burst opens and
222
+ * rapid tab switches still collapse onto a single build. */
223
+ const OVERVIEW_CACHE_TTL_MS = 1_500;
224
+ const cachedOverviews = new Map<string, { payload: ProjectsOverview; at: number }>();
225
+ const inFlightOverviews = new Map<string, Promise<ProjectsOverview>>();
226
+
227
+ function getOverview(scope: string, projects: Project[]): Promise<ProjectsOverview> {
228
+ const cached = cachedOverviews.get(scope);
229
+ if (cached && Date.now() - cached.at < OVERVIEW_CACHE_TTL_MS) {
230
+ return Promise.resolve(cached.payload);
231
+ }
232
+
233
+ const inFlight = inFlightOverviews.get(scope);
234
+ if (inFlight) return inFlight;
235
+
236
+ const build = buildOverview(projects).then((payload) => {
237
+ cachedOverviews.set(scope, { payload, at: Date.now() });
238
+ inFlightOverviews.delete(scope);
239
+ return payload;
240
+ });
241
+ // A failed build must not pin the single-flight slot: storage failures are
242
+ // already folded into `unavailable`, so a rejection here is unexpected
243
+ // (e.g. the process table is unreadable) and the next poll should retry.
244
+ build.catch(() => {
245
+ inFlightOverviews.delete(scope);
246
+ });
247
+ inFlightOverviews.set(scope, build);
248
+ return build;
249
+ }
250
+
251
+ const nullableNumber = t.Union([t.Number(), t.Null()]);
252
+
253
+ const ProjectEntrySchema = t.Object({
254
+ id: t.String(),
255
+ name: t.String(),
256
+ path: t.String(),
257
+ created_at: t.String(),
258
+ last_opened_at: t.String(),
259
+ status: t.Union([t.Literal('running'), t.Literal('idle')]),
260
+ cpuPercent: nullableNumber,
261
+ memRssBytes: nullableNumber,
262
+ memPercent: nullableNumber,
263
+ storage: t.Object({
264
+ state: t.Union([t.Literal('ready'), t.Literal('measuring'), t.Literal('unavailable')]),
265
+ sizeBytes: t.Number(),
266
+ fileCount: t.Number(),
267
+ dirCount: t.Number(),
268
+ truncated: t.Boolean(),
269
+ error: t.Union([t.String(), t.Null()])
270
+ })
271
+ });
272
+
273
+ export const overviewHandler = createRouter().http(
274
+ 'projects:overview',
275
+ {
276
+ data: t.Object({}),
277
+ response: t.Object({
278
+ totalProjects: t.Number(),
279
+ runningCount: t.Number(),
280
+ idleCount: t.Number(),
281
+ measuredCount: t.Number(),
282
+ measuringCount: t.Number(),
283
+ unavailableCount: t.Number(),
284
+ totalStorageBytes: t.Number(),
285
+ totalFiles: t.Number(),
286
+ totalDirs: t.Number(),
287
+ projects: t.Array(ProjectEntrySchema),
288
+ generatedAt: t.String()
289
+ })
290
+ },
291
+ async ({ conn }) => {
292
+ // A project's name and absolute path are not public: every other
293
+ // project-scoped handler goes through `requireProjectAccess`, and a
294
+ // list endpoint has to apply the same rule to the whole list.
295
+ const userId = ws.getUserId(conn);
296
+ const isAdmin = ws.getRole(conn) === 'admin';
297
+ const projects = isAdmin ? projectQueries.getAll() : projectQueries.getAllForUser(userId);
298
+ return getOverview(isAdmin ? 'admin' : `user:${userId}`, projects);
299
+ }
300
+ );
@@ -10,7 +10,7 @@
10
10
  import { t } from 'elysia';
11
11
  import { createRouter } from '$shared/utils/ws-server';
12
12
  import { debug } from '$shared/utils/logger';
13
- import { listMarketplaceSkills, skillService } from '$backend/skills';
13
+ import { listMarketplaceSkills, skillService, syncSkillsAllEngines } from '$backend/skills';
14
14
 
15
15
  const MARKETPLACE_SKILL_SCHEMA = t.Object({
16
16
  ref: t.String(),
@@ -31,6 +31,9 @@ const SKILL_SCHEMA = t.Object({
31
31
  marketplaceRef: t.Union([t.String(), t.Null()]),
32
32
  version: t.Union([t.String(), t.Null()]),
33
33
  license: t.Union([t.String(), t.Null()]),
34
+ triggers: t.Array(t.Union([t.Literal('auto'), t.Literal('slash')])),
35
+ argumentHint: t.Union([t.String(), t.Null()]),
36
+ uses: t.Array(t.String()),
34
37
  enabled: t.Boolean(),
35
38
  present: t.Boolean(),
36
39
  createdAt: t.String()
@@ -75,5 +78,6 @@ export const skillCatalogHandler = createRouter()
75
78
  debug.log('path', `skills:install ${data.ref}`);
76
79
  const { ref, ...override } = data;
77
80
  const skill = await skillService.install(ref, override);
81
+ await syncSkillsAllEngines();
78
82
  return { skill };
79
83
  });