@myrialabs/clopen 0.4.48 → 0.4.50

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 (114) hide show
  1. package/backend/chat/background-wait.test.ts +28 -0
  2. package/backend/chat/message-pages.test.ts +180 -0
  3. package/backend/chat/message-pages.ts +237 -0
  4. package/backend/chat/stream-manager.ts +101 -18
  5. package/backend/database/migrations/087_create_blob_line_stats.ts +37 -0
  6. package/backend/database/migrations/088_create_messages_fts_map.ts +52 -0
  7. package/backend/database/migrations/089_add_memory_layout_tiles.ts +58 -0
  8. package/backend/database/migrations/index.ts +21 -0
  9. package/backend/database/queries/blob-line-stats-queries.ts +48 -0
  10. package/backend/database/queries/graph-queries.ts +392 -135
  11. package/backend/database/queries/index.ts +2 -0
  12. package/backend/database/queries/message-fts.test.ts +120 -0
  13. package/backend/database/queries/message-queries.ts +45 -9
  14. package/backend/database/queries/session-queries.ts +3 -2
  15. package/backend/database/queries/utils-queries.ts +3 -0
  16. package/backend/db-client/env/diff.ts +9 -33
  17. package/backend/db-client/env/env.test.ts +8 -8
  18. package/backend/db-client/env/service.ts +1 -1
  19. package/backend/engine/adapters/claude/environment.ts +4 -0
  20. package/backend/engine/adapters/claude/input-gate.test.ts +59 -0
  21. package/backend/engine/adapters/claude/input-gate.ts +74 -0
  22. package/backend/engine/adapters/claude/message-converter.test.ts +16 -0
  23. package/backend/engine/adapters/claude/message-converter.ts +8 -0
  24. package/backend/engine/adapters/claude/stream.ts +15 -0
  25. package/backend/files/file-watcher.ts +19 -0
  26. package/backend/git/contributors.test.ts +35 -0
  27. package/backend/git/contributors.ts +46 -0
  28. package/backend/git/identity/scope-config.test.ts +7 -4
  29. package/backend/http/static-assets.test.ts +78 -0
  30. package/backend/http/static-assets.ts +104 -0
  31. package/backend/index.ts +46 -17
  32. package/backend/memory/README.md +7 -4
  33. package/backend/memory/layout.test.ts +377 -0
  34. package/backend/memory/layout.ts +1029 -265
  35. package/backend/memory/view.ts +257 -386
  36. package/backend/preview/browser/browser-preview-service.ts +24 -6
  37. package/backend/project/status-manager.ts +4 -2
  38. package/backend/snapshot/blob-store.ts +9 -1
  39. package/backend/snapshot/helpers.ts +3 -10
  40. package/backend/snapshot/line-stats.test.ts +80 -0
  41. package/backend/snapshot/line-stats.ts +64 -0
  42. package/backend/snapshot/snapshot-service.ts +14 -27
  43. package/backend/snapshot/turn-changes.test.ts +10 -5
  44. package/backend/snapshot/turn-changes.ts +78 -40
  45. package/backend/terminal/ptykit.ts +6 -1
  46. package/backend/utils/ws-wire.test.ts +87 -0
  47. package/backend/utils/ws-wire.ts +189 -0
  48. package/backend/utils/ws.ts +40 -38
  49. package/backend/ws/chat/stream.ts +60 -20
  50. package/backend/ws/files/read.ts +30 -0
  51. package/backend/ws/git/log.ts +52 -0
  52. package/backend/ws/memory/crud.ts +118 -81
  53. package/backend/ws/messages/crud.ts +51 -0
  54. package/backend/ws/preview/index.ts +2 -0
  55. package/backend/ws/preview/watchers.ts +84 -0
  56. package/backend/ws/sessions/crud.ts +8 -12
  57. package/backend/ws/snapshot/changes.ts +5 -6
  58. package/backend/ws/terminal/tunnel.ts +2 -2
  59. package/bin/clopen.ts +37 -30
  60. package/dist/assets/addon-clipboard-wHJhZAA4.js.br +0 -0
  61. package/dist/assets/addon-clipboard-wHJhZAA4.js.gz +0 -0
  62. package/dist/assets/addon-fit-DX4qG4td.js.br +1 -0
  63. package/dist/assets/addon-fit-DX4qG4td.js.gz +0 -0
  64. package/dist/assets/addon-ligatures-DpDY8N_X.js.br +0 -0
  65. package/dist/assets/addon-ligatures-DpDY8N_X.js.gz +0 -0
  66. package/dist/assets/addon-unicode11-Bt8F3D7-.js.br +0 -0
  67. package/dist/assets/addon-unicode11-Bt8F3D7-.js.gz +0 -0
  68. package/dist/assets/addon-web-links-DIbG5aQx.js.br +0 -0
  69. package/dist/assets/addon-web-links-DIbG5aQx.js.gz +0 -0
  70. package/dist/assets/diff.worker-BoHLxmr2.js +7 -0
  71. package/dist/assets/diff.worker-BoHLxmr2.js.br +0 -0
  72. package/dist/assets/diff.worker-BoHLxmr2.js.gz +0 -0
  73. package/dist/assets/{index-DJzwt-hq.js → index-By6KdSLT.js} +1 -1
  74. package/dist/assets/index-By6KdSLT.js.br +0 -0
  75. package/dist/assets/index-By6KdSLT.js.gz +0 -0
  76. package/dist/assets/{index-CONlwAXZ.js → index-DV4TiDn1.js} +1 -1
  77. package/dist/assets/index-DV4TiDn1.js.br +0 -0
  78. package/dist/assets/index-DV4TiDn1.js.gz +0 -0
  79. package/dist/assets/main-DIESTGTD.css +1 -0
  80. package/dist/assets/main-DIESTGTD.css.br +0 -0
  81. package/dist/assets/main-DIESTGTD.css.gz +0 -0
  82. package/dist/assets/{main-nBOb9YOA.js → main-Da3JKoua.js} +623 -623
  83. package/dist/assets/main-Da3JKoua.js.br +0 -0
  84. package/dist/assets/main-Da3JKoua.js.gz +0 -0
  85. package/dist/assets/preview-video.worker-DcpDhCWL.js.br +0 -0
  86. package/dist/assets/preview-video.worker-DcpDhCWL.js.gz +0 -0
  87. package/dist/assets/xterm-B-qIQCd3.js.br +0 -0
  88. package/dist/assets/xterm-B-qIQCd3.js.gz +0 -0
  89. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.br +0 -0
  90. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.gz +0 -0
  91. package/dist/fonts/dm-sans.css.br +0 -0
  92. package/dist/fonts/dm-sans.css.gz +0 -0
  93. package/dist/index.html +2 -2
  94. package/dist/index.html.br +0 -0
  95. package/dist/index.html.gz +0 -0
  96. package/dist/sw.js.br +0 -0
  97. package/dist/sw.js.gz +0 -0
  98. package/package.json +3 -4
  99. package/shared/types/memory.ts +96 -73
  100. package/shared/types/unified/index.ts +1 -0
  101. package/shared/types/unified/stream.ts +33 -2
  102. package/shared/utils/diff-calculator.test.ts +178 -41
  103. package/shared/utils/diff-calculator.ts +383 -100
  104. package/shared/utils/process-supervisor.test.ts +242 -0
  105. package/shared/utils/process-supervisor.ts +356 -0
  106. package/shared/utils/process-tree.ts +99 -0
  107. package/shared/utils/ws-chunk.test.ts +33 -0
  108. package/shared/utils/ws-chunk.ts +73 -0
  109. package/shared/utils/ws-client-chunks.test.ts +45 -0
  110. package/shared/utils/ws-client.ts +43 -0
  111. package/shared/utils/ws-server.ts +17 -14
  112. package/backend/database/migrations/086_single_owner.test.ts +0 -170
  113. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +0 -1
  114. package/dist/assets/main-BUiUL3eZ.css +0 -1
@@ -21,7 +21,7 @@ import { createRouter } from '$shared/utils/ws-server';
21
21
  import { projectContextService } from '$backend/mcp/internal/project-context';
22
22
  import { debug } from '$shared/utils/logger';
23
23
  import { graphQueries, graphLayoutQueries } from '$backend/database/queries/graph-queries';
24
- import { buildGraphView, buildNodeDetail } from '$backend/memory/view';
24
+ import { buildGraphMeta, buildGraphTiles, buildNodeDetail, locateNodes, type GraphViewFilter } from '$backend/memory/view';
25
25
  import { resetGraphLayoutState } from '$backend/memory/layout';
26
26
  import { markConsulted, retrieve } from '$backend/memory/retrieval';
27
27
  import { scheduleVectorIndexing } from '$backend/memory/indexer';
@@ -78,6 +78,56 @@ const NODE = t.Object({
78
78
  entityKey: t.Union([t.String(), t.Null()])
79
79
  });
80
80
 
81
+ /**
82
+ * The graph view's narrowing, shared by the meta and tile requests so the two
83
+ * can never disagree about what is being looked at.
84
+ */
85
+ const FILTER = t.Object({
86
+ // Tri-state, and each state means something different: ABSENT is every
87
+ // project, an EMPTY array is global only, and a non-empty array is those
88
+ // projects plus the globals that apply inside every one of them.
89
+ projectIds: t.Optional(t.Array(t.String())),
90
+ subkinds: t.Optional(t.Array(t.String())),
91
+ scopes: t.Optional(t.Array(SCOPE)),
92
+ sources: t.Optional(t.Array(SOURCE)),
93
+ includeArchived: t.Optional(t.Boolean()),
94
+ includeSuperseded: t.Optional(t.Boolean())
95
+ });
96
+
97
+ const REGION = t.Object({
98
+ minX: t.Number(),
99
+ maxX: t.Number(),
100
+ minY: t.Number(),
101
+ maxY: t.Number()
102
+ });
103
+
104
+ const TILE_NODE = t.Object({
105
+ id: t.String(),
106
+ label: t.String(),
107
+ community: t.Number(),
108
+ degree: t.Number(),
109
+ x: t.Number(),
110
+ y: t.Number()
111
+ });
112
+
113
+ function filterOf(data: {
114
+ projectIds?: string[];
115
+ subkinds?: string[];
116
+ scopes?: string[];
117
+ sources?: string[];
118
+ includeArchived?: boolean;
119
+ includeSuperseded?: boolean;
120
+ }): GraphViewFilter {
121
+ return {
122
+ projectIds: data.projectIds,
123
+ subkinds: data.subkinds,
124
+ scopes: data.scopes as GraphScope[] | undefined,
125
+ sources: data.sources as GraphSource[] | undefined,
126
+ includeArchived: data.includeArchived,
127
+ includeSuperseded: data.includeSuperseded
128
+ };
129
+ }
130
+
81
131
  const MEMORY_MODEL = t.Object({
82
132
  engine: t.String(),
83
133
  providerSlug: t.Optional(t.String()),
@@ -131,95 +181,82 @@ const READINESS = t.Object({
131
181
 
132
182
  export const memoryCrudHandler = createRouter()
133
183
  .http('memory:graph', {
184
+ data: FILTER,
185
+ response: t.Object({
186
+ epoch: t.Number(),
187
+ stamp: t.Number(),
188
+ world: t.Union([t.Object({ minX: t.Number(), minY: t.Number(), size: t.Number() }), t.Null()]),
189
+ spacing: t.Number(),
190
+ total: t.Number(),
191
+ unplaced: t.Number(),
192
+ extent: t.Union([REGION, t.Null()]),
193
+ degreeScale: t.Number()
194
+ })
195
+ }, async ({ data }) => {
196
+ debug.log('path', 'memory:graph');
197
+ return buildGraphMeta(filterOf(data));
198
+ })
199
+ .http('memory:graph-tiles', {
134
200
  data: t.Object({
135
- // Tri-state, and each state means something different: ABSENT is every
136
- // project, an EMPTY array is global only, and a non-empty array is those
137
- // projects plus the globals that apply inside every one of them.
138
- projectIds: t.Optional(t.Array(t.String())),
139
- subkinds: t.Optional(t.Array(t.String())),
140
- scopes: t.Optional(t.Array(SCOPE)),
141
- sources: t.Optional(t.Array(SOURCE)),
142
- includeArchived: t.Optional(t.Boolean()),
143
- includeSuperseded: t.Optional(t.Boolean()),
144
- // The rectangle of the layout to zoom into, when a mark was opened.
145
- // Absent asks for the whole graph at whatever resolution fits.
146
- region: t.Optional(
147
- t.Object({
148
- minX: t.Number(),
149
- maxX: t.Number(),
150
- minY: t.Number(),
151
- maxY: t.Number()
152
- })
153
- ),
154
- limit: t.Optional(t.Number())
201
+ ...FILTER.properties,
202
+ // The epoch the tile addresses were computed against; a mismatch is
203
+ // answered with `stale` rather than tiles from a different map.
204
+ epoch: t.Number(),
205
+ z: t.Number(),
206
+ tiles: t.Array(t.Object({ x: t.Number(), y: t.Number() })),
207
+ budget: t.Number()
155
208
  }),
156
209
  response: t.Object({
157
- level: t.String(),
158
- nodes: t.Array(t.Object({
159
- id: t.String(),
160
- subkind: t.String(),
161
- scope: t.String(),
162
- label: t.String(),
163
- projectId: t.Union([t.String(), t.Null()]),
164
- degree: t.Number(),
165
- weight: t.Number(),
166
- pinned: t.Boolean(),
167
- community: t.Number(),
168
- createdAt: t.String(),
169
- x: t.Optional(t.Number()),
170
- y: t.Optional(t.Number())
171
- })),
172
- edges: t.Array(t.Object({
173
- id: t.Number(),
174
- source: t.String(),
175
- target: t.String(),
176
- rel: t.String(),
177
- weight: t.Number()
178
- })),
179
- bins: t.Array(t.Object({
180
- id: t.String(),
181
- members: t.Number(),
182
- label: t.String(),
183
- community: t.Number(),
210
+ epoch: t.Number(),
211
+ stale: t.Boolean(),
212
+ tiles: t.Array(t.Object({
213
+ z: t.Number(),
184
214
  x: t.Number(),
185
215
  y: t.Number(),
186
- region: t.Object({
187
- minX: t.Number(),
188
- maxX: t.Number(),
189
- minY: t.Number(),
190
- maxY: t.Number()
191
- })
192
- })),
193
- binEdges: t.Array(t.Object({
194
- source: t.String(),
195
- target: t.String(),
196
- weight: t.Number()
197
- })),
198
- region: t.Union([
199
- t.Object({
200
- minX: t.Number(),
201
- maxX: t.Number(),
202
- minY: t.Number(),
203
- maxY: t.Number()
204
- }),
205
- t.Null()
206
- ]),
207
- totalNodes: t.Number(),
208
- truncated: t.Boolean()
216
+ cells: t.Number(),
217
+ nodes: t.Array(TILE_NODE),
218
+ clusters: t.Array(t.Object({
219
+ id: t.String(),
220
+ members: t.Number(),
221
+ label: t.String(),
222
+ community: t.Number(),
223
+ x: t.Number(),
224
+ y: t.Number(),
225
+ cellX: t.Number(),
226
+ cellY: t.Number()
227
+ })),
228
+ edges: t.Array(t.Object({
229
+ source: t.String(),
230
+ target: t.String(),
231
+ weight: t.Number(),
232
+ targetX: t.Number(),
233
+ targetY: t.Number()
234
+ })),
235
+ cellEdges: t.Array(t.Object({
236
+ source: t.String(),
237
+ targetCellX: t.Number(),
238
+ targetCellY: t.Number(),
239
+ weight: t.Number()
240
+ }))
241
+ }))
209
242
  })
210
243
  }, async ({ data }) => {
211
- debug.log('path', 'memory:graph');
212
- return buildGraphView({
213
- projectIds: data.projectIds,
214
- subkinds: data.subkinds,
215
- scopes: data.scopes as GraphScope[] | undefined,
216
- sources: data.sources as GraphSource[] | undefined,
217
- includeArchived: data.includeArchived,
218
- includeSuperseded: data.includeSuperseded,
219
- region: data.region,
220
- limit: data.limit
244
+ debug.log('path', `memory:graph-tiles z=${data.z} ×${data.tiles.length}`);
245
+ return buildGraphTiles({
246
+ ...filterOf(data),
247
+ epoch: data.epoch,
248
+ z: data.z,
249
+ tiles: data.tiles,
250
+ budget: data.budget
221
251
  });
222
252
  })
253
+ .http('memory:locate', {
254
+ data: t.Object({ nodeIds: t.Array(t.String()) }),
255
+ response: t.Object({ nodes: t.Array(TILE_NODE) })
256
+ }, async ({ data }) => {
257
+ debug.log('path', `memory:locate ×${data.nodeIds.length}`);
258
+ return { nodes: locateNodes(data.nodeIds) };
259
+ })
223
260
  .http('memory:node', {
224
261
  data: t.Object({ nodeId: t.String(), hops: t.Optional(t.Number()) }),
225
262
  response: t.Object({
@@ -3,6 +3,7 @@
3
3
  *
4
4
  * HTTP endpoints for message management:
5
5
  * - List messages (with optional include_all for history view)
6
+ * - Page through the active branch, its prompt index and older task tools
6
7
  * - Get message by ID
7
8
  * - Resolve which of a session's message ids are saved
8
9
  * - Delete message
@@ -13,6 +14,7 @@ import { createRouter } from '$shared/utils/ws-server';
13
14
  import { messageQueries } from '../../database/queries';
14
15
  import { loadMessage } from '$shared/utils/message-formatter';
15
16
  import { requireMessageAccess, requireSessionAccess } from '../access';
17
+ import { getMessagePage, getPromptIndex, getTaskHistory } from '../../chat/message-pages';
16
18
 
17
19
  export const crudHandler = createRouter()
18
20
  // List messages
@@ -34,6 +36,55 @@ export const crudHandler = createRouter()
34
36
  }
35
37
  })
36
38
 
39
+ // One page of the active branch — the chat loads its latest turns and pages
40
+ // back as the user scrolls up (see backend/chat/message-pages.ts).
41
+ .http('messages:list-page', {
42
+ data: t.Object({
43
+ session_id: t.String({ minLength: 1 }),
44
+ /** Return the page that ends just before this message; omit for the latest. */
45
+ before_id: t.Optional(t.String()),
46
+ /** Also reach back to this message (a jump to an old prompt). */
47
+ until_id: t.Optional(t.String()),
48
+ /** Minimum page size; the page is extended back to the start of a turn. */
49
+ limit: t.Optional(t.Number({ minimum: 1, maximum: 500 }))
50
+ }),
51
+ response: t.Object({
52
+ messages: t.Array(t.Any()),
53
+ hasMore: t.Boolean()
54
+ })
55
+ }, async ({ data }) => {
56
+ requireSessionAccess(data.session_id);
57
+ return getMessagePage(data.session_id, { beforeId: data.before_id, untilId: data.until_id, minCount: data.limit });
58
+ })
59
+
60
+ // Every user prompt on the active branch — the chat's navigation rail.
61
+ .http('messages:list-prompts', {
62
+ data: t.Object({
63
+ session_id: t.String({ minLength: 1 })
64
+ }),
65
+ response: t.Array(t.Object({
66
+ messageId: t.String(),
67
+ text: t.String(),
68
+ createdAt: t.String()
69
+ }))
70
+ }, async ({ data }) => {
71
+ requireSessionAccess(data.session_id);
72
+ return getPromptIndex(data.session_id);
73
+ })
74
+
75
+ // Task-tool calls and results older than a message — the task widget replays
76
+ // them together with the loaded messages.
77
+ .http('messages:list-task-history', {
78
+ data: t.Object({
79
+ session_id: t.String({ minLength: 1 }),
80
+ before_id: t.String({ minLength: 1 })
81
+ }),
82
+ response: t.Array(t.Any())
83
+ }, async ({ data }) => {
84
+ requireSessionAccess(data.session_id);
85
+ return getTaskHistory(data.session_id, data.before_id);
86
+ })
87
+
37
88
  // Get message by ID
38
89
  .http('messages:get', {
39
90
  data: t.Object({
@@ -57,6 +57,7 @@ import { streamPreviewHandler } from './browser/webcodecs';
57
57
  import { nativeUIPreviewHandler } from './browser/native-ui';
58
58
  import { mcpPreviewHandler } from './browser/mcp';
59
59
  import { hostPreviewHandler } from './browser/host';
60
+ import { previewWatchHandler } from './watchers';
60
61
 
61
62
  export const previewRouter = createRouter()
62
63
  .merge(tabPreviewHandler)
@@ -70,6 +71,7 @@ export const previewRouter = createRouter()
70
71
  .merge(nativeUIPreviewHandler)
71
72
  .merge(mcpPreviewHandler)
72
73
  .merge(hostPreviewHandler)
74
+ .merge(previewWatchHandler)
73
75
  // Server-emitted events (for type safety)
74
76
  .emit('preview:browser-tab-opened', t.Object({
75
77
  // projectId lets the frontend reject events that belong to a project it has
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Which connections are looking at a Preview right now.
3
+ *
4
+ * Most preview events describe state every device must stay in step with (tabs
5
+ * opened or closed, an agent taking control, a dialog) and still go to the
6
+ * whole project. A few are a panel's live detail and are frequent: every line
7
+ * the previewed page logs, and every step of the agent's cursor. Those only go
8
+ * to connections with a Preview mounted. A panel that mounts later loses
9
+ * nothing: the console is seeded from its history (`preview:browser-console-get`)
10
+ * and the agent's last cursor position is replayed on `preview:watch`.
11
+ */
12
+
13
+ import { t } from 'elysia';
14
+ import { createRouter } from '$shared/utils/ws-server';
15
+ import { ws } from '$backend/utils/ws';
16
+ import type { WSAPI } from '$backend/ws';
17
+ import { scopeProjectId } from '$shared/utils/workspace-scope';
18
+
19
+ const watching = new Set<string>();
20
+
21
+ /** Last known agent cursor per project and tab, replayed to a new watcher. */
22
+ const lastCursor = new Map<string, Map<string, WSAPI['server']['preview:browser-mcp-cursor-position']>>();
23
+
24
+ /** Send a Preview-detail event to the project's connections that have a Preview open. */
25
+ export function emitToPreviewWatchers<K extends keyof WSAPI['server']>(
26
+ projectId: string,
27
+ event: K,
28
+ payload: WSAPI['server'][K]
29
+ ): void {
30
+ ws.emit.projectWhere(projectId, (connectionId) => watching.has(connectionId), event, payload);
31
+ }
32
+
33
+ /** Remember where the agent's cursor came to rest on a tab. */
34
+ export function rememberAgentCursor(
35
+ projectId: string,
36
+ cursor: WSAPI['server']['preview:browser-mcp-cursor-position']
37
+ ): void {
38
+ let tabs = lastCursor.get(projectId);
39
+ if (!tabs) {
40
+ tabs = new Map();
41
+ lastCursor.set(projectId, tabs);
42
+ }
43
+ tabs.set(cursor.sessionId, cursor);
44
+ }
45
+
46
+ /** The agent let go of a tab: there is no cursor to show on it any more. */
47
+ export function forgetAgentCursor(projectId: string, tabId: string): void {
48
+ lastCursor.get(projectId)?.delete(tabId);
49
+ }
50
+
51
+ export const previewWatchHandler = createRouter()
52
+ /**
53
+ * A Preview was mounted (`watching: true`) or the last one went away
54
+ * (`false`). Clients send it again after a reconnect.
55
+ */
56
+ .on('preview:watch', {
57
+ data: t.Object({
58
+ watching: t.Boolean()
59
+ })
60
+ }, ({ conn, data }) => {
61
+ const connectionId = ws.getConnectionId(conn);
62
+ if (!connectionId) return;
63
+ if (!data.watching) {
64
+ watching.delete(connectionId);
65
+ return;
66
+ }
67
+ if (!watching.has(connectionId)) {
68
+ watching.add(connectionId);
69
+ ws.addCleanup(conn, () => watching.delete(connectionId));
70
+ }
71
+
72
+ let projectId: string;
73
+ try {
74
+ projectId = scopeProjectId(ws.getProjectId(conn));
75
+ } catch {
76
+ return; // No project yet — nothing to replay.
77
+ }
78
+ for (const cursor of lastCursor.get(projectId)?.values() ?? []) {
79
+ ws.sendToConnectionId(
80
+ connectionId,
81
+ JSON.stringify({ action: 'preview:browser-mcp-cursor-position', payload: cursor })
82
+ );
83
+ }
84
+ });
@@ -4,7 +4,7 @@
4
4
  * HTTP endpoints for session management:
5
5
  * - List sessions (all or by project)
6
6
  * - Create new session
7
- * - Get session by ID (with messages)
7
+ * - Get session by ID
8
8
  * - Get or create shared session
9
9
  * - Update session (title, reactivate, end)
10
10
  * - Delete session
@@ -149,25 +149,21 @@ export const crudHandler = createRouter()
149
149
  return serializeSession(session);
150
150
  })
151
151
 
152
- // Get session by ID (with messages)
152
+ // Get session by ID.
153
+ //
154
+ // The session only. It used to carry the whole message chain as well, which
155
+ // no caller read — opening a chat loads its messages through `messages:list`
156
+ // right after — so every chat open downloaded its entire history twice.
153
157
  .http('sessions:get', {
154
158
  data: t.Object({
155
159
  id: t.String({ minLength: 1 })
156
160
  }),
157
161
  response: t.Object({
158
- session: sessionSchema,
159
- messages: t.Array(t.Any())
162
+ session: sessionSchema
160
163
  })
161
164
  }, async ({ data }) => {
162
165
  const session = requireSessionAccess(data.id);
163
-
164
- // Also get messages for this session
165
- const messages = messageQueries.getBySessionId(data.id);
166
-
167
- return {
168
- session: serializeSession(session),
169
- messages
170
- };
166
+ return { session: serializeSession(session) };
171
167
  })
172
168
 
173
169
  // Get or create shared session
@@ -29,6 +29,7 @@ import {
29
29
  } from '../../database/queries';
30
30
  import { loadMessage } from '$shared/utils/message-formatter';
31
31
  import { blobStore } from '../../snapshot/blob-store';
32
+ import { blobLineStats } from '../../snapshot/line-stats';
32
33
  import { snapshotService } from '../../snapshot/snapshot-service';
33
34
  import { resolveSessionRoot } from '../../worktrees';
34
35
  import { makeScopeKey } from '$shared/utils/workspace-scope';
@@ -143,7 +144,6 @@ export const changesHandler = createRouter()
143
144
  requireSessionAccess(data.sessionId);
144
145
 
145
146
  const activePath = activeCheckpoints(data.sessionId);
146
- const readBlob = (hash: string) => blobStore.readBlob(hash);
147
147
 
148
148
  const turns = [];
149
149
  const settled: SessionScopedChanges[] = [];
@@ -152,7 +152,7 @@ export const changesHandler = createRouter()
152
152
  const snapshot = snapshotQueries.getByMessageId(checkpoint.id);
153
153
  const changes = parseSessionChanges(snapshot?.session_changes);
154
154
  settled.push(changes);
155
- const files = await buildTurnFiles(changes, readBlob);
155
+ const files = await buildTurnFiles(changes, blobLineStats);
156
156
 
157
157
  turns.push({
158
158
  checkpointMessageId: checkpoint.id,
@@ -166,7 +166,7 @@ export const changesHandler = createRouter()
166
166
  });
167
167
  }
168
168
 
169
- const net = await summariseNetChanges(settled, readBlob);
169
+ const net = await summariseNetChanges(settled, blobLineStats);
170
170
 
171
171
  // Newest first: the turn a user wants to review is almost always the last
172
172
  // one, and scrolling to reach it is a tax on the common case.
@@ -300,12 +300,11 @@ export const changesHandler = createRouter()
300
300
  );
301
301
  if (Object.keys(changes).length === 0) return { files: [], net: null };
302
302
 
303
- const readBlob = (hash: string) => blobStore.readBlob(hash);
304
- const files = await buildTurnFiles(changes, readBlob);
303
+ const files = await buildTurnFiles(changes, blobLineStats);
305
304
  const settled = activeCheckpoints(data.sessionId).map((checkpoint) =>
306
305
  parseSessionChanges(snapshotQueries.getByMessageId(checkpoint.id)?.session_changes)
307
306
  );
308
- const net = await summariseNetChanges([...settled, changes], readBlob);
307
+ const net = await summariseNetChanges([...settled, changes], blobLineStats);
309
308
  return { files, net };
310
309
  } catch (error) {
311
310
  debug.warn('snapshot', 'Failed to read pending changes:', error);
@@ -4,8 +4,8 @@
4
4
  *
5
5
  * Inbound client frames arrive on `terminal:pty`; each Clopen connection gets one
6
6
  * embedded `PtyKitConnection` whose `send` unicasts frames back on
7
- * `terminal:pty-out` (RPC responses + reattach replay) while PtyKit's own room
8
- * registry fans collaborative output out to every viewer. Identity (`userId`) is
7
+ * `terminal:pty-out` (RPC responses + reattach replay) while PtyKit fans a
8
+ * session's output out to every connection attached to it. Identity (`userId`) is
9
9
  * carried on the connection so `authorize` can enforce project access.
10
10
  */
11
11
 
package/bin/clopen.ts CHANGED
@@ -24,8 +24,10 @@ if (typeof globalThis.Bun === 'undefined') {
24
24
 
25
25
  import { existsSync, copyFileSync, readFileSync } from 'fs';
26
26
  import { join } from 'path';
27
+ import { homedir } from 'os';
27
28
  import { loadEnvFile } from '../backend/utils/env';
28
29
  import { runGitHelper } from '../backend/git/identity/cli';
30
+ import { stopOnSignals, stopRequestedBySignal, supervise } from '../shared/utils/process-supervisor';
29
31
 
30
32
  // CLI Options interface
31
33
  interface CLIOptions {
@@ -386,41 +388,46 @@ async function startServer(options: CLIOptions) {
386
388
 
387
389
  startSpinner('Starting server...');
388
390
 
389
- const serverProc = Bun.spawn(['bun', startScript], {
390
- cwd: __dirname,
391
- stdout: 'pipe',
392
- stderr: 'pipe',
393
- stdin: 'inherit',
394
- env,
395
- });
396
-
397
- // Forward subprocess output, stopping spinner on first chunk
391
+ // Output is forwarded as-is; the first chunk means the server is up.
398
392
  let spinnerActive = true;
399
-
400
- async function pipeStream(stream: ReadableStream<Uint8Array>, target: NodeJS.WriteStream) {
401
- const reader = stream.getReader();
393
+ const forward = (target: NodeJS.WriteStream) => (chunk: Uint8Array) => {
394
+ if (spinnerActive) {
395
+ stopSpinner();
396
+ spinnerActive = false;
397
+ }
402
398
  try {
403
- while (true) {
404
- const { done, value } = await reader.read();
405
- if (done) break;
406
- if (spinnerActive) {
407
- stopSpinner();
408
- spinnerActive = false;
409
- }
410
- target.write(value);
411
- }
412
- } finally {
413
- reader.releaseLock();
399
+ target.write(chunk);
400
+ } catch {
401
+ // The terminal is gone; the server keeps running regardless.
414
402
  }
415
- }
416
-
417
- await Promise.all([
418
- pipeStream(serverProc.stdout, process.stdout),
419
- pipeStream(serverProc.stderr, process.stderr),
420
- serverProc.exited,
421
- ]);
403
+ };
404
+
405
+ // Supervised: its own process group, restarted if it stops without being
406
+ // asked to, stopped with Ctrl+C / SIGTERM (e.g. `docker stop`) as before.
407
+ // See shared/utils/process-supervisor.ts.
408
+ const dataDir = env.CLOPEN_DATA_DIR?.trim() || join(homedir(), '.clopen');
409
+ const server = supervise({
410
+ name: 'server',
411
+ cmd: ['bun', startScript],
412
+ cwd: __dirname,
413
+ env,
414
+ onStdout: forward(process.stdout),
415
+ onStderr: forward(process.stderr),
416
+ log: (line) => {
417
+ if (spinnerActive) {
418
+ stopSpinner();
419
+ spinnerActive = false;
420
+ }
421
+ console.error(line);
422
+ },
423
+ reportFile: join(dataDir, 'logs', 'supervisor.log')
424
+ });
425
+ stopOnSignals([server]);
422
426
 
427
+ const code = await server.done;
423
428
  if (spinnerActive) stopSpinner();
429
+ // A stop asked for by Ctrl+C (or a closed terminal) exits from its handler.
430
+ if (!stopRequestedBySignal()) process.exit(code);
424
431
  }
425
432
 
426
433
  // ============================================================
@@ -0,0 +1 @@
1
+ � dU�?ϵ[��y�`�����djeɐ�)ɪ9uTl&�ebM~/D%6������B�ц9����3C�F����������半� ��bɿm�I ļ��);�N�E�K���3��vf&)�l���
@@ -0,0 +1,7 @@
1
+ (function(){"use strict";function I(n){for(;;){const e=n.next();if(e.done)return e.value}}function*W(n,e){const s=P(n),o=P(e),t=(yield*v(s,o)).length;return{additions:o.length-t,deletions:s.length-t}}function*B(n,e){const s=yield*v(n,e),o=[];let t=0,i=0;for(const[r,l]of s){for(;t<r;)o.push({type:"delete",oldIndex:t++});for(;i<l;)o.push({type:"insert",newIndex:i++});o.push({type:"keep",oldIndex:t++,newIndex:i++})}for(;t<n.length;)o.push({type:"delete",oldIndex:t++});for(;i<e.length;)o.push({type:"insert",newIndex:i++});return o}const K=(n,e)=>I(W(n,e)),b=(n,e)=>I(B(n,e)),z=(n,e)=>I(v(n,e)),F=(n,e)=>z(n,e).length;function*v(n,e){const s=[];let o=0;for(;o<n.length&&o<e.length&&n[o]===e[o];)s.push([o,o]),o++;let t=n.length,i=e.length;for(;t>o&&i>o&&n[t-1]===e[i-1];)t--,i--;if(t>o&&i>o){const r=new Map,l=new Int32Array(t-o),f=new Int32Array(i-o);let a=0;for(let h=o;h<t;h++)l[h-o]=E(r,n[h]),++a===16384&&(a=0,yield);for(let h=o;h<i;h++)f[h-o]=E(r,e[h]),++a===16384&&(a=0,yield);const d=new Uint8Array(r.size),g=new Uint8Array(r.size);for(let h=0;h<l.length;h++)d[l[h]]=1;for(let h=0;h<f.length;h++)g[f[h]]=1;const y=R(l,g),p=R(f,d);if(y.values.length>0&&p.values.length>0){const h=yield*G(y.values,p.values);for(let x=0;x<h.length;x++)h[x]>=0&&s.push([o+y.origin[x],o+p.origin[h[x]]])}}for(let r=0;r<n.length-t;r++)s.push([t+r,i+r]);return s}function E(n,e){let s=n.get(e);return s===void 0&&(s=n.size,n.set(e,s)),s}function R(n,e){const s=new Int32Array(n.length),o=new Int32Array(n.length);let t=0;for(let i=0;i<n.length;i++)e[n[i]]&&(s[t]=n[i],o[t]=i,t++);return{values:s.subarray(0,t),origin:o.subarray(0,t)}}function*G(n,e){const s=new j(n,e);for(;!s.step(16384);)yield;return s.matchOf}class j{constructor(e,s){this.a=e,this.b=s,this.matchOf=new Int32Array(e.length).fill(-1);const o=e.length+s.length;this.offset=o+1,this.vf=new Int32Array(2*o+3),this.vb=new Int32Array(2*o+3),this.stack=[0,e.length,0,s.length]}matchOf;vf;vb;offset;stack;searching=!1;aLo=0;aHi=0;bLo=0;bHi=0;d=0;k=0;backward=!1;step(e){const{a:s,b:o,matchOf:t,vf:i,vb:r,offset:l,stack:f}=this;for(;;){if(!this.searching){if(f.length===0)return!0;let c=f.pop(),w=f.pop(),S=f.pop(),k=f.pop();for(;k<S&&w<c&&s[k]===o[w];)t[k++]=w++;for(;k<S&&w<c&&s[S-1]===o[c-1];)t[--S]=--c;if(k>=S||w>=c)continue;this.aLo=k,this.aHi=S,this.bLo=w,this.bHi=c,this.d=0,this.k=0,this.backward=!1,this.searching=!0,i[l+1]=0,r[l+1]=0}const{aLo:a,aHi:d,bLo:g,bHi:y}=this,p=d-a,h=y-g,x=p-h,_=(x&1)!==0,lt=Math.ceil((p+h)/2);let m=this.d,u=this.k,A=this.backward,C=null;t:for(;C===null;){if(m>lt)throw new Error("diff: middle snake not found");if(!A){for(;u<=m;u+=2){let c=u===-m||u!==m&&i[l+u-1]<i[l+u+1]?i[l+u+1]:i[l+u-1]+1,w=c-u;const S=c,k=w;for(;c<p&&w<h&&s[a+c]===o[g+w];)c++,w++;i[l+u]=c;const L=x-u;if(_&&L>=-(m-1)&&L<=m-1&&c+r[l+L]>=p){C=[a+S,g+k,a+c,g+w];break t}if(e-=c-S+1,e<=0)return this.save(m,u+2,!1),!1}A=!0,u=-m}for(;u<=m;u+=2){let c=u===-m||u!==m&&r[l+u-1]<r[l+u+1]?r[l+u+1]:r[l+u-1]+1,w=c-u;const S=c,k=w;for(;c<p&&w<h&&s[d-1-c]===o[y-1-w];)c++,w++;r[l+u]=c;const L=x-u;if(!_&&L>=-m&&L<=m&&c+i[l+L]>=p){C=[a+p-c,g+h-w,a+p-S,g+h-k];break t}if(e-=c-S+1,e<=0)return this.save(m,u+2,!0),!1}m++,u=-m,A=!1}const[H,D,U,at]=C;for(let c=0;c<U-H;c++)t[H+c]=D+c;if(f.push(a,H,g,D,U,d,at,y),this.searching=!1,e<=0)return!1}}save(e,s,o){this.d=e,this.k=s,this.backward=o}}function P(n){if(!n)return[];const e=n.replace(/\r\n/g,`
2
+ `).split(`
3
+ `);return e.length>1&&e[e.length-1]===""&&e.pop(),e}function J(n){let e=1/0,s="";for(const o of n)if(o.trim()){const t=o.match(/^(\s*)/);if(t){const i=t[1].length;i<e&&(e=i,s=t[1].substring(0,e))}}return e>0&&e<1/0?{lines:n.map(o=>o.startsWith(s)?o.substring(e):o),commonIndent:s}:{lines:n,commonIndent:""}}function N(n,e){const{commonIndent:s}=J([...n,...e]);if(!s)return{oldLines:n,newLines:e,commonIndent:""};const o=s.length,t=i=>i.startsWith(s)?i.substring(o):i;return{oldLines:n.map(t),newLines:e.map(t),commonIndent:s}}const Y=.3;function Q(n,e,s){const{oldLines:o,newLines:t}=N(n.split(`
4
+ `),e.split(`
5
+ `)),i=[];let r=[],l=[];const f=()=>{r.length===0&&l.length===0||(s.highlights&&V(r,l),i.push(...r,...l),r=[],l=[])};for(const a of b(o,t))a.type==="keep"?(f(),i.push({type:"unchanged",content:o[a.oldIndex]})):a.type==="delete"?r.push({type:"removed",content:o[a.oldIndex]}):l.push({type:"added",content:t[a.newIndex]});return f(),i}function V(n,e){const s=Math.min(n.length,e.length);for(let o=0;o<s;o++){const t=n[o],i=e[o];if(t.content.length===0||i.content.length===0||X(t.content,i.content)<=Y)continue;const{oldHighlights:r,newHighlights:l}=Z(t.content,i.content);r.length>0&&(t.highlights=r),l.length>0&&(i.highlights=l)}}function X(n,e){const s=Math.max(n.length,e.length);return s===0?0:F(n.split(""),e.split(""))/s}function Z(n,e){const s=[],o=[];let t=0;const i=Math.min(n.length,e.length);for(;t<i&&n[t]===e[t];)t++;let r=0;const l=i-t;for(;r<l&&n[n.length-1-r]===e[e.length-1-r];)r++;const f=n.length-r,a=e.length-r;if(t>=f&&t>=a)return{oldHighlights:s,newHighlights:o};const d=n.substring(t,f),g=e.substring(t,a);if(d.length===0||g.length===0||!$(d,g))return d.length>0&&s.push({start:t,end:f}),g.length>0&&o.push({start:t,end:a}),{oldHighlights:s,newHighlights:o};const y=q(d,g);for(const p of y.oldRanges)s.push({start:t+p.start,end:t+p.end});for(const p of y.newRanges)o.push({start:t+p.start,end:t+p.end});return{oldHighlights:s,newHighlights:o}}function $(n,e,s=3){if(n.length<s||e.length<s)return!1;const o=new Set;for(let t=0;t<=e.length-s;t++)o.add(e.substring(t,t+s));for(let t=0;t<=n.length-s;t++)if(o.has(n.substring(t,t+s)))return!0;return!1}function q(n,e){const s=[],o=[],t=O(n),i=O(e);for(const r of b(t.map(l=>l.text),i.map(l=>l.text)))if(r.type==="delete"){const l=t[r.oldIndex];s.push({start:l.start,end:l.end})}else if(r.type==="insert"){const l=i[r.newIndex];o.push({start:l.start,end:l.end})}return{oldRanges:T(s),newRanges:T(o)}}function O(n){const e=[],s=/(\w+|[^\w]+)/g;let o;for(;(o=s.exec(n))!==null;)e.push({text:o[0],start:o.index,end:o.index+o[0].length});return e}function T(n){if(n.length===0)return[];n.sort((o,t)=>o.start-t.start);const e=[];let s=n[0];for(let o=1;o<n.length;o++){const t=n[o];t.start<=s.end?s={start:s.start,end:Math.max(s.end,t.end)}:(e.push(s),s=t)}return e.push(s),e}function tt(n){const e=[];let s=0,o=0,t=null;for(const i of n){if(i.type==="keep"){t=null,s++,o++;continue}t||(t={oldStart:s,oldCount:0,newStart:o,newCount:0},e.push(t)),i.type==="delete"?(t.oldCount++,s++):(t.newCount++,o++)}return e}function nt(n,e,s){return n.map(o=>{const t={...o};if(t.oldCount===0&&t.newCount>0)for(;t.newStart+t.newCount<s.length&&s[t.newStart]===s[t.newStart+t.newCount]&&e[t.oldStart]===s[t.newStart];)t.newStart++,t.oldStart++;else if(t.newCount===0&&t.oldCount>0)for(;t.oldStart+t.oldCount<e.length&&e[t.oldStart]===e[t.oldStart+t.oldCount]&&s[t.newStart]===e[t.oldStart];)t.oldStart++,t.newStart++;return t})}function M(n,e){if(n===e)return[];const s=n.split(`
6
+ `),o=e.split(`
7
+ `),t=nt(tt(b(s,o)),s,o),i=[];for(const r of t){const l=s.slice(r.oldStart,r.oldStart+r.oldCount),f=o.slice(r.newStart,r.newStart+r.newCount),a=r.oldCount>0?r.oldStart+1:0,d=r.oldCount>0?r.oldStart+r.oldCount:0;if(r.newCount>0&&r.oldCount>0)i.push({type:"modified",startLine:r.newStart+1,endLine:r.newStart+r.newCount,oldStartLine:a,oldEndLine:d,oldLines:l,newLines:f});else if(r.newCount>0)i.push({type:"added",startLine:r.newStart+1,endLine:r.newStart+r.newCount,oldStartLine:0,oldEndLine:0,oldLines:[],newLines:f});else{const g=Math.min(Math.max(r.newStart+1,1),Math.max(o.length,1));i.push({type:"deleted",startLine:g,endLine:g,oldStartLine:a,oldEndLine:d,oldLines:l,newLines:[]})}}return i}function et(n){return{oldCount:n.oldStartLine>0?n.oldEndLine-n.oldStartLine+1:0,newCount:n.type==="deleted"?0:n.endLine-n.startLine+1}}function ot(n){const e=[];let s=1,o=1;for(const t of n){const{oldCount:i,newCount:r}=et(t),l=Math.max(0,i>0?t.oldStartLine-s:t.startLine-o);l>0&&e.push({oldStart:s,newStart:o,length:l}),s+=l+i,o+=l+r}return e.push({oldStart:s,newStart:o,length:1/0}),t=>{if(t<1)return null;for(const i of e){if(t<i.oldStart)return null;if(t<i.oldStart+i.length)return i.newStart+(t-i.oldStart)}return null}}function st(n,e){const s=[];for(const o of n){if(o.type==="deleted"){const a=e(o.startLine);if(a===null)continue;s.push({...o,startLine:a,endLine:a,exact:!0});continue}let t=null,i=null,r=0;for(let a=o.startLine;a<=o.endLine;a++){const d=e(a);d!==null&&(r++,t===null&&(t=d),i=d)}if(t===null||i===null)continue;const l=i-t+1,f=o.endLine-o.startLine+1;s.push({...o,startLine:t,endLine:i,exact:r===f&&l===f})}return s}const it={block:n=>Q(n.oldString,n.newString,{highlights:n.highlights}),count:n=>K(n.oldContent,n.newContent),gutter:n=>M(n.before,n.after),turnGutter:n=>st(M(n.before,n.after),ot(M(n.after,n.buffer)))};function rt(n){try{const e=it[n.task];return{id:n.id,result:e(n.input)}}catch(e){return{id:n.id,error:e instanceof Error?e.message:String(e)}}}self.onmessage=n=>{self.postMessage(rt(n.data))}})();