@myrialabs/clopen 0.3.13 → 0.3.15

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 (50) hide show
  1. package/backend/chat/stream-manager.ts +15 -0
  2. package/backend/engine/README.md +16 -1669
  3. package/backend/engine/adapters/claude/message-converter.ts +36 -7
  4. package/backend/engine/adapters/claude/models.ts +219 -4
  5. package/backend/engine/docs/adapter-contract.md +183 -0
  6. package/backend/engine/docs/adding-an-engine.md +150 -0
  7. package/backend/engine/docs/database.md +123 -0
  8. package/backend/engine/docs/frontend-and-chat.md +176 -0
  9. package/backend/engine/docs/lessons-learned.md +715 -0
  10. package/backend/engine/docs/quick-reference.md +36 -0
  11. package/backend/engine/docs/system-tools.md +82 -0
  12. package/backend/engine/docs/websocket-routes.md +240 -0
  13. package/backend/files/file-archive.test.ts +131 -0
  14. package/backend/files/file-archive.ts +89 -28
  15. package/backend/files/file-operations.ts +21 -1
  16. package/backend/files/file-reading.ts +1 -13
  17. package/backend/files/file-watcher.ts +117 -3
  18. package/backend/http/audio.ts +236 -0
  19. package/backend/index.ts +6 -0
  20. package/backend/projects/project-cleanup.ts +1 -1
  21. package/backend/tunnel/cloudflared/index.ts +3 -1
  22. package/backend/tunnel/cloudflared/tunnel.ts +42 -0
  23. package/backend/tunnel/global-tunnel-manager.ts +52 -1
  24. package/backend/utils/ws.ts +9 -0
  25. package/backend/ws/chat/stream.ts +46 -38
  26. package/backend/ws/files/search.ts +5 -2
  27. package/backend/ws/files/watch.ts +48 -19
  28. package/backend/ws/files/write.ts +17 -6
  29. package/dist/assets/main-CYVFcz-a.js +358 -0
  30. package/dist/assets/{main-BqiSLc8F.css → main-DrFILAEB.css} +1 -1
  31. package/dist/audio/alert.ogg +0 -0
  32. package/dist/audio/bell.ogg +0 -0
  33. package/dist/audio/blip.ogg +0 -0
  34. package/dist/audio/chirp.ogg +0 -0
  35. package/dist/audio/cloud.ogg +0 -0
  36. package/dist/audio/glass.ogg +0 -0
  37. package/dist/audio/message.ogg +0 -0
  38. package/dist/audio/sparkle.ogg +0 -0
  39. package/dist/audio/subtle.ogg +0 -0
  40. package/dist/audio/tap.ogg +0 -0
  41. package/dist/audio/woodblock.ogg +0 -0
  42. package/dist/index.html +2 -2
  43. package/package.json +2 -2
  44. package/shared/constants/notification-sounds.ts +31 -0
  45. package/shared/types/stores/settings.ts +4 -0
  46. package/shared/types/unified/index.ts +6 -0
  47. package/shared/types/unified/stream.ts +15 -1
  48. package/shared/types/unified/tool.ts +41 -1
  49. package/dist/assets/main-DOVudc3_.js +0 -354
  50. /package/dist/audio/{notification.ogg → chime.ogg} +0 -0
@@ -1,21 +1,9 @@
1
1
  import { join, extname } from 'path';
2
+ import { readdir } from 'node:fs/promises';
2
3
  import { readFileWithEncoding, isTextFile } from '$shared/utils/file-type-detection';
3
4
 
4
5
  import { debug } from '$shared/utils/logger';
5
6
 
6
- // Bun-compatible readdir implementation (cross-platform)
7
- async function readdir(path: string): Promise<string[]> {
8
- let proc;
9
- if (process.platform === 'win32') {
10
- proc = Bun.spawn(['cmd', '/c', 'dir', '/b', '/a', path], { stdout: 'pipe', stderr: 'ignore' });
11
- } else {
12
- proc = Bun.spawn(['ls', '-1A', path], { stdout: 'pipe', stderr: 'ignore' });
13
- }
14
- const result = await new Response(proc.stdout).text();
15
- // Split and clean up, removing \r characters for Windows compatibility
16
- return result.trim().split(/\r?\n/).map(line => line.trim()).filter(Boolean);
17
- }
18
-
19
7
  // Return types
20
8
  export interface FileTreeNode {
21
9
  name: string;
@@ -82,6 +82,19 @@ interface ProjectWatcher {
82
82
  class FileWatcherManager {
83
83
  private watchers = new Map<string, ProjectWatcher>();
84
84
 
85
+ /**
86
+ * Per-project set of connection ids currently viewing the project.
87
+ * The watcher is a shared singleton per project; it must stay alive while
88
+ * ANY connection is viewing (multi-tab / multi-device) and be torn down
89
+ * only when the last viewer leaves. Reference-counting here avoids the
90
+ * previous bug where one viewer's unwatch killed the watcher for everyone,
91
+ * and where switching projects leaked orphaned watchers.
92
+ */
93
+ private viewers = new Map<string, Set<string>>();
94
+
95
+ /** Projects with an in-flight auto-restart, to avoid overlapping restarts. */
96
+ private restarting = new Set<string>();
97
+
85
98
  /**
86
99
  * Per-project dirty file tracking for snapshot system.
87
100
  * Accumulates changed file relative paths between snapshot captures.
@@ -113,7 +126,51 @@ class FileWatcherManager {
113
126
  }
114
127
 
115
128
  /**
116
- * Start watching a project directory
129
+ * Register a connection as a viewer of a project and ensure a watcher is
130
+ * running. Returns true if the project is being watched after the call.
131
+ */
132
+ async addViewer(connId: string, projectId: string, projectPath: string): Promise<boolean> {
133
+ if (!this.viewers.has(projectId)) {
134
+ this.viewers.set(projectId, new Set());
135
+ }
136
+ this.viewers.get(projectId)!.add(connId);
137
+
138
+ if (this.watchers.has(projectId)) return true;
139
+ return this.startWatching(projectId, projectPath);
140
+ }
141
+
142
+ /**
143
+ * Remove a connection as a viewer of a project. Stops the watcher only when
144
+ * no viewers remain.
145
+ */
146
+ removeViewer(connId: string, projectId: string): void {
147
+ const set = this.viewers.get(projectId);
148
+ if (!set) return;
149
+ set.delete(connId);
150
+ if (set.size === 0) {
151
+ this.viewers.delete(projectId);
152
+ this.stopWatching(projectId);
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Remove a connection from every project it was viewing. Called on hard
158
+ * disconnect (tab close, network drop) where no explicit unwatch arrives.
159
+ */
160
+ removeViewerFromAll(connId: string): void {
161
+ for (const projectId of Array.from(this.viewers.keys())) {
162
+ this.removeViewer(connId, projectId);
163
+ }
164
+ }
165
+
166
+ /** In-flight start promises, to coalesce concurrent start requests. */
167
+ private starting = new Map<string, Promise<boolean>>();
168
+
169
+ /**
170
+ * Start watching a project directory. Concurrent calls for the same project
171
+ * are coalesced: `fs.watch` setup awaits a `stat`, so without this guard two
172
+ * near-simultaneous viewers (e.g. two devices) could each build a watcher and
173
+ * leak one.
117
174
  */
118
175
  async startWatching(projectId: string, projectPath: string): Promise<boolean> {
119
176
  // Already watching this project
@@ -122,6 +179,19 @@ class FileWatcherManager {
122
179
  return true;
123
180
  }
124
181
 
182
+ const inflight = this.starting.get(projectId);
183
+ if (inflight) return inflight;
184
+
185
+ const startPromise = this.doStartWatching(projectId, projectPath);
186
+ this.starting.set(projectId, startPromise);
187
+ try {
188
+ return await startPromise;
189
+ } finally {
190
+ this.starting.delete(projectId);
191
+ }
192
+ }
193
+
194
+ private async doStartWatching(projectId: string, projectPath: string): Promise<boolean> {
125
195
  try {
126
196
  // Normalize path
127
197
  const normalizedPath = normalize(projectPath);
@@ -140,14 +210,16 @@ class FileWatcherManager {
140
210
  }
141
211
  });
142
212
 
143
- // Handle watcher errors
213
+ // Handle watcher errors. fs.watch can fault (and on some platforms go
214
+ // silently deaf) under heavy churn or after sleep/wake — recover by
215
+ // rebuilding the watcher instead of leaving the project stuck stale.
144
216
  watcher.on('error', (error) => {
145
217
  debug.error('file', `Watcher error for project ${projectId}:`, error);
146
- // Try to emit error to clients
147
218
  ws.emit.project(projectId, 'files:watch-error', {
148
219
  projectId,
149
220
  error: error.message || 'File watcher error'
150
221
  });
222
+ this.scheduleRestart(projectId);
151
223
  });
152
224
 
153
225
  // Store watcher instance
@@ -217,6 +289,17 @@ class FileWatcherManager {
217
289
  }
218
290
  }
219
291
 
292
+ /**
293
+ * Fully release a project: drop all viewers and any pending restart, then
294
+ * stop the watcher. Used when a project is removed entirely (not just when a
295
+ * single viewer navigates away).
296
+ */
297
+ releaseProject(projectId: string): void {
298
+ this.viewers.delete(projectId);
299
+ this.restarting.delete(projectId);
300
+ this.stopWatching(projectId);
301
+ }
302
+
220
303
  /**
221
304
  * Check if a project is being watched
222
305
  */
@@ -402,6 +485,37 @@ class FileWatcherManager {
402
485
  }, GIT_DEBOUNCE_MS);
403
486
  }
404
487
 
488
+ /**
489
+ * Schedule a debounced rebuild of a project's watcher after a fault.
490
+ * Guarded so overlapping error events don't spawn multiple restarts.
491
+ */
492
+ private scheduleRestart(projectId: string): void {
493
+ if (this.restarting.has(projectId)) return;
494
+ // Only restart if someone is still viewing the project.
495
+ if (!this.viewers.get(projectId)?.size) return;
496
+ this.restarting.add(projectId);
497
+
498
+ setTimeout(async () => {
499
+ this.restarting.delete(projectId);
500
+ if (!this.viewers.get(projectId)?.size) return;
501
+
502
+ const projectPath = this.watchers.get(projectId)?.projectPath;
503
+ if (!projectPath) return;
504
+
505
+ debug.warn('file', `Restarting faulted watcher for project ${projectId}`);
506
+ this.stopWatching(projectId);
507
+ await this.startWatching(projectId, projectPath);
508
+
509
+ // A faulted watcher may have dropped events while down — nudge clients
510
+ // to reconcile so nothing stays stale.
511
+ ws.emit.project(projectId, 'files:changed', {
512
+ projectId,
513
+ changes: [],
514
+ timestamp: Date.now()
515
+ });
516
+ }, 1000);
517
+ }
518
+
405
519
  /**
406
520
  * Stop all watchers (cleanup)
407
521
  */
@@ -0,0 +1,236 @@
1
+ /**
2
+ * HTTP routes for per-user custom notification sounds.
3
+ *
4
+ * Storage layout: ~/.clopen[-dev]/audio/<userId>/notification.<ext>
5
+ * One file per user — uploading replaces any previous file (including different ext).
6
+ *
7
+ * Auth: `Authorization: Bearer <session-token>` (same token issued by auth:login).
8
+ */
9
+
10
+ import { Elysia } from 'elysia';
11
+ import { join } from 'node:path';
12
+ import { mkdir, readdir, rename, stat, unlink } from 'node:fs/promises';
13
+
14
+ import { debug } from '$shared/utils/logger';
15
+ import { hashToken } from '../auth/tokens';
16
+ import { authQueries } from '../database/queries';
17
+ import { getClopenDir } from '../utils/paths';
18
+ import {
19
+ NOTIFICATION_SOUND_ALLOWED_EXTS,
20
+ NOTIFICATION_SOUND_MAX_BYTES,
21
+ isValidNotificationSoundExt
22
+ } from '$shared/constants/notification-sounds';
23
+
24
+ type AuthIdentity = { userId: string; role: string };
25
+
26
+ function authenticate(request: Request): AuthIdentity {
27
+ const header = request.headers.get('authorization') || request.headers.get('Authorization');
28
+ if (!header || !header.toLowerCase().startsWith('bearer ')) {
29
+ throw Object.assign(new Error('Authorization required'), { status: 401 });
30
+ }
31
+ const token = header.slice(7).trim();
32
+ if (!token) {
33
+ throw Object.assign(new Error('Authorization required'), { status: 401 });
34
+ }
35
+ const session = authQueries.getSessionByTokenHash(hashToken(token));
36
+ if (!session) {
37
+ throw Object.assign(new Error('Invalid session token'), { status: 401 });
38
+ }
39
+ if (new Date(session.expires_at) < new Date()) {
40
+ throw Object.assign(new Error('Session expired'), { status: 401 });
41
+ }
42
+ const user = authQueries.getUserById(session.user_id);
43
+ if (!user) {
44
+ throw Object.assign(new Error('User not found'), { status: 401 });
45
+ }
46
+ authQueries.updateLastActive(session.id);
47
+ return { userId: user.id, role: user.role };
48
+ }
49
+
50
+ function getUserAudioDir(userId: string): string {
51
+ return join(getClopenDir(), 'audio', userId);
52
+ }
53
+
54
+ const EXT_CONTENT_TYPES: Record<string, string> = {
55
+ mp3: 'audio/mpeg',
56
+ ogg: 'audio/ogg',
57
+ wav: 'audio/wav',
58
+ m4a: 'audio/mp4'
59
+ };
60
+
61
+ async function findExistingCustomFile(dir: string): Promise<{ path: string; ext: string } | null> {
62
+ let entries: string[];
63
+ try {
64
+ entries = await readdir(dir);
65
+ } catch {
66
+ return null;
67
+ }
68
+ for (const ext of NOTIFICATION_SOUND_ALLOWED_EXTS) {
69
+ const name = `notification.${ext}`;
70
+ if (entries.includes(name)) {
71
+ return { path: join(dir, name), ext };
72
+ }
73
+ }
74
+ return null;
75
+ }
76
+
77
+ export const audioRoute = new Elysia()
78
+ .post('/api/audio/upload', async ({ request, query }) => {
79
+ let identity: AuthIdentity;
80
+ try {
81
+ identity = authenticate(request);
82
+ } catch (error) {
83
+ const status = (error as { status?: number }).status ?? 401;
84
+ const message = error instanceof Error ? error.message : 'Unauthorized';
85
+ return new Response(message, { status });
86
+ }
87
+
88
+ const extParam = typeof query.ext === 'string' ? query.ext.toLowerCase() : '';
89
+ const fileSizeParam = typeof query.fileSize === 'string' ? Number(query.fileSize) : NaN;
90
+
91
+ if (!isValidNotificationSoundExt(extParam)) {
92
+ return new Response(
93
+ `Unsupported audio format. Allowed: ${NOTIFICATION_SOUND_ALLOWED_EXTS.join(', ')}`,
94
+ { status: 400 }
95
+ );
96
+ }
97
+ if (!Number.isFinite(fileSizeParam) || fileSizeParam <= 0) {
98
+ return new Response('Invalid fileSize query parameter', { status: 400 });
99
+ }
100
+ if (fileSizeParam > NOTIFICATION_SOUND_MAX_BYTES) {
101
+ return new Response(
102
+ `File too large. Max ${NOTIFICATION_SOUND_MAX_BYTES} bytes (${Math.round(NOTIFICATION_SOUND_MAX_BYTES / 1024)} KB)`,
103
+ { status: 413 }
104
+ );
105
+ }
106
+ if (!request.body) {
107
+ return new Response('Request body is empty', { status: 400 });
108
+ }
109
+
110
+ const userDir = getUserAudioDir(identity.userId);
111
+ await mkdir(userDir, { recursive: true });
112
+
113
+ const finalPath = join(userDir, `notification.${extParam}`);
114
+ const tempPath = `${finalPath}.${crypto.randomUUID()}.partial`;
115
+ const writer = Bun.file(tempPath).writer();
116
+ let written = 0;
117
+
118
+ const cleanupTemp = async () => {
119
+ try { await writer.end(); } catch { /* best-effort */ }
120
+ try { await unlink(tempPath); } catch { /* best-effort */ }
121
+ };
122
+
123
+ try {
124
+ const reader = request.body.getReader();
125
+ while (true) {
126
+ const { done, value } = await reader.read();
127
+ if (done) break;
128
+ if (!value) continue;
129
+ const incoming = value.byteLength;
130
+ if (written + incoming > fileSizeParam) {
131
+ await cleanupTemp();
132
+ return new Response('Received more bytes than declared file size', { status: 400 });
133
+ }
134
+ if (written + incoming > NOTIFICATION_SOUND_MAX_BYTES) {
135
+ await cleanupTemp();
136
+ return new Response('File too large', { status: 413 });
137
+ }
138
+ writer.write(value);
139
+ written += incoming;
140
+ }
141
+
142
+ await writer.end();
143
+
144
+ if (written !== fileSizeParam) {
145
+ await unlink(tempPath).catch(() => {});
146
+ return new Response(`Incomplete upload: received ${written} of ${fileSizeParam} bytes`, {
147
+ status: 400
148
+ });
149
+ }
150
+
151
+ // Remove any previously-uploaded file with a different extension.
152
+ const existing = await findExistingCustomFile(userDir);
153
+ if (existing && existing.path !== finalPath) {
154
+ await unlink(existing.path).catch(() => {});
155
+ }
156
+
157
+ await rename(tempPath, finalPath);
158
+ const stats = await stat(finalPath);
159
+
160
+ return Response.json({
161
+ message: 'Sound uploaded successfully',
162
+ ext: extParam,
163
+ size: stats.size,
164
+ modified: stats.mtime.toISOString()
165
+ });
166
+ } catch (error) {
167
+ await cleanupTemp();
168
+ debug.error('notification', 'HTTP audio upload error:', error);
169
+ const message = error instanceof Error ? error.message : 'Upload failed';
170
+ return new Response(message, { status: 500 });
171
+ }
172
+ })
173
+ .get('/api/audio/custom/meta', async ({ request }) => {
174
+ let identity: AuthIdentity;
175
+ try {
176
+ identity = authenticate(request);
177
+ } catch (error) {
178
+ const status = (error as { status?: number }).status ?? 401;
179
+ const message = error instanceof Error ? error.message : 'Unauthorized';
180
+ return new Response(message, { status });
181
+ }
182
+
183
+ const userDir = getUserAudioDir(identity.userId);
184
+ const existing = await findExistingCustomFile(userDir);
185
+ if (!existing) {
186
+ return Response.json({ exists: false });
187
+ }
188
+ const stats = await stat(existing.path).catch(() => null);
189
+ return Response.json({
190
+ exists: true,
191
+ ext: existing.ext,
192
+ size: stats?.size ?? 0,
193
+ modified: stats?.mtime.toISOString() ?? null
194
+ });
195
+ })
196
+ .get('/api/audio/custom', async ({ request }) => {
197
+ let identity: AuthIdentity;
198
+ try {
199
+ identity = authenticate(request);
200
+ } catch (error) {
201
+ const status = (error as { status?: number }).status ?? 401;
202
+ const message = error instanceof Error ? error.message : 'Unauthorized';
203
+ return new Response(message, { status });
204
+ }
205
+
206
+ const userDir = getUserAudioDir(identity.userId);
207
+ const existing = await findExistingCustomFile(userDir);
208
+ if (!existing) {
209
+ return new Response('No custom sound', { status: 404 });
210
+ }
211
+
212
+ const file = Bun.file(existing.path);
213
+ return new Response(file, {
214
+ headers: {
215
+ 'Content-Type': EXT_CONTENT_TYPES[existing.ext] ?? 'application/octet-stream',
216
+ 'Cache-Control': 'no-cache'
217
+ }
218
+ });
219
+ })
220
+ .delete('/api/audio/custom', async ({ request }) => {
221
+ let identity: AuthIdentity;
222
+ try {
223
+ identity = authenticate(request);
224
+ } catch (error) {
225
+ const status = (error as { status?: number }).status ?? 401;
226
+ const message = error instanceof Error ? error.message : 'Unauthorized';
227
+ return new Response(message, { status });
228
+ }
229
+
230
+ const userDir = getUserAudioDir(identity.userId);
231
+ const existing = await findExistingCustomFile(userDir);
232
+ if (existing) {
233
+ await unlink(existing.path).catch(() => {});
234
+ }
235
+ return Response.json({ message: 'Custom sound removed' });
236
+ });
package/backend/index.ts CHANGED
@@ -32,6 +32,9 @@ import { wsRouter } from './ws';
32
32
  // binary transfers with `write EPIPE`. See backend/http/files-upload.ts.
33
33
  import { filesUploadRoute } from './http/files-upload';
34
34
 
35
+ // HTTP routes for per-user notification sounds (upload / serve / delete).
36
+ import { audioRoute } from './http/audio';
37
+
35
38
  // Import browser preview manager for graceful shutdown
36
39
  import { browserPreviewServiceManager } from './preview';
37
40
 
@@ -100,6 +103,9 @@ const app = new Elysia()
100
103
  // stays on the HTTP path through the Vite dev proxy.
101
104
  .use(filesUploadRoute)
102
105
 
106
+ // Per-user notification sound upload/serve/delete.
107
+ .use(audioRoute)
108
+
103
109
  // Mount WebSocket router (all functionality now via WebSocket)
104
110
  .use(wsRouter.asPlugin('/ws'));
105
111
 
@@ -20,7 +20,7 @@ registerProjectCleanup({
20
20
  registerProjectCleanup({
21
21
  name: 'file-watcher',
22
22
  run: (projectId) => {
23
- fileWatcher.stopWatching(projectId);
23
+ fileWatcher.releaseProject(projectId);
24
24
  }
25
25
  });
26
26
 
@@ -18,5 +18,7 @@ export {
18
18
  type DeleteTunnelOptions,
19
19
  type DeleteTunnelResult,
20
20
  type RouteDnsOptions,
21
- type RouteDnsResult
21
+ type RouteDnsResult,
22
+ type ListTunnelsOptions,
23
+ type TunnelListEntry
22
24
  } from './tunnel';
@@ -106,6 +106,17 @@ export interface RouteDnsResult {
106
106
  output: string;
107
107
  }
108
108
 
109
+ export interface ListTunnelsOptions {
110
+ /** Custom path for the origin certificate */
111
+ origincert?: string;
112
+ }
113
+
114
+ export interface TunnelListEntry {
115
+ id: string;
116
+ name: string;
117
+ connections: unknown[];
118
+ }
119
+
109
120
  type OutputHandler = (output: string, tunnel: CloudflaredTunnel) => void;
110
121
 
111
122
  export class CloudflaredTunnel extends EventEmitter {
@@ -288,6 +299,37 @@ export class CloudflaredTunnel extends EventEmitter {
288
299
  throw new Error(`Failed to route DNS: ${output.trim()}`);
289
300
  }
290
301
 
302
+ /** List all tunnels on the authenticated Cloudflare account. */
303
+ static async listTunnels(options?: ListTunnelsOptions): Promise<TunnelListEntry[]> {
304
+ const args = ['tunnel'];
305
+ if (options?.origincert) args.push('--origincert', options.origincert);
306
+ args.push('list', '--output', 'json');
307
+
308
+ const { output, exitCode } = await CloudflaredTunnel.run(args);
309
+
310
+ if (exitCode !== 0) {
311
+ throw new Error(`Failed to list tunnels: ${output.trim()}`);
312
+ }
313
+
314
+ // cloudflared prints warnings (e.g. outdated-version notice) alongside the
315
+ // JSON array, so isolate the array span before parsing.
316
+ const start = output.indexOf('[');
317
+ const end = output.lastIndexOf(']');
318
+ if (start === -1 || end === -1 || end < start) return [];
319
+
320
+ try {
321
+ const parsed = JSON.parse(output.slice(start, end + 1));
322
+ if (!Array.isArray(parsed)) return [];
323
+ return parsed.map((entry) => ({
324
+ id: String(entry.id),
325
+ name: String(entry.name),
326
+ connections: Array.isArray(entry.connections) ? entry.connections : []
327
+ }));
328
+ } catch {
329
+ return [];
330
+ }
331
+ }
332
+
291
333
  // --- Private helpers ---
292
334
 
293
335
  /** Run a one-shot cloudflared command and collect all output. */
@@ -11,7 +11,7 @@ import { debug } from '$shared/utils/logger';
11
11
  import { existsSync, mkdirSync, renameSync, writeFileSync, unlinkSync, rmSync } from 'fs';
12
12
  import { homedir } from 'os';
13
13
  import { join } from 'path';
14
- import { getTunnelDir } from './tunnel-config';
14
+ import { getTunnelDir, getLocalTunnelConfigs } from './tunnel-config';
15
15
  import type { RemoteTunnelConfig, LocalTunnelConfig } from './tunnel-config';
16
16
  import { resolveCloudflaredBinary, CloudflaredTunnel, CloudflaredMissingError, type LoginHandle } from './cloudflared';
17
17
 
@@ -57,6 +57,11 @@ interface LocalTunnelInstance extends BaseTunnelInstance {
57
57
  const CERT_PATH = join(getTunnelDir(), 'cert.pem');
58
58
  const DEFAULT_CLOUDFLARED_CERT = join(homedir(), '.cloudflared', 'cert.pem');
59
59
 
60
+ function isTunnelNameConflict(error: unknown): boolean {
61
+ const message = error instanceof Error ? error.message : String(error);
62
+ return /tunnel with name already exists/i.test(message);
63
+ }
64
+
60
65
  // --- Manager ---
61
66
 
62
67
  class GlobalTunnelManager {
@@ -395,6 +400,19 @@ class GlobalTunnelManager {
395
400
  async createLocalTunnel(name: string): Promise<{ tunnelId: string; credentialsFile: string }> {
396
401
  this.ensureBinaryAvailable();
397
402
 
403
+ try {
404
+ return await this.runCreateLocalTunnel(name);
405
+ } catch (error) {
406
+ if (!isTunnelNameConflict(error)) throw error;
407
+
408
+ // Name collides on Cloudflare. Auto-recover only when it's a true orphan,
409
+ // then retry once. Anything else surfaces a clear, actionable message.
410
+ await this.resolveTunnelNameConflict(name);
411
+ return await this.runCreateLocalTunnel(name);
412
+ }
413
+ }
414
+
415
+ private async runCreateLocalTunnel(name: string): Promise<{ tunnelId: string; credentialsFile: string }> {
398
416
  // Write credentials directly to our dir (not ~/.cloudflared/)
399
417
  const tunnelBaseDir = getTunnelDir();
400
418
  if (!existsSync(tunnelBaseDir)) {
@@ -415,6 +433,39 @@ class GlobalTunnelManager {
415
433
  return { tunnelId: result.tunnelId, credentialsFile: finalCredentials };
416
434
  }
417
435
 
436
+ /**
437
+ * Handle a "tunnel with name already exists" conflict. A tunnel that exists on
438
+ * Cloudflare but isn't tracked locally and has no active connections is an orphan
439
+ * (usually a half-failed create) and is safe to delete so the create can retry.
440
+ * Everything else throws a clear message instead.
441
+ */
442
+ private async resolveTunnelNameConflict(name: string): Promise<void> {
443
+ let existing;
444
+ try {
445
+ existing = await CloudflaredTunnel.listTunnels({ origincert: CERT_PATH });
446
+ } catch (listError) {
447
+ debug.warn('tunnel', 'Could not list tunnels to resolve name conflict:', listError);
448
+ throw new Error(`A Cloudflare tunnel named "${name}" already exists on your account. Choose a different name, or remove it from the Cloudflare dashboard.`);
449
+ }
450
+
451
+ const match = existing.find((t) => t.name === name);
452
+ if (!match) {
453
+ throw new Error(`A Cloudflare tunnel named "${name}" already exists on your account. Choose a different name, or remove it from the Cloudflare dashboard.`);
454
+ }
455
+
456
+ if (getLocalTunnelConfigs().some((c) => c.tunnelId === match.id)) {
457
+ throw new Error(`A tunnel named "${name}" already exists. Choose a different name, or delete the existing tunnel first.`);
458
+ }
459
+
460
+ if (match.connections.length > 0) {
461
+ throw new Error(`A Cloudflare tunnel named "${name}" already exists and has active connections. Choose a different name, or remove it from the Cloudflare dashboard.`);
462
+ }
463
+
464
+ debug.warn('tunnel', `Orphaned tunnel "${name}" (${match.id}) found on Cloudflare; deleting before recreate`);
465
+ await CloudflaredTunnel.deleteTunnel(match.id, { force: true, origincert: CERT_PATH });
466
+ this.cleanupLocalTunnelFiles(match.id);
467
+ }
468
+
418
469
  async deleteLocalTunnel(tunnelId: string, credentialsFile?: string): Promise<void> {
419
470
  this.ensureBinaryAvailable();
420
471
 
@@ -526,6 +526,15 @@ class WSServer {
526
526
  return this.connectionState.get(id);
527
527
  }
528
528
 
529
+ /**
530
+ * Get the stable connection id for a connection, or null if not registered.
531
+ * Exposed so services (e.g. the file watcher) can reference-count viewers
532
+ * per connection without duplicating room bookkeeping.
533
+ */
534
+ getConnectionId(conn: WSConnection): string | null {
535
+ return this.resolveId(conn);
536
+ }
537
+
529
538
  /**
530
539
  * Set authentication state for a connection.
531
540
  * Called by auth handlers after successful login/setup/invite.