@myrialabs/clopen 0.4.35 → 0.4.37

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 (91) 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/git/conflict-state.test.ts +396 -0
  13. package/backend/git/git-executor.ts +6 -0
  14. package/backend/git/git-parser.ts +144 -48
  15. package/backend/git/git-service.ts +727 -57
  16. package/backend/git/push-target.test.ts +264 -0
  17. package/backend/host/metrics.test.ts +110 -0
  18. package/backend/host/metrics.ts +235 -0
  19. package/backend/index.ts +5 -2
  20. package/backend/mcp/internal/servers/browser-automation/context.ts +16 -2
  21. package/backend/ports/attribute.test.ts +3 -2
  22. package/backend/ports/attribute.ts +5 -44
  23. package/backend/preview/browser/browser-pool.ts +81 -0
  24. package/backend/preview/browser/browser-preview-service.ts +142 -32
  25. package/backend/preview/browser/browser-tab-manager.ts +350 -113
  26. package/backend/preview/browser/types.ts +9 -0
  27. package/backend/project/status-manager.ts +20 -0
  28. package/backend/projects/project-cleanup.integration.test.ts +1 -1
  29. package/backend/projects/project-cleanup.ts +7 -1
  30. package/backend/projects/shell-ownership.ts +65 -0
  31. package/backend/snapshot/snapshot-service.ts +6 -2
  32. package/backend/terminal/ptykit.ts +35 -6
  33. package/backend/utils/ws.ts +21 -1
  34. package/backend/worktrees/clone.ts +222 -0
  35. package/backend/worktrees/index.ts +29 -0
  36. package/backend/worktrees/merge.test.ts +93 -0
  37. package/backend/worktrees/merge.ts +232 -0
  38. package/backend/worktrees/paths.test.ts +60 -0
  39. package/backend/worktrees/paths.ts +60 -0
  40. package/backend/worktrees/resolve.ts +67 -0
  41. package/backend/worktrees/service.ts +315 -0
  42. package/backend/worktrees/tree.ts +59 -0
  43. package/backend/ws/access.ts +18 -0
  44. package/backend/ws/artifacts/generate.ts +2 -2
  45. package/backend/ws/chat/stream.ts +9 -2
  46. package/backend/ws/files/panel-state-scope.test.ts +102 -0
  47. package/backend/ws/files/path-access.test.ts +93 -1
  48. package/backend/ws/files/path-access.ts +54 -5
  49. package/backend/ws/files/read.ts +15 -10
  50. package/backend/ws/files/search.ts +7 -7
  51. package/backend/ws/files/state.ts +70 -8
  52. package/backend/ws/files/watch.ts +16 -14
  53. package/backend/ws/git/branch-name.ts +9 -8
  54. package/backend/ws/git/branch.ts +58 -16
  55. package/backend/ws/git/commit-message.ts +16 -13
  56. package/backend/ws/git/commit.ts +17 -17
  57. package/backend/ws/git/conflict.ts +116 -13
  58. package/backend/ws/git/diff-budget.test.ts +125 -0
  59. package/backend/ws/git/diff-budget.ts +220 -0
  60. package/backend/ws/git/diff.ts +9 -9
  61. package/backend/ws/git/ignored.ts +9 -9
  62. package/backend/ws/git/log.ts +28 -3
  63. package/backend/ws/git/remote.ts +118 -44
  64. package/backend/ws/git/staging.ts +16 -16
  65. package/backend/ws/git/status.ts +13 -13
  66. package/backend/ws/index.ts +4 -0
  67. package/backend/ws/preview/access.ts +11 -3
  68. package/backend/ws/projects/index.ts +5 -1
  69. package/backend/ws/projects/info.test.ts +54 -0
  70. package/backend/ws/projects/info.ts +398 -0
  71. package/backend/ws/sessions/crud.ts +21 -6
  72. package/backend/ws/snapshot/restore.ts +11 -14
  73. package/backend/ws/system/device-info.ts +62 -144
  74. package/backend/ws/worktrees/crud.ts +187 -0
  75. package/backend/ws/worktrees/index.ts +33 -0
  76. package/backend/ws/worktrees/transfer.ts +88 -0
  77. package/dist/assets/{index-BRJqss6F.js → index-Bik9TCBi.js} +1 -1
  78. package/dist/assets/{index-B0iIhSO9.js → index-sJmS_CCm.js} +1 -1
  79. package/dist/assets/main-DLqolBI2.css +1 -0
  80. package/dist/assets/main-Df1I3hnw.js +1096 -0
  81. package/dist/index.html +2 -2
  82. package/package.json +1 -1
  83. package/shared/types/database/schema.ts +26 -0
  84. package/shared/types/git.ts +123 -0
  85. package/shared/utils/logger.ts +1 -0
  86. package/shared/utils/workspace-scope.test.ts +80 -0
  87. package/shared/utils/workspace-scope.ts +57 -0
  88. package/shared/utils/ws-client.ts +25 -5
  89. package/shared/utils/ws-server.ts +19 -3
  90. package/dist/assets/main-Buko4D0t.css +0 -1
  91. package/dist/assets/main-C_iGUZyL.js +0 -1078
@@ -2,6 +2,7 @@ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:pat
2
2
  import { realpath } from 'node:fs/promises';
3
3
 
4
4
  import { projectQueries } from '../../database/queries/project-queries';
5
+ import { worktreeQueries } from '../../database/queries/worktree-queries';
5
6
  import { ws } from '$backend/utils/ws';
6
7
  import type { WSConnection } from '$shared/utils/ws-server';
7
8
  import type { Project } from '$shared/types/database/schema';
@@ -36,15 +37,56 @@ async function isPathInside(rootPath: string, candidatePath: string): Promise<bo
36
37
  return rel === '' || (!!rel && !rel.startsWith('..') && !isAbsolute(rel));
37
38
  }
38
39
 
39
- export function requireProjectPathAccess(conn: WSConnection, projectPath: string): Project {
40
- const project = projectQueries.getByPath(projectPath);
40
+ /**
41
+ * Resolve a workspace root to the project that owns it.
42
+ *
43
+ * A worktree root is not a registered project, so a plain project lookup
44
+ * rejects it — which is what made the Files panel deny access to every path
45
+ * inside a worktree.
46
+ */
47
+ export function resolveProjectForRoot(rootPath: string): Project | null {
48
+ const project = projectQueries.getByPath(rootPath);
49
+ if (project) return project;
50
+
51
+ const worktree = worktreeQueries.getByPath(rootPath);
52
+ if (!worktree) return null;
53
+
54
+ return projectQueries.getById(worktree.project_id);
55
+ }
56
+
57
+ export interface WorkspaceRoot {
58
+ /** The project that owns the workspace — what access is decided on. */
59
+ project: Project;
60
+ /** The directory the caller asked for: the project, or one of its worktrees. */
61
+ root: string;
62
+ worktreeId: string | null;
63
+ }
64
+
65
+ /**
66
+ * Grant access to a workspace root and hand back the root that was requested.
67
+ *
68
+ * Returning the root rather than only the project is the point: callers used to
69
+ * validate a path and then operate on `project.path`, which was identical until
70
+ * worktrees existed and silently became "list the main tree" afterwards.
71
+ */
72
+ export function requireWorkspaceRootAccess(conn: WSConnection, rootPath: string): WorkspaceRoot {
73
+ const worktree = worktreeQueries.getByPath(rootPath);
74
+ const project = worktree
75
+ ? projectQueries.getById(worktree.project_id)
76
+ : projectQueries.getByPath(rootPath);
77
+
41
78
  if (!project) {
42
79
  throw new Error('Access denied');
43
80
  }
44
- if (ws.getRole(conn) === 'admin') {
45
- return project;
81
+ if (ws.getRole(conn) !== 'admin') {
82
+ requireProjectAccess(conn, project.id);
46
83
  }
47
- return requireProjectAccess(conn, project.id);
84
+
85
+ return {
86
+ project,
87
+ root: worktree ? worktree.path : project.path,
88
+ worktreeId: worktree?.id ?? null
89
+ };
48
90
  }
49
91
 
50
92
  export async function requireFilePathAccess(conn: WSConnection, filePath: string): Promise<string> {
@@ -65,11 +107,18 @@ export async function requireFilePathAccessFor(filePath: string, role: string |
65
107
  throw new Error('Access denied');
66
108
  }
67
109
 
110
+ // A project's accessible area is its own tree plus every worktree cloned
111
+ // from it — both are workspaces the user is already entitled to.
68
112
  const projects = projectQueries.getAllForUser(userId);
69
113
  for (const project of projects) {
70
114
  if (await isPathInside(project.path, normalizedPath)) {
71
115
  return normalizedPath;
72
116
  }
117
+ for (const worktree of worktreeQueries.getByProjectId(project.id)) {
118
+ if (await isPathInside(worktree.path, normalizedPath)) {
119
+ return normalizedPath;
120
+ }
121
+ }
73
122
  }
74
123
 
75
124
  throw new Error('Access denied');
@@ -26,7 +26,7 @@ import { requireProjectAccess } from '../access';
26
26
  import {
27
27
  filterAccessibleExpandedPaths,
28
28
  requireFilePathAccess,
29
- requireProjectPathAccess,
29
+ requireWorkspaceRootAccess,
30
30
  requireSharedFilePathAccess
31
31
  } from './path-access';
32
32
 
@@ -72,8 +72,9 @@ export const readHandler = createRouter()
72
72
  ])
73
73
  )
74
74
  }, async ({ data, conn }) => {
75
- const project = requireProjectPathAccess(conn, data.project_path);
76
- const projectPath = project.path;
75
+ // The requested root, not the project's: for a worktree these differ, and
76
+ // listing the project would hand back the main tree's files and paths.
77
+ const { root: projectPath } = requireWorkspaceRootAccess(conn, data.project_path);
77
78
 
78
79
  if (!(await existsSync(projectPath))) {
79
80
  throw new Error('Project path does not exist');
@@ -186,6 +187,8 @@ export const readHandler = createRouter()
186
187
  .http('files:read-file-at', {
187
188
  data: t.Object({
188
189
  projectId: t.String(),
190
+ // Workspace root the file lives in; absent means the project itself.
191
+ rootPath: t.Optional(t.String()),
189
192
  filePath: t.String(),
190
193
  ref: t.Optional(t.String())
191
194
  }),
@@ -194,16 +197,18 @@ export const readHandler = createRouter()
194
197
  ref: t.String()
195
198
  })
196
199
  }, async ({ data, conn }) => {
197
- requireProjectAccess(conn, data.projectId);
198
- const project = projectQueries.getById(data.projectId);
199
- if (!project) throw new Error('Access denied');
200
+ // A worktree is its own checkout, so the gutter diff has to resolve
201
+ // against the tree the file is in rather than the project's.
202
+ const { root } = data.rootPath
203
+ ? requireWorkspaceRootAccess(conn, data.rootPath)
204
+ : { root: requireProjectAccess(conn, data.projectId).path };
200
205
 
201
206
  const ref = data.ref || 'HEAD';
202
207
 
203
- // Make filePath relative to project root for `git show`
208
+ // Make filePath relative to the workspace root for `git show`
204
209
  let relativePath = data.filePath;
205
210
  if (isAbsolute(data.filePath)) {
206
- relativePath = relative(project.path, data.filePath);
211
+ relativePath = relative(root, data.filePath);
207
212
  }
208
213
  // Normalize path separators for git
209
214
  relativePath = relativePath.replace(/\\/g, '/');
@@ -212,8 +217,8 @@ export const readHandler = createRouter()
212
217
  // repo's `git show HEAD:file` returns nothing for files tracked
213
218
  // inside a nested repo and gitignored by the parent, so the editor
214
219
  // gutter diff would silently go empty for subrepo files without this.
215
- const repo = await findRepoForFile(project.path, relativePath);
216
- const cwd = repo?.repoPath ?? project.path;
220
+ const repo = await findRepoForFile(root, relativePath);
221
+ const cwd = repo?.repoPath ?? root;
217
222
  const gitFilePath = repo?.relativeFilePath ?? relativePath;
218
223
 
219
224
  const content = await gitService.getFileAtRef(cwd, ref, gitFilePath);
@@ -3,7 +3,7 @@ import { createRouter } from '$shared/utils/ws-server';
3
3
  import { debug } from '$shared/utils/logger';
4
4
  import { join, extname, basename, relative } from 'path';
5
5
  import { readdir } from 'fs/promises';
6
- import { requireProjectPathAccess } from './path-access';
6
+ import { requireWorkspaceRootAccess } from './path-access';
7
7
  import { validateFileSize } from '../../files/file-size-limit';
8
8
 
9
9
  // Heuristic patterns that indicate potential ReDoS risk:
@@ -407,13 +407,13 @@ export const fileSearchHandler = createRouter()
407
407
  response: t.Array(FileSearchResultSchema)
408
408
  }, async ({ data, conn }) => {
409
409
  const { project_path, query } = data;
410
- const project = requireProjectPathAccess(conn, project_path);
410
+ const { root } = requireWorkspaceRootAccess(conn, project_path);
411
411
 
412
412
  if (!query || query.trim().length === 0) {
413
413
  return [];
414
414
  }
415
415
 
416
- return await searchFilesByName(project.path, query);
416
+ return await searchFilesByName(root, query);
417
417
  })
418
418
  .http('files:search-code', {
419
419
  data: t.Object({
@@ -446,13 +446,13 @@ export const fileSearchHandler = createRouter()
446
446
  include_pattern,
447
447
  exclude_pattern
448
448
  } = data;
449
- const project = requireProjectPathAccess(conn, project_path);
449
+ const { root } = requireWorkspaceRootAccess(conn, project_path);
450
450
 
451
451
  if (!query || query.trim().length === 0) {
452
452
  return [];
453
453
  }
454
454
 
455
- return await searchCodeContent(project.path, query, {
455
+ return await searchCodeContent(root, query, {
456
456
  caseSensitive: case_sensitive,
457
457
  wholeWord: whole_word,
458
458
  useRegex: use_regex,
@@ -491,13 +491,13 @@ export const fileSearchHandler = createRouter()
491
491
  include_pattern,
492
492
  exclude_pattern
493
493
  } = data;
494
- const project = requireProjectPathAccess(conn, project_path);
494
+ const { root } = requireWorkspaceRootAccess(conn, project_path);
495
495
 
496
496
  if (!search_query || search_query.trim().length === 0) {
497
497
  return { results: [], totalReplacements: 0, totalFiles: 0 };
498
498
  }
499
499
 
500
- const results = await replaceInFiles(project.path, search_query, replace_with, {
500
+ const results = await replaceInFiles(root, search_query, replace_with, {
501
501
  caseSensitive: case_sensitive,
502
502
  wholeWord: whole_word,
503
503
  useRegex: use_regex,
@@ -1,10 +1,14 @@
1
1
  /**
2
2
  * Files Panel State Handlers
3
3
  *
4
- * Persist per-user-per-project files panel state (expanded folders,
5
- * open tabs, scroll positions, view mode). Single source of truth in DB
6
- * so that the state survives browser refresh and follows the user across
7
- * devices.
4
+ * Persist per-user-per-workspace files panel state (expanded folders, open
5
+ * tabs, scroll positions, view mode). Single source of truth in DB so that the
6
+ * state survives browser refresh and follows the user across devices.
7
+ *
8
+ * The row is per (user, project), but the state inside it is per workspace: a
9
+ * project and each of its worktrees keep separate entries. Sharing one entry
10
+ * carried open tabs — including unsaved buffers — from the main tree into a
11
+ * worktree, which read as the edit having crossed between them.
8
12
  */
9
13
 
10
14
  import { t } from 'elysia';
@@ -13,10 +17,50 @@ import { projectQueries } from '../../database/queries/project-queries';
13
17
  import { ws as wsServer } from '../../utils/ws';
14
18
  import { requireProjectAccess } from '../access';
15
19
 
20
+ /** Stored shape: opaque per-scope state strings under one version marker. */
21
+ interface ScopedPanelState {
22
+ v: 2;
23
+ scopes: Record<string, string>;
24
+ }
25
+
26
+ function parseStored(raw: string | null): ScopedPanelState {
27
+ if (!raw) return { v: 2, scopes: {} };
28
+
29
+ try {
30
+ const parsed = JSON.parse(raw) as ScopedPanelState | Record<string, unknown>;
31
+ if (
32
+ typeof parsed === 'object' && parsed !== null &&
33
+ (parsed as ScopedPanelState).v === 2 &&
34
+ typeof (parsed as ScopedPanelState).scopes === 'object'
35
+ ) {
36
+ return parsed as ScopedPanelState;
37
+ }
38
+ } catch {
39
+ // Fall through — anything unparseable is treated as absent.
40
+ }
41
+
42
+ // Pre-worktree state was a bare panel-state document; it belongs to the main
43
+ // tree, so existing users keep their tabs instead of starting empty.
44
+ return { v: 2, scopes: {} };
45
+ }
46
+
47
+ /** Whether `raw` is legacy (flat) state rather than the scoped envelope. */
48
+ function isLegacyState(raw: string | null): boolean {
49
+ if (!raw) return false;
50
+ try {
51
+ const parsed = JSON.parse(raw) as { v?: number };
52
+ return parsed?.v !== 2;
53
+ } catch {
54
+ return false;
55
+ }
56
+ }
57
+
16
58
  export const filesStateHandler = createRouter()
17
59
  .http('files:get-panel-state', {
18
60
  data: t.Object({
19
- projectId: t.String()
61
+ projectId: t.String(),
62
+ // Absent means the main tree, which is also where legacy state lives.
63
+ scopeKey: t.Optional(t.String())
20
64
  }),
21
65
  response: t.Object({
22
66
  state: t.Union([t.String(), t.Null()])
@@ -24,19 +68,37 @@ export const filesStateHandler = createRouter()
24
68
  }, async ({ data, conn }) => {
25
69
  requireProjectAccess(conn, data.projectId);
26
70
  const userId = wsServer.getUserId(conn);
27
- const state = projectQueries.getFilesPanelState(userId, data.projectId);
28
- return { state };
71
+ const raw = projectQueries.getFilesPanelState(userId, data.projectId);
72
+
73
+ const scopeKey = data.scopeKey || data.projectId;
74
+ if (isLegacyState(raw)) {
75
+ return { state: scopeKey === data.projectId ? raw : null };
76
+ }
77
+
78
+ return { state: parseStored(raw).scopes[scopeKey] ?? null };
29
79
  })
30
80
 
31
81
  .http('files:set-panel-state', {
32
82
  data: t.Object({
33
83
  projectId: t.String(),
84
+ scopeKey: t.Optional(t.String()),
34
85
  state: t.Union([t.String(), t.Null()])
35
86
  }),
36
87
  response: t.Object({ ok: t.Boolean() })
37
88
  }, async ({ data, conn }) => {
38
89
  requireProjectAccess(conn, data.projectId);
39
90
  const userId = wsServer.getUserId(conn);
40
- projectQueries.setFilesPanelState(userId, data.projectId, data.state);
91
+
92
+ const raw = projectQueries.getFilesPanelState(userId, data.projectId);
93
+ const scopeKey = data.scopeKey || data.projectId;
94
+
95
+ // Read-modify-write so writing one workspace never drops another's entry.
96
+ const stored = parseStored(raw);
97
+ if (isLegacyState(raw) && raw) stored.scopes[data.projectId] = raw;
98
+
99
+ if (data.state === null) delete stored.scopes[scopeKey];
100
+ else stored.scopes[scopeKey] = data.state;
101
+
102
+ projectQueries.setFilesPanelState(userId, data.projectId, JSON.stringify(stored));
41
103
  return { ok: true };
42
104
  });
@@ -12,7 +12,8 @@ import { createRouter } from '$shared/utils/ws-server';
12
12
  import { fileWatcher } from '$backend/files/file-watcher';
13
13
  import { debug } from '$shared/utils/logger';
14
14
  import { ws } from '$backend/utils/ws';
15
- import { projectQueries } from '../../database/queries/project-queries';
15
+ import { makeScopeKey } from '$shared/utils/workspace-scope';
16
+ import { requireWorkspaceRootAccess } from './path-access';
16
17
  import { requireProjectAccess } from '../access';
17
18
 
18
19
  // Connection ids that already have a disconnect cleanup registered, so we
@@ -28,10 +29,10 @@ export const watchHandler = createRouter()
28
29
  }, async ({ data, conn }) => {
29
30
  const { projectPath } = data;
30
31
 
31
- const project = projectQueries.getByPath(projectPath);
32
- if (!project) throw new Error('Access denied');
33
- requireProjectAccess(conn, project.id);
34
- const projectId = project.id;
32
+ // The root may be the project or one of its worktrees; watchers are keyed
33
+ // per workspace so two trees of one project never share a watcher.
34
+ const { project, worktreeId } = requireWorkspaceRootAccess(conn, projectPath);
35
+ const projectId = makeScopeKey(project.id, worktreeId);
35
36
 
36
37
  try {
37
38
  const connId = ws.getConnectionId(conn);
@@ -54,7 +55,7 @@ export const watchHandler = createRouter()
54
55
 
55
56
  if (success) {
56
57
  // Broadcast confirmation (frontend filters by projectId)
57
- ws.emit.project(projectId, 'files:watching', {
58
+ ws.emit.project(project.id, 'files:watching', {
58
59
  projectId,
59
60
  watching: true,
60
61
  timestamp: Date.now()
@@ -63,14 +64,14 @@ export const watchHandler = createRouter()
63
64
  debug.log('file', `Started watching project ${projectId}`);
64
65
  } else {
65
66
  // Broadcast error (frontend filters by projectId)
66
- ws.emit.project(projectId, 'files:watch-error', {
67
+ ws.emit.project(project.id, 'files:watch-error', {
67
68
  projectId,
68
69
  error: 'Failed to start file watcher'
69
70
  });
70
71
  }
71
72
  } catch (error) {
72
73
  debug.error('file', 'Error starting file watch:', error);
73
- ws.emit.project(projectId, 'files:watch-error', {
74
+ ws.emit.project(project.id, 'files:watch-error', {
74
75
  projectId,
75
76
  error: error instanceof Error ? error.message : 'Unknown error'
76
77
  });
@@ -88,14 +89,15 @@ export const watchHandler = createRouter()
88
89
  })
89
90
  }, async ({ data, conn }) => {
90
91
  let projectId: string;
92
+ let roomProjectId: string;
91
93
  if (data.projectPath) {
92
- const project = projectQueries.getByPath(data.projectPath);
93
- if (!project) return; // unknown path — nothing to unwatch
94
- requireProjectAccess(conn, project.id);
95
- projectId = project.id;
94
+ const { project, worktreeId } = requireWorkspaceRootAccess(conn, data.projectPath);
95
+ roomProjectId = project.id;
96
+ projectId = makeScopeKey(project.id, worktreeId);
96
97
  } else {
97
98
  // Backwards-compatible fallback for callers that don't send a path.
98
- projectId = ws.getProjectId(conn);
99
+ roomProjectId = ws.getProjectId(conn);
100
+ projectId = roomProjectId;
99
101
  }
100
102
 
101
103
  try {
@@ -110,7 +112,7 @@ export const watchHandler = createRouter()
110
112
  // Broadcast the ACTUAL resulting state — other devices may still be
111
113
  // viewing this project, in which case the watcher is still alive and
112
114
  // they must not be told it stopped.
113
- ws.emit.project(projectId, 'files:watching', {
115
+ ws.emit.project(roomProjectId, 'files:watching', {
114
116
  projectId,
115
117
  watching: fileWatcher.isWatching(projectId),
116
118
  timestamp: Date.now()
@@ -7,6 +7,7 @@
7
7
  import { t } from 'elysia';
8
8
  import { createRouter } from '$shared/utils/ws-server';
9
9
  import { execGit } from '../../git/git-executor';
10
+ import { buildBudgetedStagedDiff, BRANCH_NAME_BUDGET } from './diff-budget';
10
11
  import { initializeEngine } from '../../engine';
11
12
  import { resolveGenerationTarget } from '../../engine/resolve-model';
12
13
  import type { EngineType } from '$shared/types/unified';
@@ -19,7 +20,7 @@ import {
19
20
  TEST_BRANCH_NAME_PREFIX
20
21
  } from '$shared/constants/git';
21
22
  import { debug } from '$shared/utils/logger';
22
- import { requireProjectAccess } from '../access';
23
+ import { requireProjectWorkspace } from '../access';
23
24
 
24
25
  const INVALID_BRANCH_SEPARATOR_CHARS = /[\s\0~^:?*[\]\\]+/g;
25
26
  const GENERATED_BRANCH_PREFIXES = [
@@ -144,13 +145,13 @@ export const branchNameHandler = createRouter()
144
145
  branchName: t.String()
145
146
  })
146
147
  }, async ({ data, conn }) => {
147
- const project = requireProjectAccess(conn, data.projectId);
148
- const cwd = resolveRepoCwd(project.path, data.repoPath);
148
+ const { root } = requireProjectWorkspace(conn, data.projectId);
149
+ const cwd = resolveRepoCwd(root, data.repoPath);
149
150
 
150
- const diffResult = await execGit(['diff', '--cached'], cwd);
151
- const rawDiff = diffResult.stdout;
152
-
153
- if (!rawDiff.trim()) {
151
+ // A branch name is a topic, not a description — the file list carries nearly
152
+ // all the signal, so this budget is much tighter than the commit-message one.
153
+ const diff = await buildBudgetedStagedDiff(cwd, BRANCH_NAME_BUDGET);
154
+ if (diff.isEmpty) {
154
155
  throw new Error('No staged changes to generate a branch name for');
155
156
  }
156
157
 
@@ -167,7 +168,7 @@ export const branchNameHandler = createRouter()
167
168
  const separator = normalizeBranchSeparator(data.branchSeparator);
168
169
  const instructions = createBranchNameInstructions(currentBranch, prefix, separator);
169
170
  const extra = data.customPrompt?.trim();
170
- const prompt = `${instructions}${extra ? `\n\nAdditional constraints:\n${extra}` : ''}\n\nGit diff:\n${rawDiff}`;
171
+ const prompt = `${instructions}${extra ? `\n\nAdditional constraints:\n${extra}` : ''}\n\n${diff.text}`;
171
172
 
172
173
  // The caller's providerSlug/account can be stale (see resolve-model.ts).
173
174
  const target = await resolveGenerationTarget(engine, data.modelId, data.providerSlug);
@@ -6,7 +6,7 @@ import { t } from 'elysia';
6
6
  import path from 'node:path';
7
7
  import { createRouter } from '$shared/utils/ws-server';
8
8
  import { gitService } from '../../git/git-service';
9
- import { requireProjectAccess } from '../access';
9
+ import { requireProjectWorkspace } from '../access';
10
10
  import { debug } from '$shared/utils/logger';
11
11
 
12
12
  const BranchSchema = t.Object({
@@ -72,8 +72,8 @@ export const branchHandler = createRouter()
72
72
  nested: t.Optional(t.Array(NestedRepoInfoSchema))
73
73
  })
74
74
  }, async ({ data, conn }) => {
75
- const project = requireProjectAccess(conn, data.projectId);
76
- return await gitService.getBranches(project.path, data.selectedRemote);
75
+ const { root } = requireProjectWorkspace(conn, data.projectId);
76
+ return await gitService.getBranches(root, data.selectedRemote);
77
77
  })
78
78
 
79
79
  .http('git:create-branch', {
@@ -87,8 +87,8 @@ export const branchHandler = createRouter()
87
87
  }),
88
88
  response: t.Object({ ok: t.Boolean() })
89
89
  }, async ({ data, conn }) => {
90
- const project = requireProjectAccess(conn, data.projectId);
91
- const cwd = resolveRepoCwd(project.path, data.repoPath);
90
+ const { root } = requireProjectWorkspace(conn, data.projectId);
91
+ const cwd = resolveRepoCwd(root, data.repoPath);
92
92
  await gitService.createBranch(cwd, data.name, data.startPoint);
93
93
  return { ok: true };
94
94
  })
@@ -102,8 +102,8 @@ export const branchHandler = createRouter()
102
102
  }),
103
103
  response: t.Object({ ok: t.Boolean() })
104
104
  }, async ({ data, conn }) => {
105
- const project = requireProjectAccess(conn, data.projectId);
106
- const cwd = resolveRepoCwd(project.path, data.repoPath);
105
+ const { root } = requireProjectWorkspace(conn, data.projectId);
106
+ const cwd = resolveRepoCwd(root, data.repoPath);
107
107
  await gitService.switchBranch(cwd, data.name);
108
108
  return { ok: true };
109
109
  })
@@ -116,8 +116,8 @@ export const branchHandler = createRouter()
116
116
  }),
117
117
  response: t.Object({ ok: t.Boolean() })
118
118
  }, async ({ data, conn }) => {
119
- const project = requireProjectAccess(conn, data.projectId);
120
- const cwd = resolveRepoCwd(project.path, data.repoPath);
119
+ const { root } = requireProjectWorkspace(conn, data.projectId);
120
+ const cwd = resolveRepoCwd(root, data.repoPath);
121
121
  await gitService.checkoutCommit(cwd, data.commitHash);
122
122
  return { ok: true };
123
123
  })
@@ -132,8 +132,8 @@ export const branchHandler = createRouter()
132
132
  }),
133
133
  response: t.Object({ ok: t.Boolean() })
134
134
  }, async ({ data, conn }) => {
135
- const project = requireProjectAccess(conn, data.projectId);
136
- const cwd = resolveRepoCwd(project.path, data.repoPath);
135
+ const { root } = requireProjectWorkspace(conn, data.projectId);
136
+ const cwd = resolveRepoCwd(root, data.repoPath);
137
137
  await gitService.deleteBranch(cwd, data.name, data.force);
138
138
  return { ok: true };
139
139
  })
@@ -147,8 +147,8 @@ export const branchHandler = createRouter()
147
147
  }),
148
148
  response: t.Object({ ok: t.Boolean() })
149
149
  }, async ({ data, conn }) => {
150
- const project = requireProjectAccess(conn, data.projectId);
151
- const cwd = resolveRepoCwd(project.path, data.repoPath);
150
+ const { root } = requireProjectWorkspace(conn, data.projectId);
151
+ const cwd = resolveRepoCwd(root, data.repoPath);
152
152
  await gitService.renameBranch(cwd, data.oldName, data.newName);
153
153
  return { ok: true };
154
154
  })
@@ -158,6 +158,10 @@ export const branchHandler = createRouter()
158
158
  projectId: t.String(),
159
159
  branchName: t.String(),
160
160
  noFastForward: t.Optional(t.Boolean()),
161
+ /** Collapse the branch into staged changes without committing. */
162
+ squash: t.Optional(t.Boolean()),
163
+ /** Refuse the merge unless it is a fast-forward. */
164
+ ffOnly: t.Optional(t.Boolean()),
161
165
  repoPath: t.Optional(t.String())
162
166
  }),
163
167
  response: t.Object({
@@ -165,7 +169,45 @@ export const branchHandler = createRouter()
165
169
  message: t.String()
166
170
  })
167
171
  }, async ({ data, conn }) => {
168
- const project = requireProjectAccess(conn, data.projectId);
169
- const cwd = resolveRepoCwd(project.path, data.repoPath);
170
- return await gitService.mergeBranch(cwd, data.branchName, data.noFastForward ?? false);
172
+ const { root } = requireProjectWorkspace(conn, data.projectId);
173
+ const cwd = resolveRepoCwd(root, data.repoPath);
174
+ return await gitService.mergeBranch(cwd, data.branchName, {
175
+ noFastForward: data.noFastForward ?? false,
176
+ squash: data.squash ?? false,
177
+ ffOnly: data.ffOnly ?? false
178
+ });
179
+ })
180
+
181
+ .http('git:rebase', {
182
+ data: t.Object({
183
+ projectId: t.String(),
184
+ upstream: t.String({ minLength: 1 }),
185
+ /** Stash and restore local changes around the rebase. Defaults to true. */
186
+ autostash: t.Optional(t.Boolean()),
187
+ repoPath: t.Optional(t.String())
188
+ }),
189
+ response: t.Object({
190
+ success: t.Boolean(),
191
+ hasConflicts: t.Boolean(),
192
+ message: t.String()
193
+ })
194
+ }, async ({ data, conn }) => {
195
+ const { root } = requireProjectWorkspace(conn, data.projectId);
196
+ const cwd = resolveRepoCwd(root, data.repoPath);
197
+ return await gitService.rebaseOnto(cwd, data.upstream, data.autostash ?? true);
198
+ })
199
+
200
+ .http('git:return-to-branch', {
201
+ data: t.Object({
202
+ projectId: t.String(),
203
+ /** Explicit target; omit to use git's own "previous checkout" shorthand. */
204
+ branch: t.Optional(t.String()),
205
+ repoPath: t.Optional(t.String())
206
+ }),
207
+ response: t.Object({ ok: t.Boolean() })
208
+ }, async ({ data, conn }) => {
209
+ const { root } = requireProjectWorkspace(conn, data.projectId);
210
+ const cwd = resolveRepoCwd(root, data.repoPath);
211
+ await gitService.returnToBranch(cwd, data.branch);
212
+ return { ok: true };
171
213
  });
@@ -6,13 +6,13 @@
6
6
 
7
7
  import { t } from 'elysia';
8
8
  import { createRouter } from '$shared/utils/ws-server';
9
- import { execGit } from '../../git/git-executor';
9
+ import { buildBudgetedStagedDiff, COMMIT_MESSAGE_BUDGET } from './diff-budget';
10
10
  import { initializeEngine } from '../../engine';
11
11
  import { resolveGenerationTarget } from '../../engine/resolve-model';
12
12
  import type { EngineType } from '$shared/types/unified';
13
13
  import type { GeneratedCommitMessage } from '$shared/types/git';
14
14
  import { debug } from '$shared/utils/logger';
15
- import { requireProjectAccess } from '../access';
15
+ import { requireProjectWorkspace } from '../access';
16
16
 
17
17
  // Schema is shaped to satisfy OpenAI's strict structured-output mode (used by
18
18
  // Codex via `outputSchema`): every object must declare `additionalProperties:
@@ -74,14 +74,12 @@ export const commitMessageHandler = createRouter()
74
74
  message: t.String()
75
75
  })
76
76
  }, async ({ data, conn }) => {
77
- const project = requireProjectAccess(conn, data.projectId);
78
- const cwd = resolveRepoCwd(project.path, data.repoPath);
77
+ const { root } = requireProjectWorkspace(conn, data.projectId);
78
+ const cwd = resolveRepoCwd(root, data.repoPath);
79
79
 
80
- // Get raw staged diff text
81
- const diffResult = await execGit(['diff', '--cached'], cwd);
82
- const rawDiff = diffResult.stdout;
83
-
84
- if (!rawDiff.trim()) {
80
+ // A budgeted view of the staged change, not the raw diff — see diff-budget.ts.
81
+ const diff = await buildBudgetedStagedDiff(cwd, COMMIT_MESSAGE_BUDGET);
82
+ if (diff.isEmpty) {
85
83
  throw new Error('No staged changes to generate a commit message for');
86
84
  }
87
85
 
@@ -96,16 +94,21 @@ export const commitMessageHandler = createRouter()
96
94
  ? 'Generate a multi-line conventional commit message with type, scope, subject, AND body fields. The body should explain WHY the change was made.'
97
95
  : 'Generate a single-line conventional commit message with type, optional scope, and subject. Leave body empty.';
98
96
 
99
- const defaultPrompt = `Analyze the following git diff and generate a conventional commit message.
97
+ // When the diff was sampled, say so: without this the model describes only
98
+ // the files it happened to see and writes a subject that misses the change.
99
+ const coverageNote = diff.truncated
100
+ ? '\n- The diff below is a sample. Describe the change as a whole using the file list, not just the visible hunks.'
101
+ : '';
102
+
103
+ const defaultPrompt = `Analyze the following staged git change and generate a conventional commit message.
100
104
 
101
105
  Rules:
102
106
  - type: one of feat, fix, refactor, docs, test, chore, style, perf, ci, build
103
107
  - scope: optional, the area of the codebase affected (e.g., git, settings, engine)
104
108
  - subject: imperative mood, lowercase, no period at end, max 72 characters
105
- - ${formatInstruction}
109
+ - ${formatInstruction}${coverageNote}
106
110
 
107
- Git diff:
108
- ${rawDiff}`;
111
+ ${diff.text}`;
109
112
 
110
113
  const extra = data.customPrompt?.trim();
111
114
  const prompt = extra