@myrialabs/clopen 0.4.48 → 0.4.49

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/chat/message-pages.test.ts +163 -0
  2. package/backend/chat/message-pages.ts +233 -0
  3. package/backend/chat/stream-manager.ts +29 -5
  4. package/backend/database/migrations/087_create_blob_line_stats.ts +37 -0
  5. package/backend/database/migrations/index.ts +7 -0
  6. package/backend/database/queries/blob-line-stats-queries.ts +48 -0
  7. package/backend/database/queries/index.ts +2 -0
  8. package/backend/db-client/env/diff.ts +9 -33
  9. package/backend/db-client/env/env.test.ts +8 -8
  10. package/backend/db-client/env/service.ts +1 -1
  11. package/backend/files/file-watcher.ts +19 -0
  12. package/backend/git/contributors.test.ts +35 -0
  13. package/backend/git/contributors.ts +46 -0
  14. package/backend/http/static-assets.test.ts +78 -0
  15. package/backend/http/static-assets.ts +104 -0
  16. package/backend/index.ts +11 -9
  17. package/backend/preview/browser/browser-preview-service.ts +24 -6
  18. package/backend/snapshot/blob-store.ts +9 -1
  19. package/backend/snapshot/helpers.ts +3 -10
  20. package/backend/snapshot/line-stats.test.ts +80 -0
  21. package/backend/snapshot/line-stats.ts +64 -0
  22. package/backend/snapshot/snapshot-service.ts +14 -27
  23. package/backend/snapshot/turn-changes.test.ts +10 -5
  24. package/backend/snapshot/turn-changes.ts +78 -40
  25. package/backend/terminal/ptykit.ts +6 -1
  26. package/backend/utils/ws-wire.test.ts +87 -0
  27. package/backend/utils/ws-wire.ts +189 -0
  28. package/backend/utils/ws.ts +40 -38
  29. package/backend/ws/chat/stream.ts +41 -10
  30. package/backend/ws/files/read.ts +30 -0
  31. package/backend/ws/git/log.ts +52 -0
  32. package/backend/ws/messages/crud.ts +49 -0
  33. package/backend/ws/preview/index.ts +2 -0
  34. package/backend/ws/preview/watchers.ts +84 -0
  35. package/backend/ws/sessions/crud.ts +8 -12
  36. package/backend/ws/snapshot/changes.ts +5 -6
  37. package/backend/ws/terminal/tunnel.ts +2 -2
  38. package/bin/clopen.ts +36 -30
  39. package/dist/assets/addon-clipboard-wHJhZAA4.js.br +0 -0
  40. package/dist/assets/addon-clipboard-wHJhZAA4.js.gz +0 -0
  41. package/dist/assets/addon-fit-DX4qG4td.js.br +1 -0
  42. package/dist/assets/addon-fit-DX4qG4td.js.gz +0 -0
  43. package/dist/assets/addon-ligatures-DpDY8N_X.js.br +0 -0
  44. package/dist/assets/addon-ligatures-DpDY8N_X.js.gz +0 -0
  45. package/dist/assets/addon-unicode11-Bt8F3D7-.js.br +0 -0
  46. package/dist/assets/addon-unicode11-Bt8F3D7-.js.gz +0 -0
  47. package/dist/assets/addon-web-links-DIbG5aQx.js.br +0 -0
  48. package/dist/assets/addon-web-links-DIbG5aQx.js.gz +0 -0
  49. package/dist/assets/diff.worker-BoHLxmr2.js +7 -0
  50. package/dist/assets/diff.worker-BoHLxmr2.js.br +0 -0
  51. package/dist/assets/diff.worker-BoHLxmr2.js.gz +0 -0
  52. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.br +0 -0
  53. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.gz +0 -0
  54. package/dist/assets/{index-CONlwAXZ.js → index-CrVWZH_D.js} +1 -1
  55. package/dist/assets/index-CrVWZH_D.js.br +0 -0
  56. package/dist/assets/index-CrVWZH_D.js.gz +0 -0
  57. package/dist/assets/{index-DJzwt-hq.js → index-DD0-3EWg.js} +1 -1
  58. package/dist/assets/index-DD0-3EWg.js.br +0 -0
  59. package/dist/assets/index-DD0-3EWg.js.gz +0 -0
  60. package/dist/assets/{main-nBOb9YOA.js → main-D2_TmcwQ.js} +604 -604
  61. package/dist/assets/main-D2_TmcwQ.js.br +0 -0
  62. package/dist/assets/main-D2_TmcwQ.js.gz +0 -0
  63. package/dist/assets/main-Yucigcmf.css +1 -0
  64. package/dist/assets/main-Yucigcmf.css.br +0 -0
  65. package/dist/assets/main-Yucigcmf.css.gz +0 -0
  66. package/dist/assets/preview-video.worker-DcpDhCWL.js.br +0 -0
  67. package/dist/assets/preview-video.worker-DcpDhCWL.js.gz +0 -0
  68. package/dist/assets/xterm-B-qIQCd3.js.br +0 -0
  69. package/dist/assets/xterm-B-qIQCd3.js.gz +0 -0
  70. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.br +0 -0
  71. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.gz +0 -0
  72. package/dist/fonts/dm-sans.css.br +0 -0
  73. package/dist/fonts/dm-sans.css.gz +0 -0
  74. package/dist/index.html +2 -2
  75. package/dist/index.html.br +0 -0
  76. package/dist/index.html.gz +0 -0
  77. package/dist/sw.js.br +0 -0
  78. package/dist/sw.js.gz +0 -0
  79. package/package.json +2 -3
  80. package/shared/types/unified/stream.ts +11 -1
  81. package/shared/utils/diff-calculator.test.ts +178 -41
  82. package/shared/utils/diff-calculator.ts +383 -100
  83. package/shared/utils/process-supervisor.test.ts +172 -0
  84. package/shared/utils/process-supervisor.ts +251 -0
  85. package/shared/utils/ws-chunk.test.ts +33 -0
  86. package/shared/utils/ws-chunk.ts +73 -0
  87. package/shared/utils/ws-client-chunks.test.ts +45 -0
  88. package/shared/utils/ws-client.ts +43 -0
  89. package/shared/utils/ws-server.ts +17 -14
  90. package/backend/database/migrations/086_single_owner.test.ts +0 -170
  91. package/dist/assets/main-BUiUL3eZ.css +0 -1
@@ -34,18 +34,13 @@ import type { WSConnection } from '$shared/utils/ws-server';
34
34
  import { encodeBinaryMessage, isBinaryAction } from '$shared/utils/ws-server';
35
35
  import { debug } from '$shared/utils/logger';
36
36
  import { clientIpFromConnection } from './client-ip';
37
+ import { sendBinary, sendText } from './ws-wire';
37
38
 
38
- /**
39
- * Performance configuration
40
- */
41
- const CONFIG = {
42
- /** Maximum send buffer before dropping frames (bytes) */
43
- MAX_BUFFER_SIZE: 1024 * 1024, // 1MB
44
- /** Enable backpressure handling */
45
- ENABLE_BACKPRESSURE: true,
46
- /** Log dropped frames */
47
- LOG_DROPPED_FRAMES: true
48
- };
39
+ /** The action of a serialized `{"action":"…",…}` event, for the traffic meter. */
40
+ function actionOf(message: string): string {
41
+ const match = /^\{"action":"([^"]+)"/.exec(message);
42
+ return match ? match[1] : 'unknown';
43
+ }
49
44
 
50
45
  /**
51
46
  * Metrics for monitoring
@@ -54,7 +49,6 @@ interface WSMetrics {
54
49
  totalConnections: number;
55
50
  activeProjects: number;
56
51
  activeUsers: number;
57
- droppedFrames: number;
58
52
  totalEmits: number;
59
53
  }
60
54
 
@@ -117,7 +111,6 @@ class WSServer {
117
111
  totalConnections: 0,
118
112
  activeProjects: 0,
119
113
  activeUsers: 0,
120
- droppedFrames: 0,
121
114
  totalEmits: 0
122
115
  };
123
116
 
@@ -731,33 +724,22 @@ class WSServer {
731
724
  }
732
725
 
733
726
  /**
734
- * Check if connection can receive data (backpressure check)
727
+ * Whether a connection can be written to at all.
728
+ *
729
+ * Deliberately not a backpressure gate. An earlier one dropped events while
730
+ * the socket's buffer held more than 1 MB — but it read `getBufferedAmount`
731
+ * off Elysia's wrapper, which does not have it, so it never fired. Making it
732
+ * fire would be worse than leaving it dead: events are a stream the client
733
+ * reassembles (stream deltas, file changes, terminal output), and a silently
734
+ * missing one is a wrong screen. What used to fill the buffer — one huge
735
+ * reply — is now chunked and drained instead (backend/utils/ws-wire.ts).
735
736
  */
736
737
  private canSend(conn: WSConnection): boolean {
737
- if (!CONFIG.ENABLE_BACKPRESSURE) return true;
738
-
739
- // Check WebSocket ready state
740
- if (conn.readyState !== 1) return false;
741
-
742
- // Check buffer size if available (Bun/uWebSockets)
743
- const rawWs = conn as any;
744
- if (typeof rawWs.getBufferedAmount === 'function') {
745
- const buffered = rawWs.getBufferedAmount();
746
- if (buffered > CONFIG.MAX_BUFFER_SIZE) {
747
- if (CONFIG.LOG_DROPPED_FRAMES) {
748
- this.metrics.droppedFrames++;
749
- const id = this.resolveId(conn) || 'unknown';
750
- debug.warn('websocket', `Backpressure: dropping frame for ${id} (buffer: ${buffered})`);
751
- }
752
- return false;
753
- }
754
- }
755
-
756
- return true;
738
+ return conn.readyState === 1;
757
739
  }
758
740
 
759
741
  /**
760
- * Send message to a single connection with backpressure handling
742
+ * Send a serialized event to a single connection.
761
743
  */
762
744
  private sendToConnection(conn: WSConnection, message: string | ArrayBuffer): boolean {
763
745
  if (!this.canSend(conn)) {
@@ -765,11 +747,10 @@ class WSServer {
765
747
  }
766
748
 
767
749
  try {
768
- // For binary data (ArrayBuffer), wrap in Buffer for Bun/Elysia compatibility
769
750
  if (message instanceof ArrayBuffer) {
770
- conn.send(Buffer.from(message));
751
+ sendBinary(conn, 'binary-event', message);
771
752
  } else {
772
- conn.send(message);
753
+ sendText(conn, actionOf(message), message);
773
754
  }
774
755
  return true;
775
756
  } catch (err) {
@@ -851,6 +832,27 @@ class WSServer {
851
832
  debug.log('websocket', `Emitted ${eventStr}${hasBinary ? ' (binary)' : ''} to ${sentCount}/${room.size} connections in project ${projectId}`);
852
833
  },
853
834
 
835
+ /**
836
+ * Emit to the connections of a project room that pass `include` — for a
837
+ * stream only some of the room is looking at (a panel's live detail).
838
+ */
839
+ projectWhere: <K extends keyof WSAPI['server']>(
840
+ projectId: string,
841
+ include: (connectionId: string) => boolean,
842
+ event: K,
843
+ payload: WSAPI['server'][K]
844
+ ): void => {
845
+ this.metrics.totalEmits++;
846
+ const room = this.projectRooms.get(projectId);
847
+ if (!room || room.size === 0) return;
848
+ let message: string | null = null;
849
+ for (const [connectionId, wsConn] of room) {
850
+ if (!include(connectionId)) continue;
851
+ message ??= JSON.stringify({ action: event, payload });
852
+ this.sendToConnection(wsConn, message);
853
+ }
854
+ },
855
+
854
856
  /**
855
857
  * Emit event to all connections of a specific user
856
858
  */
@@ -207,20 +207,31 @@ const chatSessionModelState = new Map<string, { engine: string; provider: string
207
207
  // In-memory store for account state per chat session (keyed by chatSessionId)
208
208
  const chatSessionAccountState = new Map<string, { accountId: number | null; senderId: string }>();
209
209
 
210
+ /** Streams currently forwarded to their room — at most one bridge each. */
211
+ const roomBridges = new Map<string, () => void>();
212
+
210
213
  /**
211
214
  * Forward one stream's events to its chat session room until the stream ends.
212
215
  *
213
216
  * Every path that attaches a stream to the room goes through here — the
214
217
  * sender's own request, a client re-attaching after a refresh, and a queued
215
218
  * message the server starts on its own — so the event wire format exists once.
216
- * Returns the unsubscribe; a terminal event unsubscribes by itself.
219
+ *
220
+ * Idempotent per stream, and not tied to any connection. A bridge emits to the
221
+ * whole room, so one is all a room ever needs: every client that re-attached
222
+ * used to add its own, and each frame then reached every device once per
223
+ * bridge (the client dropped the copies by `seq`, the bandwidth was spent).
224
+ * Tying a bridge to its connection had the opposite failure: when the sender's
225
+ * tab closed, its bridge went with it and the other devices still in the room
226
+ * stopped receiving the turn. It lives until the stream's terminal event.
217
227
  */
218
228
  export function bridgeStreamToRoom(
219
229
  streamId: string,
220
230
  chatSessionId: string,
221
231
  projectId: string | undefined,
222
232
  options: { presenceOnConnection?: boolean } = {}
223
- ): () => void {
233
+ ): void {
234
+ if (roomBridges.has(streamId)) return;
224
235
  const { presenceOnConnection = true } = options;
225
236
 
226
237
  const handleStreamEvent = (event: StreamEvent) => {
@@ -262,7 +273,9 @@ export function bridgeStreamToRoom(
262
273
  chatSessionId,
263
274
  processId: event.processId,
264
275
  eventType: event.data.eventType as any,
265
- partialText: event.data.partialText || '',
276
+ block: event.data.block ?? 0,
277
+ ...(typeof event.data.offset === 'number' && { offset: event.data.offset }),
278
+ ...(typeof event.data.partialText === 'string' && { partialText: event.data.partialText }),
266
279
  deltaText: event.data.deltaText || '',
267
280
  ...(event.data.reasoning && { reasoning: true }),
268
281
  timestamp: event.data.timestamp,
@@ -335,8 +348,17 @@ export function bridgeStreamToRoom(
335
348
  }
336
349
  };
337
350
 
338
- const unsubscribe = streamManager.subscribeToStream(streamId, handleStreamEvent);
339
- return unsubscribe;
351
+ const stopForwarding = streamManager.subscribeToStream(streamId, handleStreamEvent);
352
+ const unsubscribe = () => {
353
+ stopForwarding();
354
+ roomBridges.delete(streamId);
355
+ };
356
+ roomBridges.set(streamId, unsubscribe);
357
+
358
+ // A stream that ended before it was bridged will never send the terminal
359
+ // event that removes the bridge.
360
+ const status = streamManager.getStream(streamId)?.status;
361
+ if (status && status !== 'active') unsubscribe();
340
362
  }
341
363
 
342
364
  /**
@@ -523,9 +545,8 @@ export const streamHandler = createRouter()
523
545
  });
524
546
  if (!streamId) return;
525
547
 
526
- // Tied to this connection: it closes with the connection, and the
527
- // client's reconnect builds a new one.
528
- ws.addCleanup(conn, bridgeStreamToRoom(streamId, data.chatSessionId, projectId));
548
+ // One bridge per stream, living until the stream ends — see bridgeStreamToRoom.
549
+ bridgeStreamToRoom(streamId, data.chatSessionId, projectId);
529
550
  })
530
551
 
531
552
  // Reconnect to an active stream (after browser refresh / project switch)
@@ -548,7 +569,7 @@ export const streamHandler = createRouter()
548
569
 
549
570
  debug.log('chat', 'Reconnecting to active stream:', streamState.streamId);
550
571
 
551
- ws.addCleanup(conn, bridgeStreamToRoom(streamState.streamId, chatSessionId, projectId, { presenceOnConnection: false }));
572
+ bridgeStreamToRoom(streamState.streamId, chatSessionId, projectId, { presenceOnConnection: false });
552
573
 
553
574
  // Send current state snapshot to chat session room so frontend can catch up
554
575
  ws.emit.chatSession(chatSessionId, 'chat:connection', {
@@ -618,6 +639,9 @@ export const streamHandler = createRouter()
618
639
  messages: t.Array(t.Any()),
619
640
  currentPartialText: t.Optional(t.String()),
620
641
  currentReasoningText: t.Optional(t.String()),
642
+ /** The blocks those two texts belong to (see `chat:partial`). */
643
+ partialBlock: t.Optional(t.Number()),
644
+ reasoningBlock: t.Optional(t.Number()),
621
645
  error: t.Optional(t.String()),
622
646
  startedAt: t.String(),
623
647
  completedAt: t.Optional(t.String())
@@ -663,6 +687,8 @@ export const streamHandler = createRouter()
663
687
  }),
664
688
  currentPartialText: streamState.currentPartialText,
665
689
  currentReasoningText: streamState.currentReasoningText,
690
+ partialBlock: streamState.partialBlock,
691
+ reasoningBlock: streamState.reasoningBlock,
666
692
  error: streamState.error,
667
693
  startedAt: streamState.startedAt.toISOString(),
668
694
  completedAt: streamState.completedAt?.toISOString()
@@ -931,7 +957,12 @@ export const streamHandler = createRouter()
931
957
  t.Literal('update'),
932
958
  t.Literal('end')
933
959
  ]),
934
- partialText: t.String(),
960
+ /** Changes on every `start`; deltas only apply within their block. */
961
+ block: t.Number(),
962
+ /** Length of the block's text before `deltaText` (start/update). */
963
+ offset: t.Optional(t.Number()),
964
+ /** The block's full text — on `end` only. */
965
+ partialText: t.Optional(t.String()),
935
966
  deltaText: t.String(),
936
967
  reasoning: t.Optional(t.Boolean()),
937
968
  timestamp: t.String(),
@@ -179,6 +179,36 @@ export const readHandler = createRouter()
179
179
  return result;
180
180
  })
181
181
 
182
+ /**
183
+ * Size and modification time of several files at once, without their
184
+ * contents. The Files panel's safety-net check on focus uses it to re-read
185
+ * only the open tabs whose file actually changed, instead of downloading
186
+ * every open file again on every alt-tab. `modified` is in the same format
187
+ * `files:read-file` returns, so the two compare directly.
188
+ */
189
+ .http('files:read-stats', {
190
+ data: t.Object({
191
+ file_paths: t.Array(t.String())
192
+ }),
193
+ response: t.Array(t.Object({
194
+ /** The path as requested. */
195
+ path: t.String(),
196
+ exists: t.Boolean(),
197
+ size: t.Optional(t.Number()),
198
+ modified: t.Optional(t.String())
199
+ }))
200
+ }, async ({ data }) => {
201
+ return await Promise.all(data.file_paths.map(async (requested) => {
202
+ try {
203
+ const stats = await Bun.file(await resolveFilePath(requested)).stat();
204
+ if (!stats.isFile()) return { path: requested, exists: false };
205
+ return { path: requested, exists: true, size: stats.size, modified: stats.mtime.toISOString() };
206
+ } catch {
207
+ return { path: requested, exists: false };
208
+ }
209
+ }));
210
+ })
211
+
182
212
  // Read file content at a git ref (e.g. HEAD) for diff comparison
183
213
  .http('files:read-file-at', {
184
214
  data: t.Object({
@@ -8,6 +8,7 @@ import { createRouter } from '$shared/utils/ws-server';
8
8
  import { gitService } from '../../git/git-service';
9
9
  import { requireProjectWorkspace } from '../access';
10
10
  import { debug } from '$shared/utils/logger';
11
+ import { aggregateContributors, contributorKey, CONTRIBUTOR_WINDOW } from '../../git/contributors';
11
12
 
12
13
  /**
13
14
  * Resolve the working directory for a git operation. Defaults to the project
@@ -61,6 +62,57 @@ export const logHandler = createRouter()
61
62
  );
62
63
  })
63
64
 
65
+ /**
66
+ * Who authored the last `CONTRIBUTOR_WINDOW` commits, as counts. The panel used
67
+ * to download those commits in full on every git change to work this out.
68
+ */
69
+ .http('git:list-contributors', {
70
+ data: t.Object({
71
+ projectId: t.String(),
72
+ repoPath: t.Optional(t.String())
73
+ }),
74
+ response: t.Object({
75
+ contributors: t.Array(t.Object({
76
+ key: t.String(),
77
+ name: t.String(),
78
+ email: t.String(),
79
+ count: t.Number(),
80
+ lastDate: t.String()
81
+ })),
82
+ /** Commits sampled — the denominator of each contributor's share. */
83
+ total: t.Number()
84
+ })
85
+ }, async ({ data, conn }) => {
86
+ const { root } = requireProjectWorkspace(conn, data.projectId);
87
+ const cwd = resolveRepoCwd(root, data.repoPath);
88
+ const { commits } = await gitService.getLog(cwd, CONTRIBUTOR_WINDOW, 0);
89
+ return { contributors: aggregateContributors(commits), total: commits.length };
90
+ })
91
+
92
+ /** One contributor's commits within the same window — read when a row is expanded. */
93
+ .http('git:list-contributor-commits', {
94
+ data: t.Object({
95
+ projectId: t.String(),
96
+ key: t.String(),
97
+ repoPath: t.Optional(t.String())
98
+ }),
99
+ response: t.Array(t.Object({
100
+ hash: t.String(),
101
+ hashShort: t.String(),
102
+ author: t.String(),
103
+ authorEmail: t.String(),
104
+ date: t.String(),
105
+ message: t.String(),
106
+ parents: t.Array(t.String()),
107
+ refs: t.Optional(t.Array(t.String()))
108
+ }))
109
+ }, async ({ data, conn }) => {
110
+ const { root } = requireProjectWorkspace(conn, data.projectId);
111
+ const cwd = resolveRepoCwd(root, data.repoPath);
112
+ const { commits } = await gitService.getLog(cwd, CONTRIBUTOR_WINDOW, 0);
113
+ return commits.filter((commit) => contributorKey(commit) === data.key);
114
+ })
115
+
64
116
  /**
65
117
  * The repo's undo journal. Unlike `git log` this still lists commits that a
66
118
  * reset, a branch delete or a rebase orphaned, so it is the recovery path for
@@ -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,53 @@ 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
+ /** Minimum page size; the page is extended back to the start of a turn. */
47
+ limit: t.Optional(t.Number({ minimum: 1, maximum: 500 }))
48
+ }),
49
+ response: t.Object({
50
+ messages: t.Array(t.Any()),
51
+ hasMore: t.Boolean()
52
+ })
53
+ }, async ({ data }) => {
54
+ requireSessionAccess(data.session_id);
55
+ return getMessagePage(data.session_id, { beforeId: data.before_id, minCount: data.limit });
56
+ })
57
+
58
+ // Every user prompt on the active branch — the chat's navigation rail.
59
+ .http('messages:list-prompts', {
60
+ data: t.Object({
61
+ session_id: t.String({ minLength: 1 })
62
+ }),
63
+ response: t.Array(t.Object({
64
+ messageId: t.String(),
65
+ text: t.String(),
66
+ createdAt: t.String()
67
+ }))
68
+ }, async ({ data }) => {
69
+ requireSessionAccess(data.session_id);
70
+ return getPromptIndex(data.session_id);
71
+ })
72
+
73
+ // Task-tool calls and results older than a message — the task widget replays
74
+ // them together with the loaded messages.
75
+ .http('messages:list-task-history', {
76
+ data: t.Object({
77
+ session_id: t.String({ minLength: 1 }),
78
+ before_id: t.String({ minLength: 1 })
79
+ }),
80
+ response: t.Array(t.Any())
81
+ }, async ({ data }) => {
82
+ requireSessionAccess(data.session_id);
83
+ return getTaskHistory(data.session_id, data.before_id);
84
+ })
85
+
37
86
  // Get message by ID
38
87
  .http('messages:get', {
39
88
  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