@myrialabs/clopen 0.4.38 → 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 (177) hide show
  1. package/backend/auth/permissions.ts +48 -0
  2. package/backend/chat/stream-manager.ts +1 -1
  3. package/backend/database/crypto/secret-columns.ts +9 -1
  4. package/backend/database/migrations/075_create_deploy_bindings.ts +54 -0
  5. package/backend/database/migrations/076_remove_memory_code_graph.ts +229 -0
  6. package/backend/database/migrations/077_create_integration_db_links.ts +150 -0
  7. package/backend/database/migrations/078_create_worktree_branch_tables.ts +158 -0
  8. package/backend/database/migrations/index.ts +28 -0
  9. package/backend/database/queries/db-client-connection-queries.ts +19 -0
  10. package/backend/database/queries/deploy-queries.ts +124 -0
  11. package/backend/database/queries/graph-queries.ts +291 -247
  12. package/backend/database/queries/index.ts +10 -0
  13. package/backend/database/queries/integration-db-link-queries.ts +168 -0
  14. package/backend/database/queries/integration-queries.ts +34 -6
  15. package/backend/database/queries/worktree-branch-queries.ts +331 -0
  16. package/backend/db-client/cloning.test.ts +161 -0
  17. package/backend/db-client/cloning.ts +672 -0
  18. package/backend/db-client/connection-url.test.ts +117 -0
  19. package/backend/db-client/connection-url.ts +126 -0
  20. package/backend/db-client/drivers/mongodb.ts +2 -14
  21. package/backend/db-client/drivers/mysql.ts +2 -8
  22. package/backend/db-client/drivers/postgres.ts +10 -13
  23. package/backend/db-client/drivers/redis.ts +2 -6
  24. package/backend/db-client/env/detect.ts +438 -0
  25. package/backend/db-client/env/diff.ts +94 -0
  26. package/backend/db-client/env/env.test.ts +574 -0
  27. package/backend/db-client/env/index.ts +15 -0
  28. package/backend/db-client/env/naming.ts +202 -0
  29. package/backend/db-client/env/service.ts +487 -0
  30. package/backend/db-client/integrations/index.ts +44 -0
  31. package/backend/db-client/integrations/links.ts +564 -0
  32. package/backend/db-client/integrations/projector.test.ts +280 -0
  33. package/backend/db-client/integrations/projector.ts +256 -0
  34. package/backend/db-client/integrations/supabase-service.ts +266 -0
  35. package/backend/db-client/providers/neon/adapter.ts +522 -0
  36. package/backend/db-client/providers/neon/api-types.ts +182 -0
  37. package/backend/db-client/providers/neon/client.ts +298 -0
  38. package/backend/db-client/providers/neon/endpoints.test.ts +201 -0
  39. package/backend/db-client/providers/neon/endpoints.ts +314 -0
  40. package/backend/db-client/providers/neon/list.test.ts +181 -0
  41. package/backend/db-client/providers/registry.ts +27 -0
  42. package/backend/db-client/providers/supabase/adapter.ts +523 -0
  43. package/backend/db-client/providers/supabase/api-types.ts +92 -0
  44. package/backend/db-client/providers/supabase/apply-migration.ts +104 -0
  45. package/backend/db-client/providers/supabase/client.ts +259 -0
  46. package/backend/db-client/providers/supabase/features.ts +502 -0
  47. package/backend/db-client/providers/supabase/local.test.ts +78 -0
  48. package/backend/db-client/providers/supabase/local.ts +137 -0
  49. package/backend/db-client/providers/types.ts +194 -0
  50. package/backend/deployments/bindings.test.ts +43 -0
  51. package/backend/deployments/bindings.ts +216 -0
  52. package/backend/deployments/index.ts +53 -0
  53. package/backend/deployments/log-streams.ts +214 -0
  54. package/backend/deployments/prompts.ts +70 -0
  55. package/backend/deployments/providers/vercel/adapter.ts +757 -0
  56. package/backend/deployments/providers/vercel/build-logs.test.ts +80 -0
  57. package/backend/deployments/providers/vercel/build-logs.ts +211 -0
  58. package/backend/deployments/providers/vercel/client.ts +203 -0
  59. package/backend/deployments/providers/vercel/list.test.ts +624 -0
  60. package/backend/deployments/providers/vercel/normalise.test.ts +115 -0
  61. package/backend/deployments/providers/vercel/normalise.ts +113 -0
  62. package/backend/deployments/providers/vercel/types.ts +104 -0
  63. package/backend/deployments/registry.ts +27 -0
  64. package/backend/deployments/service.ts +458 -0
  65. package/backend/deployments/types.ts +278 -0
  66. package/backend/env-files/discovery.ts +48 -0
  67. package/backend/env-files/edit.ts +213 -0
  68. package/backend/env-files/env-files.test.ts +515 -0
  69. package/backend/env-files/git.ts +27 -0
  70. package/backend/env-files/index.ts +44 -0
  71. package/backend/env-files/keys.ts +69 -0
  72. package/backend/env-files/parse.ts +157 -0
  73. package/backend/env-files/write.ts +229 -0
  74. package/backend/index.ts +4 -0
  75. package/backend/integrations/health.ts +18 -4
  76. package/backend/integrations/projections/index.ts +0 -0
  77. package/backend/integrations/projections/mcp-projector.ts +7 -3
  78. package/backend/integrations/projections/types.ts +28 -9
  79. package/backend/integrations/registry/index.ts +8 -1
  80. package/backend/integrations/registry/providers/context7.ts +1 -0
  81. package/backend/integrations/registry/providers/firecrawl.ts +1 -0
  82. package/backend/integrations/registry/providers/github.ts +1 -0
  83. package/backend/integrations/registry/providers/neon.ts +55 -0
  84. package/backend/integrations/registry/providers/supabase.ts +62 -0
  85. package/backend/integrations/registry/providers/vercel.ts +47 -0
  86. package/backend/integrations/registry/types.ts +2 -0
  87. package/backend/mcp/internal/servers/memory-graph/description.ts +3 -3
  88. package/backend/mcp/internal/servers/memory-graph/runner.ts +4 -9
  89. package/backend/mcp/internal/servers/memory-graph/schema.ts +0 -4
  90. package/backend/memory/README.md +57 -34
  91. package/backend/memory/compose.test.ts +3 -3
  92. package/backend/memory/compose.ts +6 -9
  93. package/backend/memory/config.ts +0 -5
  94. package/backend/memory/consolidate.ts +1 -2
  95. package/backend/memory/context.test.ts +8 -54
  96. package/backend/memory/context.ts +19 -25
  97. package/backend/memory/extract/episodic.ts +10 -12
  98. package/backend/memory/extract/index.ts +23 -52
  99. package/backend/memory/extract/scheduler.ts +3 -6
  100. package/backend/memory/index.ts +6 -5
  101. package/backend/memory/invalidate.ts +36 -48
  102. package/backend/memory/layout.ts +319 -130
  103. package/backend/memory/retention.ts +12 -42
  104. package/backend/memory/retrieval.eval.test.ts +2 -2
  105. package/backend/memory/retrieval.test.ts +228 -183
  106. package/backend/memory/retrieval.ts +22 -21
  107. package/backend/memory/revise.test.ts +62 -116
  108. package/backend/memory/revise.ts +0 -1
  109. package/backend/memory/view.ts +8 -5
  110. package/backend/snapshot/helpers.ts +35 -41
  111. package/backend/snapshot/snapshot-service.ts +90 -0
  112. package/backend/snapshot/turn-changes.test.ts +163 -0
  113. package/backend/snapshot/turn-changes.ts +131 -0
  114. package/backend/work/start-work.ts +4 -0
  115. package/backend/worktrees/branching/engine.ts +557 -0
  116. package/backend/worktrees/branching/index.ts +56 -0
  117. package/backend/worktrees/branching/naming.test.ts +118 -0
  118. package/backend/worktrees/branching/naming.ts +97 -0
  119. package/backend/worktrees/branching/projector.test.ts +229 -0
  120. package/backend/worktrees/branching/projector.ts +139 -0
  121. package/backend/worktrees/branching/providers/neon.ts +220 -0
  122. package/backend/worktrees/branching/registry.ts +27 -0
  123. package/backend/worktrees/branching/service.ts +620 -0
  124. package/backend/worktrees/branching/suggest.test.ts +154 -0
  125. package/backend/worktrees/branching/suggest.ts +202 -0
  126. package/backend/worktrees/branching/types.ts +88 -0
  127. package/backend/worktrees/index.ts +7 -0
  128. package/backend/worktrees/service.ts +48 -1
  129. package/backend/ws/db-client/accounts.ts +225 -0
  130. package/backend/ws/db-client/connections.ts +34 -3
  131. package/backend/ws/db-client/context.ts +37 -0
  132. package/backend/ws/db-client/env.ts +142 -0
  133. package/backend/ws/db-client/index.ts +22 -1
  134. package/backend/ws/db-client/supabase.ts +188 -0
  135. package/backend/ws/deployments/actions.ts +360 -0
  136. package/backend/ws/deployments/context.ts +43 -0
  137. package/backend/ws/deployments/crud.ts +152 -0
  138. package/backend/ws/deployments/index.ts +15 -0
  139. package/backend/ws/deployments/schemas.ts +183 -0
  140. package/backend/ws/index.ts +6 -2
  141. package/backend/ws/memory/crud.ts +4 -16
  142. package/backend/ws/projects/index.ts +6 -1
  143. package/backend/ws/projects/info.ts +70 -6
  144. package/backend/ws/projects/overview.test.ts +108 -0
  145. package/backend/ws/projects/overview.ts +300 -0
  146. package/backend/ws/snapshot/changes.ts +279 -0
  147. package/backend/ws/snapshot/index.ts +4 -3
  148. package/backend/ws/system/device-info.ts +307 -76
  149. package/backend/ws/worktrees/branching.ts +212 -0
  150. package/backend/ws/worktrees/crud.ts +33 -7
  151. package/backend/ws/worktrees/index.ts +14 -0
  152. package/dist/assets/{index-DSHIANSy.js → index-D4igjF6e.js} +1 -1
  153. package/dist/assets/{index-CyH7fSbR.js → index-DONNwiXm.js} +1 -1
  154. package/dist/assets/main-BrfXH1bL.js +1205 -0
  155. package/dist/assets/main-CT1PygsW.css +1 -0
  156. package/dist/index.html +2 -2
  157. package/package.json +1 -1
  158. package/shared/constants/tool-icons.ts +13 -0
  159. package/shared/types/db-client/connection.ts +6 -0
  160. package/shared/types/db-client/env.ts +192 -0
  161. package/shared/types/db-client/index.ts +3 -0
  162. package/shared/types/db-client/integrations.ts +204 -0
  163. package/shared/types/db-client/supabase.ts +131 -0
  164. package/shared/types/deployments.ts +382 -0
  165. package/shared/types/integrations.ts +9 -0
  166. package/shared/types/memory.ts +34 -51
  167. package/shared/types/ui/components.ts +1 -1
  168. package/shared/types/worktree-branching.ts +315 -0
  169. package/shared/utils/diff-calculator.test.ts +89 -0
  170. package/shared/utils/diff-calculator.ts +30 -65
  171. package/shared/utils/logger.ts +2 -0
  172. package/backend/memory/extract/languages.ts +0 -176
  173. package/backend/memory/extract/structural.test.ts +0 -215
  174. package/backend/memory/extract/structural.ts +0 -364
  175. package/backend/ws/snapshot/content.ts +0 -85
  176. package/dist/assets/main-D2IOjftb.css +0 -1
  177. package/dist/assets/main-DM-tHKbW.js +0 -1152
@@ -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
+ );
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Turn Changes Handler
3
+ *
4
+ * Everything the AI-change indicators and the checkpoint "Changes" tab read:
5
+ * which files each turn of a chat touched, and the content on either side of
6
+ * that change.
7
+ *
8
+ * Both are answered from checkpoint snapshots rather than from Edit/Write tool
9
+ * calls — see backend/snapshot/turn-changes.ts for why that distinction is the
10
+ * whole point. The one thing snapshots cannot answer is a turn that is still
11
+ * running, which `snapshot:get-pending-changes` covers from the same baseline.
12
+ *
13
+ * Only checkpoints on the ACTIVE path are reported. After a restore, the
14
+ * checkpoints that were undone no longer describe anything on disk, so keeping
15
+ * their files in the list would mark files that carry no such change any more.
16
+ * Active-path selection is done with the same helpers the timeline uses, so the
17
+ * two views cannot disagree about which turns exist.
18
+ */
19
+
20
+ import { t } from 'elysia';
21
+ import { createRouter } from '$shared/utils/ws-server';
22
+ import { isAbsolute, join, relative } from 'path';
23
+ import { readFile } from 'fs/promises';
24
+ import {
25
+ messageQueries,
26
+ sessionQueries,
27
+ projectQueries,
28
+ snapshotQueries
29
+ } from '../../database/queries';
30
+ import { loadMessage } from '$shared/utils/message-formatter';
31
+ import { blobStore } from '../../snapshot/blob-store';
32
+ import { snapshotService } from '../../snapshot/snapshot-service';
33
+ import { resolveSessionRoot } from '../../worktrees';
34
+ import { makeScopeKey } from '$shared/utils/workspace-scope';
35
+ import { buildTurnFiles, excerptPrompt, isBinaryBuffer, statusOf } from '../../snapshot/turn-changes';
36
+ import type { TurnFileStatus } from '../../snapshot/turn-changes';
37
+ import {
38
+ buildCheckpointTree,
39
+ getCheckpointPathToRoot,
40
+ findCheckpointForHead,
41
+ extractMessageText
42
+ } from '../../snapshot/helpers';
43
+ import type { SessionScopedChanges } from '$shared/types/database/schema';
44
+ import { debug } from '$shared/utils/logger';
45
+ import { requireSessionAccess, requireMessageAccess } from '../access';
46
+
47
+ /**
48
+ * Longest prompt excerpt a turn row shows. Long enough that nearly every real
49
+ * instruction arrives whole, short enough that a chat of them stays a list.
50
+ */
51
+ const PROMPT_EXCERPT_LENGTH = 400;
52
+
53
+ const TURN_FILE_SCHEMA = t.Object({
54
+ path: t.String(),
55
+ status: t.Union([t.Literal('added'), t.Literal('modified'), t.Literal('deleted')]),
56
+ insertions: t.Number(),
57
+ deletions: t.Number(),
58
+ isBinary: t.Boolean(),
59
+ contentAvailable: t.Boolean()
60
+ });
61
+
62
+ /** Parse a snapshot's stored changes, treating unreadable JSON as "no changes". */
63
+ function parseSessionChanges(raw: unknown): SessionScopedChanges {
64
+ if (typeof raw !== 'string' || raw === '') return {};
65
+ try {
66
+ return JSON.parse(raw) as SessionScopedChanges;
67
+ } catch {
68
+ return {};
69
+ }
70
+ }
71
+
72
+ /** Read a blob as text, or null when it is missing or not text. */
73
+ async function readTextBlob(hash: string): Promise<string | null> {
74
+ if (!hash) return null;
75
+ try {
76
+ const buf = await blobStore.readBlob(hash);
77
+ return isBinaryBuffer(buf) ? null : buf.toString('utf8');
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+
83
+ export const changesHandler = createRouter()
84
+ /**
85
+ * Every turn of a chat, newest first, with the files it changed.
86
+ */
87
+ .http('snapshot:list-turn-changes', {
88
+ data: t.Object({
89
+ sessionId: t.String({ minLength: 1 })
90
+ }),
91
+ response: t.Object({
92
+ turns: t.Array(
93
+ t.Object({
94
+ checkpointMessageId: t.String(),
95
+ /** 1-based position on the active path — what "Turn 3" means. */
96
+ turnIndex: t.Number(),
97
+ timestamp: t.String(),
98
+ promptText: t.String(),
99
+ files: t.Array(TURN_FILE_SCHEMA)
100
+ })
101
+ )
102
+ })
103
+ }, async ({ data, conn }) => {
104
+ requireSessionAccess(conn, data.sessionId);
105
+
106
+ const allMessages = messageQueries.getAllBySessionId(data.sessionId);
107
+ if (allMessages.length === 0) return { turns: [] };
108
+
109
+ const { checkpoints, parentMap } = buildCheckpointTree(allMessages);
110
+ if (checkpoints.length === 0) return { turns: [] };
111
+
112
+ // No HEAD means the session was restored to before its first message, so
113
+ // no turn's changes are on disk any more.
114
+ const head = sessionQueries.getHead(data.sessionId);
115
+ if (!head) return { turns: [] };
116
+
117
+ const checkpointIds = new Set(checkpoints.map((cp) => cp.id));
118
+ const activeCheckpointId = findCheckpointForHead(head, allMessages, checkpointIds);
119
+ if (!activeCheckpointId) return { turns: [] };
120
+
121
+ const activePath = getCheckpointPathToRoot(activeCheckpointId, parentMap);
122
+ const byId = new Map(checkpoints.map((cp) => [cp.id, cp]));
123
+
124
+ const turns = [];
125
+ for (let i = 0; i < activePath.length; i++) {
126
+ const checkpoint = byId.get(activePath[i]);
127
+ if (!checkpoint) continue;
128
+
129
+ const snapshot = snapshotQueries.getByMessageId(checkpoint.id);
130
+ const changes = parseSessionChanges(snapshot?.session_changes);
131
+ const files = await buildTurnFiles(changes, (hash) => blobStore.readBlob(hash));
132
+
133
+ turns.push({
134
+ checkpointMessageId: checkpoint.id,
135
+ turnIndex: i + 1,
136
+ timestamp: checkpoint.created_at,
137
+ promptText: excerptPrompt(
138
+ extractMessageText(loadMessage(checkpoint)),
139
+ PROMPT_EXCERPT_LENGTH
140
+ ),
141
+ files
142
+ });
143
+ }
144
+
145
+ // Newest first: the turn a user wants to review is almost always the last
146
+ // one, and scrolling to reach it is a tax on the common case.
147
+ turns.reverse();
148
+ return { turns };
149
+ })
150
+
151
+ /**
152
+ * Both sides of one file's change in one turn.
153
+ *
154
+ * Replaces reading the file twice: the diff pane, the editor gutter and the
155
+ * revert action all need the same pair, and a single round-trip keeps them
156
+ * from disagreeing about which version they are looking at.
157
+ *
158
+ * Pass `messageId` for a settled turn, or `sessionId` for the turn that is
159
+ * still running — the running turn has no snapshot row yet, so its "before"
160
+ * comes from the live session baseline and its "after" from the file itself.
161
+ */
162
+ .http('snapshot:read-turn-file', {
163
+ data: t.Object({
164
+ /** Checkpoint message id — the user message that opened the turn. */
165
+ messageId: t.Optional(t.String({ minLength: 1 })),
166
+ /** Session id — for the turn currently running. */
167
+ sessionId: t.Optional(t.String({ minLength: 1 })),
168
+ filePath: t.String()
169
+ }),
170
+ response: t.Object({
171
+ /** Text before the turn; '' when the turn created the file. */
172
+ before: t.Union([t.String(), t.Null()]),
173
+ /** Text after the turn; '' when the turn deleted it. */
174
+ after: t.Union([t.String(), t.Null()]),
175
+ status: t.Union([
176
+ t.Literal('added'),
177
+ t.Literal('modified'),
178
+ t.Literal('deleted'),
179
+ t.Literal('unchanged')
180
+ ]),
181
+ isBinary: t.Boolean()
182
+ })
183
+ }, async ({ data, conn }) => {
184
+ const unchanged = { before: null, after: null, status: 'unchanged' as const, isBinary: false };
185
+
186
+ const sessionId = data.messageId
187
+ ? requireMessageAccess(conn, data.messageId).session_id
188
+ : data.sessionId;
189
+ if (!sessionId) return unchanged;
190
+ if (!data.messageId) requireSessionAccess(conn, sessionId);
191
+
192
+ const session = sessionQueries.getById(sessionId);
193
+ const root = resolveSessionRoot(sessionId)?.path
194
+ || (session ? projectQueries.getById(session.project_id)?.path : null);
195
+ if (!root) return unchanged;
196
+
197
+ const relativePath = (
198
+ isAbsolute(data.filePath) ? relative(root, data.filePath) : data.filePath
199
+ ).replace(/\\/g, '/');
200
+
201
+ if (data.messageId) {
202
+ const snapshot = snapshotQueries.getByMessageId(data.messageId);
203
+ const change = parseSessionChanges(snapshot?.session_changes)[relativePath];
204
+ if (!change) return unchanged;
205
+
206
+ const before = change.oldHash ? await readTextBlob(change.oldHash) : '';
207
+ const after = change.newHash ? await readTextBlob(change.newHash) : '';
208
+ // A side that exists but read back as null is binary or gone; either way
209
+ // there is no text to diff, and saying so beats an empty pane.
210
+ return {
211
+ before,
212
+ after,
213
+ status: statusOf(change.oldHash, change.newHash),
214
+ isBinary:
215
+ (change.oldHash !== '' && before === null) || (change.newHash !== '' && after === null)
216
+ };
217
+ }
218
+
219
+ // Running turn: the baseline is the before, and the disk is the after.
220
+ const baseline = snapshotService.getBaselineHash(sessionId, relativePath);
221
+ if (!baseline.known) return unchanged;
222
+
223
+ const before = baseline.hash ? await readTextBlob(baseline.hash) : '';
224
+ let after: string | null = null;
225
+ let exists = true;
226
+ try {
227
+ const buf = await readFile(join(root, relativePath));
228
+ after = isBinaryBuffer(buf) ? null : buf.toString('utf8');
229
+ } catch {
230
+ exists = false;
231
+ }
232
+
233
+ const status: TurnFileStatus = !baseline.hash ? 'added' : !exists ? 'deleted' : 'modified';
234
+ return {
235
+ before,
236
+ after: exists ? after : '',
237
+ status,
238
+ isBinary: (baseline.hash !== '' && before === null) || (exists && after === null)
239
+ };
240
+ })
241
+
242
+ /**
243
+ * Changes made so far by a turn that is still running.
244
+ *
245
+ * Returns an empty list rather than an error whenever it cannot answer — no
246
+ * baseline yet, nothing dirty, a session without a project — because the
247
+ * caller polls this while the model streams and a failure there must not
248
+ * become a visible error.
249
+ */
250
+ .http('snapshot:get-pending-changes', {
251
+ data: t.Object({
252
+ sessionId: t.String({ minLength: 1 })
253
+ }),
254
+ response: t.Object({
255
+ files: t.Array(TURN_FILE_SCHEMA)
256
+ })
257
+ }, async ({ data, conn }) => {
258
+ requireSessionAccess(conn, data.sessionId);
259
+
260
+ const session = sessionQueries.getById(data.sessionId);
261
+ if (!session) return { files: [] };
262
+
263
+ const root = resolveSessionRoot(data.sessionId)?.path
264
+ || projectQueries.getById(session.project_id)?.path;
265
+ if (!root) return { files: [] };
266
+
267
+ try {
268
+ const changes = await snapshotService.getPendingChanges(
269
+ root,
270
+ makeScopeKey(session.project_id, session.worktree_id ?? null),
271
+ data.sessionId
272
+ );
273
+ const files = await buildTurnFiles(changes, (hash) => blobStore.readBlob(hash));
274
+ return { files };
275
+ } catch (error) {
276
+ debug.warn('snapshot', 'Failed to read pending changes:', error);
277
+ return { files: [] };
278
+ }
279
+ });