@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
@@ -14,6 +14,7 @@ import type { Elysia } from 'elysia';
14
14
  import { t, type TSchema, type Static } from 'elysia';
15
15
  import { Value } from '@sinclair/typebox/value';
16
16
  import { debug } from './logger';
17
+ import { sendBinary, sendReply, sendText } from '$backend/utils/ws-wire';
17
18
 
18
19
  // ============================================================================
19
20
  // Singleton Encoders (Performance Optimization)
@@ -606,13 +607,13 @@ export class WSRouter<
606
607
  if (isBinaryAction(responseAction, validatedResponse)) {
607
608
  // For binary responses, wrap in success envelope with requestId
608
609
  const wrappedResponse = { success: true, data: validatedResponse, requestId };
609
- const binaryMessage = encodeBinaryMessage(responseAction, wrappedResponse);
610
- conn.send(Buffer.from(binaryMessage));
610
+ sendBinary(conn, responseAction, encodeBinaryMessage(responseAction, wrappedResponse));
611
611
  debug.log('websocket', 'HTTP success (binary):', action);
612
612
  } else {
613
- // For JSON responses, wrap in success envelope with requestId
613
+ // For JSON responses, wrap in success envelope with requestId. Large
614
+ // replies leave in chunks (see sendReply).
614
615
  const wrappedResponse = { success: true, data: validatedResponse, requestId };
615
- conn.send(JSON.stringify({ action: responseAction, payload: wrappedResponse }));
616
+ await sendReply(conn, responseAction, requestId, JSON.stringify({ action: responseAction, payload: wrappedResponse }));
616
617
  debug.log('websocket', 'HTTP success (JSON):', action);
617
618
  }
618
619
  } catch (err) {
@@ -620,7 +621,11 @@ export class WSRouter<
620
621
  const errorMessage = err instanceof Error ? err.message : String(err);
621
622
 
622
623
  const errorResponse = { success: false, error: errorMessage, requestId };
623
- conn.send(JSON.stringify({ action: responseAction, payload: errorResponse }));
624
+ try {
625
+ sendText(conn, responseAction, JSON.stringify({ action: responseAction, payload: errorResponse }));
626
+ } catch {
627
+ // Connection may be closed
628
+ }
624
629
  debug.error('websocket', `HTTP error [${action}]:`, errorMessage);
625
630
  }
626
631
  }
@@ -668,12 +673,12 @@ export class WSRouter<
668
673
  // so ws.http() on the client receives it instead of timing out
669
674
  if (this.httpRoutes.has(action)) {
670
675
  const requestId = payload?.requestId;
671
- conn.send(JSON.stringify({
676
+ sendText(conn, `${action}:response`, JSON.stringify({
672
677
  action: `${action}:response`,
673
678
  payload: { success: false, error: authResult.error, requestId }
674
679
  }));
675
680
  } else {
676
- conn.send(JSON.stringify({
681
+ sendText(conn, 'auth:error', JSON.stringify({
677
682
  action: 'auth:error',
678
683
  payload: { error: authResult.error, blockedAction: action }
679
684
  }));
@@ -709,7 +714,7 @@ export class WSRouter<
709
714
  // have no requestId and still just drop.
710
715
  if (isRequest) {
711
716
  try {
712
- conn.send(JSON.stringify({
717
+ sendText(conn, `${action}:response`, JSON.stringify({
713
718
  action: `${action}:response`,
714
719
  payload: {
715
720
  success: false,
@@ -759,13 +764,11 @@ export class WSRouter<
759
764
  */
760
765
  asPlugin(path: string = '/ws') {
761
766
  return (app: Elysia) => {
767
+ // Socket limits (payload size, idle timeout, compression) are NOT set
768
+ // here: Elysia ignores them on a `.ws()` route and only passes the
769
+ // app-level `websocket` config to Bun.serve — see WS_SERVER_OPTIONS
770
+ // in backend/utils/ws-wire.ts.
762
771
  return app.ws(path, {
763
- // Allow large binary frames (file uploads, zip extracts).
764
- // Bun/uWS default is 16MB which trips EPIPE on the dev proxy
765
- // long before the configurable per-file limit kicks in.
766
- maxPayloadLength: 1024 * 1024 * 1024, // 1 GiB
767
- // Disable inactivity disconnects during long binary transfers.
768
- idleTimeout: 960, // seconds (max allowed by uWS)
769
772
  message: (conn, message) => {
770
773
  this.handleMessage(conn, message);
771
774
  },
@@ -1,170 +0,0 @@
1
- /**
2
- * Migration 086 takes a multi-user install to a single owner. It runs the real
3
- * migration chain up to 085 against an in-memory SQLite, seeds the shapes a
4
- * team install actually had, then checks what 086 keeps and what it removes —
5
- * above all that no credential of a removed account survives.
6
- */
7
-
8
- import { describe, expect, test } from 'bun:test';
9
- import { Database } from 'bun:sqlite';
10
- import { mkdtempSync, mkdirSync, existsSync, rmSync } from 'fs';
11
- import { join } from 'path';
12
- import { tmpdir } from 'os';
13
- import type { DatabaseConnection } from '$shared/types/database/connection';
14
- import migrations from './index';
15
- import { up, down } from './086_single_owner';
16
-
17
- const NOW = '2026-01-01T00:00:00.000Z';
18
-
19
- function migratedTo085(): Database {
20
- const db = new Database(':memory:');
21
- db.exec('PRAGMA foreign_keys = ON');
22
- for (const migration of [...migrations].sort((a, b) => a.id.localeCompare(b.id))) {
23
- if (migration.id >= '086') break;
24
- migration.up(db as unknown as DatabaseConnection);
25
- }
26
- return db;
27
- }
28
-
29
- function addUser(db: Database, id: string, role: 'admin' | 'member', createdAt: string): void {
30
- db.prepare(`INSERT INTO users (id, name, color, avatar, role, personal_access_token_hash, created_at, updated_at) VALUES (?, ?, '#000', 'X', ?, ?, ?, ?)`)
31
- .run(id, id, role, `pat-${id}`, createdAt, createdAt);
32
- db.prepare(`INSERT INTO auth_sessions (id, user_id, token_hash, expires_at, created_at, last_active_at) VALUES (?, ?, ?, '2099-01-01', ?, ?)`)
33
- .run(`s-${id}`, id, `hash-${id}`, NOW, NOW);
34
- }
35
-
36
- function addProject(db: Database, id: string, path: string, kind: 'project' | 'home' = 'project', owner: string | null = null): void {
37
- db.prepare(`INSERT INTO projects (id, name, path, created_at, last_opened_at, kind, owner_user_id) VALUES (?, ?, ?, ?, ?, ?, ?)`)
38
- .run(id, id, path, NOW, NOW, kind, owner);
39
- }
40
-
41
- function seed(home: string): Database {
42
- const db = migratedTo085();
43
- // The oldest admin is the owner; a second admin and a member are removed.
44
- addUser(db, 'owner', 'admin', '2025-01-01');
45
- addUser(db, 'admin2', 'admin', '2025-02-01');
46
- addUser(db, 'member', 'member', '2024-01-01');
47
-
48
- addProject(db, 'shared', '/repo/shared');
49
- addProject(db, 'removed', '/repo/removed');
50
- addProject(db, 'home-owner', join(home, 'owner'), 'home', 'owner');
51
- addProject(db, 'home-member', join(home, 'member'), 'home', 'member');
52
- mkdirSync(join(home, 'member'), { recursive: true });
53
-
54
- for (const [user, project, state] of [['owner', 'shared', 'owner-layout'], ['owner', 'home-owner', null], ['member', 'shared', 'member-layout'], ['member', 'home-member', null]] as const) {
55
- db.prepare(`INSERT INTO user_projects (user_id, project_id, joined_at, workspace_state) VALUES (?, ?, ?, ?)`).run(user, project, NOW, state);
56
- }
57
-
58
- // A chat the member had in the shared project is project history; one in their Home is theirs.
59
- db.prepare(`INSERT INTO chat_sessions (id, project_id, started_at) VALUES ('chat-shared', 'shared', ?)`).run(NOW);
60
- db.prepare(`INSERT INTO chat_sessions (id, project_id, started_at) VALUES ('chat-home', 'home-member', ?)`).run(NOW);
61
- db.prepare(`INSERT INTO user_unread_sessions (user_id, session_id, project_id, marked_at) VALUES ('owner', 'chat-shared', 'shared', ?), ('member', 'chat-shared', 'shared', ?)`).run(NOW, NOW);
62
-
63
- db.prepare(`INSERT INTO invite_tokens (id, token_hash, role, created_by, created_at) VALUES ('inv', 'inv-hash', 'member', 'owner', ?)`).run(NOW);
64
- db.prepare(`INSERT INTO device_codes (id, code_hash, user_id, expires_at, created_at) VALUES ('dev', 'dev-hash', 'member', '2099-01-01', ?)`).run(NOW);
65
-
66
- for (const [id, owner] of [['db-owner', 'owner'], ['db-member', 'member'], ['db-legacy', null]] as const) {
67
- db.prepare(`INSERT INTO db_client_connections (id, name, driver, created_at, updated_at, owner_user_id) VALUES (?, ?, 'postgres', ?, ?, ?)`).run(id, id, NOW, NOW, owner);
68
- }
69
- for (const [id, owner] of [['ssh-owner', 'owner'], ['ssh-member', 'member']] as const) {
70
- db.prepare(`INSERT INTO ssh_connections (id, name, host, port, username, auth_method, created_at, updated_at, owner_user_id) VALUES (?, ?, 'h', 22, 'u', 'agent', ?, ?, ?)`).run(id, id, NOW, NOW, owner);
71
- }
72
- for (const [id, owner, isDefault] of [['gi-owner', 'owner', 1], ['gi-member', 'member', 1]] as const) {
73
- db.prepare(`INSERT INTO git_identities (id, owner_user_id, label, name, email, is_default, created_at, updated_at) VALUES (?, ?, 'Work', 'N', 'e@x.y', ?, ?, ?)`).run(id, owner, isDefault, NOW, NOW);
74
- }
75
- db.prepare(`INSERT INTO git_identity_bindings (project_id, user_id, identity_id, created_at, updated_at) VALUES ('shared', 'owner', 'gi-owner', ?, ?), ('shared', 'member', 'gi-member', ?, ?)`).run(NOW, NOW, NOW, NOW);
76
-
77
- db.prepare(`INSERT INTO integration_accounts (id, provider, label, auth_method, created_at, updated_at) VALUES ('bot', 'telegram', 'Bot', 'token', ?, ?)`).run(NOW, NOW);
78
- db.prepare(`INSERT INTO channel_links (id, account_id, user_id, conversation_id, platform_user_id, status, created_at) VALUES ('link-owner', 'bot', 'owner', 'c1', 'p1', 'approved', ?), ('link-member', 'bot', 'member', 'c2', 'p2', 'pending', ?)`).run(NOW, NOW);
79
- return db;
80
- }
81
-
82
- function ids(db: Database, sql: string): string[] {
83
- return (db.prepare(sql).all() as { id: string }[]).map((row) => row.id);
84
- }
85
-
86
- function columns(db: Database, table: string): string[] {
87
- return (db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).map((c) => c.name);
88
- }
89
-
90
- describe('migration 086', () => {
91
- // Homes live under `<data dir>/home/<userId>`; the migration only removes a
92
- // directory of exactly that shape.
93
- const dataDir = mkdtempSync(join(tmpdir(), 'clopen-086-'));
94
- const home = join(dataDir, 'home');
95
-
96
- test('keeps the oldest admin as the only account, and nothing a removed account could sign in with', () => {
97
- const db = seed(home);
98
- up(db as unknown as DatabaseConnection);
99
-
100
- expect(ids(db, 'SELECT id FROM users')).toEqual(['owner']);
101
- expect(ids(db, 'SELECT user_id AS id FROM auth_sessions')).toEqual(['owner']);
102
- expect(ids(db, 'SELECT id FROM device_codes')).toEqual([]);
103
- expect(ids(db, 'SELECT id FROM channel_links')).toEqual(['link-owner']);
104
- expect(columns(db, 'users')).not.toContain('role');
105
- expect(db.prepare(`SELECT name FROM sqlite_master WHERE name = 'invite_tokens'`).get()).toBeNull();
106
- db.close();
107
- });
108
-
109
- test('removes what was the others alone, keeps shared project history', () => {
110
- const db = seed(home);
111
- up(db as unknown as DatabaseConnection);
112
-
113
- expect(ids(db, 'SELECT id FROM projects ORDER BY id')).toEqual(['home-owner', 'removed', 'shared']);
114
- expect(ids(db, 'SELECT id FROM chat_sessions')).toEqual(['chat-shared']);
115
- expect(existsSync(join(home, 'member'))).toBe(false);
116
- expect(ids(db, 'SELECT id FROM db_client_connections ORDER BY id')).toEqual(['db-legacy', 'db-owner']);
117
- expect(ids(db, 'SELECT id FROM ssh_connections')).toEqual(['ssh-owner']);
118
- expect(ids(db, 'SELECT id FROM git_identities')).toEqual(['gi-owner']);
119
- expect(ids(db, 'SELECT identity_id AS id FROM git_identity_bindings')).toEqual(['gi-owner']);
120
- db.close();
121
- });
122
-
123
- test("carries the owner's workspace list and state over, without a user key", () => {
124
- const db = seed(home);
125
- up(db as unknown as DatabaseConnection);
126
-
127
- const rows = db.prepare('SELECT project_id, workspace_state FROM workspace_projects ORDER BY project_id').all();
128
- expect(rows).toEqual([
129
- { project_id: 'home-owner', workspace_state: null },
130
- { project_id: 'shared', workspace_state: 'owner-layout' }
131
- ]);
132
- // `removed` was never in the owner's list, so it stays removed.
133
- expect(db.prepare(`SELECT session_id FROM unread_sessions`).all()).toEqual([{ session_id: 'chat-shared' }]);
134
- for (const [table, column] of [['projects', 'owner_user_id'], ['db_client_connections', 'owner_user_id'], ['ssh_connections', 'owner_user_id'], ['git_identities', 'owner_user_id'], ['git_identity_bindings', 'user_id'], ['chat_sessions', 'sender_id'], ['channel_links', 'status']] as const) {
135
- expect(columns(db, table)).not.toContain(column);
136
- }
137
- db.close();
138
- });
139
-
140
- test('rolls back to the multi-user schema, the owner as its admin', () => {
141
- const db = seed(home);
142
- up(db as unknown as DatabaseConnection);
143
- down(db as unknown as DatabaseConnection);
144
-
145
- expect(db.prepare('SELECT id, role FROM users').all()).toEqual([{ id: 'owner', role: 'admin' }]);
146
- expect(db.prepare('SELECT user_id, project_id FROM user_projects ORDER BY project_id').all()).toEqual([
147
- { user_id: 'owner', project_id: 'home-owner' },
148
- { user_id: 'owner', project_id: 'shared' }
149
- ]);
150
- expect(db.prepare('SELECT owner_user_id FROM git_identities').all()).toEqual([{ owner_user_id: 'owner' }]);
151
- expect(columns(db, 'chat_sessions')).toContain('sender_id');
152
- db.close();
153
- });
154
-
155
- test('allows one Home and one default identity for the install', () => {
156
- const db = seed(home);
157
- up(db as unknown as DatabaseConnection);
158
-
159
- expect(() => addProjectAfter(db, 'home-2')).toThrow();
160
- expect(() =>
161
- db.prepare(`INSERT INTO git_identities (id, label, name, email, is_default, created_at, updated_at) VALUES ('gi-2', 'Other', 'N', 'e@x.y', 1, ?, ?)`).run(NOW, NOW)
162
- ).toThrow();
163
- db.close();
164
- rmSync(dataDir, { recursive: true, force: true });
165
- });
166
- });
167
-
168
- function addProjectAfter(db: Database, id: string): void {
169
- db.prepare(`INSERT INTO projects (id, name, path, created_at, last_opened_at, kind) VALUES (?, ?, ?, ?, ?, 'home')`).run(id, id, `/${id}`, NOW, NOW);
170
- }