diff --git a/.licenserc.yaml b/.licenserc.yaml index 5dfc5e0c..f0eabc55 100644 --- a/.licenserc.yaml +++ b/.licenserc.yaml @@ -2,9 +2,9 @@ header: license: spdx-id: Datalayer copyright-owner: Datalayer, Inc. - copyright-year: 2023-2025 + copyright-year: '' content: | - Copyright (c) [year] [owner] + Copyright (c) 2025-[year] [owner] Distributed under the terms of the MIT License. paths-ignore: diff --git a/Makefile b/Makefile index 2d839088..4d0ffcfb 100755 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. # Copyright (c) Datalayer, Inc. https://datalayer.io @@ -8,7 +8,7 @@ SHELL=/bin/bash .DEFAULT_GOAL := default -.PHONY: docs dev clean build +.PHONY: docs dev example clean build help: ## display this help @awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m\033[0m\n"} /^[a-zA-Z_-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST) @@ -27,6 +27,12 @@ dev: ## dev @exec echo npm run dev +example: ## run examples + @exec echo + @exec echo open http://localhost:3000/split/index.html + @exec echo + npm run dev + publish-npm: clean build ## publish-npm npm publish echo open https://www.npmjs.com/package/@datalayer/lexical-loro diff --git a/README.md b/README.md index 46489e3f..8b633e57 100644 --- a/README.md +++ b/README.md @@ -291,10 +291,10 @@ For complete working examples and demonstrations, see the `src/examples/` direct ```bash # Run the example application npm install -npm run example +make example # This starts both Node.js and Python servers plus a React demo app -# Open http://localhost:5173 to see dual editor interface +# Open http://localhost:3000/split/index.html to see the 2 editors view ``` The examples include: diff --git a/__tests__/setup.ts b/__tests__/setup.ts index 775e44bc..782c2417 100644 --- a/__tests__/setup.ts +++ b/__tests__/setup.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/__tests__/test_BigLoroDoc.ts b/__tests__/test_BigLoroDoc.ts index 12eae0ea..09a0891d 100644 --- a/__tests__/test_BigLoroDoc.ts +++ b/__tests__/test_BigLoroDoc.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/__tests__/test_LexicalNodeData.ts b/__tests__/test_LexicalNodeData.ts index 4ad62e34..01b169c8 100644 --- a/__tests__/test_LexicalNodeData.ts +++ b/__tests__/test_LexicalNodeData.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/__tests__/test_LoroDoc.ts b/__tests__/test_LoroDoc.ts index ed6461f0..d2262690 100644 --- a/__tests__/test_LoroDoc.ts +++ b/__tests__/test_LoroDoc.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/dev/debug-offset.js b/dev/debug-offset.js index c8797be8..4c4510cd 100644 --- a/dev/debug-offset.js +++ b/dev/debug-offset.js @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/dev/debug/debug_container_test.py b/dev/debug/debug_container_test.py index a67fbb57..3b35380f 100644 --- a/dev/debug/debug_container_test.py +++ b/dev/debug/debug_container_test.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. diff --git a/dev/debug/debug_loro_updates.py b/dev/debug/debug_loro_updates.py index 46a43dab..20ca17a1 100644 --- a/dev/debug/debug_loro_updates.py +++ b/dev/debug/debug_loro_updates.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. diff --git a/dev/debug/fix_broadcast_method.py b/dev/debug/fix_broadcast_method.py index 37b1d7fe..b2eb3ca1 100644 --- a/dev/debug/fix_broadcast_method.py +++ b/dev/debug/fix_broadcast_method.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/dev/debug/investigate_loro.py b/dev/debug/investigate_loro.py index ea03f860..78486af7 100644 --- a/dev/debug/investigate_loro.py +++ b/dev/debug/investigate_loro.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. diff --git a/dev/debug/showcase_loro_model.py b/dev/debug/showcase_loro_model.py index 549bfe5d..fbcf3b73 100644 --- a/dev/debug/showcase_loro_model.py +++ b/dev/debug/showcase_loro_model.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/dev/debug_ephemeral_integration.py b/dev/debug_ephemeral_integration.py index 012cd48f..038b4867 100644 --- a/dev/debug_ephemeral_integration.py +++ b/dev/debug_ephemeral_integration.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/dev/debug_loro_api.py b/dev/debug_loro_api.py index 2de89bd2..64f3dd94 100644 --- a/dev/debug_loro_api.py +++ b/dev/debug_loro_api.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/dev/debug_loro_map.py b/dev/debug_loro_map.py index ef06a780..c238d9f2 100644 --- a/dev/debug_loro_map.py +++ b/dev/debug_loro_map.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/dev/debug_mcp_comprehensive.py b/dev/debug_mcp_comprehensive.py index 4c490fb7..6f94a823 100644 --- a/dev/debug_mcp_comprehensive.py +++ b/dev/debug_mcp_comprehensive.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/dev/debug_tree.py b/dev/debug_tree.py index de9e57df..d2005116 100644 --- a/dev/debug_tree.py +++ b/dev/debug_tree.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/dev/debug_tree_structure.py b/dev/debug_tree_structure.py index 06e5026a..a3c4f383 100644 --- a/dev/debug_tree_structure.py +++ b/dev/debug_tree_structure.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/dev/debug_websocket_integration.py b/dev/debug_websocket_integration.py index f76113d8..f44325ac 100644 --- a/dev/debug_websocket_integration.py +++ b/dev/debug_websocket_integration.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/dev/node-server.ts b/dev/node-server.ts index 72ae2de4..e40460f9 100644 --- a/dev/node-server.ts +++ b/dev/node-server.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -35,14 +35,14 @@ class LoroWebSocketServer { } private setupServer(): void { - console.log(`๐Ÿš€ Loro WebSocket server starting on port ${this.port}`); + console.log(`Loro WebSocket server starting on port ${this.port}`); this.wss.on('connection', (ws: WebSocket) => { const clientId = this.generateClientId(); const client: Client = { ws, id: clientId }; this.clients.set(clientId, client); - console.log(`๐Ÿ“ฑ Client ${clientId} connected. Total clients: ${this.clients.size}`); + console.log(`Client ${clientId} connected. Total clients: ${this.clients.size}`); // Send welcome message ws.send(JSON.stringify({ @@ -63,7 +63,7 @@ class LoroWebSocketServer { snapshotHex: hex, docId: 'shared-text' })); - console.log(`๐Ÿ“„ Sent shared-text snapshot to client ${clientId}`); + console.log(`Sent shared-text snapshot to client ${clientId}`); } if (lexicalSnapshot && lexicalSnapshot.length > 0) { @@ -73,7 +73,7 @@ class LoroWebSocketServer { snapshotHex: hex, docId: 'lexical-shared-doc' })); - console.log(`๐Ÿ“„ Sent lexical snapshot to client ${clientId}`); + console.log(`Sent lexical snapshot to client ${clientId}`); } ws.on('message', (data: Buffer) => { @@ -91,7 +91,7 @@ class LoroWebSocketServer { if (updateHex) { this.broadcastToOthers(clientId, { type: 'loro-update', docId, updateHex }); } - console.log(`๐Ÿ”„ Broadcasting Loro update from client ${clientId} to ${this.clients.size - 1} other clients`); + console.log(`Broadcasting Loro update from client ${clientId} to ${this.clients.size - 1} other clients`); } else if (message.type === 'snapshot') { // Store the current document snapshot for new clients const docId = message.docId || 'shared-text'; @@ -104,7 +104,7 @@ class LoroWebSocketServer { } else if (message.snapshot) { this.models.set(docId, new Uint8Array(message.snapshot)); } - console.log(`๐Ÿ“„ Updated snapshot for document ${docId} from client ${clientId}`); + console.log(`Updated snapshot for document ${docId} from client ${clientId}`); } else if (message.type === 'request-snapshot') { // Client is requesting the current snapshot for a specific document const docId = message.docId || 'shared-text'; @@ -113,7 +113,7 @@ class LoroWebSocketServer { if (document && document.length > 0) { const hex = Array.from(document as Uint8Array).map((b: number) => b.toString(16).padStart(2, '0')).join(''); ws.send(JSON.stringify({ type: 'initial-snapshot', snapshotHex: hex, docId })); - console.log(`๐Ÿ“„ Sent requested snapshot for ${docId} to client ${clientId}`); + console.log(`Sent requested snapshot for ${docId} to client ${clientId}`); } else { // No snapshot available, ask other clients to provide one this.broadcastToOthers(clientId, { @@ -121,11 +121,11 @@ class LoroWebSocketServer { requesterId: clientId, docId: docId }); - console.log(`๐Ÿ“ž Requesting snapshot for ${docId} from other clients for ${clientId}`); + console.log(`Requesting snapshot for ${docId} from other clients for ${clientId}`); } } } catch (error) { - console.error('โŒ Error processing message:', error); + console.error('Error processing message:', error); ws.send(JSON.stringify({ type: 'error', message: 'Invalid message format' @@ -135,20 +135,20 @@ class LoroWebSocketServer { ws.on('close', () => { this.clients.delete(clientId); - console.log(`๐Ÿ“ด Client ${clientId} disconnected. Total clients: ${this.clients.size}`); + console.log(`Client ${clientId} disconnected. Total clients: ${this.clients.size}`); }); ws.on('error', (error: Error) => { - console.error(`โŒ WebSocket error for client ${clientId}:`, error); + console.error(`WebSocket error for client ${clientId}:`, error); this.clients.delete(clientId); }); }); this.wss.on('error', (error: Error) => { - console.error('โŒ WebSocket server error:', error); + console.error('WebSocket server error:', error); }); - console.log(`โœ… Loro WebSocket server is running on ws://localhost:${this.port}`); + console.log(`Loro WebSocket server is running on ws://localhost:${this.port}`); } private generateClientId(): string { @@ -161,7 +161,7 @@ class LoroWebSocketServer { try { client.ws.send(JSON.stringify(message)); } catch (error) { - console.error(`โŒ Error sending message to client ${clientId}:`, error); + console.error(`Error sending message to client ${clientId}:`, error); // Remove client if sending fails this.clients.delete(clientId); } @@ -177,7 +177,7 @@ class LoroWebSocketServer { } public close(): void { - console.log('๐Ÿ›‘ Shutting down Loro WebSocket server...'); + console.log('Shutting down Loro WebSocket server...'); this.wss.close(); } } @@ -187,13 +187,13 @@ const server = new LoroWebSocketServer(8080); // Graceful shutdown process.on('SIGINT', () => { - console.log('\n๐Ÿ›‘ Received SIGINT, shutting down gracefully...'); + console.log('\nReceived SIGINT, shutting down gracefully...'); server.close(); process.exit(0); }); process.on('SIGTERM', () => { - console.log('\n๐Ÿ›‘ Received SIGTERM, shutting down gracefully...'); + console.log('\nReceived SIGTERM, shutting down gracefully...'); server.close(); process.exit(0); }); @@ -201,7 +201,7 @@ process.on('SIGTERM', () => { // Log stats every 30 seconds setInterval(() => { const stats = server.getStats(); - console.log(`๐Ÿ“Š Server stats: ${stats.connectedClients} connected clients`); + console.log(`Server stats: ${stats.connectedClients} connected clients`); }, 30000); export default LoroWebSocketServer; diff --git a/dev/simple_server.py b/dev/simple_server.py index 0db099d6..2f8354e9 100644 --- a/dev/simple_server.py +++ b/dev/simple_server.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/eslint.config.js b/eslint.config.js index 32eba8bc..e115e72e 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/esm/index.html b/esm/index.html index 06d3d7b0..a89e18fc 100644 --- a/esm/index.html +++ b/esm/index.html @@ -1,5 +1,5 @@ diff --git a/esm/index.mjs b/esm/index.mjs index ced58d64..eeebf38f 100644 --- a/esm/index.mjs +++ b/esm/index.mjs @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/esm/prepopulatedRichText.mjs b/esm/prepopulatedRichText.mjs index 100df034..6825faf7 100644 --- a/esm/prepopulatedRichText.mjs +++ b/esm/prepopulatedRichText.mjs @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/esm/styles.css b/esm/styles.css index 2b8dc598..562c3b24 100644 --- a/esm/styles.css +++ b/esm/styles.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/examples/collaboration_example.py b/examples/collaboration_example.py index a96c2042..7a77a0c4 100644 --- a/examples/collaboration_example.py +++ b/examples/collaboration_example.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/examples/file_sync_example.py b/examples/file_sync_example.py index 244bd4e2..749d8d2f 100644 --- a/examples/file_sync_example.py +++ b/examples/file_sync_example.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/examples/loro_model_example.py b/examples/loro_model_example.py index 766682fa..1d505f57 100644 --- a/examples/loro_model_example.py +++ b/examples/loro_model_example.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/examples/memory_only_example.py b/examples/memory_only_example.py index 74f989f3..f434defe 100644 --- a/examples/memory_only_example.py +++ b/examples/memory_only_example.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/index.html b/index.html index 35e5566f..520c8744 100644 --- a/index.html +++ b/index.html @@ -1,5 +1,5 @@ diff --git a/lexical_loro/__init__.py b/lexical_loro/__init__.py index f775c89b..7f80451a 100644 --- a/lexical_loro/__init__.py +++ b/lexical_loro/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/lexical_loro/cli.py b/lexical_loro/cli.py index 2454796a..c7c256b0 100644 --- a/lexical_loro/cli.py +++ b/lexical_loro/cli.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ @@ -44,18 +44,18 @@ def main(port: int, host: str, log_level: str, autosave_interval: int): autosave_interval_sec=autosave_interval ) - click.echo(f"๐Ÿš€ Starting Lexical Loro relay server on {host}:{port}") - click.echo(f"๐Ÿ“‹ Log level: {log_level}") - click.echo(f"๐Ÿ’พ Auto-save interval: {autosave_interval} seconds") - click.echo("๐Ÿ“ก Pure WebSocket relay - all operations delegated to LexicalModel") + click.echo(f"Starting Lexical Loro relay server on {host}:{port}") + click.echo(f"Log level: {log_level}") + click.echo(f"Auto-save interval: {autosave_interval} seconds") + click.echo("Pure WebSocket relay - all operations delegated to LexicalModel") click.echo("Press Ctrl+C to stop the server") try: asyncio.run(server.start()) except KeyboardInterrupt: - click.echo("\n๐Ÿ›‘ Server stopped by user") + click.echo("\nServer stopped by user") except Exception as e: - click.echo(f"โŒ Server error: {e}") + click.echo(f"Server error: {e}") raise click.ClickException(str(e)) diff --git a/lexical_loro/client.py b/lexical_loro/client.py index caa2f570..6ca1f9d7 100644 --- a/lexical_loro/client.py +++ b/lexical_loro/client.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. class Client: diff --git a/lexical_loro/constants.py b/lexical_loro/constants.py index 2dc416f3..0a3433f3 100644 --- a/lexical_loro/constants.py +++ b/lexical_loro/constants.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/lexical_loro/mcp/__init__.py b/lexical_loro/mcp/__init__.py index 5f6c0236..afe4e717 100644 --- a/lexical_loro/mcp/__init__.py +++ b/lexical_loro/mcp/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/lexical_loro/mcp/__main__.py b/lexical_loro/mcp/__main__.py index 410fa9c4..161aa2c9 100644 --- a/lexical_loro/mcp/__main__.py +++ b/lexical_loro/mcp/__main__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """Main entry point for the tree-based MCP server.""" diff --git a/lexical_loro/mcp/server.py b/lexical_loro/mcp/server.py index 34078dd1..c35de2ba 100644 --- a/lexical_loro/mcp/server.py +++ b/lexical_loro/mcp/server.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ @@ -217,7 +217,7 @@ async def get_or_create_document_manager() -> TreeDocumentManager: global document_manager, _websocket_base_url if document_manager is None: - logger.debug("๐Ÿ”ง MCP SERVER: Creating TreeDocumentManager...") + logger.debug("MCP server: Creating TreeDocumentManager...") document_manager = TreeDocumentManager( base_path="./documents", websocket_url=_websocket_base_url, @@ -228,16 +228,17 @@ async def get_or_create_document_manager() -> TreeDocumentManager: # Start background tasks in async context await document_manager.start_background_tasks_async() - logger.debug("โœ… MCP SERVER: TreeDocumentManager created") + logger.debug("MCP server: TreeDocumentManager created") return document_manager # Helper function for ensuring document synchronization async def _ensure_document_synced(doc_id: str): """Ensure document is properly synchronized with WebSocket server before reading""" + logger.debug(f"MCP server: Ensuring document sync for {doc_id}") model = document_manager.get_document(doc_id) if not model: - logger.debug(f"๏ฟฝ MCP SERVER: Document {doc_id} not found, creating empty document for WebSocket sync") + logger.debug(f"MCP server: Document {doc_id} not found, creating empty document for WebSocket sync") model = document_manager.create_document_for_websocket_sync(doc_id) # Ensure WebSocket connection for collaborative sync @@ -245,6 +246,10 @@ async def _ensure_document_synced(doc_id: str): # Wait a moment for synchronization await asyncio.sleep(0.5) + logger.debug( + f"MCP server: Document sync complete for {doc_id} " + f"(connected={model.websocket_connected}, initialized={model._is_initialized})" + ) return model @@ -273,20 +278,22 @@ async def get_document(doc_id: str) -> str: # Get existing document or create if not found model = manager.get_document(doc_id) if not model: - logger.debug(f"๐Ÿ“„ MCP SERVER: Document {doc_id} not found, creating empty document for WebSocket sync") + logger.debug(f"MCP server: Document {doc_id} not found, creating empty document for WebSocket sync") # Create empty model without initializing content - let WebSocket populate it model = manager.create_document_for_websocket_sync(doc_id) - logger.debug(f"โœ… MCP SERVER: Empty document created for {doc_id}, now connecting to WebSocket for content") + logger.debug(f"MCP server: Empty document created for {doc_id}, now connecting to WebSocket for content") else: - logger.debug(f"๐Ÿ“„ MCP SERVER: Found existing document: {doc_id}") + logger.debug(f"MCP server: Found existing document: {doc_id}") # Ensure WebSocket connection for collaborative sync - logger.debug(f"๐Ÿ”Œ MCP SERVER: Ensuring WebSocket connection for document: {doc_id}") + logger.debug(f"MCP server: Ensuring WebSocket connection for document: {doc_id}") await _ensure_websocket_connection(model) - logger.debug(f"โœ… MCP SERVER: WebSocket connection established for document: {doc_id}") + logger.debug(f"MCP server: WebSocket connection established for document: {doc_id}") # Convert Loro tree to Lexical JSON format lexical_json = _loro_tree_to_lexical_json(model) + root_children = len(lexical_json.get('root', {}).get('children', [])) + logger.debug(f"MCP server: Returning document {doc_id} with {root_children} root children") result = { "success": True, @@ -333,6 +340,8 @@ async def load_document(doc_id: str) -> str: # Get the lexical data from the model lexical_json = _loro_tree_to_lexical_json(model) + root_children = len(lexical_json.get('root', {}).get('children', [])) + logger.debug(f"MCP server: Loaded document {doc_id} with {root_children} root children") # Format the response result = { @@ -559,45 +568,45 @@ async def append_paragraph(doc_id: str, text: str) -> str: async def _ensure_websocket_connection(model: LoroTreeModel) -> None: """Ensure the model is connected to the WebSocket server for collaborative sync""" try: - logger.debug(f"๐Ÿ” MCP SERVER: Checking WebSocket connection status for doc: {model.doc_id}") - logger.debug(f"๐Ÿ” MCP SERVER: Current websocket_connected status: {model.websocket_connected}") - logger.debug(f"๏ฟฝ MCP SERVER: WebSocket URL: {getattr(model, 'websocket_url', 'Not set')}") + logger.debug(f"MCP server: Checking WebSocket connection status for doc: {model.doc_id}") + logger.debug(f"MCP server: Current websocket_connected status: {model.websocket_connected}") + logger.debug(f"MCP server: WebSocket URL: {getattr(model, 'websocket_url', 'Not set')}") if not model.websocket_connected: - logger.debug(f"๐Ÿ”Œ MCP SERVER: *** INITIATING WEBSOCKET CONNECTION *** for doc: {model.doc_id}") - logger.debug(f"๐Ÿ”Œ MCP SERVER: About to call model.connect_to_websocket_server()...") + logger.debug(f"MCP server: Initiating WebSocket connection for doc: {model.doc_id}") + logger.debug(f"MCP server: About to call model.connect_to_websocket_server()...") await model.connect_to_websocket_server() - logger.debug(f"๐Ÿ”Œ MCP SERVER: connect_to_websocket_server() completed") - logger.debug(f"๐Ÿ”Œ MCP SERVER: New connection status: {model.websocket_connected}") + logger.debug(f"MCP server: connect_to_websocket_server() completed") + logger.debug(f"MCP server: New connection status: {model.websocket_connected}") # Wait a moment for the connection to stabilize and receive snapshot - logger.debug(f"โณ MCP SERVER: Waiting 0.5s for connection to stabilize...") + logger.debug("MCP server: Waiting 0.5s for connection to stabilize") await asyncio.sleep(0.5) - logger.debug(f"โœ… MCP SERVER: *** WEBSOCKET CONNECTION ESTABLISHED *** for doc: {model.doc_id}") - logger.debug(f"โœ… MCP SERVER: Connection status: {model.websocket_connected}") - logger.debug(f"โœ… MCP SERVER: Has WebSocket object: {model.websocket is not None}") - logger.debug(f"โœ… MCP SERVER: Has message listener task: {model._websocket_task is not None}") + logger.debug(f"MCP server: WebSocket connection established for doc: {model.doc_id}") + logger.debug(f"MCP server: Connection status: {model.websocket_connected}") + logger.debug(f"MCP server: Has WebSocket object: {model.websocket is not None}") + logger.debug(f"MCP server: Has message listener task: {model._websocket_task is not None}") # Check if we received initial data if model._is_initialized: - logger.debug(f"๐Ÿ“ฅ MCP SERVER: *** DOCUMENT INITIALIZED *** - {model.doc_id} received initial snapshot data from WebSocket") + logger.debug(f"MCP server: Document initialized from WebSocket snapshot: {model.doc_id}") else: - logger.warning(f"โณ MCP SERVER: *** DOCUMENT NOT INITIALIZED *** - {model.doc_id} connected but no initial snapshot received yet") + logger.warning(f"MCP server: Document not initialized yet after connect: {model.doc_id}") else: - logger.debug(f"๐Ÿ”— MCP SERVER: *** ALREADY CONNECTED *** - Model already connected to WebSocket server for doc: {model.doc_id}") - logger.debug(f"๐Ÿ”— MCP SERVER: Connection details - websocket_connected: {model.websocket_connected}, has_websocket: {model.websocket is not None}") - logger.debug(f"๐Ÿ”— MCP SERVER: REUSING existing connection (PERSISTENT document manager prevents disconnection)") - logger.debug(f"๐Ÿ”— MCP SERVER: Keepalive task running: {model._keepalive_task is not None and not model._keepalive_task.done()}") - logger.debug(f"๐Ÿ”— MCP SERVER: Monitor task running: {model._monitor_task is not None and not model._monitor_task.done()}") + logger.debug(f"MCP server: WebSocket already connected for doc: {model.doc_id}") + logger.debug(f"MCP server: Connection details - websocket_connected: {model.websocket_connected}, has_websocket: {model.websocket is not None}") + logger.debug("MCP server: Reusing existing connection (persistent document manager)") + logger.debug(f"MCP server: Keepalive task running: {model._keepalive_task is not None and not model._keepalive_task.done()}") + logger.debug(f"MCP server: Monitor task running: {model._monitor_task is not None and not model._monitor_task.done()}") except Exception as e: - logger.error(f"โŒ MCP SERVER: *** WEBSOCKET CONNECTION FAILED *** for doc {model.doc_id}: {e}") + logger.error(f"MCP server: WebSocket connection failed for doc {model.doc_id}: {e}") import traceback - logger.error(f"โŒ MCP SERVER: Connection failure traceback: {traceback.format_exc()}") + logger.error(f"MCP server: Connection failure traceback: {traceback.format_exc()}") # Don't raise - allow operations to continue even without collaboration def _loro_tree_to_lexical_json(model: LoroTreeModel) -> Dict[str, Any]: @@ -610,7 +619,7 @@ def _loro_tree_to_lexical_json(model: LoroTreeModel) -> Dict[str, Any]: # Log what MCP server is returning to client root = lexical_json.get('root', {}) children = root.get('children', []) - logger.debug(f"๐Ÿ”„ MCP SERVER RETURNING: Document {model.doc_id} with {len(children)} root children") + logger.debug(f"MCP server RETURNING: Document {model.doc_id} with {len(children)} root children") for i, child in enumerate(children): child_type = child.get('type', 'unknown') child_key = child.get('__key', 'no-key') @@ -620,7 +629,7 @@ def _loro_tree_to_lexical_json(model: LoroTreeModel) -> Dict[str, Any]: text_nodes = [c for c in child_children if c.get('type') == 'text'] if text_nodes: text_preview = f" - '{text_nodes[0].get('text', '')[:50]}'" - logger.debug(f" โ””โ”€ Child[{i}]: {child_type} (key: {child_key}, {len(child_children)} children){text_preview}") + logger.debug(f"Child[{i}]: {child_type} (key: {child_key}, {len(child_children)} children){text_preview}") return lexical_json @@ -656,7 +665,7 @@ async def _add_paragraph_to_tree_at_index(model: LoroTreeModel, text: str, index try: # Capture version vector BEFORE making any changes for incremental updates from_version = model.doc.state_vv - logger.debug(f"๐Ÿ” MCP SERVER: Captured initial version: {from_version}") + logger.debug(f"MCP server: Captured initial version: {from_version}") # Work directly with TreeIDs since we're in a tree-based system tree = model.tree @@ -671,7 +680,7 @@ async def _add_paragraph_to_tree_at_index(model: LoroTreeModel, text: str, index if not root_node: raise ValueError("Cannot find root node in document tree") - logger.debug(f"๐Ÿ“ Adding paragraph to root TreeID: {root_node.id}") + logger.debug(f"Adding paragraph to root TreeID: {root_node.id}") # Get current children count and adjust index existing_children = tree.children(root_node.id) @@ -707,7 +716,7 @@ async def _add_paragraph_to_tree_at_index(model: LoroTreeModel, text: str, index # Commit the changes - the model's local update subscription will handle WebSocket propagation automatically model.doc.commit() - logger.debug(f"โœ… MCP SERVER: Changes committed for doc {model.doc_id} at index {insert_index}") + logger.debug(f"MCP server: Changes committed for doc {model.doc_id} at index {insert_index}") return paragraph_id except Exception as e: @@ -719,7 +728,7 @@ async def _add_paragraph_to_tree(model: LoroTreeModel, text: str): try: # Capture version vector BEFORE making any changes for incremental updates from_version = model.doc.state_vv - logger.debug(f"๐Ÿ” MCP SERVER: Captured initial version: {from_version}") + logger.debug(f"MCP server: Captured initial version: {from_version}") # Work directly with TreeIDs since we're in a tree-based system tree = model.tree @@ -734,7 +743,7 @@ async def _add_paragraph_to_tree(model: LoroTreeModel, text: str): if not root_node: raise ValueError("Cannot find root node in document tree") - logger.debug(f"๐Ÿ“ Adding paragraph to root TreeID: {root_node.id}") + logger.debug(f"Adding paragraph to root TreeID: {root_node.id}") # Get current children count to append at the end existing_children = tree.children(root_node.id) @@ -769,7 +778,7 @@ async def _add_paragraph_to_tree(model: LoroTreeModel, text: str): # Commit the changes - the model's local update subscription will handle WebSocket propagation automatically model.doc.commit() - logger.debug(f"โœ… MCP SERVER: Changes committed for doc {model.doc_id} - model will handle WebSocket propagation via subscription") + logger.debug(f"MCP server: Changes committed for doc {model.doc_id} - model will handle WebSocket propagation via subscription") return paragraph_id except Exception as e: @@ -847,14 +856,14 @@ def start_command( _websocket_base_url = websocket_url # Initialize global document manager with custom path - logger.debug("๐Ÿ”ง MCP SERVER CLI: Initializing document manager...") + logger.debug("MCP server CLI: Initializing document manager...") document_manager = TreeDocumentManager( base_path=documents_path, websocket_url=websocket_url, auto_save_interval=30, max_cached_documents=50 ) - logger.debug("โœ… MCP SERVER CLI: Document manager initialized") + logger.debug("MCP server CLI: Document manager initialized") logger.info(f"Starting Lexical Loro MCP Server with transport: {transport}") logger.info(f"WebSocket base URL: {websocket_url}") diff --git a/lexical_loro/model/__init__.py b/lexical_loro/model/__init__.py index 0d07bb9b..e750ed8a 100644 --- a/lexical_loro/model/__init__.py +++ b/lexical_loro/model/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. from .lexical_loro import LoroTreeModel, TreeEventType diff --git a/lexical_loro/model/document_manager.py b/lexical_loro/model/document_manager.py index ea362b8b..8a4a15f5 100644 --- a/lexical_loro/model/document_manager.py +++ b/lexical_loro/model/document_manager.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/lexical_loro/model/lexical_converter.py b/lexical_loro/model/lexical_converter.py index 13c5c19a..c2f469fd 100644 --- a/lexical_loro/model/lexical_converter.py +++ b/lexical_loro/model/lexical_converter.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ @@ -42,8 +42,8 @@ - Provides CRDT conflict resolution 3. **Bidirectional Conversion**: - - import_from_lexical_state(): JSON โ†’ Tree - - export_to_lexical_state(): Tree โ†’ JSON + - import_from_lexical_state(): JSON -> Tree + - export_to_lexical_state(): Tree -> JSON 4. **Key Management**: - Lexical keys (__key, key, lexicalKey) are stripped during tree storage @@ -449,7 +449,7 @@ def loro_tree_to_lexical_json(doc: LoroDoc, logger=None) -> str: return json.dumps(lexical_state, indent=2) except Exception as e: if logger: - logger.error(f"โŒ [Converter] Error converting Loro tree to Lexical JSON: {e}") + logger.error(f"[Converter] Error converting Loro tree to Lexical JSON: {e}") return json.dumps(INITIAL_LEXICAL_JSON, indent=2) diff --git a/lexical_loro/model/lexical_loro.py b/lexical_loro/model/lexical_loro.py index 25371d04..c170ce41 100644 --- a/lexical_loro/model/lexical_loro.py +++ b/lexical_loro/model/lexical_loro.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ @@ -39,16 +39,16 @@ USAGE PATTERNS: ============== -โœ… Initialization: + Initialization: model = LoroTreeModel(doc_id="doc1", websocket_url="ws://localhost:3002") model.initialize_from_lexical_state(lexical_json) -โœ… Tree Operations: + Tree Operations: model.add_block_to_tree(parent_key, block_data, index) model.update_tree_node(node_key, new_data) model.remove_tree_node(node_key) -โœ… Export: + Export: lexical_state = model.export_to_lexical_state() model.save_document_state(file_path) """ @@ -164,7 +164,7 @@ def initialize_from_lexical_state(self, lexical_state: Union[str, Dict[str, Any] "node_count": len(list(self.tree.nodes())) }) - logger.debug(f"๐Ÿš€ Initialized document {self.doc_id} with root tree ID: {self.root_tree_id}") + logger.debug(f"Initialized document {self.doc_id} with root tree ID: {self.root_tree_id}") # Log initial document structure try: @@ -329,7 +329,7 @@ def add_block_to_tree( "index": index }) - logger.debug(f"โœ๏ธ Added block to tree: {new_key} (type: {block_data['type']}) to parent: {parent_key}") + logger.debug(f"Added block to tree: {new_key} (type: {block_data['type']}) to parent: {parent_key}") # Log document structure after manual addition try: @@ -382,7 +382,7 @@ def update_tree_node(self, node_key: str, new_data: Dict[str, Any]) -> None: "new_data": new_data }) - logger.debug(f"๐Ÿ”„ Updated tree node: {node_key} (type: {new_data.get('type', 'unknown')})") + logger.debug(f"Updated tree node: {node_key} (type: {new_data.get('type', 'unknown')})") # Log document structure after manual update try: @@ -433,7 +433,7 @@ def remove_tree_node(self, node_key: str) -> None: "tree_id": tree_id }) - logger.debug(f"๐Ÿ—‘๏ธ Removed tree node: {node_key}") + logger.debug(f"Removed tree node: {node_key}") # Log document structure after manual removal try: @@ -686,7 +686,7 @@ async def connect_to_websocket_server(self, max_retries: int = 5) -> None: while retry_count <= max_retries: try: document_url = f"{self.websocket_url}/{self.doc_id}" - logger.debug(f"๐Ÿ”Œ LoroTreeModel connecting to {document_url} (attempt {retry_count + 1}/{max_retries + 1})") + logger.debug(f"LoroTreeModel connecting to {document_url} (attempt {retry_count + 1}/{max_retries + 1})") # Connect with aggressive timeout settings to keep connection alive self.websocket = await websockets.connect( @@ -698,42 +698,42 @@ async def connect_to_websocket_server(self, max_retries: int = 5) -> None: compression=None # Disable compression for speed ) self.websocket_connected = True - logger.debug(f"โœ… MCP SERVER: *** WEBSOCKET CONNECTION ESTABLISHED *** for doc: {self.doc_id}") - logger.debug(f"โœ… MCP SERVER: Connected to: {document_url}") + logger.debug(f"MCP server: *** WEBSOCKET CONNECTION ESTABLISHED *** for doc: {self.doc_id}") + logger.debug(f"MCP server: Connected to: {document_url}") # Request initial snapshot - logger.debug(f"๐Ÿ“ž MCP SERVER: *** REQUESTING INITIAL SNAPSHOT *** for doc: {self.doc_id}") + logger.debug(f"MCP server: *** REQUESTING INITIAL SNAPSHOT *** for doc: {self.doc_id}") await self._request_snapshot() - logger.debug(f"๐Ÿ“ž MCP SERVER: Snapshot request sent, waiting for response...") + logger.debug(f"MCP server: Snapshot request sent, waiting for response...") # Start listening for messages - logger.debug(f"๐ŸŽง MCP SERVER: *** STARTING MESSAGE LISTENER *** for doc: {self.doc_id}") + logger.debug(f"MCP server: *** STARTING MESSAGE LISTENER *** for doc: {self.doc_id}") self._websocket_task = asyncio.create_task(self._listen_for_websocket_messages()) - logger.debug(f"๐ŸŽง MCP SERVER: Message listener task created and started") + logger.debug(f"MCP server: Message listener task created and started") # Start keepalive ping to prevent connection timeout - logger.debug(f"๐ŸŽง MCP SERVER: *** STARTING KEEPALIVE PING *** for doc: {self.doc_id}") - logger.debug(f"๐ŸŽง MCP SERVER: About to create keepalive task...") + logger.debug(f"MCP server: *** STARTING KEEPALIVE PING *** for doc: {self.doc_id}") + logger.debug(f"MCP server: About to create keepalive task...") self._keepalive_task = asyncio.create_task(self._keepalive_ping()) - logger.debug(f"๐Ÿ’“ MCP SERVER: *** KEEPALIVE TASK CREATED *** - task object: {self._keepalive_task}") - logger.debug(f"๐Ÿ’“ MCP SERVER: Keepalive task done: {self._keepalive_task.done()}") - logger.debug(f"๐Ÿ’“ MCP SERVER: Keepalive task cancelled: {self._keepalive_task.cancelled()}") + logger.debug(f"MCP server: *** KEEPALIVE TASK CREATED *** - task object: {self._keepalive_task}") + logger.debug(f"MCP server: Keepalive task done: {self._keepalive_task.done()}") + logger.debug(f"MCP server: Keepalive task cancelled: {self._keepalive_task.cancelled()}") # Start connection monitor - logger.debug(f"๐Ÿ” MCP SERVER: *** STARTING CONNECTION MONITOR *** for doc: {self.doc_id}") - logger.debug(f"๐Ÿ” MCP SERVER: About to create monitor task...") + logger.debug(f"MCP server: *** STARTING CONNECTION MONITOR *** for doc: {self.doc_id}") + logger.debug(f"MCP server: About to create monitor task...") self._monitor_task = asyncio.create_task(self._monitor_connection()) - logger.debug(f"๐Ÿ” MCP SERVER: *** MONITOR TASK CREATED *** - task object: {self._monitor_task}") - logger.debug(f"๐Ÿ” MCP SERVER: Monitor task done: {self._monitor_task.done()}") - logger.debug(f"๐Ÿ” MCP SERVER: Monitor task cancelled: {self._monitor_task.cancelled()}") + logger.debug(f"MCP server: *** MONITOR TASK CREATED *** - task object: {self._monitor_task}") + logger.debug(f"MCP server: Monitor task done: {self._monitor_task.done()}") + logger.debug(f"MCP server: Monitor task cancelled: {self._monitor_task.cancelled()}") # Set up local update subscription for automatic propagation - logger.debug(f"๐Ÿ”” MCP SERVER: *** SETTING UP LOCAL UPDATE SUBSCRIPTION *** for doc: {self.doc_id}") + logger.debug(f"MCP server: *** SETTING UP LOCAL UPDATE SUBSCRIPTION *** for doc: {self.doc_id}") self._setup_local_update_subscription() - logger.debug(f"๐Ÿ”” MCP SERVER: Local update subscription configured") + logger.debug(f"MCP server: Local update subscription configured") - logger.debug(f"๐ŸŽฏ MCP SERVER: *** ALL WEBSOCKET SETUP COMPLETE *** for doc: {self.doc_id}") - logger.debug(f"๐ŸŽฏ MCP SERVER: Now ready to receive updates from editor and send updates to WebSocket server") + logger.debug(f"MCP server: *** ALL WEBSOCKET SETUP COMPLETE *** for doc: {self.doc_id}") + logger.debug(f"MCP server: Now ready to receive updates from editor and send updates to WebSocket server") return # Success, exit retry loop except Exception as e: @@ -743,45 +743,45 @@ async def connect_to_websocket_server(self, max_retries: int = 5) -> None: if retry_count <= max_retries: # Calculate exponential backoff delay delay = base_delay * (2 ** (retry_count - 1)) - logger.warning(f"โŒ Failed to connect to WebSocket server (attempt {retry_count}): {e}") - logger.debug(f"๐Ÿ”„ Retrying in {delay:.1f} seconds...") + logger.warning(f"Failed to connect to WebSocket server (attempt {retry_count}): {e}") + logger.debug(f"Retrying in {delay:.1f} seconds...") await asyncio.sleep(delay) else: - logger.error(f"โŒ Failed to connect to WebSocket server after {max_retries + 1} attempts: {e}") - logger.debug("๐Ÿ’ก Make sure the WebSocket server is running on port 3002") + logger.error(f"Failed to connect to WebSocket server after {max_retries + 1} attempts: {e}") + logger.debug("Make sure the WebSocket server is running on port 3002") break async def disconnect_from_websocket_server(self) -> None: """Disconnect from the WebSocket server""" try: - logger.debug(f"๐Ÿงน MCP SERVER: *** TASK CLEANUP STARTING *** for doc: {self.doc_id}") + logger.debug(f"MCP server: *** TASK CLEANUP STARTING *** for doc: {self.doc_id}") if self._websocket_task: - logger.debug(f"๐Ÿงน MCP SERVER: Cancelling websocket task - done: {self._websocket_task.done()}, cancelled: {self._websocket_task.cancelled()}") + logger.debug(f"MCP server: Cancelling websocket task - done: {self._websocket_task.done()}, cancelled: {self._websocket_task.cancelled()}") self._websocket_task.cancel() self._websocket_task = None - logger.debug(f"๐Ÿงน MCP SERVER: Websocket task cancelled and cleared") + logger.debug(f"MCP server: Websocket task cancelled and cleared") if hasattr(self, '_keepalive_task') and self._keepalive_task: - logger.debug(f"๐Ÿงน MCP SERVER: Cancelling keepalive task - done: {self._keepalive_task.done()}, cancelled: {self._keepalive_task.cancelled()}") + logger.debug(f"MCP server: Cancelling keepalive task - done: {self._keepalive_task.done()}, cancelled: {self._keepalive_task.cancelled()}") self._keepalive_task.cancel() self._keepalive_task = None - logger.debug(f"๐Ÿงน MCP SERVER: Keepalive task cancelled and cleared") + logger.debug(f"MCP server: Keepalive task cancelled and cleared") if hasattr(self, '_monitor_task') and self._monitor_task: - logger.debug(f"๐Ÿงน MCP SERVER: Cancelling monitor task - done: {self._monitor_task.done()}, cancelled: {self._monitor_task.cancelled()}") + logger.debug(f"MCP server: Cancelling monitor task - done: {self._monitor_task.done()}, cancelled: {self._monitor_task.cancelled()}") self._monitor_task.cancel() self._monitor_task = None - logger.debug(f"๐Ÿงน MCP SERVER: Monitor task cancelled and cleared") + logger.debug(f"MCP server: Monitor task cancelled and cleared") - logger.debug(f"๐Ÿงน MCP SERVER: *** TASK CLEANUP COMPLETED ***") + logger.debug(f"MCP server: *** TASK CLEANUP COMPLETED ***") if self.websocket: await self.websocket.close() self.websocket = None self.websocket_connected = False - logger.debug(f"๐Ÿ”Œ LoroTreeModel disconnected from WebSocket server for doc: {self.doc_id}") + logger.debug(f"LoroTreeModel disconnected from WebSocket server for doc: {self.doc_id}") except Exception as e: logger.error(f"Error disconnecting from WebSocket server: {e}") @@ -799,157 +799,157 @@ async def _request_snapshot(self) -> None: } await self.websocket.send(json.dumps(message)) - logger.debug(f"๐Ÿ“ธ MCP SERVER: Requested initial snapshot for document: {self.doc_id}") + logger.debug(f"MCP server: Requested initial snapshot for document: {self.doc_id}") except Exception as e: - logger.error(f"โŒ MCP SERVER: Failed to request snapshot for document {self.doc_id}: {e}") + logger.error(f"MCP server: Failed to request snapshot for document {self.doc_id}: {e}") async def _listen_for_websocket_messages(self) -> None: """Listen for messages from the WebSocket server""" if not self.websocket: - logger.warning(f"โš ๏ธ MCP SERVER: Cannot listen for messages - no WebSocket connection for doc: {self.doc_id}") + logger.warning(f"MCP server: Cannot listen for messages - no WebSocket connection for doc: {self.doc_id}") return - logger.debug(f"๐ŸŽง MCP SERVER: *** STARTING WEBSOCKET MESSAGE LISTENER *** for doc: {self.doc_id}") - logger.debug(f"๐ŸŽง MCP SERVER: WebSocket URL: {self.websocket_url}/{self.doc_id}") - logger.debug(f"๐ŸŽง MCP SERVER: Connection object: {self.websocket}") - logger.debug(f"๐ŸŽง MCP SERVER: Connection state: {self.websocket.state if self.websocket else 'None'}") - logger.debug(f"๐ŸŽง MCP SERVER: Thread ID: {threading.get_ident()}") - logger.debug(f"๐ŸŽง MCP SERVER: Async loop: {asyncio.current_task()}") + logger.debug(f"MCP server: *** STARTING WEBSOCKET MESSAGE LISTENER *** for doc: {self.doc_id}") + logger.debug(f"MCP server: WebSocket URL: {self.websocket_url}/{self.doc_id}") + logger.debug(f"MCP server: Connection object: {self.websocket}") + logger.debug(f"MCP server: Connection state: {self.websocket.state if self.websocket else 'None'}") + logger.debug(f"MCP server: Thread ID: {threading.get_ident()}") + logger.debug(f"MCP server: Async loop: {asyncio.current_task()}") try: - logger.debug(f"๐ŸŽง MCP SERVER: *** ENTERING WEBSOCKET LISTEN LOOP *** for doc: {self.doc_id}") - logger.debug(f"๐ŸŽง MCP SERVER: About to start async for loop on websocket messages...") - logger.debug(f"๐ŸŽง MCP SERVER: Loop entry timestamp: {time.time()}") + logger.debug(f"MCP server: *** ENTERING WEBSOCKET LISTEN LOOP *** for doc: {self.doc_id}") + logger.debug(f"MCP server: About to start async for loop on websocket messages...") + logger.debug(f"MCP server: Loop entry timestamp: {time.time()}") message_count = 0 heartbeat_count = 0 last_heartbeat = time.time() # Add a heartbeat to verify the loop is actually running - logger.debug(f"๐Ÿ’— MCP SERVER: *** MESSAGE LISTENER HEARTBEAT #{heartbeat_count} *** - Waiting for messages...") + logger.debug(f"MCP server: *** MESSAGE LISTENER HEARTBEAT #{heartbeat_count} *** - Waiting for messages...") async for message in self.websocket: # Log heartbeat every 5 seconds to confirm listener is alive current_time = time.time() if current_time - last_heartbeat > 5: heartbeat_count += 1 - logger.debug(f"๐Ÿ’— MCP SERVER: *** LISTENER HEARTBEAT #{heartbeat_count} *** - Still listening for doc: {self.doc_id}") + logger.debug(f"MCP server: *** LISTENER HEARTBEAT #{heartbeat_count} *** - Still listening for doc: {self.doc_id}") last_heartbeat = current_time message_count += 1 - logger.debug(f"๐Ÿšจ MCP SERVER: *** WEBSOCKET MESSAGE #{message_count} RECEIVED *** for doc: {self.doc_id}") - logger.debug(f"๐Ÿšจ MCP SERVER: Timestamp: {time.time()}") - logger.debug(f"๐Ÿšจ MCP SERVER: Raw message type: {type(message)}") - logger.debug(f"๐Ÿšจ MCP SERVER: Raw message length: {len(message) if hasattr(message, '__len__') else 'unknown'}") + logger.debug(f"MCP server: *** WEBSOCKET MESSAGE #{message_count} RECEIVED *** for doc: {self.doc_id}") + logger.debug(f"MCP server: Timestamp: {time.time()}") + logger.debug(f"MCP server: Raw message type: {type(message)}") + logger.debug(f"MCP server: Raw message length: {len(message) if hasattr(message, '__len__') else 'unknown'}") if isinstance(message, str): - logger.debug(f"๐Ÿšจ MCP SERVER: String message preview: {message[:100]}{'...' if len(message) > 100 else ''}") + logger.debug(f"MCP server: String message preview: {message[:100]}{'...' if len(message) > 100 else ''}") elif isinstance(message, bytes): - logger.debug(f"๐Ÿšจ MCP SERVER: Binary message preview: {message[:50]}{'...' if len(message) > 50 else ''}") - logger.debug(f"๐Ÿ”” MCP SERVER: *** NEW WEBSOCKET MESSAGE RECEIVED *** for doc: {self.doc_id}") - logger.debug(f"๐Ÿ”” MCP SERVER: Connection status check - websocket_connected: {self.websocket_connected}") - logger.debug(f"๐Ÿ”” MCP SERVER: WebSocket object status: {self.websocket is not None}") - logger.debug(f"๐Ÿ”” MCP SERVER: Message type: {type(message)}, length: {len(message) if hasattr(message, '__len__') else 'unknown'}") + logger.debug(f"MCP server: Binary message preview: {message[:50]}{'...' if len(message) > 50 else ''}") + logger.debug(f"MCP server: *** NEW WEBSOCKET MESSAGE RECEIVED *** for doc: {self.doc_id}") + logger.debug(f"MCP server: Connection status check - websocket_connected: {self.websocket_connected}") + logger.debug(f"MCP server: WebSocket object status: {self.websocket is not None}") + logger.debug(f"MCP server: Message type: {type(message)}, length: {len(message) if hasattr(message, '__len__') else 'unknown'}") try: # Handle both binary and text messages if isinstance(message, bytes): # This is binary Loro snapshot data - logger.debug(f"๐Ÿ“ฅ MCP SERVER: ===== PROCESSING BINARY MESSAGE =====") - logger.debug(f"๐Ÿ“ฅ MCP SERVER: Received BINARY message: {len(message)} bytes for doc: {self.doc_id}") - logger.debug(f"๐Ÿ“ฅ MCP SERVER: Binary data preview: {message[:50]}{'...' if len(message) > 50 else ''}") + logger.debug(f"MCP server: ===== PROCESSING BINARY MESSAGE =====") + logger.debug(f"MCP server: Received BINARY message: {len(message)} bytes for doc: {self.doc_id}") + logger.debug(f"MCP server: Binary data preview: {message[:50]}{'...' if len(message) > 50 else ''}") await self._handle_binary_snapshot(message) - logger.debug(f"โœ… MCP SERVER: ===== BINARY MESSAGE PROCESSED =====") + logger.debug(f"MCP server: ===== BINARY MESSAGE PROCESSED =====") else: # This is JSON text message - logger.debug(f"๐Ÿ“ฅ MCP SERVER: ===== PROCESSING TEXT MESSAGE =====") - logger.debug(f"๐Ÿ“ฅ MCP SERVER: Received TEXT message for doc: {self.doc_id}: {message[:200]}{'...' if len(message) > 200 else ''}") + logger.debug(f"MCP server: ===== PROCESSING TEXT MESSAGE =====") + logger.debug(f"MCP server: Received TEXT message for doc: {self.doc_id}: {message[:200]}{'...' if len(message) > 200 else ''}") data = json.loads(message) - logger.debug(f"๐Ÿ“ฅ MCP SERVER: Parsed JSON data - type: {data.get('type', 'unknown')}") + logger.debug(f"MCP server: Parsed JSON data - type: {data.get('type', 'unknown')}") await self._handle_websocket_message(data) - logger.debug(f"โœ… MCP SERVER: ===== TEXT MESSAGE PROCESSED =====") + logger.debug(f"MCP server: ===== TEXT MESSAGE PROCESSED =====") except json.JSONDecodeError as e: - logger.error(f"โŒ MCP SERVER: Failed to parse WebSocket JSON message for doc {self.doc_id}: {e}") - logger.error(f"โŒ MCP SERVER: Raw message: {message}") + logger.error(f"MCP server: Failed to parse WebSocket JSON message for doc {self.doc_id}: {e}") + logger.error(f"MCP server: Raw message: {message}") except Exception as e: - logger.error(f"โŒ MCP SERVER: Error handling WebSocket message for doc {self.doc_id}: {e}") - logger.error(f"โŒ MCP SERVER: Message type: {type(message)}, content: {message}") + logger.error(f"MCP server: Error handling WebSocket message for doc {self.doc_id}: {e}") + logger.error(f"MCP server: Message type: {type(message)}, content: {message}") import traceback - logger.error(f"โŒ MCP SERVER: Full traceback: {traceback.format_exc()}") + logger.error(f"MCP server: Full traceback: {traceback.format_exc()}") - logger.debug(f"๐Ÿ”” MCP SERVER: *** MESSAGE #{message_count} HANDLING COMPLETE *** for doc: {self.doc_id}") - logger.debug(f"๐Ÿ”” MCP SERVER: Connection still active: {self.websocket_connected}") - logger.debug(f"๐Ÿ”” MCP SERVER: Waiting for next message... (processed {message_count} so far)") + logger.debug(f"MCP server: *** MESSAGE #{message_count} HANDLING COMPLETE *** for doc: {self.doc_id}") + logger.debug(f"MCP server: Connection still active: {self.websocket_connected}") + logger.debug(f"MCP server: Waiting for next message... (processed {message_count} so far)") except websockets.exceptions.ConnectionClosed as e: - logger.error(f"๐Ÿ’” MCP SERVER: *** WEBSOCKET CONNECTION CLOSED *** for doc: {self.doc_id}") - logger.error(f"๐Ÿ’” MCP SERVER: Connection closed exception: {e}") - logger.error(f"๐Ÿ’” MCP SERVER: Connection was closed by server or network issue") - logger.error(f"๐Ÿ’” MCP SERVER: Total messages processed before close: {message_count}") + logger.error(f"MCP server: *** WEBSOCKET CONNECTION CLOSED *** for doc: {self.doc_id}") + logger.error(f"MCP server: Connection closed exception: {e}") + logger.error(f"MCP server: Connection was closed by server or network issue") + logger.error(f"MCP server: Total messages processed before close: {message_count}") self.websocket_connected = False self.websocket = None # Try to reconnect automatically - logger.debug(f"๐Ÿ”„ MCP SERVER: Attempting automatic reconnection...") + logger.debug(f"MCP server: Attempting automatic reconnection...") await self._reconnect_websocket() except Exception as e: - logger.error(f"โŒ MCP SERVER: *** WEBSOCKET LISTENER ERROR *** for doc: {self.doc_id}: {e}") - logger.error(f"โŒ MCP SERVER: Total messages processed before error: {message_count}") + logger.error(f"MCP server: *** WEBSOCKET LISTENER ERROR *** for doc: {self.doc_id}: {e}") + logger.error(f"MCP server: Total messages processed before error: {message_count}") import traceback - logger.error(f"โŒ MCP SERVER: Full error traceback: {traceback.format_exc()}") + logger.error(f"MCP server: Full error traceback: {traceback.format_exc()}") self.websocket_connected = False self.websocket = None # Try to reconnect automatically - logger.debug(f"๐Ÿ”„ MCP SERVER: Attempting reconnection after error...") + logger.debug(f"MCP server: Attempting reconnection after error...") await self._reconnect_websocket() - logger.debug(f"๐Ÿ MCP SERVER: *** WEBSOCKET LISTEN LOOP EXITED *** for doc: {self.doc_id}") - logger.debug(f"๐Ÿ MCP SERVER: Total messages processed: {message_count}") - logger.debug(f"๐Ÿ MCP SERVER: Final connection status: {self.websocket_connected}") - logger.debug(f"๐Ÿ MCP SERVER: Loop exit timestamp: {time.time()}") + logger.debug(f"MCP server: *** WEBSOCKET LISTEN LOOP EXITED *** for doc: {self.doc_id}") + logger.debug(f"MCP server: Total messages processed: {message_count}") + logger.debug(f"MCP server: Final connection status: {self.websocket_connected}") + logger.debug(f"MCP server: Loop exit timestamp: {time.time()}") async def _keepalive_ping(self) -> None: """Send periodic ping to keep WebSocket connection alive""" try: - logger.debug(f"๐Ÿ’“ MCP SERVER: *** KEEPALIVE TASK STARTED *** for doc: {self.doc_id}") - logger.debug(f"๐Ÿ’“ MCP SERVER: Will ping every 5 seconds") - logger.debug(f"๐Ÿ’“ MCP SERVER: Initial connection state: {self.websocket_connected}") - logger.debug(f"๐Ÿ’“ MCP SERVER: Initial WebSocket object: {self.websocket is not None}") + logger.debug(f"MCP server: *** KEEPALIVE TASK STARTED *** for doc: {self.doc_id}") + logger.debug(f"MCP server: Will ping every 5 seconds") + logger.debug(f"MCP server: Initial connection state: {self.websocket_connected}") + logger.debug(f"MCP server: Initial WebSocket object: {self.websocket is not None}") ping_counter = 0 while self.websocket_connected and self.websocket: try: - logger.debug(f"๐Ÿ’“ MCP SERVER: *** KEEPALIVE SLEEP START #{ping_counter + 1} *** - waiting 5 seconds...") + logger.debug(f"MCP server: *** KEEPALIVE SLEEP START #{ping_counter + 1} *** - waiting 5 seconds...") await asyncio.sleep(5) # Ping every 5 seconds (even more frequent) ping_counter += 1 - logger.debug(f"๐Ÿ’“ MCP SERVER: *** KEEPALIVE SLEEP END #{ping_counter} *** - checking connection...") - logger.debug(f"๐Ÿ’“ MCP SERVER: websocket_connected: {self.websocket_connected}") - logger.debug(f"๐Ÿ’“ MCP SERVER: websocket object exists: {self.websocket is not None}") + logger.debug(f"MCP server: *** KEEPALIVE SLEEP END #{ping_counter} *** - checking connection...") + logger.debug(f"MCP server: websocket_connected: {self.websocket_connected}") + logger.debug(f"MCP server: websocket object exists: {self.websocket is not None}") if self.websocket and self.websocket_connected: - logger.debug(f"๐Ÿ’“ MCP SERVER: *** SENDING KEEPALIVE PING #{ping_counter} *** for doc: {self.doc_id}") - logger.debug(f"๐Ÿ’“ MCP SERVER: WebSocket state: {self.websocket.state if hasattr(self.websocket, 'state') else 'unknown'}") - logger.debug(f"๐Ÿ’“ MCP SERVER: Connection status: {self.websocket_connected}") - logger.debug(f"๐Ÿ’“ MCP SERVER: Timestamp: {time.time()}") + logger.debug(f"MCP server: *** SENDING KEEPALIVE PING #{ping_counter} *** for doc: {self.doc_id}") + logger.debug(f"MCP server: WebSocket state: {self.websocket.state if hasattr(self.websocket, 'state') else 'unknown'}") + logger.debug(f"MCP server: Connection status: {self.websocket_connected}") + logger.debug(f"MCP server: Timestamp: {time.time()}") # Try both ping() method and keepalive message try: # First try the WebSocket ping() method with short timeout - logger.debug(f"๐Ÿ’“ MCP SERVER: *** ATTEMPTING WEBSOCKET PING #{ping_counter} *** for doc: {self.doc_id}") - logger.debug(f"๐Ÿ’“ MCP SERVER: Ping timestamp: {time.time()}") - logger.debug(f"๐Ÿ’“ MCP SERVER: WebSocket object: {self.websocket}") - logger.debug(f"๐Ÿ’“ MCP SERVER: WebSocket closed status: {getattr(self.websocket, 'closed', 'unknown')}") + logger.debug(f"MCP server: *** ATTEMPTING WEBSOCKET PING #{ping_counter} *** for doc: {self.doc_id}") + logger.debug(f"MCP server: Ping timestamp: {time.time()}") + logger.debug(f"MCP server: WebSocket object: {self.websocket}") + logger.debug(f"MCP server: WebSocket closed status: {getattr(self.websocket, 'closed', 'unknown')}") pong_waiter = await self.websocket.ping() - logger.debug(f"โœ… MCP SERVER: *** WEBSOCKET PING SENT #{ping_counter} *** - awaiting pong response...") - logger.debug(f"โœ… MCP SERVER: Pong waiter object: {pong_waiter}") + logger.debug(f"MCP server: *** WEBSOCKET PING SENT #{ping_counter} *** - awaiting pong response...") + logger.debug(f"MCP server: Pong waiter object: {pong_waiter}") await asyncio.wait_for(pong_waiter, timeout=2.0) - logger.debug(f"๐ŸŽ‰ MCP SERVER: *** WEBSOCKET PING-PONG SUCCESS #{ping_counter} *** for doc: {self.doc_id}") - logger.debug(f"๐ŸŽ‰ MCP SERVER: Round-trip successful at timestamp: {time.time()}") + logger.debug(f"MCP server: *** WEBSOCKET PING-PONG SUCCESS #{ping_counter} *** for doc: {self.doc_id}") + logger.debug(f"MCP server: Round-trip successful at timestamp: {time.time()}") except asyncio.TimeoutError: - logger.error(f"โš ๏ธ MCP SERVER: *** PING TIMEOUT #{ping_counter} *** after 2s for doc: {self.doc_id}") - logger.error(f"โš ๏ธ MCP SERVER: WebSocket may be unresponsive, trying keepalive message...") + logger.error(f"MCP server: *** PING TIMEOUT #{ping_counter} *** after 2s for doc: {self.doc_id}") + logger.error(f"MCP server: WebSocket may be unresponsive, trying keepalive message...") # Fallback to keepalive message keepalive_msg = { @@ -959,16 +959,16 @@ async def _keepalive_ping(self) -> None: "ping_id": ping_counter, "reason": "ping_timeout_fallback" } - logger.debug(f"๐Ÿ“ค MCP SERVER: *** SENDING KEEPALIVE MESSAGE #{ping_counter} *** for doc: {self.doc_id}") - logger.debug(f"๐Ÿ“ค MCP SERVER: Keepalive message: {keepalive_msg}") + logger.debug(f"MCP server: *** SENDING KEEPALIVE MESSAGE #{ping_counter} *** for doc: {self.doc_id}") + logger.debug(f"MCP server: Keepalive message: {keepalive_msg}") await self.websocket.send(json.dumps(keepalive_msg)) - logger.debug(f"โœ… MCP SERVER: *** KEEPALIVE MESSAGE SENT #{ping_counter} *** for doc: {self.doc_id}") + logger.debug(f"MCP server: *** KEEPALIVE MESSAGE SENT #{ping_counter} *** for doc: {self.doc_id}") except Exception as ping_error: - logger.error(f"โŒ MCP SERVER: *** PING FAILED #{ping_counter} *** for doc: {self.doc_id}: {ping_error}") - logger.error(f"โŒ MCP SERVER: Ping error type: {type(ping_error)}") - logger.error(f"โŒ MCP SERVER: Trying keepalive message as fallback...") + logger.error(f"MCP server: *** PING FAILED #{ping_counter} *** for doc: {self.doc_id}: {ping_error}") + logger.error(f"MCP server: Ping error type: {type(ping_error)}") + logger.error(f"MCP server: Trying keepalive message as fallback...") # Fallback to keepalive message keepalive_msg = { @@ -979,101 +979,101 @@ async def _keepalive_ping(self) -> None: "reason": "ping_error_fallback", "error": str(ping_error) } - logger.debug(f"๐Ÿ“ค MCP SERVER: *** SENDING KEEPALIVE MESSAGE #{ping_counter} *** for doc: {self.doc_id}") - logger.debug(f"๐Ÿ“ค MCP SERVER: Keepalive message: {keepalive_msg}") + logger.debug(f"MCP server: *** SENDING KEEPALIVE MESSAGE #{ping_counter} *** for doc: {self.doc_id}") + logger.debug(f"MCP server: Keepalive message: {keepalive_msg}") try: await self.websocket.send(json.dumps(keepalive_msg)) - logger.debug(f"โœ… MCP SERVER: *** KEEPALIVE MESSAGE SENT #{ping_counter} *** for doc: {self.doc_id}") + logger.debug(f"MCP server: *** KEEPALIVE MESSAGE SENT #{ping_counter} *** for doc: {self.doc_id}") except Exception as send_error: - logger.error(f"๐Ÿ’ฅ MCP SERVER: *** KEEPALIVE SEND FAILED #{ping_counter} *** for doc: {self.doc_id}: {send_error}") - logger.error(f"๐Ÿ’ฅ MCP SERVER: Connection appears to be broken, will exit keepalive loop") + logger.error(f"MCP server: *** KEEPALIVE SEND FAILED #{ping_counter} *** for doc: {self.doc_id}: {send_error}") + logger.error(f"MCP server: Connection appears to be broken, will exit keepalive loop") self.websocket_connected = False break else: - logger.warning(f"๐Ÿ’” MCP SERVER: *** WEBSOCKET DISCONNECTED *** - stopping keepalive for doc: {self.doc_id}") - logger.warning(f"๐Ÿ’” MCP SERVER: websocket: {self.websocket is not None}") - logger.warning(f"๐Ÿ’” MCP SERVER: websocket_connected: {self.websocket_connected}") + logger.warning(f"MCP server: *** WEBSOCKET DISCONNECTED *** - stopping keepalive for doc: {self.doc_id}") + logger.warning(f"MCP server: websocket: {self.websocket is not None}") + logger.warning(f"MCP server: websocket_connected: {self.websocket_connected}") break except Exception as e: - logger.error(f"๐Ÿ’” MCP SERVER: Keepalive ping #{ping_counter} failed for doc {self.doc_id}: {e}") - logger.error(f"๐Ÿ’” MCP SERVER: Connection likely closed, stopping keepalive") + logger.error(f"MCP server: Keepalive ping #{ping_counter} failed for doc {self.doc_id}: {e}") + logger.error(f"MCP server: Connection likely closed, stopping keepalive") break - logger.debug(f"๐Ÿ’” MCP SERVER: Keepalive ping stopped for doc: {self.doc_id} after {ping_counter} pings") + logger.debug(f"MCP server: Keepalive ping stopped for doc: {self.doc_id} after {ping_counter} pings") except asyncio.CancelledError: - logger.debug(f"๐Ÿ’ค MCP SERVER: *** KEEPALIVE TASK CANCELLED *** for doc: {self.doc_id}") + logger.debug(f"MCP server: *** KEEPALIVE TASK CANCELLED *** for doc: {self.doc_id}") raise # Re-raise cancellation except Exception as e: - logger.error(f"๐Ÿ’ฅ MCP SERVER: *** KEEPALIVE TASK CRASHED *** for doc: {self.doc_id}: {e}") - logger.error(f"๐Ÿ’ฅ MCP SERVER: Exception type: {type(e)}") + logger.error(f"MCP server: *** KEEPALIVE TASK CRASHED *** for doc: {self.doc_id}: {e}") + logger.error(f"MCP server: Exception type: {type(e)}") import traceback - logger.error(f"๐Ÿ’ฅ MCP SERVER: Full traceback:\n{traceback.format_exc()}") + logger.error(f"MCP server: Full traceback:\n{traceback.format_exc()}") async def _monitor_connection(self) -> None: """Monitor WebSocket connection state and attempt reconnection if needed""" try: - logger.debug(f"๐Ÿ” MCP SERVER: *** CONNECTION MONITOR STARTED *** for doc: {self.doc_id}") - logger.debug(f"๐Ÿ” MCP SERVER: Will check connection every 3 seconds") - logger.debug(f"๐Ÿ” MCP SERVER: Initial monitor state - connected: {self.websocket_connected}, websocket: {self.websocket is not None}") + logger.debug(f"MCP server: *** CONNECTION MONITOR STARTED *** for doc: {self.doc_id}") + logger.debug(f"MCP server: Will check connection every 3 seconds") + logger.debug(f"MCP server: Initial monitor state - connected: {self.websocket_connected}, websocket: {self.websocket is not None}") monitor_counter = 0 while self.websocket_connected and self.websocket: try: - logger.debug(f"๐Ÿ” MCP SERVER: *** MONITOR SLEEP START #{monitor_counter + 1} *** - waiting 3 seconds...") + logger.debug(f"MCP server: *** MONITOR SLEEP START #{monitor_counter + 1} *** - waiting 3 seconds...") await asyncio.sleep(3) # Check every 3 seconds monitor_counter += 1 - logger.debug(f"๐Ÿ” MCP SERVER: *** MONITOR SLEEP END #{monitor_counter} *** - checking connection state...") + logger.debug(f"MCP server: *** MONITOR SLEEP END #{monitor_counter} *** - checking connection state...") if self.websocket: connection_state = getattr(self.websocket, 'state', 'unknown') - logger.debug(f"๐Ÿ” MCP SERVER: *** CONNECTION CHECK #{monitor_counter} *** for doc: {self.doc_id}") - logger.debug(f"๐Ÿ” MCP SERVER: WebSocket state: {connection_state}") - logger.debug(f"๐Ÿ” MCP SERVER: websocket_connected: {self.websocket_connected}") + logger.debug(f"MCP server: *** CONNECTION CHECK #{monitor_counter} *** for doc: {self.doc_id}") + logger.debug(f"MCP server: WebSocket state: {connection_state}") + logger.debug(f"MCP server: websocket_connected: {self.websocket_connected}") # Check if connection is closed or closing if hasattr(self.websocket, 'closed') and self.websocket.closed: - logger.error(f"๐Ÿ’” MCP SERVER: *** CONNECTION DETECTED AS CLOSED *** #{monitor_counter}") - logger.error(f"๐Ÿ’” MCP SERVER: Will attempt reconnection...") + logger.error(f"MCP server: *** CONNECTION DETECTED AS CLOSED *** #{monitor_counter}") + logger.error(f"MCP server: Will attempt reconnection...") self.websocket_connected = False break elif str(connection_state) in ['CLOSED', 'CLOSING']: - logger.error(f"๐Ÿ’” MCP SERVER: *** CONNECTION CLOSING/CLOSED *** #{monitor_counter} - state: {connection_state}") - logger.error(f"๐Ÿ’” MCP SERVER: Will attempt reconnection...") + logger.error(f"MCP server: *** CONNECTION CLOSING/CLOSED *** #{monitor_counter} - state: {connection_state}") + logger.error(f"MCP server: Will attempt reconnection...") self.websocket_connected = False break else: - logger.debug(f"โœ… MCP SERVER: Connection healthy #{monitor_counter} - state: {connection_state}") + logger.debug(f"MCP server: Connection healthy #{monitor_counter} - state: {connection_state}") except Exception as e: - logger.error(f"๐Ÿ’” MCP SERVER: Connection monitor error #{monitor_counter}: {e}") - logger.error(f"๐Ÿ’” MCP SERVER: Assuming connection failed, will reconnect") + logger.error(f"MCP server: Connection monitor error #{monitor_counter}: {e}") + logger.error(f"MCP server: Assuming connection failed, will reconnect") self.websocket_connected = False break - logger.debug(f"๐Ÿ” MCP SERVER: Connection monitor stopped for doc: {self.doc_id} after {monitor_counter} checks") + logger.debug(f"MCP server: Connection monitor stopped for doc: {self.doc_id} after {monitor_counter} checks") # Attempt reconnection if we detected a problem if not self.websocket_connected: - logger.debug(f"๐Ÿ”„ MCP SERVER: *** TRIGGERING RECONNECTION *** for doc: {self.doc_id}") + logger.debug(f"MCP server: *** TRIGGERING RECONNECTION *** for doc: {self.doc_id}") await self._reconnect_websocket() except asyncio.CancelledError: - logger.debug(f"๐Ÿ’ค MCP SERVER: *** CONNECTION MONITOR CANCELLED *** for doc: {self.doc_id}") + logger.debug(f"MCP server: *** CONNECTION MONITOR CANCELLED *** for doc: {self.doc_id}") raise # Re-raise cancellation except Exception as e: - logger.error(f"๐Ÿ’ฅ MCP SERVER: *** CONNECTION MONITOR CRASHED *** for doc: {self.doc_id}: {e}") - logger.error(f"๐Ÿ’ฅ MCP SERVER: Exception type: {type(e)}") + logger.error(f"MCP server: *** CONNECTION MONITOR CRASHED *** for doc: {self.doc_id}: {e}") + logger.error(f"MCP server: Exception type: {type(e)}") import traceback - logger.error(f"๐Ÿ’ฅ MCP SERVER: Full traceback:\n{traceback.format_exc()}") + logger.error(f"MCP server: Full traceback:\n{traceback.format_exc()}") async def _reconnect_websocket(self) -> None: """Attempt to reconnect to WebSocket server""" - logger.debug(f"๐Ÿ”„ Attempting to reconnect WebSocket for doc: {self.doc_id}") + logger.debug(f"Attempting to reconnect WebSocket for doc: {self.doc_id}") await asyncio.sleep(2) # Wait before reconnecting try: await self.connect_to_websocket_server(max_retries=3) @@ -1083,47 +1083,47 @@ async def _reconnect_websocket(self) -> None: async def _handle_binary_snapshot(self, binary_data: bytes) -> None: """Handle binary snapshot data directly from WebSocket server""" try: - logger.debug(f"๏ฟฝ MCP SERVER: ==== PROCESSING BINARY SNAPSHOT ====") - logger.debug(f"๐Ÿ“ธ MCP SERVER: Binary snapshot size: {len(binary_data)} bytes for document: {self.doc_id}") - logger.debug(f"๐Ÿ“ธ MCP SERVER: Document state BEFORE import - initialized: {self._is_initialized}") + logger.debug(f" MCP server: ==== PROCESSING BINARY SNAPSHOT ====") + logger.debug(f"MCP server: Binary snapshot size: {len(binary_data)} bytes for document: {self.doc_id}") + logger.debug(f"MCP server: Document state BEFORE import - initialized: {self._is_initialized}") # Log current document state before import try: pre_state = self.export_to_lexical_state() pre_children = len(pre_state.get('root', {}).get('children', [])) - logger.debug(f"๐Ÿ“ธ MCP SERVER: Pre-import document has {pre_children} children") + logger.debug(f"MCP server: Pre-import document has {pre_children} children") except Exception as e: - logger.debug(f"๐Ÿ“ธ MCP SERVER: Could not get pre-import state: {e}") + logger.debug(f"MCP server: Could not get pre-import state: {e}") # Import binary snapshot directly into Loro document - logger.debug(f"๐Ÿ“ธ MCP SERVER: Importing binary data into Loro document...") + logger.debug(f"MCP server: Importing binary data into Loro document...") self.doc.import_(binary_data) - logger.debug(f"โœ… MCP SERVER: Successfully imported binary snapshot into Loro document: {self.doc_id}") + logger.debug(f"MCP server: Successfully imported binary snapshot into Loro document: {self.doc_id}") # Update tree reference and synchronize mappings - logger.debug(f"๐Ÿ”„ MCP SERVER: Updating tree reference and syncing node mappings...") + logger.debug(f"MCP server: Updating tree reference and syncing node mappings...") self.tree = self.doc.get_tree(self.tree_name) # Check if tree has nodes after import try: all_nodes = list(self.tree.nodes()) - logger.debug(f"๐Ÿ” MCP SERVER: Tree now has {len(all_nodes)} nodes after binary import") + logger.debug(f"MCP server: Tree now has {len(all_nodes)} nodes after binary import") if all_nodes: self.mapper.sync_existing_nodes() - logger.debug(f"โœ… MCP SERVER: Tree reference updated and mappings synced") + logger.debug(f"MCP server: Tree reference updated and mappings synced") else: - logger.warning(f"โš ๏ธ MCP SERVER: Tree appears empty after binary import - this may be expected for new documents") + logger.warning(f"MCP server: Tree appears empty after binary import - this may be expected for new documents") except Exception as tree_check_error: - logger.error(f"โŒ MCP SERVER: Error checking tree nodes: {tree_check_error}") + logger.error(f"MCP server: Error checking tree nodes: {tree_check_error}") # Mark as initialized if we got valid content if not self._is_initialized: self._is_initialized = True - logger.debug(f"๐ŸŽฏ MCP SERVER: Document {self.doc_id} NOW INITIALIZED from binary WebSocket snapshot!") + logger.debug(f"MCP server: Document {self.doc_id} NOW INITIALIZED from binary WebSocket snapshot!") else: - logger.debug(f"๐Ÿ”„ MCP SERVER: Document {self.doc_id} was already initialized, updated with new snapshot") + logger.debug(f"MCP server: Document {self.doc_id} was already initialized, updated with new snapshot") # Log document structure after applying snapshot (with better error handling) try: @@ -1133,7 +1133,7 @@ async def _handle_binary_snapshot(self, binary_data: bytes) -> None: current_state = self.export_to_lexical_state(log_structure=True) self._log_document_structure(current_state, "BINARY_SNAPSHOT") root_children = current_state.get('root', {}).get('children', []) - logger.debug(f"๐Ÿ“Š MCP SERVER: AFTER SNAPSHOT - Document {self.doc_id} now has {len(root_children)} root children") + logger.debug(f"MCP server: AFTER SNAPSHOT - Document {self.doc_id} now has {len(root_children)} root children") # Log the actual content received for i, child in enumerate(root_children): @@ -1142,32 +1142,32 @@ async def _handle_binary_snapshot(self, binary_data: bytes) -> None: if child_type == 'heading': text_content = self._extract_text_from_node(child) - logger.debug(f"๐Ÿ“Š MCP SERVER: Child[{i}]: {child_type} (key: {child_key}) - '{text_content}'") + logger.debug(f"MCP server: Child[{i}]: {child_type} (key: {child_key}) - '{text_content}'") elif child_type == 'paragraph': text_content = self._extract_text_from_node(child) - logger.debug(f"๐Ÿ“Š MCP SERVER: Child[{i}]: {child_type} (key: {child_key}) - '{text_content}'") + logger.debug(f"MCP server: Child[{i}]: {child_type} (key: {child_key}) - '{text_content}'") else: - logger.debug(f"๐Ÿ“Š MCP SERVER: Child[{i}]: {child_type} (key: {child_key})") + logger.debug(f"MCP server: Child[{i}]: {child_type} (key: {child_key})") except Exception as log_error: - logger.error(f"โŒ MCP SERVER: Failed to log document structure after binary snapshot: {log_error}") + logger.error(f"MCP server: Failed to log document structure after binary snapshot: {log_error}") # Try alternative approach to check document content try: all_nodes = list(self.tree.nodes()) # Returns TreeID objects - logger.debug(f"๐Ÿ” MCP SERVER: Tree inspection - total nodes: {len(all_nodes)}") + logger.debug(f"MCP server: Tree inspection - total nodes: {len(all_nodes)}") if all_nodes: - logger.debug(f"๐Ÿ” MCP SERVER: First few nodes: {[str(node) for node in all_nodes[:5]]}") + logger.debug(f"MCP server: First few nodes: {[str(node) for node in all_nodes[:5]]}") else: - logger.debug(f"๐Ÿ” MCP SERVER: Tree is indeed empty - might be a timing issue or empty document") + logger.debug(f"MCP server: Tree is indeed empty - might be a timing issue or empty document") except Exception as inspect_error: - logger.error(f"โŒ MCP SERVER: Could not inspect tree: {inspect_error}") + logger.error(f"MCP server: Could not inspect tree: {inspect_error}") - logger.debug(f"โœ… MCP SERVER: ==== BINARY SNAPSHOT PROCESSING COMPLETE ====") + logger.debug(f"MCP server: ==== BINARY SNAPSHOT PROCESSING COMPLETE ====") except Exception as e: - logger.error(f"โŒ MCP SERVER: Failed to handle binary snapshot for {self.doc_id}: {e}") + logger.error(f"MCP server: Failed to handle binary snapshot for {self.doc_id}: {e}") import traceback - logger.error(f"โŒ MCP SERVER: Traceback: {traceback.format_exc()}") + logger.error(f"MCP server: Traceback: {traceback.format_exc()}") def _extract_text_from_node(self, node: Dict[str, Any]) -> str: """Extract text content from a node and its children""" @@ -1185,29 +1185,29 @@ def _extract_text_from_node(self, node: Dict[str, Any]) -> str: async def _handle_websocket_message(self, data: Dict[str, Any]) -> None: """Handle incoming WebSocket JSON message""" message_type = data.get("type", "") - logger.debug(f"๐Ÿ“จ MCP SERVER: Processing JSON message type '{message_type}' for doc: {self.doc_id}") + logger.debug(f"MCP server: Processing JSON message type '{message_type}' for doc: {self.doc_id}") if message_type == "update": - logger.debug(f"๐Ÿ”„ MCP SERVER: Handling UPDATE message for doc: {self.doc_id}") + logger.debug(f"MCP server: Handling UPDATE message for doc: {self.doc_id}") await self._handle_update_message(data) elif message_type == "snapshot": - logger.debug(f"๐Ÿ“ธ MCP SERVER: Handling JSON SNAPSHOT message for doc: {self.doc_id}") + logger.debug(f"MCP server: Handling JSON SNAPSHOT message for doc: {self.doc_id}") await self._handle_snapshot_message(data) elif message_type == "keepalive_ack": await self._handle_keepalive_ack(data) else: - logger.debug(f"โ“ MCP SERVER: Received unknown WebSocket message type '{message_type}' for doc: {self.doc_id} with data: {data}") + logger.debug(f"MCP server: Received unknown WebSocket message type '{message_type}' for doc: {self.doc_id} with data: {data}") async def _handle_snapshot_message(self, data: Dict[str, Any]) -> None: """Handle snapshot message from WebSocket server""" try: snapshot_data = data.get("snapshot") if snapshot_data: - logger.debug(f"๐Ÿ“ธ MCP SERVER: Receiving initial snapshot from WebSocket server for document: {self.doc_id}") + logger.debug(f"MCP server: Receiving initial snapshot from WebSocket server for document: {self.doc_id}") # Import snapshot into Loro document self.doc.import_(bytes(snapshot_data)) - logger.debug(f"โœ… MCP SERVER: Applied initial snapshot for document: {self.doc_id}") + logger.debug(f"MCP server: Applied initial snapshot for document: {self.doc_id}") # Update tree reference and synchronize mappings self.tree = self.doc.get_tree(self.tree_name) @@ -1216,13 +1216,13 @@ async def _handle_snapshot_message(self, data: Dict[str, Any]) -> None: # Mark as initialized if we got valid content if not self._is_initialized: self._is_initialized = True - logger.debug(f"๐ŸŽฏ MCP SERVER: Document {self.doc_id} initialized from WebSocket snapshot - ready for real-time collaboration!") + logger.debug(f"MCP server: Document {self.doc_id} initialized from WebSocket snapshot - ready for real-time collaboration!") # Log initial document structure try: current_state = self.export_to_lexical_state(log_structure=True) self._log_document_structure(current_state, "INITIAL_SNAPSHOT") - logger.debug(f"๐Ÿ“Š MCP SERVER: Initial document {self.doc_id} has {len(current_state.get('root', {}).get('children', []))} root children") + logger.debug(f"MCP server: Initial document {self.doc_id} has {len(current_state.get('root', {}).get('children', []))} root children") except Exception as log_error: logger.error(f"Failed to log initial document structure: {log_error}") @@ -1232,58 +1232,58 @@ async def _handle_snapshot_message(self, data: Dict[str, Any]) -> None: async def _handle_update_message(self, data: Dict[str, Any]) -> None: """Handle update message from WebSocket server""" try: - logger.debug(f"๐Ÿ”„ MCP SERVER: ===== PROCESSING UPDATE MESSAGE =====") - logger.debug(f"๐Ÿ”„ MCP SERVER: Message data keys: {list(data.keys())}") + logger.debug(f"MCP server: ===== PROCESSING UPDATE MESSAGE =====") + logger.debug(f"MCP server: Message data keys: {list(data.keys())}") update_data = data.get("update") if update_data: - logger.debug(f"๐Ÿ”„ MCP SERVER: *** UPDATE DATA FOUND ***") - logger.debug(f"๐Ÿ”„ MCP SERVER: Update data type: {type(update_data)}") - logger.debug(f"๐Ÿ”„ MCP SERVER: Update data length: {len(update_data) if hasattr(update_data, '__len__') else 'unknown'}") - logger.debug(f"๐Ÿ”„ MCP SERVER: Receiving real-time update from editor for document: {self.doc_id}") + logger.debug(f"MCP server: *** UPDATE DATA FOUND ***") + logger.debug(f"MCP server: Update data type: {type(update_data)}") + logger.debug(f"MCP server: Update data length: {len(update_data) if hasattr(update_data, '__len__') else 'unknown'}") + logger.debug(f"MCP server: Receiving real-time update from editor for document: {self.doc_id}") # Log document state BEFORE applying update try: before_state = self.export_to_lexical_state() before_children_count = len(before_state.get('root', {}).get('children', [])) - logger.debug(f"๐Ÿ“Š MCP SERVER: BEFORE UPDATE - Document {self.doc_id} has {before_children_count} root children") + logger.debug(f"MCP server: BEFORE UPDATE - Document {self.doc_id} has {before_children_count} root children") except Exception as before_log_error: logger.error(f"Failed to log document state before update: {before_log_error}") # Apply update to Loro document - logger.debug(f"๐Ÿ”„ MCP SERVER: Applying update to Loro document...") + logger.debug(f"MCP server: Applying update to Loro document...") self.doc.import_(bytes(update_data)) - logger.debug(f"โœ… MCP SERVER: Successfully imported update bytes into Loro document") + logger.debug(f"MCP server: Successfully imported update bytes into Loro document") # Refresh tree reference - logger.debug(f"๐Ÿ”„ MCP SERVER: Refreshing tree reference...") + logger.debug(f"MCP server: Refreshing tree reference...") self.tree = self.doc.get_tree(self.tree_name) - logger.debug(f"โœ… MCP SERVER: Tree reference refreshed") + logger.debug(f"MCP server: Tree reference refreshed") # Log document state AFTER applying update try: after_state = self.export_to_lexical_state(log_structure=True) after_children_count = len(after_state.get('root', {}).get('children', [])) - logger.debug(f"๐Ÿ“Š MCP SERVER: AFTER UPDATE - Document {self.doc_id} now has {after_children_count} root children") + logger.debug(f"MCP server: AFTER UPDATE - Document {self.doc_id} now has {after_children_count} root children") if after_children_count != before_children_count: - logger.debug(f"๐ŸŽฏ MCP SERVER: *** DOCUMENT CONTENT CHANGED *** from {before_children_count} to {after_children_count} children") + logger.debug(f"MCP server: *** DOCUMENT CONTENT CHANGED *** from {before_children_count} to {after_children_count} children") else: - logger.debug(f"๐Ÿ“ MCP SERVER: Document structure unchanged, but content may have been modified within existing nodes") + logger.debug(f"MCP server: Document structure unchanged, but content may have been modified within existing nodes") self._log_document_structure(after_state, "WEBSOCKET_UPDATE") except Exception as log_error: logger.error(f"Failed to log document structure after WebSocket update: {log_error}") - logger.debug(f"โœ… MCP SERVER: ===== UPDATE MESSAGE PROCESSED SUCCESSFULLY =====") + logger.debug(f"MCP server: ===== UPDATE MESSAGE PROCESSED SUCCESSFULLY =====") else: - logger.warning(f"โš ๏ธ MCP SERVER: No 'update' data found in message") - logger.warning(f"โš ๏ธ MCP SERVER: Available keys: {list(data.keys())}") + logger.warning(f"MCP server: No 'update' data found in message") + logger.warning(f"MCP server: Available keys: {list(data.keys())}") except Exception as e: - logger.error(f"โŒ MCP SERVER: Failed to handle update message: {e}") + logger.error(f"MCP server: Failed to handle update message: {e}") import traceback - logger.error(f"โŒ MCP SERVER: Update handling traceback: {traceback.format_exc()}") + logger.error(f"MCP server: Update handling traceback: {traceback.format_exc()}") async def send_update_to_websocket_server(self, update_bytes: bytes) -> None: """Send update to WebSocket server""" @@ -1299,7 +1299,7 @@ async def send_update_to_websocket_server(self, update_bytes: bytes) -> None: } await self.websocket.send(json.dumps(message)) - logger.debug(f"๐Ÿ“ค Sent update to WebSocket server for doc: {self.doc_id}") + logger.debug(f"Sent update to WebSocket server for doc: {self.doc_id}") except Exception as e: logger.error(f"Failed to send update to WebSocket server: {e}") @@ -1311,26 +1311,26 @@ async def _handle_keepalive_ack(self, data: Dict[str, Any]) -> None: server_timestamp = data.get("server_timestamp", "unknown") acknowledged = data.get("acknowledged", False) - logger.debug(f"๐Ÿ’“ MCP SERVER: *** RECEIVED KEEPALIVE ACK #{ping_id} *** for doc: {self.doc_id}") - logger.debug(f"๐Ÿ’“ MCP SERVER: Server timestamp: {server_timestamp}") - logger.debug(f"๐Ÿ’“ MCP SERVER: Acknowledged: {acknowledged}") - logger.debug(f"๐Ÿ’“ MCP SERVER: Client timestamp: {time.time()}") + logger.debug(f"MCP server: *** RECEIVED KEEPALIVE ACK #{ping_id} *** for doc: {self.doc_id}") + logger.debug(f"MCP server: Server timestamp: {server_timestamp}") + logger.debug(f"MCP server: Acknowledged: {acknowledged}") + logger.debug(f"MCP server: Client timestamp: {time.time()}") if server_timestamp != "unknown": try: roundtrip_time = time.time() - float(server_timestamp) - logger.debug(f"๐Ÿ’“ MCP SERVER: *** KEEPALIVE ROUND-TRIP TIME: {roundtrip_time:.3f}s ***") + logger.debug(f"MCP server: *** KEEPALIVE ROUND-TRIP TIME: {roundtrip_time:.3f}s ***") except (ValueError, TypeError): - logger.warning(f"๐Ÿ’“ MCP SERVER: Could not calculate round-trip time from server timestamp: {server_timestamp}") + logger.warning(f"MCP server: Could not calculate round-trip time from server timestamp: {server_timestamp}") if acknowledged: - logger.debug(f"โœ… MCP SERVER: *** KEEPALIVE #{ping_id} ACKNOWLEDGED *** - connection is healthy") + logger.debug(f"MCP server: *** KEEPALIVE #{ping_id} ACKNOWLEDGED *** - connection is healthy") else: - logger.warning(f"โš ๏ธ MCP SERVER: *** KEEPALIVE #{ping_id} NOT ACKNOWLEDGED *** - potential issue") + logger.warning(f"MCP server: *** KEEPALIVE #{ping_id} NOT ACKNOWLEDGED *** - potential issue") except Exception as e: - logger.error(f"๐Ÿ’” MCP SERVER: Error handling keepalive ACK: {e}") - logger.error(f"๐Ÿ’” MCP SERVER: ACK data: {data}") + logger.error(f"MCP server: Error handling keepalive ACK: {e}") + logger.error(f"MCP server: ACK data: {data}") def _setup_local_update_subscription(self) -> None: """Set up subscription to automatically propagate local document changes to WebSocket server""" @@ -1342,25 +1342,25 @@ def _setup_local_update_subscription(self) -> None: def local_update_callback(update_bytes): """Callback to handle local document changes and send to WebSocket""" try: - logger.debug(f"๐Ÿ”„ LOCAL UPDATE: Document {self.doc_id} changed locally, propagating {len(update_bytes)} bytes to WebSocket") + logger.debug(f"LOCAL UPDATE: Document {self.doc_id} changed locally, propagating {len(update_bytes)} bytes to WebSocket") if self.websocket_connected and self.websocket: # Schedule the async send operation asyncio.create_task(self._send_local_update_to_websocket(update_bytes)) else: - logger.warning(f"โš ๏ธ LOCAL UPDATE: WebSocket not connected for doc {self.doc_id}, cannot propagate local changes") + logger.warning(f"LOCAL UPDATE: WebSocket not connected for doc {self.doc_id}, cannot propagate local changes") return True # Continue subscription except Exception as e: - logger.error(f"โŒ LOCAL UPDATE: Failed to handle local update for doc {self.doc_id}: {e}") + logger.error(f"LOCAL UPDATE: Failed to handle local update for doc {self.doc_id}: {e}") return True # Continue subscription even on error # Subscribe to local document updates self._local_update_subscription = self.doc.subscribe_local_update(local_update_callback) - logger.debug(f"โœ… LOCAL UPDATE: Subscription established for doc: {self.doc_id}") + logger.debug(f"LOCAL UPDATE: Subscription established for doc: {self.doc_id}") except Exception as e: - logger.error(f"โŒ LOCAL UPDATE: Failed to set up subscription for doc {self.doc_id}: {e}") + logger.error(f"LOCAL UPDATE: Failed to set up subscription for doc {self.doc_id}: {e}") async def _send_local_update_to_websocket(self, update_bytes: bytes) -> None: """Send local update to WebSocket server (async helper for subscription callback)""" @@ -1376,10 +1376,10 @@ async def _send_local_update_to_websocket(self, update_bytes: bytes) -> None: } await self.websocket.send(json.dumps(message)) - logger.debug(f"โœ… LOCAL UPDATE: Successfully propagated {len(update_bytes)} bytes to WebSocket server for doc: {self.doc_id}") + logger.debug(f"LOCAL UPDATE: Successfully propagated {len(update_bytes)} bytes to WebSocket server for doc: {self.doc_id}") except Exception as e: - logger.error(f"โŒ LOCAL UPDATE: Failed to send to WebSocket server for doc {self.doc_id}: {e}") + logger.error(f"LOCAL UPDATE: Failed to send to WebSocket server for doc {self.doc_id}: {e}") def _log_document_structure(self, lexical_state: Dict[str, Any], operation: str) -> None: """ @@ -1391,17 +1391,17 @@ def _log_document_structure(self, lexical_state: Dict[str, Any], operation: str) """ try: if not lexical_state or 'root' not in lexical_state: - logger.warning(f"๐Ÿ“‹ [{operation}] Document {self.doc_id}: NO ROOT FOUND in lexical state") + logger.warning(f"[{operation}] Document {self.doc_id}: NO ROOT FOUND in lexical state") return root = lexical_state['root'] children = root.get('children', []) child_count = len(children) - logger.debug(f"๐Ÿ“‹ [{operation}] Document {self.doc_id} structure:") - logger.debug(f" โ””โ”€ Root type: {root.get('type', 'unknown')}") - logger.debug(f" โ””โ”€ Root key: {root.get('__key', 'no-key')}") - logger.debug(f" โ””โ”€ Children count: {child_count}") + logger.debug(f"[{operation}] Document {self.doc_id} structure:") + logger.debug(f"โ””โ”€ Root type: {root.get('type', 'unknown')}") + logger.debug(f"โ””โ”€ Root key: {root.get('__key', 'no-key')}") + logger.debug(f"โ””โ”€ Children count: {child_count}") # Log details of each child for i, child in enumerate(children): @@ -1416,7 +1416,7 @@ def _log_document_structure(self, lexical_state: Dict[str, Any], operation: str) if text_nodes: child_text = f" (text: '{text_nodes[0].get('text', '')}')" - logger.debug(f" โ””โ”€ Child[{i}]: {child_type} (key: {child_key}, children: {len(child_children)}){child_text}") + logger.debug(f"โ””โ”€ Child[{i}]: {child_type} (key: {child_key}, children: {len(child_children)}){child_text}") # Log grandchildren for debugging for j, grandchild in enumerate(child_children[:3]): # Limit to first 3 for brevity @@ -1424,7 +1424,7 @@ def _log_document_structure(self, lexical_state: Dict[str, Any], operation: str) gc_key = grandchild.get('__key', 'no-key') gc_text = grandchild.get('text', '') if gc_type == 'text' else '' gc_text_preview = f" '{gc_text[:50]}{'...' if len(gc_text) > 50 else ''}'" if gc_text else '' - logger.debug(f" โ””โ”€ GrandChild[{j}]: {gc_type} (key: {gc_key}){gc_text_preview}") + logger.debug(f"โ””โ”€ GrandChild[{j}]: {gc_type} (key: {gc_key}){gc_text_preview}") except Exception as e: logger.error(f"Failed to log document structure: {e}") \ No newline at end of file diff --git a/lexical_loro/model/node_mapper.py b/lexical_loro/model/node_mapper.py index 66441c0a..4e278f30 100644 --- a/lexical_loro/model/node_mapper.py +++ b/lexical_loro/model/node_mapper.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/lexical_loro/websocket/__init__.py b/lexical_loro/websocket/__init__.py index f43292be..0b39f42c 100644 --- a/lexical_loro/websocket/__init__.py +++ b/lexical_loro/websocket/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """WebSocket server module for tree-based collaboration.""" diff --git a/lexical_loro/websocket/__main__.py b/lexical_loro/websocket/__main__.py index d2c8e482..95f6275a 100644 --- a/lexical_loro/websocket/__main__.py +++ b/lexical_loro/websocket/__main__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """Main entry point for the tree-based WebSocket server.""" diff --git a/lexical_loro/websocket/server.py b/lexical_loro/websocket/server.py index 92bbc916..90b30cf4 100644 --- a/lexical_loro/websocket/server.py +++ b/lexical_loro/websocket/server.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. @@ -101,15 +101,15 @@ def default_load_model(doc_id: str) -> Optional[str]: with open(model_file, 'r', encoding='utf-8') as f: content = f.read().strip() if content: - logger.debug(f"๐Ÿ“‚ [Persistence] Loaded existing model {doc_id} from {model_file}") + logger.debug(f"[Persistence] Loaded existing model {doc_id} from {model_file}") return content # No existing file found, return None to indicate no persisted content - logger.debug(f"๐Ÿ“‚ [Persistence] No existing content found for '{doc_id}'") + logger.debug(f"[Persistence] No existing content found for '{doc_id}'") return None except Exception as e: - logger.warning(f"โš ๏ธ [Persistence] Error loading model {doc_id}: {e}") + logger.warning(f"[Persistence] Error loading model {doc_id}: {e}") return None def default_save_model(doc_id: str, lexical_json: str) -> bool: @@ -126,7 +126,7 @@ def default_save_model(doc_id: str, lexical_json: str) -> bool: """ # Type checking - enforce string type if not isinstance(lexical_json, str): - logger.debug(f"๐Ÿ”„ [Persistence] default_save_model expects str, got {type(lexical_json).__name__} for {doc_id}") + logger.debug(f"[Persistence] default_save_model expects str, got {type(lexical_json).__name__} for {doc_id}") return False try: @@ -143,11 +143,11 @@ def default_save_model(doc_id: str, lexical_json: str) -> bool: with open(model_file, 'w', encoding='utf-8') as f: f.write(lexical_json) - logger.debug(f"๐Ÿ’พ [Persistence] Saved model {doc_id} to {model_file}") + logger.debug(f"[Persistence] Saved model {doc_id} to {model_file}") return True except Exception as e: - logger.error(f"โŒ [Persistence] Failed to save model {doc_id}: {e}") + logger.error(f"[Persistence] Failed to save model {doc_id}: {e}") return False @@ -177,31 +177,31 @@ def __init__(self, name: str, # Initialize with proper Lexical content structure if needed (only if no content was loaded) if not content_loaded: try: - logger.debug(f"[Server] No persisted content found, initializing with default Lexical content") + logger.debug(f"[LORO SERVER] No persisted content found, initializing with default Lexical content") initialize_loro_doc_with_lexical_content(self.doc, logger) self.doc.commit() self.has_changes_since_save = True # Mark as changed for initial save - logger.debug(f"[Server] Successfully initialized document with default Lexical content") + logger.debug(f"[LORO SERVER] Successfully initialized document with default Lexical content") # Verify initialization tree = self.doc.get_tree(DEFAULT_TREE_NAME) final_nodes = tree.nodes() # method final_roots = tree.roots # property - logger.debug(f"[Server] After initialization - nodes: {len(final_nodes)}, roots: {len(final_roots)}") + logger.debug(f"[LORO SERVER] After initialization - nodes: {len(final_nodes)}, roots: {len(final_roots)}") except Exception as e: - logger.error(f"[Server] Error initializing document with Lexical content: {e}") + logger.error(f"[LORO SERVER] Error initializing document with Lexical content: {e}") # Fallback to empty document try: tree = self.doc.get_tree(DEFAULT_TREE_NAME) root_id = tree.create() self.doc.commit() self.has_changes_since_save = True - logger.warning(f"[Server] Fallback: Created basic empty document") + logger.warning(f"[LORO SERVER] Fallback: Created basic empty document") except Exception as fallback_e: - logger.error(f"[Server] Even fallback initialization failed: {fallback_e}") + logger.error(f"[LORO SERVER] Even fallback initialization failed: {fallback_e}") else: - logger.debug(f"[Server] Document restored from persistence, skipping initialization") + logger.debug(f"[LORO SERVER] Document restored from persistence, skipping initialization") # Log what content exists try: tree = self.doc.get_tree(DEFAULT_TREE_NAME) @@ -210,11 +210,11 @@ def __init__(self, name: str, try: meta_map = tree.get_meta(root_id) element_type = meta_map.get('elementType', 'unknown') - logger.debug(f"[Server] Existing root {i}: {root_id} -> type: {element_type}") + logger.debug(f"[LORO SERVER] Existing root {i}: {root_id} -> type: {element_type}") except Exception as e: - logger.debug(f"[Server] Error reading root {i}: {e}") + logger.debug(f"[LORO SERVER] Error reading root {i}: {e}") except Exception as e: - logger.debug(f"[Server] Error accessing restored document content: {e}") + logger.debug(f"[LORO SERVER] Error accessing restored document content: {e}") self.conns = {} # Initialize proper Loro EphemeralStore with 30 second timeout (matching Node.js server) @@ -254,36 +254,36 @@ def ephemeral_change_handler(event): asyncio.create_task(conn.send(json.dumps(asdict(message)))) broadcast_count += 1 except Exception as send_error: - logger.warn(f"[Server] ephemeral_change_handler - Failed to send to conn: {send_error}") + logger.warning(f"[LORO SERVER] ephemeral_change_handler - Failed to send to conn: {send_error}") - logger.debug(f"๐Ÿ“ก SERVER DEBUG - Broadcasted ephemeral changes to {broadcast_count} connections") + logger.debug(f"SERVER DEBUG - Broadcasted ephemeral changes to {broadcast_count} connections") # Clear the sender reference after broadcast self.last_ephemeral_sender = None except Exception as broadcast_error: - logger.error(f"[Server] ephemeral_change_handler - ERROR broadcasting: {broadcast_error}") + logger.error(f"[LORO SERVER] ephemeral_change_handler - ERROR broadcasting: {broadcast_error}") # Subscribe to the ephemeral store changes self.ephemeral_store.subscribe(ephemeral_change_handler) - logger.debug(f"[Server] Initialized document '{name}' with Loro tree structure") + logger.debug(f"[LORO SERVER] Initialized document '{name}' with Loro tree structure") def _load_from_persistence(self): """Load document content from persistence if available and convert to Loro tree structure""" try: - logger.debug(f"๐Ÿ“‚ [Persistence] Loading document '{self.name}' from storage") + logger.debug(f"[Persistence] Loading document '{self.name}' from storage") # Load Lexical JSON content lexical_content = self.load_model(self.name) if not lexical_content: - logger.debug(f"๐Ÿ“‚ [Persistence] No existing content found for '{self.name}', will use initial content") + logger.debug(f"[Persistence] No existing content found for '{self.name}', will use initial content") return False # Indicate no content was loaded # Parse the JSON to validate it try: lexical_data = json.loads(lexical_content) - logger.debug(f"๐Ÿ“‚ [Persistence] Successfully loaded existing content for '{self.name}'") + logger.debug(f"[Persistence] Successfully loaded existing content for '{self.name}'") # Convert Lexical JSON back to Loro tree structure tree = self.doc.get_tree(DEFAULT_TREE_NAME) @@ -293,15 +293,15 @@ def _load_from_persistence(self): root_id = lexical_to_loro_tree(lexical_data, tree, logger) self.doc.commit() - logger.debug(f"๐Ÿ“‚ [Persistence] Successfully restored document '{self.name}' from persistence") + logger.debug(f"[Persistence] Successfully restored document '{self.name}' from persistence") return True # Indicate content was loaded and applied except json.JSONDecodeError as e: - logger.warning(f"โš ๏ธ [Persistence] Invalid JSON in stored content for '{self.name}': {e}") + logger.warning(f"[Persistence] Invalid JSON in stored content for '{self.name}': {e}") return False except Exception as e: - logger.error(f"โŒ [Persistence] Error loading document '{self.name}': {e}") + logger.error(f"[Persistence] Error loading document '{self.name}': {e}") return False def to_json(self) -> str: @@ -313,10 +313,10 @@ def save_to_persistence(self) -> bool: """Save current document state to persistence""" try: if not self.has_changes_since_save: - logger.debug(f"โญ๏ธ [Persistence] No changes to save for document '{self.name}'") + logger.debug(f"Skipping [Persistence] No changes to save for document '{self.name}'") return True - logger.debug(f"๐Ÿ’พ [Persistence] Saving document '{self.name}' to storage") + logger.debug(f"[Persistence] Saving document '{self.name}' to storage") # Check if we're using the spacer's save function (which expects model object) # vs the standard save function (which expects JSON string) @@ -325,26 +325,26 @@ def save_to_persistence(self) -> bool: success = self.save_model(self.name, self) if not success: # If spacer-style save returns False, try JSON fallback - logger.debug(f"๐Ÿ”„ [Persistence] Spacer-style save returned False, trying JSON fallback") + logger.debug(f"[Persistence] Spacer-style save returned False, trying JSON fallback") lexical_json = loro_tree_to_lexical_json(self.doc, logger) success = self.save_model(self.name, lexical_json) except (TypeError, AttributeError, ValueError) as e: # Fallback to standard save function (pass JSON string) - logger.debug(f"๐Ÿ”„ [Persistence] Spacer-style save failed ({type(e).__name__}), trying JSON fallback") + logger.debug(f"[Persistence] Spacer-style save failed ({type(e).__name__}), trying JSON fallback") lexical_json = loro_tree_to_lexical_json(self.doc, logger) success = self.save_model(self.name, lexical_json) if success: self.has_changes_since_save = False self.last_save_time = time.time() - logger.debug(f"โœ… [Persistence] Successfully saved document '{self.name}'") + logger.debug(f"[Persistence] Successfully saved document '{self.name}'") else: - logger.error(f"โŒ [Persistence] Failed to save document '{self.name}'") + logger.error(f"[Persistence] Failed to save document '{self.name}'") return success except Exception as e: - logger.error(f"โŒ [Persistence] Error saving document '{self.name}': {e}") + logger.error(f"[Persistence] Error saving document '{self.name}': {e}") return False def mark_changed(self): @@ -368,10 +368,10 @@ def handle_client_disconnect(self, client_id: str) -> Dict[str, Any]: try: # Remove the client's ephemeral state self.ephemeral_store.delete(client_id) - logger.info(f"๐Ÿงน [Server] CLEANED UP ephemeral state for clientID: {client_id}") + logger.info(f"[LORO SERVER] CLEANED UP ephemeral state for clientID: {client_id}") return {"success": True, "removed_keys": [client_id]} except Exception as e: - logger.warning(f"โš ๏ธ [Server] Failed to cleanup ephemeral state for {client_id}: {e}") + logger.warning(f"[LORO SERVER] Failed to cleanup ephemeral state for {client_id}: {e}") return {"success": False, "error": str(e)} def to_json(self) -> Dict[str, Any]: @@ -386,7 +386,7 @@ def to_json(self) -> Dict[str, Any]: lexical_json_str = loro_tree_to_lexical_json(self.doc, logger) return json.loads(lexical_json_str) except Exception as e: - logger.error(f"โŒ [Persistence] Error converting document '{self.name}' to JSON: {e}") + logger.error(f"[Persistence] Error converting document '{self.name}' to JSON: {e}") # Return a basic empty Lexical structure as fallback return { "root": { @@ -410,7 +410,7 @@ def import_from_json(self, lexical_data: Dict[str, Any]) -> bool: True if import successful, False otherwise """ try: - logger.debug(f"๐Ÿ“ฅ [Persistence] Importing JSON data into document '{self.name}'") + logger.debug(f"[Persistence] Importing JSON data into document '{self.name}'") # Clear existing document content self.doc = LoroDoc() @@ -426,11 +426,11 @@ def import_from_json(self, lexical_data: Dict[str, Any]) -> bool: # Mark as changed for next save self.has_changes_since_save = True - logger.debug(f"โœ… [Persistence] Successfully imported JSON data into document '{self.name}'") + logger.debug(f"[Persistence] Successfully imported JSON data into document '{self.name}'") return True except Exception as e: - logger.error(f"โŒ [Persistence] Error importing JSON data into document '{self.name}': {e}") + logger.error(f"[Persistence] Error importing JSON data into document '{self.name}': {e}") return False # Global document storage @@ -455,14 +455,14 @@ async def start_global_autosave(interval_seconds: int = 30): global _global_autosave_task, _global_autosave_interval, _global_autosave_running if _global_autosave_task is not None and not _global_autosave_task.done(): - logger.debug("๐Ÿ”„ Global auto-save task already running") + logger.debug("Global auto-save task already running") return _global_autosave_interval = interval_seconds _global_autosave_running = True _global_autosave_task = asyncio.create_task(_global_autosave_loop()) - logger.info(f"๐Ÿš€ Started global auto-save task with {interval_seconds}s interval") + logger.info(f"Started global auto-save task with {interval_seconds}s interval") async def stop_global_autosave(): """Stop global auto-save task""" @@ -477,52 +477,55 @@ async def stop_global_autosave(): except asyncio.CancelledError: pass - logger.info("๐Ÿ›‘ Stopped global auto-save task") + logger.info("Stopped global auto-save task") async def _global_autosave_loop(): """Global auto-save loop - same pattern as LoroWebSocketServer""" - logger.info(f"๐Ÿš€ Global auto-save task started with interval: {_global_autosave_interval} seconds") + logger.info(f"Global auto-save task started with interval: {_global_autosave_interval} seconds") while _global_autosave_running: try: await asyncio.sleep(_global_autosave_interval) if _global_autosave_running: - logger.info(f"๐Ÿ” Global auto-save check: found {len(docs)} documents") + logger.info(f"Global auto-save check: found {len(docs)} documents") if docs: - logger.info(f"๐Ÿ”„ Auto-saving {len(docs)} documents...") + logger.info(f"Auto-saving {len(docs)} documents...") saved_count = 0 unchanged_count = 0 for doc_name, doc in docs.items(): try: if doc.needs_save(): - success = doc.save_to_persistence() + # Run the (potentially blocking) persistence call in a + # worker thread so blocking I/O (e.g. S3 uploads) does not + # stall the shared asyncio event loop and HTTP handlers. + success = await asyncio.to_thread(doc.save_to_persistence) if success: saved_count += 1 - logger.info(f"๐Ÿ’พ Auto-saved document: {doc_name}") + logger.info(f"Auto-saved document: {doc_name}") else: - logger.warning(f"โš ๏ธ Auto-save failed for document: {doc_name}") + logger.warning(f"Auto-save failed for document: {doc_name}") else: unchanged_count += 1 - logger.info(f"โญ๏ธ Skipping auto-save for unchanged document: {doc_name}") + logger.info(f"Skipping auto-save for unchanged document: {doc_name}") except Exception as e: - logger.error(f"โŒ Error auto-saving document {doc_name}: {e}") + logger.error(f"Error auto-saving document {doc_name}: {e}") if saved_count > 0: - logger.info(f"โœ… Global auto-save completed: {saved_count} saved, {unchanged_count} unchanged") + logger.info(f"Global auto-save completed: {saved_count} saved, {unchanged_count} unchanged") elif unchanged_count > 0: - logger.info(f"โ„น๏ธ Global auto-save check: {unchanged_count} documents unchanged, none saved") + logger.info(f"Global auto-save check: {unchanged_count} documents unchanged, none saved") else: - logger.debug(f"๐Ÿ” No documents to auto-save") + logger.debug(f"No documents to auto-save") except asyncio.CancelledError: - logger.debug("๐Ÿ›‘ Global auto-save task cancelled") + logger.debug("Global auto-save task cancelled") break except Exception as e: - logger.error(f"โŒ Error in global auto-save loop: {e}") + logger.error(f"Error in global auto-save loop: {e}") - logger.debug("โœ… Global auto-save task stopped") + logger.debug("Global auto-save task stopped") def get_client_id(conn) -> Optional[str]: """ @@ -566,39 +569,39 @@ def clear_docs(): """Clear all cached documents - useful for server restarts""" global docs docs.clear() - logger.debug(f"[Server] Cleared document cache") + logger.debug(f"[LORO SERVER] Cleared document cache") def get_doc(docname: str): # Extract the actual document ID from WebSocket path if needed # Handle paths like "playground/0/actual_id" -> "actual_id" if '/' in docname: actual_doc_id = docname.split('/')[-1] - logger.debug(f"๐Ÿ”„ [Server] Extracted document ID '{actual_doc_id}' from path '{docname}'") + logger.debug(f"[LORO SERVER] Extracted document ID '{actual_doc_id}' from path '{docname}'") else: actual_doc_id = docname if actual_doc_id not in docs: - logger.debug(f"๐Ÿ“„ [Server] Creating new document: {actual_doc_id}") + logger.debug(f"[LORO SERVER] Creating new document: {actual_doc_id}") docs[actual_doc_id] = WSSharedDoc(actual_doc_id, global_load_model, global_save_model) else: - logger.debug(f"๐Ÿ“„ [Server] Retrieved existing document: {actual_doc_id}") + logger.debug(f"[LORO SERVER] Retrieved existing document: {actual_doc_id}") return docs[actual_doc_id] def save_all_docs() -> Dict[str, bool]: """Save all documents to persistence""" results = {} - logger.debug(f"๐Ÿ’พ [Persistence] Saving all {len(docs)} documents") + logger.debug(f"[Persistence] Saving all {len(docs)} documents") for doc_name, doc in docs.items(): try: results[doc_name] = doc.save_to_persistence() except Exception as e: - logger.error(f"โŒ [Persistence] Error saving document '{doc_name}': {e}") + logger.error(f"[Persistence] Error saving document '{doc_name}': {e}") results[doc_name] = False saved_count = sum(1 for success in results.values() if success) - logger.debug(f"โœ… [Persistence] Saved {saved_count}/{len(docs)} documents") + logger.debug(f"[Persistence] Saved {saved_count}/{len(docs)} documents") return results def close_conn(doc, conn): @@ -607,31 +610,31 @@ def close_conn(doc, conn): client_id = get_client_id(conn) display_id = client_id if client_id else conn_id - print(f"\n๐Ÿ’”๐Ÿ’”๐Ÿ’” [server:py:ws] CONNECTION CLOSED: {display_id} (was {conn_id}) โ† document: {doc.name} ๐Ÿ’”๐Ÿ’”๐Ÿ’”") - logger.info(f"[server:py:ws] CONNECTION CLOSED: {display_id} โ† document: {doc.name}") + print(f"\n[server:py:ws] Connection closed: {display_id} (was {conn_id}) -> document: {doc.name}") + logger.info(f"[server:py:ws] Connection closed: {display_id} -> document: {doc.name}") if client_id: - logger.info(f"๐Ÿ”— [CORRELATION] Closed Frontend clientID: {client_id} (WebSocket {conn_id})") + logger.info(f"[CORRELATION] Closed Frontend clientID: {client_id} (WebSocket {conn_id})") - logger.debug(f"๐Ÿ’” [Server] *** CONNECTION CLOSING *** for document: {doc.name}") - logger.debug(f"๐Ÿ’” [Server] Closing connection: {conn}") + logger.debug(f"[LORO SERVER] Connection closing for document: {doc.name}") + logger.debug(f"[LORO SERVER] Closing connection: {conn}") # Clean up ephemeral state for this client if client_id: try: # Remove the client's ephemeral state doc.ephemeral_store.delete(client_id) - logger.info(f"๐Ÿงน [Server] CLEANED UP ephemeral state for clientID: {client_id}") - logger.info(f"๐Ÿ”— [CORRELATION] Removed ephemeral data for Frontend clientID: {client_id}") + logger.info(f"[LORO SERVER] Cleaned up ephemeral state for clientID: {client_id}") + logger.info(f"[CORRELATION] Removed ephemeral data for Frontend clientID: {client_id}") except Exception as ephemeral_error: - logger.warning(f"โš ๏ธ [Server] Failed to cleanup ephemeral state for {client_id}: {ephemeral_error}") + logger.warning(f"[LORO SERVER] Failed to cleanup ephemeral state for {client_id}: {ephemeral_error}") else: - logger.warning(f"โš ๏ธ [Server] No client_id available for connection cleanup, cannot remove ephemeral state") + logger.warning(f"[LORO SERVER] No client_id available for connection cleanup, cannot remove ephemeral state") del doc.conns[conn] - logger.debug(f"๐Ÿ’” [Server] Remaining connections for document {doc.name}: {len(doc.conns)}") - logger.debug(f"๐Ÿ’” [Server] Remaining connections list: {list(doc.conns.keys())}") + logger.debug(f"[LORO SERVER] Remaining connections for document {doc.name}: {len(doc.conns)}") + logger.debug(f"[LORO SERVER] Remaining connections list: {list(doc.conns.keys())}") else: - logger.warning(f"โš ๏ธ [Server] Tried to cleanup connection {conn} but it wasn't in doc.conns") + logger.warning(f"[LORO SERVER] Tried to cleanup connection {conn} but it wasn't in doc.conns") async def message_listener(conn, doc, message): # Get display ID (client ID if available, otherwise connection ID) @@ -644,19 +647,19 @@ async def message_listener(conn, doc, message): if isinstance(message, str): message_str = message - logger.info(f"๐Ÿ“ [Server] String message from {display_id}: {message_str[:100]}...") + logger.info(f"[LORO SERVER] String message from {display_id}: {message_str[:100]}...") elif isinstance(message, bytes): try: message_str = message.decode('utf-8') - logger.info(f"๐Ÿ“ [Server] Decoded bytes from {display_id}: {message_str[:100]}...") + logger.info(f"[LORO SERVER] Decoded bytes from {display_id}: {message_str[:100]}...") except UnicodeDecodeError: - logger.info(f"๐Ÿ’พ [Server] Binary Loro update from {display_id}: {len(message)} bytes") - logger.debug(f"[Server] Received binary Loro update: {len(message)} bytes") + logger.info(f"[LORO SERVER] Binary Loro update from {display_id}: {len(message)} bytes") + logger.debug(f"[LORO SERVER] Received binary Loro update: {len(message)} bytes") # Apply the update to the document doc.doc.import_(message) # Mark document as changed for persistence doc.mark_changed() - logger.debug(f"๐Ÿ’พ [Persistence] Marked document '{doc.name}' as changed (binary update)") + logger.debug(f"[Persistence] Marked document '{doc.name}' as changed (binary update)") # Broadcast to other connections for c in doc.conns: @@ -664,7 +667,7 @@ async def message_listener(conn, doc, message): await c.send(message) return else: - logger.warning(f"[Server] Unknown message type: {type(message)}") + logger.warning(f"[LORO SERVER] Unknown message type: {type(message)}") return if not message_str: @@ -673,12 +676,12 @@ async def message_listener(conn, doc, message): try: message_data = json.loads(message_str) except json.JSONDecodeError as e: - logger.warning(f"[Server] JSON parse error: {e}") + logger.warning(f"[LORO SERVER] JSON parse error: {e}") return message_type = message_data.get("type", "") display_id = get_client_id(conn) or get_connection_id(conn) - logger.debug(f"[Server] Received message type: {message_type} for doc: {doc.name}") + logger.debug(f"[LORO SERVER] Received message type: {message_type} for doc: {doc.name}") if message_type == MESSAGE_QUERY_SNAPSHOT: await handle_query_snapshot(conn, doc, message_data) @@ -691,10 +694,10 @@ async def message_listener(conn, doc, message): elif message_type == "keepalive": await handle_keepalive(conn, doc, message_data) else: - logger.warning(f"[Server] Unknown message type: {message_type}") + logger.warning(f"[LORO SERVER] Unknown message type '{message_type}' from {display_id} for document {doc.name}") except Exception as e: - logger.error(f"[Server] Message handling error: {e}") + logger.error(f"[LORO SERVER] Message handling error for {display_id} on document {doc.name}: {e}") async def handle_query_snapshot(conn, doc, message_data): try: @@ -706,29 +709,30 @@ async def handle_query_snapshot(conn, doc, message_data): # Store client ID mapping on first snapshot request conn.client_id = client_id display_id = client_id - logger.info(f"๐Ÿ†” [Server] CLIENT ID from snapshot request: {conn_id} โ†” {client_id}") - logger.info(f"๐Ÿ”— [CORRELATION] WebSocket {conn_id} maps to Frontend clientID: {client_id}") + logger.info(f"[LORO SERVER] Client ID from snapshot request: {conn_id} <-> {client_id}") + logger.info(f"[CORRELATION] WebSocket {conn_id} maps to Frontend clientID: {client_id}") else: display_id = get_client_id(conn) or conn_id request_id = str(time.time()) - logger.info(f"๐Ÿ“ธ [Server] Client {display_id} requesting snapshot for doc: {doc.name} (Request ID: {request_id})") + logger.info(f"[LORO SERVER] Client {display_id} requesting snapshot for doc: {doc.name} (Request ID: {request_id})") # Export actual Loro document snapshot snapshot = doc.doc.export(ExportMode.Snapshot()) - logger.info(f"๐Ÿ“ธ [Server] Sending snapshot response to {display_id}: {len(snapshot)} bytes") + logger.info(f"[LORO SERVER] Sending snapshot response to {display_id}: {len(snapshot)} bytes") # Log tree structure for debugging tree = doc.doc.get_tree(DEFAULT_TREE_NAME) nodes = tree.nodes() # method call - logger.debug(f"[Server] Snapshot contains {len(nodes)} nodes from server document") + logger.debug(f"[LORO SERVER] Snapshot contains {len(nodes)} nodes from server document") await conn.send(snapshot) + logger.debug(f"[LORO SERVER] Snapshot sent to {display_id} for document {doc.name}") except Exception as e: - logger.error(f"[Server] Error handling query-snapshot: {e}") + logger.error(f"[LORO SERVER] Error handling query-snapshot: {e}") import traceback - logger.error(f"[Server] Traceback: {traceback.format_exc()}") + logger.error(f"[LORO SERVER] Traceback: {traceback.format_exc()}") async def handle_ephemeral(conn, doc, message_data): try: @@ -767,20 +771,20 @@ async def handle_ephemeral(conn, doc, message_data): # Store the client ID mapping for future reference if not hasattr(conn, 'client_id'): conn.client_id = client_id - logger.info(f"๐Ÿ†” [Server] NEW CLIENT MAPPED: {conn_id} โ†” {client_id}") - logger.info(f"๐Ÿ”— [CORRELATION] WebSocket {conn_id} maps to Frontend clientID: {client_id}") + logger.info(f"[LORO SERVER] New client mapped: {conn_id} <-> {client_id}") + logger.info(f"[CORRELATION] WebSocket {conn_id} maps to Frontend clientID: {client_id}") else: - logger.debug(f"๐ŸŽญ [Server] CLIENT ID CONFIRMED: {conn_id} โ†’ {client_id}") + logger.debug(f"[LORO SERVER] CLIENT ID CONFIRMED: {conn_id} -> {client_id}") # Use client ID in logging if available display_id = get_client_id(conn) or conn_id # Log the processed ephemeral update with proper client ID - logger.debug(f"๐Ÿ“ก [Server] Processing ephemeral data: {len(ephemeral_data)} bytes from {display_id}") + logger.debug(f"[LORO SERVER] Processing ephemeral data: {len(ephemeral_data)} bytes from {display_id}") # Mark this connection as sender to avoid echo (moved after client ID detection) doc.last_ephemeral_sender = conn - logger.debug(f"๐Ÿ“ก SERVER DEBUG - Applied ephemeral update from {display_id}: " + logger.debug(f"SERVER DEBUG - Applied ephemeral update from {display_id}: " f"bytes_length={len(ephemeral_bytes)}, " f"before_keys={before_keys}, " f"after_keys={after_keys}, " @@ -788,7 +792,7 @@ async def handle_ephemeral(conn, doc, message_data): f"total_connections={len(doc.conns)}") except Exception as e: - logger.error(f"[Server] Error handling ephemeral: {e}") + logger.error(f"[LORO SERVER] Error handling ephemeral: {e}") doc.last_ephemeral_sender = None async def handle_query_ephemeral(conn, doc, message_data): @@ -799,20 +803,20 @@ async def handle_query_ephemeral(conn, doc, message_data): if client_id and not hasattr(conn, 'client_id'): # Store client ID mapping if not already stored conn.client_id = client_id - logger.info(f"๐Ÿ†” [Server] Client ID from ephemeral query: {conn_id} โ†” {client_id}") - logger.info(f"๐Ÿ”— [CORRELATION] WebSocket {conn_id} maps to Frontend clientID: {client_id}") + logger.info(f"[LORO SERVER] Client ID from ephemeral query: {conn_id} <-> {client_id}") + logger.info(f"[CORRELATION] WebSocket {conn_id} maps to Frontend clientID: {client_id}") display_id = client_id if client_id else conn_id - logger.debug(f"๐Ÿ‘ป [Server] Query Ephemeral from {display_id}") + logger.debug(f"[LORO SERVER] Query Ephemeral from {display_id}") try: # Get all current ephemeral state using proper Loro EphemeralStore API all_states = doc.ephemeral_store.get_all_states() all_keys = list(all_states.keys()) ephemeral_update = doc.ephemeral_store.encode_all() - logger.info(f"๐Ÿ“Š [Server] Ephemeral query response for {display_id} - all_keys: {all_keys}, encoded_length: {len(ephemeral_update)}") - logger.debug(f"๐Ÿ“ก SERVER DEBUG - Client {display_id} requesting ephemeral state: " + logger.info(f"[LORO SERVER] Ephemeral query response for {display_id} - all_keys: {all_keys}, encoded_length: {len(ephemeral_update)}") + logger.debug(f"SERVER DEBUG - Client {display_id} requesting ephemeral state: " f"all_keys_available={all_keys}, " f"encoded_length={len(ephemeral_update)}, " f"total_connections={len(doc.conns)}") @@ -826,7 +830,7 @@ async def handle_query_ephemeral(conn, doc, message_data): await conn.send(json.dumps(asdict(response))) except Exception as e: - logger.error(f"[Server] Error handling query ephemeral: {e}") + logger.error(f"[LORO SERVER] Error handling query ephemeral: {e}") doc.last_ephemeral_sender = None async def handle_keepalive(conn, doc, message_data): @@ -838,13 +842,13 @@ async def handle_keepalive(conn, doc, message_data): error_info = message_data.get("error", None) conn_id = get_connection_id(conn) - logger.debug(f"๐Ÿ’“ [Server] *** RECEIVED KEEPALIVE #{ping_id} *** from {conn_id} for doc: {doc.name}") - logger.debug(f"๐Ÿ’“ [Server] Keepalive timestamp: {timestamp}") - logger.debug(f"๐Ÿ’“ [Server] Keepalive reason: {reason}") - logger.debug(f"๐Ÿ’“ [Server] Current server time: {time.time()}") + logger.debug(f"[LORO SERVER] Received keepalive #{ping_id} from {conn_id} for doc: {doc.name}") + logger.debug(f"[LORO SERVER] Keepalive timestamp: {timestamp}") + logger.debug(f"[LORO SERVER] Keepalive reason: {reason}") + logger.debug(f"[LORO SERVER] Current server time: {time.time()}") if error_info: - logger.warning(f"๐Ÿ’“ [Server] Keepalive indicated client error: {error_info}") + logger.warning(f"[LORO SERVER] Keepalive indicated client error: {error_info}") # Send a keepalive response back to acknowledge keepalive_response = { @@ -855,22 +859,22 @@ async def handle_keepalive(conn, doc, message_data): "acknowledged": True } - logger.debug(f"๐Ÿ’“ [Server] *** SENDING KEEPALIVE ACK #{ping_id} *** to {conn_id}") - logger.debug(f"๐Ÿ’“ [Server] ACK message: {keepalive_response}") + logger.debug(f"[LORO SERVER] Sending keepalive ack #{ping_id} to {conn_id}") + logger.debug(f"[LORO SERVER] ACK message: {keepalive_response}") await conn.send(json.dumps(keepalive_response)) - logger.debug(f"โœ… [Server] *** KEEPALIVE ACK #{ping_id} SENT *** - connection maintained") + logger.debug(f"[LORO SERVER] Keepalive ack #{ping_id} sent; connection maintained") except Exception as e: - logger.error(f"๐Ÿ’” [Server] Error handling keepalive: {e}") - logger.error(f"๐Ÿ’” [Server] Keepalive message data: {message_data}") + logger.error(f"[LORO SERVER] Error handling keepalive: {e}") + logger.error(f"[LORO SERVER] Keepalive message data: {message_data}") # Don't propagate error - keepalive failure shouldn't break the connection async def handle_update(conn, doc, message_data): try: update_data = message_data.get("update", []) - logger.debug(f"[Server] Received update: {len(update_data)} bytes") + logger.debug(f"[LORO SERVER] Received update: {len(update_data)} bytes") # Apply update to Loro document if update_data: @@ -878,43 +882,43 @@ async def handle_update(conn, doc, message_data): doc.doc.import_(update_bytes) # Mark document as changed for persistence doc.mark_changed() - logger.debug(f"๐Ÿ’พ [Persistence] Marked document '{doc.name}' as changed") + logger.debug(f"[Persistence] Marked document '{doc.name}' as changed") # Broadcast to other connections - logger.debug(f"[Server] *** STARTING BROADCAST TO OTHER CONNECTIONS ***") - logger.debug(f"[Server] Total connections for doc '{doc.name}': {len(doc.conns)}") - logger.debug(f"[Server] Sender connection: {conn}") - logger.debug(f"[Server] All connections: {list(doc.conns.keys())}") + logger.debug("[LORO SERVER] Starting broadcast to other connections") + logger.debug(f"[LORO SERVER] Total connections for doc '{doc.name}': {len(doc.conns)}") + logger.debug(f"[LORO SERVER] Sender connection: {conn}") + logger.debug(f"[LORO SERVER] All connections: {list(doc.conns.keys())}") # Create a copy of connections to avoid "dictionary changed size during iteration" error connections_copy = list(doc.conns.keys()) - logger.debug(f"[Server] Created connections copy with {len(connections_copy)} connections") + logger.debug(f"[LORO SERVER] Created connections copy with {len(connections_copy)} connections") broadcast_count = 0 for c in connections_copy: - logger.debug(f"[Server] Checking connection {c} (sender: {c == conn})") + logger.debug(f"[LORO SERVER] Checking connection {c} (sender: {c == conn})") # Check if connection is still in the active connections (might have been removed) if c not in doc.conns: - logger.debug(f"โš ๏ธ [Server] Connection {c} no longer active, skipping") + logger.debug(f"[LORO SERVER] Connection {c} no longer active, skipping") continue if c != conn: - logger.debug(f"๐Ÿš€ [Server] Broadcasting update to different connection: {c}") + logger.debug(f"[LORO SERVER] Broadcasting update to different connection: {c}") try: await c.send(json.dumps(message_data)) broadcast_count += 1 - logger.debug(f"โœ… [Server] Successfully sent update to connection {c}") + logger.debug(f"[LORO SERVER] Successfully sent update to connection {c}") except Exception as send_error: - logger.error(f"โŒ [Server] Failed to send update to connection {c}: {send_error}") + logger.error(f"[LORO SERVER] Failed to send update to connection {c}: {send_error}") else: - logger.debug(f"โญ๏ธ [Server] Skipping sender connection: {c}") + logger.debug(f"[LORO SERVER] Skipping sender connection: {c}") - logger.debug(f"[Server] *** BROADCAST COMPLETE *** - Sent to {broadcast_count} connections") + logger.debug(f"[LORO SERVER] Broadcast complete; sent to {broadcast_count} connections") except Exception as e: - logger.error(f"[Server] Error handling update: {e}") + logger.error(f"[LORO SERVER] Error handling update: {e}") import traceback - logger.error(f"[Server] Traceback: {traceback.format_exc()}") + logger.error(f"[LORO SERVER] Traceback: {traceback.format_exc()}") async def setup_ws_connection(conn, path: str): doc_name = path.strip('/').split('?')[0] if path else 'default' @@ -924,30 +928,34 @@ async def setup_ws_connection(conn, path: str): # Extract actual document ID from the WebSocket path if '/' in doc_name: actual_doc_id = doc_name.split('/')[-1] - logger.debug(f"๐Ÿ”„ [Server] WebSocket path '{doc_name}' -> document ID '{actual_doc_id}'") + logger.debug(f"[LORO SERVER] WebSocket path '{doc_name}' -> document ID '{actual_doc_id}'") else: actual_doc_id = doc_name conn_id = get_connection_id(conn) # Add prominent logging that appears right after websockets.server connection logs - print(f"\n๐Ÿ”ฅ๐Ÿ”ฅ๐Ÿ”ฅ [server:py:ws] CONNECTION ESTABLISHED: {conn_id} โ†’ path: {doc_name} โ†’ document: {actual_doc_id} ๐Ÿ”ฅ๐Ÿ”ฅ๐Ÿ”ฅ") - logger.info(f"[server:py:ws] CONNECTION ID: {conn_id} โ†’ path: {doc_name} โ†’ document: {actual_doc_id} (awaiting clientID)") - logger.info(f"๐Ÿ”— [CORRELATION] WebSocket {conn_id} awaiting Frontend clientID mapping...") - logger.info(f"๐Ÿ”ฅ๐Ÿ”ฅ๐Ÿ”ฅ [Server] NEW CONNECTION STARTED: {conn_id} for document: {actual_doc_id} ๐Ÿ”ฅ๐Ÿ”ฅ๐Ÿ”ฅ") - logger.debug(f"๐Ÿ”— [Server] *** NEW CONNECTION *** {conn_id} for document: {actual_doc_id}") + print(f"\n[server:py:ws] Connection established: {conn_id} -> path: {doc_name} -> document: {actual_doc_id}") + logger.info(f"[server:py:ws] Connection ID: {conn_id} -> path: {doc_name} -> document: {actual_doc_id} (awaiting clientID)") + logger.info(f"[CORRELATION] WebSocket {conn_id} awaiting Frontend clientID mapping...") + logger.info(f"[LORO SERVER] New connection started: {conn_id} for document: {actual_doc_id}") + logger.debug(f"[LORO SERVER] New connection: {conn_id} for document: {actual_doc_id}") - doc = get_doc(doc_name) + # get_doc may load the document from persistence (e.g. blocking S3 reads) the + # first time it is accessed; run it in a worker thread so the shared asyncio + # event loop (and HTTP handlers running on it) is not stalled. + doc = await asyncio.to_thread(get_doc, doc_name) doc.conns[conn] = set() + logger.debug(f"[LORO SERVER] Document {actual_doc_id} ready for messaging") - logger.info(f"๐Ÿ“Š [server:py:ws] Total connections for '{actual_doc_id}': {len(doc.conns)} (including {conn_id})") - logger.debug(f"๐Ÿ”— [Server] Total connections now: {len(doc.conns)}") - logger.debug(f"๐Ÿ”— [Server] All connections: {list(doc.conns.keys())}") + logger.info(f"[server:py:ws] Total connections for '{actual_doc_id}': {len(doc.conns)} (including {conn_id})") + logger.debug(f"[LORO SERVER] Total connections now: {len(doc.conns)}") + logger.debug(f"[LORO SERVER] All connections: {list(doc.conns.keys())}") try: # Send initial snapshot using actual Loro document initial_snapshot = doc.doc.export(ExportMode.Snapshot()) - logger.debug(f"[Server] Sending initial snapshot to new client: {len(initial_snapshot)} bytes") + logger.debug(f"[LORO SERVER] Sending initial snapshot to new client: {len(initial_snapshot)} bytes") await conn.send(initial_snapshot) # Send current ephemeral state to new client using proper EphemeralStore API @@ -960,18 +968,18 @@ async def setup_ws_connection(conn, path: str): docId=doc_name ) await conn.send(json.dumps(asdict(ephemeral_message))) - logger.debug(f"[Server] Sent initial ephemeral state to new client: {len(ephemeral_data)} bytes") + logger.debug(f"[LORO SERVER] Sent initial ephemeral state to new client: {len(ephemeral_data)} bytes") except Exception as ephemeral_error: - logger.warn(f"[Server] Failed to send initial ephemeral state: {ephemeral_error}") + logger.warning(f"[LORO SERVER] Failed to send initial ephemeral state: {ephemeral_error}") async for message in conn: await message_listener(conn, doc, message) except websockets.exceptions.ConnectionClosed: - logger.info(f"๐Ÿšช [server:py:ws] WebSocket connection {conn_id} closed normally") + logger.info(f"[server:py:ws] WebSocket connection {conn_id} closed normally") logger.debug(f"WebSocket connection {conn_id} closed") except Exception as e: - logger.info(f"โŒ [server:py:ws] WebSocket connection {conn_id} error: {e}") + logger.info(f"[server:py:ws] WebSocket connection {conn_id} error: {e}") logger.error(f"WebSocket connection {conn_id} error: {e}") finally: close_conn(doc, conn) @@ -1007,10 +1015,10 @@ def __init__(self, host: str = "localhost", port: int = 3002, async def start(self): """Start the WebSocket server""" - logger.debug(f"๐Ÿš€ Starting LoroWebSocketServer") - logger.debug(f" Host: {self.host}") - logger.debug(f" Port: {self.port}") - logger.debug(f" Auto-save interval: {self.autosave_interval_sec} seconds") + logger.debug(f"Starting LoroWebSocketServer") + logger.debug(f"Host: {self.host}") + logger.debug(f"Port: {self.port}") + logger.debug(f"Auto-save interval: {self.autosave_interval_sec} seconds") self.running = True @@ -1021,12 +1029,12 @@ async def handler(websocket, path): await setup_ws_connection(websocket, path) self.server = await serve(handler, self.host, self.port) - logger.debug(f"โœ… LoroWebSocketServer running on ws://{self.host}:{self.port}") + logger.debug(f"LoroWebSocketServer running on ws://{self.host}:{self.port}") # Start background autosave task - logger.info(f"๐Ÿ”„ Starting background services...") + logger.info(f"Starting background services...") self._autosave_task = asyncio.create_task(self._autosave_models()) - logger.info(f" โœ“ Auto-save service ({self.autosave_interval_sec}s interval)") + logger.info(f"Auto-save service ({self.autosave_interval_sec}s interval)") try: # Keep the server running @@ -1036,7 +1044,7 @@ async def handler(websocket, path): async def stop(self): """Stop the WebSocket server""" - logger.debug("๐Ÿ›‘ Stopping LoroWebSocketServer...") + logger.debug("Stopping LoroWebSocketServer...") self.running = False # Cancel autosave task @@ -1048,61 +1056,65 @@ async def stop(self): pass # Perform final save of all documents - logger.debug("๐Ÿ’พ Performing final save of all documents...") + logger.debug("Performing final save of all documents...") save_results = save_all_docs() saved_count = sum(1 for success in save_results.values() if success) - logger.debug(f"โœ… Final save completed: {saved_count}/{len(save_results)} documents saved") + logger.debug(f"Final save completed: {saved_count}/{len(save_results)} documents saved") # Close server if self.server: self.server.close() await self.server.wait_closed() - logger.debug("โœ… WebSocket server stopped") + logger.debug("WebSocket server stopped") async def _autosave_models(self): """Periodically auto-save all models at the configured interval""" - logger.info(f"๐Ÿš€ Auto-save task started with interval: {self.autosave_interval_sec} seconds") + logger.info(f"Auto-save task started with interval: {self.autosave_interval_sec} seconds") while self.running: try: await asyncio.sleep(self.autosave_interval_sec) if self.running: - logger.debug(f"๐Ÿ” Auto-save check: found {len(docs)} documents") + logger.debug(f"Auto-save check: found {len(docs)} documents") if docs: - logger.info(f"๐Ÿ”„ Auto-saving {len(docs)} documents...") + logger.info(f"Auto-saving {len(docs)} documents...") saved_count = 0 unchanged_count = 0 for doc_name, doc in docs.items(): try: if doc.needs_save(): - success = doc.save_to_persistence() + # Run the (potentially blocking) persistence call in a + # worker thread so blocking I/O (e.g. S3 uploads) does + # not stall the shared asyncio event loop and HTTP + # handlers running on it. + success = await asyncio.to_thread(doc.save_to_persistence) if success: saved_count += 1 - logger.debug(f"๐Ÿ’พ Auto-saved document: {doc_name}") + logger.debug(f"Auto-saved document: {doc_name}") else: - logger.warning(f"โš ๏ธ Auto-save failed for document: {doc_name}") + logger.warning(f"Auto-save failed for document: {doc_name}") else: unchanged_count += 1 - logger.debug(f"โญ๏ธ Skipping auto-save for unchanged document: {doc_name}") + logger.debug(f"Skipping auto-save for unchanged document: {doc_name}") except Exception as e: - logger.error(f"โŒ Error auto-saving document {doc_name}: {e}") + logger.error(f"Error auto-saving document {doc_name}: {e}") if saved_count > 0: - logger.info(f"โœ… Auto-save completed: {saved_count} saved, {unchanged_count} unchanged") + logger.info(f"Auto-save completed: {saved_count} saved, {unchanged_count} unchanged") elif unchanged_count > 0: - logger.debug(f"โ„น๏ธ Auto-save check: {unchanged_count} documents unchanged, none saved") + logger.debug(f"Auto-save check: {unchanged_count} documents unchanged, none saved") else: - logger.debug(f"๐Ÿ” No documents to auto-save") + logger.debug(f"No documents to auto-save") except asyncio.CancelledError: - logger.debug("๐Ÿ›‘ Auto-save task cancelled") + logger.debug("Auto-save task cancelled") break except Exception as e: - logger.error(f"โŒ Error in auto-save loop: {e}") + logger.error(f"Error in auto-save loop: {e}") - logger.debug("โœ… Auto-save task stopped") + logger.debug("Auto-save task stopped") def save_all_models(self) -> Dict[str, bool]: """ @@ -1111,7 +1123,7 @@ def save_all_models(self) -> Dict[str, bool]: Returns: Dictionary mapping doc_id to save success status """ - logger.debug(f"๐Ÿ’พ Manually saving {len(docs)} documents...") + logger.debug(f"Manually saving {len(docs)} documents...") return save_all_docs() def generate_client_id(self) -> str: @@ -1123,7 +1135,7 @@ def generate_client_id(self) -> str: Unique client ID string (timestamp-based) """ client_id = str(int(time.time() * 1000)) - logger.debug(f"๐Ÿ†” Generated new client ID: {client_id}") + logger.debug(f"Generated new client ID: {client_id}") return client_id @property @@ -1160,7 +1172,7 @@ async def send_initial_snapshots(self, websocket, client_id: str, doc_id: Option doc = get_doc(doc_id) snapshot = doc.doc.export(ExportMode.Snapshot()) await websocket.send(snapshot) - logger.debug(f"๐Ÿ“ธ Sent initial snapshot for doc '{doc_id}' to client {client_id}: {len(snapshot)} bytes") + logger.debug(f"Sent initial snapshot for doc '{doc_id}' to client {client_id}: {len(snapshot)} bytes") # Send ephemeral state ephemeral_data = doc.ephemeral_store.encode_all() @@ -1171,16 +1183,16 @@ async def send_initial_snapshots(self, websocket, client_id: str, doc_id: Option docId=doc_id ) await websocket.send(json.dumps(asdict(ephemeral_message))) - logger.debug(f"๐Ÿ“ก Sent initial ephemeral state for doc '{doc_id}' to client {client_id}: {len(ephemeral_data)} bytes") + logger.debug(f"Sent initial ephemeral state for doc '{doc_id}' to client {client_id}: {len(ephemeral_data)} bytes") else: # Send snapshots for all documents (if any) for doc_name in docs.keys(): doc = docs[doc_name] snapshot = doc.doc.export(ExportMode.Snapshot()) await websocket.send(snapshot) - logger.debug(f"๐Ÿ“ธ Sent snapshot for doc '{doc_name}' to client {client_id}: {len(snapshot)} bytes") + logger.debug(f"Sent snapshot for doc '{doc_name}' to client {client_id}: {len(snapshot)} bytes") except Exception as e: - logger.error(f"โŒ Error sending initial snapshots to client {client_id}: {e}") + logger.error(f"Error sending initial snapshots to client {client_id}: {e}") async def handle_message(self, client_id: str, message: str): """ @@ -1194,7 +1206,7 @@ async def handle_message(self, client_id: str, message: str): # Find the client's connection client = self.clients.get(client_id) if not client: - logger.warning(f"โš ๏ธ Client {client_id} not found in clients dict") + logger.warning(f"Client {client_id} not found in clients dict") return conn = client.websocket @@ -1211,7 +1223,7 @@ async def handle_message(self, client_id: str, message: str): await message_listener(conn, doc, message) except Exception as e: - logger.error(f"โŒ Error handling message from client {client_id}: {e}") + logger.error(f"Error handling message from client {client_id}: {e}") def main(): @@ -1232,7 +1244,7 @@ async def run_server(): # with open(custom_file, 'r', encoding='utf-8') as f: # return f.read() # except Exception as e: - # logger.error(f"โŒ Custom load error for {doc_id}: {e}") + # logger.error(f"Custom load error for {doc_id}: {e}") # return None # def custom_save_model(doc_id: str, lexical_json: str) -> bool: @@ -1246,7 +1258,7 @@ async def run_server(): # f.write(lexical_json) # return True # except Exception as e: - # logger.error(f"โŒ Custom save error for {doc_id}: {e}") + # logger.error(f"Custom save error for {doc_id}: {e}") # return False # Create and start server with persistence @@ -1261,14 +1273,14 @@ async def run_server(): try: await server.start() except KeyboardInterrupt: - logger.debug("๐Ÿ›‘ Shutting down server...") + logger.debug("Shutting down server...") finally: await server.stop() try: asyncio.run(run_server()) except KeyboardInterrupt: - logger.debug("โœ… Server shutdown complete") + logger.debug("Server shutdown complete") if __name__ == "__main__": main() diff --git a/package.json b/package.json index 54304322..7c87e97b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@datalayer/lexical-loro", - "version": "1.0.3", + "version": "1.0.5", "main": "lib/index.js", "files": [ "lib/**/*.{css,d.ts,eot,gif,html,jpg,js,js.map,json,png,svg,woff2,ttf}", @@ -28,7 +28,7 @@ "scripts": { "build": "tsc -b && vite build", "dev": "cross-env NODE_ENV=development concurrently \"npm:server:py:ws\" \"npm:server:py:mcp\" \"vite --host --port 3000\"", - "build:tsc": "tsc", + "build:lib": "tsc", "build:dev": "vite build", "build:prod": "vite build --mode production", "server:loro": "fkill -s :1235 && cross-env HOST=localhost PORT=1235 YPERSISTENCE=./.wss-loro tsx src/collab/loro/servers/ws/server.ts", @@ -52,7 +52,7 @@ "server": "tsx dev/node-server.ts", "server:py": "lexical-loro-server", "server:py:dev": "python3 -m lexical_loro.cli", - "server:py:ws": "python3 -m lexical_loro.cli --host localhost --port 3002 --autosave-interval 5", + "server:py:ws": "fkill -s :3002 || true && python3 -m lexical_loro.cli --host localhost --port 3002 --autosave-interval 5", "server:py:mcp": "python3 -m lexical_loro.mcp start --transport streamable-http --host 0.0.0.0 --port 3001 --websocket-url ws://localhost:3002 --documents-path ./documents --log-level DEBUG", "test:js": "vitest run", "test:py": "python3 -m pytest tests/ -v", @@ -60,7 +60,7 @@ "test:py:watch": "python3 -m pytest tests/ -v --tb=short -f" }, "dependencies": { - "@datalayer/primer-addons": "^1.0.8", + "@datalayer/primer-addons": "^1.0.12", "@floating-ui/react": "^0.27.8", "@lexical/clipboard": "^0.35.0", "@lexical/code": "^0.35.0", diff --git a/split/index.html b/split/index.html index a7b4a0aa..54efdcae 100644 --- a/split/index.html +++ b/split/index.html @@ -1,5 +1,5 @@ diff --git a/src/App.tsx b/src/App.tsx index 5f406876..7c168ab5 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/Editor.tsx b/src/Editor.tsx index 85e9428a..f53c3698 100644 --- a/src/Editor.tsx +++ b/src/Editor.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -116,6 +116,7 @@ export default function Editor(): JSX.Element { const [isSmallWidthViewport, setIsSmallWidthViewport] = useState(false); const [editor] = useLexicalComposerContext(); + const collabId = new URLSearchParams(window.location.search).get('collabId') || 'main'; const [activeEditor, setActiveEditor] = useState(editor); const [isLinkEditMode, setIsLinkEditMode] = useState(false); @@ -188,13 +189,13 @@ export default function Editor(): JSX.Element { {isCollab ? ( useYjs ? ( ) : ( { const isLastRoot = index === rootNodes.length - 1; @@ -86,9 +86,9 @@ export function setupLoroDebugging(binding: Binding): void { }, verifyStructure: () => { const binding = (window as any).debugLoro.binding as Binding; - if (!binding) return console.log('โŒ Loro Binding not available'); + if (!binding) return console.log(' Loro Binding not available'); - console.log('๐Ÿ” LORO TREE VERIFICATION:'); + console.log(' LORO TREE VERIFICATION:'); const tree = binding.tree; const nodes = tree.nodes(); @@ -98,7 +98,7 @@ export function setupLoroDebugging(binding: Binding): void { // Check mapping consistency const mapper = binding.nodeMapper; - console.log('\n๐Ÿ“ Node Mappings:'); + console.log('\n Node Mappings:'); nodes.forEach((node, index) => { const data = Object.fromEntries(node.data.entries()); @@ -106,7 +106,7 @@ export function setupLoroDebugging(binding: Binding): void { // Get lexical key from mapper instead of node data const lexicalKey = binding.nodeMapper?.getLexicalKeyByLoroId(treeId) || 'no-key'; - console.log(`\n๐Ÿ“ Node ${index}:`); + console.log(`\n Node ${index}:`); console.log(' TreeID:', treeId); console.log(' Lexical Key:', lexicalKey); console.log(' Element Type:', data.elementType || 'N/A'); @@ -134,7 +134,7 @@ export function setupLoroDebugging(binding: Binding): void { return !parent && !data.isRoot; }); if (orphanedNodes.length > 0) { - console.log('\nโš ๏ธ WARNING: Found orphaned nodes (no parent, not root):'); + console.log('\n WARNING: Found orphaned nodes (no parent, not root):'); orphanedNodes.forEach(node => { const data = Object.fromEntries(node.data.entries()); const lexicalKey = binding.nodeMapper?.getLexicalKeyByLoroId(node.id) || 'no-key'; @@ -143,7 +143,7 @@ export function setupLoroDebugging(binding: Binding): void { } // Show parent-child relationships - console.log('\n๐ŸŒณ Parent-Child Relationships:'); + console.log('\n Parent-Child Relationships:'); nodes.forEach(node => { const data = Object.fromEntries(node.data.entries()); const parent = node.parent(); @@ -178,7 +178,7 @@ export function setupLoroDebugging(binding: Binding): void { // Get lexical key from mapper instead of node data const lexicalKey = binding.nodeMapper?.getLexicalKeyByLoroId(node.id) || 'no-key'; - console.log('๐Ÿ” Loro Node Details:', { + console.log(' Loro Node Details:', { treeId: node.id, lexicalKey: lexicalKey, elementType: data.elementType, @@ -191,20 +191,20 @@ export function setupLoroDebugging(binding: Binding): void { // Handle different lexical data formats if (Object.keys(lexicalProps).length > 0) { - console.log('๐Ÿ“„ Lexical Data (Individual Properties):', lexicalProps); + console.log(' Lexical Data (Individual Properties):', lexicalProps); } else if (data.lexical) { if (typeof data.lexical === 'object') { - console.log('๐Ÿ“„ Lexical Data (Current JSON Object):', data.lexical); + console.log(' Lexical Data (Current JSON Object):', data.lexical); } else if (typeof data.lexical === 'string') { try { const lexicalData = JSON.parse(data.lexical); - console.log('๐Ÿ“„ Lexical Data (Legacy JSON String):', lexicalData); + console.log(' Lexical Data (Legacy JSON String):', lexicalData); } catch (e) { - console.log('โŒ Failed to parse lexical data:', e); + console.log(' Failed to parse lexical data:', e); } } } else { - console.log('โš ๏ธ No lexical data found for this node'); + console.log(' No lexical data found for this node'); } // Fetch and log the corresponding lexical node @@ -237,15 +237,15 @@ export function setupLoroDebugging(binding: Binding): void { }); if (nodeInfo) { - console.log('๐Ÿ”— Linked Lexical Node:', nodeInfo); + console.log(' Linked Lexical Node:', nodeInfo); } else { - console.log('โš ๏ธ No lexical node found in editor state for key:', lexicalKey, '(node may have been deleted or not yet created)'); + console.log(' No lexical node found in editor state for key:', lexicalKey, '(node may have been deleted or not yet created)'); } } catch (e) { - console.log('โŒ Failed to fetch lexical node:', e); + console.log(' Failed to fetch lexical node:', e); } } else { - console.log('โš ๏ธ No valid lexical key found for this Loro node (key:', lexicalKey, ')'); + console.log(' No valid lexical key found for this Loro node (key:', lexicalKey, ')'); } } else { console.warn(`Node with TreeID "${treeId}" not found`); @@ -307,7 +307,7 @@ export function setupLoroDebugging(binding: Binding): void { const nodes = tree.nodes(); // Debug: log the actual structure to console as a tree - console.log('๐ŸŸข LORO Tree structure:'); + console.log(' LORO Tree structure:'); console.log(` Total nodes: ${nodes.length}`); console.log(` Peer ID: ${binding.doc.peerIdStr}`); console.log(` Client ID: ${binding.clientID}`); @@ -344,7 +344,7 @@ export function setupLoroDebugging(binding: Binding): void { }); if (rootNodes.length === 0) { - console.log(' โš ๏ธ No root nodes found!'); + console.log(' No root nodes found!'); } else { rootNodes.forEach((root, index) => { const isLastRoot = index === rootNodes.length - 1; @@ -352,9 +352,9 @@ export function setupLoroDebugging(binding: Binding): void { }); } - console.log('๐ŸŸข Loro Tree:', tree.toJSON()); + console.log(' Loro Tree:', tree.toJSON()); - console.log('๐ŸŸข Lexical State:', binding.editor.getEditorState().toJSON()); + console.log(' Lexical State:', binding.editor.getEditorState().toJSON()); const treeHTML = (window as any).debugLoro.generateTreeHTML(nodes); @@ -420,7 +420,7 @@ export function setupLoroDebugging(binding: Binding): void { debugDiv.innerHTML = `
- ๐ŸŸข LORO TREE โ‹ฎโ‹ฎ drag + LORO TREE โ‹ฎโ‹ฎ drag
Total nodes: ${nodes.length}
@@ -430,12 +430,12 @@ export function setupLoroDebugging(binding: Binding): void { ${treeHTML}
- ๐Ÿ”„ Refresh | - โœ… Verify | - ๐Ÿ“ Log | - ๐Ÿงน Cleanup | - ๐Ÿ”„ Reset | - โŒ Close + Refresh | + Verify | + Log | + Cleanup | + Reset | + Close
`; @@ -443,29 +443,29 @@ export function setupLoroDebugging(binding: Binding): void { }, cleanupEphemeralStore: (provider?: any) => { if (!provider) { - console.log('โš ๏ธ No provider passed. Usage: window.debugLoro.cleanupEphemeralStore(provider)'); + console.log(' No provider passed. Usage: window.debugLoro.cleanupEphemeralStore(provider)'); console.log('You can get the provider from your useCollaboration hook'); return; } if (typeof provider.cleanupStaleStates !== 'function') { - console.log('โŒ Provider does not have cleanupStaleStates method'); + console.log(' Provider does not have cleanupStaleStates method'); return; } - console.log('๐Ÿงน Cleaning up stale ephemeral states...'); + console.log(' Cleaning up stale ephemeral states...'); provider.cleanupStaleStates(); }, resetGlobalEphemeralStore: () => { try { // We need to access the WebsocketProvider class which may not be globally available - console.log('๐Ÿ”„ Attempting to reset global EphemeralStore...'); - console.log('๐Ÿ’ก You can also refresh the browser to clear the global store'); + console.log(' Attempting to reset global EphemeralStore...'); + console.log(' You can also refresh the browser to clear the global store'); // For now, instruct user to refresh alert('To reset the global ephemeral store and clear all collaborators, please refresh the browser page.'); } catch (error) { - console.warn('โŒ Reset failed:', error.message); + console.warn(' Reset failed:', error.message); } } }; diff --git a/src/collab/loro/LexicalCollaborationContext.ts b/src/collab/loro/LexicalCollaborationContext.ts index 826114d6..46a8722d 100644 --- a/src/collab/loro/LexicalCollaborationContext.ts +++ b/src/collab/loro/LexicalCollaborationContext.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/collab/loro/LexicalCollaborationPlugin.tsx b/src/collab/loro/LexicalCollaborationPlugin.tsx index 6534d5e5..7107c494 100644 --- a/src/collab/loro/LexicalCollaborationPlugin.tsx +++ b/src/collab/loro/LexicalCollaborationPlugin.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -46,8 +46,43 @@ type Props = { websocketUrl?: string; // Handler called when the initial snapshot is loaded onInitialization?: (isInitialized: boolean) => void; + // Handler called once the local collaborator identity is resolved + onIdentityResolved?: (identity: { + name: string; + color: string; + clientID: number; + }) => void; }; +function getIdentityField( + awarenessData: object | undefined, + keys: string[], +): string | undefined { + if (!awarenessData || typeof awarenessData !== 'object') { + return undefined; + } + + const data = awarenessData as Record; + const user = data.user; + const userRecord = + user && typeof user === 'object' ? (user as Record) : undefined; + + for (const key of keys) { + const direct = data[key]; + if (typeof direct === 'string' && direct.trim().length > 0) { + return direct; + } + if (userRecord) { + const nested = userRecord[key]; + if (typeof nested === 'string' && nested.trim().length > 0) { + return nested; + } + } + } + + return undefined; +} + export function LoroCollaborationPlugin({ id, providerFactory, @@ -62,6 +97,7 @@ export function LoroCollaborationPlugin({ showCollaborators = true, websocketUrl = 'ws://localhost:3002', onInitialization, + onIdentityResolved, }: Props): JSX.Element { const isBindingInitialized = useRef(false); const isProviderInitialized = useRef(false); @@ -124,25 +160,33 @@ export function LoroCollaborationPlugin({ docMap, excludedProperties, ); - - // Update collaboration context with deterministic name based on client ID - // This ensures consistent names across browser sessions + const deterministicUserData = generateDeterministicUserData(binding.clientID); - console.log('Setting deterministic user data based on client ID:', { - clientId: binding.clientID, - name: deterministicUserData.name, - color: deterministicUserData.color - }); - - // Update the collaboration context with stable name and color - const finalName = username || deterministicUserData.name; - const finalColor = cursorColor || deterministicUserData.color; + + // Prefer explicit username/color first, then awareness identity, then deterministic fallback. + const awarenessDisplayName = getIdentityField(awarenessData, [ + 'display_name', + 'displayName', + 'name', + 'username', + 'handle', + ]); + const awarenessColor = getIdentityField(awarenessData, ['color']); + const finalName = username || awarenessDisplayName || deterministicUserData.name; + const finalColor = cursorColor || awarenessColor || deterministicUserData.color; collabContext.name = finalName; collabContext.color = finalColor; collabContext.clientID = binding.clientID; - - // Update the awareness state immediately with the deterministic name + + // Notify listeners of the resolved local collaborator identity. + onIdentityResolved?.({ + name: finalName, + color: finalColor, + clientID: binding.clientID, + }); + + // Update the awareness state immediately with the resolved identity. updateLocalStateName(provider, finalName, finalColor); setBinding(binding); @@ -150,7 +194,7 @@ export function LoroCollaborationPlugin({ return () => { // Clean up binding resources if needed }; - }, [editor, provider, id, docMap, doc, excludedProperties, collabContext, username, cursorColor]); + }, [editor, provider, id, docMap, doc, excludedProperties, collabContext, username, cursorColor, awarenessData]); if (!provider || !binding) { return <>; diff --git a/src/collab/loro/State.ts b/src/collab/loro/State.ts index befa0114..4bf5d5ad 100644 --- a/src/collab/loro/State.ts +++ b/src/collab/loro/State.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/collab/loro/components/LoroCollaborationUI.tsx b/src/collab/loro/components/LoroCollaborationUI.tsx index 7963fc67..9a7b1348 100644 --- a/src/collab/loro/components/LoroCollaborationUI.tsx +++ b/src/collab/loro/components/LoroCollaborationUI.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/collab/loro/components/LoroCollaborators.tsx b/src/collab/loro/components/LoroCollaborators.tsx index b225fd6e..92b7a8be 100644 --- a/src/collab/loro/components/LoroCollaborators.tsx +++ b/src/collab/loro/components/LoroCollaborators.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -69,7 +69,7 @@ export function LoroCollaborators({ {/* Current User (if they have a cursor) */} {currentUserData && ( { - // If it's a hex color, convert to rgba - if (color.startsWith('#')) { - const hex = color.slice(1); - const r = parseInt(hex.slice(0, 2), 16); - const g = parseInt(hex.slice(2, 4), 16); - const b = parseInt(hex.slice(4, 6), 16); - return `rgba(${r}, ${g}, ${b}, ${opacity})`; - } - // If it's already rgba or rgb, just return as is (basic support) - return color; - }; - - const circleColor = isCurrentUser ? getColorWithOpacity(color, 0.1) : color; - const badgeColor = isCurrentUser ? getColorWithOpacity(color, 0.1) : color; + const circleColor = color; + const badgeColor = color; + const shortClientId = String(clientId).slice(0, 4); return (
- {name} + {`${name} ${shortClientId}`}
); diff --git a/src/collab/loro/components/index.ts b/src/collab/loro/components/index.ts index ba8c7eba..8fc7d843 100644 --- a/src/collab/loro/components/index.ts +++ b/src/collab/loro/components/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/collab/loro/index.ts b/src/collab/loro/index.ts index 406c59d7..b61ce838 100644 --- a/src/collab/loro/index.ts +++ b/src/collab/loro/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/collab/loro/integrators/BaseIntegrator.ts b/src/collab/loro/integrators/BaseIntegrator.ts index 6b47da37..761b8b30 100644 --- a/src/collab/loro/integrators/BaseIntegrator.ts +++ b/src/collab/loro/integrators/BaseIntegrator.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/collab/loro/integrators/CounterIntegrator.ts b/src/collab/loro/integrators/CounterIntegrator.ts index b706f28d..151ace99 100644 --- a/src/collab/loro/integrators/CounterIntegrator.ts +++ b/src/collab/loro/integrators/CounterIntegrator.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/collab/loro/integrators/ListIntegrator.ts b/src/collab/loro/integrators/ListIntegrator.ts index 5cce92f0..551d3539 100644 --- a/src/collab/loro/integrators/ListIntegrator.ts +++ b/src/collab/loro/integrators/ListIntegrator.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -23,7 +23,7 @@ interface ListDiff { export class ListIntegrator implements BaseIntegrator { integrate(diff: ListDiff, binding: Binding, provider: Provider): void { - console.log('๐Ÿ“‹ Handling ListDiff:', diff); + console.log(' Handling ListDiff:', diff); this.integrateInternal(diff, binding, provider); } @@ -42,7 +42,7 @@ export class ListIntegrator implements BaseIntegrator { this.integrateRetain(change, binding, provider); break; default: - console.warn(`๐Ÿ“‹ Unknown list change type: ${change.type}`); + console.warn(` Unknown list change type: ${change.type}`); } }); } @@ -83,7 +83,7 @@ export class ListIntegrator implements BaseIntegrator { // They represent portions of the list that remain unchanged if (change.attributes) { - console.log(`๐Ÿ“‹ List retain with attributes at ${change.index}, length: ${change.length}`, change.attributes); + console.log(` List retain with attributes at ${change.index}, length: ${change.length}`, change.attributes); // Handle any attribute changes if needed } } diff --git a/src/collab/loro/integrators/MapIntegrator.ts b/src/collab/loro/integrators/MapIntegrator.ts index c62185ee..289f02d4 100644 --- a/src/collab/loro/integrators/MapIntegrator.ts +++ b/src/collab/loro/integrators/MapIntegrator.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -249,7 +249,7 @@ export class MapIntegrator implements BaseIntegrator { const registeredNodes = binding.editor._nodes; const nodeInfo = registeredNodes.get(targetType); if (!nodeInfo) { - console.warn(`๐Ÿ—บ๏ธ MapIntegrator: Node type '${targetType}' not registered`); + console.warn(` MapIntegrator: Node type '${targetType}' not registered`); return; } const serializedData = { ...data }; @@ -266,7 +266,7 @@ export class MapIntegrator implements BaseIntegrator { binding.nodeMapper.removeMappingForKey(lexicalKey); binding.nodeMapper.setMapping(newNode.getKey(), treeId); } catch (error) { - console.warn(`๐Ÿ—บ๏ธ MapIntegrator: importJSON+replace failed for decorator ${targetType} node ${lexicalKey}:`, error); + console.warn(` MapIntegrator: importJSON+replace failed for decorator ${targetType} node ${lexicalKey}:`, error); } } else { try { @@ -284,7 +284,7 @@ export class MapIntegrator implements BaseIntegrator { const writable = targetNode.getWritable(); writable.updateFromJSON(serializedData); } catch (error) { - console.warn(`๐Ÿ—บ๏ธ MapIntegrator: updateFromJSON failed for ${targetType} node ${lexicalKey}:`, error); + console.warn(` MapIntegrator: updateFromJSON failed for ${targetType} node ${lexicalKey}:`, error); } } } diff --git a/src/collab/loro/integrators/TextIntegrator.ts b/src/collab/loro/integrators/TextIntegrator.ts index 2698bc0e..c2171cb3 100644 --- a/src/collab/loro/integrators/TextIntegrator.ts +++ b/src/collab/loro/integrators/TextIntegrator.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -42,7 +42,7 @@ export class TextIntegrator implements BaseIntegrator { this.integrateTextRetain(change, binding, provider); break; default: - console.warn(`๐Ÿ“ Unknown text change type: ${change.type}`); + console.warn(` Unknown text change type: ${change.type}`); } }); } diff --git a/src/collab/loro/integrators/TreeIntegrator.ts b/src/collab/loro/integrators/TreeIntegrator.ts index aaf9ec39..568d2957 100644 --- a/src/collab/loro/integrators/TreeIntegrator.ts +++ b/src/collab/loro/integrators/TreeIntegrator.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -7,7 +7,10 @@ import { $getRoot, $getNodeByKey, $isElementNode, - ElementNode + $isDecoratorNode, + ElementNode, + LexicalNode, + NodeKey, } from 'lexical'; import { TreeID } from 'loro-crdt'; import { BaseIntegrator } from './BaseIntegrator'; @@ -15,6 +18,7 @@ import { Binding } from '../Bindings'; import { Provider } from '../State'; import { parseTreeID } from '../utils/Utils'; import { createLexicalNodeFromLoro } from '../nodes/NodeFactory'; +import { invariant } from '../utils/Invariant'; interface TreeDiff { type: 'tree'; @@ -55,109 +59,164 @@ export class TreeIntegrator implements BaseIntegrator { } } + // Loro often splits a node's placement into a parentless `create` followed + // by a `move` that supplies the real parent/index. Inline nodes (text, + // linebreak) can never live at the root โ€” not even transiently โ€” so fold + // the move's parent/index back into the create and drop the now-redundant + // move. This resolves the placement up front instead of skipping the node. + const moveByTarget = new Map(); + for (const mv of moves) { + moveByTarget.set(String(mv.target), mv); + } + const foldedMoveTargets = new Set(); + for (const cr of creates) { + if (cr.parent === undefined) { + const mv = moveByTarget.get(String(cr.target)); + if (mv && mv.parent !== undefined) { + cr.parent = mv.parent; + cr.index = mv.index; + foldedMoveTargets.add(String(cr.target)); + } + } + } + const effectiveMoves = moves.filter(mv => !foldedMoveTargets.has(String(mv.target))); + // Topologically sort create operations so parents are created before children. // Without this, a TableCellNode may arrive before its parent TableRowNode, // causing the cell to fall back to $getRoot() and appear on one flat line. const sortedCreates = this.topologicalSortCreates(creates, binding); - // Execute: deletes โ†’ creates (parent-first) โ†’ moves - const operations = [...deletes, ...sortedCreates, ...moves]; - - operations.forEach(operation => { - switch (operation.action) { - case 'create': - this.integrateCreate(operation, binding, provider); - break; - case 'move': - this.integrateMove(operation, binding, provider); - break; - case 'delete': - this.integrateDelete(operation, binding, provider); - break; - default: - console.warn(`๐ŸŒณ Unknown tree operation: ${operation.action}`); - } - }); - } - - private integrateCreate( - operation: { target: TreeID; parent?: TreeID; index?: number }, - binding: Binding, - provider: Provider - ): void { - try { - let { nodeKey } = parseTreeID(operation.target); - - // Skip root node creation - root is integrated during initial setup - // But ensure the root mapping exists - // Only treat as root if it's actually a root-type node in Loro - if (nodeKey === "0") { - const treeNode = binding.tree.getNodeByID(operation.target); - const elementType = treeNode?.data.get('elementType'); - if (elementType === 'root' || !elementType) { - const root = $getRoot(); - binding.nodeMapper.setMapping(root.getKey(), operation.target); - return; + // Phase 1: deletes. + deletes.forEach(op => this.integrateDelete(op, binding, provider)); + + // Phase 2: creates (parent-first, with deferral). + // + // Topological sort orders parents before children *within this batch*, but + // a child may still reference a parent whose Lexical mapping is not yet + // established (deeply nested tables, list items inside quotes, Jupyter + // cells, โ€ฆ). Rather than dropping such a node onto the root โ€” which throws + // for inline nodes like text/linebreak ("Only element or decorator nodes + // can be inserted to the root node") and corrupts the document โ€” we defer + // it and retry until a full pass makes no further progress. + // + // Created Lexical nodes are cached so deferred retries reuse the same + // instance instead of importing (and registering) duplicate nodes. + const nodeCache = new Map(); + let pending = sortedCreates; + while (pending.length > 0) { + const stillPending: typeof pending = []; + for (const op of pending) { + if (this.integrateCreate(op, binding, provider, nodeCache) === 'deferred') { + stillPending.push(op); } - // If nodeKey is "0" but it's not actually a root element, continue with normal processing } - - // Check if node already exists and if it's the same TreeID - const existingNode = $getNodeByKey(nodeKey); - if (existingNode) { - const existingTreeID = binding.nodeMapper.getTreeIDByLexicalKey(nodeKey); - if (existingTreeID === operation.target) { - return; - } else { - // Don't reuse existing keys for different TreeIDs - let Lexical generate a fresh one - nodeKey = undefined; // Let createLexicalNodeFromLoro generate a fresh key - } + if (stillPending.length === pending.length) { + // No progress in a full pass: every remaining node references a parent + // that never arrived in this batch. This is a real ordering/data bug. + // Surface it instead of dropping the nodes onto the root (or silently + // discarding inline nodes, which would lose user content). + invariant( + false, + 'TreeIntegrator: create operations reference parents missing from the batch', + { + pending: stillPending.map(op => ({ + target: String(op.target), + parent: op.parent ? String(op.parent) : null, + })), + }, + ); } + pending = stillPending; + } - // Create Lexical node from Loro data - const lexicalNode = createLexicalNodeFromLoro( - operation.target, - binding.tree, - binding - ); + // Phase 3: moves (those not already folded into a create above). + effectiveMoves.forEach(op => this.integrateMove(op, binding, provider)); + } - if (!lexicalNode) { - return; + private integrateCreate( + operation: { target: TreeID; parent?: TreeID; index?: number }, + binding: Binding, + provider: Provider, + nodeCache: Map, + ): 'created' | 'deferred' { + let { nodeKey } = parseTreeID(operation.target); + + // Root node creation is integrated during initial setup. Only treat as + // root if it's actually a root-type node in Loro. + if (nodeKey === "0") { + const treeNode = binding.tree.getNodeByID(operation.target); + const elementType = treeNode?.data.get('elementType'); + if (elementType === 'root' || !elementType) { + const root = $getRoot(); + binding.nodeMapper.setMapping(root.getKey(), operation.target); + return 'created'; } + // nodeKey is "0" but not an actual root element โ€” fall through. + } - // Find parent node - let parentNode: ElementNode; - if (operation.parent) { - const parentKey = binding.nodeMapper.getLexicalKeyByLoroId(operation.parent); - const parentLexicalNode = parentKey ? $getNodeByKey(parentKey) : null; - - if (parentLexicalNode && $isElementNode(parentLexicalNode)) { - parentNode = parentLexicalNode; - } else { - console.warn(`๐ŸŒณ Parent NOT found for ${lexicalNode.getType()} target=${operation.target} parent=${operation.parent} parentKey=${parentKey} parentFound=${!!parentLexicalNode} isElement=${parentLexicalNode ? $isElementNode(parentLexicalNode) : 'N/A'}`); - // For text nodes, we MUST have a proper parent element - if (lexicalNode.getType() === 'text') { - return; - } - - parentNode = $getRoot(); - } - } else { - parentNode = $getRoot(); + // Node already exists with the same TreeID โ†’ idempotent, nothing to do. + const existingNode = $getNodeByKey(nodeKey); + if (existingNode) { + const existingTreeID = binding.nodeMapper.getTreeIDByLexicalKey(nodeKey); + if (existingTreeID === operation.target) { + return 'created'; } + // Different TreeID reuses this key โ€” let Lexical assign a fresh one. + nodeKey = undefined; + } - // Normal insertion - if (operation.index !== undefined) { - parentNode.splice(operation.index, 0, [lexicalNode]); - } else { - parentNode.append(lexicalNode); + // Create the Lexical node once and cache it, so deferred retries reuse + // the same instance instead of importing duplicate nodes. + const cacheKey = String(operation.target); + let lexicalNode = nodeCache.get(cacheKey); + if (lexicalNode === undefined) { + lexicalNode = createLexicalNodeFromLoro(operation.target, binding.tree, binding); + nodeCache.set(cacheKey, lexicalNode); + } + invariant( + lexicalNode != null, + 'integrateCreate: failed to materialise Lexical node from Loro data', + { target: cacheKey }, + ); + + if (operation.parent) { + const parentKey = binding.nodeMapper.getLexicalKeyByLoroId(operation.parent); + const parentLexicalNode = parentKey ? $getNodeByKey(parentKey) : null; + + // Parent expected but not mapped yet โ†’ defer until it is created. This is + // legitimate ordering (a later pass/batch supplies the parent), not an + // error that hides a bug. + if (!(parentLexicalNode && $isElementNode(parentLexicalNode))) { + return 'deferred'; } - // Set up mapping - binding.nodeMapper.setMapping(lexicalNode.getKey(), operation.target); + this.insertChild(parentLexicalNode, lexicalNode, operation.index); + } else { + // No parent โ†’ root. Only element/decorator nodes may live at the root; an + // inline node without a parent is a structural bug, not something to skip. + invariant( + this.canBeRootChild(lexicalNode), + 'integrateCreate: inline node has no parent (cannot live at root)', + { target: cacheKey, nodeType: lexicalNode.getType() }, + ); + this.insertChild($getRoot(), lexicalNode, operation.index); + } + + binding.nodeMapper.setMapping(lexicalNode.getKey(), operation.target); + return 'created'; + } + + /** Only element and decorator nodes may be inserted directly under the root. */ + private canBeRootChild(node: LexicalNode): boolean { + return $isElementNode(node) || $isDecoratorNode(node); + } - } catch (error) { - console.warn(`๐ŸŒณ Error creating node for ${operation.target}:`, error); + /** Insert a child into a parent element at an optional index. */ + private insertChild(parent: ElementNode, child: LexicalNode, index?: number): void { + if (index !== undefined) { + parent.splice(index, 0, [child]); + } else { + parent.append(child); } } @@ -166,54 +225,43 @@ export class TreeIntegrator implements BaseIntegrator { binding: Binding, provider: Provider ): void { - try { - const lexicalKey = binding.nodeMapper.getLexicalKeyByLoroId(operation.target); - if (!lexicalKey) { - console.warn(`๐ŸŒณ No Lexical key found for move target ${operation.target}`); - return; - } - - const nodeToMove = $getNodeByKey(lexicalKey); - if (!nodeToMove) { - console.warn(`๐ŸŒณ Node to move not found: ${lexicalKey}`); - return; - } - - // Find new parent - let newParent: ElementNode; - if (operation.parent) { - const parentKey = binding.nodeMapper.getLexicalKeyByLoroId(operation.parent); - const parentNode = parentKey ? $getNodeByKey(parentKey) : null; - - if (parentNode && $isElementNode(parentNode)) { - newParent = parentNode; - } else { - // For text nodes, we can't move them to root - skip this move operation - // The node is already in the correct position from our create fix - if (nodeToMove.getType() === 'text') { - return; - } - newParent = $getRoot(); - } - } else { - // For text nodes without a parent, skip the move - if (nodeToMove.getType() === 'text') { - return; - } - newParent = $getRoot(); - } - - // Remove from current position and insert at new position - nodeToMove.remove(); - - if (operation.index !== undefined) { - newParent.splice(operation.index, 0, [nodeToMove]); - } else { - newParent.append(nodeToMove); - } + const lexicalKey = binding.nodeMapper.getLexicalKeyByLoroId(operation.target); + invariant( + lexicalKey != null, + 'integrateMove: no Lexical key for move target', + { target: String(operation.target) }, + ); + + const nodeToMove = $getNodeByKey(lexicalKey); + invariant(nodeToMove != null, 'integrateMove: node to move not found', { lexicalKey }); + + // Resolve the new parent. + let newParent: ElementNode; + if (operation.parent) { + const parentKey = binding.nodeMapper.getLexicalKeyByLoroId(operation.parent); + const parentNode = parentKey ? $getNodeByKey(parentKey) : null; + invariant( + parentNode != null && $isElementNode(parentNode), + 'integrateMove: move target parent is not a mapped element', + { target: String(operation.target), parent: String(operation.parent) }, + ); + newParent = parentNode; + } else { + // No parent โ†’ root, only valid for element/decorator nodes. + invariant( + this.canBeRootChild(nodeToMove), + 'integrateMove: inline node cannot be moved to the root', + { lexicalKey, nodeType: nodeToMove.getType() }, + ); + newParent = $getRoot(); + } - } catch (error) { - console.warn(`๐ŸŒณ Error moving node ${operation.target}:`, error); + // Remove from current position and insert at new position. + nodeToMove.remove(); + if (operation.index !== undefined) { + newParent.splice(operation.index, 0, [nodeToMove]); + } else { + newParent.append(nodeToMove); } } @@ -222,31 +270,57 @@ export class TreeIntegrator implements BaseIntegrator { binding: Binding, provider: Provider ): void { - try { - const lexicalKey = binding.nodeMapper.getLexicalKeyByLoroId(operation.target); - if (!lexicalKey) { - console.warn(`๐ŸŒณ No Lexical key found for delete target ${operation.target}`); - return; - } - - const nodeToDelete = $getNodeByKey(lexicalKey); - if (!nodeToDelete) { - console.warn(`๐ŸŒณ Node to delete not found: ${lexicalKey}`); - return; - } + const lexicalKey = binding.nodeMapper.getLexicalKeyByLoroId(operation.target); + // Parent-first delete batches can make child mappings stale before their + // own delete ops arrive. Missing mapping here is therefore benign. + if (!lexicalKey) { + return; + } - // Remove from Lexical tree - nodeToDelete.remove(); - - // Clean up mapping only โ€” do NOT call deleteMapping() here because - // the Loro tree has already processed this deletion from the remote - // peer. Calling tree.delete() again would throw "is deleted or does - // not exist". + const nodeToDelete = $getNodeByKey(lexicalKey); + // Node may already be gone due to an ancestor deletion in this same batch. + if (!nodeToDelete) { binding.nodeMapper.removeMappingForKey(lexicalKey); - - } catch (error) { - console.warn(`๐ŸŒณ Error deleting node ${operation.target}:`, error); + return; + } + + // The root is never deletable in Lexical; a delete resolving to it means a + // mapping is wrong upstream โ€” surface it rather than silently ignoring. + if (nodeToDelete === $getRoot()) { + return; } + + // Clean descendant mappings first so later child-delete ops in the same + // batch become harmless no-ops instead of failing with stale mappings. + const descendantKeys = this.collectDescendantKeys(nodeToDelete); + for (const key of descendantKeys) { + binding.nodeMapper.removeMappingForKey(key); + } + + // Remove from the Lexical tree. + nodeToDelete.remove(); + + // Clean up mapping only โ€” the Loro tree already processed this deletion + // from the remote peer; calling tree.delete() again would throw. + binding.nodeMapper.removeMappingForKey(lexicalKey); + } + + private collectDescendantKeys(node: LexicalNode): NodeKey[] { + if (!$isElementNode(node)) { + return []; + } + + const keys: NodeKey[] = []; + const stack = [...node.getChildren()]; + while (stack.length > 0) { + const current = stack.pop()!; + keys.push(current.getKey()); + if ($isElementNode(current)) { + stack.push(...current.getChildren()); + } + } + + return keys; } /** diff --git a/src/collab/loro/nodes/NodeFactory.ts b/src/collab/loro/nodes/NodeFactory.ts index 4d1f60e9..1d201cc2 100644 --- a/src/collab/loro/nodes/NodeFactory.ts +++ b/src/collab/loro/nodes/NodeFactory.ts @@ -1,11 +1,12 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ import { TreeID, LoroTree } from 'loro-crdt'; import { LexicalNode, NodeKey } from 'lexical'; import { Binding } from '../Bindings'; +import { invariant } from '../utils/Invariant'; /** * Resolve lexical data from Loro, handling Loro container objects. @@ -37,10 +38,9 @@ export function createLexicalNodeFromLoro( parentKey?: NodeKey, nodeDataFromDiff?: any ): LexicalNode | null { - // Get node data from Loro tree - if (!loroTree.has(treeId)) { - return null; - } + // Get node data from Loro tree. A create op for a tree node that does not + // exist is a real inconsistency. + invariant(loroTree.has(treeId), 'NodeFactory: TreeID not present in Loro tree', { treeId }); const treeNode = loroTree.getNodeByID(treeId); @@ -53,32 +53,30 @@ export function createLexicalNodeFromLoro( } if (!lexicalData || typeof lexicalData !== 'object') { - // Last resort: construct a minimal serialization from elementType metadata + // Last resort: reconstruct a minimal serialization from elementType metadata. const fallbackType = nodeDataFromDiff?.elementType || treeNode?.data.get('elementType') || treeNode?.data.get('nodeType'); - if (!fallbackType || typeof fallbackType !== 'string') { - console.warn('๐Ÿญ NodeFactory: No lexical data or elementType for TreeID:', treeId); - return null; - } + invariant( + typeof fallbackType === 'string' && fallbackType.length > 0, + 'NodeFactory: no lexical data or elementType for TreeID', + { treeId }, + ); lexicalData = { type: fallbackType, version: 1 }; } const nodeType: string = lexicalData.type || lexicalData.__type; - if (!nodeType) { - console.warn('๐Ÿญ NodeFactory: No type field in lexical data for TreeID:', treeId); - return null; - } + invariant(!!nodeType, 'NodeFactory: no type field in lexical data for TreeID', { treeId }); - // Get the registered node class from the editor + // Get the registered node class from the editor. const registeredNodes = binding.editor._nodes; const nodeInfo = registeredNodes.get(nodeType); - - if (!nodeInfo) { - console.warn(`๐Ÿญ NodeFactory: Node type '${nodeType}' is not registered in the editor`); - return null; - } + invariant( + nodeInfo != null, + 'NodeFactory: node type is not registered in the editor', + { treeId, nodeType }, + ); // ---------- Generic creation via importJSON ---------- // Every Lexical node class must implement the static `importJSON` method. @@ -89,35 +87,24 @@ export function createLexicalNodeFromLoro( // โ€ข Base properties (format, indent, direction, style, mode, detail, โ€ฆ) // are applied via the chained `updateFromJSON` call // This removes the need for any node-type-specific branching. - try { - const serializedData = { ...lexicalData }; - - // Ensure required serialization fields - if (!serializedData.type) { - serializedData.type = nodeType; - } - if (serializedData.version === undefined) { - serializedData.version = 1; - } - // Provide an empty children array for element-type nodes whose children - // are managed as separate Loro tree nodes (importJSON itself does not - // recurse into children โ€” that is handled by TreeIntegrator). - if (!('children' in serializedData)) { - serializedData.children = []; - } + const serializedData = { ...lexicalData }; - const lexicalNode: LexicalNode = nodeInfo.klass.importJSON(serializedData); - return lexicalNode; - } catch (importError) { - console.warn(`๐Ÿญ NodeFactory: importJSON failed for '${nodeType}', trying constructor fallback:`, importError); - - // Fallback: try no-arg constructor (works for simple nodes) - try { - const lexicalNode: LexicalNode = new nodeInfo.klass(); - return lexicalNode; - } catch (ctorError) { - console.warn(`๐Ÿญ NodeFactory: Constructor also failed for '${nodeType}':`, ctorError); - return null; - } + // Ensure required serialization fields. + if (!serializedData.type) { + serializedData.type = nodeType; + } + if (serializedData.version === undefined) { + serializedData.version = 1; } + // Provide an empty children array for element-type nodes whose children are + // managed as separate Loro tree nodes (importJSON does not recurse into + // children โ€” that is handled by TreeIntegrator). + if (!('children' in serializedData)) { + serializedData.children = []; + } + + // Every registered Lexical node implements importJSON. If it throws, the + // serialized data is malformed โ€” surface it instead of silently substituting + // a blank node via a constructor fallback (which hides the real problem). + return nodeInfo.klass.importJSON(serializedData); } \ No newline at end of file diff --git a/src/collab/loro/nodes/NodesMapper.ts b/src/collab/loro/nodes/NodesMapper.ts index d9a906a0..a0011d52 100644 --- a/src/collab/loro/nodes/NodesMapper.ts +++ b/src/collab/loro/nodes/NodesMapper.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -7,6 +7,7 @@ import { LoroTree, LoroTreeNode, TreeID } from 'loro-crdt'; import { LexicalNode, NodeKey, EditorState } from 'lexical'; import { Binding } from '../Bindings'; import { LexicalNodeData } from '../types/LexicalNodeData'; +import { invariant } from '../utils/Invariant'; /** * Bidirectional mapping between Lexical NodeKeys and Loro TreeIDs @@ -142,18 +143,40 @@ export class NodeMapper { parentTreeID?: TreeID, index?: number ): TreeID { + const insertionIndex = index; + + // Loro requires the insertion index to be within [0, children.length]. An + // out-of-range index means the position was computed against stale/unsynced + // siblings; surface it instead of silently clamping (which would drop the + // node at the wrong position and hide the real ordering bug). + if (insertionIndex !== undefined) { + const parentNode = + parentTreeID !== undefined ? this.tree.getNodeByID(parentTreeID) : null; + const childrenLength = parentNode + ? (parentNode.children()?.length ?? 0) + : this.tree.roots().length; + invariant( + insertionIndex >= 0 && insertionIndex <= childrenLength, + 'createLoroNode: insertion index out of range', + { nodeKey, parentTreeID, insertionIndex, childrenLength }, + ); + } + // Create the tree node first - const treeNode = this.tree.createNode(parentTreeID, index); + const treeNode = this.tree.createNode(parentTreeID, insertionIndex); // Get the TreeID from the created node const treeId: TreeID = treeNode.id; - // Debug logging for parent relationship issues + // A requested parent must actually become this node's parent. If it does + // not, the CRDT structure diverges from Lexical โ€” surface it. if (parentTreeID) { const actualParent = treeNode.parent(); - if (!actualParent || actualParent.id !== parentTreeID) { - console.warn(`โš ๏ธ Parent relationship not set correctly for ${nodeKey}: expected ${parentTreeID}, got ${actualParent?.id || 'None'}`); - } + invariant( + actualParent != null && actualParent.id === parentTreeID, + 'createLoroNode: parent relationship not established', + { nodeKey, expected: parentTreeID, actual: actualParent?.id ?? null }, + ); } // Store basic metadata @@ -285,7 +308,7 @@ export class NodeMapper { // 2. Normal collaboration flow as nodes are created/updated // // This method is kept for compatibility but is now a no-op. - console.log('๐Ÿ“ syncExistingNodes: Skipping sync - mappings established through TreeIntegrator'); + console.log(' syncExistingNodes: Skipping sync - mappings established through TreeIntegrator'); } } diff --git a/src/collab/loro/propagators/DecoratorNodePropagator.ts b/src/collab/loro/propagators/DecoratorNodePropagator.ts index f95749d1..56ed2486 100644 --- a/src/collab/loro/propagators/DecoratorNodePropagator.ts +++ b/src/collab/loro/propagators/DecoratorNodePropagator.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/collab/loro/propagators/ElementNodePropagator.ts b/src/collab/loro/propagators/ElementNodePropagator.ts index d42b9ea8..d79d40fe 100644 --- a/src/collab/loro/propagators/ElementNodePropagator.ts +++ b/src/collab/loro/propagators/ElementNodePropagator.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -16,6 +16,7 @@ import { getNodeMapper } from '../nodes/NodesMapper'; import { LexicalNodeData } from '../types/LexicalNodeData'; import { createLexicalNodeFromLoro } from '../nodes/NodeFactory'; import { Binding } from '../Bindings'; +import { invariant } from '../utils/Invariant'; /** * ElementNode Propagator for Loro Tree Collaboration @@ -74,6 +75,8 @@ export function updateElementNodeInLoro( elementType?: string, parentId?: TreeID, index?: number, + previousSiblingId?: TreeID, + nextSiblingId?: TreeID, metadata?: Record, lexicalNodeJSON?: any, // JSON object from exportJSON() options?: ElementNodeMutatorOptions @@ -94,50 +97,106 @@ export function updateElementNodeInLoro( treeNode.data.set('elementType', elementType); } - // Move the node if parent or position changed + // Move the node only if its position in Loro actually differs from Lexical. if (parentId !== undefined || index !== undefined) { - // Note: For moving, we need access to tree - this might need to be propagated differently const { tree } = options!; - - // CRITICAL: Prevent cycle moves - a node cannot be its own parent - if (parentId && treeNode.id === parentId) { - console.warn(`๐Ÿšจ CYCLE MOVE DETECTED: Node ${treeNode.id} cannot be its own parent! Skipping move operation.`); - return; - } - - // Debug: Check if the parent exists and its children count - const parentNode = parentId ? tree.getNodeByID(parentId) : null; - const parentChildCount = parentNode ? parentNode.children.length : tree.roots().length; - - // Check if the node is already a child of the target parent + + // A node can never be its own parent โ€” that indicates a wrong parent + // mapping upstream, not something to silently skip. + invariant( + !(parentId && treeNode.id === parentId), + 'updateElementNodeInLoro: cycle move (node is its own parent)', + { nodeKey, treeId: treeNode.id }, + ); + + // Where does the node currently sit in the Loro tree? const currentParent = treeNode.parent(); - const isAlreadyChild = currentParent?.id === parentId; - - if (index !== undefined) { - let adjustedIndex = index; - - if (!isAlreadyChild) { - // Moving to a new parent - check bounds against current child count - if (index > parentChildCount) { - adjustedIndex = parentChildCount; + const currentParentId = currentParent ? currentParent.id : undefined; + const siblings = currentParent ? (currentParent.children() ?? []) : tree.roots(); + const currentIndex = siblings.findIndex(child => child.id === treeNode.id); + + const sameParent = currentParentId === parentId; + + // Re-issuing a move on every content edit is unnecessary and races with + // sibling creation (the classic source of "index out of range"). Only move + // when the parent or index genuinely changed. This is a real no-op check, + // not a masked failure. + const needsMove = + !sameParent || (index !== undefined && index !== currentIndex); + + if (needsMove) { + const parentNode = parentId ? tree.getNodeByID(parentId) : null; + const parentChildCount = parentNode + ? (parentNode.children()?.length ?? 0) + : tree.roots().length; + + if (index !== undefined) { + // Loro move index bounds: + // same-parent reorder : [0, children.length - 1] + // cross-parent move : [0, children.length] + // An index outside this range means the position was computed against + // siblings that are not yet synced. Before failing, resolve index + // from mapped sibling anchors when available. + let targetIndex = index; + const maxIndex = sameParent + ? Math.max(parentChildCount - 1, 0) + : parentChildCount; + + if (targetIndex < 0 || targetIndex > maxIndex) { + const targetSiblings = parentNode + ? (parentNode.children() ?? []) + : tree.roots(); + + if (previousSiblingId) { + const prevIndex = targetSiblings.findIndex(child => child.id === previousSiblingId); + if (prevIndex >= 0) { + targetIndex = prevIndex + 1; + } + } + + if ((targetIndex < 0 || targetIndex > maxIndex) && nextSiblingId) { + const nextIndex = targetSiblings.findIndex(child => child.id === nextSiblingId); + if (nextIndex >= 0) { + targetIndex = nextIndex; + } + } + + // A move can observe transiently sparse sibling mappings within one + // update batch (e.g. pressing Enter at the end of the document, where + // the sibling created in the same batch is not yet mapped). When the + // anchors cannot resolve the position, clamp into the valid Loro range + // instead of throwing: a hard failure rolls back the user's keystroke, + // whereas a bounded placement still converges via the CRDT and can be + // refined by subsequent updates. + if (targetIndex < 0 || targetIndex > maxIndex) { + const clamped = Math.min(Math.max(targetIndex, 0), maxIndex); + console.warn( + `[loro-collab] updateElementNodeInLoro: clamping out-of-range move index`, + { + nodeKey, + treeId: treeNode.id, + index, + targetIndex, + clamped, + maxIndex, + sameParent, + previousSiblingId, + nextSiblingId, + }, + ); + targetIndex = clamped; + } } + + tree.move(treeNode.id, parentId, targetIndex); + } else { + tree.move(treeNode.id, parentId, parentChildCount); } - - tree.move(treeNode.id, parentId, adjustedIndex); - } else { - // No specific index, append to end - tree.move(treeNode.id, parentId, parentChildCount); } } - - // The exported Lexical node data is already propagated by the mapper - // No additional JSON export needed since mapper propagates exportJSON automatically - - try { - treeNode.data.set('lastUpdated', Date.now()); - } catch (error) { - console.warn(`๐Ÿ”„ ElementNode ${treeNode.id} container deleted during timestamp update (normal during operations):`, error.message); - } + + // The exported Lexical node data is already propagated by the mapper. + treeNode.data.set('lastUpdated', Date.now()); } /** @@ -377,7 +436,7 @@ export function propagateElementNode( // because SyncLexicalToLoro sorts element mutations by depth. // But as a safety net, log a warning. if (parent && !parentId) { - console.warn(`โš ๏ธ ElementNodePropagator: parent mapping missing for ${elementType} nodeKey=${nodeKey}, parentKey=${parent.getKey()}`); + console.warn(` ElementNodePropagator: parent mapping missing for ${elementType} nodeKey=${nodeKey}, parentKey=${parent.getKey()}`); } // Collect metadata (format, style, direction, etc.) @@ -406,6 +465,8 @@ export function propagateElementNode( if (currentNode && $isElementNode(currentNode)) { // Use editorState.read() to safely access node methods let parent: any, parentId: TreeID | undefined, index: number; + let previousSiblingId: TreeID | undefined; + let nextSiblingId: TreeID | undefined; let elementType: string; const metadata: Record = {}; @@ -419,6 +480,28 @@ export function propagateElementNode( const mapper = getNodeMapper(); parentId = parent ? mapper.getTreeIDByLexicalKey(parent.getKey()) : undefined; index = currentNode.getIndexWithinParent(); + + // Resolve nearest mapped sibling anchors to stabilize target index + // when Lexical index includes siblings not yet represented in Loro. + if (parent) { + const siblings = parent.getChildren(); + for (let i = index - 1; i >= 0; i--) { + const candidate = siblings[i]; + const candidateTreeId = mapper.getTreeIDByLexicalKey(candidate.getKey()); + if (candidateTreeId && tree.has(candidateTreeId)) { + previousSiblingId = candidateTreeId; + break; + } + } + for (let i = index + 1; i < siblings.length; i++) { + const candidate = siblings[i]; + const candidateTreeId = mapper.getTreeIDByLexicalKey(candidate.getKey()); + if (candidateTreeId && tree.has(candidateTreeId)) { + nextSiblingId = candidateTreeId; + break; + } + } + } // Get element type and metadata elementType = currentNode.getType(); @@ -438,7 +521,17 @@ export function propagateElementNode( }); // Update the node in Loro after safely reading from editor state - updateElementNodeInLoro(nodeKey, elementType, parentId, index, metadata, lexicalNodeJSON, options); + updateElementNodeInLoro( + nodeKey, + elementType, + parentId, + index, + previousSiblingId, + nextSiblingId, + metadata, + lexicalNodeJSON, + options, + ); } break; } diff --git a/src/collab/loro/propagators/LineBreakNodePropagator.ts b/src/collab/loro/propagators/LineBreakNodePropagator.ts index bc4e7718..96eb1831 100644 --- a/src/collab/loro/propagators/LineBreakNodePropagator.ts +++ b/src/collab/loro/propagators/LineBreakNodePropagator.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/collab/loro/propagators/RootNodePropagator.ts b/src/collab/loro/propagators/RootNodePropagator.ts index 0a99e88c..5f5d90b9 100644 --- a/src/collab/loro/propagators/RootNodePropagator.ts +++ b/src/collab/loro/propagators/RootNodePropagator.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/collab/loro/propagators/TextNodePropagator.ts b/src/collab/loro/propagators/TextNodePropagator.ts index 7a57f81b..789e0394 100644 --- a/src/collab/loro/propagators/TextNodePropagator.ts +++ b/src/collab/loro/propagators/TextNodePropagator.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -17,6 +17,7 @@ import { getNodeMapper } from '../nodes/NodesMapper'; import { LexicalNodeData } from '../types/LexicalNodeData'; import { Binding } from '../Bindings'; import { $diffTextContentAndApplyDelta } from '../utils/Utils'; +import { invariant } from '../utils/Invariant'; /** * TextNode Propagator for Loro Tree Collaboration @@ -49,13 +50,16 @@ export function createTextNodeInLoro( options?: TextNodeMutatorOptions ): TreeID { const mapper = getNodeMapper(); - - // Debug logging for text node creation issues - if (!parentId) { - console.warn(`โŒ Creating TextNode ${nodeKey} without parent in Loro tree - THIS WILL FAIL`); - return null as any; // Return early to avoid creating orphaned nodes - } - + + // A text node is always a leaf with a parent element. A missing parent means + // the parent element was not synced first โ€” surface it instead of creating an + // orphaned (unrenderable) node. + invariant( + parentId !== undefined, + 'createTextNodeInLoro: text node has no parent in Loro tree', + { nodeKey }, + ); + // Use mapper to get or create the tree node // Note: We can't pass lexicalNode directly due to context issues, but parentId should be sufficient const treeNode = mapper.getLoroNodeByLexicalKey( @@ -101,47 +105,32 @@ export function updateTextNodeInLoro( options?: TextNodeMutatorOptions ): void { const mapper = getNodeMapper(); - - // Get the existing tree node using the mapper - const treeNode = mapper.getLoroNodeByLexicalKey(nodeKey, undefined); - + + // Updates must target an existing mapped node. Creating on update can + // accidentally create inline nodes at root when parent info is unavailable. + const treeID = mapper.getTreeIDByLexicalKey(nodeKey); + if (!treeID || !options?.tree.has(treeID)) { + return; + } + const treeNode = options.tree.getNodeByID(treeID); if (!treeNode) { - console.warn(`๐Ÿ“ TextNode ${nodeKey} not found in Loro, skipping update`); return; } - - // Note: Container validation is done in each try-catch block below since - // the container can be deleted between operations - - // Store complete lexical node data as clean JSON if provided + + // Store complete lexical node data as clean JSON if provided. if (lexicalNodeJSON) { - try { - // Store complete lexical JSON without the key - if ('key' in lexicalNodeJSON || '__key' in lexicalNodeJSON || 'lexicalKey' in lexicalNodeJSON) { - const { key, __key, lexicalKey, children, ...cleanedData } = lexicalNodeJSON; - treeNode.data.set('lexical', cleanedData); - } else { - const { children, ...cleanedData } = lexicalNodeJSON as any; - treeNode.data.set('lexical', cleanedData); - } - } catch (error) { - // This is expected during text operations when nodes get deleted/recreated - console.warn(`๐Ÿ“ TextNode ${nodeKey} container was deleted during update, skipping (normal during text operations):`, error.message); - return; + if ('key' in lexicalNodeJSON || '__key' in lexicalNodeJSON || 'lexicalKey' in lexicalNodeJSON) { + const { key, __key, lexicalKey, children, ...cleanedData } = lexicalNodeJSON; + treeNode.data.set('lexical', cleanedData); + } else { + const { children, ...cleanedData } = lexicalNodeJSON as any; + treeNode.data.set('lexical', cleanedData); } } - - // Update only essential metadata - try { - treeNode.data.set('elementType', 'text'); - treeNode.data.set('updatedAt', Date.now()); - } catch (error) { - console.warn(`๐Ÿ“ TextNode ${nodeKey} container deleted during metadata update (normal during text operations):`, error.message); - return; - } - - // The exported Lexical node data is already propagated by the mapper - // No additional JSON export needed since mapper propagates exportJSON automatically + + // Update only essential metadata. + treeNode.data.set('elementType', 'text'); + treeNode.data.set('updatedAt', Date.now()); } /** @@ -343,7 +332,7 @@ export function applyTextFormatInLoro( // Try a simple read operation to verify the container is accessible treeNode.data.get('format'); } catch (error) { - console.warn(`๐Ÿ“ TextNode ${nodeKey} container deleted during format check (normal during text operations):`, error.message); + console.warn(` TextNode ${nodeKey} container deleted during format check (normal during text operations):`, error.message); return; } @@ -362,7 +351,7 @@ export function applyTextFormatInLoro( treeNode.data.set('format', currentFormat); treeNode.data.set('lastUpdated', Date.now()); } catch (error) { - console.warn(`๐Ÿ“ TextNode ${nodeKey} container deleted during format update (normal during text operations):`, error.message); + console.warn(` TextNode ${nodeKey} container deleted during format update (normal during text operations):`, error.message); return; } } @@ -400,7 +389,7 @@ export function propagateTextNode( currentParentId = parentNode ? parentNode.id.toString() : undefined; } } catch (error) { - console.warn(`๐Ÿ“ Failed to get parent for existing TreeID ${existingTreeID}:`, error); + console.warn(` Failed to get parent for existing TreeID ${existingTreeID}:`, error); } return { currentParentId, expectedParentId }; @@ -418,7 +407,7 @@ export function propagateTextNode( actualTreeID = treeNode.id; } } catch (error) { - console.warn(`๐Ÿ“ Could not get TreeNode for ${existingTreeID} during creation:`, error); + console.warn(` Could not get TreeNode for ${existingTreeID} during creation:`, error); } // Clear the old mapping first to avoid conflicts @@ -430,7 +419,7 @@ export function propagateTextNode( tree.delete(actualTreeID); } } catch (error) { - console.warn(`๐Ÿ“ Failed to delete TreeNode ${actualTreeID} during creation:`, error); + console.warn(` Failed to delete TreeNode ${actualTreeID} during creation:`, error); } } } @@ -486,7 +475,7 @@ export function propagateTextNode( currentParentId = parentNode ? parentNode.id.toString() : undefined; } } catch (error) { - console.warn(`๐Ÿ“ Failed to get parent for existing TreeID ${existingTreeID} during update:`, error); + console.warn(` Failed to get parent for existing TreeID ${existingTreeID} during update:`, error); } return { currentParentId, expectedParentId, parent }; @@ -502,7 +491,7 @@ export function propagateTextNode( actualTreeID = treeNode.id; } } catch (error) { - console.warn(`๐Ÿ“ Could not get TreeNode for ${existingTreeID}:`, error); + console.warn(` Could not get TreeNode for ${existingTreeID}:`, error); } // Clear the old mapping first to avoid conflicts @@ -514,7 +503,7 @@ export function propagateTextNode( tree.delete(actualTreeID); } } catch (error) { - console.warn(`๐Ÿ“ Failed to delete TreeNode ${actualTreeID} during update:`, error); + console.warn(` Failed to delete TreeNode ${actualTreeID} during update:`, error); } // Now recreate the TextNode with the new parent (treat as "created") @@ -540,6 +529,33 @@ export function propagateTextNode( } } + // If a text node emits only an "updated" mutation before we have a + // mapping, treat it as a create so parent/index are explicit. + if (!existingTreeID) { + const { parent, parentId, index, textContent, format, mode, lexicalNodeJSON } = update.editorState.read(() => { + const parent = currentNode.getParent(); + const parentId = parent ? mapper.getTreeIDByLexicalKey(parent.getKey()) : undefined; + const index = currentNode.getIndexWithinParent(); + const textContent = currentNode.getTextContent(); + const format = currentNode.getFormat(); + const mode = currentNode.getMode(); + + let lexicalNodeJSON: any = undefined; + try { + lexicalNodeJSON = currentNode.exportJSON(); + } catch (error) { + console.warn('Failed to export node JSON in propagateTextNode updated(create fallback):', error); + } + + return { parent, parentId, index, textContent, format, mode, lexicalNodeJSON }; + }); + + if (parentId !== undefined) { + createTextNodeInLoro(nodeKey, textContent, format, mode, parentId, index, lexicalNodeJSON, options); + } + return; + } + // Normal update case - parent hasn't changed const { textContent, format, mode, lexicalNodeJSON } = update.editorState.read(() => { const textContent = currentNode.getTextContent(); diff --git a/src/collab/loro/propagators/index.ts b/src/collab/loro/propagators/index.ts index 4f92d2b2..2bae9d30 100644 --- a/src/collab/loro/propagators/index.ts +++ b/src/collab/loro/propagators/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -12,7 +12,7 @@ import { ElementNode, NodeKey } from 'lexical'; import { Binding } from '../Bindings'; -import { LoroTree } from 'loro-crdt/bundler/loro_wasm'; +import type { LoroTree } from 'loro-crdt'; // Root Node Propagator export * from './RootNodePropagator'; diff --git a/src/collab/loro/provider/websocket.ts b/src/collab/loro/provider/websocket.ts index c9157d9f..a2f067e4 100644 --- a/src/collab/loro/provider/websocket.ts +++ b/src/collab/loro/provider/websocket.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -62,7 +62,7 @@ class AwarenessAdapter implements AwarenessProvider { // Use the same client ID as the binding for consistency this.localClientId = doc ? generateClientID(doc) : generateRandomClientID() - console.log('๐Ÿ”„ AwarenessAdapter created:', { + console.log(' AwarenessAdapter created:', { localClientId: this.localClientId, docPeerId: doc ? doc.peerId : 'no-doc', existingStatesCount: Object.keys(ephemeralStore.getAllStates()).length @@ -336,6 +336,7 @@ messageHandlers[messageUpdate] = ( const importStatus = provider.doc.import(updateBytes) const afterVersion = provider.doc.version() + console.log('[SEED-DEBUG] messageUpdate: imported', updateBytes.length, 'bytes; importStatus=', JSON.stringify(importStatus)) // Update our last exported version to include the remote changes // This ensures we don't re-export remote changes @@ -347,7 +348,7 @@ messageHandlers[messageUpdate] = ( return null // No response needed } catch (error) { - console.warn(`โŒ [LORO-UPDATE-ERROR] Failed to apply Loro update:`, error) + console.warn(` [LORO-UPDATE-ERROR] Failed to apply Loro update:`, error) return null } } @@ -520,7 +521,7 @@ const setupWS = (provider) => { status: 'connected' }]) - console.log('โœ… WebSocket connection established, requesting initial data') + console.log(' WebSocket connection established, requesting initial data') // Since we're in onopen, we know the WebSocket is ready // Use sendMessage directly to avoid any race conditions @@ -535,11 +536,11 @@ const setupWS = (provider) => { docId: provider.docId, clientId: clientId } - console.log(`๐Ÿ”„ Requesting initial snapshot from server (ID: ${requestId}, clientId: ${clientId}):`, snapshotRequest) - console.log(`๐Ÿ”„ Provider instance ID: ${provider.wsServerUrl}/${provider.docId}, snapshotLoaded: ${provider.snapshotLoaded}`) + console.log(` Requesting initial snapshot from server (ID: ${requestId}, clientId: ${clientId}):`, snapshotRequest) + console.log(` Provider instance ID: ${provider.wsServerUrl}/${provider.docId}, snapshotLoaded: ${provider.snapshotLoaded}`) sendMessage(ws, snapshotRequest) } else { - console.log('๐Ÿ“ธ Snapshot already loaded, skipping request') + console.log(' Snapshot already loaded, skipping request') } // Then request initial ephemeral state from server @@ -573,6 +574,23 @@ const setupWS = (provider) => { }) } } + + // Flush any local document updates that were buffered while the socket + // was not ready to send (e.g. the initial-content bootstrap ran before + // the connection opened). Without this, seeded content committed before + // the socket opened would never reach the server or other collaborators. + if (provider._pendingUpdates.length > 0) { + const pending = provider._pendingUpdates + provider._pendingUpdates = [] + console.log('[SEED-DEBUG] ws.onopen: flushing', pending.length, 'buffered local updates') + for (const pendingUpdate of pending) { + sendMessage(ws, { + type: 'update', + update: Array.from(pendingUpdate), + docId: provider.docId + }) + } + } } provider.emit('status', [{ status: 'connecting' @@ -588,13 +606,13 @@ const broadcastMessage = (provider: WebsocketProvider, message: LoroWebSocketMes if (provider.wsconnected && ws && ws.readyState === ws.OPEN) { sendMessage(ws, message) } else { - console.log('โŒ [BROADCAST] WebSocket not ready for sending'); + console.log(' [BROADCAST] WebSocket not ready for sending'); } if (provider.bcconnected) { bc.publish(provider.bcChannel, JSON.stringify(message), provider) } else { - console.log('๐Ÿ“ป [BROADCAST] BroadcastChannel not connected') + console.log(' [BROADCAST] BroadcastChannel not connected') } } @@ -634,6 +652,7 @@ export class WebsocketProvider extends ObservableV2 { _exitIntegrator = null _bcSubscriber = null _lastExportedVersion: VersionVector = null // Track last exported version for incremental updates + _pendingUpdates: Uint8Array[] = [] // Local updates buffered while the socket is not ready to send /** * @param {string} wsServerUrl @@ -688,7 +707,7 @@ export class WebsocketProvider extends ObservableV2 { WebsocketProvider.globalEphemeralStore = new EphemeralStore(300000) // 5 minute timeout console.log('๐Ÿ†• Created new global EphemeralStore') } else { - console.log('โ™ป๏ธ Reusing existing global EphemeralStore - cleaning up stale user states') + console.log(' Reusing existing global EphemeralStore - cleaning up stale user states') // Clean up all existing user states when reusing store to prevent accumulation const allStates = WebsocketProvider.globalEphemeralStore.getAllStates() Object.keys(allStates).forEach(key => { @@ -696,7 +715,7 @@ export class WebsocketProvider extends ObservableV2 { const clientId = parseInt(key, 10) if (!isNaN(clientId)) { WebsocketProvider.globalEphemeralStore!.delete(key) - console.log('๐Ÿงน Cleaned up stale user state:', key) + console.log(' Cleaned up stale user state:', key) } }) } @@ -777,8 +796,25 @@ export class WebsocketProvider extends ObservableV2 { update: Array.from(update), docId: this.docId } - - broadcastMessage(this, updateMessage) + + const ws = this.ws + if (this.wsconnected && ws && ws.readyState === ws.OPEN) { + console.log('[SEED-DEBUG] _updateHandler: sending local update over WS', update.length, 'bytes') + sendMessage(ws, updateMessage) + } else { + // The socket is not ready yet โ€” this happens when the initial-content + // bootstrap commits before the connection opens. Loro delivers each + // local update to subscribeLocalUpdates exactly once, so dropping it + // here would lose the seeded content permanently (remote peers would + // never receive it). Buffer it and flush on open instead. + console.log('[SEED-DEBUG] _updateHandler: WS not ready, buffering local update', update.length, 'bytes (pending now', this._pendingUpdates.length + 1, ')') + this._pendingUpdates.push(update) + } + + // Mirror to other same-origin tabs when the BroadcastChannel is available. + if (this.bcconnected) { + bc.publish(this.bcChannel, JSON.stringify(updateMessage), this) + } } // Document update integrater - called when Loro emits document change events /** diff --git a/src/collab/loro/servers/index.ts b/src/collab/loro/servers/index.ts index 358477ad..8590781c 100644 --- a/src/collab/loro/servers/index.ts +++ b/src/collab/loro/servers/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/collab/loro/servers/ws/callback.ts b/src/collab/loro/servers/ws/callback.ts index 8559ddcd..1031bd14 100644 --- a/src/collab/loro/servers/ws/callback.ts +++ b/src/collab/loro/servers/ws/callback.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/collab/loro/servers/ws/server.ts b/src/collab/loro/servers/ws/server.ts index b7db65fc..f6b31e28 100755 --- a/src/collab/loro/servers/ws/server.ts +++ b/src/collab/loro/servers/ws/server.ts @@ -1,7 +1,7 @@ #!/usr/bin/env node /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/collab/loro/servers/ws/utils.ts b/src/collab/loro/servers/ws/utils.ts index 3a08a624..d079b4aa 100644 --- a/src/collab/loro/servers/ws/utils.ts +++ b/src/collab/loro/servers/ws/utils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -34,14 +34,14 @@ const persistenceDir = process.env.YPERSISTENCE // Helper function to log tree structure for debugging const logTreeStructure = (doc: LoroDoc, context: string) => { try { - console.log(`[Server] ${context} - Tree Structure Debug:`) + console.log(`[LORO] ${context} - Tree Structure Debug:`) // Try to get the tree container using getTree method try { const tree = doc.getTree('tree') if (tree) { const nodes = tree.nodes() - console.log(`[Server] Total nodes in tree: ${nodes.length}`) + console.log(`[LORO] Total nodes in tree: ${nodes.length}`) // Helper function to recursively log tree structure const logTreeStructureRecursive = (node: any, prefix: string = '', isLast: boolean = true, depth: number = 0) => { @@ -52,7 +52,7 @@ const logTreeStructure = (doc: LoroDoc, context: string) => { const connector = depth === 0 ? '' : (isLast ? 'โ””โ”€โ”€ ' : 'โ”œโ”€โ”€ ') const nodeInfo = `TreeID(${treeId.slice(0, 8)}...) [${elementType}]` - console.log(`[Server] ${prefix}${connector}${nodeInfo}`) + console.log(`[LORO] ${prefix}${connector}${nodeInfo}`) const children = node.children() if (children && children.length > 0) { @@ -71,11 +71,11 @@ const logTreeStructure = (doc: LoroDoc, context: string) => { return !parent || data.isRoot }) - console.log(`[Server] Root nodes: ${rootNodes.length}`) + console.log(`[LORO] Root nodes: ${rootNodes.length}`) console.log('') if (rootNodes.length === 0) { - console.log('[Server] โš ๏ธ No root nodes found!') + console.log('[LORO] No root nodes found!') } else { rootNodes.forEach((root, index) => { const isLastRoot = index === rootNodes.length - 1 @@ -84,25 +84,25 @@ const logTreeStructure = (doc: LoroDoc, context: string) => { } } else { - console.log(`[Server] No tree container found`) + console.log(`[LORO] No tree container found`) } } catch (treeError) { - console.log(`[Server] Error accessing tree container:`, treeError.message) + console.log(`[LORO] Error accessing tree container:`, treeError.message) } // Try export with different modes for debugging try { const snapshot = doc.export({ mode: 'snapshot' }) - console.log(`[Server] Snapshot size: ${snapshot.length} bytes`) + console.log(`[LORO] Snapshot size: ${snapshot.length} bytes`) const update = doc.export({ mode: 'update' }) - console.log(`[Server] Update size: ${update.length} bytes`) + console.log(`[LORO] Update size: ${update.length} bytes`) } catch (exportError) { - console.log(`[Server] Error exporting:`, exportError.message) + console.log(`[LORO] Error exporting:`, exportError.message) } } catch (error) { - console.warn(`[Server] Error logging tree structure:`, error) + console.warn(`[LORO] Error logging tree structure:`, error) } } @@ -223,7 +223,7 @@ const messageListener = (conn, doc: WSSharedDoc, message: ArrayBuffer | string | const decoder = new TextDecoder() messageStr = decoder.decode(message) } catch (decodeError) { - console.warn(`[Server] messageListener - Failed to decode ArrayBuffer as string, treating as binary Loro update`) + console.warn(`[LORO] messageListener - Failed to decode ArrayBuffer as string, treating as binary Loro update`) // If decoding fails, treat as raw binary Loro update const updateBytes = new Uint8Array(message) doc.doc.import(updateBytes) @@ -240,7 +240,7 @@ const messageListener = (conn, doc: WSSharedDoc, message: ArrayBuffer | string | const decoder = new TextDecoder() messageStr = decoder.decode(message); } catch (decodeError) { - console.warn(`[Server] messageListener - Failed to decode Uint8Array as string, treating as binary Loro update`) + console.warn(`[LORO] messageListener - Failed to decode Uint8Array as string, treating as binary Loro update`) // If decoding fails, treat as raw binary Loro update doc.doc.import(message); // Broadcast the update to other connections @@ -252,7 +252,7 @@ const messageListener = (conn, doc: WSSharedDoc, message: ArrayBuffer | string | return } } else { - console.warn(`[Server] messageListener - Unknown message type:`, typeof message) + console.warn(`[LORO] messageListener - Unknown message type:`, typeof message) return } @@ -263,37 +263,37 @@ const messageListener = (conn, doc: WSSharedDoc, message: ArrayBuffer | string | try { messageData = JSON.parse(messageStr) as LoroWebSocketMessage } catch (parseError) { - console.warn(`[Server] messageListener - JSON parse error:`, parseError.message) - console.warn(`[Server] messageListener - Raw message:`, messageStr.substring(0, 500)) + console.warn(`[LORO] messageListener - JSON parse error:`, parseError.message) + console.warn(`[LORO] messageListener - Raw message:`, messageStr.substring(0, 500)) return } - console.log(`[Server] Received message type: ${messageData.type} for doc: ${doc.name}`) + console.log(`[LORO] Received message type: ${messageData.type} for doc: ${doc.name}`) switch (messageData.type) { case messageQuerySnapshot: // Client is requesting a snapshot - send current document state const requestId = Math.random().toString(36).substr(2, 9); - console.log(`[Server] Client requesting snapshot for doc: ${doc.name} (Request ID: ${requestId})`) + console.log(`[LORO] Client requesting snapshot for doc: ${doc.name} (Request ID: ${requestId})`) // Log tree structure before creating snapshot // logTreeStructure(doc.doc, `Before creating snapshot (Request ID: ${requestId})`) try { const snapshot = doc.doc.export({ mode: 'snapshot' }) - console.log(`[Server] Sending snapshot response: ${snapshot.length} bytes (Request ID: ${requestId})`) + console.log(`[LORO] Sending snapshot response: ${snapshot.length} bytes (Request ID: ${requestId})`) // Verify the snapshot contains expected content const tree = doc.doc.getTree('tree') const nodes = tree.nodes() - console.log(`[Server] Snapshot contains ${nodes.length} nodes from server document`) + console.log(`[LORO] Snapshot contains ${nodes.length} nodes from server document`) // Send binary snapshot data directly instead of wrapped message conn.send(snapshot) } catch (snapshotError) { - console.error(`[Server] ERROR creating/sending snapshot:`, snapshotError.message) - console.error(`[Server] Stack:`, snapshotError.stack) + console.error(`[LORO] ERROR creating/sending snapshot:`, snapshotError.message) + console.error(`[LORO] Stack:`, snapshotError.stack) } break @@ -312,7 +312,7 @@ const messageListener = (conn, doc: WSSharedDoc, message: ArrayBuffer | string | const afterStates = doc.ephemeralStore.getAllStates() const afterKeys = Object.keys(afterStates) - console.log(`๐Ÿ“ก SERVER DEBUG - Applied ephemeral update from ${conn.id}:`, { + console.log(` SERVER DEBUG - Applied ephemeral update from ${conn.id}:`, { bytesLength: ephemeralBytes.length, beforeKeys, afterKeys, @@ -334,7 +334,7 @@ const messageListener = (conn, doc: WSSharedDoc, message: ArrayBuffer | string | const allKeys = Object.keys(allStates) const ephemeralUpdate = doc.ephemeralStore.encodeAll() - console.log(`๐Ÿ“ก SERVER DEBUG - Client ${conn.id} requesting ephemeral state:`, { + console.log(` SERVER DEBUG - Client ${conn.id} requesting ephemeral state:`, { allKeysAvailable: allKeys, encodedLength: ephemeralUpdate.length, totalConnections: doc.conns.size @@ -347,7 +347,7 @@ const messageListener = (conn, doc: WSSharedDoc, message: ArrayBuffer | string | } sendMessage(doc, conn, ephemeralResponse) } catch (error) { - console.warn('[Server] messageQueryEphemeral - ERROR encoding/sending ephemeral state:', error) + console.warn('[LORO] messageQueryEphemeral - ERROR encoding/sending ephemeral state:', error) } break @@ -402,15 +402,15 @@ const closeConn = (doc, conn) => { if (doc.conns.size === 0) { if (persistence !== null) { // if persisted, we store state and cleanup document - console.log(`[Server] Persisting document ${doc.name} before cleanup`) + console.log(`[LORO] Persisting document ${doc.name} before cleanup`) persistence.writeState(doc.name, doc).then(() => { // Cleanup WSSharedDoc resources (no destroy method needed for Loro) - console.log(`[Server] Document ${doc.name} persisted and cleaned up`) + console.log(`[LORO] Document ${doc.name} persisted and cleaned up`) }) docs.delete(doc.name) } else { // No persistence configured - keep document in memory for reconnections - console.log(`[Server] No persistence configured - keeping document ${doc.name} in memory for future connections`) + console.log(`[LORO] No persistence configured - keeping document ${doc.name} in memory for future connections`) // logTreeStructure(doc.doc, `Document ${doc.name} structure before keeping in memory`) } } @@ -471,18 +471,18 @@ export const setupWSConnection = (conn, req, { docName = (req.url || '').slice(1 try { const snapshot = doc.doc.export({ mode: 'snapshot' }) - console.log(`[Server] Sending initial snapshot to new client: ${snapshot.length} bytes`) + console.log(`[LORO] Sending initial snapshot to new client: ${snapshot.length} bytes`) // Verify the snapshot contains expected content const tree = doc.doc.getTree('tree') const nodes = tree.nodes() - console.log(`[Server] Initial snapshot contains ${nodes.length} nodes from server document`) + console.log(`[LORO] Initial snapshot contains ${nodes.length} nodes from server document`) // Send binary snapshot data directly instead of wrapped message conn.send(snapshot) } catch (snapshotError) { - console.error(`[Server] ERROR creating/sending initial snapshot:`, snapshotError.message) - console.error(`[Server] Stack:`, snapshotError.stack) + console.error(`[LORO] ERROR creating/sending initial snapshot:`, snapshotError.message) + console.error(`[LORO] Stack:`, snapshotError.stack) } // Send current ephemeral state if any @@ -512,7 +512,7 @@ export class WSSharedDoc { this.doc = new LoroDoc() // Initialize the document with default Lexical content - console.log(`[Server] Initializing document '${name}' with default content`) + console.log(`[LORO] Initializing document '${name}' with default content`) initializeLoroDocWithLexicalContent(this.doc) /** @@ -559,7 +559,7 @@ export class WSSharedDoc { // Clear the sender reference after broadcast this.lastEphemeralSender = null } catch (broadcastError) { - console.warn(`[Server] ephemeralChangeIntegrator - ERROR broadcasting:`, { + console.warn(`[LORO] ephemeralChangeIntegrator - ERROR broadcasting:`, { error: broadcastError.message, stack: broadcastError.stack }) diff --git a/src/collab/loro/sync/SyncCursors.ts b/src/collab/loro/sync/SyncCursors.ts index 0ef1c87d..c97a1209 100644 --- a/src/collab/loro/sync/SyncCursors.ts +++ b/src/collab/loro/sync/SyncCursors.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -53,6 +53,40 @@ export type SyncCursorPositionsFn = ( options?: SyncCursorPositionsOptions, ) => void; +function getDisplayNameFromAwareness(awareness: UserState): string { + const awarenessData = awareness.awarenessData; + if (!awarenessData || typeof awarenessData !== 'object') { + return awareness.name; + } + + const data = awarenessData as Record; + const user = data.user; + const userRecord = + user && typeof user === 'object' ? (user as Record) : undefined; + + const candidates = [ + userRecord?.display_name, + userRecord?.displayName, + userRecord?.name, + userRecord?.username, + userRecord?.handle, + data.display_name, + data.displayName, + data.name, + data.username, + data.handle, + awareness.name, + ]; + + for (const candidate of candidates) { + if (typeof candidate === 'string' && candidate.trim().length > 0) { + return candidate; + } + } + + return awareness.name; +} + /*****************************************************************************/ // Helper function to find Loro tree node for a Lexical NodeKey (read-only lookup) @@ -226,21 +260,8 @@ function createCursorSelection( isCurrentUser: boolean = false, ): CursorSelection { const color = cursor.color; - - // Helper function to convert color to rgba with opacity - const getColorWithOpacity = (color: string, opacity: number): string => { - if (color.startsWith('#')) { - const hex = color.slice(1); - const r = parseInt(hex.slice(0, 2), 16); - const g = parseInt(hex.slice(2, 4), 16); - const b = parseInt(hex.slice(4, 6), 16); - return `rgba(${r}, ${g}, ${b}, ${opacity})`; - } - return color; - }; - - const caretColor = isCurrentUser ? getColorWithOpacity(color, 0.6) : color; - const nameBackgroundColor = isCurrentUser ? getColorWithOpacity(color, 0.7) : color; + const caretColor = color; + const nameBackgroundColor = color; const caret = document.createElement('span'); caret.style.cssText = `position:absolute;top:0;bottom:0;right:-1px;width:2px;background-color:${caretColor};z-index:10;${isCurrentUser ? 'opacity:0.8;' : ''}`; @@ -301,7 +322,8 @@ export function syncCursorPositions( const [clientID, awareness] = awarenessState; visitedClientIDs.add(clientID); - const { name, color, focusing } = awareness; + const { color } = awareness; + const displayName = getDisplayNameFromAwareness(awareness); const isCurrentUser = clientID === localClientID; let selection = null; @@ -309,9 +331,16 @@ export function syncCursorPositions( if (cursor === undefined) { // Add "(Me)" label for current user's cursor - const cursorName = isCurrentUser ? `${name} (Me)` : name; + const cursorName = isCurrentUser ? `${displayName} (Me)` : displayName; cursor = createCollabCursor(cursorName, color); cursors.set(clientID, cursor); + } else if (cursor.name !== displayName) { + cursor.name = displayName; + if (cursor.selection) { + cursor.selection.name.textContent = isCurrentUser + ? `${displayName} (Me)` + : displayName; + } } // Render cursor/selection whenever valid anchorPos/focusPos exist. diff --git a/src/collab/loro/sync/SyncLexicalToLoro.ts b/src/collab/loro/sync/SyncLexicalToLoro.ts index b369ee04..d86e12f8 100644 --- a/src/collab/loro/sync/SyncLexicalToLoro.ts +++ b/src/collab/loro/sync/SyncLexicalToLoro.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -27,6 +27,21 @@ export function syncLexicalToLoro( editorState: currEditorState, } = update; + let __seedDebugMutationCount = 0; + if (mutatedNodes) { + mutatedNodes.forEach((nodeMap) => { + __seedDebugMutationCount += nodeMap.size; + }); + } + console.log( + '[SEED-DEBUG] syncLexicalToLoro: mutatedNodes=', + mutatedNodes ? 'map' : 'null', + 'totalMutations=', + __seedDebugMutationCount, + 'tags=', + Array.from(update.tags), + ); + // Process node mutations if present. // NOTE: mutatedNodes is null for selection-only updates (no DOM mutations). // See Lexical docs: "Will be null if no DOM was mutated, such as when only @@ -72,53 +87,110 @@ export function syncLexicalToLoro( } }); - // Phase 2: Collect all ElementNode mutations, sort by depth, then propagate - const elementMutations: Array<{ mutation: 'created' | 'updated' | 'destroyed'; nodeKey: string; depth: number }> = []; - - mutatedNodes.forEach((nodeMap, Klass) => { - if (isClassExtending(Klass, ElementNode) && !isClassExtending(Klass, RootNode)) { - nodeMap.forEach((mutation, nodeKey) => { - // Compute depth in Lexical tree (root=0, paragraph=1, tablecell=3, etc.) - let depth = 0; - currEditorState.read(() => { - const node = $getNodeByKey(nodeKey); - if (node) { - let current = node.getParent(); - while (current) { - depth++; - current = current.getParent(); - } - } - }); - elementMutations.push({ mutation, nodeKey, depth }); - }); - } - }); - - // Sort by depth ascending โ†’ parents (depth 1) are propagated before children (depth 2, 3, โ€ฆ) - elementMutations.sort((a, b) => a.depth - b.depth); - - for (const { mutation, nodeKey } of elementMutations) { - propagateElementNode(update, mutation, nodeKey, mutatorOptions); + // Phases 2 & 3 (unified): collect every non-root mutation with its Lexical + // tree depth AND its sibling index within its parent, then apply them in a + // single ordered pass. + // + // Ordering rationale โ€” the Loro tree requires each inserted child's index + // to be <= its parent's current children count. Two guarantees make every + // insertion valid: + // 1. depth ascending โ†’ a parent is always created before its children. + // 2. index ascending โ†’ a node's lower-indexed siblings are created + // before it, so by the time it is inserted the parent already holds + // exactly `index` children. + // Crucially, elements and leaves are ordered TOGETHER. Previously all + // ElementNodes were created before any TextNode, so a paragraph that + // interleaves text with an inline element (e.g. a link at index 11) tried + // to insert the link while the paragraph still had 0 children in Loro, + // throwing "insertion index out of range". Mixing both node categories in + // one index-sorted pass fixes that. + type NodeCategory = 'element' | 'text' | 'linebreak' | 'decorator'; + interface MutationInfo { + mutation: 'created' | 'updated' | 'destroyed'; + nodeKey: string; + depth: number; + index: number; + category: NodeCategory; } - - // Phase 3: Process leaf children (their parents are now guaranteed to be mapped) + + const collected: MutationInfo[] = []; + mutatedNodes.forEach((nodeMap, Klass) => { - if (isClassExtending(Klass, TextNode)) { - nodeMap.forEach((mutation, nodeKey) => { - propagateTextNode(update, mutation, nodeKey, mutatorOptions); - }); + let category: NodeCategory | null = null; + if (isClassExtending(Klass, RootNode)) { + return; // handled in Phase 1 + } else if (isClassExtending(Klass, ElementNode)) { + category = 'element'; + } else if (isClassExtending(Klass, TextNode)) { + category = 'text'; } else if (isClassExtending(Klass, LineBreakNode)) { - nodeMap.forEach((mutation, nodeKey) => { - propagateLineBreakNode(update, mutation, nodeKey, mutatorOptions); - }); + category = 'linebreak'; } else if (isClassExtending(Klass, DecoratorNode)) { - nodeMap.forEach((mutation, nodeKey) => { - propagateDecoratorNode(update, mutation, nodeKey, mutatorOptions); - }); + category = 'decorator'; + } + if (category === null) { + return; } + const resolvedCategory = category; + nodeMap.forEach((mutation, nodeKey) => { + // Compute depth (root=0, paragraph=1, inline element=2, โ€ฆ) and the + // node's index within its parent from the current editor state. + let depth = 0; + let index = 0; + currEditorState.read(() => { + const node = $getNodeByKey(nodeKey); + if (node) { + index = node.getIndexWithinParent(); + let current = node.getParent(); + while (current) { + depth++; + current = current.getParent(); + } + } + }); + collected.push({ mutation, nodeKey, depth, index, category: resolvedCategory }); + }); }); + const dispatch = (info: MutationInfo) => { + switch (info.category) { + case 'element': + propagateElementNode(update, info.mutation, info.nodeKey, mutatorOptions); + break; + case 'text': + propagateTextNode(update, info.mutation, info.nodeKey, mutatorOptions); + break; + case 'linebreak': + propagateLineBreakNode(update, info.mutation, info.nodeKey, mutatorOptions); + break; + case 'decorator': + propagateDecoratorNode(update, info.mutation, info.nodeKey, mutatorOptions); + break; + } + }; + + // Destroys first, deepest-first (children before parents), to avoid + // re-create/update races during bulk deletes. + collected + .filter(m => m.mutation === 'destroyed') + .sort((a, b) => b.depth - a.depth) + .forEach(dispatch); + + // Creates next, shallow-first then ascending sibling index (see rationale + // above) so every Loro insertion index stays within range. + collected + .filter(m => m.mutation === 'created') + .sort((a, b) => a.depth - b.depth || a.index - b.index) + .forEach(dispatch); + + // Updates last, parents-first for determinism. Updates never call + // createLoroNode (the mapping already exists) so their order is not + // index-sensitive. + collected + .filter(m => m.mutation === 'updated') + .sort((a, b) => a.depth - b.depth || a.index - b.index) + .forEach(dispatch); + // Commit only when there were actual node mutations (not selection-only changes) binding.doc.commit({ origin: binding.doc.peerIdStr }); } diff --git a/src/collab/loro/sync/SyncLoroToLexical.ts b/src/collab/loro/sync/SyncLoroToLexical.ts index 2d744de4..f481ae49 100644 --- a/src/collab/loro/sync/SyncLoroToLexical.ts +++ b/src/collab/loro/sync/SyncLoroToLexical.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -48,35 +48,50 @@ export function syncLoroToLexical( // Process Loro events and apply them to Lexical using the appropriate integrators eventBatch.events.forEach((event, index) => { - switch (event.diff.type) { - case 'tree': - // Call internal method that doesn't wrap in editor.update() - treeIntegrator.integrateInternal(event.diff as any, binding, provider); - break; + try { + switch (event.diff.type) { + case 'tree': + // Call internal method that doesn't wrap in editor.update() + treeIntegrator.integrateInternal(event.diff as any, binding, provider); + break; - case 'map': - // Call internal method that doesn't wrap in editor.update() - if (event.target) { - mapIntegrator.integrateWithContextInternal(event.diff as any, event.target, binding, provider); - } else { - mapIntegrator.integrateInternal(event.diff as any, binding, provider); - } - break; + case 'map': + // Call internal method that doesn't wrap in editor.update() + if (event.target) { + mapIntegrator.integrateWithContextInternal(event.diff as any, event.target, binding, provider); + } else { + mapIntegrator.integrateInternal(event.diff as any, binding, provider); + } + break; - case 'list': - listIntegrator.integrateInternal(event.diff as any, binding, provider); - break; + case 'list': + listIntegrator.integrateInternal(event.diff as any, binding, provider); + break; - case 'text': - textIntegrator.integrateInternal(event.diff as any, binding, provider); - break; + case 'text': + textIntegrator.integrateInternal(event.diff as any, binding, provider); + break; - case 'counter': - counterIntegrator.integrateInternal(event.diff as any, binding, provider); - break; + case 'counter': + counterIntegrator.integrateInternal(event.diff as any, binding, provider); + break; - default: - throw new Error(`Unsupported event diff type: ${(event.diff as any).type}. Supported types are: 'tree', 'map', 'list', 'text', 'counter'.`); + default: + throw new Error(`Unsupported event diff type: ${(event.diff as any).type}. Supported types are: 'tree', 'map', 'list', 'text', 'counter'.`); + } + } catch (err) { + console.error( + '[SEED-DEBUG] syncLoroToLexical: integrator threw for event', + index, + 'diffType=', + (event.diff as any)?.type, + 'target=', + String((event as any)?.target), + 'diff=', + JSON.stringify((event.diff as any)), + err, + ); + throw err; } }); diff --git a/src/collab/loro/types/LexicalNodeData.ts b/src/collab/loro/types/LexicalNodeData.ts index 685257a2..6d7bf0a3 100644 --- a/src/collab/loro/types/LexicalNodeData.ts +++ b/src/collab/loro/types/LexicalNodeData.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/collab/loro/useCollaboration.tsx b/src/collab/loro/useCollaboration.tsx index f4ae33bc..f00a5842 100644 --- a/src/collab/loro/useCollaboration.tsx +++ b/src/collab/loro/useCollaboration.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -10,7 +10,10 @@ import {createPortal} from 'react-dom'; import type {LexicalEditor} from 'lexical'; import {mergeRegister} from '@lexical/utils'; import { + $getNodeByKey, $getRoot, + $parseSerializedNode, + $setSelection, BLUR_COMMAND, CAN_REDO_COMMAND, CAN_UNDO_COMMAND, @@ -74,6 +77,7 @@ export function useCollaboration( }; const onSync = (isSynced: boolean) => { + console.log('[SEED-DEBUG] onSync: isSynced=', isSynced, 'shouldBootstrap=', shouldBootstrap, 'isReloadingDoc=', isReloadingDoc.current); if ( shouldBootstrap && isSynced && @@ -136,8 +140,64 @@ export function useCollaboration( // This updates the local editor state when we receive updates from other clients. const unsubscribe = binding.doc.subscribe(onLoroUpdates); + // Lexical only includes a node type in `update.mutatedNodes` when that type + // has at least one registered mutation listener. Our Lexicalโ†’Loro sync + // relies entirely on `mutatedNodes`, so any node type without a listener is + // invisible to collaboration. In particular, the bootstrap seed runs before + // other plugins mount and register their own mutation listeners, so its + // commits produced an empty `mutatedNodes` and never propagated to peers. + // Register a no-op mutation listener for every node type registered on this + // editor so `mutatedNodes` is always fully populated (this mirrors how the + // Yjs binding stays independent of other plugins). + const mutationListenerCleanups: Array<() => void> = []; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const registeredNodes = (editor as any)._nodes as + | Map + | undefined; + console.log( + '[SEED-DEBUG] registering mutation listeners; registeredNodes=', + registeredNodes ? registeredNodes.size : 'undefined', + ); + if (registeredNodes) { + registeredNodes.forEach((registered) => { + if (registered && registered.klass) { + mutationListenerCleanups.push( + // eslint-disable-next-line @typescript-eslint/no-empty-function + editor.registerMutationListener(registered.klass, () => {}, { + skipInitialization: true, + }), + ); + } + }); + } + console.log( + '[SEED-DEBUG] mutation listeners registered=', + mutationListenerCleanups.length, + 'editor._listeners.mutation.size=', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (editor as any)._listeners?.mutation?.size, + ); + const removeListener = editor.registerUpdateListener( (update) => { + let __mn = 0; + if (update.mutatedNodes) { + update.mutatedNodes.forEach((m) => { + __mn += m.size; + }); + } + console.log( + '[SEED-DEBUG] updateListener fired; tags=', + Array.from(update.tags), + 'mutatedNodes=', + update.mutatedNodes ? 'map' : 'null', + 'count=', + __mn, + 'dirtyElements=', + update.dirtyElements?.size, + 'dirtyLeaves=', + update.dirtyLeaves?.size, + ); if (update.tags.has(SKIP_COLLAB_TAG) === false) { syncLexicalToLoro( binding, @@ -174,6 +234,7 @@ export function useCollaboration( unsubscribe?.(); docMap.delete(id); removeListener(); + mutationListenerCleanups.forEach((cleanup) => cleanup()); }; }, [ binding, @@ -335,39 +396,169 @@ function initializeEditor( editor: LexicalEditor, initialEditorState?: InitialEditorStateType, ): void { + // Text used by the server-side default scaffold that fresh rooms are + // pre-seeded with. When a room only contains this scaffold it should be + // treated as empty so the host app's real initial content can replace it. + const PLACEHOLDER_TEXTS = new Set([ + 'Lexical with Loro', + 'Welcome to Lexical with Loro', + 'Type something...', + ]); + + const hasMeaningfulContent = (): boolean => { + const root = $getRoot(); + const children = root.getChildren(); + + if (children.length === 0) { + return false; + } + + for (const child of children) { + const type = child.getType(); + const text = child.getTextContent().trim(); + + if (text.length > 0) { + // Ignore the known default scaffold text so it can be overwritten by + // the host app's initial content on a freshly created room. + if (!PLACEHOLDER_TEXTS.has(text)) { + return true; + } + continue; + } + + // Ignore known scaffold placeholders used by some host apps before + // collaboration bootstrap fills the real initial document. + if (type !== 'paragraph' && type !== 'jupyter-output') { + return true; + } + } + + return false; + }; + + // Only seed a room whose sole content is the (empty/scaffold) default. + let shouldSeed = false; + editor.getEditorState().read(() => { + shouldSeed = !hasMeaningfulContent(); + }); + console.log('[SEED-DEBUG] initializeEditor: shouldSeed=', shouldSeed, 'hasInitialState=', !!initialEditorState, 'type=', typeof initialEditorState); + if (!shouldSeed || !initialEditorState) { + return; + } + + // Preferred path: a serialized editor state (string). Seed it INCREMENTALLY, + // exactly as a human collaborator would build the document โ€” append each + // top-level block in its own commit, then remove the scaffold blocks one by + // one. Each small, well-formed commit produces clean per-node "created" + // mutations that the Loro binding propagates reliably. A single bulk + // clear()+append emitted one large, malformed batch that failed to integrate + // on remote peers (inline nodes arriving without a resolved parent), which is + // why the second editor never received the initial content. + if (typeof initialEditorState === 'string') { + let serializedChildren: unknown[] = []; + try { + const serialized = JSON.parse(initialEditorState); + serializedChildren = serialized?.root?.children ?? []; + } catch (error) { + // Not a rebuildable serialized state โ†’ fall back to a whole-state swap. + editor.update( + () => { + editor.setEditorState(editor.parseEditorState(initialEditorState), { + tag: HISTORY_MERGE_TAG, + }); + }, + {tag: HISTORY_MERGE_TAG}, + ); + return; + } + + // IMPORTANT: every seed update below is committed with `discrete: true`. + // The remote snapshot import runs `editor.update({tag: SKIP_COLLAB_TAG})` + // and that update is still queued when this bootstrap runs. Without + // `discrete`, Lexical coalesces the queued remote update together with our + // seed updates into a single reconciliation and unions their tags, so the + // seed batch inherits `skip-collab` and the collab sync ignores it. A + // leading discrete no-op flushes the pending remote (skip-collab) update on + // its own, and each discrete seed update then commits as its own + // reconciliation carrying only `history-merge`, so it propagates to peers. + // eslint-disable-next-line @typescript-eslint/no-empty-function + editor.update(() => {}, {tag: HISTORY_MERGE_TAG, discrete: true}); + + // Clear any pending selection first: it may point at scaffold nodes we are + // about to remove, which would otherwise crash selection-reading plugins + // (e.g. the typeahead menu). + editor.update( + () => { + $setSelection(null); + }, + {tag: HISTORY_MERGE_TAG, discrete: true}, + ); + + // Capture the scaffold blocks AFTER the leading discrete flush, so any + // late-arriving remote scaffold nodes are included. We remove them BEFORE + // appending the real content: the scaffold's position in the Loro tree does + // not necessarily line up with its Lexical index, so appending after it + // makes the computed Loro insertion index drift out of range. Removing the + // scaffold first leaves both trees at an aligned empty root, after which + // each appended block sits at a matching index in Lexical and Loro. + let scaffoldKeys: string[] = []; + editor.getEditorState().read(() => { + scaffoldKeys = $getRoot() + .getChildren() + .map(child => child.getKey()); + }); + + console.log('[SEED-DEBUG] initializeEditor: seeding', serializedChildren.length, 'blocks, removing', scaffoldKeys.length, 'scaffold blocks first'); + + // Remove the scaffold blocks one by one so both trees reach an aligned + // empty root before we append the real content. + for (const key of scaffoldKeys) { + editor.update( + () => { + const node = $getNodeByKey(key); + if (node) { + node.remove(); + } + }, + {tag: HISTORY_MERGE_TAG, discrete: true}, + ); + } + + // Append the real content block by block into the now-empty, aligned root + // (each commit โ‰ˆ one collaborator action). + let __blockIndex = 0; + for (const serializedNode of serializedChildren) { + const __idx = __blockIndex++; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const __type = (serializedNode as any)?.type; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const __childTypes = Array.isArray((serializedNode as any)?.children) + ? // eslint-disable-next-line @typescript-eslint/no-explicit-any + (serializedNode as any).children.map((c: any) => c?.type) + : []; + editor.update( + () => { + const root = $getRoot(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root.append($parseSerializedNode(serializedNode as any)); + }, + {tag: HISTORY_MERGE_TAG, discrete: true}, + ); + console.log('[SEED-DEBUG] appended block', __idx, 'type=', __type, 'children=', __childTypes); + } + return; + } + + // Non-string fallbacks (EditorState object or builder function). editor.update( () => { - const root = $getRoot(); - if (root.isEmpty()) { - if (initialEditorState) { - switch (typeof initialEditorState) { - case 'string': { - const parsedEditorState = - editor.parseEditorState(initialEditorState); - editor.setEditorState(parsedEditorState, { - tag: HISTORY_MERGE_TAG, - }); - break; - } - case 'object': { - editor.setEditorState(initialEditorState, { - tag: HISTORY_MERGE_TAG, - }); - break; - } - case 'function': { - editor.update( - () => { - const root1 = $getRoot(); - if (root1.isEmpty()) { - initialEditorState(editor); - } - }, - {tag: HISTORY_MERGE_TAG}, - ); - break; - } - } + if (!hasMeaningfulContent()) { + if (typeof initialEditorState === 'object') { + editor.setEditorState(initialEditorState, { + tag: HISTORY_MERGE_TAG, + }); + } else if (typeof initialEditorState === 'function') { + initialEditorState(editor); } } }, diff --git a/src/collab/loro/utils/InitialContent.ts b/src/collab/loro/utils/InitialContent.ts index 88d82c28..ab0415f9 100644 --- a/src/collab/loro/utils/InitialContent.ts +++ b/src/collab/loro/utils/InitialContent.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/collab/loro/utils/Invariant.ts b/src/collab/loro/utils/Invariant.ts new file mode 100644 index 00000000..b3fbbf73 --- /dev/null +++ b/src/collab/loro/utils/Invariant.ts @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2025-2026 Datalayer, Inc. + * Distributed under the terms of the MIT License. + */ + +/** + * Assert a collaboration invariant. + * + * The Loro <-> Lexical sync engine relies on a set of structural invariants + * (a node's parent is already mapped, an insertion index is within range, a + * text node always has a parent, ...). When one of these does not hold the + * engine is in a state it cannot resolve correctly. + * + * Historically such cases were "handled" by logging a warning and skipping the + * operation (or clamping an index). That silently corrupts the shared document + * and hides the underlying bug. Instead we throw: the failure surfaces + * immediately, the surrounding `editor.update()` rolls back cleanly, and the + * root cause can be found and fixed rather than masked. + */ +export function invariant( + condition: unknown, + message: string, + context?: Record, +): asserts condition { + if (!condition) { + const details = context ? ` ${JSON.stringify(context)}` : ''; + throw new Error(`[loro-collab] Invariant failed: ${message}${details}`); + } +} diff --git a/src/collab/loro/utils/LexicalToLoro.ts b/src/collab/loro/utils/LexicalToLoro.ts index f5244053..2cfc6cc1 100644 --- a/src/collab/loro/utils/LexicalToLoro.ts +++ b/src/collab/loro/utils/LexicalToLoro.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/collab/loro/utils/Utils.ts b/src/collab/loro/utils/Utils.ts index b96ac009..b5210054 100644 --- a/src/collab/loro/utils/Utils.ts +++ b/src/collab/loro/utils/Utils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/collab/loro/wsProvider.ts b/src/collab/loro/wsProvider.ts index 345656f8..6f139f3d 100644 --- a/src/collab/loro/wsProvider.ts +++ b/src/collab/loro/wsProvider.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -29,25 +29,43 @@ export function createWebsocketProvider( } const providerInstanceId = Math.random().toString(36).substr(2, 9); - console.log(`๐Ÿญ Creating WebsocketProvider instance (ID: ${providerInstanceId}) for docId: ${id}`); + console.log(` Creating WebsocketProvider instance (ID: ${providerInstanceId}) for docId: ${id}`); // Use provided websocketUrl or fallback to URL parameters/defaults - const finalWebsocketUrl = websocketUrl || (() => { + const rawWebsocketUrl = websocketUrl || (() => { const url = new URL(window.location.href); const params = new URLSearchParams(url.search); return params.get('collabEndpoint') || 'ws://localhost:3002'; })(); - + + // The WebsocketProvider builds the connection URL as + // `serverUrl + '/' + docId + '?' + params`. If the caller embedded a query + // string (for example `?token=`) directly in the URL, the docId would be + // appended *after* the query string, corrupting the URL. Split any query + // string off the base URL and forward it through the provider `params` so the + // final URL is `serverUrl/docId?token=` as the server expects. + let finalWebsocketUrl = rawWebsocketUrl; + const params: Record = {}; + const queryIndex = finalWebsocketUrl.indexOf('?'); + if (queryIndex !== -1) { + const query = finalWebsocketUrl.slice(queryIndex + 1); + finalWebsocketUrl = finalWebsocketUrl.slice(0, queryIndex); + new URLSearchParams(query).forEach((value, key) => { + params[key] = value; + }); + } + const websocketProvider = new WebsocketProvider( finalWebsocketUrl, id, doc, { connect: false, + params, resyncInterval: RESYNC_INTERVAL, // Poll ephemeral state periodically to prevent stale user accumulation }, ); - console.log(`๐Ÿญ WebsocketProvider created for: ${finalWebsocketUrl}/${id} with resyncInterval: ${RESYNC_INTERVAL}ms`); + console.log(` WebsocketProvider created for: ${finalWebsocketUrl}/${id} with resyncInterval: ${RESYNC_INTERVAL}ms`); return websocketProvider; } diff --git a/src/collab/utils/invariant.ts b/src/collab/utils/invariant.ts index 51828dbb..44579bd8 100644 --- a/src/collab/utils/invariant.ts +++ b/src/collab/utils/invariant.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/collab/utils/simpleDiffWithCursor.ts b/src/collab/utils/simpleDiffWithCursor.ts index 19a27da8..82eab7b0 100644 --- a/src/collab/utils/simpleDiffWithCursor.ts +++ b/src/collab/utils/simpleDiffWithCursor.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/commenting/index.ts b/src/commenting/index.ts index bbc3cd43..e325c464 100644 --- a/src/commenting/index.ts +++ b/src/commenting/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/context/FlashMessageContext.tsx b/src/context/FlashMessageContext.tsx index 33f16145..171277fc 100644 --- a/src/context/FlashMessageContext.tsx +++ b/src/context/FlashMessageContext.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/context/SettingsContext.tsx b/src/context/SettingsContext.tsx index a7cf4dcf..235cba0d 100644 --- a/src/context/SettingsContext.tsx +++ b/src/context/SettingsContext.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/context/SharedHistoryContext.tsx b/src/context/SharedHistoryContext.tsx index 22541c5a..fef43f55 100644 --- a/src/context/SharedHistoryContext.tsx +++ b/src/context/SharedHistoryContext.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/context/ToolbarContext.tsx b/src/context/ToolbarContext.tsx index 6785609d..f1d40cff 100644 --- a/src/context/ToolbarContext.tsx +++ b/src/context/ToolbarContext.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/demo.tsx b/src/demo.tsx index 677a62f5..83ab4e19 100644 --- a/src/demo.tsx +++ b/src/demo.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/hooks/useFlashMessage.tsx b/src/hooks/useFlashMessage.tsx index 5923da19..c81ed652 100644 --- a/src/hooks/useFlashMessage.tsx +++ b/src/hooks/useFlashMessage.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/hooks/useModal.tsx b/src/hooks/useModal.tsx index 5af9ba0b..edb95b74 100644 --- a/src/hooks/useModal.tsx +++ b/src/hooks/useModal.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/hooks/useReport.ts b/src/hooks/useReport.ts index 4b4d5310..64b7de5e 100644 --- a/src/hooks/useReport.ts +++ b/src/hooks/useReport.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/index.css b/src/index.css index 5a2cb504..78696b65 100644 --- a/src/index.css +++ b/src/index.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/index.ts b/src/index.ts index 4f7cfb4c..c7c88c8b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/AutocompleteNode.tsx b/src/nodes/AutocompleteNode.tsx index cf46109a..0b29ad60 100644 --- a/src/nodes/AutocompleteNode.tsx +++ b/src/nodes/AutocompleteNode.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/CounterComponent.tsx b/src/nodes/CounterComponent.tsx index 74e8a4b2..bebc5276 100644 --- a/src/nodes/CounterComponent.tsx +++ b/src/nodes/CounterComponent.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/CounterNode.tsx b/src/nodes/CounterNode.tsx index 13e92692..9707fb12 100644 --- a/src/nodes/CounterNode.tsx +++ b/src/nodes/CounterNode.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/DateTimeNode/DateTimeComponent.tsx b/src/nodes/DateTimeNode/DateTimeComponent.tsx index 2bba7069..f268caf3 100644 --- a/src/nodes/DateTimeNode/DateTimeComponent.tsx +++ b/src/nodes/DateTimeNode/DateTimeComponent.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/DateTimeNode/DateTimeNode.css b/src/nodes/DateTimeNode/DateTimeNode.css index e40b8eba..62306c66 100644 --- a/src/nodes/DateTimeNode/DateTimeNode.css +++ b/src/nodes/DateTimeNode/DateTimeNode.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/DateTimeNode/DateTimeNode.tsx b/src/nodes/DateTimeNode/DateTimeNode.tsx index 25aa50f6..48df52ff 100644 --- a/src/nodes/DateTimeNode/DateTimeNode.tsx +++ b/src/nodes/DateTimeNode/DateTimeNode.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/EmojiNode.tsx b/src/nodes/EmojiNode.tsx index 50694929..4653dd40 100644 --- a/src/nodes/EmojiNode.tsx +++ b/src/nodes/EmojiNode.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/EquationComponent.tsx b/src/nodes/EquationComponent.tsx index 090a9dae..ba99a92f 100644 --- a/src/nodes/EquationComponent.tsx +++ b/src/nodes/EquationComponent.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/EquationNode.tsx b/src/nodes/EquationNode.tsx index 9a61f2f9..f4d17f2f 100644 --- a/src/nodes/EquationNode.tsx +++ b/src/nodes/EquationNode.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/ExcalidrawNode/ExcalidrawComponent.tsx b/src/nodes/ExcalidrawNode/ExcalidrawComponent.tsx index ea272385..d4801c3c 100644 --- a/src/nodes/ExcalidrawNode/ExcalidrawComponent.tsx +++ b/src/nodes/ExcalidrawNode/ExcalidrawComponent.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/ExcalidrawNode/ExcalidrawImage.tsx b/src/nodes/ExcalidrawNode/ExcalidrawImage.tsx index 2f6bc5cc..d9d77e7e 100644 --- a/src/nodes/ExcalidrawNode/ExcalidrawImage.tsx +++ b/src/nodes/ExcalidrawNode/ExcalidrawImage.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/ExcalidrawNode/index.tsx b/src/nodes/ExcalidrawNode/index.tsx index 2cf01fbc..3cb23c31 100644 --- a/src/nodes/ExcalidrawNode/index.tsx +++ b/src/nodes/ExcalidrawNode/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/FigmaNode.tsx b/src/nodes/FigmaNode.tsx index 004d051a..72110d3e 100644 --- a/src/nodes/FigmaNode.tsx +++ b/src/nodes/FigmaNode.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/ImageComponent.tsx b/src/nodes/ImageComponent.tsx index dc3f2afd..6815e8c1 100644 --- a/src/nodes/ImageComponent.tsx +++ b/src/nodes/ImageComponent.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/ImageNode.css b/src/nodes/ImageNode.css index e907c90f..d6efdf26 100644 --- a/src/nodes/ImageNode.css +++ b/src/nodes/ImageNode.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/ImageNode.tsx b/src/nodes/ImageNode.tsx index 0c4e12ea..a48d095e 100644 --- a/src/nodes/ImageNode.tsx +++ b/src/nodes/ImageNode.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/InlineImageNode/InlineImageComponent.tsx b/src/nodes/InlineImageNode/InlineImageComponent.tsx index 62b27dde..77cebded 100644 --- a/src/nodes/InlineImageNode/InlineImageComponent.tsx +++ b/src/nodes/InlineImageNode/InlineImageComponent.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/InlineImageNode/InlineImageNode.css b/src/nodes/InlineImageNode/InlineImageNode.css index 3c17b5ac..8f635431 100644 --- a/src/nodes/InlineImageNode/InlineImageNode.css +++ b/src/nodes/InlineImageNode/InlineImageNode.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/InlineImageNode/InlineImageNode.tsx b/src/nodes/InlineImageNode/InlineImageNode.tsx index b112dfd7..a21eede1 100644 --- a/src/nodes/InlineImageNode/InlineImageNode.tsx +++ b/src/nodes/InlineImageNode/InlineImageNode.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/KeywordNode.ts b/src/nodes/KeywordNode.ts index 4b00cb94..42f6fff9 100644 --- a/src/nodes/KeywordNode.ts +++ b/src/nodes/KeywordNode.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/LayoutContainerNode.ts b/src/nodes/LayoutContainerNode.ts index 0e84123d..113cf2a3 100644 --- a/src/nodes/LayoutContainerNode.ts +++ b/src/nodes/LayoutContainerNode.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/LayoutItemNode.ts b/src/nodes/LayoutItemNode.ts index 5c94707e..a71012fc 100644 --- a/src/nodes/LayoutItemNode.ts +++ b/src/nodes/LayoutItemNode.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/MentionNode.ts b/src/nodes/MentionNode.ts index 4f993d55..d5087894 100644 --- a/src/nodes/MentionNode.ts +++ b/src/nodes/MentionNode.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/PageBreakNode/index.css b/src/nodes/PageBreakNode/index.css index 7d2dec10..251e2cfc 100644 --- a/src/nodes/PageBreakNode/index.css +++ b/src/nodes/PageBreakNode/index.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/PageBreakNode/index.tsx b/src/nodes/PageBreakNode/index.tsx index 562c4c4a..14b6dbed 100644 --- a/src/nodes/PageBreakNode/index.tsx +++ b/src/nodes/PageBreakNode/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/PlaygroundNodes.ts b/src/nodes/PlaygroundNodes.ts index 81fac47b..6fb0c9ac 100644 --- a/src/nodes/PlaygroundNodes.ts +++ b/src/nodes/PlaygroundNodes.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/PollComponent.tsx b/src/nodes/PollComponent.tsx index fb601937..6dfd2a43 100644 --- a/src/nodes/PollComponent.tsx +++ b/src/nodes/PollComponent.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/PollNode.css b/src/nodes/PollNode.css index 060be85b..1608f778 100644 --- a/src/nodes/PollNode.css +++ b/src/nodes/PollNode.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/PollNode.tsx b/src/nodes/PollNode.tsx index d0ba0f93..564e176b 100644 --- a/src/nodes/PollNode.tsx +++ b/src/nodes/PollNode.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/SpecialTextNode.tsx b/src/nodes/SpecialTextNode.tsx index 6a08941e..5cc33347 100644 --- a/src/nodes/SpecialTextNode.tsx +++ b/src/nodes/SpecialTextNode.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/StickyComponent.tsx b/src/nodes/StickyComponent.tsx index 6d93527e..e322c502 100644 --- a/src/nodes/StickyComponent.tsx +++ b/src/nodes/StickyComponent.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/StickyNode.css b/src/nodes/StickyNode.css index 25f8c378..6fe17c1b 100644 --- a/src/nodes/StickyNode.css +++ b/src/nodes/StickyNode.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/StickyNode.tsx b/src/nodes/StickyNode.tsx index 739a8d5a..4ced5d22 100644 --- a/src/nodes/StickyNode.tsx +++ b/src/nodes/StickyNode.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/TweetNode.tsx b/src/nodes/TweetNode.tsx index 13d38c46..079ed2f0 100644 --- a/src/nodes/TweetNode.tsx +++ b/src/nodes/TweetNode.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/nodes/YouTubeNode.tsx b/src/nodes/YouTubeNode.tsx index c6d20fbc..8d0097be 100644 --- a/src/nodes/YouTubeNode.tsx +++ b/src/nodes/YouTubeNode.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/ActionsPlugin/index.tsx b/src/plugins/ActionsPlugin/index.tsx index 29b67875..388daa22 100644 --- a/src/plugins/ActionsPlugin/index.tsx +++ b/src/plugins/ActionsPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/AutoEmbedPlugin/index.tsx b/src/plugins/AutoEmbedPlugin/index.tsx index a7ddc8e9..6614c41a 100644 --- a/src/plugins/AutoEmbedPlugin/index.tsx +++ b/src/plugins/AutoEmbedPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/AutoLinkPlugin/index.tsx b/src/plugins/AutoLinkPlugin/index.tsx index 835279f9..c9c9fffe 100644 --- a/src/plugins/AutoLinkPlugin/index.tsx +++ b/src/plugins/AutoLinkPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/AutocompletePlugin/index.tsx b/src/plugins/AutocompletePlugin/index.tsx index 12a33077..936a8b3a 100644 --- a/src/plugins/AutocompletePlugin/index.tsx +++ b/src/plugins/AutocompletePlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/CodeActionMenuPlugin/components/CopyButton/index.tsx b/src/plugins/CodeActionMenuPlugin/components/CopyButton/index.tsx index 56626ad0..0289870f 100644 --- a/src/plugins/CodeActionMenuPlugin/components/CopyButton/index.tsx +++ b/src/plugins/CodeActionMenuPlugin/components/CopyButton/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/CodeActionMenuPlugin/components/PrettierButton/index.css b/src/plugins/CodeActionMenuPlugin/components/PrettierButton/index.css index 085d9c4d..cdb10d61 100644 --- a/src/plugins/CodeActionMenuPlugin/components/PrettierButton/index.css +++ b/src/plugins/CodeActionMenuPlugin/components/PrettierButton/index.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/CodeActionMenuPlugin/components/PrettierButton/index.tsx b/src/plugins/CodeActionMenuPlugin/components/PrettierButton/index.tsx index e0fac449..9785877f 100644 --- a/src/plugins/CodeActionMenuPlugin/components/PrettierButton/index.tsx +++ b/src/plugins/CodeActionMenuPlugin/components/PrettierButton/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/CodeActionMenuPlugin/index.css b/src/plugins/CodeActionMenuPlugin/index.css index 8e6bff9e..95c17630 100644 --- a/src/plugins/CodeActionMenuPlugin/index.css +++ b/src/plugins/CodeActionMenuPlugin/index.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/CodeActionMenuPlugin/index.tsx b/src/plugins/CodeActionMenuPlugin/index.tsx index 2e369bf5..47f0a127 100644 --- a/src/plugins/CodeActionMenuPlugin/index.tsx +++ b/src/plugins/CodeActionMenuPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/CodeActionMenuPlugin/utils.ts b/src/plugins/CodeActionMenuPlugin/utils.ts index b0d89229..7263a85c 100644 --- a/src/plugins/CodeActionMenuPlugin/utils.ts +++ b/src/plugins/CodeActionMenuPlugin/utils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/CodeHighlightPrismPlugin/index.ts b/src/plugins/CodeHighlightPrismPlugin/index.ts index a8eb7076..a09ac5e6 100644 --- a/src/plugins/CodeHighlightPrismPlugin/index.ts +++ b/src/plugins/CodeHighlightPrismPlugin/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/CodeHighlightShikiPlugin/index.ts b/src/plugins/CodeHighlightShikiPlugin/index.ts index 2429136a..ec7375f3 100644 --- a/src/plugins/CodeHighlightShikiPlugin/index.ts +++ b/src/plugins/CodeHighlightShikiPlugin/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/CollapsiblePlugin/Collapsible.css b/src/plugins/CollapsiblePlugin/Collapsible.css index 30d2a583..ed22cf96 100644 --- a/src/plugins/CollapsiblePlugin/Collapsible.css +++ b/src/plugins/CollapsiblePlugin/Collapsible.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/CollapsiblePlugin/CollapsibleContainerNode.ts b/src/plugins/CollapsiblePlugin/CollapsibleContainerNode.ts index 2771690d..e85f3231 100644 --- a/src/plugins/CollapsiblePlugin/CollapsibleContainerNode.ts +++ b/src/plugins/CollapsiblePlugin/CollapsibleContainerNode.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/CollapsiblePlugin/CollapsibleContentNode.ts b/src/plugins/CollapsiblePlugin/CollapsibleContentNode.ts index 83a64f90..1b7be793 100644 --- a/src/plugins/CollapsiblePlugin/CollapsibleContentNode.ts +++ b/src/plugins/CollapsiblePlugin/CollapsibleContentNode.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/CollapsiblePlugin/CollapsibleTitleNode.ts b/src/plugins/CollapsiblePlugin/CollapsibleTitleNode.ts index 3ce46735..799357aa 100644 --- a/src/plugins/CollapsiblePlugin/CollapsibleTitleNode.ts +++ b/src/plugins/CollapsiblePlugin/CollapsibleTitleNode.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/CollapsiblePlugin/CollapsibleUtils.ts b/src/plugins/CollapsiblePlugin/CollapsibleUtils.ts index 2b89ef46..1ebb508f 100644 --- a/src/plugins/CollapsiblePlugin/CollapsibleUtils.ts +++ b/src/plugins/CollapsiblePlugin/CollapsibleUtils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/CollapsiblePlugin/index.ts b/src/plugins/CollapsiblePlugin/index.ts index 4aa6bd4c..ea40cdec 100644 --- a/src/plugins/CollapsiblePlugin/index.ts +++ b/src/plugins/CollapsiblePlugin/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/CommentPlugin/index.css b/src/plugins/CommentPlugin/index.css index 6ded488f..ba927b90 100644 --- a/src/plugins/CommentPlugin/index.css +++ b/src/plugins/CommentPlugin/index.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/CommentPlugin/index.tsx b/src/plugins/CommentPlugin/index.tsx index d465bf6b..86c6cbf2 100644 --- a/src/plugins/CommentPlugin/index.tsx +++ b/src/plugins/CommentPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/ComponentPickerPlugin/index.tsx b/src/plugins/ComponentPickerPlugin/index.tsx index 8753ec3d..030dee53 100644 --- a/src/plugins/ComponentPickerPlugin/index.tsx +++ b/src/plugins/ComponentPickerPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/ContextMenuPlugin/index.tsx b/src/plugins/ContextMenuPlugin/index.tsx index 59854b4e..f284b657 100644 --- a/src/plugins/ContextMenuPlugin/index.tsx +++ b/src/plugins/ContextMenuPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/CounterPlugin/index.ts b/src/plugins/CounterPlugin/index.ts index d56d8eda..9c502b3e 100644 --- a/src/plugins/CounterPlugin/index.ts +++ b/src/plugins/CounterPlugin/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/DateTimePlugin/index.tsx b/src/plugins/DateTimePlugin/index.tsx index e358725b..01013040 100644 --- a/src/plugins/DateTimePlugin/index.tsx +++ b/src/plugins/DateTimePlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/DebugPlugin/index.tsx b/src/plugins/DebugPlugin/index.tsx index cc65efc1..a967aa36 100644 --- a/src/plugins/DebugPlugin/index.tsx +++ b/src/plugins/DebugPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -22,6 +22,71 @@ export function DebugPlugin(): JSX.Element | null { const [isLoadingTools, setIsLoadingTools] = useState(false); const [toolsError, setToolsError] = useState(null); + const getCurrentCollabDocId = (): string => { + const params = new URLSearchParams(window.location.search); + return params.get('collabId') || 'main'; + }; + + const isInSplitScreen = (): boolean => { + try { + return window.parent != null && window.parent.location.pathname === '/split/'; + } catch { + return false; + } + }; + + const navigateToRoom = (roomId: string, collabId: string): void => { + const url = new URL(window.location.href); + url.searchParams.set('roomId', roomId); + url.searchParams.set('collabId', collabId); + + if (isInSplitScreen()) { + window.parent.location.href = `/split/${url.search}`; + return; + } + + window.location.href = `${url.pathname}${url.search}`; + }; + + const createNewRoomWithDocument = async () => { + const roomId = Date.now().toString(36); + const collabId = `room-${roomId}`; + const seedText = `New room ${roomId} created at ${new Date().toISOString()}`; + + try { + const response = await fetch('http://localhost:3001/', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: Date.now(), + method: 'append_paragraph', + params: { + doc_id: collabId, + text: seedText, + }, + }), + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const data = await response.json(); + if (data.error) { + throw new Error(typeof data.error === 'string' ? data.error : JSON.stringify(data.error)); + } + + console.log('Created new room document:', collabId, data.result || data); + } catch (error) { + console.warn('Unable to seed room via MCP, continuing with room navigation:', error); + } + + navigateToRoom(roomId, collabId); + }; + // Fetch available MCP tools from the server const fetchMCPTools = async () => { setIsLoadingTools(true); @@ -82,7 +147,7 @@ export function DebugPlugin(): JSX.Element | null { id: Date.now(), method: 'get_document', params: { - doc_id: 'playground/0/main' + doc_id: getCurrentCollabDocId() } }) }); @@ -121,7 +186,7 @@ export function DebugPlugin(): JSX.Element | null { id: Date.now(), method: 'append_paragraph', params: { - doc_id: 'playground/0/main', + doc_id: getCurrentCollabDocId(), text: paragraphText } }) @@ -231,6 +296,7 @@ export function DebugPlugin(): JSX.Element | null { return ( <> + diff --git a/src/plugins/DocsPlugin/index.tsx b/src/plugins/DocsPlugin/index.tsx index 442f482d..0adbaa40 100644 --- a/src/plugins/DocsPlugin/index.tsx +++ b/src/plugins/DocsPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/DragDropPastePlugin/index.ts b/src/plugins/DragDropPastePlugin/index.ts index fe42dc0e..a0db53e5 100644 --- a/src/plugins/DragDropPastePlugin/index.ts +++ b/src/plugins/DragDropPastePlugin/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/DraggableBlockPlugin/index.css b/src/plugins/DraggableBlockPlugin/index.css index e57d1f1e..b46629a6 100644 --- a/src/plugins/DraggableBlockPlugin/index.css +++ b/src/plugins/DraggableBlockPlugin/index.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/DraggableBlockPlugin/index.tsx b/src/plugins/DraggableBlockPlugin/index.tsx index c0eccd7d..ee9e2935 100644 --- a/src/plugins/DraggableBlockPlugin/index.tsx +++ b/src/plugins/DraggableBlockPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/EmojiPickerPlugin/index.tsx b/src/plugins/EmojiPickerPlugin/index.tsx index 21dd4d99..be4f726f 100644 --- a/src/plugins/EmojiPickerPlugin/index.tsx +++ b/src/plugins/EmojiPickerPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/EmojisPlugin/index.ts b/src/plugins/EmojisPlugin/index.ts index d681ca51..023fb677 100644 --- a/src/plugins/EmojisPlugin/index.ts +++ b/src/plugins/EmojisPlugin/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/EquationsPlugin/index.tsx b/src/plugins/EquationsPlugin/index.tsx index 2cd3855f..fa88ed07 100644 --- a/src/plugins/EquationsPlugin/index.tsx +++ b/src/plugins/EquationsPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/ExcalidrawPlugin/index.tsx b/src/plugins/ExcalidrawPlugin/index.tsx index 1bd948a5..0d958d06 100644 --- a/src/plugins/ExcalidrawPlugin/index.tsx +++ b/src/plugins/ExcalidrawPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/FigmaPlugin/index.tsx b/src/plugins/FigmaPlugin/index.tsx index f3546635..30446e0e 100644 --- a/src/plugins/FigmaPlugin/index.tsx +++ b/src/plugins/FigmaPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/FloatingLinkEditorPlugin/index.css b/src/plugins/FloatingLinkEditorPlugin/index.css index 397ef50c..c1277914 100644 --- a/src/plugins/FloatingLinkEditorPlugin/index.css +++ b/src/plugins/FloatingLinkEditorPlugin/index.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/FloatingLinkEditorPlugin/index.tsx b/src/plugins/FloatingLinkEditorPlugin/index.tsx index c9171d74..24c85a19 100644 --- a/src/plugins/FloatingLinkEditorPlugin/index.tsx +++ b/src/plugins/FloatingLinkEditorPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/FloatingTextFormatToolbarPlugin/index.css b/src/plugins/FloatingTextFormatToolbarPlugin/index.css index 39b2cd4e..55f5c62a 100644 --- a/src/plugins/FloatingTextFormatToolbarPlugin/index.css +++ b/src/plugins/FloatingTextFormatToolbarPlugin/index.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/FloatingTextFormatToolbarPlugin/index.tsx b/src/plugins/FloatingTextFormatToolbarPlugin/index.tsx index f88605c1..00e65e40 100644 --- a/src/plugins/FloatingTextFormatToolbarPlugin/index.tsx +++ b/src/plugins/FloatingTextFormatToolbarPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/ImagesPlugin/index.tsx b/src/plugins/ImagesPlugin/index.tsx index 3e970e48..f203a1a2 100644 --- a/src/plugins/ImagesPlugin/index.tsx +++ b/src/plugins/ImagesPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/InlineImagePlugin/index.tsx b/src/plugins/InlineImagePlugin/index.tsx index a51f267e..8d718aef 100644 --- a/src/plugins/InlineImagePlugin/index.tsx +++ b/src/plugins/InlineImagePlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/KeywordsPlugin/index.ts b/src/plugins/KeywordsPlugin/index.ts index 797dfe8d..e74bcb97 100644 --- a/src/plugins/KeywordsPlugin/index.ts +++ b/src/plugins/KeywordsPlugin/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/LayoutPlugin/InsertLayoutDialog.tsx b/src/plugins/LayoutPlugin/InsertLayoutDialog.tsx index 0cc264f7..2d1f2bde 100644 --- a/src/plugins/LayoutPlugin/InsertLayoutDialog.tsx +++ b/src/plugins/LayoutPlugin/InsertLayoutDialog.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/LayoutPlugin/LayoutPlugin.tsx b/src/plugins/LayoutPlugin/LayoutPlugin.tsx index 3cf38fd7..ab19a7f6 100644 --- a/src/plugins/LayoutPlugin/LayoutPlugin.tsx +++ b/src/plugins/LayoutPlugin/LayoutPlugin.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/LinkPlugin/index.tsx b/src/plugins/LinkPlugin/index.tsx index 4f7223a4..b9384a56 100644 --- a/src/plugins/LinkPlugin/index.tsx +++ b/src/plugins/LinkPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/MarkdownShortcutPlugin/index.tsx b/src/plugins/MarkdownShortcutPlugin/index.tsx index 25c73277..0cb2e160 100644 --- a/src/plugins/MarkdownShortcutPlugin/index.tsx +++ b/src/plugins/MarkdownShortcutPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/MarkdownTransformers/index.ts b/src/plugins/MarkdownTransformers/index.ts index c016d672..9849b7e4 100644 --- a/src/plugins/MarkdownTransformers/index.ts +++ b/src/plugins/MarkdownTransformers/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/MaxLengthPlugin/index.tsx b/src/plugins/MaxLengthPlugin/index.tsx index fa4c933a..e5388bf1 100644 --- a/src/plugins/MaxLengthPlugin/index.tsx +++ b/src/plugins/MaxLengthPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/MentionsPlugin/index.tsx b/src/plugins/MentionsPlugin/index.tsx index 01c7adce..c120acb0 100644 --- a/src/plugins/MentionsPlugin/index.tsx +++ b/src/plugins/MentionsPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/PageBreakPlugin/index.tsx b/src/plugins/PageBreakPlugin/index.tsx index 3595a701..edebe86a 100644 --- a/src/plugins/PageBreakPlugin/index.tsx +++ b/src/plugins/PageBreakPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/PasteLogPlugin/index.tsx b/src/plugins/PasteLogPlugin/index.tsx index f800c770..f74bd943 100644 --- a/src/plugins/PasteLogPlugin/index.tsx +++ b/src/plugins/PasteLogPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/PollPlugin/index.tsx b/src/plugins/PollPlugin/index.tsx index 0a4183cf..2ee227a1 100644 --- a/src/plugins/PollPlugin/index.tsx +++ b/src/plugins/PollPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/ShortcutsPlugin/index.tsx b/src/plugins/ShortcutsPlugin/index.tsx index 35cbb829..3e50d84c 100644 --- a/src/plugins/ShortcutsPlugin/index.tsx +++ b/src/plugins/ShortcutsPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/ShortcutsPlugin/shortcuts.ts b/src/plugins/ShortcutsPlugin/shortcuts.ts index 6ea8b8a9..75e587cb 100644 --- a/src/plugins/ShortcutsPlugin/shortcuts.ts +++ b/src/plugins/ShortcutsPlugin/shortcuts.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/SpecialTextPlugin/index.ts b/src/plugins/SpecialTextPlugin/index.ts index 11c1a02b..01455d52 100644 --- a/src/plugins/SpecialTextPlugin/index.ts +++ b/src/plugins/SpecialTextPlugin/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/SpeechToTextPlugin/index.ts b/src/plugins/SpeechToTextPlugin/index.ts index caeae4d4..728192ee 100644 --- a/src/plugins/SpeechToTextPlugin/index.ts +++ b/src/plugins/SpeechToTextPlugin/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/StickyPlugin/index.ts b/src/plugins/StickyPlugin/index.ts index ff2c305d..8fb7061e 100644 --- a/src/plugins/StickyPlugin/index.ts +++ b/src/plugins/StickyPlugin/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/TabFocusPlugin/index.tsx b/src/plugins/TabFocusPlugin/index.tsx index c011e0e1..7989b84d 100644 --- a/src/plugins/TabFocusPlugin/index.tsx +++ b/src/plugins/TabFocusPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/TableActionMenuPlugin/index.tsx b/src/plugins/TableActionMenuPlugin/index.tsx index afd7f7ad..b48bf1ba 100644 --- a/src/plugins/TableActionMenuPlugin/index.tsx +++ b/src/plugins/TableActionMenuPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/TableCellResizer/index.css b/src/plugins/TableCellResizer/index.css index f734a563..3becd92a 100644 --- a/src/plugins/TableCellResizer/index.css +++ b/src/plugins/TableCellResizer/index.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/TableCellResizer/index.tsx b/src/plugins/TableCellResizer/index.tsx index 142b0b7a..d83efb6c 100644 --- a/src/plugins/TableCellResizer/index.tsx +++ b/src/plugins/TableCellResizer/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/TableHoverActionsPlugin/index.tsx b/src/plugins/TableHoverActionsPlugin/index.tsx index f6458877..10eba07c 100644 --- a/src/plugins/TableHoverActionsPlugin/index.tsx +++ b/src/plugins/TableHoverActionsPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/TableOfContentsPlugin/index.css b/src/plugins/TableOfContentsPlugin/index.css index a91b1721..a0db539f 100644 --- a/src/plugins/TableOfContentsPlugin/index.css +++ b/src/plugins/TableOfContentsPlugin/index.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/TableOfContentsPlugin/index.tsx b/src/plugins/TableOfContentsPlugin/index.tsx index d7091eac..7346a1ff 100644 --- a/src/plugins/TableOfContentsPlugin/index.tsx +++ b/src/plugins/TableOfContentsPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/TablePlugin.tsx b/src/plugins/TablePlugin.tsx index 56b72932..16a4f108 100644 --- a/src/plugins/TablePlugin.tsx +++ b/src/plugins/TablePlugin.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/TestRecorderPlugin/index.tsx b/src/plugins/TestRecorderPlugin/index.tsx index f5fcb389..465b48eb 100644 --- a/src/plugins/TestRecorderPlugin/index.tsx +++ b/src/plugins/TestRecorderPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/ToolbarPlugin/fontSize.css b/src/plugins/ToolbarPlugin/fontSize.css index 22d5b4a2..09238c48 100644 --- a/src/plugins/ToolbarPlugin/fontSize.css +++ b/src/plugins/ToolbarPlugin/fontSize.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/ToolbarPlugin/fontSize.tsx b/src/plugins/ToolbarPlugin/fontSize.tsx index c15b62a4..dbf76fdc 100644 --- a/src/plugins/ToolbarPlugin/fontSize.tsx +++ b/src/plugins/ToolbarPlugin/fontSize.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/ToolbarPlugin/index.tsx b/src/plugins/ToolbarPlugin/index.tsx index 06f93c05..83806955 100644 --- a/src/plugins/ToolbarPlugin/index.tsx +++ b/src/plugins/ToolbarPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/ToolbarPlugin/utils.ts b/src/plugins/ToolbarPlugin/utils.ts index 066c6f21..df218183 100644 --- a/src/plugins/ToolbarPlugin/utils.ts +++ b/src/plugins/ToolbarPlugin/utils.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/TreeViewPlugin/index.tsx b/src/plugins/TreeViewPlugin/index.tsx index f9a847fd..a002d931 100644 --- a/src/plugins/TreeViewPlugin/index.tsx +++ b/src/plugins/TreeViewPlugin/index.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/TwitterPlugin/index.ts b/src/plugins/TwitterPlugin/index.ts index 75ed9bf2..636780d4 100644 --- a/src/plugins/TwitterPlugin/index.ts +++ b/src/plugins/TwitterPlugin/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/TypingPerfPlugin/index.ts b/src/plugins/TypingPerfPlugin/index.ts index ed822079..526a31f4 100644 --- a/src/plugins/TypingPerfPlugin/index.ts +++ b/src/plugins/TypingPerfPlugin/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/plugins/YouTubePlugin/index.ts b/src/plugins/YouTubePlugin/index.ts index 87fb568d..bc00578e 100644 --- a/src/plugins/YouTubePlugin/index.ts +++ b/src/plugins/YouTubePlugin/index.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/server/validation.ts b/src/server/validation.ts index 44036c2b..64ece325 100644 --- a/src/server/validation.ts +++ b/src/server/validation.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/setupEnv.ts b/src/setupEnv.ts index 9de6715d..e960eaed 100644 --- a/src/setupEnv.ts +++ b/src/setupEnv.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/themes/CommentEditorTheme.css b/src/themes/CommentEditorTheme.css index 214e795e..3dd18ba5 100644 --- a/src/themes/CommentEditorTheme.css +++ b/src/themes/CommentEditorTheme.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/themes/CommentEditorTheme.ts b/src/themes/CommentEditorTheme.ts index c9cea0ee..37b44fb6 100644 --- a/src/themes/CommentEditorTheme.ts +++ b/src/themes/CommentEditorTheme.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/themes/PlaygroundEditorTheme.css b/src/themes/PlaygroundEditorTheme.css index 778865a8..2046b36e 100644 --- a/src/themes/PlaygroundEditorTheme.css +++ b/src/themes/PlaygroundEditorTheme.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/themes/PlaygroundEditorTheme.ts b/src/themes/PlaygroundEditorTheme.ts index f8ea231b..b8896593 100644 --- a/src/themes/PlaygroundEditorTheme.ts +++ b/src/themes/PlaygroundEditorTheme.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/themes/StickyEditorTheme.css b/src/themes/StickyEditorTheme.css index 387c4e43..7a6e062b 100644 --- a/src/themes/StickyEditorTheme.css +++ b/src/themes/StickyEditorTheme.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/themes/StickyEditorTheme.ts b/src/themes/StickyEditorTheme.ts index 6a270845..1e322039 100644 --- a/src/themes/StickyEditorTheme.ts +++ b/src/themes/StickyEditorTheme.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/tyes.dt.ts b/src/tyes.dt.ts index fc771fc7..362776bc 100644 --- a/src/tyes.dt.ts +++ b/src/tyes.dt.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/Button.css b/src/ui/Button.css index 188d7782..bedf84a9 100644 --- a/src/ui/Button.css +++ b/src/ui/Button.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/Button.tsx b/src/ui/Button.tsx index 11594008..b973b538 100644 --- a/src/ui/Button.tsx +++ b/src/ui/Button.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/ColorPicker.css b/src/ui/ColorPicker.css index 91a2ad01..14e15c7c 100644 --- a/src/ui/ColorPicker.css +++ b/src/ui/ColorPicker.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/ColorPicker.tsx b/src/ui/ColorPicker.tsx index f74a8da0..b9916c70 100644 --- a/src/ui/ColorPicker.tsx +++ b/src/ui/ColorPicker.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/ContentEditable.css b/src/ui/ContentEditable.css index f8e06484..0670e158 100644 --- a/src/ui/ContentEditable.css +++ b/src/ui/ContentEditable.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/ContentEditable.tsx b/src/ui/ContentEditable.tsx index 370464e8..c8b781ce 100644 --- a/src/ui/ContentEditable.tsx +++ b/src/ui/ContentEditable.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/Dialog.css b/src/ui/Dialog.css index 1d53b5cb..22e86029 100644 --- a/src/ui/Dialog.css +++ b/src/ui/Dialog.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/Dialog.tsx b/src/ui/Dialog.tsx index 27cd04fc..d74be4b0 100644 --- a/src/ui/Dialog.tsx +++ b/src/ui/Dialog.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/DropDown.tsx b/src/ui/DropDown.tsx index 8739e1b5..8aba52a9 100644 --- a/src/ui/DropDown.tsx +++ b/src/ui/DropDown.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/DropdownColorPicker.tsx b/src/ui/DropdownColorPicker.tsx index 376ed88e..c2cb78e2 100644 --- a/src/ui/DropdownColorPicker.tsx +++ b/src/ui/DropdownColorPicker.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/EquationEditor.css b/src/ui/EquationEditor.css index ac82f633..7469d9aa 100644 --- a/src/ui/EquationEditor.css +++ b/src/ui/EquationEditor.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/EquationEditor.tsx b/src/ui/EquationEditor.tsx index c12af3bb..f95d560a 100644 --- a/src/ui/EquationEditor.tsx +++ b/src/ui/EquationEditor.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/ExcalidrawModal.css b/src/ui/ExcalidrawModal.css index 72bbbdf1..eb0f8548 100644 --- a/src/ui/ExcalidrawModal.css +++ b/src/ui/ExcalidrawModal.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/ExcalidrawModal.tsx b/src/ui/ExcalidrawModal.tsx index 60d5ca0b..4b94630d 100644 --- a/src/ui/ExcalidrawModal.tsx +++ b/src/ui/ExcalidrawModal.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/FileInput.tsx b/src/ui/FileInput.tsx index 74bad430..7ef63cad 100644 --- a/src/ui/FileInput.tsx +++ b/src/ui/FileInput.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/FlashMessage.css b/src/ui/FlashMessage.css index 7427092c..62d920e5 100644 --- a/src/ui/FlashMessage.css +++ b/src/ui/FlashMessage.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/FlashMessage.tsx b/src/ui/FlashMessage.tsx index ba4abcc9..58d4d242 100644 --- a/src/ui/FlashMessage.tsx +++ b/src/ui/FlashMessage.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/ImageResizer.tsx b/src/ui/ImageResizer.tsx index adf7a20d..60b4695c 100644 --- a/src/ui/ImageResizer.tsx +++ b/src/ui/ImageResizer.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/Input.css b/src/ui/Input.css index fd8beb95..7cb97fed 100644 --- a/src/ui/Input.css +++ b/src/ui/Input.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/KatexEquationAlterer.css b/src/ui/KatexEquationAlterer.css index 8d12edc5..7d80db2e 100644 --- a/src/ui/KatexEquationAlterer.css +++ b/src/ui/KatexEquationAlterer.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/KatexEquationAlterer.tsx b/src/ui/KatexEquationAlterer.tsx index 5ab2ff56..2635036b 100644 --- a/src/ui/KatexEquationAlterer.tsx +++ b/src/ui/KatexEquationAlterer.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/KatexRenderer.tsx b/src/ui/KatexRenderer.tsx index d54b7d45..6e25f7fd 100644 --- a/src/ui/KatexRenderer.tsx +++ b/src/ui/KatexRenderer.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/Modal.css b/src/ui/Modal.css index 0d1e8c4f..b02bf6cf 100644 --- a/src/ui/Modal.css +++ b/src/ui/Modal.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/Modal.tsx b/src/ui/Modal.tsx index 5dcfe6b2..6e9cba75 100644 --- a/src/ui/Modal.tsx +++ b/src/ui/Modal.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/Select.css b/src/ui/Select.css index 3288d5b3..0c37957d 100644 --- a/src/ui/Select.css +++ b/src/ui/Select.css @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/Select.tsx b/src/ui/Select.tsx index 2abb67ab..7b7f4793 100644 --- a/src/ui/Select.tsx +++ b/src/ui/Select.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/Switch.tsx b/src/ui/Switch.tsx index 6378a724..206ad3ea 100644 --- a/src/ui/Switch.tsx +++ b/src/ui/Switch.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/ui/TextInput.tsx b/src/ui/TextInput.tsx index 93c0de34..943b68c0 100644 --- a/src/ui/TextInput.tsx +++ b/src/ui/TextInput.tsx @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/utils/docSerialization.ts b/src/utils/docSerialization.ts index d21f08f3..142807b9 100644 --- a/src/utils/docSerialization.ts +++ b/src/utils/docSerialization.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/utils/emoji-list.ts b/src/utils/emoji-list.ts index b5a8bc2e..ff6526c2 100644 --- a/src/utils/emoji-list.ts +++ b/src/utils/emoji-list.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/utils/getDOMRangeRect.ts b/src/utils/getDOMRangeRect.ts index 710dc341..69dca2ec 100644 --- a/src/utils/getDOMRangeRect.ts +++ b/src/utils/getDOMRangeRect.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/utils/getSelectedNode.ts b/src/utils/getSelectedNode.ts index 4ff94d59..1e49108a 100644 --- a/src/utils/getSelectedNode.ts +++ b/src/utils/getSelectedNode.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/utils/getThemeSelector.ts b/src/utils/getThemeSelector.ts index 95ed4443..c96b790b 100644 --- a/src/utils/getThemeSelector.ts +++ b/src/utils/getThemeSelector.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/utils/isMobileWidth.ts b/src/utils/isMobileWidth.ts index 092674d5..a2f8f84f 100644 --- a/src/utils/isMobileWidth.ts +++ b/src/utils/isMobileWidth.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/utils/joinClasses.ts b/src/utils/joinClasses.ts index 805aa243..7a3a8f66 100644 --- a/src/utils/joinClasses.ts +++ b/src/utils/joinClasses.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/utils/setFloatingElemPosition.ts b/src/utils/setFloatingElemPosition.ts index b8cff7e6..66b8734b 100644 --- a/src/utils/setFloatingElemPosition.ts +++ b/src/utils/setFloatingElemPosition.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/utils/setFloatingElemPositionForLinkEditor.ts b/src/utils/setFloatingElemPositionForLinkEditor.ts index 6b7f226b..885ee048 100644 --- a/src/utils/setFloatingElemPositionForLinkEditor.ts +++ b/src/utils/setFloatingElemPositionForLinkEditor.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/utils/swipe.ts b/src/utils/swipe.ts index 64406545..cfc66f84 100644 --- a/src/utils/swipe.ts +++ b/src/utils/swipe.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/src/utils/url.ts b/src/utils/url.ts index 62cdbbbd..b3d7a84d 100644 --- a/src/utils/url.ts +++ b/src/utils/url.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/test-debug.html b/test-debug.html index a4bb7c13..948ccc91 100644 --- a/test-debug.html +++ b/test-debug.html @@ -1,5 +1,5 @@ diff --git a/tests/__init__.py b/tests/__init__.py index 84f9fb26..c17be815 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. # Tests package \ No newline at end of file diff --git a/tests/test_client_id_correlation.py b/tests/test_client_id_correlation.py index 9d7cac75..47da0ace 100644 --- a/tests/test_client_id_correlation.py +++ b/tests/test_client_id_correlation.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/tests/test_direct_init.py b/tests/test_direct_init.py index 88c8abee..9c603ace 100644 --- a/tests/test_direct_init.py +++ b/tests/test_direct_init.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """Direct test of the Loro document initialization to isolate the issue.""" diff --git a/tests/test_lexical_converter.py b/tests/test_lexical_converter.py index 5ec9aeaf..05b54b1a 100644 --- a/tests/test_lexical_converter.py +++ b/tests/test_lexical_converter.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/tests/test_mcp_server_integration.py b/tests/test_mcp_server_integration.py index 0df14de1..571eadd9 100644 --- a/tests/test_mcp_server_integration.py +++ b/tests/test_mcp_server_integration.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/tests/test_persistence.py b/tests/test_persistence.py index dfb4d455..9b66d153 100644 --- a/tests/test_persistence.py +++ b/tests/test_persistence.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """ diff --git a/tests/test_tree_api.py b/tests/test_tree_api.py index eee6e50d..ecbe3e08 100644 --- a/tests/test_tree_api.py +++ b/tests/test_tree_api.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """Test the actual tree API to understand available methods.""" diff --git a/tests/test_websocket_debug.py b/tests/test_websocket_debug.py index 0b2be282..3aa5ba96 100644 --- a/tests/test_websocket_debug.py +++ b/tests/test_websocket_debug.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2023-2025 Datalayer, Inc. +# Copyright (c) 2025-2026 Datalayer, Inc. # Distributed under the terms of the MIT License. """Test the websocket server functionality to debug tree operations.""" diff --git a/vite.config.ts b/vite.config.ts index e28c56c2..7c2fba76 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ @@ -19,6 +19,9 @@ const require = createRequire(import.meta.url); // https://vitejs.dev/config/ export default defineConfig(({mode}) => ({ build: { + // Keep a modern output target so vite-plugin-top-level-await does not + // trigger unsupported downlevel transforms in esbuild. + target: 'esnext', outDir: 'build', rollupOptions: { input: { diff --git a/viteCopyEsm.ts b/viteCopyEsm.ts index 139115e7..5717b2f9 100644 --- a/viteCopyEsm.ts +++ b/viteCopyEsm.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */ diff --git a/viteCopyExcalidrawAssets.ts b/viteCopyExcalidrawAssets.ts index c61e2a2d..c9bf8016 100644 --- a/viteCopyExcalidrawAssets.ts +++ b/viteCopyExcalidrawAssets.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Datalayer, Inc. + * Copyright (c) 2025-2026 Datalayer, Inc. * Distributed under the terms of the MIT License. */