@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
package/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  <p align="center">
8
8
  <strong>Build more. Switch less.</strong><br />
9
- All-in-one workspace for Claude Code & OpenCode
9
+ All-in-one workspace for AI coding agents
10
10
  </p>
11
11
 
12
12
  <p align="center">
@@ -26,7 +26,7 @@
26
26
  <img src="https://clopen.myrialabs.dev/images/workspace-overview.webp" alt="Clopen workspace overview" />
27
27
  </p>
28
28
 
29
- All-in-one workspace for Claude Code & OpenCode. Chat, terminal, git, browser preview, and real-time collaboration, built for multi-project and multi-session workflows.
29
+ All-in-one workspace for AI coding agents — Claude Code, OpenCode, Codex, Copilot, and Qwen Code. Chat, terminal, git, browser preview, database client, and real-time collaboration, built for multi-project and multi-session workflows.
30
30
 
31
31
  ---
32
32
 
@@ -46,20 +46,20 @@ All-in-one workspace for Claude Code & OpenCode. Chat, terminal, git, browser pr
46
46
 
47
47
  A complete development environment designed around AI-assisted workflows, built to disappear into the background and just work.
48
48
 
49
- - **Multi-Account Claude Code** — Manage multiple Claude Code accounts (personal, work, or team) and switch between them instantly per chat session
50
- - **Multi-Engine Support** — Switch between Claude Code and OpenCode as your AI engine, per session
51
- - **Integrated Terminal** — Full PTY emulation with xterm.js UI. Multi-tab terminal sessions with complete ANSI/VT sequence support and full keyboard control
52
- - **Full Git Management** — Stage, commit, branch, push, pull, stash, log, and resolve conflicts, all from a clean UI. Powered by native git CLI for accuracy
49
+ - **Multi-Engine Support** — Switch between Claude Code, OpenCode, Codex, GitHub Copilot, and Qwen Code as your AI engine, per session
50
+ - **Multi-Account Per Engine** — Manage multiple accounts per engine (personal, work, or team) and switch between them instantly per chat session
51
+ - **Integrated Terminal** — Multi-tab xterm.js terminal with full keyboard control and complete ANSI/VT support, right inside your workspace
52
+ - **Full Git Management** — Stage, commit, branch, push, pull, stash, log, and resolve conflicts, all from a clean UI
53
53
  - **Real Browser Preview** — A live browser preview streams directly into your workspace. Interact with your app manually, or let the AI drive: clicking, typing, and scrolling for autonomous visual testing
54
+ - **Database Client** — Connect to PostgreSQL, MySQL, SQLite, MongoDB, and Redis. Browse schemas, run queries, and inspect data, with optional SSH tunneling for databases behind a bastion
54
55
  - **Git-Like Checkpoints** — Multi-branch undo/redo with full file snapshots. Roll back to any point in your AI conversation without touching your actual git history
55
- - **Real-Time Collaboration** — WebSocket-based presence tracking per project. Multiple users can work on the same codebase simultaneously with live awareness
56
- - **Monaco File Editor** — VS Code's editor embedded in the browser. Full syntax highlighting, autocomplete, and live file watching, right beside your AI chat
56
+ - **Real-Time Collaboration** — See who's working on which project, and collaborate live in the same codebase
57
+ - **Monaco File Editor** — VS Code's editor right in the browser. Full syntax highlighting, autocomplete, and live file watching, beside your AI chat
57
58
  - **Cloudflare Tunnel** — One-click public HTTPS URL for your local dev server. Built-in QR code for instant mobile access. Share your work without deploying
58
59
  - **MCP Support** — Full Model Context Protocol integration. Connect AI tools, external APIs, and custom capabilities to your AI agents with zero friction
59
60
  - **Flexible Authentication** — No Login or With Login mode with admin/member roles, invite links, rate-limited login, and CLI token recovery
60
- - **System Tools Installer** — Install Git, Claude Code, OpenCode, Chrome, and Cloudflared (for Public Tunnel) straight from the admin Settings UI, with live install output streamed to the browser via xterm.js
61
+ - **System Tools Installer** — Install Git, Claude Code, OpenCode, Codex, Copilot, Qwen Code, Chrome, and Cloudflared (for Public Tunnel) from a one-click admin panel
61
62
  - **Background Processing** — Chat, terminal, and other processes continue running even when you close the browser — come back later and pick up where you left off
62
- - **Database Management** — Browse tables, run queries, and inspect your database directly from the workspace *(coming soon)*
63
63
 
64
64
  ---
65
65
 
@@ -68,7 +68,7 @@ A complete development environment designed around AI-assisted workflows, built
68
68
  ### Prerequisites
69
69
 
70
70
  - [Bun.js](https://bun.sh/) v1.2.12+
71
- - [Claude Code](https://github.com/anthropics/claude-code) or [OpenCode](https://opencode.ai) — required for AI functionality
71
+ - At least one supported AI engine — [Claude Code](https://github.com/anthropics/claude-code), [OpenCode](https://opencode.ai), [Codex](https://github.com/openai/codex), [GitHub Copilot CLI](https://github.com/github/copilot-cli), or [Qwen Code](https://github.com/QwenLM/qwen-code). All are installable from **Settings → System Tools** after first launch
72
72
 
73
73
  ### Installation
74
74
 
@@ -88,7 +88,7 @@ Or manually via Bun:
88
88
  bun add -g @myrialabs/clopen
89
89
  ```
90
90
 
91
- You can also update from the **Settings → Maintenance > Updates** section in the web UI.
91
+ You can also update from the **Settings → Maintenance → Updates** section in the web UI.
92
92
 
93
93
  ### Usage
94
94
 
@@ -104,12 +104,13 @@ On first launch, a setup wizard guides you through:
104
104
 
105
105
  1. **Authentication mode** — Choose between **No Login** (no authentication required, ideal for personal/local use) or **With Login** (login with Personal Access Token, supports team collaboration)
106
106
  2. **Admin account** — If With Login mode is selected, create your admin account and save the generated PAT
107
- 3. **AI Engines** — Check Claude Code and OpenCode installation status
108
- 4. **Preferences** — Set theme, font size, and notification preferences
107
+ 3. **System Tools** — Install Git, Chrome, Cloudflared, and any AI engine you don't have yet — straight from the wizard, no terminal needed
108
+ 4. **AI Engines** — Check installation status for Claude Code, OpenCode, Codex, Copilot, and Qwen Code, and sign in to the engines you'll use
109
+ 5. **Preferences** — Set dark mode, font size, sound notifications, and message layout (Classic cards or Compact lines)
109
110
 
110
- You can change the authentication mode anytime in **Settings → Security > Authentication**.
111
+ You can change the authentication mode anytime in **Settings → Security → Authentication**.
111
112
 
112
- To invite team members (With Login mode), go to **Settings → Team > Invite** and generate an invite link (valid for 15 minutes).
113
+ To invite team members (With Login mode), go to **Settings → Team → Invite** and generate an invite link (valid for 15 minutes).
113
114
 
114
115
  If you lose your admin token:
115
116
 
@@ -149,9 +150,8 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines and [DECISIONS.md](DECISIO
149
150
  | Styling | Tailwind CSS v4 |
150
151
  | Database | SQLite with migrations |
151
152
  | Terminal | bun-pty |
152
- | AI Engines | Claude Code + OpenCode |
153
-
154
- Clopen uses an engine-agnostic adapter pattern — both engines normalize output to a unified message format (`shared/types/unified`), ensuring a consistent experience regardless of which engine is selected.
153
+ | AI Engines | Claude Code, OpenCode, Codex, Copilot, Qwen Code |
154
+ | DB Client | Postgres, MySQL, SQLite, MongoDB, Redis (+ SSH tunnel) |
155
155
 
156
156
  ---
157
157
 
@@ -185,6 +185,9 @@ MIT License - see [LICENSE](LICENSE) for details.
185
185
 
186
186
  - [Claude Code](https://github.com/anthropics/claude-code) by Anthropic
187
187
  - [OpenCode](https://opencode.ai) by Anomaly
188
+ - [Codex](https://github.com/openai/codex) by OpenAI
189
+ - [GitHub Copilot CLI](https://github.com/github/copilot-cli) by GitHub
190
+ - [Qwen Code](https://github.com/QwenLM/qwen-code) by Alibaba Qwen
188
191
  - [Bun](https://bun.sh/) runtime
189
192
  - [Svelte](https://svelte.dev/) framework
190
193
 
@@ -4,7 +4,8 @@
4
4
  * Core authentication logic: user creation, session management, invite handling.
5
5
  */
6
6
 
7
- import { authQueries, settingsQueries } from '$backend/database/queries';
7
+ import { authQueries, projectQueries, settingsQueries } from '$backend/database/queries';
8
+ import type { Project } from '$shared/types/database/schema';
8
9
  import { generateSessionToken, generatePAT, generateInviteToken, hashToken, getTokenType } from './tokens';
9
10
  import { generateColorFromString, getInitials } from '$backend/utils/user-helpers';
10
11
  import { debug } from '$shared/utils/logger';
@@ -472,6 +473,60 @@ export function logoutAllSessions(): number {
472
473
  return count;
473
474
  }
474
475
 
476
+ /**
477
+ * List projects assigned to a specific user (admin view)
478
+ */
479
+ export function listUserProjects(userId: string): Project[] {
480
+ const user = authQueries.getUserById(userId);
481
+ if (!user) {
482
+ throw new Error('User not found');
483
+ }
484
+ return projectQueries.getAllForUser(userId);
485
+ }
486
+
487
+ /**
488
+ * Assign a project to a user. Admins are implicitly assigned to all projects
489
+ * they create, but this is used to grant a member access to a project.
490
+ * Returns true if a new assignment was added, false if user already had access.
491
+ */
492
+ export function assignProjectToUser(userId: string, projectId: string): boolean {
493
+ const user = authQueries.getUserById(userId);
494
+ if (!user) {
495
+ throw new Error('Access denied');
496
+ }
497
+ const project = projectQueries.getById(projectId);
498
+ if (!project) {
499
+ throw new Error('Access denied');
500
+ }
501
+ if (projectQueries.userHasProject(userId, projectId)) {
502
+ return false;
503
+ }
504
+ projectQueries.addUserProject(userId, projectId);
505
+ debug.log('auth', `Project ${projectId} assigned to user ${userId}`);
506
+ return true;
507
+ }
508
+
509
+ /**
510
+ * Revoke a user's access to a project. Refuses to remove the last admin
511
+ * association to avoid orphaning the project.
512
+ */
513
+ export function unassignProjectFromUser(userId: string, projectId: string): boolean {
514
+ const user = authQueries.getUserById(userId);
515
+ if (!user) {
516
+ throw new Error('Access denied');
517
+ }
518
+ const project = projectQueries.getById(projectId);
519
+ if (!project) {
520
+ throw new Error('Access denied');
521
+ }
522
+ if (!projectQueries.userHasProject(userId, projectId)) {
523
+ return false;
524
+ }
525
+ projectQueries.removeUserProject(userId, projectId);
526
+ debug.log('auth', `Project ${projectId} unassigned from user ${userId}`);
527
+ return true;
528
+ }
529
+
475
530
  /**
476
531
  * Cleanup expired sessions
477
532
  */
@@ -26,13 +26,76 @@ 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
+ 'auth:list-user-projects',
30
+ 'auth:assign-project',
31
+ 'auth:unassign-project',
32
+ // Project lifecycle — members can only access projects they are assigned to
33
+ // by an admin. Create/delete remain admin-only operations.
34
+ 'projects:create',
35
+ 'projects:delete',
36
+ 'settings:update',
37
+ 'settings:update-batch',
38
+ 'system:run-update',
39
+ 'system:clear-data',
30
40
  // System Tools — binary installation is an admin-only operation.
31
41
  'system-tools:status',
32
42
  'system-tools:status-all',
33
43
  'system-tools:install-start',
34
44
  'system-tools:install-cancel',
35
- 'system-tools:install-session'
45
+ 'system-tools:install-session',
46
+ // Engine — account/provider mutations are global system credentials and
47
+ // must only be changed by admins. Read-only routes (status, *-list) stay
48
+ // open so any authenticated user can see what is configured.
49
+ 'engine:claude-accounts-switch',
50
+ 'engine:claude-accounts-delete',
51
+ 'engine:claude-accounts-rename',
52
+ 'engine:claude-account-setup-start',
53
+ 'engine:claude-account-setup-submit',
54
+ 'engine:claude-account-setup-cancel',
55
+ 'engine:codex-accounts-add-api-key',
56
+ 'engine:codex-accounts-switch',
57
+ 'engine:codex-accounts-delete',
58
+ 'engine:codex-accounts-rename',
59
+ 'engine:codex-account-setup-start',
60
+ 'engine:codex-account-setup-cancel',
61
+ 'engine:codex-restart',
62
+ 'engine:copilot-accounts-add',
63
+ 'engine:copilot-accounts-switch',
64
+ 'engine:copilot-accounts-delete',
65
+ 'engine:copilot-accounts-rename',
66
+ 'engine:copilot-restart',
67
+ 'engine:qwen-accounts-add',
68
+ 'engine:qwen-accounts-switch',
69
+ 'engine:qwen-accounts-delete',
70
+ 'engine:qwen-accounts-rename',
71
+ 'engine:opencode-provider-add',
72
+ 'engine:opencode-provider-remove',
73
+ 'engine:opencode-provider-toggle',
74
+ 'engine:opencode-provider-update-options',
75
+ 'engine:opencode-account-add',
76
+ 'engine:opencode-account-switch',
77
+ 'engine:opencode-account-delete',
78
+ 'engine:opencode-account-rename',
79
+ 'engine:opencode-server-restart',
80
+ 'engine:opencode-models-dev-fetch',
81
+ // Tunnel — remote/local management mutates global Cloudflare credentials,
82
+ // cloudflared auth, and ingress rules. Quick Tunnel is ephemeral and stays
83
+ // open. Read-only routes (status, *-list, ingress, auth-status) stay open so
84
+ // any authenticated user can see what is active.
85
+ 'tunnel:remote:config:add',
86
+ 'tunnel:remote:config:remove',
87
+ 'tunnel:remote:start',
88
+ 'tunnel:remote:stop',
89
+ 'tunnel:local:login-start',
90
+ 'tunnel:local:login-cancel',
91
+ 'tunnel:local:logout',
92
+ 'tunnel:local:set-zone',
93
+ 'tunnel:local:create',
94
+ 'tunnel:local:delete',
95
+ 'tunnel:local:ingress:add',
96
+ 'tunnel:local:ingress:remove',
97
+ 'tunnel:local:start',
98
+ 'tunnel:local:stop'
36
99
  ]);
37
100
 
38
101
  /**
@@ -67,3 +130,4 @@ export function checkRouteAccess(
67
130
  // All other routes — any authenticated user
68
131
  return { allowed: true };
69
132
  }
133
+
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Expired Session Cleanup Scheduler
3
+ *
4
+ * Periodically removes expired auth sessions from the database.
5
+ * Without this, the auth_sessions table grows unbounded as expired
6
+ * sessions are never purged in long-running deployments.
7
+ *
8
+ * Pattern: same timer + dispose() approach as AuthRateLimiter.
9
+ */
10
+
11
+ import { authQueries } from '../database/queries';
12
+ import { debug } from '$shared/utils/logger';
13
+
14
+ /** How often to sweep for expired sessions (1 hour) */
15
+ const CLEANUP_INTERVAL_MS = 60 * 60_000;
16
+
17
+ class SessionCleanupScheduler {
18
+ private timer: ReturnType<typeof setInterval> | null = null;
19
+
20
+ constructor() {
21
+ // Timer is started in start(), not here — database may not be initialized yet.
22
+ }
23
+
24
+ /**
25
+ * Start the periodic cleanup timer and run an initial sweep.
26
+ * Must be called AFTER database initialization.
27
+ */
28
+ start(): void {
29
+ if (this.timer) return; // Already started
30
+ this.timer = setInterval(() => this.cleanup(), CLEANUP_INTERVAL_MS);
31
+ // Run once at startup so long-stale sessions are cleared immediately
32
+ this.cleanup();
33
+ }
34
+
35
+ private cleanup(): void {
36
+ try {
37
+ const deleted = authQueries.deleteExpiredSessions();
38
+ if (deleted > 0) {
39
+ debug.log('auth', `Session cleanup: removed ${deleted} expired session(s)`);
40
+ }
41
+ } catch (error) {
42
+ debug.warn('auth', 'Session cleanup failed:', error);
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Dispose — stop cleanup timer. Called during graceful shutdown.
48
+ */
49
+ dispose(): void {
50
+ if (this.timer) {
51
+ clearInterval(this.timer);
52
+ this.timer = null;
53
+ }
54
+ }
55
+ }
56
+
57
+ /** Singleton instance — started when the module is imported */
58
+ export const sessionCleanupScheduler = new SessionCleanupScheduler();
@@ -50,6 +50,7 @@ export interface StreamState {
50
50
  projectPath?: string;
51
51
  processId: string;
52
52
  engine: EngineType;
53
+ accountId?: number;
53
54
  status: 'active' | 'completed' | 'error' | 'cancelled';
54
55
  startedAt: Date;
55
56
  completedAt?: Date;
@@ -156,6 +157,7 @@ export type StreamEventType =
156
157
  | 'message'
157
158
  | 'partial'
158
159
  | 'notification'
160
+ | 'rate_limit'
159
161
  | 'complete'
160
162
  | 'error'
161
163
  | 'cancelled';
@@ -173,11 +175,57 @@ export interface StreamEvent {
173
175
  // Stream Manager
174
176
  // ============================================================================
175
177
 
178
+ export interface RateLimitSnapshot {
179
+ engine: EngineType;
180
+ accountId: number;
181
+ status: 'allowed_warning' | 'rejected';
182
+ utilization: number;
183
+ resetsAt: number | null;
184
+ receivedAt: string;
185
+ }
186
+
176
187
  class StreamManager extends EventEmitter {
177
188
  private activeStreams = new Map<string, StreamState>();
178
189
  private sessionStreams = new Map<string, string>(); // composite key -> streamId
179
190
  /** Guard against duplicate lifecycle events (e.g. if both inner and outer error paths fire) */
180
191
  private lifecycleEmitted = new Set<string>();
192
+ /** Latest rate-limit snapshot per `${engine}:${accountId}`. Persists across refresh so the UI banner can rehydrate on join. */
193
+ private activeRateLimits = new Map<string, RateLimitSnapshot>();
194
+
195
+ private getAccountKey(engine: EngineType, accountId: number): string {
196
+ return `${engine}:${accountId}`;
197
+ }
198
+
199
+ /** Return active rate limit for an account, purging it lazily if `resetsAt` has passed. */
200
+ getRateLimitForAccount(engine: EngineType, accountId: number): RateLimitSnapshot | null {
201
+ const key = this.getAccountKey(engine, accountId);
202
+ const snap = this.activeRateLimits.get(key);
203
+ if (!snap) return null;
204
+ if (snap.resetsAt && snap.resetsAt * 1000 < Date.now()) {
205
+ this.activeRateLimits.delete(key);
206
+ return null;
207
+ }
208
+ return snap;
209
+ }
210
+
211
+ /** Return every active rate-limit snapshot, lazily purging expired entries. */
212
+ getAllActiveRateLimits(): RateLimitSnapshot[] {
213
+ const now = Date.now();
214
+ const active: RateLimitSnapshot[] = [];
215
+ for (const [key, snap] of this.activeRateLimits) {
216
+ if (snap.resetsAt && snap.resetsAt * 1000 < now) {
217
+ this.activeRateLimits.delete(key);
218
+ continue;
219
+ }
220
+ active.push(snap);
221
+ }
222
+ return active;
223
+ }
224
+
225
+ /** Clear an active rate limit (called when the user dismisses the banner). */
226
+ dismissRateLimit(engine: EngineType, accountId: number): void {
227
+ this.activeRateLimits.delete(this.getAccountKey(engine, accountId));
228
+ }
181
229
 
182
230
  constructor() {
183
231
  super();
@@ -244,6 +292,7 @@ class StreamManager extends EventEmitter {
244
292
  projectPath: request.projectPath,
245
293
  processId,
246
294
  engine: request.engine.type,
295
+ accountId: request.engine.account?.id || undefined,
247
296
  status: 'active',
248
297
  startedAt: new Date(),
249
298
  messages: [],
@@ -277,6 +326,13 @@ class StreamManager extends EventEmitter {
277
326
  projectContextService.registerSession(request.chatSessionId, request.projectId);
278
327
  projectContextService.registerStream(streamId, request.projectId, request.chatSessionId);
279
328
  }
329
+ // Hand the AbortSignal to MCP so tool handlers can fast-fail on
330
+ // cancellation. Without this, the engine subprocess dies on cancel
331
+ // but the in-flight HTTP-MCP tool keeps issuing puppeteer ops —
332
+ // surfacing as "preview keeps moving by itself" after interrupt.
333
+ if (streamState.abortController) {
334
+ projectContextService.registerStreamSignal(streamId, streamState.abortController.signal);
335
+ }
280
336
 
281
337
  // Emit connection event immediately
282
338
  this.emitStreamEvent(streamState, 'connection', {
@@ -644,19 +700,29 @@ class StreamManager extends EventEmitter {
644
700
  // ── Rate Limit ─────────────────────────────────────────
645
701
  case 'rate_limit': {
646
702
  const rl = output as RateLimitEvent;
647
- const isRejected = rl.status === 'rejected';
648
- const resetTime = rl.resetsAt
649
- ? new Date(rl.resetsAt * 1000).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' })
650
- : 'unknown';
651
- this.emitStreamEvent(streamState, 'notification', {
652
- notification: {
653
- type: isRejected ? 'error' : 'warning',
654
- title: isRejected ? 'Rate Limit Reached' : 'Rate Limit Warning',
655
- message: isRejected
656
- ? `Rate limit exceeded. Resets at ${resetTime}.`
657
- : `Approaching rate limit (${Math.round((rl.utilization || 0) * 100)}% used). Resets at ${resetTime}.`,
658
- },
659
- timestamp: new Date().toISOString()
703
+ const accountId = streamState.accountId;
704
+ const nowIso = new Date().toISOString();
705
+ if (accountId) {
706
+ this.activeRateLimits.set(
707
+ this.getAccountKey(streamState.engine, accountId),
708
+ {
709
+ engine: streamState.engine,
710
+ accountId,
711
+ status: rl.status,
712
+ utilization: rl.utilization,
713
+ resetsAt: rl.resetsAt,
714
+ receivedAt: nowIso
715
+ }
716
+ );
717
+ }
718
+ this.emitStreamEvent(streamState, 'rate_limit', {
719
+ chatSessionId: streamState.chatSessionId,
720
+ engine: streamState.engine,
721
+ accountId: accountId ?? 0,
722
+ status: rl.status,
723
+ utilization: rl.utilization,
724
+ resetsAt: rl.resetsAt,
725
+ timestamp: nowIso
660
726
  });
661
727
  continue;
662
728
  }
@@ -686,6 +752,13 @@ class StreamManager extends EventEmitter {
686
752
  });
687
753
  }
688
754
  }
755
+ // Codex emits usage only once per turn (after all items
756
+ // streamed live), so saved assistant rows have usage:null.
757
+ // Backfill the turn's aggregate to every saved assistant
758
+ // without usage so it survives a refresh.
759
+ if (successResult.usage && streamState.engine === 'codex') {
760
+ this.backfillUsageForStream(streamState, successResult.usage, requestSender);
761
+ }
689
762
  } else {
690
763
  const errResult = output as ErrorResultEvent;
691
764
  if (errResult.errors?.length) {
@@ -1337,6 +1410,63 @@ class StreamManager extends EventEmitter {
1337
1410
  }
1338
1411
  }
1339
1412
 
1413
+ /**
1414
+ * Backfill `usage` onto every saved assistant row for a stream.
1415
+ *
1416
+ * Codex SDK emits its `Usage` aggregate exactly once per turn (in
1417
+ * `turn.completed`), well after the individual assistant items have
1418
+ * streamed and been persisted live with `usage: null`. Without this
1419
+ * backfill the persisted tool_use rows would carry no usage data, and
1420
+ * after a browser refresh the frontend would lose the per-message usage
1421
+ * that the live stream had attached in memory.
1422
+ *
1423
+ * Engine-gated to Codex by the caller: Claude Code and Copilot already
1424
+ * attach per-call usage on each assistant message, so applying a
1425
+ * stream-wide aggregate to them would overwrite that finer-grained data.
1426
+ */
1427
+ private backfillUsageForStream(
1428
+ streamState: StreamState,
1429
+ usage: TokenUsage,
1430
+ requestSender: StreamRequest['sender'],
1431
+ ): void {
1432
+ try {
1433
+ const { getDatabase } = require('../database');
1434
+ const db = getDatabase();
1435
+ const updateStmt = db.prepare('UPDATE messages SET data = ? WHERE id = ?');
1436
+
1437
+ for (const entry of streamState.messages as any[]) {
1438
+ const msg = entry?.message as UnifiedMessage | undefined;
1439
+ if (!msg || msg.type !== 'assistant') continue;
1440
+ if (msg.usage) continue;
1441
+ if (!entry.message_id) continue;
1442
+
1443
+ const patched: AssistantMessage = { ...(msg as AssistantMessage), usage };
1444
+ try {
1445
+ updateStmt.run(JSON.stringify(patched), entry.message_id);
1446
+ } catch (err) {
1447
+ debug.error('chat', 'Failed to UPDATE usage row:', err);
1448
+ continue;
1449
+ }
1450
+
1451
+ entry.message = patched;
1452
+ entry.usage = usage;
1453
+
1454
+ this.emitStreamEvent(streamState, 'message', {
1455
+ processId: streamState.processId,
1456
+ message: patched,
1457
+ usage,
1458
+ timestamp: patched.createdAt,
1459
+ message_id: entry.message_id,
1460
+ parent_message_id: entry.parent_message_id ?? null,
1461
+ sender_id: requestSender.id,
1462
+ sender_name: requestSender.name,
1463
+ });
1464
+ }
1465
+ } catch (err) {
1466
+ debug.error('chat', 'Failed to backfill usage for stream:', err);
1467
+ }
1468
+ }
1469
+
1340
1470
  /**
1341
1471
  * Extract detailed error info from an error object.
1342
1472
  * Handles engine-specific error shapes (Anthropic APIError, OpenCode SDK errors).
@@ -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
+ };