@myrialabs/clopen 0.3.11 → 0.3.13

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 (67) hide show
  1. package/backend/auth/session-invalidation.test.ts +116 -0
  2. package/backend/auth/session-invalidation.ts +78 -0
  3. package/backend/chat/stream-manager.ts +4 -0
  4. package/backend/database/migrations/036_create_auth_audit_log.ts +30 -0
  5. package/backend/database/migrations/037_repair_auth_audit_log_schema.ts +38 -0
  6. package/backend/database/migrations/index.ts +14 -0
  7. package/backend/database/queries/audit-log-queries.test.ts +162 -0
  8. package/backend/database/queries/audit-log-queries.ts +98 -0
  9. package/backend/database/queries/index.ts +2 -1
  10. package/backend/engine/README.md +101 -29
  11. package/backend/engine/adapters/claude/message-converter.ts +1 -0
  12. package/backend/engine/adapters/codex/stream.ts +54 -1
  13. package/backend/engine/adapters/copilot/stream.ts +79 -19
  14. package/backend/engine/adapters/opencode/stream.ts +23 -23
  15. package/backend/engine/adapters/qwen/stream.ts +83 -1
  16. package/backend/engine/structured-helpers.ts +59 -0
  17. package/backend/files/file-archive.ts +191 -0
  18. package/backend/files/file-operations.ts +25 -61
  19. package/backend/files/file-size-limit.test.ts +85 -0
  20. package/backend/files/file-size-limit.ts +52 -0
  21. package/backend/git/git-service.ts +48 -4
  22. package/backend/http/files-upload.ts +168 -0
  23. package/backend/index.ts +14 -0
  24. package/backend/mcp/config.ts +4 -1
  25. package/backend/mcp/output-validator.test.ts +52 -0
  26. package/backend/mcp/output-validator.ts +103 -0
  27. package/backend/mcp/project-context.test.ts +22 -0
  28. package/backend/mcp/project-context.ts +35 -0
  29. package/backend/mcp/servers/helper.ts +11 -2
  30. package/backend/project/status-manager.test.ts +32 -0
  31. package/backend/project/status-manager.ts +7 -0
  32. package/backend/projects/project-cleanup-registry.test.ts +48 -0
  33. package/backend/projects/project-cleanup-registry.ts +44 -0
  34. package/backend/projects/project-cleanup.integration.test.ts +36 -0
  35. package/backend/projects/project-cleanup.ts +32 -0
  36. package/backend/terminal/pty-session-manager.ts +3 -0
  37. package/backend/terminal/stream-manager.ts +1 -1
  38. package/backend/utils/ws.ts +46 -0
  39. package/backend/ws/auth/index.ts +4 -0
  40. package/backend/ws/auth/login.ts +31 -19
  41. package/backend/ws/auth/users.ts +21 -2
  42. package/backend/ws/chat/stream.ts +11 -0
  43. package/backend/ws/files/path-access.test.ts +166 -0
  44. package/backend/ws/files/path-access.ts +56 -22
  45. package/backend/ws/files/read.ts +5 -5
  46. package/backend/ws/files/search.ts +4 -0
  47. package/backend/ws/files/write.ts +47 -25
  48. package/backend/ws/git/commit-message.ts +12 -5
  49. package/backend/ws/git/remote.ts +6 -3
  50. package/backend/ws/message-rate-limiter.test.ts +79 -0
  51. package/backend/ws/message-rate-limiter.ts +134 -0
  52. package/backend/ws/projects/crud.ts +3 -0
  53. package/backend/ws/terminal/session.ts +1 -0
  54. package/dist/assets/main-BqiSLc8F.css +1 -0
  55. package/dist/assets/main-DOVudc3_.js +354 -0
  56. package/dist/index.html +2 -2
  57. package/package.json +8 -7
  58. package/shared/types/git.ts +4 -2
  59. package/shared/types/stores/settings.ts +4 -0
  60. package/shared/types/unified/index.ts +1 -0
  61. package/shared/types/unified/stream.ts +8 -0
  62. package/shared/utils/logger.ts +1 -0
  63. package/shared/utils/ws-server.ts +17 -6
  64. package/backend/engine/adapters/copilot/session-fork.ts +0 -111
  65. package/dist/assets/index-DmghE6mf.js +0 -2
  66. package/dist/assets/main-DiDuzJJh.js +0 -318
  67. package/dist/assets/main-N1w7Llvp.css +0 -1
package/dist/index.html CHANGED
@@ -58,8 +58,8 @@
58
58
  }
59
59
  })();
60
60
  </script>
61
- <script type="module" crossorigin src="/assets/main-DiDuzJJh.js"></script>
62
- <link rel="stylesheet" crossorigin href="/assets/main-N1w7Llvp.css">
61
+ <script type="module" crossorigin src="/assets/main-DOVudc3_.js"></script>
62
+ <link rel="stylesheet" crossorigin href="/assets/main-BqiSLc8F.css">
63
63
  </head>
64
64
  <body
65
65
  class="min-h-dvh bg-white text-slate-900 dark:bg-slate-950 dark:text-slate-100 transition-colors duration-200"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myrialabs/clopen",
3
- "version": "0.3.11",
3
+ "version": "0.3.13",
4
4
  "description": "All-in-one web workspace for Claude Code & OpenCode — chat, terminal, git, browser preview, checkpoints, and real-time collaboration",
5
5
  "author": "Myria Labs",
6
6
  "license": "MIT",
@@ -87,16 +87,16 @@
87
87
  "vite": "^7.0.4"
88
88
  },
89
89
  "dependencies": {
90
- "@anthropic-ai/claude-agent-sdk": "^0.2.112",
91
- "@anthropic-ai/sdk": "^0.90.0",
90
+ "@anthropic-ai/claude-agent-sdk": "^0.3.148",
91
+ "@anthropic-ai/sdk": "^0.98.0",
92
92
  "@elysiajs/cors": "^1.4.0",
93
- "@github/copilot-sdk": "^0.3.0",
93
+ "@github/copilot-sdk": "^1.0.0-beta.4",
94
94
  "@iconify-json/lucide": "^1.2.57",
95
95
  "@iconify-json/material-icon-theme": "^1.2.16",
96
- "@modelcontextprotocol/sdk": "^1.26.0",
96
+ "@modelcontextprotocol/sdk": "^1.29.0",
97
97
  "@monaco-editor/loader": "^1.5.0",
98
- "@openai/codex-sdk": "^0.125.0",
99
- "@opencode-ai/sdk": "^1.4.8",
98
+ "@openai/codex-sdk": "^0.133.0",
99
+ "@opencode-ai/sdk": "^1.15.7",
100
100
  "@qwen-code/sdk": "^0.1.7",
101
101
  "@xterm/addon-clipboard": "^0.2.0",
102
102
  "@xterm/addon-fit": "^0.11.0",
@@ -108,6 +108,7 @@
108
108
  "@xterm/xterm": "^6.0.0",
109
109
  "bun-pty": "^0.4.2",
110
110
  "elysia": "^1.4.19",
111
+ "fflate": "^0.8.3",
111
112
  "file-type": "^21.0.0",
112
113
  "is-text-path": "^3.0.0",
113
114
  "marked": "^16.1.1",
@@ -180,7 +180,9 @@ export type CommitMessageFormat = 'single-line' | 'multi-line';
180
180
  /** Structured commit message output from AI */
181
181
  export interface GeneratedCommitMessage {
182
182
  type: string;
183
- scope: string;
183
+ /** Null when no scope applies — strict-schema engines (Codex) require explicit null over omission. */
184
+ scope: string | null;
184
185
  subject: string;
185
- body: string;
186
+ /** Null for single-line commits — strict-schema engines (Codex) require explicit null over omission. */
187
+ body: string | null;
186
188
  }
@@ -29,6 +29,8 @@ export interface AppSettings {
29
29
  fontSize: number;
30
30
  /** Chat message appearance variant. Default: 'classic'. */
31
31
  chatAppearance: 'classic' | 'compact';
32
+ /** Git diff viewer layout — true = side-by-side (2 columns), false = inline (1 column). Default: true. */
33
+ gitDiffSideBySide: boolean;
32
34
  /** AI commit message generator configuration */
33
35
  commitGenerator: CommitGeneratorSettings;
34
36
  }
@@ -48,4 +50,6 @@ export interface SystemSettings {
48
50
  autoUpdate: boolean;
49
51
  /** Session lifetime in days. Default: 30. */
50
52
  sessionLifetimeDays: number;
53
+ /** Maximum file size (megabytes) for write, upload, zip, and extract operations. Default: 500. */
54
+ maxFileSizeMB: number;
51
55
  }
@@ -122,6 +122,7 @@ export type {
122
122
  SystemInitEvent,
123
123
  McpServerStatus,
124
124
  RateLimitEvent,
125
+ RateLimitType,
125
126
  EngineOutput,
126
127
  StreamEventType,
127
128
  StreamStatus,
@@ -85,12 +85,20 @@ export interface McpServerStatus {
85
85
  status: 'connected' | 'disconnected' | 'error';
86
86
  }
87
87
 
88
+ export type RateLimitType =
89
+ | 'five_hour'
90
+ | 'seven_day'
91
+ | 'seven_day_opus'
92
+ | 'seven_day_sonnet'
93
+ | 'overage';
94
+
88
95
  export interface RateLimitEvent {
89
96
  type: 'rate_limit';
90
97
  sessionId: string;
91
98
  status: 'rejected' | 'allowed_warning';
92
99
  utilization: number;
93
100
  resetsAt: number | null;
101
+ rateLimitType: RateLimitType | null;
94
102
  }
95
103
 
96
104
  // ============================================================
@@ -28,6 +28,7 @@ export type LogLabel =
28
28
  | 'websocket'
29
29
  | 'mcp'
30
30
  | 'notification'
31
+ | 'rate-limit'
31
32
 
32
33
  // Configuration
33
34
  | 'project'
@@ -281,21 +281,20 @@ export class WSRouter<
281
281
 
282
282
  /** Optional auth middleware — called before every route handler */
283
283
  private authMiddleware: ((conn: WSConnection, action: string) => Promise<{ allowed: boolean; error?: string }>) | null = null;
284
+ private rateLimiter: ((conn: WSConnection, action: string) => boolean) | null = null;
284
285
 
285
286
  constructor() {
286
- // Register built-in context management route
287
287
  this.registerContextHandler();
288
288
  }
289
289
 
290
- /**
291
- * Set an auth middleware function that gates all route handlers.
292
- * The middleware receives the connection and action, and returns { allowed, error? }.
293
- * If not allowed, the handler is not called and an auth:error event is sent to the client.
294
- */
295
290
  setAuthMiddleware(fn: (conn: WSConnection, action: string) => Promise<{ allowed: boolean; error?: string }>): void {
296
291
  this.authMiddleware = fn;
297
292
  }
298
293
 
294
+ setRateLimiter(fn: (conn: WSConnection, action: string) => boolean): void {
295
+ this.rateLimiter = fn;
296
+ }
297
+
299
298
  /**
300
299
  * Register built-in ws:set-context handler
301
300
  * Allows frontend to sync user/project context
@@ -628,6 +627,12 @@ export class WSRouter<
628
627
  }
629
628
  // ═══ END AUTH GATE ═══
630
629
 
630
+ // ═══ RATE LIMIT GATE ═══
631
+ if (this.rateLimiter && !this.rateLimiter(conn, action)) {
632
+ return;
633
+ }
634
+ // ═══ END RATE LIMIT GATE ═══
635
+
631
636
  // Check if this is an HTTP route
632
637
  const httpRoute = this.httpRoutes.get(action);
633
638
  if (httpRoute) {
@@ -663,6 +668,12 @@ export class WSRouter<
663
668
  asPlugin(path: string = '/ws') {
664
669
  return (app: Elysia) => {
665
670
  return app.ws(path, {
671
+ // Allow large binary frames (file uploads, zip extracts).
672
+ // Bun/uWS default is 16MB which trips EPIPE on the dev proxy
673
+ // long before the configurable per-file limit kicks in.
674
+ maxPayloadLength: 1024 * 1024 * 1024, // 1 GiB
675
+ // Disable inactivity disconnects during long binary transfers.
676
+ idleTimeout: 960, // seconds (max allowed by uWS)
666
677
  message: (conn, message) => {
667
678
  this.handleMessage(conn, message);
668
679
  },
@@ -1,111 +0,0 @@
1
- /**
2
- * Copilot Session Fork (workaround)
3
- *
4
- * The Copilot SDK does not yet expose a native `forkSession()` API
5
- * (tracking issues: github/copilot-cli#1313, #1697, #2058). To support our
6
- * multi-branch checkpoints feature — which lets the user replay an earlier
7
- * point in the conversation as a sibling branch — we replicate the SDK's
8
- * own recommended workaround: copy the on-disk session state directory to
9
- * a fresh ID and patch the embedded session identifiers.
10
- *
11
- * On-disk layout (`~/.copilot/session-state/<sessionId>/`):
12
- * ├── workspace.yaml — first line is `id: <sessionId>`
13
- * ├── events.jsonl — first event is `session.start { data.sessionId }`
14
- * ├── checkpoints/
15
- * ├── files/
16
- * └── research/
17
- *
18
- * Both `workspace.yaml#id` and the first `events.jsonl` line's
19
- * `data.sessionId` must be rewritten to the new ID so that resume picks the
20
- * fork up as an independent session.
21
- *
22
- * TODO: When @github/copilot-sdk gains a native `forkSession()` (or an
23
- * equivalent like `client.session.fork()`), delete this helper and switch
24
- * `CopilotEngine.streamQuery` to use the SDK API directly — the same way
25
- * the Claude adapter passes `forkSession: true` and the OpenCode adapter
26
- * calls `client.session.fork({ path: { id } })`.
27
- */
28
-
29
- import fs from 'node:fs';
30
- import path from 'node:path';
31
- import os from 'node:os';
32
- import { debug } from '$shared/utils/logger';
33
-
34
- const SESSION_STATE_DIR = path.join(os.homedir(), '.copilot', 'session-state');
35
-
36
- export function getSessionStatePath(sessionId: string): string {
37
- return path.join(SESSION_STATE_DIR, sessionId);
38
- }
39
-
40
- export function sessionStateExists(sessionId: string): boolean {
41
- return fs.existsSync(getSessionStatePath(sessionId));
42
- }
43
-
44
- /**
45
- * Copy `sourceSessionId`'s state directory to `forkSessionId` and patch the
46
- * session identifiers stored inside. Returns true on success, false if the
47
- * source directory is missing (caller should fall back to a fresh session).
48
- *
49
- * The destination is removed first if it already exists so a re-fork from
50
- * the same source produces a clean copy.
51
- */
52
- export function forkCopilotSessionState(sourceSessionId: string, forkSessionId: string): boolean {
53
- const srcDir = getSessionStatePath(sourceSessionId);
54
- const dstDir = getSessionStatePath(forkSessionId);
55
-
56
- if (!fs.existsSync(srcDir)) {
57
- debug.warn('engine', `Copilot fork: source session ${sourceSessionId} not found on disk`);
58
- return false;
59
- }
60
-
61
- if (fs.existsSync(dstDir)) {
62
- fs.rmSync(dstDir, { recursive: true, force: true });
63
- }
64
-
65
- fs.cpSync(srcDir, dstDir, { recursive: true });
66
- patchWorkspaceYaml(dstDir, forkSessionId);
67
- patchEventsJsonl(dstDir, forkSessionId);
68
-
69
- debug.log('engine', `Copilot fork: ${sourceSessionId} → ${forkSessionId}`);
70
- return true;
71
- }
72
-
73
- /**
74
- * Replace the `id:` field at the top of workspace.yaml with the fork ID.
75
- * The file is a small YAML map written by the SDK with one key per line, so
76
- * a targeted regex replace is safer than parsing & re-serialising YAML
77
- * (which would lose comments / formatting).
78
- */
79
- function patchWorkspaceYaml(dstDir: string, forkSessionId: string): void {
80
- const wsPath = path.join(dstDir, 'workspace.yaml');
81
- if (!fs.existsSync(wsPath)) return;
82
-
83
- const original = fs.readFileSync(wsPath, 'utf-8');
84
- const patched = original.replace(/^id:\s*.*$/m, `id: ${forkSessionId}`);
85
- fs.writeFileSync(wsPath, patched);
86
- }
87
-
88
- /**
89
- * Rewrite `data.sessionId` on the first line of events.jsonl (the
90
- * `session.start` event) so the SDK's resume path treats this directory
91
- * as the fork's own history.
92
- */
93
- function patchEventsJsonl(dstDir: string, forkSessionId: string): void {
94
- const evPath = path.join(dstDir, 'events.jsonl');
95
- if (!fs.existsSync(evPath)) return;
96
-
97
- const raw = fs.readFileSync(evPath, 'utf-8');
98
- const newlineIdx = raw.indexOf('\n');
99
- const firstLine = newlineIdx === -1 ? raw : raw.slice(0, newlineIdx);
100
- const rest = newlineIdx === -1 ? '' : raw.slice(newlineIdx);
101
-
102
- try {
103
- const parsed = JSON.parse(firstLine) as { data?: { sessionId?: string } };
104
- if (parsed?.data) {
105
- parsed.data.sessionId = forkSessionId;
106
- fs.writeFileSync(evPath, JSON.stringify(parsed) + rest);
107
- }
108
- } catch (err) {
109
- debug.warn('engine', `Copilot fork: failed to patch events.jsonl session.start (non-fatal):`, err);
110
- }
111
- }
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/main-DiDuzJJh.js","assets/main-N1w7Llvp.css"])))=>i.map(i=>d[i]);
2
- import{t as c,a as h,d,b as m,c as S,_ as p,o as P}from"./main-DiDuzJJh.js";class v{projectContexts=new Map;currentProjectId=null;constructor(){}getOrCreateProjectContext(e,s){let t=this.projectContexts.get(e);return t||(t={projectId:e,projectPath:s,sessionIds:[],activeSessionId:null,lastActiveAt:new Date,sessionOutputs:new Map,sessionCommandHistories:new Map},this.projectContexts.set(e,t),this.persistContexts()),t}async switchToProject(e,s){this.currentProjectId&&this.currentProjectId!==e&&(await this.saveCurrentProjectState(),await this.hideProjectTerminalSessions(this.currentProjectId));const t=this.getOrCreateProjectContext(e,s);this.currentProjectId!==e&&c.clearAllSessions(),t.sessionIds.length===0?await this.createProjectTerminalSessions(e,s):await this.showProjectTerminalSessions(t),this.currentProjectId=e,t.lastActiveAt=new Date,this.persistContexts(),await this.checkAndRestoreActiveStreams(e)}async createProjectTerminalSessions(e,s){const t=this.getOrCreateProjectContext(e,s),n=await h.listProjectSessions(e);if(n.length>0){d.log("terminal",`Found ${n.length} existing PTY sessions for project ${e}`),n.sort((r,l)=>r.sessionId.localeCompare(l.sessionId));for(const r of n){const l=r.sessionId.split("-"),f=l[l.length-1]||"1",I={id:r.sessionId,name:`Terminal ${f}`,directory:r.cwd||s,lines:[],commandHistory:[],isActive:!1,createdAt:new Date(r.createdAt),lastUsedAt:new Date(r.lastActivityAt),shellType:"Unknown",terminalBuffer:void 0,projectId:e,projectPath:s};c.addSession(I),m.createSession(r.sessionId,e,s,r.cwd||s),t.sessionIds.push(r.sessionId);const u=r.sessionId.match(/terminal-(\d+)/);u&&c.updateNextSessionId(parseInt(u[1],10)+1)}let o=n[0].sessionId;if(typeof sessionStorage<"u")try{const r=sessionStorage.getItem(`terminal-active-session-${e}`);r&&t.sessionIds.includes(r)&&(o=r)}catch{}t.activeSessionId=o,c.switchToSession(t.activeSessionId),this.persistContexts();return}const i=c.createNewSession(s,s,e),a=c.getSession(i);a&&(a.directory=s),m.createSession(i,e,s,s),t.sessionIds.push(i),t.activeSessionId=i,c.switchToSession(i),this.persistContexts()}async hideProjectTerminalSessions(e){const s=this.projectContexts.get(e);if(s){for(const t of s.sessionIds){const n=m.getSession(t);n&&n.isExecuting&&n.streamId&&S.saveActiveStream(t,n.streamId,n.lastCommand||"",e)}for(const t of s.sessionIds)h.cleanupListeners(t);c.clearAllSessions()}}async showProjectTerminalSessions(e){c.clearAllSessions();const{terminalPersistenceManager:s}=await p(async()=>{const{terminalPersistenceManager:n}=await import("./main-DiDuzJJh.js").then(i=>i.p);return{terminalPersistenceManager:n}},__vite__mapDeps([0,1])),t=s.getAllActiveStreams();if(e.sessionIds.length>0)for(const n of e.sessionIds){const i=n.split("-"),a=i[i.length-1]||"1",o={id:n,name:`Terminal ${a}`,directory:e.projectPath,lines:[],commandHistory:[],isActive:!1,createdAt:new Date,lastUsedAt:new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:e.projectId,projectPath:e.projectPath};let r=!1,l=null;for(const u of t)if(u.projectId===e.projectId){const g=u.sessionId.split("-");if(g[g.length-1]===a){r=!0,l=u;break}}o.lines=[];const f=e.sessionCommandHistories.get(n);f&&(o.commandHistory=f);const I=m.getSession(n);if(I&&(f&&(I.commandHistory=f),o.directory=e.projectPath,(r||I.isExecuting)&&(c.setExecutingState(n,!0),l&&(I.isExecuting=!0,I.streamId=l.streamId,I.lastCommand=l.command))),c.addSession(o),!I||I.projectId!==e.projectId){const u=m.createSession(n,e.projectId,e.projectPath,e.projectPath);r&&l&&(u.isExecuting=!0,u.streamId=l.streamId,u.lastCommand=l.command)}else m.updateSession(n,{projectId:e.projectId,projectPath:e.projectPath,workingDirectory:e.projectPath})}else{const n=c.createNewSession(e.projectPath,e.projectPath,e.projectId);m.createSession(n,e.projectId,e.projectPath,e.projectPath),e.sessionIds.push(n),e.activeSessionId=n}e.activeSessionId&&e.sessionIds.includes(e.activeSessionId)?c.switchToSession(e.activeSessionId):e.sessionIds.length>0&&(e.activeSessionId=e.sessionIds[0],c.switchToSession(e.activeSessionId)),this.persistContexts()}async restoreProjectTerminalSessions(e){for(const s of e.sessionIds){const t=c.getSession(s),n=m.getSession(s);if(!t)if(n)this.restoreSessionToStore(n);else{const i=c.createNewSession(e.projectPath,e.projectPath,e.projectId),a=e.sessionIds.indexOf(s);a!==-1&&(e.sessionIds[a]=i),m.updateSession(i,{projectId:e.projectId,projectPath:e.projectPath}),e.activeSessionId===s&&(e.activeSessionId=i)}}e.activeSessionId?c.switchToSession(e.activeSessionId):e.sessionIds.length>0&&(e.activeSessionId=e.sessionIds[0],c.switchToSession(e.activeSessionId))}restoreSessionToStore(e,s){const t=e.projectPath||e.workingDirectory,n=e.id.split("-"),i=n[n.length-1]||"1",a={id:e.id,name:`Terminal ${i}`,directory:t,lines:[],commandHistory:e.commandHistory||[],isActive:!1,createdAt:e.createdAt||new Date,lastUsedAt:e.lastUsedAt||new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:e.projectId,projectPath:e.projectPath};if(s&&s.sessionOutputs.has(e.id)){const o=s.sessionOutputs.get(e.id);o&&(a.lines=o.map(r=>({content:r.content,type:r.type,timestamp:r.timestamp})))}c.addSession(a)}async saveCurrentProjectState(){if(!this.currentProjectId)return;const e=this.projectContexts.get(this.currentProjectId);if(!e)return;const s=c.activeSessionId;s&&(e.activeSessionId=s);for(const t of e.sessionIds){const n=c.getSession(t);if(n){const i=n.lines.map(o=>({content:o.content,type:o.type,timestamp:o.timestamp||new Date}));e.sessionOutputs.set(t,i);let a=0;for(const o of n.lines)(o.type==="output"||o.type==="error")&&a++;e.sessionOutputs.set(`${t}-metadata`,{outputCount:a}),n.commandHistory&&n.commandHistory.length>0&&e.sessionCommandHistories.set(t,n.commandHistory),m.updateSession(t,{commandHistory:n.commandHistory,workingDirectory:n.directory,projectId:this.currentProjectId,projectPath:e.projectPath})}}this.persistContexts()}saveAllProjectStates(){this.currentProjectId&&this.saveCurrentProjectState();for(const[e,s]of this.projectContexts.entries())if(e!==this.currentProjectId)for(const t of s.sessionIds){const n=m.getSession(t);n&&n.commandHistory&&s.sessionCommandHistories.set(t,n.commandHistory)}this.persistContexts()}addTerminalToCurrentProject(e,s){const t=e||this.currentProjectId;if(!t)return null;let n=this.projectContexts.get(t);if(!n&&s&&(n=this.getOrCreateProjectContext(t,s)),!n)return null;e&&e!==this.currentProjectId&&(this.currentProjectId=e);const i=c.createNewSession(n.projectPath,n.projectPath,t),a=c.getSession(i);return a&&(a.directory=n.projectPath),m.createSession(i,t,n.projectPath,n.projectPath),n.sessionIds.push(i),n.activeSessionId=i,this.persistContexts(),i}async removeTerminalFromCurrentProject(e){if(!this.currentProjectId)return!1;const s=this.projectContexts.get(this.currentProjectId);return!s||s.sessionIds.length<=1?!1:(s.sessionIds=s.sessionIds.filter(t=>t!==e),s.activeSessionId===e&&s.sessionIds.length>0&&(s.activeSessionId=s.sessionIds[0]),await c.closeSession(e),m.removeSession(e),this.persistContexts(),!0)}removeSessionFromContext(e){d.log("terminal",`🗑️ [projectManager] Removing session from context: ${e}`);for(const[s,t]of this.projectContexts.entries()){const n=t.sessionIds.indexOf(e);if(n!==-1){d.log("terminal",`🗑️ [projectManager] Found session in project: ${s}`),d.log("terminal",`🗑️ [projectManager] Sessions before: ${t.sessionIds.join(", ")}`),t.sessionIds.splice(n,1),t.sessionOutputs.delete(e),t.sessionOutputs.delete(`${e}-metadata`),t.sessionCommandHistories.delete(e),t.activeSessionId===e&&(t.activeSessionId=t.sessionIds[0]||null,d.log("terminal",`🗑️ [projectManager] Updated activeSessionId to: ${t.activeSessionId}`)),d.log("terminal",`🗑️ [projectManager] Sessions after: ${t.sessionIds.join(", ")}`),m.removeSession(e),this.persistContexts(),d.log("terminal","🗑️ [projectManager] Context persisted");return}}d.log("terminal","🗑️ [projectManager] Session not found in any project context")}getProjectSessions(e){return this.projectContexts.get(e)?.sessionIds||[]}hasRunningTerminals(e){const s=this.projectContexts.get(e);return s?s.sessionIds.some(t=>m.getSession(t)?.isExecuting||!1):!1}getTerminalCount(e){return this.projectContexts.get(e)?.sessionIds.length||0}persistContexts(){for(const[e,s]of this.projectContexts.entries())for(const t of s.sessionIds){const n=m.getSession(t);n&&n.isExecuting&&n.streamId&&S.saveActiveStream(t,n.streamId,n.lastCommand||"",e)}}loadPersistedContexts(){}clearAll(){this.projectContexts.clear(),this.currentProjectId=null}initialize(){typeof window>"u"||this.setupCollaborativeListeners()}setupCollaborativeListeners(){p(async()=>{const{default:e}=await import("./main-DiDuzJJh.js").then(s=>s.w);return{default:e}},__vite__mapDeps([0,1])).then(({default:e})=>{e.on("terminal:tab-created",s=>{if(d.log("terminal",`📥 Received terminal:tab-created: ${s.sessionId}`),!this.currentProjectId)return;const t=this.projectContexts.get(this.currentProjectId);if(!t)return;if(t.sessionIds.includes(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} already exists locally, skipping`);return}if(c.getSession(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} already in store, skipping`);return}d.log("terminal",`➕ Adding remote terminal tab: ${s.sessionId}`);const i=s.sessionId.split("-"),a=i[i.length-1]||"1",o={id:s.sessionId,name:`Terminal ${a}`,directory:s.currentDirectory,lines:[],commandHistory:[],isActive:!1,createdAt:new Date,lastUsedAt:new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:this.currentProjectId,projectPath:t.projectPath};c.addSession(o),t.sessionIds.push(s.sessionId),m.createSession(s.sessionId,this.currentProjectId,t.projectPath,s.currentDirectory);const r=s.sessionId.match(/terminal-(\d+)/);r&&c.updateNextSessionId(parseInt(r[1],10)+1)}),e.on("terminal:tab-closed",s=>{if(d.log("terminal",`📥 Received terminal:tab-closed: ${s.sessionId}`),!this.currentProjectId)return;const t=this.projectContexts.get(this.currentProjectId);if(!t)return;if(!t.sessionIds.includes(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} not in our context, skipping`);return}if(!c.getSession(s.sessionId)){this.removeSessionFromContext(s.sessionId);return}d.log("terminal",`➖ Removing remote terminal tab: ${s.sessionId}`),this.removeSessionFromContext(s.sessionId),c.removeSessionFromStore(s.sessionId)}),d.log("terminal","✅ Terminal collaborative listeners registered")}),P(()=>{this.validateSessionsAfterReconnect()})}async validateSessionsAfterReconnect(){if(!this.currentProjectId)return;const e=this.projectContexts.get(this.currentProjectId);if(!(!e||e.sessionIds.length===0)){d.log("terminal","Validating terminal sessions after reconnect...");try{const s=await h.listProjectSessions(this.currentProjectId),t=new Set(s.map(i=>i.sessionId)),n=e.sessionIds.filter(i=>!t.has(i));if(n.length===0){d.log("terminal","All terminal sessions still alive after reconnect");return}d.log("terminal",`Found ${n.length} dead terminal session(s) after reconnect, cleaning up`);for(const i of n)this.removeSessionFromContext(i),c.removeSessionFromStore(i),h.cleanupListeners(i);e.sessionIds.length===0&&(d.log("terminal","All terminal sessions dead after reconnect, creating new session"),await this.createProjectTerminalSessions(this.currentProjectId,e.projectPath))}catch(s){d.error("terminal","Failed to validate terminal sessions after reconnect:",s)}}}getProjectIndicator(e){const s=this.projectContexts.get(e);if(!s)return{hasTerminals:!1,runningCount:0,totalCount:0};let t=0;const n=new Set;for(const o of s.sessionIds)if(m.getSession(o)?.isExecuting){const l=o.split("-"),f=l[l.length-1];n.add(f),t++}const i=S.getAllActiveStreams(),a=new Set;for(const o of i)if(!a.has(o.streamId)&&o.projectId===e){const r=o.sessionId.split("-"),l=r[r.length-1];n.has(l)||s.sessionIds.some(I=>{const u=I.split("-");return u[u.length-1]===l})&&(n.add(l),t++),a.add(o.streamId)}return{hasTerminals:s.sessionIds.length>0,runningCount:t,totalCount:s.sessionIds.length}}async checkAndRestoreActiveStreams(e){if(typeof window>"u")return;const s=this.projectContexts.get(e);if(!s)return;const{terminalPersistenceManager:t}=await p(async()=>{const{terminalPersistenceManager:a}=await import("./main-DiDuzJJh.js").then(o=>o.p);return{terminalPersistenceManager:a}},__vite__mapDeps([0,1])),{backgroundTerminalService:n}=await p(async()=>{const{backgroundTerminalService:a}=await import("./main-DiDuzJJh.js").then(o=>o.i);return{backgroundTerminalService:a}},__vite__mapDeps([0,1])),i=t.getAllActiveStreams();for(const a of i)if(a.projectId===e){const o=a.sessionId.split("-"),r=o[o.length-1];for(const l of s.sessionIds){const f=l.split("-");if(f[f.length-1]===r&&m.getSession(l)){m.startExecution(l,a.command,a.streamId),c.setExecutingState(l,!0);break}}}}}const j=new v,T=Object.freeze(Object.defineProperty({__proto__:null,terminalProjectManager:j},Symbol.toStringTag,{value:"Module"})),A=Object.freeze(Object.defineProperty({__proto__:null,terminalPersistenceManager:S,terminalProjectManager:j,terminalService:h,terminalSessionManager:m},Symbol.toStringTag,{value:"Module"}));export{A as i,T as p};