@myrialabs/clopen 0.4.32 → 0.4.34

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 (102) hide show
  1. package/backend/auth/permissions.ts +3 -0
  2. package/backend/auth/rate-limiter.test.ts +115 -0
  3. package/backend/auth/rate-limiter.ts +25 -12
  4. package/backend/chat/stream-manager.ts +4 -1
  5. package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
  6. package/backend/database/migrations/index.ts +7 -0
  7. package/backend/database/queries/db-client-connection-queries.ts +7 -2
  8. package/backend/database/queries/file-audit-log-queries.ts +1 -0
  9. package/backend/database/queries/index.ts +3 -0
  10. package/backend/database/queries/ssh-connection-queries.ts +244 -0
  11. package/backend/database/queries/ssh-known-host-queries.ts +67 -0
  12. package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
  13. package/backend/db-client/connection-manager.ts +21 -1
  14. package/backend/engine/adapters/codex/message-converter.ts +18 -12
  15. package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
  16. package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
  17. package/backend/engine/adapters/codex/stream.ts +33 -4
  18. package/backend/engine/adapters/copilot/stream.ts +1 -1
  19. package/backend/engine/adapters/cursor/stream.ts +1 -1
  20. package/backend/engine/adapters/qwen/stream.ts +1 -1
  21. package/backend/engine/docs/adapter-contract.md +7 -0
  22. package/backend/files/file-watcher.ts +283 -51
  23. package/backend/files/git-events.test.ts +110 -0
  24. package/backend/git/git-dirs.test.ts +132 -0
  25. package/backend/git/git-dirs.ts +0 -0
  26. package/backend/git/nested-repos.test.ts +108 -5
  27. package/backend/git/nested-repos.ts +103 -18
  28. package/backend/http/audio.ts +5 -32
  29. package/backend/http/bearer-auth.ts +47 -0
  30. package/backend/http/files-download.test.ts +146 -0
  31. package/backend/http/files-download.ts +109 -0
  32. package/backend/http/files-upload.ts +3 -29
  33. package/backend/http/ssh-sftp.ts +133 -0
  34. package/backend/index.ts +25 -2
  35. package/backend/mcp/README.md +34 -6
  36. package/backend/mcp/index.ts +8 -8
  37. package/backend/mcp/internal/config.ts +69 -19
  38. package/backend/mcp/internal/project-context.test.ts +40 -0
  39. package/backend/mcp/internal/project-context.ts +80 -7
  40. package/backend/mcp/internal/remote-server.test.ts +17 -2
  41. package/backend/mcp/internal/remote-server.ts +36 -3
  42. package/backend/mcp/internal/servers/helper.ts +48 -18
  43. package/backend/middleware/security.test.ts +95 -0
  44. package/backend/middleware/security.ts +114 -0
  45. package/backend/ports/attribute.test.ts +231 -0
  46. package/backend/ports/attribute.ts +444 -0
  47. package/backend/ports/kill.ts +203 -0
  48. package/backend/ports/monitor.ts +365 -0
  49. package/backend/ports/processes.test.ts +98 -0
  50. package/backend/ports/processes.ts +374 -0
  51. package/backend/ports/registry.ts +165 -0
  52. package/backend/ports/runner.ts +195 -0
  53. package/backend/ports/scan-host.ts +260 -0
  54. package/backend/ports/scan.test.ts +341 -0
  55. package/backend/ports/scan.ts +687 -0
  56. package/backend/ports/ssh-lineage.ts +318 -0
  57. package/backend/preview/browser/browser-video-capture.ts +51 -4
  58. package/backend/ssh/client-pool.ts +196 -0
  59. package/backend/ssh/connect.ts +375 -0
  60. package/backend/ssh/disk-usage.test.ts +134 -0
  61. package/backend/ssh/disk-usage.ts +214 -0
  62. package/backend/ssh/forwards.ts +340 -0
  63. package/backend/ssh/health.ts +141 -0
  64. package/backend/ssh/known-hosts.ts +96 -0
  65. package/backend/ssh/pty-backend.ts +215 -0
  66. package/backend/ssh/ptykit.ts +66 -0
  67. package/backend/ssh/sftp.test.ts +242 -0
  68. package/backend/ssh/sftp.ts +967 -0
  69. package/backend/ssh/socks5.test.ts +167 -0
  70. package/backend/ssh/socks5.ts +164 -0
  71. package/backend/ssh/tunnel.ts +87 -0
  72. package/backend/ws/auth/device.ts +1 -1
  73. package/backend/ws/auth/login.ts +8 -4
  74. package/backend/ws/db-client/connections.ts +1 -0
  75. package/backend/ws/files/watch.ts +5 -1
  76. package/backend/ws/index.ts +6 -0
  77. package/backend/ws/ports/index.ts +19 -0
  78. package/backend/ws/ports/kill.ts +80 -0
  79. package/backend/ws/ports/list.ts +60 -0
  80. package/backend/ws/ssh/access.ts +31 -0
  81. package/backend/ws/ssh/connections.ts +224 -0
  82. package/backend/ws/ssh/forwards.ts +109 -0
  83. package/backend/ws/ssh/index.ts +18 -0
  84. package/backend/ws/ssh/sftp.ts +259 -0
  85. package/backend/ws/ssh/tunnel.ts +93 -0
  86. package/dist/assets/{index-hu17G6tX.js → index-gGTMFUa8.js} +1 -1
  87. package/dist/assets/{index-DSvGoxp2.js → index-vW2RpdHu.js} +1 -1
  88. package/dist/assets/main-CYCMEbXB.css +1 -0
  89. package/dist/assets/{main-BccclZsC.js → main-ZCojSzvW.js} +506 -477
  90. package/dist/index.html +2 -2
  91. package/package.json +1 -1
  92. package/shared/types/database/schema.ts +49 -0
  93. package/shared/types/db-client/connection.ts +6 -0
  94. package/shared/types/ports/index.ts +5 -0
  95. package/shared/types/ports/port.ts +192 -0
  96. package/shared/types/ssh/connection.ts +80 -0
  97. package/shared/types/ssh/forward.ts +46 -0
  98. package/shared/types/ssh/index.ts +8 -0
  99. package/shared/types/ssh/known-host.ts +19 -0
  100. package/shared/types/ssh/sftp.ts +141 -0
  101. package/shared/utils/logger.ts +2 -0
  102. package/dist/assets/main-Ciuw0wF0.css +0 -1
@@ -0,0 +1,244 @@
1
+ import { getDatabase } from '../index';
2
+ import type { DBSshConnectionRow } from '$shared/types/database/schema';
3
+ import type { SshAuthMethod, SshConnection, SshConnectionInput } from '$shared/types/ssh';
4
+
5
+ function rowToConnection(row: DBSshConnectionRow): SshConnection {
6
+ return {
7
+ id: row.id,
8
+ name: row.name,
9
+ host: row.host,
10
+ port: row.port,
11
+ username: row.username,
12
+ authMethod: row.auth_method as SshAuthMethod,
13
+ password: row.password,
14
+ privateKey: row.private_key,
15
+ privateKeyPath: row.private_key_path,
16
+ passphrase: row.passphrase,
17
+ agentSocket: row.agent_socket,
18
+ jumpConnectionId: row.jump_connection_id,
19
+ initialPath: row.initial_path,
20
+ keepaliveSeconds: row.keepalive_seconds,
21
+ strictHostKey: row.strict_host_key === 1,
22
+ color: row.color,
23
+ createdAt: row.created_at,
24
+ updatedAt: row.updated_at,
25
+ lastUsedAt: row.last_used_at
26
+ };
27
+ }
28
+
29
+ /**
30
+ * Strip every secret before a connection leaves the server. The client only
31
+ * ever needs to know *whether* a credential is set, which it infers from the
32
+ * auth method — mirrors db-client's redactConnectionSecrets.
33
+ */
34
+ function redactConnectionSecrets(connection: SshConnection): SshConnection {
35
+ return {
36
+ ...connection,
37
+ password: null,
38
+ privateKey: null,
39
+ passphrase: null
40
+ };
41
+ }
42
+
43
+ function hasConnectionAccess(row: DBSshConnectionRow, userId: string, isAdmin: boolean): boolean {
44
+ if (isAdmin) return true;
45
+ return row.owner_user_id === userId;
46
+ }
47
+
48
+ /**
49
+ * An empty string in a patch means "the form did not re-send this secret",
50
+ * not "clear it" — otherwise editing the name of a key-authenticated host
51
+ * would wipe the key.
52
+ */
53
+ function preserveExistingSecret(patchValue: string | undefined, existingValue: string | null): string | null {
54
+ if (patchValue === undefined || patchValue === '') return existingValue;
55
+ return patchValue;
56
+ }
57
+
58
+ function getRowById(id: string): DBSshConnectionRow | null {
59
+ const db = getDatabase();
60
+ return db.prepare('SELECT * FROM ssh_connections WHERE id = ?').get(id) as DBSshConnectionRow | null;
61
+ }
62
+
63
+ /**
64
+ * True when adding `jumpConnectionId` as `connectionId`'s bastion would create
65
+ * a cycle (A jumps through B which jumps back through A). Walking the chain is
66
+ * cheap and stops an unbounded connect loop at save time rather than at dial time.
67
+ */
68
+ function wouldCycle(connectionId: string, jumpConnectionId: string | null): boolean {
69
+ let cursor = jumpConnectionId;
70
+ const visited = new Set<string>([connectionId]);
71
+ while (cursor) {
72
+ if (visited.has(cursor)) return true;
73
+ visited.add(cursor);
74
+ cursor = getRowById(cursor)?.jump_connection_id ?? null;
75
+ }
76
+ return false;
77
+ }
78
+
79
+ function insertConnection(input: SshConnectionInput, ownerUserId: string | null): SshConnection {
80
+ const db = getDatabase();
81
+ const id = crypto.randomUUID();
82
+ const now = new Date().toISOString();
83
+
84
+ db.prepare(`
85
+ INSERT INTO ssh_connections (
86
+ id, name, host, port, username, auth_method,
87
+ password, private_key, private_key_path, passphrase, agent_socket,
88
+ jump_connection_id, initial_path, keepalive_seconds, strict_host_key,
89
+ color, owner_user_id, created_at, updated_at, last_used_at
90
+ ) VALUES (
91
+ ?, ?, ?, ?, ?, ?,
92
+ ?, ?, ?, ?, ?,
93
+ ?, ?, ?, ?,
94
+ ?, ?, ?, ?, ?
95
+ )
96
+ `).run(
97
+ id,
98
+ input.name,
99
+ input.host,
100
+ input.port ?? 22,
101
+ input.username,
102
+ input.authMethod ?? 'password',
103
+ input.password || null,
104
+ input.privateKey || null,
105
+ input.privateKeyPath || null,
106
+ input.passphrase || null,
107
+ input.agentSocket || null,
108
+ input.jumpConnectionId || null,
109
+ input.initialPath || null,
110
+ input.keepaliveSeconds ?? 30,
111
+ input.strictHostKey === false ? 0 : 1,
112
+ input.color || null,
113
+ ownerUserId,
114
+ now,
115
+ now,
116
+ null
117
+ );
118
+
119
+ const row = getRowById(id);
120
+ if (!row) throw new Error('ssh connection not found');
121
+ return rowToConnection(row);
122
+ }
123
+
124
+ export const sshConnectionQueries = {
125
+ listForUser(userId: string, isAdmin: boolean): SshConnection[] {
126
+ const db = getDatabase();
127
+ const rows = (isAdmin
128
+ ? db.prepare(`
129
+ SELECT * FROM ssh_connections
130
+ ORDER BY (last_used_at IS NULL), last_used_at DESC, created_at DESC
131
+ `).all()
132
+ : db.prepare(`
133
+ SELECT * FROM ssh_connections
134
+ WHERE owner_user_id = ?
135
+ ORDER BY (last_used_at IS NULL), last_used_at DESC, created_at DESC
136
+ `).all(userId)) as DBSshConnectionRow[];
137
+
138
+ return rows.map((row) => redactConnectionSecrets(rowToConnection(row)));
139
+ },
140
+
141
+ getForUser(id: string, userId: string, isAdmin: boolean): SshConnection | null {
142
+ const row = getRowById(id);
143
+ if (!row || !hasConnectionAccess(row, userId, isAdmin)) return null;
144
+ return redactConnectionSecrets(rowToConnection(row));
145
+ },
146
+
147
+ /** Full connection including secrets — server-side callers only. Throws on denial. */
148
+ ensureAccess(id: string, userId: string, isAdmin: boolean): SshConnection {
149
+ const row = getRowById(id);
150
+ if (!row || !hasConnectionAccess(row, userId, isAdmin)) {
151
+ throw new Error('ssh connection not found');
152
+ }
153
+ return rowToConnection(row);
154
+ },
155
+
156
+ get(id: string): SshConnection | null {
157
+ const row = getRowById(id);
158
+ return row ? rowToConnection(row) : null;
159
+ },
160
+
161
+ createForUser(input: SshConnectionInput, ownerUserId: string): SshConnection {
162
+ if (input.jumpConnectionId && !getRowById(input.jumpConnectionId)) {
163
+ throw new Error('Jump host not found');
164
+ }
165
+ return redactConnectionSecrets(insertConnection(input, ownerUserId));
166
+ },
167
+
168
+ update(id: string, patch: Partial<SshConnectionInput>): SshConnection {
169
+ const db = getDatabase();
170
+ const existing = getRowById(id);
171
+ if (!existing) throw new Error('ssh connection not found');
172
+
173
+ const sets: string[] = [];
174
+ const values: unknown[] = [];
175
+ const push = (column: string, value: unknown): void => {
176
+ sets.push(`${column} = ?`);
177
+ values.push(value);
178
+ };
179
+
180
+ if (patch.name !== undefined) push('name', patch.name);
181
+ if (patch.host !== undefined) push('host', patch.host);
182
+ if (patch.port !== undefined) push('port', patch.port ?? 22);
183
+ if (patch.username !== undefined) push('username', patch.username);
184
+ if (patch.authMethod !== undefined) push('auth_method', patch.authMethod);
185
+ if (patch.privateKeyPath !== undefined) push('private_key_path', patch.privateKeyPath || null);
186
+ if (patch.agentSocket !== undefined) push('agent_socket', patch.agentSocket || null);
187
+ if (patch.initialPath !== undefined) push('initial_path', patch.initialPath || null);
188
+ if (patch.keepaliveSeconds !== undefined) push('keepalive_seconds', patch.keepaliveSeconds ?? 30);
189
+ if (patch.strictHostKey !== undefined) push('strict_host_key', patch.strictHostKey ? 1 : 0);
190
+ if (patch.color !== undefined) push('color', patch.color || null);
191
+
192
+ if (patch.jumpConnectionId !== undefined) {
193
+ const jumpConnectionId = patch.jumpConnectionId || null;
194
+ if (jumpConnectionId && !getRowById(jumpConnectionId)) {
195
+ throw new Error('Jump host not found');
196
+ }
197
+ if (jumpConnectionId === id) {
198
+ throw new Error('A host cannot jump through itself');
199
+ }
200
+ if (wouldCycle(id, jumpConnectionId)) {
201
+ throw new Error('That jump host would create a loop');
202
+ }
203
+ push('jump_connection_id', jumpConnectionId);
204
+ }
205
+
206
+ if (patch.password !== undefined) push('password', preserveExistingSecret(patch.password, existing.password));
207
+ if (patch.privateKey !== undefined) push('private_key', preserveExistingSecret(patch.privateKey, existing.private_key));
208
+ if (patch.passphrase !== undefined) push('passphrase', preserveExistingSecret(patch.passphrase, existing.passphrase));
209
+
210
+ push('updated_at', new Date().toISOString());
211
+
212
+ values.push(id);
213
+ db.prepare(`UPDATE ssh_connections SET ${sets.join(', ')} WHERE id = ?`).run(...values);
214
+
215
+ const row = getRowById(id);
216
+ if (!row) throw new Error('ssh connection not found');
217
+ return rowToConnection(row);
218
+ },
219
+
220
+ updateForUser(
221
+ id: string,
222
+ patch: Partial<SshConnectionInput>,
223
+ userId: string,
224
+ isAdmin: boolean
225
+ ): SshConnection {
226
+ this.ensureAccess(id, userId, isAdmin);
227
+ return redactConnectionSecrets(this.update(id, patch));
228
+ },
229
+
230
+ delete(id: string): void {
231
+ const db = getDatabase();
232
+ db.prepare('DELETE FROM ssh_connections WHERE id = ?').run(id);
233
+ },
234
+
235
+ deleteForUser(id: string, userId: string, isAdmin: boolean): void {
236
+ this.ensureAccess(id, userId, isAdmin);
237
+ this.delete(id);
238
+ },
239
+
240
+ markUsed(id: string): void {
241
+ const db = getDatabase();
242
+ db.prepare('UPDATE ssh_connections SET last_used_at = ? WHERE id = ?').run(new Date().toISOString(), id);
243
+ }
244
+ };
@@ -0,0 +1,67 @@
1
+ import { getDatabase } from '../index';
2
+ import type { DBSshKnownHostRow } from '$shared/types/database/schema';
3
+ import type { SshKnownHost } from '$shared/types/ssh';
4
+
5
+ function rowToKnownHost(row: DBSshKnownHostRow): SshKnownHost {
6
+ return {
7
+ id: row.id,
8
+ host: row.host,
9
+ port: row.port,
10
+ keyType: row.key_type,
11
+ fingerprint: row.fingerprint,
12
+ addedAt: row.added_at,
13
+ lastSeenAt: row.last_seen_at
14
+ };
15
+ }
16
+
17
+ export const sshKnownHostQueries = {
18
+ list(): SshKnownHost[] {
19
+ const db = getDatabase();
20
+ const rows = db.prepare(`
21
+ SELECT * FROM ssh_known_hosts ORDER BY host ASC, port ASC
22
+ `).all() as DBSshKnownHostRow[];
23
+ return rows.map(rowToKnownHost);
24
+ },
25
+
26
+ find(host: string, port: number): SshKnownHost | null {
27
+ const db = getDatabase();
28
+ const row = db.prepare(`
29
+ SELECT * FROM ssh_known_hosts WHERE host = ? AND port = ?
30
+ `).get(host, port) as DBSshKnownHostRow | null;
31
+ return row ? rowToKnownHost(row) : null;
32
+ },
33
+
34
+ /**
35
+ * Record the key a host presented, replacing any previous one. Used both for
36
+ * trust-on-first-use and for an explicit "trust the new key" after a change.
37
+ */
38
+ trust(host: string, port: number, keyType: string, fingerprint: string): SshKnownHost {
39
+ const db = getDatabase();
40
+ const now = new Date().toISOString();
41
+ db.prepare(`
42
+ INSERT INTO ssh_known_hosts (id, host, port, key_type, fingerprint, added_at, last_seen_at)
43
+ VALUES (?, ?, ?, ?, ?, ?, ?)
44
+ ON CONFLICT (host, port) DO UPDATE SET
45
+ key_type = excluded.key_type,
46
+ fingerprint = excluded.fingerprint,
47
+ added_at = excluded.added_at,
48
+ last_seen_at = excluded.last_seen_at
49
+ `).run(crypto.randomUUID(), host, port, keyType, fingerprint, now, now);
50
+
51
+ const saved = this.find(host, port);
52
+ if (!saved) throw new Error('Failed to record host key');
53
+ return saved;
54
+ },
55
+
56
+ markSeen(host: string, port: number): void {
57
+ const db = getDatabase();
58
+ db.prepare(`
59
+ UPDATE ssh_known_hosts SET last_seen_at = ? WHERE host = ? AND port = ?
60
+ `).run(new Date().toISOString(), host, port);
61
+ },
62
+
63
+ forget(host: string, port: number): void {
64
+ const db = getDatabase();
65
+ db.prepare('DELETE FROM ssh_known_hosts WHERE host = ? AND port = ?').run(host, port);
66
+ }
67
+ };
@@ -0,0 +1,113 @@
1
+ import { getDatabase } from '../index';
2
+ import type { DBSshPortForwardRow } from '$shared/types/database/schema';
3
+ import type { SshForward, SshForwardInput, SshForwardType } from '$shared/types/ssh';
4
+
5
+ function rowToForward(row: DBSshPortForwardRow): SshForward {
6
+ return {
7
+ id: row.id,
8
+ connectionId: row.connection_id,
9
+ name: row.name,
10
+ type: row.type as SshForwardType,
11
+ listenHost: row.listen_host,
12
+ listenPort: row.listen_port,
13
+ destHost: row.dest_host,
14
+ destPort: row.dest_port,
15
+ autoStart: row.auto_start === 1,
16
+ createdAt: row.created_at,
17
+ updatedAt: row.updated_at
18
+ };
19
+ }
20
+
21
+ function getRowById(id: string): DBSshPortForwardRow | null {
22
+ const db = getDatabase();
23
+ return db.prepare('SELECT * FROM ssh_port_forwards WHERE id = ?').get(id) as DBSshPortForwardRow | null;
24
+ }
25
+
26
+ export const sshPortForwardQueries = {
27
+ listForConnection(connectionId: string): SshForward[] {
28
+ const db = getDatabase();
29
+ const rows = db.prepare(`
30
+ SELECT * FROM ssh_port_forwards WHERE connection_id = ? ORDER BY created_at ASC
31
+ `).all(connectionId) as DBSshPortForwardRow[];
32
+ return rows.map(rowToForward);
33
+ },
34
+
35
+ get(id: string): SshForward | null {
36
+ const row = getRowById(id);
37
+ return row ? rowToForward(row) : null;
38
+ },
39
+
40
+ create(connectionId: string, input: SshForwardInput): SshForward {
41
+ const db = getDatabase();
42
+ const id = crypto.randomUUID();
43
+ const now = new Date().toISOString();
44
+
45
+ db.prepare(`
46
+ INSERT INTO ssh_port_forwards (
47
+ id, connection_id, name, type,
48
+ listen_host, listen_port, dest_host, dest_port,
49
+ auto_start, created_at, updated_at
50
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
51
+ `).run(
52
+ id,
53
+ connectionId,
54
+ input.name,
55
+ input.type,
56
+ input.listenHost || '127.0.0.1',
57
+ input.listenPort,
58
+ input.type === 'dynamic' ? null : (input.destHost || null),
59
+ input.type === 'dynamic' ? null : (input.destPort ?? null),
60
+ input.autoStart ? 1 : 0,
61
+ now,
62
+ now
63
+ );
64
+
65
+ const created = this.get(id);
66
+ if (!created) throw new Error('ssh port forward not found');
67
+ return created;
68
+ },
69
+
70
+ update(id: string, patch: Partial<SshForwardInput>): SshForward {
71
+ const db = getDatabase();
72
+ const existing = getRowById(id);
73
+ if (!existing) throw new Error('ssh port forward not found');
74
+
75
+ const sets: string[] = [];
76
+ const values: unknown[] = [];
77
+ const push = (column: string, value: unknown): void => {
78
+ sets.push(`${column} = ?`);
79
+ values.push(value);
80
+ };
81
+
82
+ const type = (patch.type ?? existing.type) as SshForwardType;
83
+
84
+ if (patch.name !== undefined) push('name', patch.name);
85
+ if (patch.type !== undefined) push('type', patch.type);
86
+ if (patch.listenHost !== undefined) push('listen_host', patch.listenHost || '127.0.0.1');
87
+ if (patch.listenPort !== undefined) push('listen_port', patch.listenPort);
88
+ // A dynamic forward has no fixed destination; clear it so a type switch
89
+ // never leaves a stale host:port behind.
90
+ if (type === 'dynamic') {
91
+ push('dest_host', null);
92
+ push('dest_port', null);
93
+ } else {
94
+ if (patch.destHost !== undefined) push('dest_host', patch.destHost || null);
95
+ if (patch.destPort !== undefined) push('dest_port', patch.destPort ?? null);
96
+ }
97
+ if (patch.autoStart !== undefined) push('auto_start', patch.autoStart ? 1 : 0);
98
+
99
+ push('updated_at', new Date().toISOString());
100
+
101
+ values.push(id);
102
+ db.prepare(`UPDATE ssh_port_forwards SET ${sets.join(', ')} WHERE id = ?`).run(...values);
103
+
104
+ const updated = this.get(id);
105
+ if (!updated) throw new Error('ssh port forward not found');
106
+ return updated;
107
+ },
108
+
109
+ delete(id: string): void {
110
+ const db = getDatabase();
111
+ db.prepare('DELETE FROM ssh_port_forwards WHERE id = ?').run(id);
112
+ }
113
+ };
@@ -8,6 +8,7 @@
8
8
 
9
9
  import { dbClientConnectionQueries } from '../database/queries';
10
10
  import { openSshTunnel, type SshTunnel } from './ssh-tunnel';
11
+ import { openTunnelViaSavedConnection } from '../ssh/tunnel';
11
12
  import { MysqlAdapter } from './drivers/mysql';
12
13
  import { PostgresAdapter } from './drivers/postgres';
13
14
  import { SqliteAdapter } from './drivers/sqlite';
@@ -39,6 +40,19 @@ class ConnectionManager {
39
40
  private entries = new Map<string, ConnectionEntry>();
40
41
  private sweeperHandle: ReturnType<typeof setInterval> | null = null;
41
42
 
43
+ /**
44
+ * Local ports currently held open by SSH tunnels, for the port manager.
45
+ * These are ephemeral ports nobody asked for by number, so without this the
46
+ * panel would show them as an unexplained listener owned by Clopen itself.
47
+ */
48
+ activeTunnelPorts(): Array<{ connectionId: string; localPort: number }> {
49
+ const ports: Array<{ connectionId: string; localPort: number }> = [];
50
+ for (const [connectionId, entry] of this.entries) {
51
+ if (entry.tunnel) ports.push({ connectionId, localPort: entry.tunnel.localPort });
52
+ }
53
+ return ports;
54
+ }
55
+
42
56
  private startSweeper(): void {
43
57
  if (this.sweeperHandle) return;
44
58
  this.sweeperHandle = setInterval(() => {
@@ -72,7 +86,12 @@ class ConnectionManager {
72
86
  if (conn.ssh.enabled && conn.driver !== 'sqlite') {
73
87
  const remoteHost = conn.host || '127.0.0.1';
74
88
  const remotePort = conn.port ?? defaultPortFor(conn.driver);
75
- tunnel = await openSshTunnel(conn.ssh, remoteHost, remotePort);
89
+ // Two modes: a saved SSH host from the SSH client (shared credentials,
90
+ // jump chain and trusted host key), or the credentials stored inline on
91
+ // this connection. The inline path is what every existing connection uses.
92
+ tunnel = conn.ssh.connectionId
93
+ ? await openTunnelViaSavedConnection(conn.ssh.connectionId, remoteHost, remotePort)
94
+ : await openSshTunnel(conn.ssh, remoteHost, remotePort);
76
95
  }
77
96
 
78
97
  try {
@@ -250,6 +269,7 @@ function inputToConnection(input: DbClientConnectionInput): DbClientConnection {
250
269
  sslCa: input.sslCa ?? null,
251
270
  ssh: {
252
271
  enabled: input.ssh?.enabled ?? false,
272
+ connectionId: input.ssh?.connectionId ?? null,
253
273
  host: input.ssh?.host ?? '',
254
274
  port: input.ssh?.port ?? 22,
255
275
  username: input.ssh?.username ?? '',
@@ -77,7 +77,7 @@ import type {
77
77
  } from '@openai/codex-sdk';
78
78
  import { resolveOpenCodeToolName } from '../../../mcp';
79
79
  import { readLastTokenUsageFromRollout } from './usage-rollout';
80
- import { readApplyPatchesFromRollout, findMatchingPatch } from './patch-rollout';
80
+ import { readFileChangeSetsFromRollout, findMatchingFileChangeSet } from './patch-rollout';
81
81
 
82
82
  // ============================================================================
83
83
  // Engine Identity
@@ -469,29 +469,35 @@ function buildFileChangePair(item: FileChangeItem, state: CodexStreamState): Eng
469
469
  const baseId = item.id;
470
470
  const isFailed = item.status === 'failed';
471
471
 
472
- // SDK doesn't carry diff content on FileUpdateChange — pull it from the
473
- // rollout JSONL's apply_patch envelope so Edit blocks render real before/
474
- // after text. Falls back to empty strings if the rollout isn't readable.
475
- const updatePaths = item.changes.filter(c => c.kind === 'update').map(c => c.path);
476
- const matchedPatch = updatePaths.length > 0
477
- ? findMatchingPatch(readApplyPatchesFromRollout(state.sessionId), updatePaths)
478
- : null;
472
+ // SDK doesn't carry file content on FileUpdateChange — pull it from the
473
+ // rollout JSONL's `patch_apply_end` event so Edit blocks render the real
474
+ // before/after text and Write blocks the real file body. Falls back to
475
+ // empty strings if the rollout isn't readable.
476
+ const changedPaths = item.changes.map(change => change.path);
477
+ const matchedChangeSet = findMatchingFileChangeSet(
478
+ readFileChangeSetsFromRollout(state.sessionId),
479
+ changedPaths,
480
+ );
479
481
 
480
482
  item.changes.forEach((change, idx) => {
481
483
  const toolId = `${baseId}:${idx}`;
482
484
  let toolName: string;
483
485
  let input: Record<string, unknown>;
484
486
 
487
+ const recovered = matchedChangeSet?.get(change.path);
488
+
485
489
  if (change.kind === 'add') {
486
490
  toolName = 'Write';
487
- input = { filePath: change.path, content: '' } satisfies WriteInput as unknown as Record<string, unknown>;
491
+ input = {
492
+ filePath: change.path,
493
+ content: recovered?.content ?? '',
494
+ } satisfies WriteInput as unknown as Record<string, unknown>;
488
495
  } else if (change.kind === 'update') {
489
496
  toolName = 'Edit';
490
- const diff = matchedPatch?.get(change.path);
491
497
  input = {
492
498
  filePath: change.path,
493
- oldString: diff?.oldString ?? '',
494
- newString: diff?.newString ?? '',
499
+ oldString: recovered?.oldString ?? '',
500
+ newString: recovered?.newString ?? '',
495
501
  } satisfies EditInput as unknown as Record<string, unknown>;
496
502
  } else {
497
503
  // delete → no canonical UI; map to Bash `rm <path>` so the user
@@ -0,0 +1,88 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import type { FileChangeSet } from './patch-rollout';
3
+ import { parseUnifiedDiff, findMatchingFileChangeSet } from './patch-rollout';
4
+
5
+ describe('parseUnifiedDiff', () => {
6
+ test('splits a single hunk into before/after text', () => {
7
+ const diff = [
8
+ '@@ -1,4 +1,4 @@',
9
+ ' :root {',
10
+ '- --accent: #1d4ed8;',
11
+ '+ --accent: #7c3aed;',
12
+ ' }',
13
+ ''
14
+ ].join('\n');
15
+
16
+ expect(parseUnifiedDiff(diff)).toEqual({
17
+ oldString: ':root {\n --accent: #1d4ed8;\n}\n',
18
+ newString: ':root {\n --accent: #7c3aed;\n}\n'
19
+ });
20
+ });
21
+
22
+ test('concatenates every hunk so the Edit block shows all changes', () => {
23
+ const diff = [
24
+ '@@ -1,2 +1,2 @@',
25
+ '-first old',
26
+ '+first new',
27
+ ' shared',
28
+ '@@ -9,2 +9,2 @@',
29
+ '-second old',
30
+ '+second new',
31
+ ''
32
+ ].join('\n');
33
+
34
+ const { oldString, newString } = parseUnifiedDiff(diff);
35
+ expect(oldString).toBe('first old\nshared\nsecond old\n');
36
+ expect(newString).toBe('first new\nshared\nsecond new\n');
37
+ });
38
+
39
+ test('ignores headers before the first hunk but keeps dashes inside one', () => {
40
+ const diff = [
41
+ '--- a/notes.md',
42
+ '+++ b/notes.md',
43
+ '@@ -1,2 +1,2 @@',
44
+ '---',
45
+ '+++',
46
+ ''
47
+ ].join('\n');
48
+
49
+ // Inside a hunk `---` is a removed line whose text is `--`, and `+++`
50
+ // an added line whose text is `++` — not file headers.
51
+ expect(parseUnifiedDiff(diff)).toEqual({ oldString: '--\n', newString: '++\n' });
52
+ });
53
+
54
+ test('drops the no-newline annotation', () => {
55
+ const diff = ['@@ -1 +1 @@', '-old', '\', '+new'].join('\n');
56
+ expect(parseUnifiedDiff(diff)).toEqual({ oldString: 'old', newString: 'new' });
57
+ });
58
+
59
+ test('returns empty strings for an empty diff', () => {
60
+ expect(parseUnifiedDiff('')).toEqual({ oldString: '', newString: '' });
61
+ });
62
+ });
63
+
64
+ describe('findMatchingFileChangeSet', () => {
65
+ const changeSetFor = (...paths: string[]): FileChangeSet =>
66
+ new Map(paths.map(path => [path, { kind: 'update' as const, oldString: path, newString: path, content: '' }]));
67
+
68
+ test('prefers the newest change set that covers every wanted path', () => {
69
+ const older = changeSetFor('/repo/a.ts');
70
+ const newer = changeSetFor('/repo/a.ts', '/repo/b.ts');
71
+
72
+ expect(findMatchingFileChangeSet([older, newer], ['/repo/a.ts'])).toBe(newer);
73
+ expect(findMatchingFileChangeSet([older, newer], ['/repo/a.ts', '/repo/b.ts'])).toBe(newer);
74
+ });
75
+
76
+ test('skips change sets that miss one of the wanted paths', () => {
77
+ const matching = changeSetFor('/repo/a.ts', '/repo/b.ts');
78
+ const partial = changeSetFor('/repo/a.ts');
79
+
80
+ expect(findMatchingFileChangeSet([matching, partial], ['/repo/a.ts', '/repo/b.ts'])).toBe(matching);
81
+ });
82
+
83
+ test('returns null when nothing matches or nothing is wanted', () => {
84
+ expect(findMatchingFileChangeSet([changeSetFor('/repo/a.ts')], ['/repo/c.ts'])).toBeNull();
85
+ expect(findMatchingFileChangeSet([changeSetFor('/repo/a.ts')], [])).toBeNull();
86
+ expect(findMatchingFileChangeSet([], ['/repo/a.ts'])).toBeNull();
87
+ });
88
+ });