@myrialabs/clopen 0.4.34 → 0.4.36

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 (125) hide show
  1. package/backend/artifacts/sync.test.ts +63 -0
  2. package/backend/artifacts/sync.ts +56 -3
  3. package/backend/auth/permissions.ts +7 -0
  4. package/backend/containers/actions.ts +316 -0
  5. package/backend/containers/disk-usage.test.ts +68 -0
  6. package/backend/containers/disk-usage.ts +170 -0
  7. package/backend/containers/logs.ts +335 -0
  8. package/backend/containers/monitor.ts +410 -0
  9. package/backend/containers/parse.test.ts +599 -0
  10. package/backend/containers/parse.ts +905 -0
  11. package/backend/containers/port-index.test.ts +91 -0
  12. package/backend/containers/port-index.ts +198 -0
  13. package/backend/containers/prune-job.test.ts +148 -0
  14. package/backend/containers/prune-job.ts +129 -0
  15. package/backend/containers/pty-backend.ts +337 -0
  16. package/backend/containers/pty.ts +114 -0
  17. package/backend/containers/runtime.ts +218 -0
  18. package/backend/containers/scan.ts +293 -0
  19. package/backend/database/migrations/070_create_worktrees_table.ts +67 -0
  20. package/backend/database/migrations/index.ts +7 -0
  21. package/backend/database/queries/index.ts +1 -0
  22. package/backend/database/queries/session-queries.ts +50 -11
  23. package/backend/database/queries/worktree-queries.ts +148 -0
  24. package/backend/engine/adapters/opencode/server.ts +389 -83
  25. package/backend/engine/adapters/opencode/stream.ts +14 -14
  26. package/backend/engine/hot-reload.ts +25 -10
  27. package/backend/files/file-watcher.test.ts +105 -0
  28. package/backend/files/file-watcher.ts +80 -10
  29. package/backend/git/git-service.test.ts +33 -0
  30. package/backend/git/git-service.ts +7 -3
  31. package/backend/git/nested-repos.test.ts +292 -1
  32. package/backend/git/nested-repos.ts +330 -17
  33. package/backend/host/metrics.test.ts +110 -0
  34. package/backend/host/metrics.ts +235 -0
  35. package/backend/{ports → host}/runner.ts +19 -10
  36. package/backend/index.ts +16 -4
  37. package/backend/mcp/internal/servers/browser-automation/context.ts +16 -2
  38. package/backend/ports/attribute.test.ts +3 -2
  39. package/backend/ports/attribute.ts +6 -45
  40. package/backend/ports/kill.ts +1 -1
  41. package/backend/ports/monitor.ts +1 -1
  42. package/backend/ports/processes.ts +1 -1
  43. package/backend/ports/scan-host.ts +77 -8
  44. package/backend/ports/scan.test.ts +1 -1
  45. package/backend/ports/scan.ts +1 -1
  46. package/backend/ports/ssh-lineage.ts +1 -1
  47. package/backend/preview/browser/browser-pool.ts +81 -0
  48. package/backend/preview/browser/browser-preview-service.ts +142 -32
  49. package/backend/preview/browser/browser-tab-manager.ts +350 -113
  50. package/backend/preview/browser/browser-video-capture.ts +84 -31
  51. package/backend/preview/browser/types.ts +9 -0
  52. package/backend/projects/project-cleanup.integration.test.ts +1 -1
  53. package/backend/projects/project-cleanup.ts +7 -1
  54. package/backend/projects/shell-ownership.ts +65 -0
  55. package/backend/snapshot/snapshot-service.ts +6 -2
  56. package/backend/terminal/ptykit.ts +35 -6
  57. package/backend/utils/ws.ts +21 -1
  58. package/backend/worktrees/clone.ts +222 -0
  59. package/backend/worktrees/index.ts +29 -0
  60. package/backend/worktrees/merge.test.ts +93 -0
  61. package/backend/worktrees/merge.ts +232 -0
  62. package/backend/worktrees/paths.test.ts +60 -0
  63. package/backend/worktrees/paths.ts +60 -0
  64. package/backend/worktrees/resolve.ts +67 -0
  65. package/backend/worktrees/service.ts +315 -0
  66. package/backend/worktrees/tree.ts +59 -0
  67. package/backend/ws/access.ts +18 -0
  68. package/backend/ws/artifacts/generate.ts +2 -2
  69. package/backend/ws/chat/stream.ts +9 -2
  70. package/backend/ws/containers/actions.ts +156 -0
  71. package/backend/ws/containers/index.ts +43 -0
  72. package/backend/ws/containers/list.ts +146 -0
  73. package/backend/ws/containers/logs.ts +43 -0
  74. package/backend/ws/containers/tunnel.ts +101 -0
  75. package/backend/ws/files/panel-state-scope.test.ts +102 -0
  76. package/backend/ws/files/path-access.test.ts +93 -1
  77. package/backend/ws/files/path-access.ts +54 -5
  78. package/backend/ws/files/read.ts +15 -10
  79. package/backend/ws/files/search.ts +7 -7
  80. package/backend/ws/files/state.ts +70 -8
  81. package/backend/ws/files/watch.ts +16 -14
  82. package/backend/ws/git/branch-name.ts +3 -3
  83. package/backend/ws/git/branch.ts +15 -15
  84. package/backend/ws/git/commit-message.ts +3 -3
  85. package/backend/ws/git/commit.ts +17 -17
  86. package/backend/ws/git/conflict.ts +10 -10
  87. package/backend/ws/git/diff.ts +9 -9
  88. package/backend/ws/git/ignored.ts +9 -9
  89. package/backend/ws/git/log.ts +6 -4
  90. package/backend/ws/git/remote.ts +43 -43
  91. package/backend/ws/git/staging.ts +16 -16
  92. package/backend/ws/git/status.ts +47 -37
  93. package/backend/ws/index.ts +6 -0
  94. package/backend/ws/message-rate-limiter.test.ts +45 -0
  95. package/backend/ws/message-rate-limiter.ts +34 -3
  96. package/backend/ws/preview/access.ts +11 -3
  97. package/backend/ws/projects/index.ts +5 -1
  98. package/backend/ws/projects/info.test.ts +54 -0
  99. package/backend/ws/projects/info.ts +398 -0
  100. package/backend/ws/sessions/crud.ts +21 -6
  101. package/backend/ws/snapshot/restore.ts +11 -14
  102. package/backend/ws/ssh/connections.ts +8 -0
  103. package/backend/ws/system/device-info.ts +70 -96
  104. package/backend/ws/worktrees/crud.ts +187 -0
  105. package/backend/ws/worktrees/index.ts +33 -0
  106. package/backend/ws/worktrees/transfer.ts +88 -0
  107. package/dist/assets/{index-vW2RpdHu.js → index-Bg-SUCFg.js} +1 -1
  108. package/dist/assets/{index-gGTMFUa8.js → index-Cz4YpHVi.js} +1 -1
  109. package/dist/assets/main-9G7IpQpK.css +1 -0
  110. package/dist/assets/main-BofFsH8E.js +1085 -0
  111. package/dist/index.html +2 -2
  112. package/dist/manifest.json +9 -2
  113. package/package.json +1 -1
  114. package/shared/types/containers/container.ts +366 -0
  115. package/shared/types/containers/index.ts +5 -0
  116. package/shared/types/database/schema.ts +26 -0
  117. package/shared/types/host/index.ts +18 -0
  118. package/shared/types/ports/port.ts +47 -9
  119. package/shared/utils/logger.ts +3 -0
  120. package/shared/utils/workspace-scope.test.ts +80 -0
  121. package/shared/utils/workspace-scope.ts +57 -0
  122. package/shared/utils/ws-client.ts +92 -17
  123. package/shared/utils/ws-server.ts +83 -16
  124. package/dist/assets/main-CYCMEbXB.css +0 -1
  125. package/dist/assets/main-ZCojSzvW.js +0 -1060
@@ -8,7 +8,7 @@
8
8
 
9
9
  import { t } from 'elysia';
10
10
  import { createRouter } from '$shared/utils/ws-server';
11
- import { messageQueries, sessionQueries, projectQueries, checkpointQueries } from '../../database/queries';
11
+ import { messageQueries, sessionQueries, checkpointQueries } from '../../database/queries';
12
12
  import { snapshotService } from '../../snapshot/snapshot-service';
13
13
  import { streamManager } from '../../chat/stream-manager';
14
14
  import { debug } from '$shared/utils/logger';
@@ -22,6 +22,7 @@ import {
22
22
  } from '../../snapshot/helpers';
23
23
  import { ws } from '$backend/utils/ws';
24
24
  import { requireSessionAccess } from '../access';
25
+ import { resolveSessionRoot } from '../../worktrees';
25
26
 
26
27
  export const restoreHandler = createRouter()
27
28
  /**
@@ -52,13 +53,9 @@ export const restoreHandler = createRouter()
52
53
 
53
54
  debug.log('snapshot', `Checking restore conflicts for checkpoint ${messageId} in session ${sessionId}`);
54
55
 
55
- // Resolve project path for reading file contents
56
- let projectPath: string | undefined;
57
- const session = sessionQueries.getById(sessionId);
58
- if (session) {
59
- const project = projectQueries.getById(session.project_id);
60
- if (project) projectPath = project.path;
61
- }
56
+ // Read file contents from the tree this session actually runs in —
57
+ // its worktree when it has one, the project otherwise.
58
+ const projectPath = resolveSessionRoot(sessionId)?.path || undefined;
62
59
 
63
60
  // Build checkpoint path for branch-aware conflict detection
64
61
  let targetPath: string[] | undefined;
@@ -147,10 +144,10 @@ export const restoreHandler = createRouter()
147
144
  let filesRestored = 0;
148
145
  let filesSkipped = 0;
149
146
 
150
- const project = projectQueries.getById(session.project_id);
151
- if (project) {
147
+ const sessionRoot = resolveSessionRoot(sessionId);
148
+ if (sessionRoot?.path) {
152
149
  const result = await snapshotService.restoreSessionScoped(
153
- project.path,
150
+ sessionRoot.path,
154
151
  sessionId,
155
152
  null, // null = restore to initial (before all snapshots)
156
153
  conflictResolutions
@@ -327,10 +324,10 @@ export const restoreHandler = createRouter()
327
324
  let filesRestored = 0;
328
325
  let filesSkipped = 0;
329
326
 
330
- const project = projectQueries.getById(session.project_id);
331
- if (project) {
327
+ const sessionRoot = resolveSessionRoot(sessionId);
328
+ if (sessionRoot?.path) {
332
329
  const result = await snapshotService.restoreSessionScoped(
333
- project.path,
330
+ sessionRoot.path,
334
331
  sessionId,
335
332
  resolvedCheckpointId,
336
333
  conflictResolutions,
@@ -11,6 +11,8 @@ import { sshForwardManager } from '../../ssh/forwards';
11
11
  import { sshHealthService } from '../../ssh/health';
12
12
  import { knownHosts } from '../../ssh/known-hosts';
13
13
  import { killSessionsForConnection } from '../../ssh/ptykit';
14
+ import { killContainerSessionsForHost } from '../../containers/pty';
15
+ import { stopLogStreamsForHost } from '../../containers/logs';
14
16
  import type { SshConnectionInput } from '$shared/types/ssh';
15
17
  import { debug } from '$shared/utils/logger';
16
18
  import { getSshPrincipal, requireSshConnection } from './access';
@@ -78,9 +80,13 @@ function isInput(value: unknown): value is SshConnectionInput {
78
80
  /**
79
81
  * Changing where or how a host is reached invalidates everything riding the old
80
82
  * transport, so shells, forwards and the pooled client all go before the write.
83
+ * That includes the two things this host's containers hold open: shells running
84
+ * inside them, and any log stream being followed.
81
85
  */
82
86
  async function tearDownConnection(connectionId: string): Promise<void> {
83
87
  killSessionsForConnection(connectionId);
88
+ killContainerSessionsForHost(connectionId);
89
+ stopLogStreamsForHost(connectionId);
84
90
  await sshForwardManager.stopForConnection(connectionId);
85
91
  sshClientPool.release(connectionId);
86
92
  // Editing or deleting is not "disconnect" — a host suspended earlier should
@@ -187,6 +193,8 @@ export const sshConnectionsHandler = createRouter()
187
193
  }, async ({ data, conn }) => {
188
194
  requireSshConnection(conn, data.id);
189
195
  killSessionsForConnection(data.id);
196
+ killContainerSessionsForHost(data.id);
197
+ stopLogStreamsForHost(data.id);
190
198
  await sshForwardManager.stopForConnection(data.id);
191
199
  sshClientPool.suspend(data.id);
192
200
  return sshHealthService.testSaved(data.id);
@@ -11,9 +11,12 @@
11
11
  * not expose it (only NVIDIA via nvidia-smi typically does), so util fields
12
12
  * are `null` when unavailable rather than a misleading `0`.
13
13
  *
14
- * Static facts (OS, CPU model, core count, GPU model, virtualization) are
15
- * captured once per process; dynamic metrics (load, memory, battery, disk,
16
- * GPU utilization) are recomputed on every request so the panel can poll live.
14
+ * Static facts (OS, CPU model, core count, installed RAM, GPU model,
15
+ * virtualization) come from `backend/host/metrics.ts`, which probes them once
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
20
  */
18
21
 
19
22
  import { t } from 'elysia';
@@ -21,62 +24,16 @@ import os from 'node:os';
21
24
  import si from 'systeminformation';
22
25
  import type { Systeminformation } from 'systeminformation';
23
26
  import { createRouter } from '$shared/utils/ws-server';
27
+ import { getHostFacts, withTimeout } from '../../host/metrics';
24
28
 
25
- interface StaticInfo {
26
- hostname: string;
27
- platform: string;
28
- distro: string;
29
- release: string;
30
- kernel: string;
31
- arch: string;
32
- isVirtual: boolean;
33
- cpuBrand: string;
34
- cpuManufacturer: string;
35
- physicalCores: number;
36
- logicalCores: number;
37
- cpuSpeedGhz: number | null;
38
- gpus: Array<{ model: string; vendor: string; vramMb: number | null }>;
39
- }
40
-
41
- /** Static facts don't change while the process runs — resolve them once. */
42
- let staticInfoPromise: Promise<StaticInfo> | null = null;
43
-
44
- async function getStaticInfo(): Promise<StaticInfo> {
45
- if (!staticInfoPromise) {
46
- staticInfoPromise = (async () => {
47
- const [osInfo, cpu, system, graphics] = await Promise.all([
48
- si.osInfo(),
49
- si.cpu(),
50
- si.system(),
51
- si.graphics()
52
- ]);
53
- return {
54
- hostname: osInfo.hostname || os.hostname(),
55
- platform: osInfo.platform,
56
- distro: osInfo.distro,
57
- release: osInfo.release,
58
- kernel: osInfo.kernel,
59
- arch: osInfo.arch || os.arch(),
60
- isVirtual: Boolean(system.virtual),
61
- cpuBrand: cpu.brand,
62
- cpuManufacturer: cpu.manufacturer,
63
- physicalCores: cpu.physicalCores || cpu.cores,
64
- logicalCores: cpu.cores,
65
- cpuSpeedGhz: typeof cpu.speed === 'number' && cpu.speed > 0 ? cpu.speed : null,
66
- gpus: graphics.controllers.map((c) => ({
67
- model: c.model || 'Unknown GPU',
68
- vendor: c.vendor || 'Unknown',
69
- vramMb: typeof c.vram === 'number' && c.vram > 0 ? c.vram : null
70
- }))
71
- };
72
- })().catch((err) => {
73
- // Don't cache a failed probe — allow the next request to retry.
74
- staticInfoPromise = null;
75
- throw err;
76
- });
77
- }
78
- return staticInfoPromise;
79
- }
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;
80
37
 
81
38
  const GpuSchema = t.Object({
82
39
  model: t.String(),
@@ -210,27 +167,40 @@ export const deviceInfoHandler = createRouter()
210
167
  disks: t.Array(DiskSchema)
211
168
  })
212
169
  }, async () => {
213
- const staticInfo = await getStaticInfo();
170
+ const facts = await getHostFacts();
214
171
 
215
172
  const [load, mem, battery, graphics, fsSize, netDefault] = await Promise.all([
216
- si.currentLoad(),
217
- si.mem(),
218
- si.battery(),
219
- si.graphics(),
220
- si.fsSize(),
221
- si.networkInterfaces('default')
173
+ withTimeout(si.currentLoad(), 3500),
174
+ 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)
222
179
  ]);
223
180
 
224
- // networkInterfaces('default') returns the single default interface, but
225
- // normalize defensively in case a build returns an array.
226
- const net = Array.isArray(netDefault) ? netDefault[0] : netDefault;
181
+ // Update last-good caches; reuse them when a probe times out so the UI
182
+ // 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;
227
197
 
228
198
  // avgLoad is 0/undefined on platforms without load average (e.g. Windows).
229
- const loadAvg1 = typeof load.avgLoad === 'number' && load.avgLoad > 0 ? load.avgLoad : null;
199
+ const loadAvg1 = typeof loadEff?.avgLoad === 'number' && loadEff.avgLoad > 0 ? loadEff.avgLoad : null;
230
200
 
231
201
  // Pair live GPU utilization with the cached controller identity by index.
232
- const gpus = staticInfo.gpus.map((g, i) => {
233
- const live = graphics.controllers[i];
202
+ const gpus = facts.gpus.map((g, i) => {
203
+ const live = graphicsEff?.controllers?.[i];
234
204
  return {
235
205
  model: g.model,
236
206
  vendor: g.vendor,
@@ -242,32 +212,36 @@ export const deviceInfoHandler = createRouter()
242
212
  });
243
213
 
244
214
  // Show only the primary disk(s); collapses macOS APFS synthetic volumes.
245
- const disks = selectPrimaryDisks(fsSize, staticInfo.platform);
215
+ const disks = selectPrimaryDisks(fsSizeEff, facts.platform);
246
216
 
247
217
  return {
248
- hostname: staticInfo.hostname,
249
- platform: staticInfo.platform,
250
- distro: staticInfo.distro,
251
- release: staticInfo.release,
252
- kernel: staticInfo.kernel,
253
- arch: staticInfo.arch,
254
- isVirtual: staticInfo.isVirtual,
218
+ hostname: facts.hostname,
219
+ platform: facts.platform,
220
+ distro: facts.distro,
221
+ release: facts.release,
222
+ kernel: facts.kernel,
223
+ arch: facts.arch,
224
+ isVirtual: facts.isVirtual,
255
225
  uptimeSec: os.uptime(),
256
226
  cpu: {
257
- brand: staticInfo.cpuBrand,
258
- manufacturer: staticInfo.cpuManufacturer,
259
- physicalCores: staticInfo.physicalCores,
260
- logicalCores: staticInfo.logicalCores,
261
- speedGhz: staticInfo.cpuSpeedGhz,
262
- loadPercent: typeof load.currentLoad === 'number' ? load.currentLoad : 0,
227
+ brand: facts.cpuBrand,
228
+ manufacturer: facts.cpuManufacturer,
229
+ physicalCores: facts.physicalCores,
230
+ logicalCores: facts.logicalCores,
231
+ speedGhz: facts.cpuSpeedGhz,
232
+ // Percent of total machine capacity — the same basis Project Info
233
+ // normalises its per-project figure to, so the two are comparable.
234
+ loadPercent: typeof loadEff?.currentLoad === 'number' ? loadEff.currentLoad : 0,
263
235
  loadAvg1
264
236
  },
265
237
  memory: {
266
- totalBytes: mem.total,
267
- usedBytes: mem.active,
268
- freeBytes: mem.available,
269
- swapTotalBytes: mem.swaptotal,
270
- swapUsedBytes: mem.swapused
238
+ // Installed RAM comes from the shared host facts so this total and
239
+ // the one Project Info divides by are always the same number.
240
+ totalBytes: facts.totalMemBytes,
241
+ usedBytes: memEff?.active ?? os.totalmem() - os.freemem(),
242
+ freeBytes: memEff?.available ?? os.freemem(),
243
+ swapTotalBytes: memEff?.swaptotal ?? 0,
244
+ swapUsedBytes: memEff?.swapused ?? 0
271
245
  },
272
246
  network: {
273
247
  iface: net?.iface || '',
@@ -275,13 +249,13 @@ export const deviceInfoHandler = createRouter()
275
249
  mac: net?.mac || ''
276
250
  },
277
251
  battery: {
278
- hasBattery: Boolean(battery.hasBattery),
279
- percent: typeof battery.percent === 'number' && battery.hasBattery ? battery.percent : null,
280
- isCharging: Boolean(battery.isCharging),
281
- acConnected: Boolean(battery.acConnected),
252
+ hasBattery: Boolean(batteryEff?.hasBattery),
253
+ percent: typeof batteryEff?.percent === 'number' && batteryEff.hasBattery ? batteryEff.percent : null,
254
+ isCharging: Boolean(batteryEff?.isCharging),
255
+ acConnected: Boolean(batteryEff?.acConnected),
282
256
  timeRemainingMinutes:
283
- typeof battery.timeRemaining === 'number' && battery.timeRemaining > 0
284
- ? battery.timeRemaining
257
+ typeof batteryEff?.timeRemaining === 'number' && batteryEff.timeRemaining > 0
258
+ ? batteryEff.timeRemaining
285
259
  : null
286
260
  },
287
261
  gpus,
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Worktree CRUD
3
+ *
4
+ * Listing, creating, renaming and deleting the isolated project copies that
5
+ * chat sessions can run in.
6
+ */
7
+
8
+ import { t } from 'elysia';
9
+ import { createRouter } from '$shared/utils/ws-server';
10
+ import type { WSConnection } from '$shared/utils/ws-server';
11
+ import type { Worktree } from '$shared/types/database/schema';
12
+ import { sessionQueries, worktreeQueries } from '../../database/queries';
13
+ import {
14
+ countPendingChanges,
15
+ createWorktree,
16
+ getWorktreeDiskUsage,
17
+ removeWorktree
18
+ } from '../../worktrees';
19
+ import { ws } from '$backend/utils/ws';
20
+ import { debug } from '$shared/utils/logger';
21
+ import { requireCurrentProjectAccess, requireSessionAccess } from '../access';
22
+
23
+ export const worktreeSchema = t.Object({
24
+ id: t.String(),
25
+ project_id: t.String(),
26
+ name: t.String(),
27
+ slug: t.String(),
28
+ path: t.String(),
29
+ status: t.Union([t.Literal('active'), t.Literal('applied'), t.Literal('archived')]),
30
+ clone_mode: t.Union([t.Literal('reflink'), t.Literal('copy')]),
31
+ created_by: t.Optional(t.String()),
32
+ created_at: t.String(),
33
+ last_opened_at: t.Optional(t.String()),
34
+ last_applied_at: t.Optional(t.String()),
35
+ sessionCount: t.Number()
36
+ });
37
+
38
+ /**
39
+ * Convert a row → response. `base_tree` is deliberately dropped: it is a full
40
+ * hash map of the project and has no use on the client.
41
+ */
42
+ export function serializeWorktree(worktree: Worktree) {
43
+ return {
44
+ id: worktree.id,
45
+ project_id: worktree.project_id,
46
+ name: worktree.name,
47
+ slug: worktree.slug,
48
+ path: worktree.path,
49
+ status: worktree.status,
50
+ clone_mode: worktree.clone_mode,
51
+ created_by: worktree.created_by ?? undefined,
52
+ created_at: worktree.created_at,
53
+ last_opened_at: worktree.last_opened_at ?? undefined,
54
+ last_applied_at: worktree.last_applied_at ?? undefined,
55
+ sessionCount: worktreeQueries.countSessions(worktree.id)
56
+ };
57
+ }
58
+
59
+ /** Tell everyone in the project that the worktree list moved. */
60
+ function broadcastWorktrees(projectId: string): void {
61
+ ws.emit.project(projectId, 'worktrees:changed', {
62
+ projectId,
63
+ worktrees: worktreeQueries.getByProjectId(projectId).map(serializeWorktree)
64
+ });
65
+ }
66
+
67
+ export const worktreeCrudHandler = createRouter()
68
+ .http('worktrees:list', {
69
+ data: t.Object({}),
70
+ response: t.Array(worktreeSchema)
71
+ }, async ({ conn }) => {
72
+ const { projectId } = requireCurrentProjectAccess(conn);
73
+ return worktreeQueries.getByProjectId(projectId).map(serializeWorktree);
74
+ })
75
+
76
+ .http('worktrees:create', {
77
+ data: t.Object({
78
+ name: t.String({ minLength: 1, maxLength: 80 })
79
+ }),
80
+ response: t.Object({
81
+ worktree: worktreeSchema,
82
+ fileCount: t.Number(),
83
+ carriedIgnoredFiles: t.Boolean()
84
+ })
85
+ }, async ({ data, conn }) => {
86
+ const { projectId, userId } = requireCurrentProjectAccess(conn);
87
+
88
+ const result = await createWorktree({
89
+ projectId,
90
+ name: data.name,
91
+ createdBy: userId
92
+ });
93
+
94
+ broadcastWorktrees(projectId);
95
+
96
+ return {
97
+ worktree: serializeWorktree(result.worktree),
98
+ fileCount: result.fileCount,
99
+ carriedIgnoredFiles: result.carriedIgnoredFiles
100
+ };
101
+ })
102
+
103
+ .http('worktrees:rename', {
104
+ data: t.Object({
105
+ id: t.String({ minLength: 1 }),
106
+ name: t.String({ minLength: 1, maxLength: 80 })
107
+ }),
108
+ response: worktreeSchema
109
+ }, async ({ data, conn }) => {
110
+ const worktree = requireWorktreeAccess(conn, data.id);
111
+ worktreeQueries.rename(worktree.id, data.name.trim());
112
+ broadcastWorktrees(worktree.project_id);
113
+
114
+ const updated = worktreeQueries.getById(worktree.id);
115
+ if (!updated) throw new Error('Worktree not found');
116
+ return serializeWorktree(updated);
117
+ })
118
+
119
+ .http('worktrees:delete', {
120
+ data: t.Object({
121
+ id: t.String({ minLength: 1 })
122
+ }),
123
+ response: t.Object({ success: t.Boolean() })
124
+ }, async ({ data, conn }) => {
125
+ const worktree = requireWorktreeAccess(conn, data.id);
126
+ await removeWorktree(worktree.id);
127
+ broadcastWorktrees(worktree.project_id);
128
+ debug.log('worktree', `Deleted worktree ${worktree.name}`);
129
+ return { success: true };
130
+ })
131
+
132
+ /** Divergence and disk footprint — computed on demand, never in the list. */
133
+ .http('worktrees:status', {
134
+ data: t.Object({
135
+ id: t.String({ minLength: 1 })
136
+ }),
137
+ response: t.Object({
138
+ pendingChanges: t.Number(),
139
+ diskKilobytes: t.Optional(t.Number())
140
+ })
141
+ }, async ({ data, conn }) => {
142
+ const worktree = requireWorktreeAccess(conn, data.id);
143
+ const [pendingChanges, diskKilobytes] = await Promise.all([
144
+ countPendingChanges(worktree.id),
145
+ getWorktreeDiskUsage(worktree.path)
146
+ ]);
147
+
148
+ return { pendingChanges, diskKilobytes: diskKilobytes ?? undefined };
149
+ })
150
+
151
+ /** Bind (or unbind) a chat session to a worktree. */
152
+ .http('worktrees:assign-session', {
153
+ data: t.Object({
154
+ sessionId: t.String({ minLength: 1 }),
155
+ worktreeId: t.Union([t.String(), t.Null()])
156
+ }),
157
+ response: t.Object({ success: t.Boolean() })
158
+ }, async ({ data, conn }) => {
159
+ const session = requireSessionAccess(conn, data.sessionId);
160
+
161
+ if (data.worktreeId !== null) {
162
+ const worktree = worktreeQueries.getById(data.worktreeId);
163
+ if (!worktree || worktree.project_id !== session.project_id) {
164
+ throw new Error('Worktree not found');
165
+ }
166
+ worktreeQueries.touch(worktree.id);
167
+ }
168
+
169
+ sessionQueries.setWorktree(session.id, data.worktreeId);
170
+ ws.emit.project(session.project_id, 'worktrees:session-assigned', {
171
+ sessionId: session.id,
172
+ worktreeId: data.worktreeId
173
+ });
174
+
175
+ return { success: true };
176
+ });
177
+
178
+ /** A worktree is reachable exactly when its project is. */
179
+ export function requireWorktreeAccess(conn: WSConnection, worktreeId: string): Worktree {
180
+ const worktree = worktreeQueries.getById(worktreeId);
181
+ if (!worktree) throw new Error('Access denied');
182
+
183
+ const { projectId } = requireCurrentProjectAccess(conn);
184
+ if (worktree.project_id !== projectId) throw new Error('Access denied');
185
+
186
+ return worktree;
187
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Worktrees Router
3
+ *
4
+ * Structure:
5
+ * - crud.ts: list/create/rename/delete/status and session binding
6
+ * - transfer.ts: two-phase apply (worktree → main) and sync (main → worktree)
7
+ */
8
+
9
+ import { t } from 'elysia';
10
+ import { createRouter } from '$shared/utils/ws-server';
11
+ import { worktreeCrudHandler } from './crud';
12
+ import { worktreeTransferHandler } from './transfer';
13
+
14
+ export const worktreesRouter = createRouter()
15
+ .merge(worktreeCrudHandler)
16
+ .merge(worktreeTransferHandler)
17
+ // Collaborative broadcast events (Server → Client)
18
+ .emit('worktrees:changed', t.Object({
19
+ projectId: t.String(),
20
+ worktrees: t.Array(t.Any())
21
+ }))
22
+ .emit('worktrees:session-assigned', t.Object({
23
+ sessionId: t.String(),
24
+ worktreeId: t.Union([t.String(), t.Null()])
25
+ }))
26
+ .emit('worktrees:transferred', t.Object({
27
+ worktreeId: t.String(),
28
+ projectId: t.String(),
29
+ direction: t.Union([t.Literal('apply'), t.Literal('sync')]),
30
+ written: t.Number(),
31
+ deleted: t.Number(),
32
+ skipped: t.Number()
33
+ }));
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Moving work between a worktree and the main tree.
3
+ *
4
+ * Two phases, mirroring the checkpoint restore flow: preview first so the user
5
+ * sees what would change and resolves anything contested, then execute.
6
+ */
7
+
8
+ import { t } from 'elysia';
9
+ import { createRouter } from '$shared/utils/ws-server';
10
+ import { executeTransfer, previewTransfer } from '../../worktrees';
11
+ import type { MergeResolution } from '../../worktrees';
12
+ import { ws } from '$backend/utils/ws';
13
+ import { debug } from '$shared/utils/logger';
14
+ import { requireWorktreeAccess } from './crud';
15
+
16
+ const directionSchema = t.Union([t.Literal('apply'), t.Literal('sync')]);
17
+
18
+ const changeSchema = t.Object({
19
+ path: t.String(),
20
+ status: t.Union([t.Literal('added'), t.Literal('modified'), t.Literal('deleted')]),
21
+ conflict: t.Boolean(),
22
+ autoMergeable: t.Boolean()
23
+ });
24
+
25
+ export const worktreeTransferHandler = createRouter()
26
+ /** Phase 1: what would change, and what needs a decision. */
27
+ .http('worktrees:preview-transfer', {
28
+ data: t.Object({
29
+ id: t.String({ minLength: 1 }),
30
+ direction: directionSchema
31
+ }),
32
+ response: t.Object({
33
+ direction: directionSchema,
34
+ changes: t.Array(changeSchema),
35
+ conflicts: t.Array(t.Object({
36
+ ...changeSchema.properties,
37
+ sourceContent: t.Optional(t.String()),
38
+ targetContent: t.Optional(t.String())
39
+ }))
40
+ })
41
+ }, async ({ data, conn }) => {
42
+ const worktree = requireWorktreeAccess(conn, data.id);
43
+ const preview = await previewTransfer(worktree.id, data.direction);
44
+
45
+ debug.log(
46
+ 'worktree',
47
+ `Preview ${data.direction} for ${worktree.name}: ${preview.changes.length} changes, ${preview.conflicts.length} conflicts`
48
+ );
49
+
50
+ return preview;
51
+ })
52
+
53
+ /** Phase 2: carry the changes across using the user's resolutions. */
54
+ .http('worktrees:transfer', {
55
+ data: t.Object({
56
+ id: t.String({ minLength: 1 }),
57
+ direction: directionSchema,
58
+ resolutions: t.Optional(t.Record(
59
+ t.String(),
60
+ t.Union([t.Literal('source'), t.Literal('target'), t.Literal('merge')])
61
+ ))
62
+ }),
63
+ response: t.Object({
64
+ written: t.Number(),
65
+ deleted: t.Number(),
66
+ skipped: t.Number(),
67
+ failed: t.Array(t.String())
68
+ })
69
+ }, async ({ data, conn }) => {
70
+ const worktree = requireWorktreeAccess(conn, data.id);
71
+
72
+ const result = await executeTransfer(
73
+ worktree.id,
74
+ data.direction,
75
+ (data.resolutions ?? {}) as Record<string, MergeResolution>
76
+ );
77
+
78
+ ws.emit.project(worktree.project_id, 'worktrees:transferred', {
79
+ worktreeId: worktree.id,
80
+ projectId: worktree.project_id,
81
+ direction: data.direction,
82
+ written: result.written,
83
+ deleted: result.deleted,
84
+ skipped: result.skipped
85
+ });
86
+
87
+ return result;
88
+ });
@@ -1 +1 @@
1
- import{s as _,_ as d,r as s,a as u}from"./main-ZCojSzvW.js";import{C as T,P as y,W as E,d as L,b as g,c as v,h as P,l as b,m as k,e as D,n as O,f as R,g as S,t as V}from"./main-ZCojSzvW.js";async function h(o,e={}){const i=e.loading===!1?void 0:_(o,e.loadingText??"Loading…"),[{Terminal:l},{FitAddon:c}]=await Promise.all([d(()=>import("./xterm-B-qIQCd3.js"),[]),d(()=>import("./addon-fit-DX4qG4td.js"),[])]).catch(r=>{throw i?.(),r}),a=new l({scrollback:e.scrollback??5e3,fontSize:e.fontSize??13,fontFamily:e.fontFamily??"ui-monospace, SFMono-Regular, Menlo, monospace",lineHeight:e.lineHeight??1,cursorBlink:e.cursorBlink??!1,cursorStyle:e.cursorStyle??"block",disableStdin:e.stdin!==!0,allowProposedApi:!0,convertEol:!0,theme:s(e.theme),...e.cols?{cols:e.cols}:{},...e.rows?{rows:e.rows}:{},...e.terminalOptions??{}}),t=e.fit===!1?void 0:new c;if(t&&a.loadAddon(t),e.clipboard)try{const{ClipboardAddon:r}=await d(()=>import("./addon-clipboard-wHJhZAA4.js"),[]);a.loadAddon(new r)}catch{}if(e.webLinks)try{const{WebLinksAddon:r}=await d(()=>import("./addon-web-links-DIbG5aQx.js"),[]);a.loadAddon(new r)}catch{}if(e.unicode11)try{const{Unicode11Addon:r}=await d(()=>import("./addon-unicode11-Bt8F3D7-.js"),[]);a.loadAddon(new r),a.unicode.activeVersion="11"}catch{}for(const r of e.addons??[])a.loadAddon(r);if(a.open(o),e.ligatures)try{const{LigaturesAddon:r}=await d(()=>import("./addon-ligatures-DpDY8N_X.js"),[]);a.loadAddon(new r)}catch{}const m=t?u({resize:async()=>{}},a,t,{debounceMs:e.fitDebounceMs??100}):void 0;e.onReady?.(a),i?.();let n=!1;return{terminal:a,fitAddon:t,write:r=>a.write(r),clear:()=>{a.clear(),a.reset()},fit:()=>t?.fit(),setTheme:r=>{a.options.theme=s(r)},dispose(){n||(n=!0,m?.(),a.dispose())}}}export{T as ClientSession,y as PtyKitClient,E as WsCore,u as attachFit,L as darkTheme,g as defaultPersistence,v as draculaTheme,P as hostSocket,b as lightTheme,k as matrixTheme,D as mountTerminal,h as mountViewer,O as nordTheme,s as resolveTheme,_ as showLoadingOverlay,R as solarizedDarkTheme,S as solarizedLightTheme,V as themes};
1
+ import{s as _,_ as d,r as s,a as u}from"./main-BofFsH8E.js";import{C as T,P as y,W as E,d as L,b as g,c as v,h as P,l as b,m as k,e as D,n as O,f as R,g as S,t as V}from"./main-BofFsH8E.js";async function h(o,e={}){const i=e.loading===!1?void 0:_(o,e.loadingText??"Loading…"),[{Terminal:l},{FitAddon:c}]=await Promise.all([d(()=>import("./xterm-B-qIQCd3.js"),[]),d(()=>import("./addon-fit-DX4qG4td.js"),[])]).catch(r=>{throw i?.(),r}),a=new l({scrollback:e.scrollback??5e3,fontSize:e.fontSize??13,fontFamily:e.fontFamily??"ui-monospace, SFMono-Regular, Menlo, monospace",lineHeight:e.lineHeight??1,cursorBlink:e.cursorBlink??!1,cursorStyle:e.cursorStyle??"block",disableStdin:e.stdin!==!0,allowProposedApi:!0,convertEol:!0,theme:s(e.theme),...e.cols?{cols:e.cols}:{},...e.rows?{rows:e.rows}:{},...e.terminalOptions??{}}),t=e.fit===!1?void 0:new c;if(t&&a.loadAddon(t),e.clipboard)try{const{ClipboardAddon:r}=await d(()=>import("./addon-clipboard-wHJhZAA4.js"),[]);a.loadAddon(new r)}catch{}if(e.webLinks)try{const{WebLinksAddon:r}=await d(()=>import("./addon-web-links-DIbG5aQx.js"),[]);a.loadAddon(new r)}catch{}if(e.unicode11)try{const{Unicode11Addon:r}=await d(()=>import("./addon-unicode11-Bt8F3D7-.js"),[]);a.loadAddon(new r),a.unicode.activeVersion="11"}catch{}for(const r of e.addons??[])a.loadAddon(r);if(a.open(o),e.ligatures)try{const{LigaturesAddon:r}=await d(()=>import("./addon-ligatures-DpDY8N_X.js"),[]);a.loadAddon(new r)}catch{}const m=t?u({resize:async()=>{}},a,t,{debounceMs:e.fitDebounceMs??100}):void 0;e.onReady?.(a),i?.();let n=!1;return{terminal:a,fitAddon:t,write:r=>a.write(r),clear:()=>{a.clear(),a.reset()},fit:()=>t?.fit(),setTheme:r=>{a.options.theme=s(r)},dispose(){n||(n=!0,m?.(),a.dispose())}}}export{T as ClientSession,y as PtyKitClient,E as WsCore,u as attachFit,L as darkTheme,g as defaultPersistence,v as draculaTheme,P as hostSocket,b as lightTheme,k as matrixTheme,D as mountTerminal,h as mountViewer,O as nordTheme,s as resolveTheme,_ as showLoadingOverlay,R as solarizedDarkTheme,S as solarizedLightTheme,V as themes};