A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
improvement: [rtc] migrate y-js to Loro (#4831)
Myles Scolnickc6cc574db18d
diff --git a/frontend/package.json b/frontend/package.jsonindex f5c843dd52..cda998ae67 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -113,6 +113,8 @@"js-cookie": "^3.0.5","katex": "^0.16.22","lodash-es": "^4.17.21",+ "loro-codemirror": "^0.1.6",+ "loro-crdt": "^1.5.4","lucide-react": "^0.503.0","lz-string": "^1.5.0","marked": "^15.0.11",@@ -150,9 +152,6 @@"vega-loader": "^4.5.3","vscode-languageserver-protocol": "^3.17.5","web-vitals": "^4.2.4",- "y-codemirror.next": "^0.3.5",- "y-websocket": "^2.1.0",- "yjs": "^13.6.26","zod": "^3.24.3"},"scripts": {@@ -238,6 +237,8 @@"turbo": "^2.5.2","typescript": "^5.8.3","vite": "^6.3.2",+ "vite-plugin-top-level-await": "^1.5.0",+ "vite-plugin-wasm": "^3.4.1","vite-tsconfig-paths": "^5.1.4","vitest": "^3.1.1"},diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 9a996b5798..809df84a9f 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -315,6 +315,12 @@ importers:lodash-es:specifier: ^4.17.21version: 4.17.21+ loro-codemirror:+ specifier: ^0.1.6+ loro-crdt:+ specifier: ^1.5.4+ version: 1.5.4lucide-react:specifier: ^0.503.0version: 0.503.0([email protected])@@ -426,15 +432,6 @@ importers:web-vitals:specifier: ^4.2.4version: 4.2.4- y-codemirror.next:- specifier: ^0.3.5- y-websocket:- specifier: ^2.1.0- version: 2.1.0([email protected])- yjs:- specifier: ^13.6.26- version: 13.6.26zod:specifier: ^3.24.3version: 3.24.3@@ -610,6 +607,12 @@ importers:vite:specifier: ^6.3.2version: 6.3.2(@types/[email protected])([email protected])([email protected])([email protected])([email protected])+ vite-plugin-top-level-await:+ specifier: ^1.5.0+ version: 1.5.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ vite-plugin-wasm:+ specifier: ^3.4.1+ version: 3.4.1([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))vite-tsconfig-paths:specifier: ^5.1.4version: 5.1.4([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))@@ -3014,6 +3017,15 @@ packages:'@codemirror/state': 6.x.x'@codemirror/view': 6.x.x+ '@rollup/[email protected]':+ resolution: {integrity: sha512-10monEYsBp3scM4/ND4LNH5Rxvh3e/cVeL3jWTgZ2SrQ+BmUoQcopVQvnaMcOnykb1VkxUFuDAN+0FnpTFRy2A==}+ engines: {node: '>=14.0.0'}+ peerDependencies:+ rollup: ^1.20.0||^2.0.0||^3.0.0||^4.0.0+ peerDependenciesMeta:+ rollup:+ optional: true+'@rollup/[email protected]':resolution: {integrity: sha512-pTd9rIsP92h+B6wWwFbW8RkZv4hiR/xKsqre4SIuAOaOEQRxi0lqLke9k2/7WegC85GgUs9pjmOjCUi3In4vwA==}engines: {node: '>=14.0.0'}@@ -3985,16 +3997,6 @@ packages:resolution: {integrity: sha512-d8XPSGjfyzlXC3Xx891DJRyZfqk5JU0BJrDQcsWomFIV1/BIzPW5HDH5iDdWpqWaav0YVIEzT1RHTwWr0FFshA==}- resolution: {integrity: sha512-BsLm5vFMRUrrLeCcRc+G0t2qOaTzpoJQLOubq2XM72eNpjF5UdU5o/5NvlNhx95XHcAvcl8OMXr4mlg/fRgUXQ==}- engines: {node: '>=6'}- deprecated: Superseded by abstract-level (https://github.com/Level/community#faq)-- resolution: {integrity: sha512-TU5nlYgta8YrBMNpc9FwQzRbiXsj49gsALsXadbGHt9CROPzX5fB0rWDR5mtdpOOKa5XqRFpbj1QroPAoPzVjQ==}- engines: {node: '>=6'}- deprecated: Superseded by abstract-level (https://github.com/Level/community#faq)-resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==}peerDependencies:@@ -4201,9 +4203,6 @@ packages:resolution: {integrity: sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==}engines: {node: '>=8'}- resolution: {integrity: sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ==}-resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==}@@ -4322,9 +4321,6 @@ packages:resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}- resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==}-resolution: {integrity: sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==}@@ -5013,11 +5009,6 @@ packages:resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==}- resolution: {integrity: sha512-a59VOT+oDy7vtAbLRCZwWgxu2BaCfd5Hk7wxJd48ei7I+nsg8Orlb9CLG0PMZienk9BSUKgeAqkO2+Lw+1+Ukw==}- engines: {node: '>=6'}- deprecated: Superseded by abstract-level (https://github.com/Level/community#faq)-resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==}engines: {node: '>= 0.4'}@@ -5154,11 +5145,6 @@ packages:resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==}- resolution: {integrity: sha512-QKrV0iKR6MZVJV08QY0wp1e7vF6QbhnbQhb07bwpEyuz4uZiZgPlEGdkCROuFkUwdxlFaiPIhjyarH1ee/3vhw==}- engines: {node: '>=6'}- deprecated: Superseded by abstract-level (https://github.com/Level/community#faq)-resolution: {integrity: sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==}@@ -5899,9 +5885,6 @@ packages:engines: {node: '>=0.10.0'}hasBin: true- resolution: {integrity: sha512-HR7EVodfFUdQCTIeySw+WDRFJlPcLOJbXfwwZ7Oom6tjsvZ3bOkCDJHehQC3nxJrv7+f9XecwazynjU8e4Vw3Q==}-resolution: {integrity: sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==}engines: {node: '>=6'}@@ -6166,9 +6149,6 @@ packages:peerDependencies:ws: '*'- resolution: {integrity: sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==}-resolution: {integrity: sha512-Yljz7ffyPbrLpLngrMtZ7NduUgVvi6wG9RJ9IUcyCd59YQ911PBJphODUcbOVbqYfxe1wuYf/LJ8PauMRwsM/g==}@@ -6348,52 +6328,6 @@ packages:engines: {node: '>=6'}hasBin: true- resolution: {integrity: sha512-UyIwNb1lJBChJnGfjmO0OR+ezh2iVu1Kas3nvBS/BzGnx79dv6g7unpKIDNPMhfdTEGoc7mC8uAu51XEtX+FHQ==}- engines: {node: '>=6'}- deprecated: Superseded by level-transcoder (https://github.com/Level/community#faq)-- resolution: {integrity: sha512-OTKKOqeav2QWcERMJR7IS9CUo1sHnke2C0gkSmcR7QuEtFNLLzHQAvnMw8ykvEcv0Qtkg0p7FOwP1v9e5Smdcw==}- engines: {node: '>=6'}- deprecated: Superseded by abstract-level (https://github.com/Level/community#faq)-- resolution: {integrity: sha512-UVprBJXite4gPS+3VznfgDSU8PTRuVX0NXwoWW50KLxd2yw4Y1t2JUR5In1itQnudZqRMT9DlAM3Q//9NCjCFw==}- engines: {node: '>=6'}- deprecated: Superseded by abstract-level (https://github.com/Level/community#faq)-- resolution: {integrity: sha512-ZSthfEqzGSOMWoUGhTXdX9jv26d32XJuHz/5YnuHZzH6wldfWMOVwI9TBtKcya4BKTyTt3XVA0A3cF3q5CY30Q==}- engines: {node: '>=6'}-- resolution: {integrity: sha512-SnBIDo2pdO5VXh02ZmtAyPP6/+6YTJg2ibLtl9C34pWvmtMEmRTWpra+qO/hifkUtBTOtfx6S9vLDjBsBK4gRg==}- deprecated: Superseded by browser-level (https://github.com/Level/community#faq)-- resolution: {integrity: sha512-HMwMaQPlTC1IlcwT3+swhqf/NUO+ZhXVz6TY1zZIIZlIR0YSn8GtAAWmIvKjNY16ZkEg/JcpAuQskxsXqC0yOQ==}- engines: {node: '>=6'}- deprecated: Superseded by abstract-level (https://github.com/Level/community#faq)-- resolution: {integrity: sha512-rXM7GYnW8gsl1vedTJIbzOrRv85c/2uCMpiiCzO2fndd06U/kUXEEU9evYn4zFggBOg36IsBW8LzqIpETwwQzg==}- engines: {node: '>=6'}-- resolution: {integrity: sha512-psRSqJZCsC/irNhfHzrVZbmPYXDcEYhA5TVNwr+V92jF44rbf86hqGp8fiT702FyiArScYIlPSBTDUASCVNSpw==}- engines: {node: '>=8.6.0'}-- resolution: {integrity: sha512-iB8O/7Db9lPaITU1aA2txU/cBEXAt4vWwKQRrrWuS6XDgbP4QZGj9BL2aNbwb002atoQ/lIotJkfyzz+ygQnUQ==}- engines: {node: '>=8.6.0'}- deprecated: Superseded by classic-level (https://github.com/Level/community#faq)-- resolution: {integrity: sha512-94++VFO3qN95cM/d6eBXvd894oJE0w3cInq9USsyQzzoJxmiYzPAocNcuGCPGGjoXqDVJcr3C1jzt1TSjyaiLQ==}- engines: {node: '>=6'}- deprecated: Superseded by abstract-level (https://github.com/Level/community#faq)-resolution: {integrity: sha512-0OO4y2iOHix2W6ujICbKIaEQXvFQHue65vUG3pb5EUomzPI90z9hsA1VsO/dbIIpC53J8gxM9Q4Oho0jrCM/yA==}engines: {node: '>= 0.8.0'}@@ -6402,11 +6336,6 @@ packages:resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==}engines: {node: '>= 0.8.0'}- resolution: {integrity: sha512-vwztYuUf1uf/1zQxfzRfO5yzfNKhTtgOByCruuiQQxWQXnPb8Itaube5ylofcV0oM0aKal9Mv+S1s1Ky0UYP1w==}- engines: {node: '>=16'}- hasBin: true-resolution: {integrity: sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==}engines: {node: '>=14'}@@ -6444,9 +6373,6 @@ packages:resolution: {integrity: sha512-aVx8ztPv7/2ULbArGJ2Y42bG1mEQ5mGjpdvrbJcJFU3TbYybe+QlLS4pst9zV52ymy2in1KpFPiZnAOATxD4+Q==}- resolution: {integrity: sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==}-resolution: {integrity: sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==}@@ -6472,6 +6398,16 @@ packages:resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}hasBin: true+ resolution: {integrity: sha512-lVD+uD/I5owgmkPwyz98nZjtfvcR85XFxHGkS3C2M8RsKRRs+BIh+Y5Vay1Zx4Ppv5fybN97/WSk0ndI/+XOrQ==}+ peerDependencies:+ '@codemirror/state': ^6.0.0+ '@codemirror/view': ^6.7.0+ loro-crdt: ^1.4.6++ resolution: {integrity: sha512-yqtu2/JhuVTbGLCQT29P8nyUsMtetMpdqINJzxfIC9ZKsIXob3mhIFCo/BcsA7gga2Ck+BcOvOhC+OBQvSj8xg==}+resolution: {integrity: sha512-kkIp7XSkP78ZxJEsSxW3712C6teJVoeHHwgo9zJ380de7IYyJ2ISlxojcH2pC5OFLewESmnRi/+XCDIEEVyoug==}@@ -6481,9 +6417,6 @@ packages:resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}- resolution: {integrity: sha512-AI2r85+4MquTw9ZYqabu4nMwy9Oftlfa/e/52t9IjtfG+mGBbTNdAoZ3RQKLHR6r0wQnwZnPIEh/Ya6XTWAKNA==}-resolution: {integrity: sha512-HGGkdlPWQ0vTF8jJ5TdIqhQXZi6uh3LnNgfZ8MHiuxFfX3RZeA79r2MW2tHAZKlAVfoNE8esm3p+O6VkIvpj6w==}peerDependencies:@@ -6733,9 +6666,6 @@ packages:engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}hasBin: true- resolution: {integrity: sha512-A0xLykHtARfueITVDernsAWdtIMbOJgKgcluwENp3AlsKN/PloyO10HtmoqnFAQAcxPkgZN7wdfPfEd0zNGxbg==}-resolution: {integrity: sha512-zkVhZUA3y8mbz652WrL5x0fB0ehrBkulWT3TomAQ9iDtyXZvzKeEA6GPxAItBYeNYl5yngKRX612qHOhvMkDeg==}@@ -6771,10 +6701,6 @@ packages:encoding:optional: true- resolution: {integrity: sha512-dSq1xmcPDKPZ2EED2S6zw/b9NKsqzXRE6dVr8TVQnI3FJOTteUMuqF3Qqs6LZg+mLGYJWqQzMbIjMtJqTv87nQ==}- hasBin: true-resolution: {integrity: sha512-xxOWJsBKtzAq7DY0J+DTzuz58K8e7sJbdgwkbMWQe8UYB6ekmsQ45q0M/tJDsGaZmbC+l7n57UV8Hl5tHxO9uw==}@@ -7706,10 +7632,6 @@ packages:resolution: {integrity: sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==}- resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==}- engines: {node: '>= 6'}-resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==}engines: {node: '>=8.10.0'}@@ -8636,6 +8558,10 @@ packages:resolution: {integrity: sha512-kZf/K6hEIrWHI6XqOFUiiMa+79wE/D8Q+NCNAWclkyg3b4d2k7s0QGepNjiABc+aR3N1PAyHL7p6UcLY6LmrnA==}+ resolution: {integrity: sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==}+ hasBin: true+resolution: {integrity: sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==}hasBin: true@@ -8808,6 +8734,16 @@ packages:engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}hasBin: true+ resolution: {integrity: sha512-r/DtuvHrSqUVk23XpG2cl8gjt1aATMG5cjExXL1BUTcSNab6CzkcPua9BPEc9fuTP5UpwClCxUe3+dNGL0yrgQ==}+ peerDependencies:+ vite: '>=2.8'++ resolution: {integrity: sha512-ja3nSo2UCkVeitltJGkS3pfQHAanHv/DqGatdI39ja6McgABlpsZ5hVgl6wuR8Qx5etY3T5qgDQhOWzc5RReZA==}+ peerDependencies:+ vite: ^2 || ^3 || ^4 || ^5 || ^6+resolution: {integrity: sha512-cYj0LRuLV2c2sMqhqhGpaO3LretdtMn/BVX4cPLanIZuwwrkVl+lK84E/miEXkCHWXuq65rhNN4rXsBcOB3S4w==}peerDependencies:@@ -9050,17 +8986,6 @@ packages:resolution: {integrity: sha512-+QU2zd6OTD8XWIJCbffaiQeH9U73qIqafo1x6V1snCWYGJf6cVE0cDR4D8xRzcEnfI21IFrUPzPGtcPf8AC+Rw==}engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}- resolution: {integrity: sha512-jmTjYU0j60B+vHey6TfR3Z7RD61z/hmxBS3VMSGIrroOWXQEneK1zNuotOUrGyBHQj0yrpsLHPWtigEFd13ndA==}- peerDependencies:- bufferutil: ^4.0.1- utf-8-validate: ^5.0.2- peerDependenciesMeta:- bufferutil:- optional: true- utf-8-validate:- optional: true-resolution: {integrity: sha512-F+P9Jil7UiSKSkppIiD94dN07AwvFixvLIj1Og1Rl9GGMuNipJnV9JzjD6XuqmAeiswGvUmNLjr5cFuXwNS77Q==}engines: {node: '>=8.3.0'}@@ -9100,31 +9025,6 @@ packages:resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==}engines: {node: '>=0.4'}- resolution: {integrity: sha512-VluNu3e5HfEXybnypnsGwKAj+fKLd4iAnR7JuX1Sfyydmn1jCBS5wwEL/uS04Ch2ib0DnMAOF6ZRR/8kK3wyGw==}- peerDependencies:- '@codemirror/state': ^6.0.0- '@codemirror/view': ^6.0.0- yjs: ^13.5.6-- resolution: {integrity: sha512-6ulEn5AXfXJYi89rXPEg2mMHAyyw8+ZfeMMdOtBbV8FJpQ1NOrcgi6DTAcXof0dap84NjHPT2+9d0rb6cFsjEg==}- peerDependencies:- yjs: ^13.0.0-- resolution: {integrity: sha512-vHRF2L6iT3rwj1jub/K5tYcTT/mEYDUppgNPXwp8fmLpui9f7Yeq3OEtTLVF012j39QnV+KEQpNqoN7CWU7Y9Q==}- engines: {node: '>=16.0.0', npm: '>=8.0.0'}- peerDependencies:- yjs: ^13.0.0-- resolution: {integrity: sha512-WHYDRqomaGkkaujtowCDwL8KYk+t1zQCGIgKyvxvchhjTQlMgWXRHJK+FDEcWmHA7I7o/4fy0eniOrtmz0e4mA==}- engines: {node: '>=16.0.0', npm: '>=8.0.0'}- hasBin: true- peerDependencies:- yjs: ^13.5.6-resolution: {integrity: sha512-uGZHXkHnhF0XeeAPgnKfPv1bgKAYyVvmNL1xlKsPYZPaIHxGti2hHqvOCQv71XMsLxu1QjergkqogUnms5D3YQ==}@@ -9167,10 +9067,6 @@ packages:resolution: {integrity: sha512-6/QWTdisjnu5UHUzQGst+UOEuEVwIzFVGBjq3jMTFNs5WJQsH/X6nMURSaScIdF5txylr1Ao9bvbWiKi2yXbwA==}- resolution: {integrity: sha512-wiARO3wixu7mtoRP5f7LqpUtsURP9SmNgXUt3RlnZg4qDuF7dUjthwIvwxIDmK55dPw4Wl4QdW5A3ag0atwu7g==}- engines: {node: '>=16.0.0', npm: '>=8.0.0'}-resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}engines: {node: '>=10'}@@ -12430,6 +12326,8 @@ snapshots:'@codemirror/state': 6.5.2'@codemirror/view': 6.36.6+ '@rollup/[email protected]': {}+'@rollup/[email protected]':dependencies:'@types/estree': 1.0.7@@ -13563,24 +13461,6 @@ snapshots:- dependencies:- buffer: 5.7.1- immediate: 3.3.0- level-concat-iterator: 2.0.1- level-supports: 1.0.1- xtend: 4.0.2- optional: true-- dependencies:- buffer: 5.7.1- immediate: 3.3.0- level-concat-iterator: 2.0.1- level-supports: 1.0.1- xtend: 4.0.2- optional: true-dependencies:acorn: 8.14.1@@ -13791,9 +13671,6 @@ snapshots:- optional: true-@@ -13908,12 +13785,6 @@ snapshots:- dependencies:- base64-js: 1.5.1- ieee754: 1.2.1- optional: true-dependencies:base64-js: 1.5.1@@ -14699,12 +14570,6 @@ snapshots:- dependencies:- abstract-leveldown: 6.2.3- inherits: 2.0.4- optional: true-dependencies:es-define-property: 1.0.0@@ -14841,14 +14706,6 @@ snapshots:- dependencies:- abstract-leveldown: 6.3.0- inherits: 2.0.4- level-codec: 9.0.2- level-errors: 2.0.1- optional: true-dependencies:once: 1.4.0@@ -15846,9 +15703,6 @@ snapshots:optional: true- optional: true-dependencies:parent-module: 1.0.1@@ -16072,8 +15926,6 @@ snapshots:dependencies:ws: 7.5.9- [email protected]: {}-@@ -16261,68 +16113,6 @@ snapshots:source-map: 0.6.1optional: true- dependencies:- buffer: 5.7.1- optional: true-- optional: true-- dependencies:- errno: 0.1.8- optional: true-- dependencies:- inherits: 2.0.4- readable-stream: 3.6.2- xtend: 4.0.2- optional: true-- dependencies:- abstract-leveldown: 6.2.3- buffer: 5.7.1- inherits: 2.0.4- ltgt: 2.2.1- optional: true-- dependencies:- encoding-down: 6.3.0- levelup: 4.4.0- optional: true-- dependencies:- xtend: 4.0.2- optional: true-- dependencies:- level-js: 5.0.2- level-packager: 5.1.1- leveldown: 5.6.0- optional: true-- dependencies:- abstract-leveldown: 6.2.3- napi-macros: 2.0.0- node-gyp-build: 4.1.1- optional: true-- dependencies:- deferred-leveldown: 5.3.0- level-errors: 2.0.1- level-iterator-stream: 4.0.2- level-supports: 1.0.1- xtend: 4.0.2- optional: true-dependencies:prelude-ls: 1.1.2@@ -16333,10 +16123,6 @@ snapshots:prelude-ls: 1.2.1type-check: 0.4.0- dependencies:- isomorphic.js: 0.2.5-@@ -16373,8 +16159,6 @@ snapshots:- [email protected]: {}-@@ -16393,6 +16177,14 @@ snapshots:dependencies:js-tokens: 4.0.0+ [email protected](@codemirror/[email protected])(@codemirror/[email protected])([email protected]):+ dependencies:+ '@codemirror/state': 6.5.2+ '@codemirror/view': 6.36.6+ loro-crdt: 1.5.4++ [email protected]: {}+@@ -16401,9 +16193,6 @@ snapshots:dependencies:yallist: 3.1.1- optional: true-dependencies:react: 18.3.1@@ -16836,9 +16625,6 @@ snapshots:- optional: true-@@ -16872,9 +16658,6 @@ snapshots:dependencies:whatwg-url: 5.0.0- optional: true-@@ -17989,13 +17772,6 @@ snapshots:string_decoder: 1.1.1util-deprecate: 1.0.2- dependencies:- inherits: 2.0.4- string_decoder: 1.1.1- util-deprecate: 1.0.2- optional: true-dependencies:picomatch: 2.3.1@@ -19122,6 +18898,8 @@ snapshots:is-typed-array: 1.1.13which-typed-array: 1.1.15+ [email protected]: {}+@@ -19504,6 +19282,20 @@ snapshots:- tsx- yaml+ [email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])):+ dependencies:+ '@rollup/plugin-virtual': 3.0.2+ '@swc/core': 1.11.21+ uuid: 10.0.0+ vite: 6.3.2(@types/[email protected])([email protected])([email protected])([email protected])([email protected])+ transitivePeerDependencies:+ - '@swc/helpers'+ - rollup++ [email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])):+ dependencies:+ vite: 6.3.2(@types/[email protected])([email protected])([email protected])([email protected])([email protected])+[email protected]([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:debug: 4.4.0@@ -19773,11 +19565,6 @@ snapshots:imurmurhash: 0.1.4signal-exit: 4.1.0- dependencies:- async-limiter: 1.0.1- optional: true-@@ -19790,38 +19577,6 @@ snapshots:- [email protected](@codemirror/[email protected])(@codemirror/[email protected])([email protected]):- dependencies:- '@codemirror/state': 6.5.2- '@codemirror/view': 6.36.6- lib0: 0.2.99- yjs: 13.6.26-- dependencies:- level: 6.0.1- lib0: 0.2.99- yjs: 13.6.26- optional: true-- dependencies:- lib0: 0.2.99- yjs: 13.6.26-- dependencies:- lib0: 0.2.99- lodash.debounce: 4.0.8- y-protocols: 1.0.6([email protected])- yjs: 13.6.26- optionalDependencies:- ws: 6.2.3- y-leveldb: 0.1.2([email protected])- transitivePeerDependencies:- - bufferutil- - utf-8-validate-@@ -19884,10 +19639,6 @@ snapshots:y18n: 3.2.2yargs-parser: 4.2.1- dependencies:- lib0: 0.2.99-diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex 4394c91648..2d83632923 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -34,10 +34,15 @@ import { useSplitCellCallback } from "../useSplitCell";import { invariant } from "@/utils/invariant";import { connectionAtom } from "@/core/network/connection";import { WebSocketState } from "@/core/websocket/types";-import { realTimeCollaboration } from "@/core/codemirror/rtc/extension";+import {+ connectedDocAtom,+ realTimeCollaboration,+} from "@/core/codemirror/rtc/extension";import { store } from "@/core/state/jotai";import { useDeleteCellCallback } from "../useDeleteCell";import { useSaveNotebook } from "@/core/saving/save-component";+import { DelayMount } from "@/components/utils/delay-mount";+import { Button } from "@/components/ui/button";export interface CellEditorPropsextends Pick<CellRuntimeState, "status">,@@ -234,9 +239,10 @@ const CellEditorInternal = ({saveOrNameNotebook,]);+ const rtcEnabled = getFeatureFlag("rtc_v2");const handleInitializeEditor = useEvent(() => {// If rtc is enabled, use collaborative editing- if (getFeatureFlag("rtc_v2")) {+ if (rtcEnabled) {const rtc = realTimeCollaboration(cellId,(code) => {@@ -259,13 +265,15 @@ const CellEditorInternal = ({});setEditorView(ev);// Initialize the language adapter- switchLanguage(ev, getInitialLanguageAdapter(ev.state).type);+ if (!rtcEnabled) {+ switchLanguage(ev, getInitialLanguageAdapter(ev.state).type);+ }});const handleReconfigureEditor = useEvent(() => {invariant(editorViewRef.current !== null, "Editor view is not initialized");// If rtc is enabled, use collaborative editing- if (getFeatureFlag("rtc_v2")) {+ if (rtcEnabled) {const rtc = realTimeCollaboration(cellId, (code) => {// It's not really a formatting change,// but this means it won't be marked as stale@@ -292,7 +300,7 @@ const CellEditorInternal = ({const handleDeserializeEditor = useEvent(() => {invariant(serializedEditorState, "Editor view is not initialized");- if (getFeatureFlag("rtc_v2")) {+ if (rtcEnabled) {const rtc = realTimeCollaboration(cellId,(code) => {@@ -303,6 +311,7 @@ const CellEditorInternal = ({code,);extensions.push(rtc.extension);+ code = rtc.code;}const ev = new EditorView({@@ -316,7 +325,9 @@ const CellEditorInternal = ({),});// Initialize the language adapter- switchLanguage(ev, getInitialLanguageAdapter(ev.state).type);+ if (!rtcEnabled) {+ switchLanguage(ev, getInitialLanguageAdapter(ev.state).type);+ }setEditorView(ev);// Clear the serialized state so that we don't re-create the editor next timecellActions.clearSerializedEditorState({ cellId });@@ -507,9 +518,27 @@ function WithWaitUntilConnected<T extends {}>() {const WaitUntilConnectedComponent = (props: T) => {const connection = useAtomValue(connectionAtom);+ const [rtcDoc, setRtcDoc] = useAtom(connectedDocAtom);- if (connection.state === WebSocketState.CONNECTING) {- return null;+ if (+ connection.state === WebSocketState.CONNECTING ||+ rtcDoc === undefined+ ) {+ return (+ <div className="flex h-full w-full items-baseline p-4">+ <DelayMount milliseconds={1000} fallback={null}>+ <span>Waiting for real-time collaboration connection...</span>+ <Button+ variant="link"+ onClick={() => {+ setRtcDoc("disabled");+ }}+ >+ Turn off real-time collaboration+ </Button>+ </DelayMount>+ </div>+ );}return <Component {...props} />;diff --git a/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts b/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.tsindex 01c7c5224a..9abdaaacc7 100644--- a/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts+++ b/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts@@ -28,7 +28,11 @@ export function useDelayVisibility(numCells: number, mode: AppMode) {focusCellByName(cellName);} else {// Otherwise focus on the first cell- focusFirstEditor();+ try {+ focusFirstEditor();+ } catch (error) {+ Logger.warn("Error focusing first editor", error);+ }}});}diff --git a/frontend/src/core/codemirror/rtc/__tests__/cell-manager.test.ts b/frontend/src/core/codemirror/rtc/__tests__/cell-manager.test.tsdeleted file mode 100644index 0352f55a6d..0000000000--- a/frontend/src/core/codemirror/rtc/__tests__/cell-manager.test.ts+++ /dev/null@@ -1,137 +0,0 @@-/* Copyright 2024 Marimo. All rights reserved. */-import {- describe,- it,- expect,- vi,- beforeEach,- afterEach,- type Mock,-} from "vitest";-import { CellProviderManager } from "../cell-manager";-import { WebsocketProvider } from "y-websocket";-import * as Y from "yjs";-import { store } from "@/core/state/jotai";-import { WebSocketState } from "@/core/websocket/types";-import { getSessionId } from "@/core/kernel/session";-import type { CellId } from "@/core/cells/ids";-import { connectionAtom } from "@/core/network/connection";--// Mock dependencies-vi.mock("y-websocket", () => ({- WebsocketProvider: vi.fn().mockImplementation(() => ({- on: vi.fn(),- destroy: vi.fn(),- })),-}));--vi.mock("@/core/kernel/session", () => ({- getSessionId: vi.fn(),-}));--const CELL_ID = "cell1" as CellId;--describe("CellProviderManager", () => {- let manager: CellProviderManager;- const mockProvider = {- doc: {- getText: vi.fn(),- },- on: vi.fn(),- destroy: vi.fn(),- };- const mockYText = {};-- beforeEach(() => {- vi.clearAllMocks();- manager = CellProviderManager.getInstance();- (WebsocketProvider as Mock).mockImplementation(() => mockProvider);- mockProvider.doc.getText.mockReturnValue(mockYText);- store.set(connectionAtom, { state: WebSocketState.OPEN });- vi.spyOn(store, "get");- (getSessionId as Mock).mockReturnValue("test-session");- });-- afterEach(() => {- manager.disconnectAll();- });-- it("should be a singleton", () => {- const instance1 = CellProviderManager.getInstance();- const instance2 = CellProviderManager.getInstance();- expect(instance1).toBe(instance2);- });-- it("should create new provider if none exists", async () => {- const { provider, ytext } = manager.getOrCreateProvider(- CELL_ID,- "initial code",- );-- expect(WebsocketProvider).toHaveBeenCalledWith(- "ws",- CELL_ID,- expect.any(Y.Doc),- {- params: {- session_id: "test-session",- },- resyncInterval: 5000,- },- );- expect(provider).toBe(mockProvider);- expect(ytext.toJSON()).toBe("");- });-- it("should return existing provider if one exists", async () => {- manager.getOrCreateProvider(CELL_ID, "initial code");- const { provider: provider2 } = manager.getOrCreateProvider(- CELL_ID,- "different code",- );-- expect(WebsocketProvider).toHaveBeenCalledTimes(1);- expect(provider2).toBe(mockProvider);- });-- it("should include file path in params if present", async () => {- const originalLocation = window.location;- // @ts-expect-error ehhh typescript- // biome-ignore lint/performance/noDelete: ehh- delete window.location;- window.location = {- ...originalLocation,- search: "?file=/path/to/file.py",- } as never;-- manager.getOrCreateProvider(CELL_ID, "initial code");-- expect(WebsocketProvider).toHaveBeenCalledWith(- "ws",- "cell1",- expect.any(Y.Doc),- {- params: {- session_id: "test-session",- file: "/path/to/file.py",- },- resyncInterval: 5000,- },- );- });-- it("should disconnect a specific provider", () => {- manager.getOrCreateProvider(CELL_ID, "code");- manager.disconnect(CELL_ID);-- expect(mockProvider.destroy).toHaveBeenCalled();- });-- it("should disconnect all providers", async () => {- manager.getOrCreateProvider(CELL_ID, "code");- manager.getOrCreateProvider("cell2" as CellId, "code");- manager.disconnectAll();-- expect(mockProvider.destroy).toHaveBeenCalledTimes(2);- });-});diff --git a/frontend/src/core/codemirror/rtc/cell-manager.ts b/frontend/src/core/codemirror/rtc/cell-manager.tsdeleted file mode 100644index 79fcc6ed45..0000000000--- a/frontend/src/core/codemirror/rtc/cell-manager.ts+++ /dev/null@@ -1,101 +0,0 @@-/* Copyright 2024 Marimo. All rights reserved. */-import { WebsocketProvider } from "y-websocket";-import * as Y from "yjs";-import type { CellId } from "@/core/cells/ids";-import { KnownQueryParams } from "@/core/constants";-import { getSessionId } from "@/core/kernel/session";-import { connectionAtom } from "@/core/network/connection";-import { WebSocketState } from "@/core/websocket/types";-import { store } from "@/core/state/jotai";-import { Logger } from "@/utils/Logger";--const DOC_KEY = "code";-const LANGUAGE_KEY = "language";--export class CellProviderManager {- private providers = new Map<CellId, WebsocketProvider>();- private static instance: CellProviderManager;-- private constructor() {- this.listenForConnectionChanges();- }-- static getInstance(): CellProviderManager {- if (!CellProviderManager.instance) {- CellProviderManager.instance = new CellProviderManager();- }- return CellProviderManager.instance;- }-- getOrCreateProvider(- cellId: CellId,- initialCode = "",- ): { provider: WebsocketProvider; ytext: Y.Text; ylanguage: Y.Text } {- const existingProvider = this.providers.get(cellId);- if (existingProvider) {- return {- provider: existingProvider,- ytext: existingProvider.doc.getText(DOC_KEY),- ylanguage: existingProvider.doc.getText(LANGUAGE_KEY),- };- }-- const ydoc = new Y.Doc();- const ytext = ydoc.getText(DOC_KEY);- const ylanguage = ydoc.getText(LANGUAGE_KEY);-- const params: Record<string, string> = {- session_id: getSessionId(),- };- const searchParams = new URLSearchParams(window.location.search);- const filePath = searchParams.get(KnownQueryParams.filePath);- if (filePath) {- params.file = filePath;- }-- const provider = new WebsocketProvider("ws", cellId, ydoc, {- params,- // This serves as a heartbeat to keep the connection alive- // otherwise, the connection will close and can lead to data loss- // or duplicate code from an awkward rsync.- resyncInterval: 5000,- });-- this.providers.set(cellId, provider);- provider.on("connection-close", () => {- Logger.warn("RTC: connection closed. This could lead to data loss.");- });- provider.on("connection-error", () => {- Logger.warn("RTC: connection error. This could lead to data loss.");- });-- return { provider, ytext, ylanguage };- }-- listenForConnectionChanges(): void {- const handleDisconnect = () => {- const value = store.get(connectionAtom);- const shouldDisconnect =- value.state === WebSocketState.CLOSED ||- value.state === WebSocketState.CLOSING;- if (shouldDisconnect) {- this.disconnectAll();- }- };- store.sub(connectionAtom, handleDisconnect);- }-- disconnect(cellId: CellId): void {- const provider = this.providers.get(cellId);- if (provider) {- provider.destroy();- this.providers.delete(cellId);- }- }-- disconnectAll(): void {- for (const [cellId] of this.providers) {- this.disconnect(cellId);- }- }-}diff --git a/frontend/src/core/codemirror/rtc/extension.ts b/frontend/src/core/codemirror/rtc/extension.tsindex 7048ff0e4c..86588d7a2d 100644--- a/frontend/src/core/codemirror/rtc/extension.ts+++ b/frontend/src/core/codemirror/rtc/extension.ts@@ -1,22 +1,121 @@/* Copyright 2024 Marimo. All rights reserved. */-import { yCollab } from "y-codemirror.next";++import { Awareness, LoroDoc, LoroText } from "loro-crdt";import type { CellId } from "@/core/cells/ids";import { isWasm } from "@/core/wasm/utils";import type { Extension } from "@codemirror/state";-import { CellProviderManager } from "./cell-manager";+import ReconnectingWebSocket from "partysocket/ws";+import { createWsUrl } from "@/core/websocket/createWsUrl";+import { getSessionId } from "@/core/kernel/session";+import { once } from "@/utils/once";+import { LoroSyncPlugin } from "./loro/sync";import { EditorView, ViewPlugin } from "@codemirror/view";import {+ getInitialLanguageAdapter,languageAdapterState,setLanguageAdapter,switchLanguage,} from "../language/extension";import { LanguageAdapters } from "../language/LanguageAdapters";import type { LanguageAdapterType } from "../language/types";+import { atom } from "jotai";+import { waitForConnectionOpen } from "@/core/network/connection";+import { store } from "@/core/state/jotai";+import { getFeatureFlag } from "@/core/config/feature-flag";+import { initialMode } from "@/core/mode";import { Logger } from "@/utils/Logger";+export const connectedDocAtom = atom<LoroDoc | "disabled" | undefined>(+ undefined,+);++// Create a Loro document+const doc = new LoroDoc();+const awareness: Awareness = new Awareness(doc.peerIdStr);+// const undoManager = new UndoManager(doc, {});++// Create a websocket connection to the server+const getWs = once(() => {+ Logger.debug("[rtc] creating websocket");++ const url = createWsUrl(getSessionId()).replace("/ws", "/ws_sync");++ // Create the websocket, but don't connect it yet+ const ws = new ReconnectingWebSocket(url, undefined, {+ // We don't want Infinity retries+ maxRetries: 10,+ debug: false,+ startClosed: true,+ connectionTimeout: 10_000,+ });++ // Start the connection+ Promise.resolve().then(async () => {+ // First wait the main /ws connection to be open+ // This is to ensure the LoroDoc is created on the server+ await waitForConnectionOpen();++ // Now open the websocket+ ws.reconnect();+ });++ // Receive updates from the server+ ws.addEventListener("message", async (event) => {+ const blob: Blob = event.data;+ const bytes = await blob.arrayBuffer();+ doc.import(new Uint8Array(bytes));+ Logger.debug("[rtc] imported doc change. new doc:", doc.toJSON());++ // Set the active doc only once the first message is received+ // This is to ensure the LoroDoc is created on the server, and not the client.+ if (store.get(connectedDocAtom) !== doc) {+ store.set(connectedDocAtom, doc);+ }+ });++ // Handle open event+ ws.addEventListener("open", () => {+ Logger.debug("[rtc] websocket open");+ });++ // Handle close event+ ws.addEventListener("close", (e) => {+ Logger.warn("[rtc] websocket close", e);++ // Remove the active doc+ if (store.get(connectedDocAtom) === doc) {+ store.set(connectedDocAtom, undefined);+ }+ });++ return ws;+});++// Kick off the connection for edit mode+if (getFeatureFlag("rtc_v2") && initialMode === "edit") {+ getWs();+}++// Send local updates to the server+doc.subscribeLocalUpdates((update) => {+ Logger.debug("[rtc] local update, sending to server");+ const ws = getWs();+ ws.send(update);+});++// Handle awareness changes+awareness.addListener((updates, origin) => {+ const changes = [...updates.added, ...updates.removed, ...updates.updated];+ if (origin === "local") {+ Logger.debug("[rtc] awareness changes", changes);+ const ws = getWs();+ ws.send(awareness.encode(changes));+ }+});+export function realTimeCollaboration(cellId: CellId,- updateCellCode: (code: string) => void,+ _updateCellCode: (code: string) => void,initialCode = "",): { extension: Extension; code: string } {if (isWasm()) {@@ -26,112 +125,107 @@ export function realTimeCollaboration(};}- const manager = CellProviderManager.getInstance();- const { ytext, ylanguage, provider } = manager.getOrCreateProvider(- cellId,- initialCode,- );-- // Code sync plugin- const codeSync = ViewPlugin.define((view) => {- const handleSync = (isSynced: boolean) => {- Logger.debug(`RTC sync=${isSynced}, ytext.length=${ytext.toJSON()}`);-- // If it's not synced, update the editor code- if (!isSynced) {- const code = ytext.toJSON();- view.dispatch({- changes: {- from: 0,- to: view.state.doc.length,- insert: code,- },- });- }+ const hasPath = doc.getByPath(`codes/${cellId}`) !== undefined;+ const loroText = doc+ .getMap("codes")+ .getOrCreateContainer(cellId, new LoroText());+ if (!hasPath) {+ Logger.warn("[rtc] initializing code for new cell", initialCode);+ loroText.insert(0, initialCode);+ }- // If it's synced, update the cell code- if (isSynced) {- updateCellCode(ytext.toJSON());-- // If the cell is new, insert the initial code- // Only do this once when we first connect and the document is empty- if (initialCode && ytext.length === 0) {- // Set a flag to prevent multiple insertions- const hasInserted = ytext.doc- ?.getMap("_metadata")- .get("initialCodeInserted");- if (!hasInserted) {- ytext.doc?.transact(() => {- ytext.delete(0, ytext.length);- ytext.insert(0, initialCode);- // Mark that we've inserted the initial code- ytext.doc?.getMap("_metadata").set("initialCodeInserted", true);- });- }- }- }- };+ return {+ code: initialCode.toString(),+ extension: [+ languageObserverExtension(cellId),+ languageListenerExtension(cellId),+ LoroSyncPlugin(doc, ["codes", cellId], () => {+ return loroText;+ }),+ ],+ };+}- // Wait for provider to connect before initializing with local code- provider.on("sync", handleSync);- return {- destroy() {- provider.off("sync", handleSync);- },- };- });+/**+ * Create a view plugin to observe language changes+ * When the language changes, we need to update our local language+ * Server -> Local+ * @param cellId - The cell id+ * @returns Extension+ */+function languageObserverExtension(cellId: CellId) {+ const updateLanguage = (view: EditorView) => {+ const language = doc.getByPath(`languages/${cellId}`) as+ | LoroText+ | undefined;+ if (!language) {+ return;+ }+ const currentLang = view.state.field(languageAdapterState).type;+ const newLang = language.toString() as LanguageAdapterType;- // Create a view plugin to observe language changes- const languageObserver = ViewPlugin.define((view) => {- const observer = () => {- const newLang = ylanguage.toJSON() as LanguageAdapterType;- const currentLang = view.state.field(languageAdapterState).type;- if (newLang !== currentLang) {- Logger.debug(- `[debug] Received language change: ${currentLang} -> ${newLang}`,- );- const adapter = LanguageAdapters[newLang]();- switchLanguage(view, adapter.type, { keepCodeAsIs: true });- }- };+ if (newLang !== currentLang) {+ Logger.debug(+ `[rtc] Received language change: ${currentLang} -> ${newLang}`,+ );+ const adapter = LanguageAdapters[newLang]();+ switchLanguage(view, adapter.type, { keepCodeAsIs: true });+ }+ };++ return ViewPlugin.define((view) => {+ // Initialize the language+ Promise.resolve().then(() => updateLanguage(view));++ const unsubscribeLanguage = doc.subscribe(() => {+ updateLanguage(view);+ });- ylanguage.observe(observer);return {destroy() {- ylanguage.unobserve(observer);+ unsubscribeLanguage();},};});+}++/**+ * Listen for local language changes+ * This is used to sync the language with the server+ * Local -> Server+ * @returns Extension+ */+function languageListenerExtension(cellId: CellId) {+ return EditorView.updateListener.of((update) => {+ const currentLang = doc+ .getMap("languages")+ .getOrCreateContainer(cellId, new LoroText());++ if (!currentLang.toString()) {+ // If the language is not set, set it to the current language+ const lang = getInitialLanguageAdapter(update.state).type;+ switchLanguage(update.view, lang);+ Logger.debug("[rtc] no language, setting default to", lang);+ currentLang.delete(0, currentLang.length);+ currentLang.insert(0, lang);+ doc.commit();+ return;+ }- // Listen for language changes- const languageListener = EditorView.updateListener.of((update) => {for (const tr of update.transactions) {for (const e of tr.effects) {- if (e.is(setLanguageAdapter)) {- const currentLang = ylanguage.toJSON();- if (currentLang !== e.value.type) {- Logger.debug(- `[debug] Setting language: ${currentLang} -> ${e.value.type}`,- );- ylanguage.doc?.transact(() => {- ylanguage.delete(0, ylanguage.length);- ylanguage.insert(0, e.value.type);- });- }+ if (+ e.is(setLanguageAdapter) &&+ currentLang.toString() !== e.value.type+ ) {+ Logger.debug(+ `[rtc] Setting language: ${currentLang} -> ${e.value.type}`,+ );+ currentLang.delete(0, currentLang.length);+ currentLang.insert(0, e.value.type);+ doc.commit();}}}});-- const extension = [- languageObserver,- languageListener,- codeSync,- yCollab(ytext, null),- ];-- return {- code: ytext.toJSON(),- extension,- };}diff --git a/frontend/src/core/codemirror/rtc/loro/sync.ts b/frontend/src/core/codemirror/rtc/loro/sync.tsnew file mode 100644index 0000000000..4895c66f3a--- /dev/null+++ b/frontend/src/core/codemirror/rtc/loro/sync.ts@@ -0,0 +1,159 @@+/* Copyright 2024 Marimo. All rights reserved. */++// Vendored from https://github.com/loro-dev/loro-codemirror/blob/main/src/index.ts+// and adapted to support:+// - custom `getTextFromDoc`+// - filter diffs by path++import type { Extension } from "@codemirror/state";+import { ViewPlugin } from "@codemirror/view";+import { Annotation, type ChangeSpec } from "@codemirror/state";+import type { EditorView, PluginValue, ViewUpdate } from "@codemirror/view";+import type {+ LoroDoc,+ LoroEventBatch,+ LoroText,+ Subscription,+} from "loro-crdt";+import { Logger } from "@/utils/Logger";++/**+ * It is used to sync the document with the remote users.+ *+ * @param doc - LoroDoc instance+ * @returns Extension+ */+export const LoroSyncPlugin = (+ doc: LoroDoc,+ docPath: string[],+ getTextFromDoc: (doc: LoroDoc) => LoroText,+): Extension => {+ return ViewPlugin.define(+ (view) => new LoroSyncPluginValue(view, doc, docPath, getTextFromDoc),+ );+};++export const loroSyncAnnotation = Annotation.define();++export class LoroSyncPluginValue implements PluginValue {+ sub?: Subscription;+ private isInitDispatch = false;++ constructor(+ private view: EditorView,+ private doc: LoroDoc,+ private docPath: string[],+ private getTextFromDoc: (doc: LoroDoc) => LoroText,+ ) {+ this.sub = doc.subscribe(this.onRemoteUpdate);+ Promise.resolve().then(() => {+ this.isInitDispatch = true;+ const currentText = this.view.state.doc.toString();+ const text = this.getTextFromDoc(this.doc);++ if (currentText === text.toString()) {+ return;+ }+ Logger.debug("[rtc] initializing text", text.toString());+ view.dispatch({+ changes: [+ {+ from: 0,+ to: this.view.state.doc.length,+ insert: text.toString(),+ },+ ],+ });+ });+ }++ onRemoteUpdate = (e: LoroEventBatch) => {+ if (e.by === "local") {+ return;+ }+ if (e.by === "checkout") {+ // TODO: better handle checkout+ this.view.dispatch({+ changes: [+ {+ from: 0,+ to: this.view.state.doc.length,+ insert: this.getTextFromDoc(this.doc).toString(),+ },+ ],+ annotations: [loroSyncAnnotation.of(this)],+ });+ return;+ }+ if (e.by === "import") {+ const changes: ChangeSpec[] = [];+ let pos = 0;+ for (const { diff, path } of e.events) {+ if (path.join("/") !== this.docPath.join("/")) {+ continue;+ }+ if (diff.type !== "text") {+ continue;+ }+ const textDiff = diff.diff;+ for (const delta of textDiff) {+ if (delta.insert) {+ changes.push({+ from: pos,+ to: pos,+ insert: delta.insert,+ });+ } else if (delta.delete) {+ changes.push({+ from: pos,+ to: pos + delta.delete,+ });+ pos += delta.delete;+ } else if (delta.retain != null) {+ pos += delta.retain;+ }+ }+ if (changes.length > 0) {+ Logger.debug("[rtc] Received text changes", changes);+ this.view.dispatch({+ changes,+ annotations: [loroSyncAnnotation.of(this)],+ });+ }+ }+ }+ };++ update(update: ViewUpdate): void {+ if (this.isInitDispatch) {+ this.isInitDispatch = false;+ return;+ }++ if (+ !update.docChanged ||+ (update.transactions.length > 0 &&+ (update.transactions[0].annotation(loroSyncAnnotation) === this ||+ update.transactions[0].annotation(loroSyncAnnotation) === "undo"))+ ) {+ return;+ }+ let adj = 0;+ update.changes.iterChanges((fromA, toA, fromB, toB, insert) => {+ const insertText = insert.sliceString(0, insert.length, "\n");+ if (fromA !== toA) {+ this.getTextFromDoc(this.doc).delete(fromA + adj, toA - fromA);+ }+ if (insertText.length > 0) {+ this.getTextFromDoc(this.doc).insert(fromA + adj, insertText);+ }+ adj += insertText.length - (toA - fromA);+ });+ this.doc.commit();+ }++ destroy(): void {+ this.sub?.();+ this.sub = undefined;+ }+}diff --git a/frontend/vite.config.mts b/frontend/vite.config.mtsindex 369a3a84c9..008cfcef6a 100644--- a/frontend/vite.config.mts+++ b/frontend/vite.config.mts@@ -1,5 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. */import { defineConfig, type Plugin } from "vite";+import wasm from "vite-plugin-wasm";+import topLevelAwait from "vite-plugin-top-level-await";import react from "@vitejs/plugin-react";import tsconfigPaths from "vite-tsconfig-paths";import { codecovVitePlugin } from "@codecov/vite-plugin";@@ -213,6 +215,14 @@ export default defineConfig({origin: TARGET,},},+ "/ws_sync": {+ target: `ws://${HOST}:${SERVER_PORT}`,+ ws: true,+ changeOrigin: true,+ headers: {+ origin: TARGET,+ },+ },"/lsp": {target: `ws://${HOST}:${SERVER_PORT}`,ws: true,@@ -278,5 +288,7 @@ export default defineConfig({bundleName: "marimo",uploadToken: process.env.CODECOV_TOKEN,}),+ wasm(),+ topLevelAwait(),],});diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.pyindex b9e50b512e..a891d4940f 100644--- a/marimo/_dependencies/dependencies.py+++ b/marimo/_dependencies/dependencies.py@@ -203,6 +203,7 @@ class DependencyManager:"docstring_to_markdown", min_version="0.17.0")tomlkit = Dependency("tomlkit")+ loro = Dependency("loro")# Version requirements to properly support the new superfences introduced in# pymdown#2470diff --git a/marimo/_server/api/endpoints/ws.py b/marimo/_server/api/endpoints/ws.pyindex 8071881bb5..02d126eb16 100644--- a/marimo/_server/api/endpoints/ws.py+++ b/marimo/_server/api/endpoints/ws.py@@ -3,9 +3,7 @@ from __future__ import annotationsimport asyncioimport json-from dataclasses import dataclassfrom enum import IntEnum-from functools import partialfrom typing import TYPE_CHECKING, Any, Callable, Optionalfrom starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState@@ -14,6 +12,7 @@ from marimo import _loggersfrom marimo._ast.cell import CellConfigfrom marimo._cli.upgrade import check_for_updatesfrom marimo._config.settings import GLOBAL_SETTINGS+from marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.ops import (Alert,Banner,@@ -37,11 +36,12 @@ from marimo._server.model import (SessionMode,)from marimo._server.router import APIRouter+from marimo._server.rtc.doc import LoroDocManagerfrom marimo._server.sessions import Session, SessionManagerfrom marimo._types.ids import CellId_t, ConsumerId, SessionIdif TYPE_CHECKING:- from pycrdt import Doc, Text, TransactionEvent+ from loro import DiffEventLOGGER = _loggers.marimo_logger()@@ -58,6 +58,9 @@ class WebSocketCodes(IntEnum):FORBIDDEN = 1008+DOC_MANAGER = LoroDocManager()++@router.websocket("/ws")async def websocket_endpoint(websocket: WebSocket,@@ -107,94 +110,22 @@ async def websocket_endpoint().start()-@dataclass-class YCell:- ydoc: Doc[Text]- code_text: Text- language_text: Text- clients: int- cleaner: asyncio.Task[None] | None = None---# TODO: we should use a more robust key type than the filename-# since renaming the file will break RTC.-@dataclass-class CellIdAndFileKey:- cell_id: str- file_key: MarimoFileKey-- def __hash__(self) -> int:- return hash((self.cell_id, self.file_key))---ycells: dict[CellIdAndFileKey, YCell] = {}-ycell_lock = asyncio.Lock()---def put_updates(- update_queue: asyncio.Queue[bytes], event: TransactionEvent-) -> None:- update = event.update- update_queue.put_nowait(update)---async def send_updates(+# WebSocket endpoint for LoroDoc synchronization[email protected]("/ws_sync")+async def ws_sync(websocket: WebSocket,- update_queue: asyncio.Queue[bytes],- cell_id: str,) -> None:- from pycrdt import create_update_message-- try:- while True:- update = await update_queue.get()- message = create_update_message(update)- await websocket.send_bytes(message)- except Exception as e:- LOGGER.warning(- f"RTC: Could not send Y update to client for cell with ID {cell_id}: {str(e)}",- )---async def clean_cell(- cell_id_and_file_key: CellIdAndFileKey, timeout: float = 60-) -> None:- try:- await asyncio.sleep(timeout)- async with ycell_lock:- if cell_id_and_file_key in ycells:- ycell = ycells[cell_id_and_file_key]- # Double-check client count before removing- if not ycell.clients:- LOGGER.debug(- f"RTC: Removing cell {cell_id_and_file_key.cell_id} as it has no clients"- )- # Store the YDoc state before removing it- # This could be used to restore state for quick reconnects if needed- del ycells[cell_id_and_file_key]- else:- LOGGER.warning(- f"RTC: Cell {cell_id_and_file_key.cell_id} not found in ycells dict during cleanup"- )- except asyncio.CancelledError:- # Task was cancelled due to client reconnection- LOGGER.debug(- f"RTC: clean_cell task cancelled for cell {cell_id_and_file_key.cell_id} - likely due to reconnection"+ """+ Websocket endpoint for LoroDoc synchronization+ """+ if not DependencyManager.loro.has():+ LOGGER.warning("RTC: Loro is not installed, closing websocket")+ await websocket.close(+ WebSocketCodes.NORMAL_CLOSE, "MARIMO_LORO_NOT_INSTALLED")- pass-+ return[email protected]("/ws/{cell_id}")-async def ycell_provider(- websocket: WebSocket,-) -> None:- from pycrdt import (- Doc,- Text,- YMessageType,- create_sync_message,- handle_sync_message,- )+ from loro import ExportModeapp_state = AppState(websocket)file_key: Optional[MarimoFileKey] = (@@ -217,70 +148,64 @@ async def ycell_provider()await websocket.close(WebSocketCodes.FORBIDDEN, "MARIMO_NOT_ALLOWED")return+await websocket.accept()- cell_id = CellId_t(websocket.path_params["cell_id"])- key = CellIdAndFileKey(cell_id, file_key)- async with ycell_lock:- if key in ycells:- ycell = ycells[key]- ydoc = ycell.ydoc- ycell.clients += 1- if ycell.cleaner is not None:- LOGGER.debug(- f"RTC: Cancelling existing cleaner for cell {cell_id}"- )- ycell.cleaner.cancel()- ycell.cleaner = None- else:- code = ""- LOGGER.debug(- f"RTC: Creating new ydoc for new cell {cell_id} with empty code"- )- ydoc = Doc[Text]()- ytext = ydoc.get("code", type=Text)- ylang = ydoc.get("language", type=Text)- ytext += code- ycell = YCell(- ydoc=ydoc, code_text=ytext, language_text=ylang, clients=1++ # Get or create the LoroDoc and add the client to it+ update_queue = asyncio.Queue[bytes]()+ doc = await DOC_MANAGER.get_or_create_doc(file_key)+ DOC_MANAGER.add_client_to_doc(file_key, update_queue)++ # Send initial sync+ # Use shallow snapshot for fewer bytes+ init_sync_msg = doc.export(+ ExportMode.ShallowSnapshot(frontiers=doc.state_frontiers)+ )+ await websocket.send_bytes(init_sync_msg)++ def handle_doc_update(event: DiffEvent) -> None:+ LOGGER.debug("RTC: doc updated", event)++ # Create an async task to send updates to the client+ async def send_updates() -> None:+ try:+ while True:+ update = await update_queue.get()+ await websocket.send_bytes(update)+ except Exception as e:+ LOGGER.warning(+ f"RTC: Could not send loro update to client for file {file_key}: {str(e)}",)- ycells[key] = ycell- update_queue: asyncio.Queue[bytes] = asyncio.Queue()- task = asyncio.create_task(send_updates(websocket, update_queue, cell_id))- subscription = ydoc.observe(partial(put_updates, update_queue))- sync_message = create_sync_message(ydoc)++ # Subscribe to LoroDoc updates+ subscription = doc.subscribe_root(handle_doc_update)+ send_task = asyncio.create_task(send_updates())+try:- await websocket.send_bytes(sync_message)+ # Listen for updates from the clientwhile True:message = await websocket.receive_bytes()- message_type = message[0]- if message_type == YMessageType.SYNC:- reply = handle_sync_message(message[1:], ydoc)- if reply is not None:- await websocket.send_bytes(reply)+ await DOC_MANAGER.broadcast_update(file_key, message, update_queue)+ # Check if the message is an awareness update+ if message.startswith(b"awareness:"):+ LOGGER.debug("RTC: received awareness update")+ else:+ # Apply the update to the LoroDoc+ doc.import_(message)except WebSocketDisconnect:+ LOGGER.warning("RTC: WebSocket disconnected")# Normal disconnectionpassexcept Exception as e:LOGGER.warning(- f"RTC: Exception in websocket loop for cell {cell_id}: {str(e)}"+ f"RTC: Exception in websocket loop for file {file_key}: {str(e)}")- passfinally:- # Cleanup cell resources- # Start the cleanup task timer- task.cancel()- ydoc.unobserve(subscription)- async with ycell_lock:- ycell.clients -= 1- if not ycell.clients:- if ycell.cleaner is not None:- LOGGER.warning(- f"RTC: Cancelling existing cleaner for cell {cell_id}"- )- ycell.cleaner.cancel()- ycell.cleaner = None- # Timeout of 60 seconds to allow for client reconnection- ycell.cleaner = asyncio.create_task(clean_cell(key, 60.0))+ LOGGER.warning("RTC: Cleaning up resources")+ # Cleanup resources+ send_task.cancel()+ subscription.unsubscribe()+ await DOC_MANAGER.remove_client(file_key, update_queue)KIOSK_ONLY_OPERATIONS = {@@ -363,6 +288,23 @@ class WebsocketHandler(SessionConsumer):)))++ # If RTC is enabled, initialize the LoroDoc with cell code+ if self.rtc_enabled and self.mode == SessionMode.EDIT:+ if not DependencyManager.loro.has():+ LOGGER.warning(+ "RTC: Loro is not installed, disabling real-time collaboration"+ )+ self.rtc_enabled = False+ return++ async def init_loro_doc() -> None:+ await DOC_MANAGER.create_doc(+ self.file_key, cell_ids, codes+ )++ asyncio.create_task(init_loro_doc())+else:codes, names, configs, cell_ids = tuple(zip(diff --git a/marimo/_server/rtc/doc.py b/marimo/_server/rtc/doc.pynew file mode 100644index 0000000000..2efe15377e--- /dev/null+++ b/marimo/_server/rtc/doc.py@@ -0,0 +1,150 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import asyncio+from typing import TYPE_CHECKING, Optional++from marimo import _loggers+from marimo._server.file_router import MarimoFileKey+from marimo._types.ids import CellId_t++if TYPE_CHECKING:+ from loro import LoroDoc++LOGGER = _loggers.marimo_logger()+++class LoroDocManager:+ def __init__(self) -> None:+ self.loro_docs: dict[MarimoFileKey, LoroDoc] = {}+ self.loro_docs_lock = asyncio.Lock()+ self.loro_docs_clients: dict[+ MarimoFileKey, set[asyncio.Queue[bytes]]+ ] = {}+ self.loro_docs_cleaners: dict[+ MarimoFileKey, Optional[asyncio.Task[None]]+ ] = {}++ async def _clean_loro_doc(+ self, file_key: MarimoFileKey, timeout: float = 60+ ) -> None:+ """Clean up a loro doc if no clients are connected."""+ try:+ await asyncio.sleep(timeout)+ async with self.loro_docs_lock:+ if (+ file_key in self.loro_docs_clients+ and len(self.loro_docs_clients[file_key]) == 0+ ):+ LOGGER.debug(+ f"RTC: Removing loro doc for file {file_key} as it has no clients"+ )+ # Clean up the document+ if file_key in self.loro_docs:+ del self.loro_docs[file_key]+ if file_key in self.loro_docs_clients:+ del self.loro_docs_clients[file_key]+ if file_key in self.loro_docs_cleaners:+ del self.loro_docs_cleaners[file_key]+ except asyncio.CancelledError:+ # Task was cancelled due to client reconnection+ LOGGER.debug(+ f"RTC: clean_loro_doc task cancelled for file {file_key} - likely due to reconnection"+ )+ pass++ async def create_doc(+ self,+ file_key: MarimoFileKey,+ cell_ids: tuple[CellId_t, ...],+ codes: tuple[str, ...],+ ) -> LoroDoc:+ """Create a new loro doc."""+ from loro import LoroDoc, LoroText++ assert len(cell_ids) == len(codes), (+ "cell_ids and codes must be the same length"+ )++ async with self.loro_docs_lock:+ if file_key in self.loro_docs:+ return self.loro_docs[file_key]++ LOGGER.debug(f"RTC: Initializing LoroDoc for file {file_key}")+ doc = LoroDoc() # type: ignore[no-untyped-call]+ self.loro_docs[file_key] = doc++ # Add all cell code to the doc+ doc_codes = doc.get_map("codes")+ doc.get_map("languages")+ for cell_id, code in zip(cell_ids, codes):+ cell_text = LoroText() # type: ignore[no-untyped-call]+ cell_text.insert(0, code)+ doc_codes.insert_container(cell_id, cell_text)++ # We don't set the language here because it will be set+ # when the client connects for the first time.+ return doc++ async def get_or_create_doc(self, file_key: MarimoFileKey) -> LoroDoc:+ """Get or create a loro doc for a file key."""+ from loro import LoroDoc++ async with self.loro_docs_lock:+ if file_key in self.loro_docs:+ doc = self.loro_docs[file_key]+ # Cancel existing cleaner task if it exists+ cleaner = self.loro_docs_cleaners.get(file_key, None)+ if cleaner is not None:+ LOGGER.debug(+ f"RTC: Cancelling existing cleaner for file {file_key}"+ )+ cleaner.cancel()+ self.loro_docs_cleaners[file_key] = None+ else:+ LOGGER.warning(f"RTC: Expected loro doc for file {file_key}")+ doc = LoroDoc() # type: ignore[no-untyped-call]+ self.loro_docs[file_key] = doc+ return doc++ def add_client_to_doc(+ self, file_key: MarimoFileKey, update_queue: asyncio.Queue[bytes]+ ) -> None:+ """Add a client queue to the loro doc clients."""+ if file_key not in self.loro_docs_clients:+ self.loro_docs_clients[file_key] = {update_queue}+ else:+ self.loro_docs_clients[file_key].add(update_queue)++ async def broadcast_update(+ self,+ file_key: MarimoFileKey,+ message: bytes,+ exclude_queue: Optional[asyncio.Queue[bytes]] = None,+ ) -> None:+ """Broadcast an update to all clients except the excluded queue."""+ clients = self.loro_docs_clients[file_key]+ for client in clients:+ if client == exclude_queue:+ continue+ client.put_nowait(message)++ async def remove_client(+ self,+ file_key: MarimoFileKey,+ update_queue: asyncio.Queue[bytes],+ ) -> None:+ """Clean up a loro client and potentially the doc if no clients remain."""+ async with self.loro_docs_lock:+ self.loro_docs_clients[file_key].remove(update_queue)+ # If no clients are connected, set up a cleaner task+ if len(self.loro_docs_clients[file_key]) == 0:+ # Remove any existing cleaner+ cleaner = self.loro_docs_cleaners.get(file_key, None)+ if cleaner is not None:+ cleaner.cancel()+ self.loro_docs_cleaners[file_key] = None+ # Create a new cleaner with timeout of 60 seconds+ self.loro_docs_cleaners[file_key] = asyncio.create_task(+ self._clean_loro_doc(file_key, 60.0)+ )diff --git a/marimo/_utils/health.py b/marimo/_utils/health.pyindex d4fc20271a..9b6b3da718 100644--- a/marimo/_utils/health.py+++ b/marimo/_utils/health.py@@ -65,7 +65,7 @@ def get_optional_modules_list() -> dict[str, str]:"pandas","polars","pyarrow",- "pycrdt",+ "loro","pylsp-mypy","pytest","python-lsp-ruff",diff --git a/pyproject.toml b/pyproject.tomlindex 84c7a8584f..b93242814d 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -34,8 +34,8 @@ dependencies = ["starlette>=0.26.1,!=0.36.0",# websockets for use with starlette, and for lsp"websockets >= 10.0.0",- # pycrdt for collaborative editing- "pycrdt >=0.11.0,<0.12.0",+ # loro for collaborative editing+ "loro>=1.5.0",# python <=3.10 compatibility"typing_extensions>=4.4.0; python_version < '3.11'",# for rst parsing; lowerbound determined by awscli requiring < 0.17,@@ -191,6 +191,7 @@ dependencies = ["matplotlib>=3.8.0","sqlglot>=23.4","sqlalchemy>=2.0.40",+ "loro>=1.5.0","pandas-stubs>=1.5.3.230321","pyiceberg>=0.9.0","types-Pillow~=10.2.0.20240520",@@ -512,7 +513,6 @@ format_on_save = true[tool.marimo.experimental]multi_column = true-chat_sidebar = true[tool.marimo.display]dataframes = "rich"diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.pyindex fcf06ea862..5eb84a7e44 100644--- a/tests/_server/api/endpoints/test_ws.py+++ b/tests/_server/api/endpoints/test_ws.py@@ -1,24 +1,18 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-import asynciofrom contextlib import contextmanagerfrom dataclasses import asdictfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Optionalimport pytest-from pycrdt import (- YMessageType,-)from starlette.websockets import WebSocketDisconnectfrom marimo._config.manager import UserConfigManagerfrom marimo._messaging.ops import KernelCapabilities, KernelReadyfrom marimo._server.api.endpoints.ws import (- CellIdAndFileKey,WebSocketCodes,- clean_cell,)from marimo._server.model import SessionModefrom marimo._server.sessions import SessionManager@@ -367,224 +361,3 @@ def rtc_enabled(config: UserConfigManager):yieldfinally:config.save_config(prev_config)---async def test_ycell_sync(client: TestClient) -> None:- """Test that Y-CRDT sync works between multiple clients"""- ws_1 = "/ws?session_id=123"- ws_2 = "/ws?session_id=456"-- cell_id = "Hbol"-- ws_1_cell_1 = f"/ws/{cell_id}?session_id=123"- ws_2_cell_1 = f"/ws/{cell_id}?session_id=456"-- # First connect main websocket to create session- with (- rtc_enabled(get_user_config_manager(client)),- client.websocket_connect(ws_1) as websocket,- client.websocket_connect(ws_2) as websocket2,- ):- data = websocket.receive_json()- assert_parse_ready_response(data)- data2 = websocket2.receive_json()- assert_parse_ready_response(data2)-- # Connect first client to cell websocket- with client.websocket_connect(ws_1_cell_1) as cell_ws1:- # Should receive initial sync message- sync_msg1 = cell_ws1.receive_bytes()- assert sync_msg1[0] == YMessageType.SYNC-- # Connect second client- with client.websocket_connect(ws_2_cell_1) as cell_ws2:- # Should receive initial sync- sync_msg2 = cell_ws2.receive_bytes()- assert sync_msg2[0] == YMessageType.SYNC-- # Send update from client 1- update_msg = bytes([YMessageType.AWARENESS]) + b"test update"- cell_ws1.send_bytes(update_msg)-- # Client 2 should receive the update- # TODO: This hangs- # received = cell_ws2.receive_bytes()- # assert received[0] == YMessageType.AWARENESS- # assert received[1:] == b"test update"-- client.post("/api/kernel/shutdown", headers=HEADERS)---async def test_ycell_cleanup_on_session_close(- client: TestClient,-) -> None:- """Test that cell websockets are cleaned up when session closes"""- with (- rtc_enabled(get_user_config_manager(client)),- client.websocket_connect("/ws?session_id=123") as websocket,- ):- data = websocket.receive_json()- assert_kernel_ready_response(data)-- cell_id = "Hbol"- # Connect to cell websocket- with client.websocket_connect(- f"/ws/{cell_id}?session_id=123"- ) as cell_ws:- sync_msg = cell_ws.receive_bytes()- assert sync_msg[0] == YMessageType.SYNC-- # Close main websocket- websocket.close()-- # Cell websocket should close automatically- # TODO: This hangs- # with pytest.raises(WebSocketDisconnect):- # while True:- # cell_ws.receive_bytes()-- client.post("/api/kernel/shutdown", headers=HEADERS)---async def test_ycell_persistence(client: TestClient) -> None:- """Test that cell content persists between connections"""- cell_id = "Hbol"- initial_code = "print('hello')"-- # First connection sets initial code- with (- rtc_enabled(get_user_config_manager(client)),- client.websocket_connect("/ws?session_id=123") as websocket,- ):- data = websocket.receive_json()- assert_kernel_ready_response(data)-- with client.websocket_connect(- f"/ws/{cell_id}?session_id=123"- ) as cell_ws1:- sync_msg = cell_ws1.receive_bytes()- assert sync_msg[0] == YMessageType.SYNC-- # Send initial code- update_msg = (- bytes([YMessageType.AWARENESS]) + initial_code.encode()- )- cell_ws1.send_bytes(update_msg)-- # Second connection should receive persisted code- with (- rtc_enabled(get_user_config_manager(client)),- client.websocket_connect("/ws?session_id=456") as websocket,- ):- data = websocket.receive_json()- assert_kernel_ready_response(data, create_response({"resumed": True}))-- with client.websocket_connect(- f"/ws/{cell_id}?session_id=456"- ) as cell_ws2:- sync_msg = cell_ws2.receive_bytes()- # Verify initial code is preserved- assert sync_msg[0] == YMessageType.SYNC- # Sync message contains binary yjs data, not raw code- assert len(sync_msg[1:]) > 0-- client.post("/api/kernel/shutdown", headers=HEADERS)---async def test_ycell_cleanup_after_close(- client: TestClient, temp_marimo_file: str-) -> None:- """Test that cell data is cleaned up after all clients disconnect"""- from marimo._server.api.endpoints.ws import ycells-- cell_id = "Hbol"-- with client.websocket_connect(- f"/ws?session_id=123&file={temp_marimo_file}"- ) as websocket:- data = websocket.receive_json()- assert_parse_ready_response(data)-- with client.websocket_connect(- f"/ws/{cell_id}?session_id=123&file={temp_marimo_file}"- ) as cell_ws:- key = CellIdAndFileKey(cell_id, temp_marimo_file)- sync_msg = cell_ws.receive_bytes()- assert sync_msg[0] == YMessageType.SYNC- assert key in ycells-- # Close websocket- cell_ws.close()-- # Cell should still exist- assert key in ycells-- # Wait for cleanup- await clean_cell(key, timeout=0.01)-- # Cell should be removed- assert key not in ycells-- client.post("/api/kernel/shutdown", headers=HEADERS)---async def test_ycell_multiple_clients(- client: TestClient, temp_marimo_file: str-) -> None:- """Test multiple clients can connect to same cell"""- cell_id = "Hbol"-- with client.websocket_connect(- f"/ws?session_id=123&file={temp_marimo_file}"- ) as websocket:- data = websocket.receive_json()- assert_parse_ready_response(data)-- # Connect first client- with client.websocket_connect(- f"/ws/{cell_id}?session_id=123&file={temp_marimo_file}"- ) as cell_ws1:- sync_msg1 = cell_ws1.receive_bytes()- assert sync_msg1[0] == YMessageType.SYNC-- # Connect second client- with client.websocket_connect(- f"/ws/{cell_id}?session_id=123&file={temp_marimo_file}"- ) as cell_ws2:- sync_msg2 = cell_ws2.receive_bytes()- assert sync_msg2[0] == YMessageType.SYNC-- # Both should receive updates- update_msg = bytes([1]) + b"test"- cell_ws1.send_bytes(update_msg)-- # TODO: This hangs- # received = cell_ws2.receive_bytes()- # assert received[0] == YMessageType.AWARENESS- # assert received[1:] == b"test"-- # Verify client count- from marimo._server.api.endpoints.ws import ycells-- key = CellIdAndFileKey(cell_id, temp_marimo_file)-- assert ycells[key].clients == 2-- # Close one client- cell_ws2.close()- await asyncio.sleep(0.1)- assert ycells[key].clients == 1-- client.post("/api/kernel/shutdown", headers=HEADERS)---async def test_ycell_invalid_session(client: TestClient) -> None:- """Test connecting to cell with invalid session is rejected"""- cell_id = "Hbol"-- with pytest.raises(WebSocketDisconnect) as exc_info:- with client.websocket_connect(f"/ws/{cell_id}?session_id=invalid"):- pass-- assert exc_info.value.code == WebSocketCodes.FORBIDDEN- assert exc_info.value.reason == "MARIMO_NOT_ALLOWED"diff --git a/tests/_server/api/endpoints/test_ws_rtc.py b/tests/_server/api/endpoints/test_ws_rtc.pyindex 047dea19ca..1d99fd3e8d 100644--- a/tests/_server/api/endpoints/test_ws_rtc.py+++ b/tests/_server/api/endpoints/test_ws_rtc.py@@ -1,56 +1,121 @@from __future__ import annotationsimport asyncio-from typing import TYPE_CHECKING+from contextlib import contextmanager+from dataclasses import asdict+from typing import TYPE_CHECKING, Any, Optional, castimport pytest-from pycrdt import Doc, Text--from marimo._server.api.endpoints.ws import (- CellIdAndFileKey,- YCell,- clean_cell,- ycells,-)+from loro import LoroDoc, LoroText++from marimo._config.manager import UserConfigManager+from marimo._messaging.ops import KernelCapabilities, KernelReady+from marimo._server.api.endpoints.ws import DOC_MANAGERfrom marimo._server.file_router import MarimoFileKeyfrom marimo._types.ids import CellId_t+from marimo._utils.parse_dataclass import parse_raw+from tests._server.conftest import get_session_manager, get_user_config_manager+from tests._server.mocks import token_headerif TYPE_CHECKING:from collections.abc import AsyncGenerator+ from starlette.testclient import TestClient+++def create_response(+ partial_response: dict[str, Any],+) -> dict[str, Any]:+ response: dict[str, Any] = {+ "cell_ids": ["Hbol"],+ "codes": ["import marimo as mo"],+ "names": ["__"],+ "layout": None,+ "resumed": False,+ "ui_values": {},+ "last_executed_code": {},+ "last_execution_time": {},+ "kiosk": False,+ "configs": [{"disabled": False, "hide_code": False}],+ "app_config": {"width": "full"},+ "capabilities": asdict(KernelCapabilities()),+ }+ response.update(partial_response)+ return response+++def headers(session_id: str) -> dict[str, str]:+ return {+ "Marimo-Session-Id": session_id,+ **token_header("fake-token"),+ }+++HEADERS = {+ **token_header("fake-token"),+}+++def assert_kernel_ready_response(+ raw_data: dict[str, Any], response: Optional[dict[str, Any]] = None+) -> None:+ if response is None:+ response = create_response({})+ data = parse_raw(raw_data["data"], KernelReady)+ expected = parse_raw(response, KernelReady)+ assert data.cell_ids == expected.cell_ids+ assert data.codes == expected.codes+ assert data.names == expected.names+ assert data.layout == expected.layout+ assert data.resumed == expected.resumed+ assert data.ui_values == expected.ui_values+ assert data.configs == expected.configs+ assert data.app_config == expected.app_config+ assert data.kiosk == expected.kiosk+ assert data.capabilities == expected.capabilities+++def assert_parse_ready_response(raw_data: dict[str, Any]) -> None:+ data = parse_raw(raw_data["data"], KernelReady)+ assert data is not None+@pytest.fixture # type: ignore-async def setup_ycell() -> AsyncGenerator[None, None]:- """Setup and teardown for ycell tests"""- # Clear any existing ycells- ycells.clear()+async def setup_loro_docs() -> AsyncGenerator[None, None]:+ """Setup and teardown for loro_docs tests"""+ # Clear any existing loro docs+ DOC_MANAGER.loro_docs.clear()+ DOC_MANAGER.loro_docs_clients.clear()+ DOC_MANAGER.loro_docs_cleaners.clear()yield# Cleanup after test- ycells.clear()+ DOC_MANAGER.loro_docs.clear()+ DOC_MANAGER.loro_docs_clients.clear()+ DOC_MANAGER.loro_docs_cleaners.clear()-async def test_quick_reconnection(setup_ycell: None) -> None:+async def test_quick_reconnection(setup_loro_docs: None) -> None:"""Test that quick reconnection properly handles cleanup task cancellation"""- del setup_ycell+ del setup_loro_docs# Setup- cell_id = CellId_t("test_cell")file_key = MarimoFileKey("test_file")- key = CellIdAndFileKey(cell_id, file_key)- # Create initial ycell- ydoc = Doc[Text]()- ycode = ydoc.get("code", type=Text)- ylang = ydoc.get("language", type=Text)- ycell = YCell(ydoc=ydoc, code_text=ycode, language_text=ylang, clients=1)- ycells[key] = ycell+ # Create initial loro_doc+ doc = LoroDoc()+ DOC_MANAGER.loro_docs[file_key] = doc++ # Setup client queue+ update_queue = asyncio.Queue[bytes]()+ DOC_MANAGER.loro_docs_clients[file_key] = {update_queue}# Start cleanup task- cleanup_task = asyncio.create_task(clean_cell(key))+ cleanup_task = asyncio.create_task(DOC_MANAGER._clean_loro_doc(file_key))# Simulate quick reconnection by creating a new client before cleanup finishes- ycells[key].clients += 1+ new_queue = asyncio.Queue[bytes]()+ DOC_MANAGER.loro_docs_clients[file_key].add(new_queue)- # Cancel cleanup task (simulating what happens in ycell_provider)+ # Cancel cleanup taskcleanup_task.cancel()try:await cleanup_task@@ -58,48 +123,195 @@ async def test_quick_reconnection(setup_ycell: None) -> None:pass# Verify state- assert len(ycells) == 1- assert ycells[key].clients == 2 # Original client + reconnected client+ assert len(DOC_MANAGER.loro_docs) == 1+ assert (+ len(DOC_MANAGER.loro_docs_clients[file_key]) == 2+ ) # Original client + reconnected client-async def test_two_users_sync(setup_ycell: None) -> None:+async def test_two_users_sync(setup_loro_docs: None) -> None:"""Test that two users can connect and sync text properly without duplicates"""- del setup_ycell- cell_id = CellId_t("test_cell")+ del setup_loro_docsfile_key = MarimoFileKey("test_file")- key = CellIdAndFileKey(cell_id, file_key)+ cell_id = str(CellId_t("test_cell")) # Convert CellId to string for loro# First user connects- ydoc1 = Doc[Text]()- ycode1 = ydoc1.get("code", type=Text)- ylang1 = ydoc1.get("language", type=Text)- ycell1 = YCell(- ydoc=ydoc1, code_text=ycode1, language_text=ylang1, clients=1- )- ycells[key] = ycell1+ doc = LoroDoc()+ DOC_MANAGER.loro_docs[file_key] = doc++ # Setup client queues for both users+ queue1 = asyncio.Queue[bytes]()+ queue2 = asyncio.Queue[bytes]()+ DOC_MANAGER.loro_docs_clients[file_key] = {queue1, queue2}- # Set initial text- ycode1.insert(0, "print('hello')")- ylang1.insert(0, "python")+ # Get maps from doc+ doc_codes = doc.get_map("codes")+ doc_languages = doc.get_map("languages")- # Second user connects- ydoc2 = Doc[Text]()- ycode2 = ydoc2.get("code", type=Text)- ylang2 = ydoc2.get("language", type=Text)+ # Add text to the doc using get_or_create_container+ code_text = doc_codes.get_or_create_container(cell_id, LoroText())+ code_text_typed = cast(LoroText, code_text)+ code_text_typed.insert(0, "print('hello')")- # Simulate sync by using same key- ycells[key].clients += 1+ lang_text = doc_languages.get_or_create_container(cell_id, LoroText())+ lang_text_typed = cast(LoroText, lang_text)+ lang_text_typed.insert(0, "python")# Verify state- assert len(ycells) == 1 # No duplicates- assert ycells[key].clients == 2- assert ycode1.to_py() == "print('hello')"- assert ylang1.to_py() == "python"+ assert len(DOC_MANAGER.loro_docs) == 1+ assert len(DOC_MANAGER.loro_docs_clients[file_key]) == 2- # Second user makes changes- ycode1.insert(len(ycode1.to_py()), "\nprint('world')")+ # Make sure we can get the text content+ assert code_text_typed.to_string() == "print('hello')"++ # Second user makes changes - no need to retrieve the text again+ code_text_typed.insert(+ len(code_text_typed.to_string()), "\nprint('world')"+ )# Verify changes propagate- assert ycode1.to_py() == "print('hello')\nprint('world')"- assert ylang1.to_py() == "python"- assert ycells[key].code_text.to_py() == "print('hello')\nprint('world')"+ assert code_text_typed.to_string() == "print('hello')\nprint('world')"+ assert lang_text_typed.to_string() == "python"+++@contextmanager+def rtc_enabled(config: UserConfigManager):+ prev_config = config.get_config()+ try:+ config.save_config({"experimental": {"rtc_v2": True}})+ yield+ finally:+ config.save_config(prev_config)+++async def test_loro_sync(client: TestClient) -> None:+ """Test that Loro-CRDT sync works between multiple clients"""+ # Set up unique websocket paths for each client+ ws_1 = "/ws?session_id=123"+ ws_2 = "/ws?session_id=456"++ # Set up unique synchronization websocket paths for each client+ ws_1_sync = "/ws_sync?session_id=123"+ ws_2_sync = "/ws_sync?session_id=456"++ # First connect main websockets to create sessions+ with (+ rtc_enabled(get_user_config_manager(client)),+ client.websocket_connect(ws_1) as websocket1,+ client.websocket_connect(ws_2) as websocket2,+ ):+ # Verify both websockets received kernel ready messages+ data1 = websocket1.receive_json()+ assert_kernel_ready_response(data1)+ data2 = websocket2.receive_json()+ assert_parse_ready_response(data2)++ # Connect first client to sync websocket+ with client.websocket_connect(ws_1_sync) as sync_ws1:+ # Should receive initial sync message (binary data)+ sync_msg1 = sync_ws1.receive_bytes()+ # Loro sends binary data directly+ assert len(sync_msg1) > 0++ # Connect second client to sync websocket+ with client.websocket_connect(ws_2_sync) as sync_ws2:+ # Should receive initial sync message (binary data)+ sync_msg2 = sync_ws2.receive_bytes()+ assert len(sync_msg2) > 0++ # Verify both clients received initial sync data+ assert len(sync_msg1) > 0+ assert len(sync_msg2) > 0++ # Clean up by shutting down the kernel+ client.post("/api/kernel/shutdown", headers=HEADERS)+++async def test_loro_cleanup_on_session_close(+ client: TestClient,+) -> None:+ """Test that cell websockets are cleaned up when session closes"""+ from loro import ExportMode, LoroDoc++ # Create a LoroDoc for the cell content+ doc = LoroDoc()+ initial_code = doc.export(ExportMode.Snapshot())++ file_key = get_session_manager(client).file_router.get_unique_file_key()+ assert file_key is not None++ with (+ rtc_enabled(get_user_config_manager(client)),+ client.websocket_connect("/ws?session_id=123") as websocket,+ ):+ data = websocket.receive_json()+ assert_kernel_ready_response(data)++ # Connect to cell websocket+ with client.websocket_connect("/ws_sync?session_id=123") as cell_ws:+ sync_msg = cell_ws.receive_bytes()+ assert len(sync_msg) > 0++ assert file_key in DOC_MANAGER.loro_docs_clients+ assert len(DOC_MANAGER.loro_docs_clients[file_key]) == 1++ # Close main websocket+ websocket.close()++ # Give the server some time to process the disconnection+ await asyncio.sleep(1.5)++ try:+ cell_ws.send_bytes(initial_code)+ except Exception:+ pass++ assert len(DOC_MANAGER.loro_docs_clients[file_key]) == 0++ client.post("/api/kernel/shutdown", headers=HEADERS)+++async def test_loro_persistence(client: TestClient) -> None:+ """Test that cell content persists between connections"""+ from loro import ExportMode, LoroDoc++ # Create a LoroDoc for the cell content+ doc = LoroDoc()+ initial_code = doc.export(ExportMode.Snapshot())++ # First connection sets initial code+ with (+ rtc_enabled(get_user_config_manager(client)),+ client.websocket_connect("/ws?session_id=123") as websocket,+ ):+ data = websocket.receive_json()+ assert_kernel_ready_response(data)++ with client.websocket_connect("/ws_sync?session_id=123") as cell_ws1:+ sync_msg = cell_ws1.receive_bytes()+ assert len(sync_msg) > 0++ # Send initial code update+ # In Loro, we send the binary snapshot directly+ cell_ws1.send_bytes(initial_code)++ # Allow time for the update to be processed+ await asyncio.sleep(0.2)++ # Allow some time for cleanup between sessions+ await asyncio.sleep(0.2)++ # Second connection should receive persisted code+ with (+ rtc_enabled(get_user_config_manager(client)),+ client.websocket_connect("/ws?session_id=456") as websocket,+ ):+ data = websocket.receive_json()+ assert_kernel_ready_response(data, create_response({"resumed": True}))++ with client.websocket_connect("/ws_sync?session_id=456") as cell_ws2:+ sync_msg = cell_ws2.receive_bytes()+ # Verify initial sync contains data+ assert len(sync_msg) > 0++ client.post("/api/kernel/shutdown", headers=HEADERS)