@myrialabs/clopen 0.4.35 → 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 (82) hide show
  1. package/backend/artifacts/sync.test.ts +63 -0
  2. package/backend/artifacts/sync.ts +56 -3
  3. package/backend/database/migrations/070_create_worktrees_table.ts +67 -0
  4. package/backend/database/migrations/index.ts +7 -0
  5. package/backend/database/queries/index.ts +1 -0
  6. package/backend/database/queries/session-queries.ts +50 -11
  7. package/backend/database/queries/worktree-queries.ts +148 -0
  8. package/backend/engine/adapters/opencode/server.ts +389 -83
  9. package/backend/engine/adapters/opencode/stream.ts +14 -14
  10. package/backend/engine/hot-reload.ts +25 -10
  11. package/backend/files/file-watcher.ts +35 -9
  12. package/backend/host/metrics.test.ts +110 -0
  13. package/backend/host/metrics.ts +235 -0
  14. package/backend/index.ts +5 -2
  15. package/backend/mcp/internal/servers/browser-automation/context.ts +16 -2
  16. package/backend/ports/attribute.test.ts +3 -2
  17. package/backend/ports/attribute.ts +5 -44
  18. package/backend/preview/browser/browser-pool.ts +81 -0
  19. package/backend/preview/browser/browser-preview-service.ts +142 -32
  20. package/backend/preview/browser/browser-tab-manager.ts +350 -113
  21. package/backend/preview/browser/types.ts +9 -0
  22. package/backend/projects/project-cleanup.integration.test.ts +1 -1
  23. package/backend/projects/project-cleanup.ts +7 -1
  24. package/backend/projects/shell-ownership.ts +65 -0
  25. package/backend/snapshot/snapshot-service.ts +6 -2
  26. package/backend/terminal/ptykit.ts +35 -6
  27. package/backend/utils/ws.ts +21 -1
  28. package/backend/worktrees/clone.ts +222 -0
  29. package/backend/worktrees/index.ts +29 -0
  30. package/backend/worktrees/merge.test.ts +93 -0
  31. package/backend/worktrees/merge.ts +232 -0
  32. package/backend/worktrees/paths.test.ts +60 -0
  33. package/backend/worktrees/paths.ts +60 -0
  34. package/backend/worktrees/resolve.ts +67 -0
  35. package/backend/worktrees/service.ts +315 -0
  36. package/backend/worktrees/tree.ts +59 -0
  37. package/backend/ws/access.ts +18 -0
  38. package/backend/ws/artifacts/generate.ts +2 -2
  39. package/backend/ws/chat/stream.ts +9 -2
  40. package/backend/ws/files/panel-state-scope.test.ts +102 -0
  41. package/backend/ws/files/path-access.test.ts +93 -1
  42. package/backend/ws/files/path-access.ts +54 -5
  43. package/backend/ws/files/read.ts +15 -10
  44. package/backend/ws/files/search.ts +7 -7
  45. package/backend/ws/files/state.ts +70 -8
  46. package/backend/ws/files/watch.ts +16 -14
  47. package/backend/ws/git/branch-name.ts +3 -3
  48. package/backend/ws/git/branch.ts +15 -15
  49. package/backend/ws/git/commit-message.ts +3 -3
  50. package/backend/ws/git/commit.ts +17 -17
  51. package/backend/ws/git/conflict.ts +10 -10
  52. package/backend/ws/git/diff.ts +9 -9
  53. package/backend/ws/git/ignored.ts +9 -9
  54. package/backend/ws/git/log.ts +3 -3
  55. package/backend/ws/git/remote.ts +43 -43
  56. package/backend/ws/git/staging.ts +16 -16
  57. package/backend/ws/git/status.ts +13 -13
  58. package/backend/ws/index.ts +4 -0
  59. package/backend/ws/preview/access.ts +11 -3
  60. package/backend/ws/projects/index.ts +5 -1
  61. package/backend/ws/projects/info.test.ts +54 -0
  62. package/backend/ws/projects/info.ts +398 -0
  63. package/backend/ws/sessions/crud.ts +21 -6
  64. package/backend/ws/snapshot/restore.ts +11 -14
  65. package/backend/ws/system/device-info.ts +62 -144
  66. package/backend/ws/worktrees/crud.ts +187 -0
  67. package/backend/ws/worktrees/index.ts +33 -0
  68. package/backend/ws/worktrees/transfer.ts +88 -0
  69. package/dist/assets/{index-B0iIhSO9.js → index-Bg-SUCFg.js} +1 -1
  70. package/dist/assets/{index-BRJqss6F.js → index-Cz4YpHVi.js} +1 -1
  71. package/dist/assets/main-9G7IpQpK.css +1 -0
  72. package/dist/assets/main-BofFsH8E.js +1085 -0
  73. package/dist/index.html +2 -2
  74. package/package.json +1 -1
  75. package/shared/types/database/schema.ts +26 -0
  76. package/shared/utils/logger.ts +1 -0
  77. package/shared/utils/workspace-scope.test.ts +80 -0
  78. package/shared/utils/workspace-scope.ts +57 -0
  79. package/shared/utils/ws-client.ts +25 -5
  80. package/shared/utils/ws-server.ts +19 -3
  81. package/dist/assets/main-Buko4D0t.css +0 -1
  82. package/dist/assets/main-C_iGUZyL.js +0 -1078
@@ -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,42 +24,7 @@ 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';
24
-
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
- /** Timeout helper: race a promise against a deadline, return fallback on timeout. */
42
- function withTimeout<T>(promise: Promise<T>, ms: number, fallback: T): Promise<T> {
43
- let timer: ReturnType<typeof setTimeout> | undefined;
44
- const timeout = new Promise<T>((_, reject) => {
45
- timer = setTimeout(() => reject(new Error(`timeout after ${ms}ms`)), ms);
46
- });
47
- return Promise.race([promise, timeout])
48
- .then((v) => {
49
- clearTimeout(timer);
50
- return v;
51
- })
52
- .catch(() => {
53
- clearTimeout(timer);
54
- return fallback;
55
- });
56
- }
57
-
58
- /** Static facts don't change while the process runs — resolve them once. */
59
- let staticInfoPromise: Promise<StaticInfo> | null = null;
27
+ import { getHostFacts, withTimeout } from '../../host/metrics';
60
28
 
61
29
  /** Last-good caches for dynamic probes: prevents transient WMI timeouts from
62
30
  * flickering the UI between "This Device" <-> "Server" or dropping Storage cards. */
@@ -67,60 +35,6 @@ let lastLoadCache: Systeminformation.CurrentLoadData | null = null;
67
35
  let lastGraphicsCache: Systeminformation.GraphicsData | null = null;
68
36
  let lastNetCache: Systeminformation.NetworkInterfacesData | null = null;
69
37
 
70
- async function getStaticInfo(): Promise<StaticInfo> {
71
- if (!staticInfoPromise) {
72
- staticInfoPromise = (async () => {
73
- const fallbackOs = {
74
- hostname: os.hostname(),
75
- platform: os.platform(),
76
- distro: '',
77
- release: os.release(),
78
- kernel: os.version(),
79
- arch: os.arch()
80
- } as unknown as Systeminformation.OsData;
81
- const fallbackCpu = {
82
- brand: '',
83
- manufacturer: '',
84
- physicalCores: os.cpus().length,
85
- cores: os.cpus().length,
86
- speed: 0
87
- } as unknown as Systeminformation.CpuData;
88
- const fallbackSystem = { virtual: false } as unknown as Systeminformation.SystemData;
89
- const fallbackGraphics = { controllers: [] } as unknown as Systeminformation.GraphicsData;
90
- const [osInfo, cpu, system, graphics] = await Promise.all([
91
- withTimeout(si.osInfo(), 4000, fallbackOs),
92
- withTimeout(si.cpu(), 4000, fallbackCpu),
93
- withTimeout(si.system(), 4000, fallbackSystem),
94
- withTimeout(si.graphics(), 4000, fallbackGraphics)
95
- ]);
96
- return {
97
- hostname: (osInfo?.hostname || os.hostname()) as string,
98
- platform: (osInfo?.platform || os.platform()) as string,
99
- distro: (osInfo?.distro || '') as string,
100
- release: (osInfo?.release || os.release()) as string,
101
- kernel: (osInfo?.kernel || os.version()) as string,
102
- arch: (osInfo?.arch || os.arch()) as string,
103
- isVirtual: Boolean(system?.virtual),
104
- cpuBrand: (cpu?.brand || '') as string,
105
- cpuManufacturer: (cpu?.manufacturer || '') as string,
106
- physicalCores: (cpu?.physicalCores || cpu?.cores || os.cpus().length) as number,
107
- logicalCores: (cpu?.cores || os.cpus().length) as number,
108
- cpuSpeedGhz: typeof cpu?.speed === 'number' && cpu.speed > 0 ? cpu.speed : null,
109
- gpus: graphics.controllers.map((c) => ({
110
- model: c.model || 'Unknown GPU',
111
- vendor: c.vendor || 'Unknown',
112
- vramMb: typeof c.vram === 'number' && c.vram > 0 ? c.vram : null
113
- }))
114
- };
115
- })().catch((err) => {
116
- // Don't cache a failed probe — allow the next request to retry.
117
- staticInfoPromise = null;
118
- throw err;
119
- });
120
- }
121
- return staticInfoPromise;
122
- }
123
-
124
38
  const GpuSchema = t.Object({
125
39
  model: t.String(),
126
40
  vendor: t.String(),
@@ -253,40 +167,40 @@ export const deviceInfoHandler = createRouter()
253
167
  disks: t.Array(DiskSchema)
254
168
  })
255
169
  }, async () => {
256
- const staticInfo = await getStaticInfo();
170
+ const facts = await getHostFacts();
257
171
 
258
172
  const [load, mem, battery, graphics, fsSize, netDefault] = await Promise.all([
259
- withTimeout(si.currentLoad(), 3500, null as unknown as Systeminformation.CurrentLoadData | null),
260
- withTimeout(si.mem(), 3500, null as unknown as Systeminformation.MemData | null),
261
- withTimeout(si.battery(), 3500, null as unknown as Systeminformation.BatteryData | null),
262
- withTimeout(si.graphics(), 3500, null as unknown as Systeminformation.GraphicsData | null),
263
- withTimeout(si.fsSize(), 3500, null as unknown as Systeminformation.FsSizeData[] | null),
264
- withTimeout(si.networkInterfaces('default'), 3500, null as unknown as Systeminformation.NetworkInterfacesData | null)
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)
265
179
  ]);
266
180
 
267
181
  // Update last-good caches; reuse them when a probe times out so the UI
268
182
  // doesn't flicker between "This Device" <-> "Server" or drop Storage cards.
269
- if (mem) lastMemCache = mem as unknown as Systeminformation.MemData;
270
- if (battery) lastBatteryCache = battery as unknown as Systeminformation.BatteryData;
271
- if (fsSize) lastFsSizeCache = fsSize as unknown as Systeminformation.FsSizeData[];
272
- if (load) lastLoadCache = load as unknown as Systeminformation.CurrentLoadData;
273
- if (graphics) lastGraphicsCache = graphics as unknown as Systeminformation.GraphicsData;
274
- if (netDefault) lastNetCache = (Array.isArray(netDefault) ? netDefault[0] : netDefault) as unknown as Systeminformation.NetworkInterfacesData;
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;
275
189
 
276
- const memEff = (mem as unknown as Systeminformation.MemData) ?? lastMemCache;
277
- const batteryEff = (battery as unknown as Systeminformation.BatteryData) ?? lastBatteryCache;
278
- const fsSizeEff = (fsSize as unknown as Systeminformation.FsSizeData[]) ?? lastFsSizeCache ?? [];
279
- const loadEff = (load as unknown as Systeminformation.CurrentLoadData) ?? lastLoadCache;
280
- const graphicsEff = (graphics as unknown as Systeminformation.GraphicsData) ?? lastGraphicsCache ?? { controllers: [] } as unknown as Systeminformation.GraphicsData;
281
- const netRawEff = (netDefault as unknown as Systeminformation.NetworkInterfacesData | null) ?? lastNetCache;
282
- const net = Array.isArray(netRawEff) ? netRawEff[0] : (netRawEff as unknown as Systeminformation.NetworkInterfacesData | null);
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;
283
197
 
284
198
  // avgLoad is 0/undefined on platforms without load average (e.g. Windows).
285
- const loadAvg1 = typeof (loadEff as unknown as { avgLoad?: number })?.avgLoad === 'number' && (loadEff as unknown as { avgLoad: number }).avgLoad > 0 ? (loadEff as unknown as { avgLoad: number }).avgLoad : null;
199
+ const loadAvg1 = typeof loadEff?.avgLoad === 'number' && loadEff.avgLoad > 0 ? loadEff.avgLoad : null;
286
200
 
287
201
  // Pair live GPU utilization with the cached controller identity by index.
288
- const gpus = staticInfo.gpus.map((g, i) => {
289
- const live = (graphicsEff as Systeminformation.GraphicsData)?.controllers?.[i];
202
+ const gpus = facts.gpus.map((g, i) => {
203
+ const live = graphicsEff?.controllers?.[i];
290
204
  return {
291
205
  model: g.model,
292
206
  vendor: g.vendor,
@@ -298,46 +212,50 @@ export const deviceInfoHandler = createRouter()
298
212
  });
299
213
 
300
214
  // Show only the primary disk(s); collapses macOS APFS synthetic volumes.
301
- const disks = selectPrimaryDisks((fsSizeEff as Systeminformation.FsSizeData[]) || [], staticInfo.platform);
215
+ const disks = selectPrimaryDisks(fsSizeEff, facts.platform);
302
216
 
303
217
  return {
304
- hostname: staticInfo.hostname,
305
- platform: staticInfo.platform,
306
- distro: staticInfo.distro,
307
- release: staticInfo.release,
308
- kernel: staticInfo.kernel,
309
- arch: staticInfo.arch,
310
- 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,
311
225
  uptimeSec: os.uptime(),
312
226
  cpu: {
313
- brand: staticInfo.cpuBrand,
314
- manufacturer: staticInfo.cpuManufacturer,
315
- physicalCores: staticInfo.physicalCores,
316
- logicalCores: staticInfo.logicalCores,
317
- speedGhz: staticInfo.cpuSpeedGhz,
318
- loadPercent: typeof (loadEff as unknown as { currentLoad?: number })?.currentLoad === 'number' ? (loadEff as unknown as { currentLoad: number }).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,
319
235
  loadAvg1
320
236
  },
321
237
  memory: {
322
- totalBytes: (memEff as unknown as Systeminformation.MemData)?.total ?? os.totalmem(),
323
- usedBytes: (memEff as unknown as Systeminformation.MemData)?.active ?? os.totalmem() - os.freemem(),
324
- freeBytes: (memEff as unknown as Systeminformation.MemData)?.available ?? os.freemem(),
325
- swapTotalBytes: (memEff as unknown as Systeminformation.MemData)?.swaptotal ?? 0,
326
- swapUsedBytes: (memEff as unknown as Systeminformation.MemData)?.swapused ?? 0
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
327
245
  },
328
246
  network: {
329
- iface: (net as unknown as { iface?: string })?.iface || '',
330
- ip4: (net as unknown as { ip4?: string })?.ip4 || '',
331
- mac: (net as unknown as { mac?: string })?.mac || ''
247
+ iface: net?.iface || '',
248
+ ip4: net?.ip4 || '',
249
+ mac: net?.mac || ''
332
250
  },
333
251
  battery: {
334
- hasBattery: Boolean((batteryEff as unknown as Systeminformation.BatteryData)?.hasBattery),
335
- percent: typeof (batteryEff as unknown as Systeminformation.BatteryData)?.percent === 'number' && (batteryEff as unknown as Systeminformation.BatteryData)?.hasBattery ? (batteryEff as unknown as Systeminformation.BatteryData).percent : null,
336
- isCharging: Boolean((batteryEff as unknown as Systeminformation.BatteryData)?.isCharging),
337
- acConnected: Boolean((batteryEff as unknown as Systeminformation.BatteryData)?.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),
338
256
  timeRemainingMinutes:
339
- typeof (batteryEff as unknown as Systeminformation.BatteryData)?.timeRemaining === 'number' && (batteryEff as unknown as Systeminformation.BatteryData).timeRemaining > 0
340
- ? (batteryEff as unknown as Systeminformation.BatteryData).timeRemaining
257
+ typeof batteryEff?.timeRemaining === 'number' && batteryEff.timeRemaining > 0
258
+ ? batteryEff.timeRemaining
341
259
  : null
342
260
  },
343
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-C_iGUZyL.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-C_iGUZyL.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};