@myrialabs/clopen 0.4.39 → 0.4.40

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 (88) hide show
  1. package/backend/auth/permissions.ts +23 -0
  2. package/backend/database/crypto/secret-columns.ts +5 -1
  3. package/backend/database/migrations/078_create_worktree_branch_tables.ts +158 -0
  4. package/backend/database/migrations/index.ts +7 -0
  5. package/backend/database/queries/index.ts +6 -0
  6. package/backend/database/queries/worktree-branch-queries.ts +331 -0
  7. package/backend/db-client/cloning.test.ts +161 -0
  8. package/backend/db-client/cloning.ts +672 -0
  9. package/backend/db-client/connection-url.test.ts +117 -0
  10. package/backend/db-client/connection-url.ts +126 -0
  11. package/backend/db-client/drivers/mongodb.ts +2 -14
  12. package/backend/db-client/drivers/mysql.ts +2 -8
  13. package/backend/db-client/drivers/postgres.ts +10 -13
  14. package/backend/db-client/drivers/redis.ts +2 -6
  15. package/backend/db-client/env/detect.ts +438 -0
  16. package/backend/db-client/env/diff.ts +94 -0
  17. package/backend/db-client/env/env.test.ts +574 -0
  18. package/backend/db-client/env/index.ts +15 -0
  19. package/backend/db-client/env/naming.ts +202 -0
  20. package/backend/db-client/env/service.ts +487 -0
  21. package/backend/db-client/integrations/index.ts +7 -0
  22. package/backend/db-client/integrations/links.ts +41 -10
  23. package/backend/db-client/providers/neon/adapter.ts +522 -0
  24. package/backend/db-client/providers/neon/api-types.ts +182 -0
  25. package/backend/db-client/providers/neon/client.ts +298 -0
  26. package/backend/db-client/providers/neon/endpoints.test.ts +201 -0
  27. package/backend/db-client/providers/neon/endpoints.ts +314 -0
  28. package/backend/db-client/providers/neon/list.test.ts +181 -0
  29. package/backend/db-client/providers/supabase/adapter.ts +25 -2
  30. package/backend/db-client/providers/types.ts +57 -0
  31. package/backend/env-files/discovery.ts +48 -0
  32. package/backend/env-files/edit.ts +213 -0
  33. package/backend/env-files/env-files.test.ts +515 -0
  34. package/backend/env-files/git.ts +27 -0
  35. package/backend/env-files/index.ts +44 -0
  36. package/backend/env-files/keys.ts +69 -0
  37. package/backend/env-files/parse.ts +157 -0
  38. package/backend/env-files/write.ts +229 -0
  39. package/backend/integrations/health.ts +18 -4
  40. package/backend/integrations/projections/types.ts +9 -2
  41. package/backend/integrations/registry/index.ts +3 -0
  42. package/backend/integrations/registry/providers/context7.ts +1 -0
  43. package/backend/integrations/registry/providers/firecrawl.ts +1 -0
  44. package/backend/integrations/registry/providers/github.ts +1 -0
  45. package/backend/integrations/registry/providers/neon.ts +55 -0
  46. package/backend/integrations/registry/providers/supabase.ts +1 -0
  47. package/backend/integrations/registry/providers/vercel.ts +1 -0
  48. package/backend/integrations/registry/types.ts +2 -0
  49. package/backend/work/start-work.ts +4 -0
  50. package/backend/worktrees/branching/engine.ts +557 -0
  51. package/backend/worktrees/branching/index.ts +56 -0
  52. package/backend/worktrees/branching/naming.test.ts +118 -0
  53. package/backend/worktrees/branching/naming.ts +97 -0
  54. package/backend/worktrees/branching/projector.test.ts +229 -0
  55. package/backend/worktrees/branching/projector.ts +139 -0
  56. package/backend/worktrees/branching/providers/neon.ts +220 -0
  57. package/backend/worktrees/branching/registry.ts +27 -0
  58. package/backend/worktrees/branching/service.ts +620 -0
  59. package/backend/worktrees/branching/suggest.test.ts +154 -0
  60. package/backend/worktrees/branching/suggest.ts +202 -0
  61. package/backend/worktrees/branching/types.ts +88 -0
  62. package/backend/worktrees/index.ts +7 -0
  63. package/backend/worktrees/service.ts +48 -1
  64. package/backend/ws/db-client/env.ts +142 -0
  65. package/backend/ws/db-client/index.ts +2 -0
  66. package/backend/ws/projects/index.ts +6 -1
  67. package/backend/ws/projects/info.ts +70 -6
  68. package/backend/ws/projects/overview.test.ts +108 -0
  69. package/backend/ws/projects/overview.ts +300 -0
  70. package/backend/ws/system/device-info.ts +307 -76
  71. package/backend/ws/worktrees/branching.ts +212 -0
  72. package/backend/ws/worktrees/crud.ts +33 -7
  73. package/backend/ws/worktrees/index.ts +14 -0
  74. package/dist/assets/{index-C8Gi-b6U.js → index-D4igjF6e.js} +1 -1
  75. package/dist/assets/{index-BrF6nqld.js → index-DONNwiXm.js} +1 -1
  76. package/dist/assets/main-BrfXH1bL.js +1205 -0
  77. package/dist/assets/main-CT1PygsW.css +1 -0
  78. package/dist/index.html +2 -2
  79. package/package.json +1 -1
  80. package/shared/constants/tool-icons.ts +6 -2
  81. package/shared/types/db-client/env.ts +192 -0
  82. package/shared/types/db-client/index.ts +1 -0
  83. package/shared/types/db-client/integrations.ts +30 -0
  84. package/shared/types/integrations.ts +9 -0
  85. package/shared/types/worktree-branching.ts +315 -0
  86. package/shared/utils/logger.ts +1 -0
  87. package/dist/assets/main-Bd3gb79F.css +0 -1
  88. package/dist/assets/main-Bo1hD7mt.js +0 -1191
@@ -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
+ );