@myrialabs/clopen 0.4.37 → 0.4.39

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 (193) hide show
  1. package/README.md +2 -2
  2. package/backend/auth/permissions.ts +39 -0
  3. package/backend/bootstrap.ts +16 -0
  4. package/backend/chat/stream-manager.ts +1 -1
  5. package/backend/database/crypto/envelope.test.ts +93 -0
  6. package/backend/database/crypto/envelope.ts +127 -0
  7. package/backend/database/crypto/index.ts +22 -0
  8. package/backend/database/crypto/master-key.ts +129 -0
  9. package/backend/database/crypto/secret-columns.ts +151 -0
  10. package/backend/database/migrations/071_create_notes_tables.ts +90 -0
  11. package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
  12. package/backend/database/migrations/073_create_integration_tables.ts +119 -0
  13. package/backend/database/migrations/074_create_work_tables.ts +94 -0
  14. package/backend/database/migrations/075_create_deploy_bindings.ts +54 -0
  15. package/backend/database/migrations/076_remove_memory_code_graph.ts +229 -0
  16. package/backend/database/migrations/077_create_integration_db_links.ts +150 -0
  17. package/backend/database/migrations/index.ts +49 -0
  18. package/backend/database/queries/db-client-connection-queries.ts +42 -12
  19. package/backend/database/queries/deploy-queries.ts +124 -0
  20. package/backend/database/queries/engine-queries.ts +23 -10
  21. package/backend/database/queries/graph-queries.ts +291 -247
  22. package/backend/database/queries/index.ts +10 -1
  23. package/backend/database/queries/integration-db-link-queries.ts +168 -0
  24. package/backend/database/queries/integration-queries.ts +325 -0
  25. package/backend/database/queries/mcp-server-queries.ts +38 -11
  26. package/backend/database/queries/note-queries.test.ts +190 -0
  27. package/backend/database/queries/note-queries.ts +269 -0
  28. package/backend/database/queries/profile-queries.ts +1 -1
  29. package/backend/database/queries/ssh-connection-queries.ts +19 -8
  30. package/backend/database/queries/work-queries.ts +210 -0
  31. package/backend/db-client/integrations/index.ts +37 -0
  32. package/backend/db-client/integrations/links.ts +533 -0
  33. package/backend/db-client/integrations/projector.test.ts +280 -0
  34. package/backend/db-client/integrations/projector.ts +256 -0
  35. package/backend/db-client/integrations/supabase-service.ts +266 -0
  36. package/backend/db-client/providers/registry.ts +27 -0
  37. package/backend/db-client/providers/supabase/adapter.ts +500 -0
  38. package/backend/db-client/providers/supabase/api-types.ts +92 -0
  39. package/backend/db-client/providers/supabase/apply-migration.ts +104 -0
  40. package/backend/db-client/providers/supabase/client.ts +259 -0
  41. package/backend/db-client/providers/supabase/features.ts +502 -0
  42. package/backend/db-client/providers/supabase/local.test.ts +78 -0
  43. package/backend/db-client/providers/supabase/local.ts +137 -0
  44. package/backend/db-client/providers/types.ts +137 -0
  45. package/backend/deployments/bindings.test.ts +43 -0
  46. package/backend/deployments/bindings.ts +216 -0
  47. package/backend/deployments/index.ts +53 -0
  48. package/backend/deployments/log-streams.ts +214 -0
  49. package/backend/deployments/prompts.ts +70 -0
  50. package/backend/deployments/providers/vercel/adapter.ts +757 -0
  51. package/backend/deployments/providers/vercel/build-logs.test.ts +80 -0
  52. package/backend/deployments/providers/vercel/build-logs.ts +211 -0
  53. package/backend/deployments/providers/vercel/client.ts +203 -0
  54. package/backend/deployments/providers/vercel/list.test.ts +624 -0
  55. package/backend/deployments/providers/vercel/normalise.test.ts +115 -0
  56. package/backend/deployments/providers/vercel/normalise.ts +113 -0
  57. package/backend/deployments/providers/vercel/types.ts +104 -0
  58. package/backend/deployments/registry.ts +27 -0
  59. package/backend/deployments/service.ts +458 -0
  60. package/backend/deployments/types.ts +278 -0
  61. package/backend/engine/docs/artifacts.md +22 -9
  62. package/backend/files/os-clipboard.test.ts +209 -0
  63. package/backend/files/os-clipboard.ts +567 -0
  64. package/backend/http/integration-hooks.ts +42 -0
  65. package/backend/http/notes-images.test.ts +228 -0
  66. package/backend/http/notes-images.ts +196 -0
  67. package/backend/index.ts +13 -0
  68. package/backend/integrations/accounts.ts +229 -0
  69. package/backend/integrations/health.ts +146 -0
  70. package/backend/integrations/index.ts +36 -0
  71. package/backend/integrations/projections/index.ts +0 -0
  72. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  73. package/backend/integrations/projections/mcp-projector.ts +163 -0
  74. package/backend/integrations/projections/types.ts +63 -0
  75. package/backend/integrations/registry/define.ts +38 -0
  76. package/backend/integrations/registry/index.ts +60 -0
  77. package/backend/integrations/registry/providers/context7.ts +44 -0
  78. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  79. package/backend/integrations/registry/providers/github.ts +78 -0
  80. package/backend/integrations/registry/providers/supabase.ts +61 -0
  81. package/backend/integrations/registry/providers/vercel.ts +46 -0
  82. package/backend/integrations/registry/types.ts +96 -0
  83. package/backend/integrations/webhooks/gateway.ts +160 -0
  84. package/backend/integrations/webhooks/verify.ts +65 -0
  85. package/backend/mcp/README.md +25 -3
  86. package/backend/mcp/external/config.ts +35 -1
  87. package/backend/mcp/index.ts +1 -1
  88. package/backend/mcp/internal/config.ts +1 -1
  89. package/backend/mcp/internal/servers/memory-graph/description.ts +3 -3
  90. package/backend/mcp/internal/servers/memory-graph/runner.ts +4 -9
  91. package/backend/mcp/internal/servers/memory-graph/schema.ts +0 -4
  92. package/backend/memory/README.md +57 -34
  93. package/backend/memory/compose.test.ts +3 -3
  94. package/backend/memory/compose.ts +6 -9
  95. package/backend/memory/config.ts +0 -5
  96. package/backend/memory/consolidate.ts +1 -2
  97. package/backend/memory/context.test.ts +8 -54
  98. package/backend/memory/context.ts +19 -25
  99. package/backend/memory/extract/episodic.ts +10 -12
  100. package/backend/memory/extract/index.ts +23 -52
  101. package/backend/memory/extract/scheduler.ts +3 -6
  102. package/backend/memory/index.ts +6 -5
  103. package/backend/memory/invalidate.ts +36 -48
  104. package/backend/memory/layout.ts +319 -130
  105. package/backend/memory/retention.ts +12 -42
  106. package/backend/memory/retrieval.eval.test.ts +2 -2
  107. package/backend/memory/retrieval.test.ts +228 -183
  108. package/backend/memory/retrieval.ts +22 -21
  109. package/backend/memory/revise.test.ts +62 -116
  110. package/backend/memory/revise.ts +0 -1
  111. package/backend/memory/view.ts +8 -5
  112. package/backend/notes/access.test.ts +82 -0
  113. package/backend/notes/access.ts +27 -0
  114. package/backend/notes/storage.test.ts +77 -0
  115. package/backend/notes/storage.ts +114 -0
  116. package/backend/permissions/service.ts +2 -2
  117. package/backend/profiles/service.ts +1 -1
  118. package/backend/projects/project-cleanup.ts +6 -0
  119. package/backend/snapshot/helpers.ts +35 -41
  120. package/backend/snapshot/snapshot-service.ts +90 -0
  121. package/backend/snapshot/turn-changes.test.ts +163 -0
  122. package/backend/snapshot/turn-changes.ts +131 -0
  123. package/backend/work/bindings.ts +124 -0
  124. package/backend/work/index.ts +42 -0
  125. package/backend/work/prompts.ts +150 -0
  126. package/backend/work/providers/github/actions-logs.ts +180 -0
  127. package/backend/work/providers/github/adapter.test.ts +88 -0
  128. package/backend/work/providers/github/adapter.ts +1255 -0
  129. package/backend/work/providers/github/client.ts +280 -0
  130. package/backend/work/providers/github/list-range.test.ts +158 -0
  131. package/backend/work/providers/github/token-kind.test.ts +42 -0
  132. package/backend/work/pull-requests.ts +242 -0
  133. package/backend/work/registry.ts +27 -0
  134. package/backend/work/service.ts +436 -0
  135. package/backend/work/start-work.test.ts +71 -0
  136. package/backend/work/start-work.ts +232 -0
  137. package/backend/work/types.ts +180 -0
  138. package/backend/ws/db-client/accounts.ts +225 -0
  139. package/backend/ws/db-client/connections.ts +34 -3
  140. package/backend/ws/db-client/context.ts +37 -0
  141. package/backend/ws/db-client/index.ts +20 -1
  142. package/backend/ws/db-client/supabase.ts +188 -0
  143. package/backend/ws/deployments/actions.ts +360 -0
  144. package/backend/ws/deployments/context.ts +43 -0
  145. package/backend/ws/deployments/crud.ts +152 -0
  146. package/backend/ws/deployments/index.ts +15 -0
  147. package/backend/ws/deployments/schemas.ts +183 -0
  148. package/backend/ws/files/clipboard.ts +78 -0
  149. package/backend/ws/files/index.ts +5 -0
  150. package/backend/ws/git/diff-budget.ts +70 -11
  151. package/backend/ws/index.ts +16 -2
  152. package/backend/ws/integrations/crud.ts +219 -0
  153. package/backend/ws/integrations/index.ts +22 -0
  154. package/backend/ws/mcp/crud.ts +25 -1
  155. package/backend/ws/memory/crud.ts +4 -16
  156. package/backend/ws/notes/index.ts +278 -0
  157. package/backend/ws/profiles/crud.ts +1 -1
  158. package/backend/ws/snapshot/changes.ts +279 -0
  159. package/backend/ws/snapshot/index.ts +4 -3
  160. package/backend/ws/work/actions.ts +206 -0
  161. package/backend/ws/work/context.ts +51 -0
  162. package/backend/ws/work/crud.ts +347 -0
  163. package/backend/ws/work/index.ts +17 -0
  164. package/backend/ws/work/pull-requests.ts +177 -0
  165. package/backend/ws/work/schemas.ts +226 -0
  166. package/dist/assets/{index-sJmS_CCm.js → index-BrF6nqld.js} +1 -1
  167. package/dist/assets/{index-Bik9TCBi.js → index-C8Gi-b6U.js} +1 -1
  168. package/dist/assets/main-Bd3gb79F.css +1 -0
  169. package/dist/assets/main-Bo1hD7mt.js +1191 -0
  170. package/dist/index.html +2 -2
  171. package/package.json +1 -1
  172. package/shared/constants/engine-tools.ts +1 -1
  173. package/shared/constants/tool-icons.ts +42 -0
  174. package/shared/types/database/schema.ts +41 -0
  175. package/shared/types/db-client/connection.ts +6 -0
  176. package/shared/types/db-client/index.ts +2 -0
  177. package/shared/types/db-client/integrations.ts +174 -0
  178. package/shared/types/db-client/supabase.ts +131 -0
  179. package/shared/types/deployments.ts +382 -0
  180. package/shared/types/integrations.ts +140 -0
  181. package/shared/types/memory.ts +34 -51
  182. package/shared/types/stores/settings.ts +8 -0
  183. package/shared/types/ui/components.ts +1 -1
  184. package/shared/types/work.ts +426 -0
  185. package/shared/utils/diff-calculator.test.ts +89 -0
  186. package/shared/utils/diff-calculator.ts +30 -65
  187. package/shared/utils/logger.ts +4 -0
  188. package/backend/memory/extract/languages.ts +0 -176
  189. package/backend/memory/extract/structural.test.ts +0 -215
  190. package/backend/memory/extract/structural.ts +0 -364
  191. package/backend/ws/snapshot/content.ts +0 -85
  192. package/dist/assets/main-DLqolBI2.css +0 -1
  193. package/dist/assets/main-Df1I3hnw.js +0 -1096
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Turn Changes Handler
3
+ *
4
+ * Everything the AI-change indicators and the checkpoint "Changes" tab read:
5
+ * which files each turn of a chat touched, and the content on either side of
6
+ * that change.
7
+ *
8
+ * Both are answered from checkpoint snapshots rather than from Edit/Write tool
9
+ * calls — see backend/snapshot/turn-changes.ts for why that distinction is the
10
+ * whole point. The one thing snapshots cannot answer is a turn that is still
11
+ * running, which `snapshot:get-pending-changes` covers from the same baseline.
12
+ *
13
+ * Only checkpoints on the ACTIVE path are reported. After a restore, the
14
+ * checkpoints that were undone no longer describe anything on disk, so keeping
15
+ * their files in the list would mark files that carry no such change any more.
16
+ * Active-path selection is done with the same helpers the timeline uses, so the
17
+ * two views cannot disagree about which turns exist.
18
+ */
19
+
20
+ import { t } from 'elysia';
21
+ import { createRouter } from '$shared/utils/ws-server';
22
+ import { isAbsolute, join, relative } from 'path';
23
+ import { readFile } from 'fs/promises';
24
+ import {
25
+ messageQueries,
26
+ sessionQueries,
27
+ projectQueries,
28
+ snapshotQueries
29
+ } from '../../database/queries';
30
+ import { loadMessage } from '$shared/utils/message-formatter';
31
+ import { blobStore } from '../../snapshot/blob-store';
32
+ import { snapshotService } from '../../snapshot/snapshot-service';
33
+ import { resolveSessionRoot } from '../../worktrees';
34
+ import { makeScopeKey } from '$shared/utils/workspace-scope';
35
+ import { buildTurnFiles, excerptPrompt, isBinaryBuffer, statusOf } from '../../snapshot/turn-changes';
36
+ import type { TurnFileStatus } from '../../snapshot/turn-changes';
37
+ import {
38
+ buildCheckpointTree,
39
+ getCheckpointPathToRoot,
40
+ findCheckpointForHead,
41
+ extractMessageText
42
+ } from '../../snapshot/helpers';
43
+ import type { SessionScopedChanges } from '$shared/types/database/schema';
44
+ import { debug } from '$shared/utils/logger';
45
+ import { requireSessionAccess, requireMessageAccess } from '../access';
46
+
47
+ /**
48
+ * Longest prompt excerpt a turn row shows. Long enough that nearly every real
49
+ * instruction arrives whole, short enough that a chat of them stays a list.
50
+ */
51
+ const PROMPT_EXCERPT_LENGTH = 400;
52
+
53
+ const TURN_FILE_SCHEMA = t.Object({
54
+ path: t.String(),
55
+ status: t.Union([t.Literal('added'), t.Literal('modified'), t.Literal('deleted')]),
56
+ insertions: t.Number(),
57
+ deletions: t.Number(),
58
+ isBinary: t.Boolean(),
59
+ contentAvailable: t.Boolean()
60
+ });
61
+
62
+ /** Parse a snapshot's stored changes, treating unreadable JSON as "no changes". */
63
+ function parseSessionChanges(raw: unknown): SessionScopedChanges {
64
+ if (typeof raw !== 'string' || raw === '') return {};
65
+ try {
66
+ return JSON.parse(raw) as SessionScopedChanges;
67
+ } catch {
68
+ return {};
69
+ }
70
+ }
71
+
72
+ /** Read a blob as text, or null when it is missing or not text. */
73
+ async function readTextBlob(hash: string): Promise<string | null> {
74
+ if (!hash) return null;
75
+ try {
76
+ const buf = await blobStore.readBlob(hash);
77
+ return isBinaryBuffer(buf) ? null : buf.toString('utf8');
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+
83
+ export const changesHandler = createRouter()
84
+ /**
85
+ * Every turn of a chat, newest first, with the files it changed.
86
+ */
87
+ .http('snapshot:list-turn-changes', {
88
+ data: t.Object({
89
+ sessionId: t.String({ minLength: 1 })
90
+ }),
91
+ response: t.Object({
92
+ turns: t.Array(
93
+ t.Object({
94
+ checkpointMessageId: t.String(),
95
+ /** 1-based position on the active path — what "Turn 3" means. */
96
+ turnIndex: t.Number(),
97
+ timestamp: t.String(),
98
+ promptText: t.String(),
99
+ files: t.Array(TURN_FILE_SCHEMA)
100
+ })
101
+ )
102
+ })
103
+ }, async ({ data, conn }) => {
104
+ requireSessionAccess(conn, data.sessionId);
105
+
106
+ const allMessages = messageQueries.getAllBySessionId(data.sessionId);
107
+ if (allMessages.length === 0) return { turns: [] };
108
+
109
+ const { checkpoints, parentMap } = buildCheckpointTree(allMessages);
110
+ if (checkpoints.length === 0) return { turns: [] };
111
+
112
+ // No HEAD means the session was restored to before its first message, so
113
+ // no turn's changes are on disk any more.
114
+ const head = sessionQueries.getHead(data.sessionId);
115
+ if (!head) return { turns: [] };
116
+
117
+ const checkpointIds = new Set(checkpoints.map((cp) => cp.id));
118
+ const activeCheckpointId = findCheckpointForHead(head, allMessages, checkpointIds);
119
+ if (!activeCheckpointId) return { turns: [] };
120
+
121
+ const activePath = getCheckpointPathToRoot(activeCheckpointId, parentMap);
122
+ const byId = new Map(checkpoints.map((cp) => [cp.id, cp]));
123
+
124
+ const turns = [];
125
+ for (let i = 0; i < activePath.length; i++) {
126
+ const checkpoint = byId.get(activePath[i]);
127
+ if (!checkpoint) continue;
128
+
129
+ const snapshot = snapshotQueries.getByMessageId(checkpoint.id);
130
+ const changes = parseSessionChanges(snapshot?.session_changes);
131
+ const files = await buildTurnFiles(changes, (hash) => blobStore.readBlob(hash));
132
+
133
+ turns.push({
134
+ checkpointMessageId: checkpoint.id,
135
+ turnIndex: i + 1,
136
+ timestamp: checkpoint.created_at,
137
+ promptText: excerptPrompt(
138
+ extractMessageText(loadMessage(checkpoint)),
139
+ PROMPT_EXCERPT_LENGTH
140
+ ),
141
+ files
142
+ });
143
+ }
144
+
145
+ // Newest first: the turn a user wants to review is almost always the last
146
+ // one, and scrolling to reach it is a tax on the common case.
147
+ turns.reverse();
148
+ return { turns };
149
+ })
150
+
151
+ /**
152
+ * Both sides of one file's change in one turn.
153
+ *
154
+ * Replaces reading the file twice: the diff pane, the editor gutter and the
155
+ * revert action all need the same pair, and a single round-trip keeps them
156
+ * from disagreeing about which version they are looking at.
157
+ *
158
+ * Pass `messageId` for a settled turn, or `sessionId` for the turn that is
159
+ * still running — the running turn has no snapshot row yet, so its "before"
160
+ * comes from the live session baseline and its "after" from the file itself.
161
+ */
162
+ .http('snapshot:read-turn-file', {
163
+ data: t.Object({
164
+ /** Checkpoint message id — the user message that opened the turn. */
165
+ messageId: t.Optional(t.String({ minLength: 1 })),
166
+ /** Session id — for the turn currently running. */
167
+ sessionId: t.Optional(t.String({ minLength: 1 })),
168
+ filePath: t.String()
169
+ }),
170
+ response: t.Object({
171
+ /** Text before the turn; '' when the turn created the file. */
172
+ before: t.Union([t.String(), t.Null()]),
173
+ /** Text after the turn; '' when the turn deleted it. */
174
+ after: t.Union([t.String(), t.Null()]),
175
+ status: t.Union([
176
+ t.Literal('added'),
177
+ t.Literal('modified'),
178
+ t.Literal('deleted'),
179
+ t.Literal('unchanged')
180
+ ]),
181
+ isBinary: t.Boolean()
182
+ })
183
+ }, async ({ data, conn }) => {
184
+ const unchanged = { before: null, after: null, status: 'unchanged' as const, isBinary: false };
185
+
186
+ const sessionId = data.messageId
187
+ ? requireMessageAccess(conn, data.messageId).session_id
188
+ : data.sessionId;
189
+ if (!sessionId) return unchanged;
190
+ if (!data.messageId) requireSessionAccess(conn, sessionId);
191
+
192
+ const session = sessionQueries.getById(sessionId);
193
+ const root = resolveSessionRoot(sessionId)?.path
194
+ || (session ? projectQueries.getById(session.project_id)?.path : null);
195
+ if (!root) return unchanged;
196
+
197
+ const relativePath = (
198
+ isAbsolute(data.filePath) ? relative(root, data.filePath) : data.filePath
199
+ ).replace(/\\/g, '/');
200
+
201
+ if (data.messageId) {
202
+ const snapshot = snapshotQueries.getByMessageId(data.messageId);
203
+ const change = parseSessionChanges(snapshot?.session_changes)[relativePath];
204
+ if (!change) return unchanged;
205
+
206
+ const before = change.oldHash ? await readTextBlob(change.oldHash) : '';
207
+ const after = change.newHash ? await readTextBlob(change.newHash) : '';
208
+ // A side that exists but read back as null is binary or gone; either way
209
+ // there is no text to diff, and saying so beats an empty pane.
210
+ return {
211
+ before,
212
+ after,
213
+ status: statusOf(change.oldHash, change.newHash),
214
+ isBinary:
215
+ (change.oldHash !== '' && before === null) || (change.newHash !== '' && after === null)
216
+ };
217
+ }
218
+
219
+ // Running turn: the baseline is the before, and the disk is the after.
220
+ const baseline = snapshotService.getBaselineHash(sessionId, relativePath);
221
+ if (!baseline.known) return unchanged;
222
+
223
+ const before = baseline.hash ? await readTextBlob(baseline.hash) : '';
224
+ let after: string | null = null;
225
+ let exists = true;
226
+ try {
227
+ const buf = await readFile(join(root, relativePath));
228
+ after = isBinaryBuffer(buf) ? null : buf.toString('utf8');
229
+ } catch {
230
+ exists = false;
231
+ }
232
+
233
+ const status: TurnFileStatus = !baseline.hash ? 'added' : !exists ? 'deleted' : 'modified';
234
+ return {
235
+ before,
236
+ after: exists ? after : '',
237
+ status,
238
+ isBinary: (baseline.hash !== '' && before === null) || (exists && after === null)
239
+ };
240
+ })
241
+
242
+ /**
243
+ * Changes made so far by a turn that is still running.
244
+ *
245
+ * Returns an empty list rather than an error whenever it cannot answer — no
246
+ * baseline yet, nothing dirty, a session without a project — because the
247
+ * caller polls this while the model streams and a failure there must not
248
+ * become a visible error.
249
+ */
250
+ .http('snapshot:get-pending-changes', {
251
+ data: t.Object({
252
+ sessionId: t.String({ minLength: 1 })
253
+ }),
254
+ response: t.Object({
255
+ files: t.Array(TURN_FILE_SCHEMA)
256
+ })
257
+ }, async ({ data, conn }) => {
258
+ requireSessionAccess(conn, data.sessionId);
259
+
260
+ const session = sessionQueries.getById(data.sessionId);
261
+ if (!session) return { files: [] };
262
+
263
+ const root = resolveSessionRoot(data.sessionId)?.path
264
+ || projectQueries.getById(session.project_id)?.path;
265
+ if (!root) return { files: [] };
266
+
267
+ try {
268
+ const changes = await snapshotService.getPendingChanges(
269
+ root,
270
+ makeScopeKey(session.project_id, session.worktree_id ?? null),
271
+ data.sessionId
272
+ );
273
+ const files = await buildTurnFiles(changes, (hash) => blobStore.readBlob(hash));
274
+ return { files };
275
+ } catch (error) {
276
+ debug.warn('snapshot', 'Failed to read pending changes:', error);
277
+ return { files: [] };
278
+ }
279
+ });
@@ -6,15 +6,16 @@
6
6
  * Structure:
7
7
  * - restore.ts: Unified restore operation (replaces undo + redo)
8
8
  * - timeline.ts: Timeline visualization data
9
- * - content.ts: Pre-checkpoint file content (AI gutter diff base)
9
+ * - changes.ts: Per-turn file changes and their content, which is what the
10
+ * AI-change indicators, the editor gutter and the Changes tab all read
10
11
  */
11
12
 
12
13
  import { createRouter } from '$shared/utils/ws-server';
13
14
  import { restoreHandler } from './restore';
14
15
  import { timelineHandler } from './timeline';
15
- import { contentHandler } from './content';
16
+ import { changesHandler } from './changes';
16
17
 
17
18
  export const snapshotRouter = createRouter()
18
19
  .merge(restoreHandler)
19
20
  .merge(timelineHandler)
20
- .merge(contentHandler);
21
+ .merge(changesHandler);
@@ -0,0 +1,206 @@
1
+ /**
2
+ * The two actions that turn a work item into work.
3
+ *
4
+ * work:start-work item → worktree + branch + session + first prompt
5
+ * work:checks CI runs for a branch
6
+ * work:check-logs a failing run's logs, composed into a chat prompt
7
+ *
8
+ * Both return TEXT for the client to send rather than sending it themselves.
9
+ * The chat pipeline is driven from the browser — it owns which session is
10
+ * active, the streaming state and the optimistic message — and a second, silent
11
+ * path that injects messages from the backend would race with all three.
12
+ */
13
+
14
+ import { t } from 'elysia';
15
+ import { createRouter } from '$shared/utils/ws-server';
16
+ import { gitService } from '$backend/git/git-service';
17
+ import { buildCheckLogPrompt, workService, startWork } from '$backend/work';
18
+ import { serializeWorktree } from '../worktrees/crud';
19
+ import { worktreeQueries } from '$backend/database/queries';
20
+ import { ws } from '$backend/utils/ws';
21
+ import type { EngineType } from '$shared/types/unified';
22
+ import { resolveWorkProject } from './context';
23
+ import { announceWorkChanged } from './crud';
24
+ import {
25
+ CHECK_RUN_SCHEMA,
26
+ COMMIT_DETAIL_SCHEMA,
27
+ COMMIT_SCHEMA,
28
+ FILE_CHANGE_SCHEMA,
29
+ KIND_SCHEMA
30
+ } from './schemas';
31
+ import { debug } from '$shared/utils/logger';
32
+
33
+ const ENGINE_SCHEMA = t.Union([
34
+ t.Literal('claude-code'),
35
+ t.Literal('opencode'),
36
+ t.Literal('copilot'),
37
+ t.Literal('codex'),
38
+ t.Literal('qwen'),
39
+ t.Literal('pi'),
40
+ t.Literal('cline'),
41
+ t.Literal('cursor')
42
+ ]);
43
+
44
+ /** The branch the caller is looking at, when it did not name one. */
45
+ async function currentBranchOf(root: string): Promise<string> {
46
+ const branches = await gitService.getBranches(root);
47
+ if (!branches.current || branches.detached) {
48
+ throw new Error('This workspace is not on a branch');
49
+ }
50
+ return branches.current;
51
+ }
52
+
53
+ export const workActionsHandler = createRouter()
54
+ .http('work:start-work', {
55
+ data: t.Object({
56
+ projectId: t.Optional(t.String()),
57
+ accountId: t.String({ minLength: 1 }),
58
+ kind: KIND_SCHEMA,
59
+ id: t.String({ minLength: 1 }),
60
+ engine: ENGINE_SCHEMA
61
+ }),
62
+ response: t.Object({
63
+ worktreeId: t.String(),
64
+ worktreeName: t.String(),
65
+ sessionId: t.String(),
66
+ branch: t.String(),
67
+ prompt: t.String(),
68
+ transitionedTo: t.Union([t.String(), t.Null()]),
69
+ transitionError: t.Union([t.String(), t.Null()]),
70
+ needsSetup: t.Boolean()
71
+ })
72
+ }, async ({ data, conn }) => {
73
+ const { projectId } = resolveWorkProject(conn, data.projectId);
74
+ const userId = ws.getUserId(conn);
75
+
76
+ const result = await startWork({
77
+ projectId,
78
+ accountId: data.accountId,
79
+ kind: data.kind,
80
+ itemId: data.id,
81
+ engine: data.engine as EngineType,
82
+ userId
83
+ });
84
+
85
+ // The worktree list and the session list both just changed for everyone in
86
+ // the project, and the person who clicked is about to switch into both.
87
+ ws.emit.project(projectId, 'worktrees:changed', {
88
+ projectId,
89
+ worktrees: worktreeQueries.getByProjectId(projectId).map(serializeWorktree)
90
+ });
91
+ announceWorkChanged(projectId);
92
+
93
+ debug.log('work', `Started work on ${data.kind} ${data.id} in worktree ${result.worktreeId}`);
94
+ return result;
95
+ })
96
+
97
+ .http('work:checks', {
98
+ data: t.Object({
99
+ projectId: t.Optional(t.String()),
100
+ accountId: t.String({ minLength: 1 }),
101
+ branch: t.Optional(t.String())
102
+ }),
103
+ response: t.Object({
104
+ branch: t.String(),
105
+ runs: t.Array(CHECK_RUN_SCHEMA)
106
+ })
107
+ }, async ({ data, conn }) => {
108
+ const { projectId, root } = resolveWorkProject(conn, data.projectId);
109
+
110
+ const branch = data.branch?.trim() || (await currentBranchOf(root));
111
+ return { branch, runs: await workService.listChecks(projectId, data.accountId, branch) };
112
+ })
113
+
114
+ .http('work:check-logs', {
115
+ data: t.Object({
116
+ projectId: t.Optional(t.String()),
117
+ accountId: t.String({ minLength: 1 }),
118
+ runId: t.String({ minLength: 1 }),
119
+ branch: t.String({ minLength: 1 }),
120
+ runUrl: t.String()
121
+ }),
122
+ response: t.Object({
123
+ runName: t.String(),
124
+ /** The logs themselves, so they can be READ here rather than only sent. */
125
+ text: t.String(),
126
+ prompt: t.String(),
127
+ truncated: t.Boolean()
128
+ })
129
+ }, async ({ data, conn }) => {
130
+ const { projectId } = resolveWorkProject(conn, data.projectId);
131
+ const bundle = await workService.fetchCheckLogs(projectId, data.accountId, data.runId);
132
+
133
+ return {
134
+ runName: bundle.runName,
135
+ text: bundle.text,
136
+ prompt: buildCheckLogPrompt(bundle, {
137
+ locator: workService.describeBinding(projectId, data.accountId) ?? 'this repository',
138
+ branch: data.branch,
139
+ runUrl: data.runUrl
140
+ }),
141
+ truncated: bundle.truncated
142
+ };
143
+ })
144
+
145
+ .http('work:pr-commits', {
146
+ data: t.Object({
147
+ projectId: t.Optional(t.String()),
148
+ accountId: t.String({ minLength: 1 }),
149
+ id: t.String({ minLength: 1 })
150
+ }),
151
+ response: t.Array(COMMIT_SCHEMA)
152
+ }, async ({ data, conn }) => {
153
+ const { projectId } = resolveWorkProject(conn, data.projectId);
154
+ return workService.listCommits(projectId, data.accountId, data.id);
155
+ })
156
+
157
+ /**
158
+ * One commit, opened.
159
+ *
160
+ * Separate from `pr-commits` because it costs a request per commit and the
161
+ * list is read far more often than any single commit is opened.
162
+ */
163
+ .http('work:commit-detail', {
164
+ data: t.Object({
165
+ projectId: t.Optional(t.String()),
166
+ accountId: t.String({ minLength: 1 }),
167
+ sha: t.String({ minLength: 1, maxLength: 100 })
168
+ }),
169
+ response: COMMIT_DETAIL_SCHEMA
170
+ }, async ({ data, conn }) => {
171
+ const { projectId } = resolveWorkProject(conn, data.projectId);
172
+ return workService.commitDetail(projectId, data.accountId, data.sha);
173
+ })
174
+
175
+ .http('work:file-content', {
176
+ data: t.Object({
177
+ projectId: t.Optional(t.String()),
178
+ accountId: t.String({ minLength: 1 }),
179
+ path: t.String({ minLength: 1, maxLength: 1000 }),
180
+ ref: t.String({ minLength: 1, maxLength: 250 }),
181
+ /** Preferred address: it survives forks, deletions and gone branches. */
182
+ blobSha: t.Optional(t.String({ maxLength: 100 }))
183
+ }),
184
+ response: t.Object({ content: t.String(), truncated: t.Boolean() })
185
+ }, async ({ data, conn }) => {
186
+ const { projectId } = resolveWorkProject(conn, data.projectId);
187
+ return workService.fetchFileContent(
188
+ projectId,
189
+ data.accountId,
190
+ data.path,
191
+ data.ref,
192
+ data.blobSha
193
+ );
194
+ })
195
+
196
+ .http('work:pr-files', {
197
+ data: t.Object({
198
+ projectId: t.Optional(t.String()),
199
+ accountId: t.String({ minLength: 1 }),
200
+ id: t.String({ minLength: 1 })
201
+ }),
202
+ response: t.Array(FILE_CHANGE_SCHEMA)
203
+ }, async ({ data, conn }) => {
204
+ const { projectId } = resolveWorkProject(conn, data.projectId);
205
+ return workService.listFiles(projectId, data.accountId, data.id);
206
+ });
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Which project an issues route acts on.
3
+ *
4
+ * The surface lives in More Tools, and More Tools is global — a user looking at
5
+ * project A should be able to read project B's issues without leaving their
6
+ * session. So every route takes an OPTIONAL `projectId` and falls back to the
7
+ * connection's current one, rather than reading the connection and nothing else.
8
+ *
9
+ * Access is still checked per call. `projectId` arriving from the client is a
10
+ * request, not a permission: `requireProjectAccess` is what decides.
11
+ */
12
+
13
+ import type { WSConnection } from '$shared/utils/ws-server';
14
+ import type { Project } from '$shared/types/database/schema';
15
+ import { ws } from '$backend/utils/ws';
16
+ import { resolveWorktreeRoot } from '$backend/worktrees';
17
+ import { requireProjectAccess } from '../access';
18
+
19
+ export interface IssueProjectContext {
20
+ projectId: string;
21
+ project: Project;
22
+ /**
23
+ * The tree git commands run against.
24
+ *
25
+ * Worktree-aware ONLY for the project the connection is actually viewing: a
26
+ * worktree belongs to a session, and resolving another project's root
27
+ * through this connection's worktree id would run git in the wrong tree —
28
+ * or in one that does not exist.
29
+ */
30
+ root: string;
31
+ /** True when this is the project the user is currently working in. */
32
+ isCurrent: boolean;
33
+ }
34
+
35
+ export function resolveWorkProject(conn: WSConnection, projectId?: string): IssueProjectContext {
36
+ const current = ws.getProjectId(conn);
37
+ const target = (projectId ?? '').trim() || current;
38
+ const project = requireProjectAccess(conn, target);
39
+
40
+ if (target !== current) {
41
+ return { projectId: target, project, root: project.path, isCurrent: false };
42
+ }
43
+
44
+ const resolved = resolveWorktreeRoot(target, ws.getWorktreeId(conn));
45
+ return {
46
+ projectId: target,
47
+ project,
48
+ root: resolved.path || project.path,
49
+ isCurrent: true
50
+ };
51
+ }