@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
package/dist/index.html CHANGED
@@ -58,8 +58,8 @@
58
58
  }
59
59
  })();
60
60
  </script>
61
- <script type="module" crossorigin src="/assets/main-C_iGUZyL.js"></script>
62
- <link rel="stylesheet" crossorigin href="/assets/main-Buko4D0t.css">
61
+ <script type="module" crossorigin src="/assets/main-Df1I3hnw.js"></script>
62
+ <link rel="stylesheet" crossorigin href="/assets/main-DLqolBI2.css">
63
63
  </head>
64
64
  <body
65
65
  class="min-h-dvh bg-white text-slate-900 dark:bg-slate-950 dark:text-slate-100 transition-colors duration-200"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myrialabs/clopen",
3
- "version": "0.4.35",
3
+ "version": "0.4.37",
4
4
  "description": "All-in-one web workspace for AI coding agents — Claude Code, OpenCode, Codex, Copilot, Qwen Code, Pi, Cline, and Cursor — with chat, terminal, git, browser preview, database client, checkpoints, and real-time collaboration",
5
5
  "author": "Myria Labs",
6
6
  "license": "MIT",
@@ -14,6 +14,31 @@ export interface Project {
14
14
  default_profile_id?: number | null; // Shared per-project default Profile (null = none)
15
15
  }
16
16
 
17
+ /** Isolation status of a worktree copy. */
18
+ export type WorktreeStatus = 'active' | 'applied' | 'archived';
19
+
20
+ /** How the worktree directory was materialised from the main tree. */
21
+ export type WorktreeCloneMode = 'reflink' | 'copy';
22
+
23
+ /**
24
+ * An isolated copy of a project that sessions can run in. `base_tree` is the
25
+ * merge base — a JSON TreeMap of the main tree at clone time.
26
+ */
27
+ export interface Worktree {
28
+ id: string;
29
+ project_id: string;
30
+ name: string;
31
+ slug: string;
32
+ path: string;
33
+ status: WorktreeStatus;
34
+ clone_mode: WorktreeCloneMode;
35
+ base_tree: string;
36
+ created_by?: string | null;
37
+ created_at: string;
38
+ last_opened_at?: string | null;
39
+ last_applied_at?: string | null;
40
+ }
41
+
17
42
  export interface ChatSession {
18
43
  // ── Identity ──
19
44
  id: string;
@@ -31,6 +56,7 @@ export interface ChatSession {
31
56
  account_name?: string; // Display name of the selected account
32
57
  profile_id?: number | null; // Active Profile bundle for this session (null = use project default / none)
33
58
  reasoning_effort?: string | null; // Reasoning/thinking level token (native per engine; null = engine default)
59
+ worktree_id?: string | null; // Isolated worktree this session runs in (null = main project tree)
34
60
 
35
61
  // ── HEAD state (re-derived when HEAD changes: undo/redo/restore/branch) ──
36
62
  head_message_id?: string; // Git-like HEAD pointer to current branch tip
@@ -46,6 +46,12 @@ export interface GitBranch {
46
46
  name: string;
47
47
  isCurrent: boolean;
48
48
  isRemote: boolean;
49
+ /**
50
+ * The branch this one tracks, e.g. `origin/main`. Populated from
51
+ * `%(upstream:short)`, or from `branch.<name>.remote`/`.merge` when the
52
+ * configured remote is a bare URL — which is what `gh pr checkout` writes for
53
+ * a fork PR, and which has no remote-tracking ref for git to name.
54
+ */
49
55
  upstream?: string;
50
56
  ahead: number;
51
57
  behind: number;
@@ -163,10 +169,107 @@ export interface GitConflictMarker {
163
169
  baseContent?: string;
164
170
  }
165
171
 
172
+ /**
173
+ * How git recorded the conflict, derived from the porcelain XY code. Only
174
+ * `both-modified` and `both-added` carry inline `<<<<<<<` markers; the rest are
175
+ * add/delete disagreements where the only meaningful answer is "keep the file"
176
+ * or "delete the file", which is why they need their own UI affordance.
177
+ */
178
+ export type GitConflictKind =
179
+ | 'both-modified' // UU
180
+ | 'both-added' // AA
181
+ | 'added-by-us' // AU
182
+ | 'added-by-them' // UA
183
+ | 'deleted-by-us' // DU
184
+ | 'deleted-by-them' // UD
185
+ | 'both-deleted'; // DD
186
+
187
+ /** Ways a single conflicted path can be resolved. */
188
+ export type GitConflictResolution =
189
+ /** Take the whole file from our side (`git checkout --ours`). */
190
+ | 'ours'
191
+ /** Take the whole file from their side (`git checkout --theirs`). */
192
+ | 'theirs'
193
+ /** Write caller-supplied content, then stage it. */
194
+ | 'custom'
195
+ /** Keep the working-tree file as it stands (`git add`). */
196
+ | 'keep'
197
+ /** Resolve as deleted (`git rm`). */
198
+ | 'delete'
199
+ /** Put the conflict markers back (`git checkout --merge`). */
200
+ | 'reset';
201
+
166
202
  export interface GitConflictFile {
167
203
  path: string;
204
+ /** Working-tree text. Empty when `contentOmitted` is true. */
168
205
  content: string;
169
206
  markers: GitConflictMarker[];
207
+ kind: GitConflictKind;
208
+ /** True when the file has no text side to edit (binary, missing, or oversized). */
209
+ contentOmitted: boolean;
210
+ /** Why the content was omitted — drives the resolver's fallback UI. */
211
+ omitReason?: 'binary' | 'missing' | 'too-large';
212
+ /** Working-tree size in bytes, when the file exists. */
213
+ size?: number;
214
+ }
215
+
216
+ /**
217
+ * Everything the UI needs to explain (and finish) an in-progress operation.
218
+ *
219
+ * `oursLabel`/`theirsLabel` exist because the two sides swap meaning between
220
+ * merge and rebase: rebasing replays your commits onto the upstream, so `ours`
221
+ * is the branch you are rebasing *onto* and `theirs` is your own commit — the
222
+ * exact opposite of a merge. Showing the raw words without the branch names is
223
+ * the single biggest source of wrong resolutions.
224
+ */
225
+ export interface GitOperationState {
226
+ operation: GitOperation | null;
227
+ /** 1-based position in a multi-commit replay (rebase only). */
228
+ step?: number;
229
+ /** Total commits in the replay (rebase only). */
230
+ total?: number;
231
+ /** Human label for the `ours` side, e.g. "main". */
232
+ oursLabel: string;
233
+ /** Human label for the `theirs` side, e.g. "your commit". */
234
+ theirsLabel: string;
235
+ /** Subject of the commit being replayed, when there is one. */
236
+ currentCommit?: string;
237
+ /** Paths still unmerged. `--continue` is refused while this is non-zero. */
238
+ unmergedCount: number;
239
+ canContinue: boolean;
240
+ canSkip: boolean;
241
+ /**
242
+ * Unmerged paths with no operation sentinel — a `stash pop`/`apply` that hit
243
+ * a conflict. The stash entry survives a failed pop, so aborting here must
244
+ * say so rather than implying the work is gone.
245
+ */
246
+ stashConflict: boolean;
247
+ }
248
+
249
+ // ============================================
250
+ // Push Target
251
+ // ============================================
252
+
253
+ /**
254
+ * Where `git push` will actually send this branch.
255
+ *
256
+ * The panel used to push to whichever remote its dropdown had selected, with
257
+ * `-u`. On a fork PR checked out for review that pushed the contributor's work
258
+ * into the main repository as a new branch, and the `-u` rewrote the branch's
259
+ * remote so every later push went there too. Resolving the real destination —
260
+ * and showing it — is what keeps that from happening.
261
+ */
262
+ export interface GitPushTarget {
263
+ /** Remote name, or a bare URL when that is how the branch is configured. */
264
+ remote: string;
265
+ /** Branch name on the far side, which need not match the local name. */
266
+ remoteBranch: string;
267
+ /** False when the branch tracks nothing, so a push has to pick a destination. */
268
+ hasUpstream: boolean;
269
+ /** True when `remote` is a URL rather than a configured remote name. */
270
+ isUrl: boolean;
271
+ /** The local branch this was resolved for. */
272
+ branch: string;
170
273
  }
171
274
 
172
275
  // ============================================
@@ -208,6 +311,26 @@ export interface GitTag {
208
311
  isAnnotated: boolean;
209
312
  }
210
313
 
314
+ // ============================================
315
+ // Reflog
316
+ // ============================================
317
+
318
+ /**
319
+ * One `git reflog` row. This is the repo's undo journal: it still holds commits
320
+ * that branch deletes, resets and rebases have orphaned, so it is the only way
321
+ * back from a destructive action.
322
+ */
323
+ export interface GitReflogEntry {
324
+ hash: string;
325
+ hashShort: string;
326
+ /** Reflog selector, e.g. `HEAD@{3}`. */
327
+ selector: string;
328
+ /** The recorded action, e.g. `rebase (finish)` or `commit`. */
329
+ action: string;
330
+ subject: string;
331
+ date: string;
332
+ }
333
+
211
334
  // ============================================
212
335
  // Commit Message Generation
213
336
  // ============================================
@@ -10,6 +10,7 @@ export type LogLabel =
10
10
  | 'chat'
11
11
  | 'checkpoint'
12
12
  | 'snapshot'
13
+ | 'worktree'
13
14
 
14
15
  // Preview
15
16
  | 'preview'
@@ -0,0 +1,80 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { isScopeOfProject, makeScopeKey, parseScopeKey, scopeProjectId, scopeSlug } from './workspace-scope';
3
+
4
+ const PROJECT = '0f8c2a1e-1111-4a2b-9c3d-000000000001';
5
+ const WORKTREE = '5b7d3c9f-2222-4e6a-8b1c-000000000002';
6
+
7
+ describe('makeScopeKey', () => {
8
+ test('is the project id itself for the main tree', () => {
9
+ expect(makeScopeKey(PROJECT, null)).toBe(PROJECT);
10
+ expect(makeScopeKey(PROJECT)).toBe(PROJECT);
11
+ expect(makeScopeKey(PROJECT, '')).toBe(PROJECT);
12
+ });
13
+
14
+ test('joins project and worktree for a worktree', () => {
15
+ expect(makeScopeKey(PROJECT, WORKTREE)).toBe(`${PROJECT}~${WORKTREE}`);
16
+ });
17
+ });
18
+
19
+ describe('parseScopeKey', () => {
20
+ test('reads back a main-tree key', () => {
21
+ expect(parseScopeKey(PROJECT)).toEqual({ projectId: PROJECT, worktreeId: null });
22
+ });
23
+
24
+ test('reads back a worktree key', () => {
25
+ expect(parseScopeKey(makeScopeKey(PROJECT, WORKTREE))).toEqual({
26
+ projectId: PROJECT,
27
+ worktreeId: WORKTREE
28
+ });
29
+ });
30
+
31
+ test('treats a trailing separator as the main tree', () => {
32
+ expect(parseScopeKey(`${PROJECT}~`)).toEqual({ projectId: PROJECT, worktreeId: null });
33
+ });
34
+ });
35
+
36
+ describe('scopeProjectId', () => {
37
+ test('is what every access check runs against', () => {
38
+ expect(scopeProjectId(makeScopeKey(PROJECT, WORKTREE))).toBe(PROJECT);
39
+ expect(scopeProjectId(PROJECT)).toBe(PROJECT);
40
+ });
41
+ });
42
+
43
+ describe('isScopeOfProject', () => {
44
+ test('matches the project and each of its worktrees', () => {
45
+ expect(isScopeOfProject(PROJECT, PROJECT)).toBe(true);
46
+ expect(isScopeOfProject(makeScopeKey(PROJECT, WORKTREE), PROJECT)).toBe(true);
47
+ });
48
+
49
+ test('rejects another project', () => {
50
+ const other = '9999aaaa-3333-4c4d-8e5f-000000000003';
51
+ expect(isScopeOfProject(makeScopeKey(other, WORKTREE), PROJECT)).toBe(false);
52
+ });
53
+
54
+ test('rejects a project id that merely shares a prefix', () => {
55
+ expect(isScopeOfProject(`${PROJECT}-extra`, PROJECT)).toBe(false);
56
+ });
57
+ });
58
+
59
+ describe('scopeSlug', () => {
60
+ test('distinguishes a worktree from its project', () => {
61
+ expect(scopeSlug(PROJECT)).not.toBe(scopeSlug(makeScopeKey(PROJECT, WORKTREE)));
62
+ });
63
+
64
+ test('distinguishes two worktrees of the same project', () => {
65
+ const other = 'aaaa1111-4444-4f7b-9d2e-000000000004';
66
+ expect(scopeSlug(makeScopeKey(PROJECT, WORKTREE))).not.toBe(
67
+ scopeSlug(makeScopeKey(PROJECT, other))
68
+ );
69
+ });
70
+
71
+ test('is stable and alphanumeric so it survives id sanitisation', () => {
72
+ const slug = scopeSlug(makeScopeKey(PROJECT, WORKTREE));
73
+ expect(slug).toBe(scopeSlug(makeScopeKey(PROJECT, WORKTREE)));
74
+ expect(slug).toMatch(/^[a-zA-Z0-9]+$/);
75
+ });
76
+
77
+ test('keeps the main-tree token short and project-derived', () => {
78
+ expect(scopeSlug(PROJECT)).toBe('0f8c2a1e');
79
+ });
80
+ });
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Workspace scope keys.
3
+ *
4
+ * Terminal sessions and preview tabs are keyed per workspace, not per project:
5
+ * a worktree exists so its work stays separate, and sharing those keys with the
6
+ * main tree would leak one task's shells and tabs into another's.
7
+ *
8
+ * Access is always decided on the project id, so the key stays parseable back
9
+ * to it rather than becoming an opaque identifier of its own.
10
+ */
11
+
12
+ /** Separator that cannot appear in a UUID, so parsing is unambiguous. */
13
+ const SCOPE_SEPARATOR = '~';
14
+
15
+ /** Key for a workspace: the project itself, or one of its worktrees. */
16
+ export function makeScopeKey(projectId: string, worktreeId?: string | null): string {
17
+ return worktreeId ? `${projectId}${SCOPE_SEPARATOR}${worktreeId}` : projectId;
18
+ }
19
+
20
+ export function parseScopeKey(scopeKey: string): { projectId: string; worktreeId: string | null } {
21
+ const index = scopeKey.indexOf(SCOPE_SEPARATOR);
22
+ if (index === -1) return { projectId: scopeKey, worktreeId: null };
23
+
24
+ return {
25
+ projectId: scopeKey.slice(0, index),
26
+ worktreeId: scopeKey.slice(index + SCOPE_SEPARATOR.length) || null
27
+ };
28
+ }
29
+
30
+ /** The project a scope key belongs to — what every access check runs against. */
31
+ export function scopeProjectId(scopeKey: string): string {
32
+ return parseScopeKey(scopeKey).projectId;
33
+ }
34
+
35
+ /** Whether `scopeKey` is any workspace of `projectId` (the project or a worktree). */
36
+ export function isScopeOfProject(scopeKey: string, projectId: string): boolean {
37
+ return parseScopeKey(scopeKey).projectId === projectId;
38
+ }
39
+
40
+ /**
41
+ * Short id-safe token that distinguishes one workspace from another.
42
+ *
43
+ * Ids generated per workspace (terminal sessions, preview tabs) are numbered
44
+ * from 1 inside their own scope, so two scopes of the same project mint the
45
+ * same id. Embedding this token is what keeps those numbers from colliding —
46
+ * a collision is not cosmetic: PtyKit refuses a session id held by another
47
+ * namespace, and the preview client matches events on tab id alone.
48
+ */
49
+ export function scopeSlug(scopeKey: string): string {
50
+ const { projectId, worktreeId } = parseScopeKey(scopeKey);
51
+ const alphanumeric = (value: string) => value.replace(/[^a-zA-Z0-9]/g, '');
52
+
53
+ const head = alphanumeric(projectId).slice(0, 8);
54
+ if (!worktreeId) return head;
55
+ // `w` keeps the token alphanumeric, so it survives id sanitisation.
56
+ return `${head}w${alphanumeric(worktreeId).slice(0, 6)}`;
57
+ }
@@ -299,9 +299,11 @@ export class WSClient<TAPI extends { client: any; server: any }> {
299
299
  private context: {
300
300
  userId: string | null;
301
301
  projectId: string | null;
302
+ worktreeId: string | null;
302
303
  } = {
303
304
  userId: null,
304
- projectId: null
305
+ projectId: null,
306
+ worktreeId: null
305
307
  };
306
308
 
307
309
  /** Session token for re-authentication on reconnection */
@@ -775,6 +777,8 @@ export class WSClient<TAPI extends { client: any; server: any }> {
775
777
  if (this.context.projectId === projectId) return;
776
778
 
777
779
  this.context.projectId = projectId;
780
+ // A worktree belongs to one project, so it never survives the switch.
781
+ this.context.worktreeId = null;
778
782
  debug.log('websocket', 'Context: project set to', projectId);
779
783
 
780
784
  if (this.isConnected) {
@@ -782,10 +786,25 @@ export class WSClient<TAPI extends { client: any; server: any }> {
782
786
  }
783
787
  }
784
788
 
789
+ /**
790
+ * Set the worktree this client is viewing (null = the main project tree).
791
+ * Server-side scoping of terminals and preview tabs reads this.
792
+ */
793
+ async setWorktree(worktreeId: string | null): Promise<void> {
794
+ if (this.context.worktreeId === worktreeId) return;
795
+
796
+ this.context.worktreeId = worktreeId;
797
+ debug.log('websocket', 'Context: worktree set to', worktreeId);
798
+
799
+ if (this.isConnected) {
800
+ await this.syncContext();
801
+ }
802
+ }
803
+
785
804
  /**
786
805
  * Get current context
787
806
  */
788
- getContext(): { userId: string | null; projectId: string | null } {
807
+ getContext(): { userId: string | null; projectId: string | null; worktreeId: string | null } {
789
808
  return { ...this.context };
790
809
  }
791
810
 
@@ -862,15 +881,16 @@ export class WSClient<TAPI extends { client: any; server: any }> {
862
881
  // Register response listener
863
882
  unsubResponse = this.on('ws:set-context:response' as any, handleResponse);
864
883
 
865
- // Send context sync request (only projectId — userId is set server-side by auth)
884
+ // Send context sync request (userId is set server-side by auth)
866
885
  this.emit('ws:set-context' as any, {
867
886
  requestId,
868
887
  data: {
869
- projectId: this.context.projectId
888
+ projectId: this.context.projectId,
889
+ worktreeId: this.context.worktreeId
870
890
  }
871
891
  } as any);
872
892
 
873
- debug.log('websocket', 'Context sync sent: projectId=', this.context.projectId);
893
+ debug.log('websocket', 'Context sync sent: projectId=', this.context.projectId, 'worktreeId=', this.context.worktreeId);
874
894
  });
875
895
  }
876
896
 
@@ -308,11 +308,13 @@ export class WSRouter<
308
308
  this.httpRoutes.set('ws:set-context', {
309
309
  action: 'ws:set-context',
310
310
  dataSchema: t.Object({
311
- projectId: t.Optional(t.Union([t.String(), t.Null()]))
311
+ projectId: t.Optional(t.Union([t.String(), t.Null()])),
312
+ worktreeId: t.Optional(t.Union([t.String(), t.Null()]))
312
313
  }),
313
314
  responseSchema: t.Object({
314
315
  userId: t.Union([t.String(), t.Null()]),
315
- projectId: t.Union([t.String(), t.Null()])
316
+ projectId: t.Union([t.String(), t.Null()]),
317
+ worktreeId: t.Union([t.String(), t.Null()])
316
318
  }),
317
319
  handler: async ({ conn, data }) => {
318
320
  // Import ws server to update context
@@ -338,11 +340,25 @@ export class WSRouter<
338
340
  wsServer.setProject(conn, data.projectId);
339
341
  }
340
342
 
343
+ // Which tree this connection is viewing. Validated against the
344
+ // project so a client cannot point itself at another one's worktree.
345
+ if (data.worktreeId !== undefined) {
346
+ let worktreeId = data.worktreeId;
347
+ if (worktreeId !== null) {
348
+ const { worktreeQueries } = await import('$backend/database/queries');
349
+ const activeProjectId = wsServer.getConnectionState(conn)?.projectId ?? null;
350
+ const worktree = worktreeQueries.getById(worktreeId);
351
+ if (!worktree || worktree.project_id !== activeProjectId) worktreeId = null;
352
+ }
353
+ wsServer.setWorktree(conn, worktreeId);
354
+ }
355
+
341
356
  // Read back from connectionState (single source of truth)
342
357
  const state = wsServer.getConnectionState(conn);
343
358
  return {
344
359
  userId: state?.userId ?? null,
345
- projectId: state?.projectId ?? null
360
+ projectId: state?.projectId ?? null,
361
+ worktreeId: state?.worktreeId ?? null
346
362
  };
347
363
  }
348
364
  });