@myrialabs/clopen 0.4.13 → 0.4.15

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 (49) hide show
  1. package/backend/auth/permissions.ts +2 -0
  2. package/backend/database/migrations/056_support_mssql_driver.ts +137 -0
  3. package/backend/database/migrations/index.ts +7 -0
  4. package/backend/database/queries/engine-queries.ts +13 -0
  5. package/backend/database/queries/message-queries.ts +43 -1
  6. package/backend/db-client/connection-manager.ts +8 -2
  7. package/backend/db-client/drivers/mssql.ts +829 -0
  8. package/backend/db-client/drivers/mysql.ts +33 -4
  9. package/backend/db-client/drivers/postgres.ts +55 -5
  10. package/backend/db-client/drivers/sql-builders.test.ts +70 -0
  11. package/backend/db-client/drivers/sql-builders.ts +9 -2
  12. package/backend/db-client/pool-config.ts +32 -0
  13. package/backend/db-client/query-executor.test.ts +42 -0
  14. package/backend/db-client/query-executor.ts +47 -3
  15. package/backend/engine/adapters/opencode/config.ts +9 -0
  16. package/backend/engine/adapters/opencode/models.ts +10 -1
  17. package/backend/engine/adapters/opencode/server.ts +110 -2
  18. package/backend/index.ts +11 -4
  19. package/backend/preview/browser/browser-preview-service.ts +15 -6
  20. package/backend/preview/browser/browser-video-capture.ts +232 -100
  21. package/backend/preview/browser/scripts/video-stream.ts +216 -56
  22. package/backend/preview/browser/types.ts +24 -12
  23. package/backend/utils/bun-compat.ts +5 -1
  24. package/backend/ws/chat/stream.ts +12 -4
  25. package/backend/ws/db-client/connections.ts +2 -1
  26. package/backend/ws/db-client/query.ts +41 -4
  27. package/backend/ws/db-client/schema.ts +45 -1
  28. package/backend/ws/engine/claude/accounts.ts +37 -13
  29. package/backend/ws/engine/codex/accounts.ts +36 -4
  30. package/backend/ws/engine/copilot/accounts.ts +12 -0
  31. package/backend/ws/engine/opencode/providers.ts +72 -1
  32. package/backend/ws/engine/qwen/accounts.ts +22 -0
  33. package/backend/ws/messages/crud.ts +13 -0
  34. package/backend/ws/preview/browser/interact.ts +10 -8
  35. package/backend/ws/preview/browser/webcodecs.ts +26 -2
  36. package/bin/clopen.ts +3 -0
  37. package/bunfig.toml +4 -0
  38. package/dist/assets/{index-BWf-DDJN.js → index-ChF_jIXj.js} +1 -1
  39. package/dist/assets/{index-CDZf6lfv.js → index-EunAFLxP.js} +1 -1
  40. package/dist/assets/{main-C15mQTCW.js → main-CTs4NXwP.js} +407 -367
  41. package/dist/assets/main-moCAkEwm.css +1 -0
  42. package/dist/index.html +2 -2
  43. package/package.json +6 -1
  44. package/shared/types/db-client/connection.ts +1 -1
  45. package/shared/types/db-client/query.ts +4 -1
  46. package/shared/utils/db-client/split-sql.test.ts +13 -0
  47. package/shared/utils/db-client/split-sql.ts +38 -1
  48. package/shared/utils/subagent-wire-trim.ts +87 -0
  49. package/dist/assets/main-Ba5ZGlY4.css +0 -1
@@ -29,6 +29,31 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
29
29
  let videoFrameCount = 0;
30
30
  let audioFrameCount = 0;
31
31
  let lastKeyframeTime = 0;
32
+ let forceNextKeyframe = false;
33
+ let motionSeq = 0; // Increments per motion frame — used to detect staleness of deferred top-offs
34
+ let topOffRetryTimer: any = null;
35
+
36
+ // Codec selection: prefer VP9 in quantizer mode (per-frame quality control,
37
+ // Chrome-Remote-Desktop-style), fall back to VP8 with fixed bitrate.
38
+ // codecId is embedded in every video packet so the client picks the right decoder.
39
+ // vp9Allowed comes from the CLIENT (decode capability, negotiated at stream
40
+ // start) — the headless browser can encode VP9, but the viewer must decode it.
41
+ let codecId = 0; // 0 = vp8, 1 = vp9
42
+ let usingQuantizer = false;
43
+ let vp9Allowed = true;
44
+
45
+ // Source-side backpressure threshold: when the DataChannel can't drain
46
+ // (slow network), skip encoding motion frames instead of queueing them.
47
+ // Kept SMALL (≈ 2-3 motion frames) on purpose: anything queued here is
48
+ // display latency. Quality adapts to congestion via the quantizer ladder
49
+ // (see currentMotionQuantizer) long before frames get skipped, so the
50
+ // stream degrades to coarser-but-current rather than sharp-but-stale.
51
+ const MAX_BUFFERED_BYTES = 64 * 1024;
52
+
53
+ // Frames larger than this are split into fragments (packet type 2) to stay
54
+ // well under the SCTP max-message-size (~256KB on common WebRTC stacks).
55
+ // Mostly hit by near-lossless top-off keyframes of complex pages.
56
+ const FRAGMENT_SIZE = 64 * 1024;
32
57
 
33
58
  // Cursor tracking
34
59
  let lastCursor = 'default';
@@ -93,22 +118,53 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
93
118
  lastCursor = 'default';
94
119
  }
95
120
 
96
- // Detect supported video codec
97
- async function detectVideoCodec() {
98
- const codecConfig: VideoEncoderConfig = {
121
+ // Build encoder config for the currently selected codec mode
122
+ function buildEncoderConfig(width: number, height: number, bitrate?: number): VideoEncoderConfig {
123
+ if (usingQuantizer) {
124
+ // Quantizer mode: no bitrate — quality is controlled per-frame in encode()
125
+ return {
126
+ codec: 'vp09.00.10.08',
127
+ width,
128
+ height,
129
+ framerate: config.framerate,
130
+ bitrateMode: 'quantizer',
131
+ hardwareAcceleration: config.hardwareAcceleration,
132
+ latencyMode: config.latencyMode
133
+ } as VideoEncoderConfig;
134
+ }
135
+
136
+ return {
99
137
  codec: config.codec,
100
- width: config.width,
101
- height: config.height,
102
- bitrate: config.bitrate,
138
+ width,
139
+ height,
140
+ bitrate: bitrate || config.bitrate,
103
141
  framerate: config.framerate,
104
142
  hardwareAcceleration: config.hardwareAcceleration,
105
143
  latencyMode: config.latencyMode
106
144
  };
145
+ }
146
+
147
+ // Detect supported video codec — prefer VP9 quantizer mode, fall back to VP8
148
+ async function detectVideoCodec() {
149
+ if (vp9Allowed) {
150
+ usingQuantizer = true;
151
+ codecId = 1;
152
+ const vp9Config = buildEncoderConfig(config.width, config.height);
153
+ try {
154
+ const support = await VideoEncoder.isConfigSupported(vp9Config);
155
+ if (support.supported) {
156
+ return vp9Config;
157
+ }
158
+ } catch (e) {}
159
+ }
107
160
 
161
+ usingQuantizer = false;
162
+ codecId = 0;
163
+ const vp8Config = buildEncoderConfig(config.width, config.height);
108
164
  try {
109
- const support = await VideoEncoder.isConfigSupported(codecConfig);
165
+ const support = await VideoEncoder.isConfigSupported(vp8Config);
110
166
  if (support.supported) {
111
- return codecConfig;
167
+ return vp8Config;
112
168
  }
113
169
  } catch (e) {}
114
170
 
@@ -150,17 +206,21 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
150
206
 
151
207
  peerConnection.oniceconnectionstatechange = () => {};
152
208
 
153
- // Create DataChannel for encoded chunks
209
+ // Create DataChannel for encoded chunks.
210
+ // Reliable + ordered: VP8/VP9 delta chains require in-order, lossless
211
+ // delivery — a single lost/reordered chunk corrupts decoding until the
212
+ // next keyframe (smearing/ghosting). Latency is bounded by source-side
213
+ // frame dropping instead (see MAX_BUFFERED_BYTES backpressure).
154
214
  dataChannel = peerConnection.createDataChannel('media', {
155
- ordered: false, // Allow out-of-order delivery for lower latency
156
- maxRetransmits: 0 // No retransmits = lower latency
215
+ ordered: true
157
216
  });
158
217
 
159
218
  dataChannel.binaryType = 'arraybuffer';
160
219
 
161
220
  dataChannel.onopen = () => {
162
- // Force keyframe when DataChannel opens (previous keyframes may have been lost)
163
- lastKeyframeTime = 0;
221
+ // Force keyframe when DataChannel opens — the decoder on the other
222
+ // side needs a sync point (keyframes are on-demand only)
223
+ forceNextKeyframe = true;
164
224
  };
165
225
 
166
226
  dataChannel.onclose = () => {};
@@ -191,30 +251,62 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
191
251
  function handleEncodedVideoChunk(chunk: EncodedVideoChunk, metadata: any) {
192
252
  if (!dataChannel || dataChannel.readyState !== 'open') return;
193
253
 
194
- // Send chunk via DataChannel
195
- // Format: [type(1)][timestamp(8)][keyframe(1)][size(4)][data]
196
254
  const isKeyframe = chunk.type === 'key' ? 1 : 0;
197
255
  const timestamp = chunk.timestamp;
198
256
  const data = new Uint8Array(chunk.byteLength);
199
257
  chunk.copyTo(data);
200
258
 
201
- const packet = new ArrayBuffer(1 + 8 + 1 + 4 + data.byteLength);
202
- const view = new DataView(packet);
203
- const packetData = new Uint8Array(packet);
204
-
205
- // Type: 0 = video
206
- view.setUint8(0, 0);
207
- // Timestamp (microseconds)
208
- view.setBigUint64(1, BigInt(timestamp), true);
209
- // Keyframe flag
210
- view.setUint8(9, isKeyframe);
211
- // Data size
212
- view.setUint32(10, data.byteLength, true);
213
- // Copy data
214
- packetData.set(data, 14);
215
-
216
259
  try {
217
- dataChannel.send(packet);
260
+ if (data.byteLength <= FRAGMENT_SIZE) {
261
+ // Single packet
262
+ // Format: [type=0(1)][timestamp(8)][keyframe(1)][codec(1)][size(4)][data]
263
+ const packet = new ArrayBuffer(1 + 8 + 1 + 1 + 4 + data.byteLength);
264
+ const view = new DataView(packet);
265
+ const packetData = new Uint8Array(packet);
266
+
267
+ // Type: 0 = video
268
+ view.setUint8(0, 0);
269
+ // Timestamp (microseconds)
270
+ view.setBigUint64(1, BigInt(timestamp), true);
271
+ // Keyframe flag
272
+ view.setUint8(9, isKeyframe);
273
+ // Codec: 0 = vp8, 1 = vp9 (lets the client pick the right decoder)
274
+ view.setUint8(10, codecId);
275
+ // Data size
276
+ view.setUint32(11, data.byteLength, true);
277
+ // Copy data
278
+ packetData.set(data, 15);
279
+
280
+ dataChannel.send(packet);
281
+ } else {
282
+ // Large frame (e.g. near-lossless top-off keyframe) — fragment.
283
+ // The channel is reliable + ordered, so fragments arrive in order
284
+ // and the client simply reassembles by index.
285
+ // Format: [type=2(1)][timestamp(8)][keyframe(1)][codec(1)][fragIndex(2)][fragCount(2)][size(4)][data]
286
+ const fragCount = Math.ceil(data.byteLength / FRAGMENT_SIZE);
287
+
288
+ for (let i = 0; i < fragCount; i++) {
289
+ const start = i * FRAGMENT_SIZE;
290
+ const fragData = data.subarray(start, Math.min(start + FRAGMENT_SIZE, data.byteLength));
291
+
292
+ const packet = new ArrayBuffer(1 + 8 + 1 + 1 + 2 + 2 + 4 + fragData.byteLength);
293
+ const view = new DataView(packet);
294
+ const packetData = new Uint8Array(packet);
295
+
296
+ // Type: 2 = video fragment
297
+ view.setUint8(0, 2);
298
+ view.setBigUint64(1, BigInt(timestamp), true);
299
+ view.setUint8(9, isKeyframe);
300
+ view.setUint8(10, codecId);
301
+ view.setUint16(11, i, true);
302
+ view.setUint16(13, fragCount, true);
303
+ view.setUint32(15, fragData.byteLength, true);
304
+ packetData.set(fragData, 19);
305
+
306
+ dataChannel.send(packet);
307
+ }
308
+ }
309
+
218
310
  videoFrameCount++;
219
311
  } catch (e) {}
220
312
  }
@@ -223,6 +315,10 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
223
315
  function sendAudioChunk(timestamp: number, data: Uint8Array) {
224
316
  if (!dataChannel || dataChannel.readyState !== 'open') return;
225
317
 
318
+ // Backpressure: drop audio when the channel is congested — the client's
319
+ // playback scheduler handles gaps cleanly, and stale audio is worthless
320
+ if (dataChannel.bufferedAmount > MAX_BUFFERED_BYTES) return;
321
+
226
322
  // Format: [type(1)][timestamp(8)][size(4)][data]
227
323
  const packet = new ArrayBuffer(1 + 8 + 4 + data.byteLength);
228
324
  const view = new DataView(packet);
@@ -243,11 +339,50 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
243
339
  } catch (e) {}
244
340
  }
245
341
 
246
- // Encode video frame from JPEG data
247
- async function encodeFrame(imageData: string) {
342
+ // Congestion-adaptive motion quantizer: when the DataChannel is backing up
343
+ // (slow network), spend fewer bits per frame instead of stalling. The
344
+ // still-page top-off restores full quality once motion stops, so temporary
345
+ // coarseness during congestion is invisible in the end result.
346
+ function currentMotionQuantizer(): number {
347
+ const buffered = dataChannel ? dataChannel.bufferedAmount : 0;
348
+ if (buffered > MAX_BUFFERED_BYTES / 2) return Math.min(60, config.motionQuantizer + 16);
349
+ if (buffered > MAX_BUFFERED_BYTES / 4) return Math.min(60, config.motionQuantizer + 8);
350
+ return config.motionQuantizer;
351
+ }
352
+
353
+ // Encode video frame from image data.
354
+ // Motion frames arrive as JPEG (CDP screencast); top-off frames arrive as
355
+ // lossless PNG (Page.captureScreenshot) when the page goes still, and are
356
+ // encoded near-losslessly so the last motion-degraded frame doesn't stick.
357
+ async function encodeFrame(imageData: string, isTopOff?: boolean) {
248
358
  if (!videoEncoder || !isCapturing) return;
249
359
 
250
360
  try {
361
+ // Source-side backpressure: if the network can't drain the channel,
362
+ // skip motion frames BEFORE decoding/encoding. Dropping input frames
363
+ // is safe (the encoder just references the last encoded frame);
364
+ // dropping encoded chunks would corrupt the delta chain.
365
+ if (!isTopOff) {
366
+ motionSeq++;
367
+ if (dataChannel && dataChannel.bufferedAmount > MAX_BUFFERED_BYTES) {
368
+ return;
369
+ }
370
+ } else if (dataChannel && dataChannel.bufferedAmount > MAX_BUFFERED_BYTES) {
371
+ // Channel congested — dumping a large near-lossless frame on it
372
+ // now would spike latency. Defer briefly; abandon if new motion
373
+ // arrives (the backend captures a fresh top-off after the next
374
+ // still period anyway).
375
+ const seqAtCapture = motionSeq;
376
+ if (topOffRetryTimer) clearTimeout(topOffRetryTimer);
377
+ topOffRetryTimer = setTimeout(() => {
378
+ topOffRetryTimer = null;
379
+ if (motionSeq === seqAtCapture && isCapturing) {
380
+ encodeFrame(imageData, true);
381
+ }
382
+ }, 250);
383
+ return;
384
+ }
385
+
251
386
  // Direct base64 decode (avoids fetch() + data URL parsing overhead)
252
387
  const binaryStr = atob(imageData);
253
388
  const len = binaryStr.length;
@@ -256,9 +391,9 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
256
391
  bytes[i] = binaryStr.charCodeAt(i);
257
392
  }
258
393
 
259
- // Decode JPEG via createImageBitmap (avoids per-frame ImageDecoder
394
+ // Decode via createImageBitmap (avoids per-frame ImageDecoder
260
395
  // constructor/destructor overhead)
261
- const blob = new Blob([bytes], { type: 'image/jpeg' });
396
+ const blob = new Blob([bytes], { type: isTopOff ? 'image/png' : 'image/jpeg' });
262
397
  const bitmap = await createImageBitmap(blob);
263
398
 
264
399
  // Get aligned timestamp in microseconds
@@ -270,16 +405,30 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
270
405
  alpha: 'discard'
271
406
  });
272
407
 
273
- // Check if keyframe needed
408
+ // Keyframes are on-demand only (stream start, reconnect, reconfigure,
409
+ // client request) — the channel is reliable so no periodic keyframes
410
+ // are needed. keyframeInterval > 0 re-enables a periodic timer.
274
411
  const now = Date.now();
275
- const needsKeyframe = (now - lastKeyframeTime) > (config.keyframeInterval * 1000);
412
+ const needsKeyframe = forceNextKeyframe ||
413
+ (config.keyframeInterval > 0 && (now - lastKeyframeTime) > (config.keyframeInterval * 1000));
276
414
 
277
415
  if (needsKeyframe) {
278
416
  lastKeyframeTime = now;
417
+ forceNextKeyframe = false;
279
418
  }
280
419
 
281
- // Encode frame
282
- videoEncoder.encode(frame, { keyFrame: needsKeyframe });
420
+ // Encode frame — in quantizer mode, quality is chosen per frame:
421
+ // cheap during motion (raised further under congestion),
422
+ // near-lossless for still-page top-off refreshes
423
+ if (usingQuantizer) {
424
+ const quantizer = isTopOff ? config.topOffQuantizer : currentMotionQuantizer();
425
+ videoEncoder.encode(frame, {
426
+ keyFrame: needsKeyframe,
427
+ vp9: { quantizer }
428
+ } as VideoEncoderEncodeOptions);
429
+ } else {
430
+ videoEncoder.encode(frame, { keyFrame: needsKeyframe });
431
+ }
283
432
  videoFrameCount++;
284
433
 
285
434
  // Close immediately to prevent memory leaks
@@ -288,17 +437,26 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
288
437
  } catch (error) {}
289
438
  }
290
439
 
440
+ // Force the next encoded frame to be a keyframe (client-driven sync point,
441
+ // PLI equivalent — used when the client decoder errors or joins mid-stream)
442
+ function forceKeyframe() {
443
+ forceNextKeyframe = true;
444
+ }
445
+
291
446
  // Start streaming
292
- async function startStreaming() {
447
+ // allowVp9: client decode capability negotiated at stream start
448
+ async function startStreaming(allowVp9?: boolean) {
293
449
  if (isCapturing) return true;
294
450
 
451
+ vp9Allowed = allowVp9 !== false;
452
+
295
453
  try {
296
454
  await initPeerConnection();
297
455
  await initVideoEncoder();
298
456
 
299
457
  isCapturing = true;
300
- // Set to 0 to force first frame as keyframe (required for decoder init)
301
- lastKeyframeTime = 0;
458
+ // Force first frame as keyframe (required for decoder init)
459
+ forceNextKeyframe = true;
302
460
 
303
461
  // Start tracking cursor changes
304
462
  startCursorTracking();
@@ -314,6 +472,12 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
314
472
  function stopStreaming() {
315
473
  isCapturing = false;
316
474
 
475
+ // Cancel any deferred top-off retry
476
+ if (topOffRetryTimer) {
477
+ clearTimeout(topOffRetryTimer);
478
+ topOffRetryTimer = null;
479
+ }
480
+
317
481
  // Stop cursor tracking
318
482
  stopCursorTracking();
319
483
 
@@ -391,7 +555,7 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
391
555
  }
392
556
 
393
557
  // Reconfigure video encoder with new dimensions (hot-swap)
394
- async function reconfigureEncoder(newWidth: number, newHeight: number) {
558
+ async function reconfigureEncoder(newWidth: number, newHeight: number, newBitrate?: number) {
395
559
  if (!videoEncoder || !isCapturing) {
396
560
  return false;
397
561
  }
@@ -400,16 +564,8 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
400
564
  // Flush pending frames
401
565
  await videoEncoder.flush();
402
566
 
403
- // Create new codec config with updated dimensions
404
- const newCodecConfig: VideoEncoderConfig = {
405
- codec: config.codec,
406
- width: newWidth,
407
- height: newHeight,
408
- bitrate: config.bitrate,
409
- framerate: config.framerate,
410
- hardwareAcceleration: config.hardwareAcceleration,
411
- latencyMode: config.latencyMode
412
- };
567
+ // Create new codec config with updated dimensions (keeps current codec mode)
568
+ const newCodecConfig = buildEncoderConfig(newWidth, newHeight, newBitrate);
413
569
 
414
570
  // Check if new config is supported
415
571
  const support = await VideoEncoder.isConfigSupported(newCodecConfig);
@@ -423,9 +579,12 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
423
579
  // Update config reference
424
580
  config.width = newWidth;
425
581
  config.height = newHeight;
582
+ if (newBitrate) {
583
+ config.bitrate = newBitrate;
584
+ }
426
585
 
427
- // Reset keyframe timer to force keyframe after reconfigure
428
- lastKeyframeTime = 0;
586
+ // Force keyframe after reconfigure (decoder needs a sync point at the new dimensions)
587
+ forceNextKeyframe = true;
429
588
 
430
589
  return true;
431
590
  } catch (error) {
@@ -445,7 +604,7 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
445
604
  videoFramesEncoded: videoFrameCount,
446
605
  audioFramesEncoded: audioFrameCount,
447
606
  connectionState: peerConnection.connectionState,
448
- videoCodec: config.codec,
607
+ videoCodec: usingQuantizer ? 'vp9' : config.codec,
449
608
  audioCodec: 'opus' as const
450
609
  };
451
610
 
@@ -469,6 +628,7 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
469
628
  handleAnswer,
470
629
  addIceCandidate,
471
630
  encodeFrame,
631
+ forceKeyframe,
472
632
  sendAudioChunk,
473
633
  getStats,
474
634
  reconfigureEncoder,
@@ -65,7 +65,7 @@ export interface BrowserTab {
65
65
  lastUniqueFrameTime?: number;
66
66
  stableFrameStartTime?: number;
67
67
  lastCursorInfo?: { x: number; y: number; cursor: string };
68
- scale?: number; // Frontend canvas scale factor (for bandwidth optimization)
68
+ scale?: number; // Frontend display fit-scale (CSS-only; does NOT affect capture resolution)
69
69
 
70
70
  // Interaction tracking
71
71
  lastInteractionTime?: number;
@@ -207,15 +207,17 @@ export interface BrowserScreenshotFrame {
207
207
  */
208
208
  export interface StreamingConfig {
209
209
  video: {
210
- codec: string;
210
+ codec: string; // Fallback codec (VP8, fixed-bitrate mode) when VP9 quantizer mode is unsupported
211
211
  width: number;
212
212
  height: number;
213
- framerate: number;
213
+ framerate: number; // Max encode fps — screencast frames above this rate are dropped at the source
214
214
  bitrate: number;
215
- keyframeInterval: number;
215
+ keyframeInterval: number; // Seconds between periodic keyframes; 0 = on-demand only (start/reconnect/client request)
216
216
  screenshotQuality: number;
217
217
  hardwareAcceleration: 'no-preference' | 'prefer-hardware' | 'prefer-software';
218
218
  latencyMode: 'quality' | 'realtime';
219
+ motionQuantizer: number; // VP9 per-frame quantizer (0-63) while the page is moving — cheap, allowed to be soft
220
+ topOffQuantizer: number; // VP9 quantizer for still-page refresh frames — near-lossless so text stays crisp
219
221
  };
220
222
  audio: {
221
223
  codec: string
@@ -229,11 +231,19 @@ export interface StreamingConfig {
229
231
  /**
230
232
  * Default streaming configuration
231
233
  *
232
- * Optimized for visual quality with reduced resource usage:
233
- * - Software encoding (hardwareAcceleration: 'no-preference')
234
- * - JPEG quality 65: slightly lower than before but still preserves thin borders/text
235
- * - VP8 at 1.0Mbps: ~17% reduction from 1.2Mbps, sharp edges preserved by VP8 codec
236
- * - keyframeInterval 5s: less frequent large keyframes, saves bandwidth on static pages
234
+ * Chrome-Remote-Desktop-style adaptive quality:
235
+ * - Preferred: VP9 in quantizer mode — motion frames encoded cheaply
236
+ * (motionQuantizer, raised further under congestion), and when the page
237
+ * goes still a near-lossless refresh frame is sent (topOffQuantizer) so
238
+ * text stays crisp. Idle pages cost ~0 bandwidth (CDP screencast only
239
+ * fires on damage).
240
+ * - Fallback: VP8 at a resolution-scaled bitrate (see computeBitrate).
241
+ * - Keyframes on demand only (keyframeInterval 0) — the DataChannel is
242
+ * reliable, and the client requests a keyframe on decoder errors.
243
+ * - Encode rate capped at `framerate` — screencast can fire at compositor
244
+ * rate (up to 60fps); excess frames are dropped at the source.
245
+ * - JPEG quality 75 for motion source frames (encoder quantizer controls
246
+ * output size, so higher source quality no longer inflates bandwidth)
237
247
  * - Opus for audio (efficient and widely supported)
238
248
  */
239
249
  export const DEFAULT_STREAMING_CONFIG: StreamingConfig = {
@@ -243,10 +253,12 @@ export const DEFAULT_STREAMING_CONFIG: StreamingConfig = {
243
253
  height: 0,
244
254
  framerate: 24,
245
255
  bitrate: 1_000_000,
246
- keyframeInterval: 5,
247
- screenshotQuality: 65,
256
+ keyframeInterval: 0,
257
+ screenshotQuality: 75,
248
258
  hardwareAcceleration: 'no-preference',
249
- latencyMode: 'realtime'
259
+ latencyMode: 'realtime',
260
+ motionQuantizer: 40,
261
+ topOffQuantizer: 10
250
262
  },
251
263
  audio: {
252
264
  codec: 'opus',
@@ -14,7 +14,11 @@
14
14
  * reports "not building a snapshot" — always true for a normally-running
15
15
  * process, so `bson` skips its snapshot branch and loads cleanly.
16
16
  *
17
- * Import this before any module that (transitively) imports `mongodb`/`bson`.
17
+ * This file MUST be loaded via Bun's `--preload` / `bunfig.toml preload`, NOT a
18
+ * plain `import`. Bun does not guarantee that an earlier ESM side-effect import
19
+ * runs before a later CJS import is evaluated, so `import './bun-compat'` at the
20
+ * top of an entry still lets `mongodb`/`bson` load (and crash) first. `preload`
21
+ * is the only mechanism that reliably runs before the entry's import graph.
18
22
  */
19
23
 
20
24
  if (typeof globalThis.Bun !== 'undefined') {
@@ -10,8 +10,9 @@
10
10
  import { t } from 'elysia';
11
11
  import { createRouter } from '$shared/utils/ws-server';
12
12
  import { streamManager, type StreamEvent } from '../../chat/stream-manager';
13
- import type { EngineType } from '$shared/types/unified';
13
+ import type { EngineType, UnifiedMessage } from '$shared/types/unified';
14
14
  import { debug } from '$shared/utils/logger';
15
+ import { trimSubAgentForWire } from '$shared/utils/subagent-wire-trim';
15
16
  import { ws } from '$backend/utils/ws';
16
17
  import { broadcastPresence } from '../projects/status';
17
18
  import { sessionQueries, messageQueries } from '../../database/queries';
@@ -280,7 +281,7 @@ export const streamHandler = createRouter()
280
281
  case 'message': {
281
282
  ws.emit.chatSession(chatSessionId, 'chat:message', {
282
283
  processId: event.processId,
283
- message: event.data.message,
284
+ message: trimSubAgentForWire(event.data.message),
284
285
  usage: event.data.usage,
285
286
  timestamp: event.data.timestamp,
286
287
  message_id: event.data.message_id,
@@ -424,7 +425,7 @@ export const streamHandler = createRouter()
424
425
  case 'message': {
425
426
  ws.emit.chatSession(chatSessionId, 'chat:message', {
426
427
  processId: event.processId,
427
- message: event.data.message,
428
+ message: trimSubAgentForWire(event.data.message),
428
429
  usage: event.data.usage,
429
430
  timestamp: event.data.timestamp,
430
431
  message_id: event.data.message_id,
@@ -618,7 +619,14 @@ export const streamHandler = createRouter()
618
619
  streamId: streamState.streamId,
619
620
  status: streamState.status,
620
621
  processId: streamState.processId,
621
- messages: streamState.messages,
622
+ // Trim sub-agent noise from the catch-up buffer too (see trimSubAgentForWire).
623
+ // Buffer entries wrap the UnifiedMessage under `.message`; leave the rest intact.
624
+ messages: streamState.messages.map(entry => {
625
+ const wrapped = entry as { message?: UnifiedMessage };
626
+ return wrapped?.message
627
+ ? { ...wrapped, message: trimSubAgentForWire(wrapped.message) }
628
+ : entry;
629
+ }),
622
630
  currentPartialText: streamState.currentPartialText,
623
631
  currentReasoningText: streamState.currentReasoningText,
624
632
  error: streamState.error,
@@ -21,7 +21,8 @@ const driverSchema = t.Union([
21
21
  t.Literal('postgres'),
22
22
  t.Literal('sqlite'),
23
23
  t.Literal('mongodb'),
24
- t.Literal('redis')
24
+ t.Literal('redis'),
25
+ t.Literal('mssql')
25
26
  ]);
26
27
 
27
28
  const sslModeSchema = t.Union([
@@ -85,7 +85,24 @@ export const queryHandler = createRouter()
85
85
  rowCount: result.rowCount ?? null,
86
86
  error: null
87
87
  });
88
- return result;
88
+ const top = {
89
+ ...result,
90
+ batch: result.batch ?? {
91
+ statements: [{
92
+ index: 0,
93
+ query: data.query,
94
+ queryClass: 'read' as const,
95
+ status: 'success' as const,
96
+ result,
97
+ error: null,
98
+ durationMs: result.durationMs
99
+ }],
100
+ totalDurationMs: result.durationMs,
101
+ transaction: false,
102
+ ok: true
103
+ }
104
+ };
105
+ return top;
89
106
  } catch (error) {
90
107
  recordHistory({
91
108
  connectionId: data.connectionId,
@@ -130,7 +147,24 @@ export const queryHandler = createRouter()
130
147
  rowCount: result.rowCount ?? null,
131
148
  error: null
132
149
  });
133
- return result;
150
+ const top = {
151
+ ...result,
152
+ batch: result.batch ?? {
153
+ statements: [{
154
+ index: 0,
155
+ query: data.query,
156
+ queryClass: 'write' as const,
157
+ status: 'success' as const,
158
+ result,
159
+ error: null,
160
+ durationMs: result.durationMs
161
+ }],
162
+ totalDurationMs: result.durationMs,
163
+ transaction: false,
164
+ ok: true
165
+ }
166
+ };
167
+ return top;
134
168
  } catch (error) {
135
169
  recordHistory({
136
170
  connectionId: data.connectionId,
@@ -159,8 +193,11 @@ export const queryHandler = createRouter()
159
193
  const connection = requireDbClientConnectionAccess(conn, data.connectionId);
160
194
  const adapter = await connectionManager.get(data.connectionId);
161
195
  // Statement splitting is a SQL concern; Mongo/Redis payloads run whole.
162
- const isSql = connection.driver === 'mysql' || connection.driver === 'postgres' || connection.driver === 'sqlite';
163
- const split = isSql ? splitSqlStatements(data.query) : [data.query.trim()];
196
+ const isSql = connection.driver === 'mysql' || connection.driver === 'postgres' || connection.driver === 'sqlite' || connection.driver === 'mssql';
197
+ // SQL Server separates batch-sensitive DDL by blank lines rather than `;`.
198
+ const split = isSql
199
+ ? splitSqlStatements(data.query, { splitOnBlankLine: connection.driver === 'mssql' })
200
+ : [data.query.trim()];
164
201
  const statements = split.length > 0 ? split : [data.query.trim()];
165
202
  try {
166
203
  const batch = await executeBatch({