@myrialabs/clopen 0.3.7 → 0.3.9

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 (149) hide show
  1. package/backend/auth/permissions.ts +41 -2
  2. package/backend/chat/stream-manager.ts +71 -0
  3. package/backend/database/migrations/030_add_files_panel_state_to_user_projects.ts +34 -0
  4. package/backend/database/migrations/031_create_db_client_tables.ts +74 -0
  5. package/backend/database/migrations/032_seed_copilot_provider.ts +19 -0
  6. package/backend/database/migrations/033_seed_codex_provider.ts +19 -0
  7. package/backend/database/migrations/034_seed_qwen_provider.ts +119 -0
  8. package/backend/database/migrations/035_add_owner_to_db_client_connections.ts +34 -0
  9. package/backend/database/migrations/index.ts +43 -1
  10. package/backend/database/queries/db-client-connection-queries.ts +343 -0
  11. package/backend/database/queries/db-client-query-history-queries.ts +113 -0
  12. package/backend/database/queries/engine-queries.ts +12 -0
  13. package/backend/database/queries/index.ts +3 -1
  14. package/backend/database/queries/project-queries.ts +28 -0
  15. package/backend/db-client/connection-manager.ts +257 -0
  16. package/backend/db-client/drivers/bun-sql-helpers.ts +41 -0
  17. package/backend/db-client/drivers/mongodb.ts +358 -0
  18. package/backend/db-client/drivers/mysql.ts +385 -0
  19. package/backend/db-client/drivers/postgres.ts +446 -0
  20. package/backend/db-client/drivers/redis.ts +267 -0
  21. package/backend/db-client/drivers/sql-builders.ts +215 -0
  22. package/backend/db-client/drivers/sqlite.ts +346 -0
  23. package/backend/db-client/drivers/types.ts +92 -0
  24. package/backend/db-client/query-executor.ts +126 -0
  25. package/backend/db-client/ssh-tunnel.ts +122 -0
  26. package/backend/engine/README.md +1702 -0
  27. package/backend/engine/adapters/claude/models.ts +141 -0
  28. package/backend/engine/adapters/claude/stream.ts +1 -1
  29. package/backend/engine/adapters/codex/credential.ts +179 -0
  30. package/backend/engine/adapters/codex/error-handler.ts +65 -0
  31. package/backend/engine/adapters/codex/index.ts +1 -0
  32. package/backend/engine/adapters/codex/message-converter.ts +646 -0
  33. package/backend/engine/adapters/codex/models.ts +105 -0
  34. package/backend/engine/adapters/codex/patch-rollout.ts +169 -0
  35. package/backend/engine/adapters/codex/session-fork.ts +149 -0
  36. package/backend/engine/adapters/codex/stream.ts +310 -0
  37. package/backend/engine/adapters/codex/usage-rollout.ts +145 -0
  38. package/backend/engine/adapters/copilot/error-handler.ts +94 -0
  39. package/backend/engine/adapters/copilot/index.ts +1 -0
  40. package/backend/engine/adapters/copilot/message-converter.ts +973 -0
  41. package/backend/engine/adapters/copilot/models.ts +92 -0
  42. package/backend/engine/adapters/copilot/session-fork.ts +111 -0
  43. package/backend/engine/adapters/copilot/stream.ts +573 -0
  44. package/backend/engine/adapters/opencode/config.ts +56 -104
  45. package/backend/engine/adapters/opencode/error-handler.ts +71 -0
  46. package/backend/engine/adapters/opencode/models.ts +79 -0
  47. package/backend/engine/adapters/opencode/presets.ts +91 -0
  48. package/backend/engine/adapters/opencode/stream.ts +5 -115
  49. package/backend/engine/adapters/qwen/credential.ts +78 -0
  50. package/backend/engine/adapters/qwen/environment.ts +84 -0
  51. package/backend/engine/adapters/qwen/error-handler.ts +71 -0
  52. package/backend/engine/adapters/qwen/index.ts +1 -0
  53. package/backend/engine/adapters/qwen/message-converter.ts +1055 -0
  54. package/backend/engine/adapters/qwen/models.ts +81 -0
  55. package/backend/engine/adapters/qwen/presets.ts +51 -0
  56. package/backend/engine/adapters/qwen/session-fork.ts +97 -0
  57. package/backend/engine/adapters/qwen/stream.ts +380 -0
  58. package/backend/engine/index.ts +35 -0
  59. package/backend/engine/install-recipes.ts +80 -1
  60. package/backend/engine/install-runner.ts +4 -0
  61. package/backend/git/git-service.ts +12 -0
  62. package/backend/mcp/README.md +84 -14
  63. package/backend/mcp/config.ts +218 -17
  64. package/backend/mcp/index.ts +2 -0
  65. package/backend/mcp/project-context.ts +55 -0
  66. package/backend/mcp/servers/browser-automation/actions.ts +6 -1
  67. package/backend/mcp/servers/helper.ts +13 -0
  68. package/backend/middleware/error-handler.ts +16 -2
  69. package/backend/preview/browser/browser-preview-service.ts +4 -4
  70. package/backend/preview/browser/scripts/video-stream.ts +9 -3
  71. package/backend/ws/README.md +128 -3
  72. package/backend/ws/access.ts +56 -0
  73. package/backend/ws/chat/stream.ts +36 -12
  74. package/backend/ws/db-client/access.ts +19 -0
  75. package/backend/ws/db-client/connections.ts +194 -0
  76. package/backend/ws/db-client/index.ts +17 -0
  77. package/backend/ws/db-client/io.ts +456 -0
  78. package/backend/ws/db-client/query.ts +214 -0
  79. package/backend/ws/db-client/schema.ts +81 -0
  80. package/backend/ws/db-client/structure.ts +230 -0
  81. package/backend/ws/engine/access.ts +39 -0
  82. package/backend/ws/engine/claude/accounts.ts +15 -10
  83. package/backend/ws/engine/codex/accounts.ts +516 -0
  84. package/backend/ws/engine/codex/index.ts +14 -0
  85. package/backend/ws/engine/codex/status.ts +87 -0
  86. package/backend/ws/engine/copilot/accounts.ts +122 -0
  87. package/backend/ws/engine/copilot/index.ts +13 -0
  88. package/backend/ws/engine/copilot/status.ts +54 -0
  89. package/backend/ws/engine/index.ts +7 -1
  90. package/backend/ws/engine/opencode/providers.ts +1 -1
  91. package/backend/ws/engine/qwen/accounts.ts +137 -0
  92. package/backend/ws/engine/qwen/index.ts +15 -0
  93. package/backend/ws/engine/qwen/presets.ts +40 -0
  94. package/backend/ws/engine/qwen/status.ts +54 -0
  95. package/backend/ws/files/index.ts +5 -1
  96. package/backend/ws/files/read.ts +34 -0
  97. package/backend/ws/files/state.ts +42 -0
  98. package/backend/ws/files/watch.ts +7 -1
  99. package/backend/ws/git/branch.ts +13 -19
  100. package/backend/ws/git/commit-message.ts +3 -4
  101. package/backend/ws/git/commit.ts +5 -7
  102. package/backend/ws/git/conflict.ts +7 -10
  103. package/backend/ws/git/diff.ts +7 -10
  104. package/backend/ws/git/log.ts +3 -4
  105. package/backend/ws/git/remote.ts +30 -43
  106. package/backend/ws/git/staging.ts +13 -19
  107. package/backend/ws/git/status.ts +7 -11
  108. package/backend/ws/index.ts +5 -1
  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 +5 -40
  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 +4 -10
  120. package/backend/ws/projects/status.ts +2 -0
  121. package/backend/ws/sessions/crud.ts +22 -33
  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 +12 -6
  130. package/backend/ws/terminal/session.ts +35 -14
  131. package/backend/ws/terminal/stream.ts +4 -1
  132. package/dist/assets/{index-C86jwBxR.js → index-D8V2wj9B.js} +2 -2
  133. package/dist/assets/{main-DhLx8wD1.js → main-C9nYVmnw.js} +222 -195
  134. package/dist/assets/main-hspyFOoK.css +1 -0
  135. package/dist/index.html +2 -2
  136. package/package.json +7 -1
  137. package/shared/constants/engines.ts +45 -140
  138. package/shared/types/database/schema.ts +49 -1
  139. package/shared/types/db-client/connection.ts +60 -0
  140. package/shared/types/db-client/index.ts +6 -0
  141. package/shared/types/db-client/query.ts +77 -0
  142. package/shared/types/unified/common.ts +1 -1
  143. package/shared/types/unified/engine.ts +29 -1
  144. package/shared/types/unified/index.ts +2 -0
  145. package/shared/types/unified/message.ts +1 -1
  146. package/shared/types/unified/tool.ts +17 -2
  147. package/shared/utils/logger.ts +1 -0
  148. package/shared/utils/ws-server.ts +14 -0
  149. package/dist/assets/main-jTnmAoXS.css +0 -1
@@ -26,13 +26,51 @@ export const ADMIN_ONLY_ROUTES = new Set([
26
26
  'auth:revoke-invite',
27
27
  'auth:list-users',
28
28
  'auth:remove-user',
29
- 'settings:update-system',
29
+ 'settings:update',
30
+ 'settings:update-batch',
31
+ 'system:run-update',
32
+ 'system:clear-data',
30
33
  // System Tools — binary installation is an admin-only operation.
31
34
  'system-tools:status',
32
35
  'system-tools:status-all',
33
36
  'system-tools:install-start',
34
37
  'system-tools:install-cancel',
35
- 'system-tools:install-session'
38
+ 'system-tools:install-session',
39
+ // Engine — account/provider mutations are global system credentials and
40
+ // must only be changed by admins. Read-only routes (status, *-list) stay
41
+ // open so any authenticated user can see what is configured.
42
+ 'engine:claude-accounts-switch',
43
+ 'engine:claude-accounts-delete',
44
+ 'engine:claude-accounts-rename',
45
+ 'engine:claude-account-setup-start',
46
+ 'engine:claude-account-setup-submit',
47
+ 'engine:claude-account-setup-cancel',
48
+ 'engine:codex-accounts-add-api-key',
49
+ 'engine:codex-accounts-switch',
50
+ 'engine:codex-accounts-delete',
51
+ 'engine:codex-accounts-rename',
52
+ 'engine:codex-account-setup-start',
53
+ 'engine:codex-account-setup-cancel',
54
+ 'engine:codex-restart',
55
+ 'engine:copilot-accounts-add',
56
+ 'engine:copilot-accounts-switch',
57
+ 'engine:copilot-accounts-delete',
58
+ 'engine:copilot-accounts-rename',
59
+ 'engine:copilot-restart',
60
+ 'engine:qwen-accounts-add',
61
+ 'engine:qwen-accounts-switch',
62
+ 'engine:qwen-accounts-delete',
63
+ 'engine:qwen-accounts-rename',
64
+ 'engine:opencode-provider-add',
65
+ 'engine:opencode-provider-remove',
66
+ 'engine:opencode-provider-toggle',
67
+ 'engine:opencode-provider-update-options',
68
+ 'engine:opencode-account-add',
69
+ 'engine:opencode-account-switch',
70
+ 'engine:opencode-account-delete',
71
+ 'engine:opencode-account-rename',
72
+ 'engine:opencode-server-restart',
73
+ 'engine:opencode-models-dev-fetch'
36
74
  ]);
37
75
 
38
76
  /**
@@ -67,3 +105,4 @@ export function checkRouteAccess(
67
105
  // All other routes — any authenticated user
68
106
  return { allowed: true };
69
107
  }
108
+
@@ -277,6 +277,13 @@ class StreamManager extends EventEmitter {
277
277
  projectContextService.registerSession(request.chatSessionId, request.projectId);
278
278
  projectContextService.registerStream(streamId, request.projectId, request.chatSessionId);
279
279
  }
280
+ // Hand the AbortSignal to MCP so tool handlers can fast-fail on
281
+ // cancellation. Without this, the engine subprocess dies on cancel
282
+ // but the in-flight HTTP-MCP tool keeps issuing puppeteer ops —
283
+ // surfacing as "preview keeps moving by itself" after interrupt.
284
+ if (streamState.abortController) {
285
+ projectContextService.registerStreamSignal(streamId, streamState.abortController.signal);
286
+ }
280
287
 
281
288
  // Emit connection event immediately
282
289
  this.emitStreamEvent(streamState, 'connection', {
@@ -686,6 +693,13 @@ class StreamManager extends EventEmitter {
686
693
  });
687
694
  }
688
695
  }
696
+ // Codex emits usage only once per turn (after all items
697
+ // streamed live), so saved assistant rows have usage:null.
698
+ // Backfill the turn's aggregate to every saved assistant
699
+ // without usage so it survives a refresh.
700
+ if (successResult.usage && streamState.engine === 'codex') {
701
+ this.backfillUsageForStream(streamState, successResult.usage, requestSender);
702
+ }
689
703
  } else {
690
704
  const errResult = output as ErrorResultEvent;
691
705
  if (errResult.errors?.length) {
@@ -1337,6 +1351,63 @@ class StreamManager extends EventEmitter {
1337
1351
  }
1338
1352
  }
1339
1353
 
1354
+ /**
1355
+ * Backfill `usage` onto every saved assistant row for a stream.
1356
+ *
1357
+ * Codex SDK emits its `Usage` aggregate exactly once per turn (in
1358
+ * `turn.completed`), well after the individual assistant items have
1359
+ * streamed and been persisted live with `usage: null`. Without this
1360
+ * backfill the persisted tool_use rows would carry no usage data, and
1361
+ * after a browser refresh the frontend would lose the per-message usage
1362
+ * that the live stream had attached in memory.
1363
+ *
1364
+ * Engine-gated to Codex by the caller: Claude Code and Copilot already
1365
+ * attach per-call usage on each assistant message, so applying a
1366
+ * stream-wide aggregate to them would overwrite that finer-grained data.
1367
+ */
1368
+ private backfillUsageForStream(
1369
+ streamState: StreamState,
1370
+ usage: TokenUsage,
1371
+ requestSender: StreamRequest['sender'],
1372
+ ): void {
1373
+ try {
1374
+ const { getDatabase } = require('../database');
1375
+ const db = getDatabase();
1376
+ const updateStmt = db.prepare('UPDATE messages SET data = ? WHERE id = ?');
1377
+
1378
+ for (const entry of streamState.messages as any[]) {
1379
+ const msg = entry?.message as UnifiedMessage | undefined;
1380
+ if (!msg || msg.type !== 'assistant') continue;
1381
+ if (msg.usage) continue;
1382
+ if (!entry.message_id) continue;
1383
+
1384
+ const patched: AssistantMessage = { ...(msg as AssistantMessage), usage };
1385
+ try {
1386
+ updateStmt.run(JSON.stringify(patched), entry.message_id);
1387
+ } catch (err) {
1388
+ debug.error('chat', 'Failed to UPDATE usage row:', err);
1389
+ continue;
1390
+ }
1391
+
1392
+ entry.message = patched;
1393
+ entry.usage = usage;
1394
+
1395
+ this.emitStreamEvent(streamState, 'message', {
1396
+ processId: streamState.processId,
1397
+ message: patched,
1398
+ usage,
1399
+ timestamp: patched.createdAt,
1400
+ message_id: entry.message_id,
1401
+ parent_message_id: entry.parent_message_id ?? null,
1402
+ sender_id: requestSender.id,
1403
+ sender_name: requestSender.name,
1404
+ });
1405
+ }
1406
+ } catch (err) {
1407
+ debug.error('chat', 'Failed to backfill usage for stream:', err);
1408
+ }
1409
+ }
1410
+
1340
1411
  /**
1341
1412
  * Extract detailed error info from an error object.
1342
1413
  * Handles engine-specific error shapes (Anthropic APIError, OpenCode SDK errors).
@@ -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 files_panel_state to user_projects for files panel restore';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Adding files_panel_state to user_projects...');
8
+ db.exec(`ALTER TABLE user_projects ADD COLUMN files_panel_state TEXT`);
9
+ debug.log('migration', 'files_panel_state column added');
10
+ };
11
+
12
+ export const down = (db: DatabaseConnection): void => {
13
+ debug.log('migration', 'Removing files_panel_state from user_projects...');
14
+ db.exec(`
15
+ CREATE TABLE user_projects_backup AS
16
+ SELECT user_id, project_id, joined_at, current_session_id FROM user_projects
17
+ `);
18
+ db.exec(`DROP TABLE user_projects`);
19
+ db.exec(`
20
+ CREATE TABLE user_projects (
21
+ user_id TEXT NOT NULL,
22
+ project_id TEXT NOT NULL,
23
+ joined_at TEXT NOT NULL,
24
+ current_session_id TEXT,
25
+ PRIMARY KEY (user_id, project_id),
26
+ FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
27
+ )
28
+ `);
29
+ db.exec(`INSERT INTO user_projects SELECT * FROM user_projects_backup`);
30
+ db.exec(`DROP TABLE user_projects_backup`);
31
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_user_projects_user_id ON user_projects(user_id)`);
32
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_user_projects_project_id ON user_projects(project_id)`);
33
+ debug.log('migration', 'files_panel_state column removed');
34
+ };
@@ -0,0 +1,74 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create db_client_connections and db_client_query_history tables';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Creating db_client_connections table...');
8
+
9
+ db.exec(`
10
+ CREATE TABLE IF NOT EXISTS db_client_connections (
11
+ id TEXT PRIMARY KEY,
12
+ name TEXT NOT NULL,
13
+ driver TEXT NOT NULL CHECK (driver IN ('mysql','postgres','sqlite','mongodb','redis')),
14
+ host TEXT,
15
+ port INTEGER,
16
+ username TEXT,
17
+ password TEXT,
18
+ database TEXT,
19
+ ssl_mode TEXT DEFAULT 'disable' CHECK (ssl_mode IN ('disable','require','verify-ca','verify-full')),
20
+ ssl_ca TEXT,
21
+ ssh_enabled INTEGER NOT NULL DEFAULT 0,
22
+ ssh_host TEXT,
23
+ ssh_port INTEGER DEFAULT 22,
24
+ ssh_username TEXT,
25
+ ssh_auth_method TEXT DEFAULT 'password' CHECK (ssh_auth_method IN ('password','key')),
26
+ ssh_password TEXT,
27
+ ssh_private_key TEXT,
28
+ ssh_passphrase TEXT,
29
+ options_json TEXT,
30
+ color TEXT,
31
+ created_at TEXT NOT NULL,
32
+ updated_at TEXT NOT NULL,
33
+ last_used_at TEXT
34
+ )
35
+ `);
36
+
37
+ db.exec(`
38
+ CREATE INDEX IF NOT EXISTS idx_db_client_conn_last_used
39
+ ON db_client_connections(last_used_at DESC)
40
+ `);
41
+
42
+ debug.log('migration', 'Creating db_client_query_history table...');
43
+
44
+ db.exec(`
45
+ CREATE TABLE IF NOT EXISTS db_client_query_history (
46
+ id TEXT PRIMARY KEY,
47
+ connection_id TEXT NOT NULL,
48
+ user_id TEXT,
49
+ query TEXT NOT NULL,
50
+ duration_ms INTEGER,
51
+ row_count INTEGER,
52
+ status TEXT NOT NULL CHECK (status IN ('success','error')),
53
+ error TEXT,
54
+ executed_at TEXT NOT NULL,
55
+ FOREIGN KEY (connection_id) REFERENCES db_client_connections(id) ON DELETE CASCADE
56
+ )
57
+ `);
58
+
59
+ db.exec(`
60
+ CREATE INDEX IF NOT EXISTS idx_db_client_hist_conn_time
61
+ ON db_client_query_history(connection_id, executed_at DESC)
62
+ `);
63
+
64
+ debug.log('migration', 'db-client tables created');
65
+ };
66
+
67
+ export const down = (db: DatabaseConnection): void => {
68
+ debug.log('migration', 'Dropping db-client tables...');
69
+ db.exec('DROP INDEX IF EXISTS idx_db_client_hist_conn_time');
70
+ db.exec('DROP INDEX IF EXISTS idx_db_client_conn_last_used');
71
+ db.exec('DROP TABLE IF EXISTS db_client_query_history');
72
+ db.exec('DROP TABLE IF EXISTS db_client_connections');
73
+ debug.log('migration', 'db-client tables dropped');
74
+ };
@@ -0,0 +1,19 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Seed GitHub Copilot provider into engine_providers';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Seeding GitHub Copilot provider...');
8
+ db.exec(`
9
+ INSERT OR IGNORE INTO engine_providers (engine_type, slug, name, npm, api_url, options, is_enabled)
10
+ VALUES ('copilot', 'github', 'GitHub', NULL, NULL, '{}', 1)
11
+ `);
12
+ debug.log('migration', 'GitHub Copilot provider seeded');
13
+ };
14
+
15
+ export const down = (db: DatabaseConnection): void => {
16
+ debug.log('migration', 'Removing GitHub Copilot provider...');
17
+ db.exec(`DELETE FROM engine_providers WHERE engine_type = 'copilot' AND slug = 'github'`);
18
+ debug.log('migration', 'GitHub Copilot provider removed');
19
+ };
@@ -0,0 +1,19 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Seed OpenAI Codex provider into engine_providers';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Seeding OpenAI Codex provider...');
8
+ db.exec(`
9
+ INSERT OR IGNORE INTO engine_providers (engine_type, slug, name, npm, api_url, options, is_enabled)
10
+ VALUES ('codex', 'openai', 'OpenAI', NULL, NULL, '{}', 1)
11
+ `);
12
+ debug.log('migration', 'OpenAI Codex provider seeded');
13
+ };
14
+
15
+ export const down = (db: DatabaseConnection): void => {
16
+ debug.log('migration', 'Removing OpenAI Codex provider...');
17
+ db.exec(`DELETE FROM engine_providers WHERE engine_type = 'codex' AND slug = 'openai'`);
18
+ debug.log('migration', 'OpenAI Codex provider removed');
19
+ };
@@ -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
+ };
@@ -28,6 +28,12 @@ import * as migration026 from './026_create_invite_tokens_table';
28
28
  import * as migration027 from './027_create_opencode_providers_table';
29
29
  import * as migration028 from './028_create_opencode_accounts_table';
30
30
  import * as migration029 from './029_migrate_messages_to_unified';
31
+ import * as migration030 from './030_add_files_panel_state_to_user_projects';
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';
31
37
 
32
38
  // Export all migrations in order
33
39
  export const migrations = [
@@ -204,7 +210,43 @@ export const migrations = [
204
210
  description: migration029.description,
205
211
  up: migration029.up,
206
212
  down: migration029.down
213
+ },
214
+ {
215
+ id: '030',
216
+ description: migration030.description,
217
+ up: migration030.up,
218
+ down: migration030.down
219
+ },
220
+ {
221
+ id: '031',
222
+ description: migration031.description,
223
+ up: migration031.up,
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
207
249
  }
208
250
  ];
209
251
 
210
- export default migrations;
252
+ export default migrations;