@myrialabs/clopen 0.4.6 → 0.4.8

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 (44) hide show
  1. package/backend/auth/session-invalidation.test.ts +17 -21
  2. package/backend/auth/session-invalidation.ts +10 -11
  3. package/backend/db-client/drivers/mysql.ts +21 -0
  4. package/backend/db-client/drivers/postgres.ts +20 -0
  5. package/backend/db-client/drivers/sqlite.ts +21 -0
  6. package/backend/db-client/drivers/types.ts +19 -0
  7. package/backend/db-client/query-executor.ts +89 -1
  8. package/backend/engine/adapters/claude/models.ts +46 -3
  9. package/backend/files/file-archive.test.ts +86 -26
  10. package/backend/files/file-archive.ts +214 -134
  11. package/backend/terminal/index.ts +2 -5
  12. package/backend/terminal/ptykit.ts +64 -0
  13. package/backend/tunnel/tunnel-config.ts +1 -1
  14. package/backend/utils/ws.ts +14 -0
  15. package/backend/ws/db-client/query-history-retention.test.ts +217 -0
  16. package/backend/ws/db-client/query.ts +77 -2
  17. package/backend/ws/files/write.ts +23 -7
  18. package/backend/ws/git/ignored.ts +65 -0
  19. package/backend/ws/git/index.ts +3 -1
  20. package/backend/ws/projects/crud.ts +4 -4
  21. package/backend/ws/system/operations.ts +23 -0
  22. package/backend/ws/terminal/index.ts +6 -33
  23. package/backend/ws/terminal/tunnel.ts +76 -0
  24. package/dist/assets/__vite-browser-external-BIHI7g3E.js +1 -0
  25. package/dist/assets/index-B_F_OgoC.js +1 -0
  26. package/dist/assets/index-jGo0X72U.js +1 -0
  27. package/dist/assets/{main-TYNK6Orl.js → main-BkCc3WEB.js} +321 -260
  28. package/dist/assets/main-CWDwET4x.css +1 -0
  29. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm +0 -0
  30. package/dist/index.html +2 -2
  31. package/package.json +7 -11
  32. package/shared/constants/engines.ts +4 -4
  33. package/shared/types/db-client/query.ts +33 -0
  34. package/shared/utils/db-client/split-sql.test.ts +88 -0
  35. package/shared/utils/db-client/split-sql.ts +132 -0
  36. package/backend/terminal/helpers.ts +0 -14
  37. package/backend/terminal/pty-manager.ts +0 -4
  38. package/backend/terminal/pty-session-manager.ts +0 -349
  39. package/backend/terminal/stream-manager.ts +0 -300
  40. package/backend/ws/terminal/access.ts +0 -56
  41. package/backend/ws/terminal/persistence.ts +0 -145
  42. package/backend/ws/terminal/session.ts +0 -470
  43. package/backend/ws/terminal/stream.ts +0 -82
  44. package/dist/assets/main-BkMrek4_.css +0 -1
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Test query history retention policy enforcement.
3
+ *
4
+ * Verifies that deterministic pruning keeps exactly HISTORY_KEEP_PER_CONNECTION
5
+ * entries after every PRUNE_EVERY_N_QUERIES inserts, replacing the old
6
+ * probabilistic approach that could allow unbounded growth.
7
+ */
8
+
9
+ import { describe, test, expect, beforeEach } from 'bun:test';
10
+ import { initializeDatabase, closeDatabase } from '../../database';
11
+ import { dbClientQueryHistoryQueries } from '../../database/queries';
12
+ import { dbClientConnectionQueries } from '../../database/queries';
13
+
14
+ const HISTORY_KEEP_PER_CONNECTION = 200;
15
+ const PRUNE_EVERY_N_QUERIES = 10;
16
+
17
+ describe('Query History Retention', () => {
18
+ beforeEach(async () => {
19
+ await initializeDatabase();
20
+ // Clean up any existing test data
21
+ const db = await import('../../database').then(m => m.getDatabase());
22
+ db.prepare('DELETE FROM db_client_query_history').run();
23
+ db.prepare('DELETE FROM db_client_connections').run();
24
+ });
25
+
26
+ test('prunes history after PRUNE_EVERY_N_QUERIES inserts', () => {
27
+ // Create a test connection
28
+ const connection = dbClientConnectionQueries.createForUser({
29
+ name: 'test-connection',
30
+ driver: 'postgres',
31
+ host: 'localhost',
32
+ port: 5432,
33
+ username: 'test',
34
+ password: 'test',
35
+ database: 'testdb',
36
+ sslMode: 'disable',
37
+ ssh: {
38
+ enabled: false,
39
+ host: '',
40
+ port: 22,
41
+ username: '',
42
+ authMethod: 'password',
43
+ password: '',
44
+ privateKey: '',
45
+ passphrase: ''
46
+ },
47
+ options: {}
48
+ }, 'test-user-id');
49
+
50
+ // Insert HISTORY_KEEP_PER_CONNECTION + 50 queries (250 total)
51
+ const totalQueries = HISTORY_KEEP_PER_CONNECTION + 50;
52
+ for (let i = 0; i < totalQueries; i++) {
53
+ dbClientQueryHistoryQueries.insert({
54
+ connectionId: connection.id,
55
+ userId: 'test-user-id',
56
+ query: `SELECT ${i};`,
57
+ durationMs: Math.random() * 100,
58
+ rowCount: 1,
59
+ status: 'success',
60
+ error: null
61
+ });
62
+
63
+ // Manually trigger prune every PRUNE_EVERY_N_QUERIES
64
+ if ((i + 1) % PRUNE_EVERY_N_QUERIES === 0) {
65
+ dbClientQueryHistoryQueries.prune(connection.id, HISTORY_KEEP_PER_CONNECTION);
66
+ }
67
+ }
68
+
69
+ // Verify exactly HISTORY_KEEP_PER_CONNECTION entries remain
70
+ const { total } = dbClientQueryHistoryQueries.list({
71
+ connectionId: connection.id,
72
+ limit: 1000
73
+ });
74
+
75
+ expect(total).toBe(HISTORY_KEEP_PER_CONNECTION);
76
+ });
77
+
78
+ test('keeps most recent queries after pruning', () => {
79
+ const connection = dbClientConnectionQueries.createForUser({
80
+ name: 'test-connection-2',
81
+ driver: 'postgres',
82
+ host: 'localhost',
83
+ port: 5432,
84
+ username: 'test',
85
+ password: 'test',
86
+ database: 'testdb',
87
+ sslMode: 'disable',
88
+ ssh: {
89
+ enabled: false,
90
+ host: '',
91
+ port: 22,
92
+ username: '',
93
+ authMethod: 'password',
94
+ password: '',
95
+ privateKey: '',
96
+ passphrase: ''
97
+ },
98
+ options: {}
99
+ }, 'test-user-id');
100
+
101
+ // Insert 250 queries — more than HISTORY_KEEP_PER_CONNECTION
102
+ for (let i = 0; i < 250; i++) {
103
+ dbClientQueryHistoryQueries.insert({
104
+ connectionId: connection.id,
105
+ userId: 'test-user-id',
106
+ query: `SELECT ${i};`,
107
+ durationMs: 10,
108
+ rowCount: 1,
109
+ status: 'success',
110
+ error: null
111
+ });
112
+
113
+ if ((i + 1) % PRUNE_EVERY_N_QUERIES === 0) {
114
+ dbClientQueryHistoryQueries.prune(connection.id, HISTORY_KEEP_PER_CONNECTION);
115
+ }
116
+ }
117
+
118
+ const { items, total } = dbClientQueryHistoryQueries.list({
119
+ connectionId: connection.id,
120
+ limit: 1000
121
+ });
122
+
123
+ expect(total).toBe(HISTORY_KEEP_PER_CONNECTION);
124
+ expect(items.length).toBe(HISTORY_KEEP_PER_CONNECTION);
125
+ });
126
+
127
+ test('prune does not affect other connections', () => {
128
+ // Create two connections
129
+ const conn1 = dbClientConnectionQueries.createForUser({
130
+ name: 'connection-1',
131
+ driver: 'postgres',
132
+ host: 'localhost',
133
+ port: 5432,
134
+ username: 'test',
135
+ password: 'test',
136
+ database: 'testdb',
137
+ sslMode: 'disable',
138
+ ssh: {
139
+ enabled: false,
140
+ host: '',
141
+ port: 22,
142
+ username: '',
143
+ authMethod: 'password',
144
+ password: '',
145
+ privateKey: '',
146
+ passphrase: ''
147
+ },
148
+ options: {}
149
+ }, 'user-1');
150
+
151
+ const conn2 = dbClientConnectionQueries.createForUser({
152
+ name: 'connection-2',
153
+ driver: 'mysql',
154
+ host: 'localhost',
155
+ port: 3306,
156
+ username: 'test',
157
+ password: 'test',
158
+ database: 'testdb',
159
+ sslMode: 'disable',
160
+ ssh: {
161
+ enabled: false,
162
+ host: '',
163
+ port: 22,
164
+ username: '',
165
+ authMethod: 'password',
166
+ password: '',
167
+ privateKey: '',
168
+ passphrase: ''
169
+ },
170
+ options: {}
171
+ }, 'user-2');
172
+
173
+ // Insert 250 queries for conn1
174
+ for (let i = 0; i < 250; i++) {
175
+ dbClientQueryHistoryQueries.insert({
176
+ connectionId: conn1.id,
177
+ userId: 'user-1',
178
+ query: `SELECT ${i};`,
179
+ durationMs: 10,
180
+ rowCount: 1,
181
+ status: 'success',
182
+ error: null
183
+ });
184
+ if ((i + 1) % PRUNE_EVERY_N_QUERIES === 0) {
185
+ dbClientQueryHistoryQueries.prune(conn1.id, HISTORY_KEEP_PER_CONNECTION);
186
+ }
187
+ }
188
+
189
+ // Insert only 50 queries for conn2
190
+ for (let i = 0; i < 50; i++) {
191
+ dbClientQueryHistoryQueries.insert({
192
+ connectionId: conn2.id,
193
+ userId: 'user-2',
194
+ query: `SELECT ${i};`,
195
+ durationMs: 10,
196
+ rowCount: 1,
197
+ status: 'success',
198
+ error: null
199
+ });
200
+ }
201
+
202
+ // Verify conn1 has exactly 200
203
+ const { total: total1 } = dbClientQueryHistoryQueries.list({
204
+ connectionId: conn1.id,
205
+ limit: 1000
206
+ });
207
+ expect(total1).toBe(HISTORY_KEEP_PER_CONNECTION);
208
+
209
+ // Verify conn2 still has all 50 (not affected by conn1 pruning)
210
+ const { total: total2 } = dbClientQueryHistoryQueries.list({
211
+ connectionId: conn2.id,
212
+ limit: 1000
213
+ });
214
+ expect(total2).toBe(50);
215
+ });
216
+ });
217
+
@@ -3,14 +3,20 @@
3
3
  */
4
4
 
5
5
  import { t } from 'elysia';
6
+ import type { DbClientQueryResult } from '$shared/types/db-client';
6
7
  import { createRouter } from '$shared/utils/ws-server';
7
8
  import { connectionManager } from '../../db-client/connection-manager';
8
- import { runSafely } from '../../db-client/query-executor';
9
+ import { executeBatch, runSafely } from '../../db-client/query-executor';
10
+ import { splitSqlStatements } from '$shared/utils/db-client/split-sql';
9
11
  import { dbClientQueryHistoryQueries } from '../../database/queries';
10
12
  import { getDbClientPrincipal, requireDbClientConnectionAccess } from './access';
11
13
  import { debug } from '$shared/utils/logger';
12
14
 
13
15
  const HISTORY_KEEP_PER_CONNECTION = 200;
16
+ const PRUNE_EVERY_N_QUERIES = 10;
17
+
18
+ // Track insert count per connection for deterministic pruning
19
+ const insertCounters = new Map<string, number>();
14
20
 
15
21
  function recordHistory(input: {
16
22
  connectionId: string;
@@ -31,8 +37,14 @@ function recordHistory(input: {
31
37
  status: input.status,
32
38
  error: input.error
33
39
  });
34
- if (Math.random() < 0.05) {
40
+
41
+ // Deterministic pruning: prune after every N inserts
42
+ const count = (insertCounters.get(input.connectionId) ?? 0) + 1;
43
+ insertCounters.set(input.connectionId, count);
44
+
45
+ if (count >= PRUNE_EVERY_N_QUERIES) {
35
46
  dbClientQueryHistoryQueries.prune(input.connectionId, HISTORY_KEEP_PER_CONNECTION);
47
+ insertCounters.set(input.connectionId, 0);
36
48
  }
37
49
  } catch (err) {
38
50
  // history must never break query execution
@@ -133,6 +145,69 @@ export const queryHandler = createRouter()
133
145
  }
134
146
  })
135
147
 
148
+ .http('db-client:execute-batch', {
149
+ data: t.Object({
150
+ connectionId: t.String({ minLength: 1 }),
151
+ query: t.String({ minLength: 1 }),
152
+ params: t.Optional(t.Array(t.Any())),
153
+ database: t.Optional(t.String()),
154
+ limit: t.Optional(t.Number())
155
+ }),
156
+ response: t.Any()
157
+ }, async ({ data, conn }) => {
158
+ const { userId } = getDbClientPrincipal(conn);
159
+ const connection = requireDbClientConnectionAccess(conn, data.connectionId);
160
+ const adapter = await connectionManager.get(data.connectionId);
161
+ // 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()];
164
+ const statements = split.length > 0 ? split : [data.query.trim()];
165
+ try {
166
+ const batch = await executeBatch({
167
+ driver: connection.driver,
168
+ adapter,
169
+ statements,
170
+ params: data.params,
171
+ database: data.database,
172
+ limit: data.limit
173
+ });
174
+ const rowCount = batch.statements.reduce((acc, s) => acc + (s.result?.rowCount ?? 0), 0);
175
+ const affectedRows = batch.statements.reduce((acc, s) => acc + (s.result?.affectedRows ?? 0), 0);
176
+ const failed = batch.statements.find((s) => s.status === 'error');
177
+ recordHistory({
178
+ connectionId: data.connectionId,
179
+ userId,
180
+ query: data.query,
181
+ status: batch.ok ? 'success' : 'error',
182
+ durationMs: batch.totalDurationMs,
183
+ rowCount,
184
+ error: failed?.error ?? null
185
+ });
186
+ // Mirror the last statement that produced rows at the top level (so
187
+ // existing single-result consumers keep working) with the full
188
+ // per-statement report attached under `batch`.
189
+ const reversed = [...batch.statements].reverse();
190
+ const lastResult = reversed.find((s) => s.result && s.result.rows.length > 0)?.result
191
+ ?? reversed.find((s) => s.result)?.result
192
+ ?? null;
193
+ const top: DbClientQueryResult = lastResult
194
+ ? { ...lastResult, durationMs: batch.totalDurationMs, batch }
195
+ : { columns: [], rows: [], rowCount, affectedRows, durationMs: batch.totalDurationMs, driverMeta: {}, batch };
196
+ return top;
197
+ } catch (error) {
198
+ recordHistory({
199
+ connectionId: data.connectionId,
200
+ userId,
201
+ query: data.query,
202
+ status: 'error',
203
+ durationMs: null,
204
+ rowCount: null,
205
+ error: error instanceof Error ? error.message : String(error)
206
+ });
207
+ throw error;
208
+ }
209
+ })
210
+
136
211
  .http('db-client:explain', {
137
212
  data: t.Object({
138
213
  connectionId: t.String({ minLength: 1 }),
@@ -22,7 +22,7 @@ import {
22
22
  duplicateOperation,
23
23
  deleteOperation
24
24
  } from '../../files/file-operations';
25
- import { createZipOperation, extractZipOperation } from '../../files/file-archive';
25
+ import { createArchiveOperation, extractArchiveOperation } from '../../files/file-archive';
26
26
  import { stat as fsStat, readdir as fsReaddir, rename as fsRename } from 'node:fs/promises';
27
27
  import { requireFilePathAccess, requireSharedFilePathAccess } from './path-access';
28
28
 
@@ -127,11 +127,21 @@ export const writeHandler = createRouter()
127
127
  // kept getting dropped by the Vite dev proxy with `write EPIPE` on
128
128
  // sustained binary transfers (any chunk size). See backend/http/files-upload.ts.
129
129
 
130
- // Zip operation — compress a set of files/directories into a single archive
130
+ // Compress operation — pack files/directories into an archive (zip/tar/7z)
131
131
  .http('files:zip', {
132
132
  data: t.Object({
133
133
  sourcePaths: t.Array(t.String()),
134
- targetPath: t.String()
134
+ targetPath: t.String(),
135
+ format: t.Optional(t.Union([
136
+ t.Literal('zip'),
137
+ t.Literal('tar'),
138
+ t.Literal('tar.gz'),
139
+ t.Literal('tar.zst'),
140
+ t.Literal('7z')
141
+ ])),
142
+ method: t.Optional(t.Union([t.Literal('store'), t.Literal('deflate'), t.Literal('zstd')])),
143
+ level: t.Optional(t.Number()),
144
+ password: t.Optional(t.String())
135
145
  }),
136
146
  response: t.Object({
137
147
  message: t.String(),
@@ -148,14 +158,20 @@ export const writeHandler = createRouter()
148
158
  resolvedSources.push(await requireFilePathAccess(conn, p));
149
159
  }
150
160
  const resolvedTarget = await requireFilePathAccess(conn, data.targetPath);
151
- return await createZipOperation(resolvedSources, resolvedTarget);
161
+ return await createArchiveOperation(resolvedSources, resolvedTarget, {
162
+ format: data.format,
163
+ method: data.method,
164
+ level: data.level,
165
+ password: data.password
166
+ });
152
167
  })
153
168
 
154
- // Extract operation — extract a zip archive into a target directory
169
+ // Extract operation — extract any supported archive into a target directory
155
170
  .http('files:extract', {
156
171
  data: t.Object({
157
172
  archivePath: t.String(),
158
- targetDir: t.String()
173
+ targetDir: t.String(),
174
+ password: t.Optional(t.String())
159
175
  }),
160
176
  response: t.Object({
161
177
  message: t.String(),
@@ -166,7 +182,7 @@ export const writeHandler = createRouter()
166
182
  }, async ({ data, conn }) => {
167
183
  const archivePath = await requireFilePathAccess(conn, data.archivePath);
168
184
  const targetDir = await requireFilePathAccess(conn, data.targetDir);
169
- return await extractZipOperation(archivePath, targetDir);
185
+ return await extractArchiveOperation(archivePath, targetDir, data.password);
170
186
  })
171
187
 
172
188
  // Delete operation
@@ -0,0 +1,65 @@
1
+ import { t } from 'elysia';
2
+ import { createRouter } from '$shared/utils/ws-server';
3
+ import { execGit } from '../../git/git-executor';
4
+ import { requireProjectAccess } from '../access';
5
+ import path from 'path';
6
+
7
+ export const ignoredHandler = createRouter()
8
+ .http('git:ignored-paths', {
9
+ data: t.Object({
10
+ projectId: t.String()
11
+ }),
12
+ response: t.Object({
13
+ ignored: t.Array(t.String())
14
+ })
15
+ }, async ({ data, conn }) => {
16
+ const project = requireProjectAccess(conn, data.projectId);
17
+ const ignored: string[] = [];
18
+
19
+ try {
20
+ const isRepo = await execGit(['rev-parse', '--is-inside-work-tree'], project.path, 5_000)
21
+ .then(r => r.exitCode === 0)
22
+ .catch(() => false);
23
+
24
+ if (!isRepo) return { ignored };
25
+
26
+ // Get ignored files (leaf paths)
27
+ const filesResult = await execGit(
28
+ ['ls-files', '--others', '--ignored', '--exclude-standard'],
29
+ project.path,
30
+ 30_000
31
+ );
32
+ if (filesResult.exitCode === 0) {
33
+ const sep = project.path.includes('\\') ? '\\' : '/';
34
+ for (const line of filesResult.stdout.split('\n')) {
35
+ const relPath = line.trim();
36
+ if (!relPath) continue;
37
+ ignored.push(path.join(project.path, relPath.replace(/\//g, sep)));
38
+ }
39
+ }
40
+
41
+ // Get ignored directories (shown with --directory flag)
42
+ const dirsResult = await execGit(
43
+ ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory'],
44
+ project.path,
45
+ 30_000
46
+ );
47
+ if (dirsResult.exitCode === 0) {
48
+ const seen = new Set(ignored);
49
+ const sep = project.path.includes('\\') ? '\\' : '/';
50
+ for (const line of dirsResult.stdout.split('\n')) {
51
+ const relPath = line.trim().replace(/\/$/, '');
52
+ if (!relPath) continue;
53
+ const absPath = path.join(project.path, relPath.replace(/\//g, sep));
54
+ if (!seen.has(absPath)) {
55
+ ignored.push(absPath);
56
+ seen.add(absPath);
57
+ }
58
+ }
59
+ }
60
+ } catch {
61
+ // If git fails, return empty
62
+ }
63
+
64
+ return { ignored };
65
+ });
@@ -14,6 +14,7 @@ import { remoteHandler } from './remote';
14
14
  import { conflictHandler } from './conflict';
15
15
  import { commitMessageHandler } from './commit-message';
16
16
  import { branchNameHandler } from './branch-name';
17
+ import { ignoredHandler } from './ignored';
17
18
 
18
19
  export const gitRouter = createRouter()
19
20
  .merge(statusHandler)
@@ -25,4 +26,5 @@ export const gitRouter = createRouter()
25
26
  .merge(remoteHandler)
26
27
  .merge(conflictHandler)
27
28
  .merge(commitMessageHandler)
28
- .merge(branchNameHandler);
29
+ .merge(branchNameHandler)
30
+ .merge(ignoredHandler);
@@ -17,7 +17,7 @@ import { ws } from '$backend/utils/ws';
17
17
  import { snapshotService } from '../../snapshot/snapshot-service';
18
18
  import { blobStore } from '../../snapshot/blob-store';
19
19
  import { streamManager } from '../../chat/stream-manager';
20
- import { terminalStreamManager } from '../../terminal/stream-manager';
20
+ import { cleanupProjectSessions } from '../../terminal/ptykit';
21
21
  import { broadcastPresence } from '../projects/status';
22
22
  import { debug } from '$shared/utils/logger';
23
23
  import { requireProjectAccess } from '../access';
@@ -106,9 +106,9 @@ export const crudHandler = createRouter()
106
106
 
107
107
  const mode = data.mode ?? 'remove';
108
108
 
109
- // Clean up terminal streams for this project
110
- const cleanedStreams = terminalStreamManager.cleanupProjectStreams(data.id);
111
- debug.log('project', `Cleaned up ${cleanedStreams} terminal streams for project ${data.id}`);
109
+ // Clean up terminal (PTY) sessions for this project
110
+ const cleanedStreams = cleanupProjectSessions(data.id);
111
+ debug.log('project', `Cleaned up ${cleanedStreams} terminal sessions for project ${data.id}`);
112
112
 
113
113
  if (mode === 'full') {
114
114
  // Full delete: remove sessions with blob cleanup, then the project itself
@@ -88,6 +88,29 @@ export const operationsHandler = createRouter()
88
88
  };
89
89
  })
90
90
 
91
+ // Fetch release notes from GitHub
92
+ .http('system:get-release-notes', {
93
+ data: t.Object({}),
94
+ response: t.Object({
95
+ tag_name: t.String(),
96
+ body: t.String(),
97
+ html_url: t.String(),
98
+ published_at: t.String()
99
+ })
100
+ }, async () => {
101
+ const response = await fetch('https://api.github.com/repos/myrialabs/clopen/releases/latest');
102
+ if (!response.ok) {
103
+ throw new Error(`GitHub API returned ${response.status}`);
104
+ }
105
+ const data = await response.json() as { tag_name: string; body: string; html_url: string; published_at: string };
106
+ return {
107
+ tag_name: data.tag_name,
108
+ body: data.body || '',
109
+ html_url: data.html_url,
110
+ published_at: data.published_at
111
+ };
112
+ })
113
+
91
114
  // Run package update
92
115
  .http('system:run-update', {
93
116
  data: t.Object({}),
@@ -1,40 +1,13 @@
1
1
  /**
2
2
  * Terminal Router
3
3
  *
4
- * Combines all terminal WebSocket handlers into a single router.
5
- * Replaces SSE-based terminal streaming with WebSocket bi-directional communication.
6
- *
7
- * Structure:
8
- * - session.ts: HTTP endpoints for session management (create, resize, kill, cancel, check-shell, pty-status)
9
- * - stream.ts: Real-time events for terminal I/O (input, output, exit, directory, ready)
10
- * - persistence.ts: Stream persistence and reconnection (stream-status, missed-output, reconnect)
4
+ * Terminal PTY sessions run on @myrialabs/ptykit. Its embedded WebSocket server
5
+ * is tunneled over Clopen's app-wide socket — see `tunnel.ts`. All session
6
+ * lifecycle, I/O, scrollback reattach, rooms, and reconnect are handled by the
7
+ * PtyKit wire protocol carried on `terminal:pty` / `terminal:pty-out`.
11
8
  */
12
9
 
13
- import { t } from 'elysia';
14
10
  import { createRouter } from '$shared/utils/ws-server';
15
- import { sessionHandler } from './session';
16
- import { streamHandler } from './stream';
17
- import { persistenceHandler } from './persistence';
18
-
19
- export const terminalRouter = createRouter()
20
- // Session Management (HTTP)
21
- .merge(sessionHandler)
22
-
23
- // Stream Events (Real-time I/O)
24
- .merge(streamHandler)
25
-
26
- // Stream Persistence (HTTP + Events)
27
- .merge(persistenceHandler)
11
+ import { terminalTunnelHandler } from './tunnel';
28
12
 
29
- // Collaborative broadcast events (Server → Client)
30
- .emit('terminal:tab-created', t.Object({
31
- sessionId: t.String(),
32
- streamId: t.String(),
33
- pid: t.Number(),
34
- currentDirectory: t.String(),
35
- cols: t.Number(),
36
- rows: t.Number()
37
- }))
38
- .emit('terminal:tab-closed', t.Object({
39
- sessionId: t.String()
40
- }));
13
+ export const terminalRouter = createRouter().merge(terminalTunnelHandler);
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Terminal tunnel — carries the PtyKit wire protocol over Clopen's app-wide
3
+ * WebSocket instead of a dedicated `/pty` socket.
4
+ *
5
+ * Inbound client frames arrive on `terminal:pty`; each Clopen connection gets one
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
9
+ * carried on the connection so `authorize` can enforce project access.
10
+ */
11
+
12
+ import { t } from 'elysia';
13
+ import { createRouter } from '$shared/utils/ws-server';
14
+ import type { WSConnection } from '$shared/utils/ws-server';
15
+ import type { PtyKitConnection } from '@myrialabs/ptykit/server';
16
+ import type { WireFrame } from '@myrialabs/ptykit';
17
+ import { ws } from '$backend/utils/ws';
18
+ import { ptyKitServer } from '../../terminal/ptykit';
19
+ import { debug } from '$shared/utils/logger';
20
+
21
+ /** One embedded PtyKit connection per Clopen ws connection (by stable id). */
22
+ const ptyConnections = new Map<string, PtyKitConnection>();
23
+
24
+ /** Resolve (or lazily create) the PtyKit connection backing a Clopen connection. */
25
+ function getPtyConnection(conn: WSConnection): PtyKitConnection {
26
+ const connId = ws.getConnectionId(conn);
27
+ if (!connId) {
28
+ throw new Error('Connection not registered');
29
+ }
30
+
31
+ const existing = ptyConnections.get(connId);
32
+ if (existing) return existing;
33
+
34
+ const userId = ws.getUserId(conn);
35
+ const ptyConn = ptyKitServer.createConnection({
36
+ data: { userId, connId },
37
+ send: (frame) => {
38
+ ws.sendToConnectionId(connId, JSON.stringify({ action: 'terminal:pty-out', payload: frame }));
39
+ }
40
+ });
41
+ ptyKitServer.handleOpen(ptyConn);
42
+ ptyConnections.set(connId, ptyConn);
43
+
44
+ // Tear the PtyKit connection down (leave rooms) when the socket closes.
45
+ ws.addCleanup(conn, () => {
46
+ ptyKitServer.handleClose(ptyConn);
47
+ ptyConnections.delete(connId);
48
+ });
49
+
50
+ debug.log('terminal', `🔌 PtyKit connection opened for ${connId}`);
51
+ return ptyConn;
52
+ }
53
+
54
+ export const terminalTunnelHandler = createRouter()
55
+ // Client → server: one PtyKit wire frame.
56
+ .on('terminal:pty', {
57
+ data: t.Object({
58
+ action: t.String(),
59
+ payload: t.Any()
60
+ })
61
+ }, ({ conn, data }) => {
62
+ const ptyConn = getPtyConnection(conn);
63
+ void ptyKitServer.handleFrame(ptyConn, data as WireFrame);
64
+ })
65
+ // Server → client: PtyKit wire frames (RPC responses + broadcast events,
66
+ // including PtyKit's own room-level `tab-created` / `tab-closed`). Declared for
67
+ // the typed WSAPI; actually sent via ws.sendToConnectionId above.
68
+ //
69
+ // Collaborative tab-list sync rides this same stream: the frontend subscribes
70
+ // to PtyKit's tab events via `ptyClient.onSessionCreated` / `onSessionClosed`
71
+ // (see frontend/services/terminal/project.service.ts), so there are no
72
+ // Clopen-native tab events to declare here.
73
+ .emit('terminal:pty-out', t.Object({
74
+ action: t.String(),
75
+ payload: t.Any()
76
+ }));
@@ -0,0 +1 @@
1
+ const e={};export{e as default};
@@ -0,0 +1 @@
1
+ import{s as _,_ as d,r as s,a as u}from"./main-BkCc3WEB.js";import{C as T,P as y,W as E,d as L,b as g,c as v,h as P,l as b,m as k,e as D,n as O,f as R,g as S,t as V}from"./main-BkCc3WEB.js";async function h(o,e={}){const i=e.loading===!1?void 0:_(o,e.loadingText??"Loading…"),[{Terminal:l},{FitAddon:c}]=await Promise.all([d(()=>import("./xterm-B-qIQCd3.js"),[]),d(()=>import("./addon-fit-DX4qG4td.js"),[])]).catch(r=>{throw i?.(),r}),a=new l({scrollback:e.scrollback??5e3,fontSize:e.fontSize??13,fontFamily:e.fontFamily??"ui-monospace, SFMono-Regular, Menlo, monospace",lineHeight:e.lineHeight??1,cursorBlink:e.cursorBlink??!1,cursorStyle:e.cursorStyle??"block",disableStdin:e.stdin!==!0,allowProposedApi:!0,convertEol:!0,theme:s(e.theme),...e.cols?{cols:e.cols}:{},...e.rows?{rows:e.rows}:{},...e.terminalOptions??{}}),t=e.fit===!1?void 0:new c;if(t&&a.loadAddon(t),e.clipboard)try{const{ClipboardAddon:r}=await d(()=>import("./addon-clipboard-wHJhZAA4.js"),[]);a.loadAddon(new r)}catch{}if(e.webLinks)try{const{WebLinksAddon:r}=await d(()=>import("./addon-web-links-DIbG5aQx.js"),[]);a.loadAddon(new r)}catch{}if(e.unicode11)try{const{Unicode11Addon:r}=await d(()=>import("./addon-unicode11-Bt8F3D7-.js"),[]);a.loadAddon(new r),a.unicode.activeVersion="11"}catch{}for(const r of e.addons??[])a.loadAddon(r);if(a.open(o),e.ligatures)try{const{LigaturesAddon:r}=await d(()=>import("./addon-ligatures-DpDY8N_X.js"),[]);a.loadAddon(new r)}catch{}const m=t?u({resize:async()=>{}},a,t,{debounceMs:e.fitDebounceMs??100}):void 0;e.onReady?.(a),i?.();let n=!1;return{terminal:a,fitAddon:t,write:r=>a.write(r),clear:()=>{a.clear(),a.reset()},fit:()=>t?.fit(),setTheme:r=>{a.options.theme=s(r)},dispose(){n||(n=!0,m?.(),a.dispose())}}}export{T as ClientSession,y as PtyKitClient,E as WsCore,u as attachFit,L as darkTheme,g as defaultPersistence,v as draculaTheme,P as hostSocket,b as lightTheme,k as matrixTheme,D as mountTerminal,h as mountViewer,O as nordTheme,s as resolveTheme,_ as showLoadingOverlay,R as solarizedDarkTheme,S as solarizedLightTheme,V as themes};