@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
@@ -6,15 +6,16 @@
6
6
  * Structure:
7
7
  * - restore.ts: Unified restore operation (replaces undo + redo)
8
8
  * - timeline.ts: Timeline visualization data
9
- * - content.ts: Pre-checkpoint file content (AI gutter diff base)
9
+ * - changes.ts: Per-turn file changes and their content, which is what the
10
+ * AI-change indicators, the editor gutter and the Changes tab all read
10
11
  */
11
12
 
12
13
  import { createRouter } from '$shared/utils/ws-server';
13
14
  import { restoreHandler } from './restore';
14
15
  import { timelineHandler } from './timeline';
15
- import { contentHandler } from './content';
16
+ import { changesHandler } from './changes';
16
17
 
17
18
  export const snapshotRouter = createRouter()
18
19
  .merge(restoreHandler)
19
20
  .merge(timelineHandler)
20
- .merge(contentHandler);
21
+ .merge(changesHandler);
@@ -14,9 +14,11 @@
14
14
  * Static facts (OS, CPU model, core count, installed RAM, GPU model,
15
15
  * virtualization) come from `backend/host/metrics.ts`, which probes them once
16
16
  * per process and is also what Project Info reads, so the two panels cannot
17
- * disagree about the machine they are describing. Dynamic metrics (load,
18
- * memory in use, battery, disk, GPU utilization) are recomputed on every
19
- * request so the panel can poll live.
17
+ * disagree about the machine they are describing. Fast live metrics (CPU via
18
+ * OS deltas, memory, network, uptime) are re-read on every request so the
19
+ * panel polls live. Slow WMI-bound metrics (battery, disk usage, GPU) are
20
+ * cached for 60s and refreshed in the background, so one timed-out probe can
21
+ * never flip the panel between "This Device" <-> "Server" or drop cards.
20
22
  */
21
23
 
22
24
  import { t } from 'elysia';
@@ -26,14 +28,141 @@ import type { Systeminformation } from 'systeminformation';
26
28
  import { createRouter } from '$shared/utils/ws-server';
27
29
  import { getHostFacts, withTimeout } from '../../host/metrics';
28
30
 
29
- /** Last-good caches for dynamic probes: prevents transient WMI timeouts from
30
- * flickering the UI between "This Device" <-> "Server" or dropping Storage cards. */
31
- let lastMemCache: Systeminformation.MemData | null = null;
32
- let lastBatteryCache: Systeminformation.BatteryData | null = null;
33
- let lastFsSizeCache: Systeminformation.FsSizeData[] | null = null;
34
- let lastLoadCache: Systeminformation.CurrentLoadData | null = null;
35
- let lastGraphicsCache: Systeminformation.GraphicsData | null = null;
36
- let lastNetCache: Systeminformation.NetworkInterfacesData | null = null;
31
+ /** Two-tier probing. Fast signals (CPU via os deltas, memory, network, uptime)
32
+ * are cheap and re-read on every request. Slow signals (battery, disk usage,
33
+ * GPU) shell out to WMI/PowerShell, change slowly, and time out under load —
34
+ * re-probing them on every poll is what made the panel flip between
35
+ * "This Device" <-> "Server" and made Battery/Swap/Storage cards appear and
36
+ * vanish on every open/close. Slow signals are cached for SLOW_TTL_MS and
37
+ * refreshed in the background; a request only waits for them on cold start
38
+ * when no snapshot exists at all. */
39
+ const LAST_GOOD_MAX_AGE_MS = 60_000;
40
+ const SLOW_TTL_MS = 60_000;
41
+ interface TimedCache<T> { value: T; at: number }
42
+ let lastMemCache: TimedCache<Systeminformation.MemData> | null = null;
43
+ let lastNetCache: TimedCache<Systeminformation.NetworkInterfacesData> | null = null;
44
+
45
+ function fresh<T>(cache: TimedCache<T> | null): T | null {
46
+ if (!cache || Date.now() - cache.at > LAST_GOOD_MAX_AGE_MS) return null;
47
+ return cache.value;
48
+ }
49
+
50
+ interface SlowSnapshot {
51
+ battery: Systeminformation.BatteryData | null;
52
+ fsSize: Systeminformation.FsSizeData[] | null;
53
+ graphics: Systeminformation.GraphicsData | null;
54
+ at: number;
55
+ }
56
+ let slowCache: SlowSnapshot | null = null;
57
+ let slowInFlight: Promise<SlowSnapshot> | null = null;
58
+
59
+ /** Battery presence is sticky: WMI transiently reports no-battery/timeout on
60
+ * laptops under load, which used to flip the whole panel to "Server". Only
61
+ * three consecutive *explicit* no-battery readings (not timeouts) clear it. */
62
+ let stickyHasBattery = false;
63
+ let batteryFalseStreak = 0;
64
+
65
+ async function probeSlow(): Promise<SlowSnapshot> {
66
+ const [battery, graphics, fsSize] = await Promise.all([
67
+ withTimeout(si.battery(), 8000),
68
+ withTimeout(si.graphics(), 8000),
69
+ withTimeout(si.fsSize(), 8000)
70
+ ]);
71
+ if (battery) {
72
+ if (battery.hasBattery) {
73
+ stickyHasBattery = true;
74
+ batteryFalseStreak = 0;
75
+ } else if (++batteryFalseStreak >= 3) {
76
+ stickyHasBattery = false;
77
+ }
78
+ }
79
+ const snapshot: SlowSnapshot = { battery, fsSize, graphics, at: Date.now() };
80
+ // Merge: never let one timed-out probe wipe a good snapshot from another.
81
+ if (slowCache) {
82
+ if (!snapshot.battery) snapshot.battery = slowCache.battery;
83
+ if (!snapshot.fsSize) snapshot.fsSize = slowCache.fsSize;
84
+ if (!snapshot.graphics) snapshot.graphics = slowCache.graphics;
85
+ }
86
+ slowCache = snapshot;
87
+ return snapshot;
88
+ }
89
+
90
+ /** Slow signals for one request: fresh cache served instantly, stale cache
91
+ * served instantly while a background refresh runs, cold start awaits. */
92
+ function ensureSlow(): Promise<SlowSnapshot> {
93
+ if (slowCache && Date.now() - slowCache.at < SLOW_TTL_MS) {
94
+ return Promise.resolve(slowCache);
95
+ }
96
+ if (slowInFlight) return slowInFlight;
97
+ slowInFlight = probeSlow().then((snapshot) => {
98
+ slowInFlight = null;
99
+ return snapshot;
100
+ });
101
+ slowInFlight.then(
102
+ () => {},
103
+ () => {
104
+ slowInFlight = null;
105
+ }
106
+ );
107
+ // Stale-but-usable snapshot wins over waiting: the Device tab must open
108
+ // instantly with consistent cards, then correct itself next poll.
109
+ if (slowCache) return Promise.resolve(slowCache);
110
+ return slowInFlight;
111
+ }
112
+
113
+ /** Rolling OS-level CPU measurement (same source Task Manager samples).
114
+ * `si.currentLoad()` on a cold process — especially while 11 WMI/PowerShell
115
+ * probes run concurrently — can spike to 100%, and the spike is partly the
116
+ * measurement storm itself. Sampling `os.cpus()` deltas between requests
117
+ * (one per uncached request) measures the real machine load instead. */
118
+ let lastCpuSample: { busy: number; total: number; at: number } | null = null;
119
+ let lastCpuPercent: number | null = null;
120
+ /** A delta is an average over the gap between samples. Across a closed panel
121
+ * that gap is minutes, and the resulting figure describes a window nobody
122
+ * asked about — so an old baseline is dropped and re-seeded instead. */
123
+ const MAX_CPU_SAMPLE_GAP_MS = 15_000;
124
+
125
+ function sampleOsCpuPercent(): number | null {
126
+ let busy = 0;
127
+ let total = 0;
128
+ // Containers with no readable per-core stats report an empty list; there is
129
+ // nothing to difference, so the si probe stays the source for that host.
130
+ for (const core of os.cpus()) {
131
+ const active = core.times.user + core.times.nice + core.times.sys + core.times.irq;
132
+ busy += active;
133
+ total += active + core.times.idle;
134
+ }
135
+ const now = Date.now();
136
+ const prev = lastCpuSample;
137
+ lastCpuSample = total > 0 ? { busy, total, at: now } : null;
138
+
139
+ if (prev && now - prev.at > MAX_CPU_SAMPLE_GAP_MS) {
140
+ // Re-seeded above; this tick falls back to si.currentLoad() and the
141
+ // next one has a baseline worth differencing.
142
+ lastCpuPercent = null;
143
+ return null;
144
+ }
145
+ if (prev && now - prev.at >= 500 && total - prev.total > 0) {
146
+ const pct = ((busy - prev.busy) / (total - prev.total)) * 100;
147
+ lastCpuPercent = Math.min(100, Math.max(0, pct));
148
+ }
149
+ return lastCpuPercent;
150
+ }
151
+
152
+ /** OS fallback for the default network interface when `si` returns nothing
153
+ * (e.g. transient WMI timeout): first up, non-internal IPv4 interface. */
154
+ function osFallbackNetwork(): { iface: string; ip4: string; mac: string } | null {
155
+ const ifaces = os.networkInterfaces();
156
+ for (const [name, addrs] of Object.entries(ifaces)) {
157
+ for (const addr of addrs ?? []) {
158
+ if (addr.internal || addr.family !== 'IPv4' || !addr.address) continue;
159
+ // Skip virtual/tunnel adapters without a real MAC.
160
+ if (!addr.mac || addr.mac === '00:00:00:00:00:00') continue;
161
+ return { iface: name, ip4: addr.address, mac: addr.mac };
162
+ }
163
+ }
164
+ return null;
165
+ }
37
166
 
38
167
  const GpuSchema = t.Object({
39
168
  model: t.String(),
@@ -129,74 +258,111 @@ function selectPrimaryDisks(raw: Systeminformation.FsSizeData[], platform: strin
129
258
  .sort((a, b) => (a.mount === '/' ? -1 : b.mount === '/' ? 1 : b.sizeBytes - a.sizeBytes));
130
259
  }
131
260
 
132
- export const deviceInfoHandler = createRouter()
133
- .http('system:device-info', {
134
- data: t.Object({}),
135
- response: t.Object({
136
- hostname: t.String(),
137
- platform: t.String(),
138
- distro: t.String(),
139
- release: t.String(),
140
- kernel: t.String(),
141
- arch: t.String(),
142
- isVirtual: t.Boolean(),
143
- uptimeSec: t.Number(),
144
- cpu: t.Object({
145
- brand: t.String(),
146
- manufacturer: t.String(),
147
- physicalCores: t.Number(),
148
- logicalCores: t.Number(),
149
- speedGhz: t.Union([t.Number(), t.Null()]),
150
- loadPercent: t.Number(),
151
- loadAvg1: t.Union([t.Number(), t.Null()])
152
- }),
153
- memory: t.Object({
154
- totalBytes: t.Number(),
155
- usedBytes: t.Number(),
156
- freeBytes: t.Number(),
157
- swapTotalBytes: t.Number(),
158
- swapUsedBytes: t.Number()
159
- }),
160
- network: t.Object({
161
- iface: t.String(),
162
- ip4: t.String(),
163
- mac: t.String()
164
- }),
165
- battery: BatterySchema,
166
- gpus: t.Array(GpuSchema),
167
- disks: t.Array(DiskSchema)
168
- })
169
- }, async () => {
170
- const facts = await getHostFacts();
261
+ /** Response snapshot served from cache inside the TTL so a burst of opens
262
+ * and rapid tab switches never re-run the si.* probes. */
263
+ interface DeviceInfoPayload {
264
+ hostname: string;
265
+ platform: string;
266
+ distro: string;
267
+ release: string;
268
+ kernel: string;
269
+ arch: string;
270
+ isVirtual: boolean;
271
+ uptimeSec: number;
272
+ cpu: {
273
+ brand: string;
274
+ manufacturer: string;
275
+ physicalCores: number;
276
+ logicalCores: number;
277
+ speedGhz: number | null;
278
+ loadPercent: number;
279
+ loadAvg1: number | null;
280
+ };
281
+ memory: {
282
+ totalBytes: number;
283
+ usedBytes: number;
284
+ freeBytes: number;
285
+ swapTotalBytes: number;
286
+ swapUsedBytes: number;
287
+ };
288
+ network: { iface: string; ip4: string; mac: string };
289
+ battery: {
290
+ hasBattery: boolean;
291
+ percent: number | null;
292
+ isCharging: boolean;
293
+ acConnected: boolean;
294
+ timeRemainingMinutes: number | null;
295
+ };
296
+ gpus: Array<{
297
+ model: string;
298
+ vendor: string;
299
+ vramMb: number | null;
300
+ utilizationGpu: number | null;
301
+ memoryUsedMb: number | null;
302
+ memoryTotalMb: number | null;
303
+ }>;
304
+ disks: DiskInfo[];
305
+ }
306
+
307
+ /** Comfortably under the frontend's 3s heartbeat. At an equal TTL, jitter
308
+ * means roughly every other poll is answered with the payload it already
309
+ * has, so a panel advertising live numbers would really move every 6s. */
310
+ const DEVICE_CACHE_TTL_MS = 1500;
311
+ let cachedDevice: { payload: DeviceInfoPayload; at: number } | null = null;
312
+ let inFlightDevice: Promise<DeviceInfoPayload> | null = null;
313
+
314
+ async function buildDeviceInfo(): Promise<DeviceInfoPayload> {
315
+ // Static facts and live probes launch together. They used to run one
316
+ // after another (facts ~4s cold, then probes ~3.5s), which stacked past
317
+ // 7s on first open while other settings tabs render instantly.
318
+ // Concurrent, the slowest single phase bounds the total.
319
+ const factsP = getHostFacts();
171
320
 
172
- const [load, mem, battery, graphics, fsSize, netDefault] = await Promise.all([
173
- withTimeout(si.currentLoad(), 3500),
321
+ // OS-level CPU sample taken at request start; the delta is measured
322
+ // against the previous uncached request, free of probe overhead.
323
+ const osCpuPercent = sampleOsCpuPercent();
324
+
325
+ // Per-poll storm cut from ~11 concurrent spawns to 3: only CPU
326
+ // fallback, memory, and network run here. Battery/disks/GPU come
327
+ // from the slow tier so one WMI timeout can no longer flip cards
328
+ // or inflate the CPU reading with its own measurement cost.
329
+ const dynamicP = Promise.all([
330
+ // si CPU is only a first-poll fallback; once the OS delta has a
331
+ // baseline it is both cheaper and more accurate, so skip the spawn.
332
+ osCpuPercent !== null
333
+ ? Promise.resolve(null)
334
+ : withTimeout(si.currentLoad(), 3500),
174
335
  withTimeout(si.mem(), 3500),
175
- withTimeout(si.battery(), 3500),
176
- withTimeout(si.graphics(), 3500),
177
- withTimeout(si.fsSize(), 3500),
178
- withTimeout(si.networkInterfaces('default'), 3500)
336
+ withTimeout(si.networkInterfaces('default'), 3500),
337
+ ensureSlow()
338
+ ]);
339
+
340
+ const [facts, [load, mem, netDefault, slow]] = await Promise.all([
341
+ factsP,
342
+ dynamicP
179
343
  ]);
180
344
 
181
345
  // Update last-good caches; reuse them when a probe times out so the UI
182
346
  // doesn't flicker between "This Device" <-> "Server" or drop Storage cards.
183
- if (mem) lastMemCache = mem;
184
- if (battery) lastBatteryCache = battery;
185
- if (fsSize) lastFsSizeCache = fsSize;
186
- if (load) lastLoadCache = load;
187
- if (graphics) lastGraphicsCache = graphics;
188
- if (netDefault) lastNetCache = Array.isArray(netDefault) ? netDefault[0] : netDefault;
189
-
190
- const memEff = mem ?? lastMemCache;
191
- const batteryEff = battery ?? lastBatteryCache;
192
- const fsSizeEff = fsSize ?? lastFsSizeCache ?? [];
193
- const loadEff = load ?? lastLoadCache;
194
- const graphicsEff = graphics ?? lastGraphicsCache;
195
- const netRawEff = netDefault ?? lastNetCache;
196
- const net = Array.isArray(netRawEff) ? netRawEff[0] : netRawEff;
197
-
198
- // avgLoad is 0/undefined on platforms without load average (e.g. Windows).
199
- const loadAvg1 = typeof loadEff?.avgLoad === 'number' && loadEff.avgLoad > 0 ? loadEff.avgLoad : null;
347
+ // Stale entries (>60s) are ignored so timed-out probes can't pin old
348
+ // numbers as live device state forever.
349
+ const now = Date.now();
350
+ if (mem) lastMemCache = { value: mem, at: now };
351
+ if (netDefault) lastNetCache = { value: Array.isArray(netDefault) ? netDefault[0] : netDefault, at: now };
352
+
353
+ const memEff = mem ?? fresh(lastMemCache);
354
+ const batteryEff = slow.battery;
355
+ const fsSizeEff = slow.fsSize ?? [];
356
+ const graphicsEff = slow.graphics;
357
+ const netRawEff = netDefault ?? fresh(lastNetCache);
358
+ const netSi = Array.isArray(netRawEff) ? netRawEff[0] : netRawEff;
359
+ const netOsFallback = !netSi?.ip4 ? osFallbackNetwork() : null;
360
+ const net = netSi?.ip4 ? netSi : netOsFallback;
361
+
362
+ // Authoritative 1-minute load average straight from the OS (zeros on
363
+ // Windows → null, same as before, but without waiting on si timing).
364
+ const osAvg1 = os.loadavg()[0];
365
+ const loadAvg1 = typeof osAvg1 === 'number' && osAvg1 > 0 ? osAvg1 : null;
200
366
 
201
367
  // Pair live GPU utilization with the cached controller identity by index.
202
368
  const gpus = facts.gpus.map((g, i) => {
@@ -231,7 +397,9 @@ export const deviceInfoHandler = createRouter()
231
397
  speedGhz: facts.cpuSpeedGhz,
232
398
  // Percent of total machine capacity — the same basis Project Info
233
399
  // normalises its per-project figure to, so the two are comparable.
234
- loadPercent: typeof loadEff?.currentLoad === 'number' ? loadEff.currentLoad : 0,
400
+ // OS-delta first (immune to the si cold-start spike and to the
401
+ // probe storm's own CPU cost), si reading as fallback.
402
+ loadPercent: osCpuPercent ?? (typeof load?.currentLoad === 'number' ? load.currentLoad : 0),
235
403
  loadAvg1
236
404
  },
237
405
  memory: {
@@ -249,8 +417,12 @@ export const deviceInfoHandler = createRouter()
249
417
  mac: net?.mac || ''
250
418
  },
251
419
  battery: {
252
- hasBattery: Boolean(batteryEff?.hasBattery),
253
- percent: typeof batteryEff?.percent === 'number' && batteryEff.hasBattery ? batteryEff.percent : null,
420
+ // Sticky presence: a single timed-out/no-battery WMI read must
421
+ // not flip the panel to "Server" on a laptop with a battery.
422
+ hasBattery: stickyHasBattery || Boolean(batteryEff?.hasBattery),
423
+ // Rounded to a whole percent like the OS taskbar/menu-bar shows;
424
+ // si can report floats on some platforms (e.g. 27.6 → 28).
425
+ percent: typeof batteryEff?.percent === 'number' && batteryEff.hasBattery ? Math.round(batteryEff.percent) : null,
254
426
  isCharging: Boolean(batteryEff?.isCharging),
255
427
  acConnected: Boolean(batteryEff?.acConnected),
256
428
  timeRemainingMinutes:
@@ -261,4 +433,63 @@ export const deviceInfoHandler = createRouter()
261
433
  gpus,
262
434
  disks
263
435
  };
436
+ }
437
+
438
+ function getDeviceInfo(): Promise<DeviceInfoPayload> {
439
+ if (cachedDevice && Date.now() - cachedDevice.at < DEVICE_CACHE_TTL_MS) {
440
+ return Promise.resolve(cachedDevice.payload);
441
+ }
442
+ if (inFlightDevice) return inFlightDevice;
443
+
444
+ inFlightDevice = buildDeviceInfo().then((payload) => {
445
+ cachedDevice = { payload, at: Date.now() };
446
+ inFlightDevice = null;
447
+ return payload;
264
448
  });
449
+ inFlightDevice.then(
450
+ () => {},
451
+ () => {
452
+ inFlightDevice = null;
453
+ }
454
+ );
455
+ return inFlightDevice;
456
+ }
457
+
458
+ export const deviceInfoHandler = createRouter()
459
+ .http('system:device-info', {
460
+ data: t.Object({}),
461
+ response: t.Object({
462
+ hostname: t.String(),
463
+ platform: t.String(),
464
+ distro: t.String(),
465
+ release: t.String(),
466
+ kernel: t.String(),
467
+ arch: t.String(),
468
+ isVirtual: t.Boolean(),
469
+ uptimeSec: t.Number(),
470
+ cpu: t.Object({
471
+ brand: t.String(),
472
+ manufacturer: t.String(),
473
+ physicalCores: t.Number(),
474
+ logicalCores: t.Number(),
475
+ speedGhz: t.Union([t.Number(), t.Null()]),
476
+ loadPercent: t.Number(),
477
+ loadAvg1: t.Union([t.Number(), t.Null()])
478
+ }),
479
+ memory: t.Object({
480
+ totalBytes: t.Number(),
481
+ usedBytes: t.Number(),
482
+ freeBytes: t.Number(),
483
+ swapTotalBytes: t.Number(),
484
+ swapUsedBytes: t.Number()
485
+ }),
486
+ network: t.Object({
487
+ iface: t.String(),
488
+ ip4: t.String(),
489
+ mac: t.String()
490
+ }),
491
+ battery: BatterySchema,
492
+ gpus: t.Array(GpuSchema),
493
+ disks: t.Array(DiskSchema)
494
+ })
495
+ }, async () => getDeviceInfo());
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Worktree database branching routes.
3
+ *
4
+ * worktrees:branching-state sources, binding, dotenv files, branches
5
+ * worktrees:branch-suggest the binding this project's own `.env` implies
6
+ * worktrees:branch-parents databases one source can copy from
7
+ * worktrees:branching-save point this project at a parent database
8
+ * worktrees:branching-clear stop branching — existing branches are left alone
9
+ * worktrees:branch-rewrite-env retry the dotenv write
10
+ * worktrees:branch-orphans branches with no live worktree, both kinds
11
+ * worktrees:branch-delete destroy an orphan at the provider
12
+ * worktrees:branch-forget drop the row, leave the remote branch alone
13
+ * worktrees:branch-delete-remote destroy a branch the sweep found untracked
14
+ *
15
+ * ACCESS IS SPLIT, deliberately, and enforced in two places. Every route here
16
+ * takes project access the way `worktrees:create` and `git:push` do — they act
17
+ * inside one project. The DESTROYING ones are additionally listed in
18
+ * `backend/auth/permissions.ts` as admin-only, the way `db-client:link` is:
19
+ * deleting one destroys a real database.
20
+ *
21
+ * Choosing a SOURCE is gated per source rather than per route, because the two
22
+ * kinds belong to different people. An integration account belongs to the
23
+ * install and spends its quota, so only an admin is shown one; a DB Client
24
+ * connection belongs to whoever saved it, and refusing a member their own would
25
+ * make the whole feature admin-only for no reason that survives being stated.
26
+ * `listBranchSources` decides, and `requireSource` enforces.
27
+ */
28
+
29
+ import { t } from 'elysia';
30
+ import { createRouter } from '$shared/utils/ws-server';
31
+ import { initializeDatabase } from '../../database';
32
+ import { worktreeBranching } from '../../worktrees';
33
+ import { ws } from '$backend/utils/ws';
34
+ import { requireCurrentProjectAccess } from '../access';
35
+
36
+ /**
37
+ * Who is asking.
38
+ *
39
+ * Passed into every source-facing call rather than checked here, because the
40
+ * rule is not "admin or not": an integration account belongs to the install and
41
+ * is admin-only, while a DB Client connection belongs to whoever saved it. One
42
+ * helper in the service answers both — see `requireSource`.
43
+ */
44
+ function principalOf(conn: Parameters<typeof ws.getUserId>[0]) {
45
+ return { userId: ws.getUserId(conn), isAdmin: ws.getRole(conn) === 'admin' };
46
+ }
47
+
48
+ /**
49
+ * Tell everyone in the project that its branches or binding moved.
50
+ *
51
+ * The broadcast state is built for an ADMIN. Every recipient re-reads the
52
+ * source list through their own request anyway, and building one payload per
53
+ * viewer here would make an announcement O(viewers) round trips into the
54
+ * database for a list that is about to be refetched.
55
+ */
56
+ async function announce(projectId: string): Promise<void> {
57
+ ws.emit.project(projectId, 'worktrees:branching-changed', {
58
+ projectId,
59
+ state: await worktreeBranching.state(projectId, { userId: '', isAdmin: true })
60
+ });
61
+ }
62
+
63
+ export const worktreeBranchingHandler = createRouter()
64
+ .http('worktrees:branching-state', {
65
+ data: t.Object({}),
66
+ response: t.Any()
67
+ }, async ({ conn }) => {
68
+ await initializeDatabase();
69
+ const { projectId } = requireCurrentProjectAccess(conn);
70
+ return worktreeBranching.state(projectId, principalOf(conn));
71
+ })
72
+
73
+ /**
74
+ * The binding this project would get if it asked for one.
75
+ *
76
+ * Its own route rather than a field on `branching-state`, because it reads
77
+ * the project's dotenv files from disk and the state route is on the path of
78
+ * every worktree dialog open.
79
+ */
80
+ .http('worktrees:branch-suggest', {
81
+ data: t.Object({}),
82
+ response: t.Nullable(t.Any())
83
+ }, async ({ conn }) => {
84
+ await initializeDatabase();
85
+ const { projectId } = requireCurrentProjectAccess(conn);
86
+ return worktreeBranching.suggest(projectId);
87
+ })
88
+
89
+ .http('worktrees:branch-parents', {
90
+ data: t.Object({
91
+ sourceKind: t.Union([t.Literal('account'), t.Literal('connection')]),
92
+ sourceId: t.String({ minLength: 1 })
93
+ }),
94
+ response: t.Array(t.Any())
95
+ }, async ({ data, conn }) => {
96
+ requireCurrentProjectAccess(conn);
97
+ return worktreeBranching.parents(data, principalOf(conn));
98
+ })
99
+
100
+ .http('worktrees:branching-save', {
101
+ data: t.Object({
102
+ sourceKind: t.Union([t.Literal('account'), t.Literal('connection')]),
103
+ sourceId: t.String({ minLength: 1 }),
104
+ parentRef: t.String({ minLength: 1 }),
105
+ parentName: t.String(),
106
+ config: t.Object({
107
+ envVar: t.Optional(t.String()),
108
+ envFile: t.Optional(t.String()),
109
+ autoCreate: t.Optional(t.Boolean()),
110
+ pooled: t.Optional(t.Boolean()),
111
+ dataMode: t.Optional(
112
+ t.Union([t.Literal('schema-data'), t.Literal('schema'), t.Literal('empty')])
113
+ )
114
+ })
115
+ }),
116
+ response: t.Any()
117
+ }, async ({ data, conn }) => {
118
+ await initializeDatabase();
119
+ const { projectId } = requireCurrentProjectAccess(conn);
120
+
121
+ const binding = worktreeBranching.saveBinding({ projectId, ...data }, principalOf(conn));
122
+ await announce(projectId);
123
+ return binding;
124
+ })
125
+
126
+ .http('worktrees:branching-clear', {
127
+ data: t.Object({}),
128
+ response: t.Object({ success: t.Boolean() })
129
+ }, async ({ conn }) => {
130
+ const { projectId } = requireCurrentProjectAccess(conn);
131
+
132
+ worktreeBranching.clearBinding(projectId);
133
+ await announce(projectId);
134
+ return { success: true };
135
+ })
136
+
137
+ .http('worktrees:branch-rewrite-env', {
138
+ data: t.Object({ branchId: t.String({ minLength: 1 }) }),
139
+ response: t.Nullable(t.Any())
140
+ }, async ({ data, conn }) => {
141
+ const { projectId } = requireCurrentProjectAccess(conn);
142
+ const branch = await worktreeBranching.rewriteEnv(data.branchId);
143
+ await announce(projectId);
144
+ return branch;
145
+ })
146
+
147
+ /**
148
+ * Both kinds of leak in one answer.
149
+ *
150
+ * Tracked orphans come from the database and always succeed. The remote sweep
151
+ * talks to the provider and can fail, so it is reported as `sweepError`
152
+ * rather than taking the whole route down with it: a list that says "no
153
+ * untracked branches" because it could not look is exactly the false
154
+ * reassurance this feature exists to avoid.
155
+ */
156
+ .http('worktrees:branch-orphans', {
157
+ data: t.Object({}),
158
+ response: t.Object({
159
+ tracked: t.Array(t.Any()),
160
+ untracked: t.Array(t.Any()),
161
+ sweepError: t.Nullable(t.String())
162
+ })
163
+ }, async ({ conn }) => {
164
+ const { projectId } = requireCurrentProjectAccess(conn);
165
+
166
+ let untracked: unknown[] = [];
167
+ let sweepError: string | null = null;
168
+ try {
169
+ untracked = await worktreeBranching.unknownBranches(projectId);
170
+ } catch (error) {
171
+ sweepError = error instanceof Error ? error.message : String(error);
172
+ }
173
+
174
+ return { tracked: worktreeBranching.orphans(), untracked, sweepError };
175
+ })
176
+
177
+ .http('worktrees:branch-delete', {
178
+ data: t.Object({ branchId: t.String({ minLength: 1 }) }),
179
+ response: t.Object({ success: t.Boolean() })
180
+ }, async ({ data, conn }) => {
181
+ const { projectId } = requireCurrentProjectAccess(conn);
182
+
183
+ await worktreeBranching.deleteOrphan(data.branchId);
184
+ await announce(projectId);
185
+ return { success: true };
186
+ })
187
+
188
+ .http('worktrees:branch-forget', {
189
+ data: t.Object({ branchId: t.String({ minLength: 1 }) }),
190
+ response: t.Object({ success: t.Boolean() })
191
+ }, async ({ data, conn }) => {
192
+ const { projectId } = requireCurrentProjectAccess(conn);
193
+
194
+ worktreeBranching.forgetOrphan(data.branchId);
195
+ await announce(projectId);
196
+ return { success: true };
197
+ })
198
+
199
+ .http('worktrees:branch-delete-remote', {
200
+ data: t.Object({
201
+ sourceKind: t.Union([t.Literal('account'), t.Literal('connection')]),
202
+ sourceId: t.String({ minLength: 1 }),
203
+ parentRef: t.String({ minLength: 1 }),
204
+ branchRef: t.String({ minLength: 1 })
205
+ }),
206
+ response: t.Object({ success: t.Boolean() })
207
+ }, async ({ data, conn }) => {
208
+ requireCurrentProjectAccess(conn);
209
+
210
+ await worktreeBranching.deleteUnknown(data);
211
+ return { success: true };
212
+ });