@myrialabs/clopen 0.3.8 → 0.3.10

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 (146) hide show
  1. package/README.md +22 -19
  2. package/backend/auth/auth-service.ts +56 -1
  3. package/backend/auth/permissions.ts +66 -2
  4. package/backend/auth/session-cleanup.ts +58 -0
  5. package/backend/chat/stream-manager.ts +143 -13
  6. package/backend/database/migrations/032_seed_copilot_provider.ts +19 -0
  7. package/backend/database/migrations/033_seed_codex_provider.ts +19 -0
  8. package/backend/database/migrations/034_seed_qwen_provider.ts +119 -0
  9. package/backend/database/migrations/035_add_owner_to_db_client_connections.ts +34 -0
  10. package/backend/database/migrations/index.ts +29 -1
  11. package/backend/database/queries/db-client-connection-queries.ts +160 -54
  12. package/backend/database/queries/engine-queries.ts +12 -0
  13. package/backend/database/queries/project-queries.ts +10 -5
  14. package/backend/db-client/connection-manager.ts +9 -3
  15. package/backend/engine/README.md +1702 -0
  16. package/backend/engine/adapters/claude/models.ts +141 -0
  17. package/backend/engine/adapters/claude/stream.ts +1 -1
  18. package/backend/engine/adapters/codex/credential.ts +179 -0
  19. package/backend/engine/adapters/codex/error-handler.ts +65 -0
  20. package/backend/engine/adapters/codex/index.ts +1 -0
  21. package/backend/engine/adapters/codex/message-converter.ts +646 -0
  22. package/backend/engine/adapters/codex/models.ts +105 -0
  23. package/backend/engine/adapters/codex/patch-rollout.ts +169 -0
  24. package/backend/engine/adapters/codex/session-fork.ts +149 -0
  25. package/backend/engine/adapters/codex/stream.ts +310 -0
  26. package/backend/engine/adapters/codex/usage-rollout.ts +145 -0
  27. package/backend/engine/adapters/copilot/error-handler.ts +94 -0
  28. package/backend/engine/adapters/copilot/index.ts +1 -0
  29. package/backend/engine/adapters/copilot/message-converter.ts +973 -0
  30. package/backend/engine/adapters/copilot/models.ts +92 -0
  31. package/backend/engine/adapters/copilot/session-fork.ts +111 -0
  32. package/backend/engine/adapters/copilot/stream.ts +570 -0
  33. package/backend/engine/adapters/opencode/config.ts +56 -104
  34. package/backend/engine/adapters/opencode/error-handler.ts +71 -0
  35. package/backend/engine/adapters/opencode/models.ts +79 -0
  36. package/backend/engine/adapters/opencode/presets.ts +91 -0
  37. package/backend/engine/adapters/opencode/stream.ts +8 -114
  38. package/backend/engine/adapters/qwen/credential.ts +78 -0
  39. package/backend/engine/adapters/qwen/environment.ts +84 -0
  40. package/backend/engine/adapters/qwen/error-handler.ts +71 -0
  41. package/backend/engine/adapters/qwen/index.ts +1 -0
  42. package/backend/engine/adapters/qwen/message-converter.ts +1055 -0
  43. package/backend/engine/adapters/qwen/models.ts +81 -0
  44. package/backend/engine/adapters/qwen/presets.ts +51 -0
  45. package/backend/engine/adapters/qwen/session-fork.ts +97 -0
  46. package/backend/engine/adapters/qwen/stream.ts +379 -0
  47. package/backend/engine/index.ts +35 -0
  48. package/backend/engine/install-recipes.ts +80 -1
  49. package/backend/engine/install-runner.ts +4 -0
  50. package/backend/files/path-browsing.ts +20 -0
  51. package/backend/git/git-service.ts +81 -11
  52. package/backend/git/git-spawn-validation.test.ts +75 -0
  53. package/backend/git/git-spawn-validation.ts +77 -0
  54. package/backend/index.ts +5 -0
  55. package/backend/mcp/README.md +84 -14
  56. package/backend/mcp/config.ts +218 -17
  57. package/backend/mcp/index.ts +2 -0
  58. package/backend/mcp/project-context.ts +55 -0
  59. package/backend/mcp/servers/browser-automation/actions.ts +6 -1
  60. package/backend/mcp/servers/helper.ts +13 -0
  61. package/backend/middleware/error-handler.ts +16 -2
  62. package/backend/preview/browser/browser-preview-service.ts +4 -4
  63. package/backend/preview/browser/browser-tab-manager.ts +23 -3
  64. package/backend/snapshot/gitignore.ts +4 -9
  65. package/backend/tunnel/cloudflared/binary.ts +2 -2
  66. package/backend/tunnel/global-tunnel-manager.ts +9 -3
  67. package/backend/utils/ws.ts +5 -1
  68. package/backend/ws/README.md +128 -3
  69. package/backend/ws/access.ts +56 -0
  70. package/backend/ws/auth/index.ts +14 -0
  71. package/backend/ws/auth/login.ts +3 -0
  72. package/backend/ws/auth/users.ts +61 -1
  73. package/backend/ws/chat/stream.ts +139 -22
  74. package/backend/ws/db-client/access.ts +19 -0
  75. package/backend/ws/db-client/connections.ts +31 -17
  76. package/backend/ws/db-client/io.ts +7 -9
  77. package/backend/ws/db-client/query.ts +86 -32
  78. package/backend/ws/db-client/schema.ts +9 -4
  79. package/backend/ws/db-client/structure.ts +22 -10
  80. package/backend/ws/engine/access.ts +39 -0
  81. package/backend/ws/engine/claude/accounts.ts +15 -10
  82. package/backend/ws/engine/codex/accounts.ts +516 -0
  83. package/backend/ws/engine/codex/index.ts +14 -0
  84. package/backend/ws/engine/codex/status.ts +87 -0
  85. package/backend/ws/engine/copilot/accounts.ts +122 -0
  86. package/backend/ws/engine/copilot/index.ts +13 -0
  87. package/backend/ws/engine/copilot/status.ts +54 -0
  88. package/backend/ws/engine/index.ts +7 -1
  89. package/backend/ws/engine/opencode/providers.ts +1 -1
  90. package/backend/ws/engine/qwen/accounts.ts +137 -0
  91. package/backend/ws/engine/qwen/index.ts +15 -0
  92. package/backend/ws/engine/qwen/presets.ts +40 -0
  93. package/backend/ws/engine/qwen/status.ts +54 -0
  94. package/backend/ws/files/path-access.ts +101 -0
  95. package/backend/ws/files/read.ts +26 -11
  96. package/backend/ws/files/search.ts +10 -6
  97. package/backend/ws/files/state.ts +3 -0
  98. package/backend/ws/files/watch.ts +7 -1
  99. package/backend/ws/files/write.ts +109 -15
  100. package/backend/ws/git/branch.ts +13 -19
  101. package/backend/ws/git/commit-message.ts +3 -4
  102. package/backend/ws/git/commit.ts +5 -7
  103. package/backend/ws/git/conflict.ts +7 -10
  104. package/backend/ws/git/diff.ts +7 -10
  105. package/backend/ws/git/log.ts +3 -4
  106. package/backend/ws/git/remote.ts +30 -43
  107. package/backend/ws/git/staging.ts +13 -19
  108. package/backend/ws/git/status.ts +7 -11
  109. package/backend/ws/messages/crud.ts +7 -13
  110. package/backend/ws/preview/access.ts +45 -0
  111. package/backend/ws/preview/browser/cleanup.ts +3 -11
  112. package/backend/ws/preview/browser/console.ts +7 -42
  113. package/backend/ws/preview/browser/interact.ts +2 -6
  114. package/backend/ws/preview/browser/native-ui.ts +5 -18
  115. package/backend/ws/preview/browser/stats.ts +2 -12
  116. package/backend/ws/preview/browser/tab-info.ts +4 -20
  117. package/backend/ws/preview/browser/tab.ts +4 -27
  118. package/backend/ws/preview/browser/webcodecs.ts +6 -47
  119. package/backend/ws/projects/crud.ts +15 -16
  120. package/backend/ws/projects/status.ts +5 -1
  121. package/backend/ws/sessions/crud.ts +31 -36
  122. package/backend/ws/settings/crud.ts +13 -13
  123. package/backend/ws/snapshot/restore.ts +5 -2
  124. package/backend/ws/snapshot/timeline.ts +3 -1
  125. package/backend/ws/system-tools/access.ts +28 -0
  126. package/backend/ws/system-tools/install.ts +13 -4
  127. package/backend/ws/system-tools/status.ts +5 -2
  128. package/backend/ws/terminal/access.ts +56 -0
  129. package/backend/ws/terminal/persistence.ts +13 -7
  130. package/backend/ws/terminal/session.ts +35 -14
  131. package/backend/ws/terminal/stream.ts +4 -1
  132. package/dist/assets/{index-DqAGCTFT.js → index-C1afGwHY.js} +2 -2
  133. package/dist/assets/main-CZb3Y_Z_.js +315 -0
  134. package/dist/assets/main-Cn8cX2DY.css +1 -0
  135. package/dist/index.html +2 -2
  136. package/package.json +5 -1
  137. package/shared/constants/engines.ts +45 -140
  138. package/shared/types/database/schema.ts +1 -0
  139. package/shared/types/unified/common.ts +1 -1
  140. package/shared/types/unified/engine.ts +29 -1
  141. package/shared/types/unified/index.ts +2 -0
  142. package/shared/types/unified/message.ts +1 -1
  143. package/shared/types/unified/tool.ts +17 -2
  144. package/shared/utils/ws-server.ts +14 -0
  145. package/dist/assets/main-DsED0rLr.js +0 -304
  146. package/dist/assets/main-eWY9R8g9.css +0 -1
@@ -0,0 +1,119 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description =
5
+ 'Seed Qwen Code provider and store credentials as JSON with per-account preset/baseUrl';
6
+
7
+ interface ProviderRow {
8
+ id: number;
9
+ options: string | null;
10
+ }
11
+
12
+ interface AccountRow {
13
+ id: number;
14
+ credential: string | null;
15
+ }
16
+
17
+ const DEFAULT_PRESET = 'dashscope-intl';
18
+ const DASHSCOPE_INTL = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1';
19
+ const DASHSCOPE_CN = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
20
+ const OPENROUTER = 'https://openrouter.ai/api/v1';
21
+ const FIREWORKS = 'https://api.fireworks.ai/inference/v1';
22
+
23
+ function presetFromBaseUrl(baseUrl: string | null | undefined): string {
24
+ if (!baseUrl) return DEFAULT_PRESET;
25
+ const lower = baseUrl.toLowerCase();
26
+ if (lower.startsWith(DASHSCOPE_INTL.toLowerCase())) return 'dashscope-intl';
27
+ if (lower.startsWith(DASHSCOPE_CN.toLowerCase())) return 'dashscope-cn';
28
+ if (lower.startsWith(OPENROUTER.toLowerCase())) return 'openrouter';
29
+ if (lower.startsWith(FIREWORKS.toLowerCase())) return 'fireworks';
30
+ return 'custom';
31
+ }
32
+
33
+ export const up = (db: DatabaseConnection): void => {
34
+ debug.log('migration', 'Seeding Qwen Code provider...');
35
+ db.exec(`
36
+ INSERT OR IGNORE INTO engine_providers (engine_type, slug, name, npm, api_url, options, is_enabled)
37
+ VALUES ('qwen', 'qwen', 'Qwen', NULL, NULL, '{}', 1)
38
+ `);
39
+ debug.log('migration', 'Qwen Code provider seeded');
40
+
41
+ debug.log('migration', 'Migrating Qwen credentials to JSON form...');
42
+
43
+ const providers = db.prepare(
44
+ `SELECT id, options FROM engine_providers WHERE engine_type = 'qwen'`
45
+ ).all() as ProviderRow[];
46
+
47
+ for (const provider of providers) {
48
+ // Pull the previous provider-level baseUrl (if any) so we can fold it
49
+ // into each account's credential JSON.
50
+ let providerBaseUrl: string | undefined;
51
+ try {
52
+ const opts = JSON.parse(provider.options || '{}') as { baseUrl?: unknown };
53
+ if (typeof opts.baseUrl === 'string' && opts.baseUrl.trim().length > 0) {
54
+ providerBaseUrl = opts.baseUrl.trim();
55
+ }
56
+ } catch {
57
+ /* malformed options — treat as no baseUrl */
58
+ }
59
+
60
+ const preset = presetFromBaseUrl(providerBaseUrl);
61
+
62
+ const accounts = db.prepare(
63
+ `SELECT id, credential FROM engine_accounts WHERE provider_id = ?`
64
+ ).all(provider.id) as AccountRow[];
65
+
66
+ for (const account of accounts) {
67
+ const raw = (account.credential ?? '').trim();
68
+ // Skip accounts that already store JSON (idempotent re-run safety).
69
+ if (raw.startsWith('{')) continue;
70
+
71
+ const json: Record<string, unknown> = { apiKey: raw, preset };
72
+ if (providerBaseUrl) json.baseUrl = providerBaseUrl;
73
+
74
+ db.prepare(`UPDATE engine_accounts SET credential = ? WHERE id = ?`).run(
75
+ JSON.stringify(json),
76
+ account.id,
77
+ );
78
+ }
79
+
80
+ // Clear the provider-level baseUrl now that it's per-account.
81
+ if (providerBaseUrl !== undefined) {
82
+ db.prepare(`UPDATE engine_providers SET options = ? WHERE id = ?`).run('{}', provider.id);
83
+ }
84
+ }
85
+
86
+ debug.log('migration', 'Qwen credentials migrated to JSON form');
87
+ };
88
+
89
+ export const down = (db: DatabaseConnection): void => {
90
+ // Best-effort reverse: extract `apiKey` from the JSON blob and write it
91
+ // back as a raw string before removing the provider.
92
+ debug.log('migration', 'Reverting Qwen credentials to raw API key strings...');
93
+
94
+ const providers = db.prepare(
95
+ `SELECT id, options FROM engine_providers WHERE engine_type = 'qwen'`
96
+ ).all() as ProviderRow[];
97
+
98
+ for (const provider of providers) {
99
+ const accounts = db.prepare(
100
+ `SELECT id, credential FROM engine_accounts WHERE provider_id = ?`
101
+ ).all(provider.id) as AccountRow[];
102
+
103
+ for (const account of accounts) {
104
+ const raw = (account.credential ?? '').trim();
105
+ if (!raw.startsWith('{')) continue;
106
+ try {
107
+ const parsed = JSON.parse(raw) as { apiKey?: unknown };
108
+ const apiKey = typeof parsed.apiKey === 'string' ? parsed.apiKey : '';
109
+ db.prepare(`UPDATE engine_accounts SET credential = ? WHERE id = ?`).run(apiKey, account.id);
110
+ } catch {
111
+ /* leave malformed entries alone */
112
+ }
113
+ }
114
+ }
115
+
116
+ debug.log('migration', 'Removing Qwen Code provider...');
117
+ db.exec(`DELETE FROM engine_providers WHERE engine_type = 'qwen' AND slug = 'qwen'`);
118
+ debug.log('migration', 'Qwen Code provider removed');
119
+ };
@@ -0,0 +1,34 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Add owner_user_id to db_client_connections table';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Adding owner_user_id to db_client_connections...');
8
+
9
+ // SQLite does not support IF NOT EXISTS for ADD COLUMN, so we ignore duplicate-column errors.
10
+ try {
11
+ db.exec(`
12
+ ALTER TABLE db_client_connections
13
+ ADD COLUMN owner_user_id TEXT
14
+ `);
15
+ } catch (error) {
16
+ const message = error instanceof Error ? error.message : String(error);
17
+ if (!message.toLowerCase().includes('duplicate column name')) {
18
+ throw error;
19
+ }
20
+ }
21
+
22
+ db.exec(`
23
+ CREATE INDEX IF NOT EXISTS idx_db_client_conn_owner
24
+ ON db_client_connections(owner_user_id)
25
+ `);
26
+
27
+ debug.log('migration', 'owner_user_id migration completed');
28
+ };
29
+
30
+ export const down = (db: DatabaseConnection): void => {
31
+ // SQLite cannot drop columns without table rebuild; keep rollback non-destructive.
32
+ debug.log('migration', 'Dropping idx_db_client_conn_owner index...');
33
+ db.exec('DROP INDEX IF EXISTS idx_db_client_conn_owner');
34
+ };
@@ -30,6 +30,10 @@ import * as migration028 from './028_create_opencode_accounts_table';
30
30
  import * as migration029 from './029_migrate_messages_to_unified';
31
31
  import * as migration030 from './030_add_files_panel_state_to_user_projects';
32
32
  import * as migration031 from './031_create_db_client_tables';
33
+ import * as migration032 from './032_seed_copilot_provider';
34
+ import * as migration033 from './033_seed_codex_provider';
35
+ import * as migration034 from './034_seed_qwen_provider';
36
+ import * as migration035 from './035_add_owner_to_db_client_connections';
33
37
 
34
38
  // Export all migrations in order
35
39
  export const migrations = [
@@ -218,7 +222,31 @@ export const migrations = [
218
222
  description: migration031.description,
219
223
  up: migration031.up,
220
224
  down: migration031.down
225
+ },
226
+ {
227
+ id: '032',
228
+ description: migration032.description,
229
+ up: migration032.up,
230
+ down: migration032.down
231
+ },
232
+ {
233
+ id: '033',
234
+ description: migration033.description,
235
+ up: migration033.up,
236
+ down: migration033.down
237
+ },
238
+ {
239
+ id: '034',
240
+ description: migration034.description,
241
+ up: migration034.up,
242
+ down: migration034.down
243
+ },
244
+ {
245
+ id: '035',
246
+ description: migration035.description,
247
+ up: migration035.up,
248
+ down: migration035.down
221
249
  }
222
250
  ];
223
251
 
224
- export default migrations;
252
+ export default migrations;
@@ -64,6 +64,36 @@ function rowToConnection(row: DBDbClientConnectionRow): DbClientConnection {
64
64
  };
65
65
  }
66
66
 
67
+ function redactConnectionSecrets(connection: DbClientConnection): DbClientConnection {
68
+ return {
69
+ ...connection,
70
+ password: null,
71
+ ssh: {
72
+ ...connection.ssh,
73
+ password: undefined,
74
+ privateKey: undefined,
75
+ passphrase: undefined
76
+ }
77
+ };
78
+ }
79
+
80
+ function hasConnectionAccess(
81
+ row: DBDbClientConnectionRow,
82
+ userId: string,
83
+ isAdmin: boolean
84
+ ): boolean {
85
+ if (isAdmin) return true;
86
+ return row.owner_user_id === userId;
87
+ }
88
+
89
+ function preserveExistingSecret(
90
+ patchValue: string | undefined,
91
+ existingValue: string | null
92
+ ): string | null {
93
+ if (patchValue === undefined || patchValue === '') return existingValue;
94
+ return patchValue;
95
+ }
96
+
67
97
  interface InsertParams {
68
98
  name: string;
69
99
  driver: DbDriver;
@@ -77,9 +107,10 @@ interface InsertParams {
77
107
  ssh: DbClientSshConfig;
78
108
  options: Record<string, unknown>;
79
109
  color: string | null;
110
+ ownerUserId: string | null;
80
111
  }
81
112
 
82
- function normalizeInput(input: DbClientConnectionInput): InsertParams {
113
+ function normalizeInput(input: DbClientConnectionInput, ownerUserId: string | null): InsertParams {
83
114
  const ssh: DbClientSshConfig = {
84
115
  ...DEFAULT_SSH,
85
116
  ...(input.ssh ?? {})
@@ -96,11 +127,102 @@ function normalizeInput(input: DbClientConnectionInput): InsertParams {
96
127
  sslCa: input.sslCa ?? null,
97
128
  ssh,
98
129
  options: input.options ?? {},
99
- color: input.color ?? null
130
+ color: input.color ?? null,
131
+ ownerUserId
100
132
  };
101
133
  }
102
134
 
135
+ function getRowById(id: string): DBDbClientConnectionRow | null {
136
+ const db = getDatabase();
137
+ return db.prepare(`
138
+ SELECT * FROM db_client_connections WHERE id = ?
139
+ `).get(id) as DBDbClientConnectionRow | null;
140
+ }
141
+
142
+ function insertConnection(input: DbClientConnectionInput, ownerUserId: string | null): DbClientConnection {
143
+ const db = getDatabase();
144
+ const id = crypto.randomUUID();
145
+ const now = new Date().toISOString();
146
+ const params = normalizeInput(input, ownerUserId);
147
+
148
+ db.prepare(`
149
+ INSERT INTO db_client_connections (
150
+ id, name, driver,
151
+ host, port, username, password, database,
152
+ ssl_mode, ssl_ca,
153
+ ssh_enabled, ssh_host, ssh_port, ssh_username, ssh_auth_method,
154
+ ssh_password, ssh_private_key, ssh_passphrase,
155
+ options_json, color,
156
+ owner_user_id,
157
+ created_at, updated_at, last_used_at
158
+ ) VALUES (
159
+ ?, ?, ?,
160
+ ?, ?, ?, ?, ?,
161
+ ?, ?,
162
+ ?, ?, ?, ?, ?,
163
+ ?, ?, ?,
164
+ ?, ?,
165
+ ?,
166
+ ?, ?, ?
167
+ )
168
+ `).run(
169
+ id, params.name, params.driver,
170
+ params.host, params.port, params.username, params.password, params.database,
171
+ params.sslMode, params.sslCa,
172
+ params.ssh.enabled ? 1 : 0,
173
+ params.ssh.host || null,
174
+ params.ssh.port,
175
+ params.ssh.username || null,
176
+ params.ssh.authMethod,
177
+ params.ssh.password || null,
178
+ params.ssh.privateKey || null,
179
+ params.ssh.passphrase || null,
180
+ JSON.stringify(params.options),
181
+ params.color,
182
+ params.ownerUserId,
183
+ now, now, null
184
+ );
185
+
186
+ const row = getRowById(id);
187
+ if (!row) {
188
+ throw new Error('db-client connection not found');
189
+ }
190
+ return rowToConnection(row);
191
+ }
192
+
103
193
  export const dbClientConnectionQueries = {
194
+ listForUser(userId: string, isAdmin: boolean): DbClientConnection[] {
195
+ const db = getDatabase();
196
+ const rows = (isAdmin
197
+ ? db.prepare(`
198
+ SELECT * FROM db_client_connections
199
+ ORDER BY (last_used_at IS NULL), last_used_at DESC, created_at DESC
200
+ `).all()
201
+ : db.prepare(`
202
+ SELECT * FROM db_client_connections
203
+ WHERE owner_user_id = ?
204
+ ORDER BY (last_used_at IS NULL), last_used_at DESC, created_at DESC
205
+ `).all(userId)) as DBDbClientConnectionRow[];
206
+
207
+ return rows.map((row) => redactConnectionSecrets(rowToConnection(row)));
208
+ },
209
+
210
+ getForUser(id: string, userId: string, isAdmin: boolean): DbClientConnection | null {
211
+ const row = getRowById(id);
212
+ if (!row || !hasConnectionAccess(row, userId, isAdmin)) {
213
+ return null;
214
+ }
215
+ return redactConnectionSecrets(rowToConnection(row));
216
+ },
217
+
218
+ ensureAccess(id: string, userId: string, isAdmin: boolean): DbClientConnection {
219
+ const row = getRowById(id);
220
+ if (!row || !hasConnectionAccess(row, userId, isAdmin)) {
221
+ throw new Error('db-client connection not found');
222
+ }
223
+ return rowToConnection(row);
224
+ },
225
+
104
226
  list(): DbClientConnection[] {
105
227
  const db = getDatabase();
106
228
  const rows = db.prepare(`
@@ -111,61 +233,22 @@ export const dbClientConnectionQueries = {
111
233
  },
112
234
 
113
235
  get(id: string): DbClientConnection | null {
114
- const db = getDatabase();
115
- const row = db.prepare(`
116
- SELECT * FROM db_client_connections WHERE id = ?
117
- `).get(id) as DBDbClientConnectionRow | null;
236
+ const row = getRowById(id);
118
237
  return row ? rowToConnection(row) : null;
119
238
  },
120
239
 
121
240
  create(input: DbClientConnectionInput): DbClientConnection {
122
- const db = getDatabase();
123
- const id = crypto.randomUUID();
124
- const now = new Date().toISOString();
125
- const params = normalizeInput(input);
126
-
127
- db.prepare(`
128
- INSERT INTO db_client_connections (
129
- id, name, driver,
130
- host, port, username, password, database,
131
- ssl_mode, ssl_ca,
132
- ssh_enabled, ssh_host, ssh_port, ssh_username, ssh_auth_method,
133
- ssh_password, ssh_private_key, ssh_passphrase,
134
- options_json, color,
135
- created_at, updated_at, last_used_at
136
- ) VALUES (
137
- ?, ?, ?,
138
- ?, ?, ?, ?, ?,
139
- ?, ?,
140
- ?, ?, ?, ?, ?,
141
- ?, ?, ?,
142
- ?, ?,
143
- ?, ?, ?
144
- )
145
- `).run(
146
- id, params.name, params.driver,
147
- params.host, params.port, params.username, params.password, params.database,
148
- params.sslMode, params.sslCa,
149
- params.ssh.enabled ? 1 : 0,
150
- params.ssh.host || null,
151
- params.ssh.port,
152
- params.ssh.username || null,
153
- params.ssh.authMethod,
154
- params.ssh.password || null,
155
- params.ssh.privateKey || null,
156
- params.ssh.passphrase || null,
157
- JSON.stringify(params.options),
158
- params.color,
159
- now, now, null
160
- );
161
-
162
- const row = db.prepare('SELECT * FROM db_client_connections WHERE id = ?').get(id) as DBDbClientConnectionRow;
163
- return rowToConnection(row);
241
+ return insertConnection(input, null);
242
+ },
243
+
244
+ createForUser(input: DbClientConnectionInput, ownerUserId: string): DbClientConnection {
245
+ const connection = insertConnection(input, ownerUserId);
246
+ return redactConnectionSecrets(connection);
164
247
  },
165
248
 
166
249
  update(id: string, patch: Partial<DbClientConnectionInput>): DbClientConnection {
167
250
  const db = getDatabase();
168
- const existing = db.prepare('SELECT * FROM db_client_connections WHERE id = ?').get(id) as DBDbClientConnectionRow | null;
251
+ const existing = getRowById(id);
169
252
  if (!existing) {
170
253
  throw new Error('db-client connection not found');
171
254
  }
@@ -182,7 +265,7 @@ export const dbClientConnectionQueries = {
182
265
  if (patch.host !== undefined) push('host', patch.host || null);
183
266
  if (patch.port !== undefined) push('port', patch.port ?? null);
184
267
  if (patch.username !== undefined) push('username', patch.username || null);
185
- if (patch.password !== undefined) push('password', patch.password || null);
268
+ if (patch.password !== undefined && patch.password !== '') push('password', patch.password);
186
269
  if (patch.database !== undefined) push('database', patch.database || null);
187
270
  if (patch.sslMode !== undefined) push('ssl_mode', patch.sslMode);
188
271
  if (patch.sslCa !== undefined) push('ssl_ca', patch.sslCa || null);
@@ -201,14 +284,18 @@ export const dbClientConnectionQueries = {
201
284
  passphrase: existing.ssh_passphrase ?? '',
202
285
  ...patch.ssh
203
286
  };
287
+ const sshPassword = preserveExistingSecret(patch.ssh.password, existing.ssh_password);
288
+ const sshPrivateKey = preserveExistingSecret(patch.ssh.privateKey, existing.ssh_private_key);
289
+ const sshPassphrase = preserveExistingSecret(patch.ssh.passphrase, existing.ssh_passphrase);
290
+
204
291
  push('ssh_enabled', merged.enabled ? 1 : 0);
205
292
  push('ssh_host', merged.host || null);
206
293
  push('ssh_port', merged.port);
207
294
  push('ssh_username', merged.username || null);
208
295
  push('ssh_auth_method', merged.authMethod);
209
- push('ssh_password', merged.password || null);
210
- push('ssh_private_key', merged.privateKey || null);
211
- push('ssh_passphrase', merged.passphrase || null);
296
+ push('ssh_password', sshPassword);
297
+ push('ssh_private_key', sshPrivateKey);
298
+ push('ssh_passphrase', sshPassphrase);
212
299
  }
213
300
 
214
301
  push('updated_at', new Date().toISOString());
@@ -220,15 +307,34 @@ export const dbClientConnectionQueries = {
220
307
  values.push(id);
221
308
  db.prepare(`UPDATE db_client_connections SET ${sets.join(', ')} WHERE id = ?`).run(...values);
222
309
 
223
- const row = db.prepare('SELECT * FROM db_client_connections WHERE id = ?').get(id) as DBDbClientConnectionRow;
310
+ const row = getRowById(id);
311
+ if (!row) {
312
+ throw new Error('db-client connection not found');
313
+ }
224
314
  return rowToConnection(row);
225
315
  },
226
316
 
317
+ updateForUser(
318
+ id: string,
319
+ patch: Partial<DbClientConnectionInput>,
320
+ userId: string,
321
+ isAdmin: boolean
322
+ ): DbClientConnection {
323
+ this.ensureAccess(id, userId, isAdmin);
324
+ const updated = this.update(id, patch);
325
+ return redactConnectionSecrets(updated);
326
+ },
327
+
227
328
  delete(id: string): void {
228
329
  const db = getDatabase();
229
330
  db.prepare('DELETE FROM db_client_connections WHERE id = ?').run(id);
230
331
  },
231
332
 
333
+ deleteForUser(id: string, userId: string, isAdmin: boolean): void {
334
+ this.ensureAccess(id, userId, isAdmin);
335
+ this.delete(id);
336
+ },
337
+
232
338
  markUsed(id: string): void {
233
339
  const db = getDatabase();
234
340
  const now = new Date().toISOString();
@@ -220,6 +220,18 @@ export const engineQueries = {
220
220
  db.prepare(`UPDATE engine_accounts SET name = ? WHERE id = ?`).run(name, accountId);
221
221
  },
222
222
 
223
+ /**
224
+ * Replace the stored credential for an existing account. Used by adapters
225
+ * whose CLI mutates an external dotfile in place (e.g. Codex's
226
+ * ~/.codex/auth.json token refresh) — the adapter snapshots the file back
227
+ * into `credential` after each stream so refreshed tokens survive across
228
+ * account switches.
229
+ */
230
+ updateAccountCredential(accountId: number, credential: string): void {
231
+ const db = getDatabase();
232
+ db.prepare(`UPDATE engine_accounts SET credential = ? WHERE id = ?`).run(credential, accountId);
233
+ },
234
+
223
235
  // ------------------------------------------------------------------
224
236
  // Composite
225
237
  // ------------------------------------------------------------------
@@ -34,6 +34,16 @@ export const projectQueries = {
34
34
  `).get(path) as Project | null;
35
35
  },
36
36
 
37
+ userHasProject(userId: string, projectId: string): boolean {
38
+ const db = getDatabase();
39
+ const result = db.prepare(`
40
+ SELECT 1 as ok FROM user_projects
41
+ WHERE user_id = ? AND project_id = ?
42
+ LIMIT 1
43
+ `).get(userId, projectId) as { ok: number } | undefined;
44
+ return Boolean(result);
45
+ },
46
+
37
47
  create(project: Omit<Project, 'id'>): Project {
38
48
  const db = getDatabase();
39
49
  const id = crypto.randomUUID();
@@ -123,11 +133,6 @@ export const projectQueries = {
123
133
 
124
134
  setFilesPanelState(userId: string, projectId: string, state: string | null): void {
125
135
  const db = getDatabase();
126
- const now = new Date().toISOString();
127
- db.prepare(`
128
- INSERT OR IGNORE INTO user_projects (user_id, project_id, joined_at)
129
- VALUES (?, ?, ?)
130
- `).run(userId, projectId, now);
131
136
  db.prepare(`
132
137
  UPDATE user_projects
133
138
  SET files_panel_state = ?
@@ -73,7 +73,9 @@ class ConnectionManager {
73
73
  try {
74
74
  await adapter.connect(conn, tunnel?.localPort);
75
75
  } catch (err) {
76
- if (tunnel) await tunnel.close().catch(() => {});
76
+ if (tunnel) await tunnel.close().catch((err) => {
77
+ debug.warn('db-client', 'Failed to close SSH tunnel after adapter connect error:', err);
78
+ });
77
79
  throw err;
78
80
  }
79
81
 
@@ -164,8 +166,12 @@ class ConnectionManager {
164
166
  error: err instanceof Error ? err.message : String(err)
165
167
  };
166
168
  } finally {
167
- if (adapter) await adapter.close().catch(() => {});
168
- if (tunnel) await tunnel.close().catch(() => {});
169
+ if (adapter) await adapter.close().catch((err) => {
170
+ debug.warn('db-client', 'Transient adapter close error during health test:', err);
171
+ });
172
+ if (tunnel) await tunnel.close().catch((err) => {
173
+ debug.warn('db-client', 'Transient tunnel close error during health test:', err);
174
+ });
169
175
  }
170
176
  }
171
177