@nocturnium/svelte-ide 1.0.2 → 1.0.4

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 (78) hide show
  1. package/README.md +5 -3
  2. package/dist/components/ai/AIMessageContent.svelte +24 -14
  3. package/dist/components/ai/AIPanel.svelte +22 -0
  4. package/dist/components/editor/CollaborativeEditor.svelte +68 -5
  5. package/dist/components/editor/CollaborativeEditor.svelte.d.ts +14 -0
  6. package/dist/components/editor/ContextLens.svelte +16 -10
  7. package/dist/components/editor/CustomEditor.svelte +52 -33
  8. package/dist/components/editor/CustomEditor.svelte.d.ts +2 -2
  9. package/dist/components/editor/EchoCursorLayer.svelte +43 -11
  10. package/dist/components/editor/Editor.svelte +17 -0
  11. package/dist/components/editor/Editor.svelte.d.ts +9 -0
  12. package/dist/components/editor/EditorPane.svelte +18 -1
  13. package/dist/components/editor/EditorPane.svelte.d.ts +5 -0
  14. package/dist/components/editor/EditorSelections.svelte +27 -11
  15. package/dist/components/editor/EditorSelections.svelte.d.ts +1 -0
  16. package/dist/components/editor/GhostBracketLayer.svelte +38 -25
  17. package/dist/components/editor/core/folding.d.ts +11 -0
  18. package/dist/components/editor/core/folding.js +41 -0
  19. package/dist/components/editor/core/index.d.ts +0 -5
  20. package/dist/components/editor/core/index.js +4 -5
  21. package/dist/components/editor/core/state.d.ts +5 -0
  22. package/dist/components/editor/core/state.js +131 -12
  23. package/dist/components/editor/editor-find.d.ts +1 -0
  24. package/dist/components/editor/editor-find.js +6 -5
  25. package/dist/components/editor/editor-input.d.ts +1 -0
  26. package/dist/components/editor/editor-input.js +4 -1
  27. package/dist/components/editor/editor-scroll.d.ts +1 -0
  28. package/dist/components/editor/editor-scroll.js +2 -1
  29. package/dist/components/editor/index.d.ts +19 -3
  30. package/dist/components/editor/index.js +18 -4
  31. package/dist/components/editor/tokenizer/base.d.ts +1 -25
  32. package/dist/components/editor/tokenizer/base.js +0 -172
  33. package/dist/components/editor/tokenizer/index.d.ts +4 -0
  34. package/dist/components/editor/tokenizer/index.js +1 -1
  35. package/dist/components/editor/tokenizer/languages/html.d.ts +3 -2
  36. package/dist/components/editor/tokenizer/languages/html.js +64 -6
  37. package/dist/components/editor/tokenizer/languages/javascript.d.ts +0 -3
  38. package/dist/components/editor/tokenizer/languages/javascript.js +1 -2
  39. package/dist/components/editor/tokenizer/languages/svelte.d.ts +1 -1
  40. package/dist/components/editor/tokenizer/languages/svelte.js +6 -1
  41. package/dist/components/editor/tokenizer/types.d.ts +0 -28
  42. package/dist/crdt/awareness.d.ts +8 -2
  43. package/dist/crdt/awareness.js +11 -4
  44. package/dist/crdt/document.d.ts +10 -1
  45. package/dist/crdt/document.js +15 -7
  46. package/dist/crdt/index.d.ts +8 -2
  47. package/dist/crdt/index.js +5 -2
  48. package/dist/crdt/undo.d.ts +2 -7
  49. package/dist/crdt/undo.js +1 -8
  50. package/dist/index.d.ts +7 -9
  51. package/dist/index.js +7 -9
  52. package/dist/services/error-handling.d.ts +2 -11
  53. package/dist/services/error-handling.js +15 -4
  54. package/dist/services/lsp-client.d.ts +3 -0
  55. package/dist/services/lsp-client.js +55 -10
  56. package/dist/services/mock-ai.js +1 -1
  57. package/dist/services/optimistic.d.ts +8 -5
  58. package/dist/services/optimistic.js +36 -10
  59. package/dist/services/vfs-client.js +11 -3
  60. package/dist/stores/agents.svelte.js +3 -2
  61. package/dist/stores/ai-persistence.svelte.js +7 -2
  62. package/dist/stores/ai.svelte.js +3 -2
  63. package/dist/stores/collaboration.svelte.d.ts +1 -1
  64. package/dist/stores/collaboration.svelte.js +3 -2
  65. package/dist/stores/editor.svelte.js +29 -5
  66. package/dist/stores/layout.svelte.js +3 -0
  67. package/dist/stores/plugin.svelte.js +9 -3
  68. package/dist/stores/vfs.svelte.js +26 -9
  69. package/dist/styles/theme.css +43 -0
  70. package/dist/types/vfs.d.ts +15 -1
  71. package/dist/types/vfs.js +9 -0
  72. package/dist/utils/language.d.ts +4 -3
  73. package/dist/utils/language.js +8 -18
  74. package/package.json +1 -1
  75. package/dist/components/editor/MinimalEditor.svelte +0 -75
  76. package/dist/components/editor/MinimalEditor.svelte.d.ts +0 -6
  77. package/dist/components/editor/MinimalEditor2.svelte +0 -84
  78. package/dist/components/editor/MinimalEditor2.svelte.d.ts +0 -6
@@ -109,6 +109,7 @@ export class LSPClient {
109
109
  _capabilities = null;
110
110
  reconnectAttempts = 0;
111
111
  reconnectTimeout = null;
112
+ intentionalDisconnect = false;
112
113
  // Document tracking
113
114
  openDocuments = new Map();
114
115
  diagnosticsCache = new Map();
@@ -177,11 +178,24 @@ export class LSPClient {
177
178
  if (this._state !== 'disconnected' && this._state !== 'error') {
178
179
  return;
179
180
  }
181
+ this.intentionalDisconnect = false;
182
+ if (this.reconnectTimeout) {
183
+ clearTimeout(this.reconnectTimeout);
184
+ this.reconnectTimeout = null;
185
+ }
186
+ this.cleanupSocket();
180
187
  this.setState('connecting');
181
188
  return new Promise((resolve, reject) => {
182
189
  try {
183
- this.ws = new WebSocket(this.config.serverUrl);
184
- this.ws.onopen = async () => {
190
+ const socket = new WebSocket(this.config.serverUrl);
191
+ this.ws = socket;
192
+ socket.onopen = async () => {
193
+ if (socket !== this.ws)
194
+ return;
195
+ if (this.reconnectTimeout) {
196
+ clearTimeout(this.reconnectTimeout);
197
+ this.reconnectTimeout = null;
198
+ }
185
199
  this.reconnectAttempts = 0;
186
200
  this.setState('connected');
187
201
  try {
@@ -192,17 +206,21 @@ export class LSPClient {
192
206
  reject(err);
193
207
  }
194
208
  };
195
- this.ws.onclose = () => {
196
- this.handleDisconnect();
209
+ socket.onclose = () => {
210
+ this.handleDisconnect(socket);
197
211
  };
198
- this.ws.onerror = (_event) => {
212
+ socket.onerror = (_event) => {
213
+ if (socket !== this.ws)
214
+ return;
199
215
  const error = new Error('WebSocket error');
200
216
  this.emitEvent('onError', error);
201
217
  if (this._state === 'connecting') {
202
218
  reject(error);
203
219
  }
204
220
  };
205
- this.ws.onmessage = (event) => {
221
+ socket.onmessage = (event) => {
222
+ if (socket !== this.ws)
223
+ return;
206
224
  this.handleMessage(event.data);
207
225
  };
208
226
  }
@@ -212,7 +230,29 @@ export class LSPClient {
212
230
  }
213
231
  });
214
232
  }
215
- handleDisconnect() {
233
+ cleanupSocket(socket = this.ws) {
234
+ if (!socket)
235
+ return;
236
+ socket.onopen = null;
237
+ socket.onclose = null;
238
+ socket.onerror = null;
239
+ socket.onmessage = null;
240
+ if (socket.readyState !== WebSocket.CLOSING) {
241
+ socket.close();
242
+ }
243
+ if (socket === this.ws) {
244
+ this.ws = null;
245
+ }
246
+ }
247
+ getReconnectDelay(attempt) {
248
+ const baseDelay = this.config.reconnectDelay ?? 1000;
249
+ const exponentialDelay = baseDelay * 2 ** (attempt - 1);
250
+ const jitter = 0.75 + Math.random() * 0.5;
251
+ return Math.round(exponentialDelay * jitter);
252
+ }
253
+ handleDisconnect(socket = this.ws) {
254
+ const wasIntentional = this.intentionalDisconnect;
255
+ this.cleanupSocket(socket);
216
256
  this.setState('disconnected');
217
257
  // Cancel pending requests
218
258
  for (const [_id, pending] of this.pendingRequests) {
@@ -220,11 +260,15 @@ export class LSPClient {
220
260
  pending.reject(new Error('Connection closed'));
221
261
  }
222
262
  this.pendingRequests.clear();
263
+ if (wasIntentional) {
264
+ this.intentionalDisconnect = false;
265
+ return;
266
+ }
223
267
  // Auto-reconnect
224
268
  if (this.config.autoReconnect &&
225
269
  this.reconnectAttempts < (this.config.maxReconnectAttempts ?? 5)) {
226
270
  this.reconnectAttempts++;
227
- const delay = (this.config.reconnectDelay ?? 1000) * this.reconnectAttempts;
271
+ const delay = this.getReconnectDelay(this.reconnectAttempts);
228
272
  if (this.config.debug) {
229
273
  console.log(`[LSP] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);
230
274
  }
@@ -236,6 +280,7 @@ export class LSPClient {
236
280
  }
237
281
  }
238
282
  async disconnect() {
283
+ this.intentionalDisconnect = true;
239
284
  if (this.reconnectTimeout) {
240
285
  clearTimeout(this.reconnectTimeout);
241
286
  this.reconnectTimeout = null;
@@ -251,10 +296,10 @@ export class LSPClient {
251
296
  // Ignore errors during shutdown
252
297
  }
253
298
  }
254
- this.ws.close();
255
- this.ws = null;
299
+ this.cleanupSocket();
256
300
  }
257
301
  this.setState('disconnected');
302
+ this.intentionalDisconnect = false;
258
303
  }
259
304
  // ============================================================================
260
305
  // Initialize
@@ -282,7 +282,7 @@ export function createMockMessage(role, content, options = {}) {
282
282
  ...options,
283
283
  metadata: role === 'assistant'
284
284
  ? {
285
- model: 'claude-3-5-sonnet-mock',
285
+ model: 'nocturnium-demo-mock',
286
286
  tokensUsed: Math.floor(content.length / 4),
287
287
  latencyMs: Math.floor(500 + Math.random() * 1500),
288
288
  ...options.metadata
@@ -6,6 +6,7 @@
6
6
  */
7
7
  export interface OptimisticOperation<T> {
8
8
  id: string;
9
+ scopeKey?: string;
9
10
  type: string;
10
11
  payload: T;
11
12
  timestamp: number;
@@ -53,6 +54,7 @@ type CommitFn<T> = () => Promise<T>;
53
54
  * ```
54
55
  */
55
56
  export declare function optimisticUpdate<T, R>(options: {
57
+ scopeKey?: string;
56
58
  type: string;
57
59
  payload: T;
58
60
  apply: () => void;
@@ -84,6 +86,7 @@ export declare function createOptimisticState<T>(initialValue: T): {
84
86
  * Batch multiple optimistic operations
85
87
  */
86
88
  export declare function batchOptimisticUpdates(operations: Array<{
89
+ scopeKey?: string;
87
90
  type: string;
88
91
  payload: unknown;
89
92
  apply: () => void;
@@ -95,9 +98,9 @@ export declare function batchOptimisticUpdates(operations: Array<{
95
98
  failedCount: number;
96
99
  }>;
97
100
  /**
98
- * Get all pending operations
101
+ * Get pending operations, optionally limited to one document/workspace scope.
99
102
  */
100
- export declare function getPendingOperations(): OptimisticOperation<unknown>[];
103
+ export declare function getPendingOperations(scopeKey?: string): OptimisticOperation<unknown>[];
101
104
  /**
102
105
  * Get operation by ID
103
106
  */
@@ -105,11 +108,11 @@ export declare function getOperation(id: string): OptimisticOperation<unknown> |
105
108
  /**
106
109
  * Cancel a pending operation
107
110
  */
108
- export declare function cancelOperation(id: string): Promise<boolean>;
111
+ export declare function cancelOperation(id: string, scopeKey?: string): Promise<boolean>;
109
112
  /**
110
- * Cancel all pending operations
113
+ * Cancel pending operations, optionally limited to one document/workspace scope.
111
114
  */
112
- export declare function cancelAllOperations(): Promise<void>;
115
+ export declare function cancelAllOperations(scopeKey?: string): Promise<void>;
113
116
  export interface ConflictInfo {
114
117
  type: 'version' | 'lock' | 'concurrent';
115
118
  localVersion?: number;
@@ -4,6 +4,7 @@
4
4
  * Provides utilities for optimistic UI updates with automatic rollback on failure.
5
5
  * Implements a queue-based system for managing pending operations.
6
6
  */
7
+ const DEFAULT_SCOPE_KEY = '__global__';
7
8
  // ============================================================================
8
9
  // Operation Queue
9
10
  // ============================================================================
@@ -38,8 +39,10 @@ const rollbackFunctions = new Map();
38
39
  export async function optimisticUpdate(options) {
39
40
  const { type, payload, apply, rollback, commit, config = {} } = options;
40
41
  const { maxRetries = 3, retryDelay = 1000, onCommit, onRollback, onRetry } = config;
42
+ const scopeKey = options.scopeKey ?? getScopeKeyFromPayload(payload);
41
43
  const operation = {
42
44
  id: crypto.randomUUID(),
45
+ scopeKey,
43
46
  type,
44
47
  payload,
45
48
  timestamp: Date.now(),
@@ -85,7 +88,7 @@ export async function optimisticUpdate(options) {
85
88
  operation.retryCount++;
86
89
  if (operation.retryCount <= maxRetries) {
87
90
  onRetry?.(operation, operation.retryCount);
88
- await delay(retryDelay * operation.retryCount); // Exponential backoff
91
+ await delay(getRetryDelay(retryDelay, operation.retryCount));
89
92
  }
90
93
  }
91
94
  }
@@ -227,10 +230,10 @@ export async function batchOptimisticUpdates(operations, config) {
227
230
  // Queue Management
228
231
  // ============================================================================
229
232
  /**
230
- * Get all pending operations
233
+ * Get pending operations, optionally limited to one document/workspace scope.
231
234
  */
232
- export function getPendingOperations() {
233
- return Array.from(operationQueue.values()).filter((op) => op.status === 'pending');
235
+ export function getPendingOperations(scopeKey) {
236
+ return Array.from(operationQueue.values()).filter((op) => op.status === 'pending' && (!scopeKey || op.scopeKey === scopeKey));
234
237
  }
235
238
  /**
236
239
  * Get operation by ID
@@ -241,9 +244,11 @@ export function getOperation(id) {
241
244
  /**
242
245
  * Cancel a pending operation
243
246
  */
244
- export async function cancelOperation(id) {
247
+ export async function cancelOperation(id, scopeKey) {
245
248
  const operation = operationQueue.get(id);
246
- if (!operation || operation.status !== 'pending') {
249
+ if (!operation ||
250
+ operation.status !== 'pending' ||
251
+ (scopeKey && operation.scopeKey !== scopeKey)) {
247
252
  return false;
248
253
  }
249
254
  const rollback = rollbackFunctions.get(id);
@@ -262,12 +267,12 @@ export async function cancelOperation(id) {
262
267
  return true;
263
268
  }
264
269
  /**
265
- * Cancel all pending operations
270
+ * Cancel pending operations, optionally limited to one document/workspace scope.
266
271
  */
267
- export async function cancelAllOperations() {
268
- const pending = getPendingOperations();
272
+ export async function cancelAllOperations(scopeKey) {
273
+ const pending = getPendingOperations(scopeKey);
269
274
  for (const op of pending) {
270
- await cancelOperation(op.id);
275
+ await cancelOperation(op.id, scopeKey);
271
276
  }
272
277
  }
273
278
  /**
@@ -319,6 +324,27 @@ export function parseConflictDetails(error) {
319
324
  function delay(ms) {
320
325
  return new Promise((resolve) => setTimeout(resolve, ms));
321
326
  }
327
+ function getScopeKeyFromPayload(payload) {
328
+ if (payload && typeof payload === 'object') {
329
+ const candidate = payload;
330
+ if (typeof candidate.scopeKey === 'string')
331
+ return candidate.scopeKey;
332
+ if (typeof candidate.workspaceId === 'string' && typeof candidate.path === 'string') {
333
+ return `${candidate.workspaceId}:${candidate.path}`;
334
+ }
335
+ if (typeof candidate.workspace === 'string' && typeof candidate.path === 'string') {
336
+ return `${candidate.workspace}:${candidate.path}`;
337
+ }
338
+ if (typeof candidate.path === 'string')
339
+ return candidate.path;
340
+ }
341
+ return DEFAULT_SCOPE_KEY;
342
+ }
343
+ function getRetryDelay(baseDelay, attempt) {
344
+ const exponentialDelay = baseDelay * 2 ** (attempt - 1);
345
+ const jitter = 0.75 + Math.random() * 0.5;
346
+ return Math.round(exponentialDelay * jitter);
347
+ }
322
348
  /**
323
349
  * Create a debounced optimistic updater
324
350
  */
@@ -55,7 +55,7 @@ async function request(path, options = {}) {
55
55
  if (err instanceof VFSError)
56
56
  throw err;
57
57
  if (err instanceof Error && err.name === 'AbortError') {
58
- throw new VFSError('Request timeout', 'NETWORK_ERROR');
58
+ throw new VFSError('Request timeout', 'TIMEOUT');
59
59
  }
60
60
  throw new VFSError(err instanceof Error ? err.message : 'Unknown error', 'NETWORK_ERROR', err);
61
61
  }
@@ -65,14 +65,22 @@ async function request(path, options = {}) {
65
65
  }
66
66
  function mapStatusToErrorCode(status) {
67
67
  switch (status) {
68
- case 404:
69
- return 'FILE_NOT_FOUND';
68
+ case 401:
70
69
  case 403:
71
70
  return 'PERMISSION_DENIED';
71
+ case 404:
72
+ return 'FILE_NOT_FOUND';
72
73
  case 409:
73
74
  return 'VERSION_CONFLICT';
74
75
  case 423:
75
76
  return 'FILE_LOCKED';
77
+ case 429:
78
+ return 'RATE_LIMITED';
79
+ case 500:
80
+ case 502:
81
+ case 503:
82
+ case 504:
83
+ return 'SERVER_ERROR';
76
84
  default:
77
85
  return 'NETWORK_ERROR';
78
86
  }
@@ -5,13 +5,14 @@
5
5
  * Note: Svelte 5 modules cannot directly export $derived values.
6
6
  * We use getter functions to expose reactive derived state.
7
7
  */
8
+ import { SvelteMap } from 'svelte/reactivity';
8
9
  const state = $state({
9
- agents: new Map(),
10
+ agents: new SvelteMap(),
10
11
  events: [],
11
12
  maxEvents: 200,
12
13
  activities: [],
13
14
  maxActivities: 500,
14
- cursors: new Map(),
15
+ cursors: new SvelteMap(),
15
16
  selectedAgentId: null,
16
17
  filter: 'all',
17
18
  connected: false,
@@ -3,6 +3,7 @@
3
3
  *
4
4
  * Handles saving and loading AI conversations to IndexedDB/localStorage
5
5
  */
6
+ import { browser } from '$app/environment';
6
7
  const DEFAULT_CONFIG = {
7
8
  dbName: 'svelte-ide-ai',
8
9
  storeName: 'conversations',
@@ -31,7 +32,7 @@ export async function initPersistence(options) {
31
32
  config = { ...DEFAULT_CONFIG, ...options };
32
33
  try {
33
34
  // Check if IndexedDB is available
34
- if (!('indexedDB' in globalThis)) {
35
+ if (!browser || !('indexedDB' in globalThis)) {
35
36
  console.warn('IndexedDB not available, using localStorage fallback');
36
37
  initialized = true;
37
38
  return true;
@@ -52,7 +53,7 @@ export async function initPersistence(options) {
52
53
  */
53
54
  function openDatabase() {
54
55
  return new Promise((resolve, reject) => {
55
- const request = indexedDB.open(config.dbName, config.version);
56
+ const request = globalThis.indexedDB.open(config.dbName, config.version);
56
57
  request.onerror = () => reject(request.error);
57
58
  request.onsuccess = () => resolve(request.result);
58
59
  request.onupgradeneeded = (event) => {
@@ -318,6 +319,8 @@ export async function pruneOldConversations() {
318
319
  }
319
320
  // localStorage helpers
320
321
  function getLocalStorageConversations() {
322
+ if (typeof localStorage === 'undefined')
323
+ return [];
321
324
  try {
322
325
  const data = localStorage.getItem('ai-conversations');
323
326
  return data ? JSON.parse(data) : [];
@@ -327,6 +330,8 @@ function getLocalStorageConversations() {
327
330
  }
328
331
  }
329
332
  function setLocalStorageConversations(conversations) {
333
+ if (typeof localStorage === 'undefined')
334
+ return;
330
335
  try {
331
336
  localStorage.setItem('ai-conversations', JSON.stringify(conversations));
332
337
  }
@@ -5,10 +5,11 @@
5
5
  * Note: Svelte 5 modules cannot directly export $derived values.
6
6
  * We use getter functions to expose reactive derived state.
7
7
  */
8
+ import { SvelteMap } from 'svelte/reactivity';
8
9
  // Default configuration
9
10
  const defaultConfig = {
10
11
  endpoint: '/api/chat',
11
- model: 'claude-3-5-sonnet',
12
+ model: 'nocturnium-demo-mock',
12
13
  systemPrompt: 'You are a helpful coding assistant integrated into an IDE.',
13
14
  tools: [],
14
15
  maxTokens: 4096,
@@ -19,7 +20,7 @@ const defaultConfig = {
19
20
  const state = $state({
20
21
  conversations: [],
21
22
  activeConversationId: null,
22
- tools: new Map(),
23
+ tools: new SvelteMap(),
23
24
  config: { ...defaultConfig },
24
25
  editSessions: [],
25
26
  suggestions: [],
@@ -24,7 +24,7 @@ export declare const config: {
24
24
  readonly current: CollaborationConfig | null;
25
25
  };
26
26
  export declare const status: {
27
- readonly current: "error" | "connected" | "disconnected" | "connecting";
27
+ readonly current: "error" | "disconnected" | "connecting" | "connected";
28
28
  };
29
29
  export declare const error: {
30
30
  readonly current: string | null;
@@ -5,6 +5,7 @@
5
5
  * Note: Svelte 5 modules cannot directly export $derived values.
6
6
  * We use getter functions to expose reactive derived state.
7
7
  */
8
+ import { SvelteMap } from 'svelte/reactivity';
8
9
  // Reactive state
9
10
  const state = $state({
10
11
  config: null,
@@ -12,8 +13,8 @@ const state = $state({
12
13
  error: null,
13
14
  synced: false,
14
15
  users: [],
15
- cursors: new Map(),
16
- awareness: new Map(),
16
+ cursors: new SvelteMap(),
17
+ awareness: new SvelteMap(),
17
18
  aiSessions: [],
18
19
  pendingChanges: [],
19
20
  snapshots: [],
@@ -5,6 +5,7 @@
5
5
  * Note: Svelte 5 modules cannot directly export $derived values.
6
6
  * We use getter functions to expose reactive derived state.
7
7
  */
8
+ import { SvelteMap } from 'svelte/reactivity';
8
9
  import { DEFAULT_EDITOR_PREFERENCES } from '../types';
9
10
  import { detectLanguage } from '../utils/language';
10
11
  // Reactive state using $state rune
@@ -17,6 +18,12 @@ const state = $state({
17
18
  loading: false,
18
19
  error: null
19
20
  });
21
+ // Private saved-content baseline used to compute dirty state without changing
22
+ // the exported EditorTab shape.
23
+ const savedContents = new SvelteMap();
24
+ function isTabDirty(tab) {
25
+ return tab.content !== (savedContents.get(tab.id) ?? tab.content);
26
+ }
20
27
  // Getter functions for derived values (Svelte 5 module-safe)
21
28
  export function getTabs() {
22
29
  return state.tabs;
@@ -122,6 +129,7 @@ export function openFile(path, content, options) {
122
129
  isDirty: false,
123
130
  cursorPosition: { line: 1, column: 1 }
124
131
  };
132
+ savedContents.set(id, content);
125
133
  state.tabs = [...state.tabs, tab];
126
134
  if (options?.focus !== false) {
127
135
  state.activeTabId = id;
@@ -138,10 +146,11 @@ export function closeTab(tabId) {
138
146
  if (index === -1)
139
147
  return false;
140
148
  const tab = state.tabs[index];
141
- if (tab.isDirty) {
149
+ if (isTabDirty(tab)) {
142
150
  // Could prompt for save here - returning false indicates unsaved changes
143
151
  return false;
144
152
  }
153
+ savedContents.delete(tabId);
145
154
  state.tabs = state.tabs.filter((t) => t.id !== tabId);
146
155
  // Update active tab if we closed the active one
147
156
  if (state.activeTabId === tabId) {
@@ -157,6 +166,7 @@ export function forceCloseTab(tabId) {
157
166
  const index = state.tabs.findIndex((t) => t.id === tabId);
158
167
  if (index === -1)
159
168
  return;
169
+ savedContents.delete(tabId);
160
170
  state.tabs = state.tabs.filter((t) => t.id !== tabId);
161
171
  if (state.activeTabId === tabId) {
162
172
  const newIndex = Math.min(index, state.tabs.length - 1);
@@ -167,9 +177,10 @@ export function forceCloseTab(tabId) {
167
177
  * Close all tabs
168
178
  */
169
179
  export function closeAllTabs(force = false) {
170
- if (!force && state.tabs.some((t) => t.isDirty)) {
180
+ if (!force && state.tabs.some(isTabDirty)) {
171
181
  return false;
172
182
  }
183
+ savedContents.clear();
173
184
  state.tabs = [];
174
185
  state.activeTabId = null;
175
186
  return true;
@@ -178,9 +189,14 @@ export function closeAllTabs(force = false) {
178
189
  * Close other tabs (keep the specified one)
179
190
  */
180
191
  export function closeOtherTabs(keepTabId, force = false) {
181
- if (!force && state.tabs.some((t) => t.id !== keepTabId && t.isDirty)) {
192
+ if (!force && state.tabs.some((t) => t.id !== keepTabId && isTabDirty(t))) {
182
193
  return false;
183
194
  }
195
+ for (const tab of state.tabs) {
196
+ if (tab.id !== keepTabId) {
197
+ savedContents.delete(tab.id);
198
+ }
199
+ }
184
200
  state.tabs = state.tabs.filter((t) => t.id === keepTabId);
185
201
  state.activeTabId = keepTabId;
186
202
  return true;
@@ -197,13 +213,21 @@ export function setActiveTab(tabId) {
197
213
  * Update content for a tab
198
214
  */
199
215
  export function updateContent(tabId, content) {
200
- state.tabs = state.tabs.map((t) => t.id === tabId ? { ...t, content, isDirty: t.content !== content || t.isDirty } : t);
216
+ state.tabs = state.tabs.map((t) => t.id === tabId
217
+ ? { ...t, content, isDirty: content !== (savedContents.get(tabId) ?? t.content) }
218
+ : t);
201
219
  }
202
220
  /**
203
221
  * Mark a tab as saved
204
222
  */
205
223
  export function markSaved(tabId, newContent) {
206
- state.tabs = state.tabs.map((t) => t.id === tabId ? { ...t, isDirty: false, content: newContent ?? t.content } : t);
224
+ state.tabs = state.tabs.map((t) => t.id === tabId
225
+ ? (() => {
226
+ const content = newContent ?? t.content;
227
+ savedContents.set(tabId, content);
228
+ return { ...t, isDirty: false, content };
229
+ })()
230
+ : t);
207
231
  }
208
232
  /**
209
233
  * Update cursor position for a tab
@@ -5,6 +5,7 @@
5
5
  * Note: Svelte 5 modules cannot directly export $derived values.
6
6
  * We use getter functions to expose reactive derived state.
7
7
  */
8
+ import { browser } from '$app/environment';
8
9
  // Default sizes
9
10
  const SIDEBAR_DEFAULT_WIDTH = 260;
10
11
  const SIDEBAR_MIN_WIDTH = 180;
@@ -219,6 +220,8 @@ export function toggleStatusBar() {
219
220
  */
220
221
  export function toggleFullScreen() {
221
222
  state.isFullScreen = !state.isFullScreen;
223
+ if (!browser || typeof document === 'undefined')
224
+ return;
222
225
  if (state.isFullScreen) {
223
226
  document.documentElement.requestFullscreen?.();
224
227
  }
@@ -10,12 +10,14 @@
10
10
  * Note: Svelte 5 modules cannot directly export $derived values.
11
11
  * We use getter functions to expose reactive derived state.
12
12
  */
13
+ import { browser } from '$app/environment';
14
+ import { SvelteMap } from 'svelte/reactivity';
13
15
  // Reactive state
14
16
  const state = $state({
15
17
  proposals: [],
16
- instances: new Map(),
17
- commands: new Map(),
18
- panels: new Map(),
18
+ instances: new SvelteMap(),
19
+ commands: new SvelteMap(),
20
+ panels: new SvelteMap(),
19
21
  eventSource: null,
20
22
  connected: false,
21
23
  loadingProposals: false,
@@ -151,6 +153,10 @@ export function connect(endpoint = '/api/plugins/stream') {
151
153
  if (state.eventSource) {
152
154
  state.eventSource.close();
153
155
  }
156
+ if (!browser || typeof EventSource === 'undefined') {
157
+ state.connected = false;
158
+ return;
159
+ }
154
160
  const eventSource = new EventSource(endpoint);
155
161
  eventSource.onopen = () => {
156
162
  state.connected = true;
@@ -6,7 +6,8 @@
6
6
  * We use getter functions to expose reactive derived state.
7
7
  */
8
8
  import * as vfsClient from '../services/vfs-client';
9
- import { SvelteMap } from 'svelte/reactivity';
9
+ import { browser } from '$app/environment';
10
+ import { SvelteMap, SvelteSet } from 'svelte/reactivity';
10
11
  import { parseError, isConflictError, logError } from '../services/error-handling';
11
12
  import { optimisticUpdate } from '../services/optimistic';
12
13
  // Reactive state using $state rune
@@ -14,12 +15,12 @@ const state = $state({
14
15
  workspace: null,
15
16
  workspaceLoading: false,
16
17
  files: [],
17
- fileMap: new Map(),
18
- dirtyFiles: new Set(),
19
- locks: new Map(),
20
- lockStatuses: new Map(),
21
- pendingLocks: new Set(),
22
- activeTransactions: new Map(),
18
+ fileMap: new SvelteMap(),
19
+ dirtyFiles: new SvelteSet(),
20
+ locks: new SvelteMap(),
21
+ lockStatuses: new SvelteMap(),
22
+ pendingLocks: new SvelteSet(),
23
+ activeTransactions: new SvelteMap(),
23
24
  transactionHistory: [],
24
25
  eventSource: null,
25
26
  connected: false,
@@ -30,7 +31,7 @@ const state = $state({
30
31
  errorCode: null,
31
32
  structuredError: null,
32
33
  version: 0,
33
- pendingRetries: new Map(),
34
+ pendingRetries: new SvelteMap(),
34
35
  conflictQueue: []
35
36
  });
36
37
  // Event handlers for SSE
@@ -39,6 +40,7 @@ const eventHandlers = new Map();
39
40
  // Lock TTL refresh intervals
40
41
  // eslint-disable-next-line svelte/prefer-svelte-reactivity -- non-reactive internal timer registry, not UI state
41
42
  const lockRefreshIntervals = new Map(); // path -> intervalId
43
+ let reconnectTimer = null;
42
44
  // Current user ID (set during initialization)
43
45
  let currentUserId = null;
44
46
  // ============================================================================
@@ -496,6 +498,8 @@ export function setLocks(locks) {
496
498
  }
497
499
  }
498
500
  function startLockRefresh(lock) {
501
+ if (!browser || typeof window === 'undefined')
502
+ return;
499
503
  // Refresh at 80% of TTL to ensure we don't lose the lock
500
504
  const refreshInterval = lock.ttl * 0.8;
501
505
  const intervalId = window.setInterval(async () => {
@@ -581,9 +585,17 @@ export function completeTransaction(transactionId, status) {
581
585
  const BASE_RECONNECT_DELAY = 1000;
582
586
  const MAX_RECONNECT_ATTEMPTS = 10;
583
587
  export function connect(workspaceId) {
588
+ if (reconnectTimer) {
589
+ clearTimeout(reconnectTimer);
590
+ reconnectTimer = null;
591
+ }
584
592
  if (state.eventSource) {
585
593
  state.eventSource.close();
586
594
  }
595
+ if (!browser || typeof EventSource === 'undefined') {
596
+ state.connected = false;
597
+ return;
598
+ }
587
599
  const endpoint = `/api/vfs/workspaces/${workspaceId}/stream`;
588
600
  const eventSource = new EventSource(endpoint);
589
601
  eventSource.onopen = () => {
@@ -597,7 +609,8 @@ export function connect(workspaceId) {
597
609
  if (state.reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
598
610
  const delay = BASE_RECONNECT_DELAY * Math.pow(2, state.reconnectAttempts);
599
611
  state.reconnectAttempts++;
600
- setTimeout(() => {
612
+ reconnectTimer = setTimeout(() => {
613
+ reconnectTimer = null;
601
614
  if (!state.connected) {
602
615
  connect(workspaceId);
603
616
  }
@@ -619,6 +632,10 @@ export function connect(workspaceId) {
619
632
  state.eventSource = eventSource;
620
633
  }
621
634
  export function disconnect() {
635
+ if (reconnectTimer) {
636
+ clearTimeout(reconnectTimer);
637
+ reconnectTimer = null;
638
+ }
622
639
  if (state.eventSource) {
623
640
  state.eventSource.close();
624
641
  state.eventSource = null;