AI-native design editor. Open-source Figma alternative.
chore(cloud): license Cloud under Apache-2.0 and build the editor without it (#1228)
Danila Poyarkovf917c738636e
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex e90f76b5d..bcaf0646b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -120,6 +120,9 @@ jobs:- name: Enforce architecture and type-shape boundariesrun: bun run check:arch && bun run check:test-homes && bun run test:type-shapes+ - name: Build the editor without Cloud+ run: bun run check:cloud-off+package-quality:name: Package integrityneeds: changesdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 7d5d44063..d67602bcb 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -80,6 +80,10 @@ Do not submit placeholder PRs. Remove template comments before opening a PR. DoCodeRabbit may flag PR description or readability issues for maintainers to review. Missing template sections or validation details are normal review feedback; they are not, by themselves, a personal judgment on the contributor. Maintainers may close PRs manually when they are clearly automated, not written in English, unrelated to the project, or impossible to review without substantial guesswork. If you are unsure how to fix something, please open a detailed issue instead of submitting a placeholder PR.+## Licensing++A contribution is licensed under the license of the files it changes, as [`REUSE.toml`](./REUSE.toml) maps them: MIT for most of the repository, and Apache-2.0 for OpenPencil Cloud's server, relay, administration, and the pages it serves (section 5 of the Apache License). New files under those paths take the same license.+## Commits### Attributiondiff --git a/LICENSES/Apache-2.0.txt b/LICENSES/Apache-2.0.txtnew file mode 100644index 000000000..d64569567--- /dev/null+++ b/LICENSES/Apache-2.0.txt@@ -0,0 +1,202 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/LICENSES/MIT.txt b/LICENSES/MIT.txtnew file mode 100644index 000000000..45c157d6d--- /dev/null+++ b/LICENSES/MIT.txt@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Danila Poyarkov and OpenPencil contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdindex f52606f54..a1ad27062 100644--- a/README.md+++ b/README.md@@ -232,7 +232,7 @@ bun run dev:portless # Web editor at https://open-pencil.localhostbun run tauri dev # Desktop app (requires Rust)```-[CONTRIBUTING.md](CONTRIBUTING.md) covers setup, quality gates, pull requests, and commits. [AGENTS.md](AGENTS.md) maps the repository and links the guide inside each package. Desktop builds need [Rust](https://rustup.rs/) and the [Tauri v2 prerequisites](https://v2.tauri.app/start/prerequisites/); run `bun run tauri build`.+[CONTRIBUTING.md](CONTRIBUTING.md) covers setup, quality gates, pull requests, and commits. [AGENTS.md](AGENTS.md) maps the repository and links the guide inside each package. Desktop builds need [Rust](https://rustup.rs/) and the [Tauri v2 prerequisites](https://v2.tauri.app/start/prerequisites/); run `bun run tauri build`. Set `VITE_OPENPENCIL_CLOUD=off` to build the web or desktop editor without OpenPencil Cloud.### Tech stack@@ -252,6 +252,6 @@ Thanks to [@sld0Ant](https://github.com/sld0Ant) (Anton Soldatov) for creating a## License-OpenPencil is licensed under the [MIT License](./LICENSE).+OpenPencil is licensed under the [MIT License](./LICENSE). OpenPencil Cloud's server, relay, and administration in [`packages/cloud`](./packages/cloud), and the pages it serves for signing in and administration, are licensed under the [Apache License 2.0](./LICENSES/Apache-2.0.txt); the protocol editors use to talk to it, `packages/cloud/src/contract` and `packages/cloud/src/client`, stays MIT. [`REUSE.toml`](./REUSE.toml) lists which paths each license covers.Copyright (c) 2026 Danila Poyarkov and OpenPencil contributors.diff --git a/REUSE.toml b/REUSE.tomlnew file mode 100644index 000000000..6470bc63a--- /dev/null+++ b/REUSE.toml@@ -0,0 +1,40 @@+# Which license covers which files, in the REUSE format (https://reuse.software). Later+# annotations override earlier ones for the paths they match.+version = 1++# The editor, its packages, and the repository tooling.+[[annotations]]+path = "**"+precedence = "override"+SPDX-FileCopyrightText = "2026 Danila Poyarkov and OpenPencil contributors"+SPDX-License-Identifier = "MIT"++# OpenPencil Cloud's server, relay, and administration, and the pages it serves for signing in,+# account security, and administration.+[[annotations]]+path = [+ "packages/cloud/**",+ "cloud.html",+ "src/cloud/**",+ "src/app/cloud-portal/**",+ "src/components/cloud-portal/**",+ "src/theme/cloud-portal/**",+ "src/views/cloud/**",+ "tests/app/cloud-portal/**",+ "vite/cloud-portal.ts",+]+precedence = "override"+SPDX-FileCopyrightText = "2026 Danila Poyarkov and OpenPencil contributors"+SPDX-License-Identifier = "Apache-2.0"++# The protocol editors and other clients speak to a Cloud server stays MIT.+[[annotations]]+path = [+ "packages/cloud/src/contract/**",+ "packages/cloud/src/client/**",+ "packages/cloud/tests/contract/**",+ "packages/cloud/tests/client/**",+]+precedence = "override"+SPDX-FileCopyrightText = "2026 Danila Poyarkov and OpenPencil contributors"+SPDX-License-Identifier = "MIT"diff --git a/bun.lock b/bun.lockindex 6f11bfb9b..868e38196 100644--- a/bun.lock+++ b/bun.lock@@ -582,6 +582,13 @@"@open-pencil/package-artifacts-tools": "workspace:*",},},+ "tools/checks/cloud-off": {+ "name": "@open-pencil/cloud-off-tools",+ "dependencies": {+ "@open-pencil/package-artifacts-tools": "workspace:*",+ "vite": "8.1.4",+ },+ },"tools/checks/docs": {"name": "@open-pencil/docs-tools","dependencies": {@@ -1560,6 +1567,8 @@"@open-pencil/cloud": ["@open-pencil/cloud@workspace:packages/cloud"],+ "@open-pencil/cloud-off-tools": ["@open-pencil/cloud-off-tools@workspace:tools/checks/cloud-off"],+"@open-pencil/cloud-tools": ["@open-pencil/cloud-tools@workspace:tools/dev/cloud"],"@open-pencil/core": ["@open-pencil/core@workspace:packages/core"],diff --git a/changes/1069/added.md b/changes/1069/added.mdindex b19ad1d53..a21e5dd3c 100644--- a/changes/1069/added.md+++ b/changes/1069/added.md@@ -1 +1 @@-- OpenPencil Cloud is ready to self-host, and to try before the hosted service opens: open the editor with `?cloud=preview`, or follow an invitation, to keep documents on your team's server and edit them together. Connect a server in **Settings → Cloud**, which also holds the hosted service's waitlist: email and password sign in, and create an account, right in the dialog, while Google, Apple, and two-step sign-in finish in the browser. Home lists the server's workspaces and the documents shared with you, every account starts with a workspace of its own and can create team workspaces whose admins invite people by email as admins, editors, or viewers and delete them once they are empty, **New design** creates in the place Home shows, **File → Save to…** saves the open document straight to the only workspace or bucket it can go to and asks only when there are several, **File → Browse files…** opens Home where you left it, and a status beside the name appears when the document is offline, couldn't save, changed in two places, with the choice to keep both versions, or is view only. Opening a Cloud document joins its live room, so everyone with it open sees edits and cursors as they happen while one editor saves for all. **Share** invites people by email and turns on a link that opens the document for guests, within what the workspace's plan allows; on a computer, the web editor offers to open invitations and shared links in the desktop app. The server, its relay, and its pages for signing in, account security, and administration are in `@open-pencil/cloud`.+- OpenPencil Cloud is ready to self-host, and to try before the hosted service opens: open the editor with `?cloud=preview`, or follow an invitation, to keep documents on your team's server and edit them together. Connect a server in **Settings → Cloud**, which also holds the hosted service's waitlist: email and password sign in, and create an account, right in the dialog, while Google, Apple, and two-step sign-in finish in the browser. Home lists the server's workspaces and the documents shared with you, every account starts with a workspace of its own and can create team workspaces whose admins invite people by email as admins, editors, or viewers and delete them once they are empty, **New design** creates in the place Home shows, **File → Save to…** saves the open document straight to the only workspace or bucket it can go to and asks only when there are several, **File → Browse files…** opens Home where you left it, and a status beside the name appears when the document is offline, couldn't save, changed in two places, with the choice to keep both versions, or is view only. Opening a Cloud document joins its live room, so everyone with it open sees edits and cursors as they happen while one editor saves for all. **Share** invites people by email and turns on a link that opens the document for guests, within what the workspace's plan allows; on a computer, the web editor offers to open invitations and shared links in the desktop app. The server, its relay, and its pages for signing in, account security, and administration are in `@open-pencil/cloud` under the Apache License 2.0, while the protocol the editor speaks to it stays MIT; `VITE_OPENPENCIL_CLOUD=off` builds the editor without Cloud.diff --git a/package.json b/package.jsonindex e29dc435d..5c85dec9c 100644--- a/package.json+++ b/package.json@@ -22,6 +22,7 @@"vite","tools","tools/checks/architecture",+ "tools/checks/cloud-off","tools/checks/docs","tools/checks/i18n","tools/checks/lint",@@ -64,7 +65,7 @@"lint:structure": "oxlint -c oxlint.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/scene-graph/scripts/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/dom-css/src/ packages/dom-css/tests/ packages/dom-css/scripts/ packages/pen/src/ packages/pen/scripts/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/design-jsx/scripts/ packages/emit/src/ packages/emit/tests/ packages/emit/scripts/ packages/kiwi/src/ packages/kiwi/tests/ packages/kiwi/scripts/ packages/fig/src/ packages/fig/tests/ packages/fig/scripts/ packages/core/tests/ packages/cli/tests/ packages/scene-graph/tests/ packages/vue/tests/ tests/ scripts/ tools/ packages/docs/.vitepress/theme/landing/","format": "oxfmt --write .oxfmtrc.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/scene-graph/scripts/ packages/core/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/cloud/tsdown.config.ts packages/cloud/tsdown.standalone.config.ts packages/vue/src/ packages/dom-css/src/ packages/dom-css/tests/ packages/dom-css/scripts/ packages/pen/src/ packages/pen/scripts/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/design-jsx/scripts/ packages/emit/src/ packages/emit/tests/ packages/emit/scripts/ packages/kiwi/src/ packages/kiwi/tests/ packages/kiwi/scripts/ packages/fig/src/ packages/fig/tests/ packages/fig/scripts/ tests scripts/ tools/ packages/docs/.vitepress/theme/landing/","format:check": "bun run format && status=$(git status --porcelain -uall) && test -z \"$status\" || (echo \"$status\" && exit 1)",- "check": "bun run check:icons && bun run build:packages && bun run lint && tsgo --noEmit && bun run check:vue && bun run check:native-test && bun run check:i18n && bun run check:docs && bun run check:changelog && bun run check:packages && bun run check:deps && bun run check:audit && bun run check:secrets && bun run check:monorepo && bun run check:arch && bun run check:test-homes && bun run check:test-types && bun run test:type-shapes && bun run check:tools && bun run test:tools && bun run test:dupes",+ "check": "bun run check:icons && bun run build:packages && bun run lint && tsgo --noEmit && bun run check:vue && bun run check:native-test && bun run check:i18n && bun run check:docs && bun run check:changelog && bun run check:packages && bun run check:deps && bun run check:audit && bun run check:secrets && bun run check:monorepo && bun run check:arch && bun run check:test-homes && bun run check:cloud-off && bun run check:test-types && bun run test:type-shapes && bun run check:tools && bun run test:tools && bun run test:dupes","check:commits": "commitlint","check:changelog": "bun tools/release/release-packages/src/changelog/check.ts","changelog:assemble": "bun tools/release/release-packages/src/changelog/assemble.ts",@@ -80,6 +81,7 @@"check:packages": "bun tools/checks/package-quality/src/cli.ts check","check:arch": "steiger .","check:test-homes": "bun tools/checks/test-homes/src/index.ts",+ "check:cloud-off": "bun tools/checks/cloud-off/src/index.ts","check:test-types": "bun tools/checks/test-types/src/index.ts","check:vue": "vue-tsc --noEmit -p tsconfig.json && vue-tsc --noEmit -p packages/vue/tsconfig.json","test": "OPENPENCIL_TEST_SERVER=app playwright test --project=openpencil --grep-invert @real-llm",diff --git a/packages/cloud/LICENSE b/packages/cloud/LICENSEnew file mode 100644index 000000000..d64569567--- /dev/null+++ b/packages/cloud/LICENSE@@ -0,0 +1,202 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/packages/cloud/NOTICE b/packages/cloud/NOTICEnew file mode 100644index 000000000..d56010be4--- /dev/null+++ b/packages/cloud/NOTICE@@ -0,0 +1,6 @@+OpenPencil Cloud+Copyright 2026 Danila Poyarkov and OpenPencil contributors++This product is licensed under the Apache License, Version 2.0 (see LICENSE),+except src/contract and src/client, the protocol the editor and other clients+speak, which are under the MIT License (see ../../LICENSE).diff --git a/packages/cloud/package.json b/packages/cloud/package.jsonindex f459214c0..44b0d59ae 100644--- a/packages/cloud/package.json+++ b/packages/cloud/package.json@@ -2,7 +2,7 @@"name": "@open-pencil/cloud","version": "0.15.1","private": true,- "license": "MIT",+ "license": "Apache-2.0 AND MIT","type": "module","imports": {"#cloud/*": {diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.mdindex 97d039edb..c73a12a3b 100644--- a/packages/docs/development/cloud.md+++ b/packages/docs/development/cloud.md@@ -283,3 +283,10 @@ desktop app, which gets the same path, server, and secret as `openpencil://cloudThe native side checks the ID, secret, and server before the editor sees a link. The secret isvisible in the launch arguments to other processes on the same computer; pasting links into theapp would avoid that at the cost of a manual step for everyone.++**2026-10 · Cloud's server is Apache-2.0, and the editor builds without it.** The server, relay,+administration, and the pages the server serves are Apache-2.0 for its patent grant; the protocol+in `contract` and `client` stays MIT, so the editor and other clients stay MIT. `REUSE.toml` maps+the paths rather than a separate package, which would have moved the protocol out of+`packages/cloud` for no legal gain. `VITE_OPENPENCIL_CLOUD=off` swaps Cloud's two entry points for+stand-ins, and `check:cloud-off` proves that build bundles none of Cloud.diff --git a/src/AGENTS.md b/src/AGENTS.mdindex 8b42fedd4..52fb73eab 100644--- a/src/AGENTS.md+++ b/src/AGENTS.md@@ -26,6 +26,7 @@ Root Tauri/Vite app. Services and state live under `src/app/**`, views under `sr- ACP transport lives under `src/app/ai/acp/**`; provider definitions in `packages/core/src/constants.ts`; profiles in `src/app/ai/models/**`. Keep provider connections, reusable profiles, and role assignments separate, and resolve credentials lazily. ACP process changes require checking `desktop/capabilities/**`.- Browser-native WebMCP registration lives under `src/app/automation/webmcp/`, consumes per-tool exposure metadata, and is feature-detected through `document.modelContext`. App completion under `src/app/automation/execution/` loads fonts after commit.- Collaboration lives under `src/app/collab/**` on Yjs and awareness over a `CollabRoomTransport`: Trystero for peer-to-peer rooms, the Cloud relay (`transport/cloud.ts`) for Cloud documents. Preserve crypto-safe room IDs and peer cleanup. Room channels are named in `COLLAB_ACTIONS` from `@open-pencil/cloud/contract`, because the relay reads the document ones to persist rooms and drop viewer writes (`tests/integration/collab/cloud-relay.test.ts`).+- Outside Cloud's own folders, app code reaches Cloud only through `@/app/cloud/integration` (and its `/storage` provider list) and components through `@/components/cloud/integration`; a `VITE_OPENPENCIL_CLOUD=off` build swaps both for their `off` stand-ins, which must keep the same names (`tests/app/cloud/integration/off.test.ts`), and must bundle no other Cloud module (`bun run check:cloud-off`).- Cloud servers are profiles of the `openpencil-cloud` storage provider (server = profile, workspace = container) and their sessions its credential; app code reaches a server through `src/app/cloud/sessions/connection.ts`, never with its own fetch (`tests/app/cloud/sessions/connection.test.ts`).- An open Cloud document is live in its relay room, and only the elected saver (`electCloudSaver` in `src/app/cloud/rooms/live.ts`) uploads its revisions; guests from a link never save (`tests/integration/collab/cloud-relay.test.ts`).- The Cloud portal is its own entry (`cloud.html`, `src/cloud/`, `src/views/cloud/`) served by the Cloud server, not the editor; it must not import editor sessions, CanvasKit, or `src/app/shell/**`, so `bun run build:cloud-portal` stays small (`open-pencil/no-editor-imports-in-cloud-portal`, `check:arch`).diff --git a/src/App.vue b/src/App.vueindex 3560eff52..a011bfaf4 100644--- a/src/App.vue+++ b/src/App.vue@@ -8,8 +8,7 @@ import { useRouter } from 'vue-router'import { provideEditor, useI18n } from '@open-pencil/vue'-import { watchCloudRooms } from '@/app/cloud/rooms/live'-import { startCloudSessions } from '@/app/cloud/sessions/startup'+import { startCloud } from '@/app/cloud/integration'import { useDocumentCloseProtection } from '@/app/document/close/use'import { useFollowingEditorStore } from '@/app/editor/active-store'import { animationsEnabled } from '@/app/shell/motion'@@ -19,15 +18,12 @@ import { useRestartApprovals } from '@/app/shell/updater/approvals'import { scheduleStartupUpdateCheck } from '@/app/shell/updater/check'import { kickSyncEngine } from '@/app/storage/sync'import { prepareForReload } from '@/app/tabs'-import CloudConnectHost from '@/components/cloud/connect/CloudConnectHost.vue'-import CloudInvitationHost from '@/components/cloud/invitation/CloudInvitationHost.vue'-import CloudSaveHost from '@/components/cloud/save/CloudSaveHost.vue'-import CloudNewWorkspaceHost from '@/components/cloud/workspace/CloudNewWorkspaceHost.vue'-import CloudWorkspaceMembersHost from '@/components/cloud/workspace/CloudWorkspaceMembersHost.vue'+import { CloudHosts } from '@/components/cloud/integration'import UnsavedChangesDialog from '@/components/document/UnsavedChangesDialog.vue'import PublishLibraryDialog from '@/components/libraries/PublishLibraryDialog.vue'import LibraryUpdateReviewDialog from '@/components/libraries/review/LibraryUpdateReviewDialog.vue'import RecoveryDialog from '@/components/recovery/RecoveryDialog.vue'+import SaveToHost from '@/components/save-to/SaveToHost.vue'import AISetupDialog from '@/components/settings/ai-setup/AISetupDialog.vue'import SettingsDialog from '@/components/settings/SettingsDialog.vue'import UsageStatsPrompt from '@/components/sharing/UsageStatsPrompt.vue'@@ -58,10 +54,9 @@ onMounted(() => {toast.setupGlobalErrorHandler()scheduleStartupUpdateCheck(updates)void kickSyncEngine()- onUnmounted(watchCloudRooms())- void startCloudSessions({- leaveLinkAddress: () => router.isReady().then(() => router.replace('/'))- })+ onUnmounted(+ startCloud({ leaveLinkAddress: () => router.isReady().then(() => router.replace('/')) })+ )})</script>@@ -73,11 +68,8 @@ onMounted(() => {</AppShell><SettingsDialog /><AISetupDialog />- <CloudConnectHost />- <CloudSaveHost />- <CloudInvitationHost />- <CloudNewWorkspaceHost />- <CloudWorkspaceMembersHost />+ <SaveToHost />+ <CloudHosts /><RecoveryDialog /><UnsavedChangesDialog /><PublishLibraryDialog />diff --git a/src/app/cloud/documents/save.ts b/src/app/cloud/documents/save.tsindex ae81a4cb5..4d7ae435d 100644--- a/src/app/cloud/documents/save.ts+++ b/src/app/cloud/documents/save.ts@@ -1,18 +1,9 @@-import { useLocalStorage } from '@vueuse/core'-import { computed, ref, shallowRef, watch } from 'vue'--import type { EditorStore } from '@/app/editor/session'+import type { StorageLocation } from '@/app/integrations/storage'import {- activeStorageProviderID,- isStorageConfigured,- readStoragePreferences-} from '@/app/integrations/storage'-import { rememberRecentStorageDocument } from '@/app/recent-files'-import { openSettingsDialog } from '@/app/settings/dialog'-import { getLocalCanvasStore } from '@/app/storage/local-store'-import { getOutbox, syncUIState, uploadProgressByCanvas } from '@/app/storage/sync'-import { onStorageWorkspaceEvent } from '@/app/storage/workspace/events'-import { IS_BROWSER } from '@/constants'+ saveDestinationKey,+ type SaveDestination,+ type SaveFailure+} from '@/app/storage/save-to/model'import { openCloudConnect } from '../connect/flow'import { cloudServerHost } from '../servers/address'@@ -20,235 +11,72 @@ import { cloudServers, findCloudServer } from '../servers/store'import { cloudAPIClient, cloudConnection, refreshCloudConnection } from '../sessions/connection'import { CLOUD_STORAGE_PROVIDER_ID } from '../sessions/token'-export type CloudSaveState =- | { kind: 'ready' }- | { kind: 'saving'; sentBytes: number; totalBytes: number }- | { kind: 'error'; reason: 'too-large'; limitBytes: number }- | { kind: 'error'; reason: 'offline' | 'quota' | 'unavailable' }--/** Where Save to can put a document: a signed-in server's workspaces, or the storage bucket. */-export type SaveDestinationGroup =- | {- kind: 'cloud'- serverId: string- host: string- workspaces: { id: string; name: string; role: 'viewer' | 'editor' | 'admin' }[]- }- | { kind: 'storage'; providerId: string; label: string }--export const cloudSaveOpen = ref(false)-export const cloudSaveName = ref('')-/** `cloud/serverId/workspaceId` or `storage/providerId`: the chosen destination. */-export const cloudSaveDestination = ref('')-export const cloudSaveState = shallowRef<CloudSaveState>({ kind: 'ready' })-export const cloudSaveDestinations = shallowRef<SaveDestinationGroup[]>([])-/** The destination saved to last, chosen first next time. */-const lastDestination = IS_BROWSER ? useLocalStorage('open-pencil:save-destination', '') : ref('')-let target: EditorStore | null = null--/** Workspaces of every signed-in server, grouped by server. */-const cloudDestinations = computed(() =>- cloudServers.value.flatMap((server): SaveDestinationGroup[] => {- const connection = cloudConnection(server.id)- if (connection.state !== 'signed-in' || !connection.workspaces.length) return []- return [- {- kind: 'cloud',- serverId: server.id,- host: cloudServerHost(server.url),- workspaces: connection.workspaces.map(({ id, name, role }) => ({ id, name, role }))- }- ]- })-)--async function storageDestination(): Promise<SaveDestinationGroup[]> {- const providerId = activeStorageProviderID.value- if (!(await isStorageConfigured(providerId))) return []- const bucket = readStoragePreferences(providerId).bucket.trim()- return [{ kind: 'storage', providerId, label: bucket || providerId }]-}--/** Every destination the document can go to, as `kind/...` keys a writer can save to. */-function writableKeys(groups: SaveDestinationGroup[]): string[] {- return groups.flatMap((group) =>- group.kind === 'storage'- ? [`storage/${group.providerId}`]- : group.workspaces- .filter((workspace) => workspace.role !== 'viewer')- .map((workspace) => `cloud/${group.serverId}/${workspace.id}`)- )-}--/** Servers still being checked are waited for, so a fresh start does not look signed out. */-async function settledCloudDestinations(): Promise<SaveDestinationGroup[]> {+/**+ * The workspaces of every signed-in server, as places Save to can put a document. Servers still+ * being checked are waited for, so a fresh start does not look signed out.+ */+export async function cloudSaveDestinations(): Promise<SaveDestination[]> {const checking = cloudServers.value.filter((server) => cloudConnection(server.id).state === 'checking')await Promise.all(checking.map((server) => refreshCloudConnection(server)))- return cloudDestinations.value-}--/**- * Save to: straight to the only place the document can go, or a choice when there are several.- * With nowhere to save yet, it signs in to the server this app knows, or opens Cloud settings.- */-export async function openSaveTo(store: EditorStore): Promise<void> {- const groups = [...(await settledCloudDestinations()), ...(await storageDestination())]- const keys = writableKeys(groups)- target = store- cloudSaveName.value = store.state.documentName || 'Untitled'- cloudSaveState.value = { kind: 'ready' }- cloudSaveDestinations.value = groups- if (keys.length === 0) {- const signedOut = cloudServers.value.find((server) => {- const state = cloudConnection(server.id).state- return state === 'expired' || state === 'signed-out'+ return cloudServers.value.flatMap((server) => {+ const connection = cloudConnection(server.id)+ if (connection.state !== 'signed-in') return []+ const place = { id: server.id, label: cloudServerHost(server.url) }+ return connection.workspaces.map((workspace): SaveDestination => {+ const location = {+ providerId: CLOUD_STORAGE_PROVIDER_ID,+ profileId: server.id,+ containerId: workspace.id+ }+ return {+ key: saveDestinationKey(location),+ location,+ label: workspace.name,+ kind: 'workspace',+ place,+ role: workspace.role+ }})- if (signedOut) openCloudConnect({ serverId: signedOut.id })- else openSettingsDialog('cloud')- return- }- if (keys.length === 1) {- cloudSaveDestination.value = keys[0] ?? ''- // The dialog only appears when the save fails, to say why.- if (!(await saveToDestination())) cloudSaveOpen.value = true- return- }- cloudSaveDestination.value = keys.includes(lastDestination.value)- ? lastDestination.value- : (keys[0] ?? '')- cloudSaveOpen.value = true+ })}-/**- * Follows a new document's first upload: true once it is on the server, or when the person- * closes the dialog and leaves it to finish in the background; false when the upload failed.- */-function waitForFirstUpload(documentId: string, totalBytes: number): Promise<boolean> {- return new Promise((resolve) => {- const stops: (() => void)[] = []- const finish = (uploaded: boolean) => {- for (const stop of stops) stop()- resolve(uploaded)- }- async function check() {- const meta = await getLocalCanvasStore().getMeta(documentId)- if (meta?.syncStatus === 'synced') return finish(true)- // The engine parks a job it cannot finish until the person acts, rather than dropping it.- const jobs = await getOutbox().list()- const parked = jobs.some(- (job) => job.canvasId === documentId && job.nextAttemptAt === Number.MAX_SAFE_INTEGER- )- if (meta?.syncStatus === 'error' || parked) finish(false)- }- stops.push(- watch(uploadProgressByCanvas, (progress) => {- const sent = progress.get(documentId)- if (sent !== undefined) {- cloudSaveState.value = { kind: 'saving', sentBytes: sent * totalBytes, totalBytes }- }- }),- watch(cloudSaveOpen, (open) => {- if (!open) finish(true)- }),- // Failures move the engine's state without a document event.- watch(syncUIState, () => void check()),- onStorageWorkspaceEvent((event) => {- if (event.documentId === documentId) void check()- })- )- // A small file can finish uploading before these watchers exist.- void check()+/** Signs in to a server this app knows but is signed out of; false when there is none. */+export function signInToSaveTo(): boolean {+ const signedOut = cloudServers.value.find((server) => {+ const state = cloudConnection(server.id).state+ return state === 'expired' || state === 'signed-out'})+ if (signedOut) openCloudConnect({ serverId: signedOut.id })+ return signedOut !== undefined}/**- * Why the first upload failed, from the workspace's limits: the server refuses a file over its- * size limit or one that does not fit the remaining storage without saying which.+ * Why a document's first upload to a Cloud workspace failed, from the workspace's limits: the+ * server refuses a file over its size limit, or one that does not fit the remaining storage,+ * without saying which. Null for anywhere that is not a Cloud workspace.*/-async function uploadFailure(- serverId: string,- workspaceId: string,+export async function cloudUploadFailure(+ location: StorageLocation,size: number-): Promise<CloudSaveState> {- const server = findCloudServer(serverId)+): Promise<SaveFailure | null> {+ const { providerId, profileId, containerId } = location+ if (providerId !== CLOUD_STORAGE_PROVIDER_ID || !profileId || !containerId) return null+ const server = findCloudServer(profileId)const discovery = server ? cloudConnection(server.id).discovery : null- if (!server || !discovery) return { kind: 'error', reason: 'unavailable' }+ if (!server || !discovery) return { reason: 'unavailable' }const entitlements = await cloudAPIClient(server, discovery)- .getWorkspaceEntitlements(workspaceId)+ .getWorkspaceEntitlements(containerId).catch(() => null)- if (!entitlements) return { kind: 'error', reason: 'unavailable' }+ if (!entitlements) return { reason: 'unavailable' }const { limits, usage } = entitlementsif (size > limits.maximumFileBytes) {- return { kind: 'error', reason: 'too-large', limitBytes: limits.maximumFileBytes }+ return { reason: 'too-large', limitBytes: limits.maximumFileBytes }}const stored = usage.committedStorageBytes + usage.reservedStorageBytesif (limits.maximumStorageBytes !== null && stored + size > limits.maximumStorageBytes) {- return { kind: 'error', reason: 'quota' }- }- return { kind: 'error', reason: 'unavailable' }-}--async function saveToStorageBucket(store: EditorStore, providerId: string): Promise<boolean> {- if (!(await store.saveFigFileToStorage({ providerId }))) return false- const binding = store.getStorageBinding()- if (binding) rememberRecentStorageDocument(binding, store.state.documentName)- return true-}--/**- * Saves the document to the chosen destination. A Cloud copy is kept on this device and the tab- * moves to it at once, then the save follows the first upload. The file it came from is left as- * it was.- */-export async function saveToDestination(): Promise<boolean> {- const store = target- const destination = cloudSaveDestination.value- const [kind, first, second] = destination.split('/')- const name = cloudSaveName.value.trim()- if (!store || !name || !first) return false- if (!navigator.onLine) {- cloudSaveState.value = { kind: 'error', reason: 'offline' }- return false- }- const previousName = store.state.documentName- store.state.documentName = name- cloudSaveState.value = { kind: 'saving', sentBytes: 0, totalBytes: 0 }- if (kind === 'storage') {- if (!(await saveToStorageBucket(store, first))) {- store.state.documentName = previousName- cloudSaveState.value = { kind: 'error', reason: 'unavailable' }- return false- }- lastDestination.value = destination- cloudSaveOpen.value = false- return true- }- const serverId = first- const workspaceId = second- if (!workspaceId) return false- const location = {- providerId: CLOUD_STORAGE_PROVIDER_ID,- profileId: serverId,- containerId: workspaceId- }- if (!(await store.saveFigFileToStorage(location))) {- // Nothing was saved, so the tab keeps the name it had.- store.state.documentName = previousName- cloudSaveState.value = { kind: 'error', reason: 'unavailable' }- return false- }- lastDestination.value = destination- const binding = store.getStorageBinding()- if (!binding) return false- rememberRecentStorageDocument(binding, name)- const meta = await getLocalCanvasStore().getMeta(binding.documentId)- const size = meta?.figSize ?? 0- if (!(await waitForFirstUpload(binding.documentId, size))) {- cloudSaveState.value = await uploadFailure(serverId, workspaceId, size)- return false+ return { reason: 'quota' }}- cloudSaveOpen.value = false- return true+ return { reason: 'unavailable' }}diff --git a/src/app/cloud/home.ts b/src/app/cloud/home.tsnew file mode 100644index 000000000..42433e14f--- /dev/null+++ b/src/app/cloud/home.ts@@ -0,0 +1,39 @@+import { computed } from 'vue'++import { openCloudConnect } from './connect/flow'+import { cloudServerHost } from './servers/address'+import { homeCloudServer } from './servers/store'+import { cloudConnection } from './sessions/connection'+import { signOutOfCloud } from './sessions/sign-out'+import { openNewWorkspace } from './workspaces/manage'++/** The server Home shows: who is signed in to it, and its workspaces. */+export function useHomeCloud() {+ const connection = computed(() => {+ const server = homeCloudServer.value+ return server ? { server, ...cloudConnection(server.id) } : null+ })+ const signedIn = computed(() =>+ connection.value?.state === 'signed-in' ? connection.value : null+ )+ return {+ signedIn: computed(() => signedIn.value !== null),+ account: computed(() => {+ const current = signedIn.value+ if (!current?.account) return null+ return { ...current.account, host: cloudServerHost(current.server.url) }+ }),+ workspaces: computed(() => signedIn.value?.workspaces ?? []),+ serverId: computed(() => signedIn.value?.server.id ?? null),+ // Signing back in goes straight to the server Home shows; without one, choose a server.+ connect: () => openCloudConnect({ serverId: homeCloudServer.value?.id }),+ newWorkspace: () => {+ const server = signedIn.value?.server+ if (server) openNewWorkspace(server.id)+ },+ signOut: async () => {+ const current = signedIn.value+ if (current?.discovery) await signOutOfCloud(current.server.id, current.discovery)+ }+ }+}diff --git a/src/app/cloud/integration/index.ts b/src/app/cloud/integration/index.tsnew file mode 100644index 000000000..828f54c08--- /dev/null+++ b/src/app/cloud/integration/index.ts@@ -0,0 +1,22 @@+/**+ * Everything the rest of the app uses from Cloud. A build with `VITE_OPENPENCIL_CLOUD=off`+ * resolves this module to `./off`, which offers the same names and does nothing, so Cloud's code+ * stays out of that build; app code outside Cloud's folders imports Cloud only from here.+ */+import { watchCloudRooms } from '../rooms/live'+import { startCloudSessions } from '../sessions/startup'++export { isCloudBinding } from '../documents/status'+export { cloudSaveDestinations, cloudUploadFailure, signInToSaveTo } from '../documents/save'+export { useHomeCloud } from '../home'+export { CLOUD_STORAGE_PROVIDER_ID } from '../sessions/token'++/** This build has Cloud; whether it shows depends on the server's listing or a preview. */+export const CLOUD_INCLUDED: boolean = true++/** Starts Cloud sign-ins, links, and live rooms; returns what stops the room watcher. */+export function startCloud(options: { leaveLinkAddress(): Promise<unknown> }): () => void {+ const stop = watchCloudRooms()+ void startCloudSessions(options)+ return stop+}diff --git a/src/app/cloud/integration/off/index.ts b/src/app/cloud/integration/off/index.tsnew file mode 100644index 000000000..19dbc77b2--- /dev/null+++ b/src/app/cloud/integration/off/index.ts@@ -0,0 +1,49 @@+import { noop } from 'es-toolkit'+import { computed } from 'vue'++import type { WorkspaceSummary } from '@open-pencil/cloud/contract'++import type { CloudAccount } from '@/app/cloud/servers/store'+import type { SaveDestination, SaveFailure } from '@/app/storage/save-to/model'++/**+ * What a build without Cloud (`VITE_OPENPENCIL_CLOUD=off`) resolves `@/app/cloud/integration`+ * to: the same names, offering nothing. Only types come from Cloud's modules, so none of its code+ * is bundled.+ */+export const CLOUD_INCLUDED: boolean = false++// Still the identifier Home and Save to compare locations with; no provider registers it.+export { CLOUD_STORAGE_PROVIDER_ID } from '@/app/cloud/sessions/token'++export function startCloud(): () => void {+ return noop+}++export function isCloudBinding(): boolean {+ return false+}++export async function cloudSaveDestinations(): Promise<SaveDestination[]> {+ return []+}++export function signInToSaveTo(): boolean {+ return false+}++export async function cloudUploadFailure(): Promise<SaveFailure | null> {+ return null+}++export function useHomeCloud() {+ return {+ signedIn: computed(() => false),+ account: computed<(CloudAccount & { host: string }) | null>(() => null),+ workspaces: computed<WorkspaceSummary[]>(() => []),+ serverId: computed<string | null>(() => null),+ connect: noop,+ newWorkspace: noop,+ signOut: () => Promise.resolve()+ }+}diff --git a/src/app/cloud/integration/off/storage.ts b/src/app/cloud/integration/off/storage.tsnew file mode 100644index 000000000..0b7308221--- /dev/null+++ b/src/app/cloud/integration/off/storage.ts@@ -0,0 +1,4 @@+import type { StorageProviderRegistration } from '@/app/integrations/storage/types'++/** A build without Cloud adds no storage providers. */+export const CLOUD_STORAGE_PROVIDERS: readonly StorageProviderRegistration[] = []diff --git a/src/app/cloud/integration/storage.ts b/src/app/cloud/integration/storage.tsnew file mode 100644index 000000000..76c3102f9--- /dev/null+++ b/src/app/cloud/integration/storage.ts@@ -0,0 +1,21 @@+import { createCloudStorageAdapter } from '@/app/integrations/storage/cloud/adapter'+import { defineStorageProvider } from '@/app/integrations/storage/registry'+import type { StorageProviderRegistration } from '@/app/integrations/storage/types'++import { CLOUD_SESSION_FIELD, CLOUD_STORAGE_PROVIDER_ID } from '../sessions/token'++/**+ * The storage providers Cloud adds: servers are profiles and workspaces containers, and signing+ * in replaces typed credentials. Kept apart from the rest of the integration, which the storage+ * registry would otherwise load in a cycle.+ */+export const CLOUD_STORAGE_PROVIDERS: readonly StorageProviderRegistration[] = [+ defineStorageProvider({+ id: CLOUD_STORAGE_PROVIDER_ID,+ label: 'OpenPencil Cloud',+ description: 'Workspaces on OpenPencil Cloud or your team’s own server',+ preferenceFields: [],+ credentialFields: [{ id: CLOUD_SESSION_FIELD, label: 'Session' }],+ createAdapter: (runtime) => createCloudStorageAdapter(runtime)+ })+]diff --git a/src/app/home/locations.ts b/src/app/home/locations.tsindex 5896c46ba..c72cd1d45 100644--- a/src/app/home/locations.ts+++ b/src/app/home/locations.ts@@ -1,11 +1,6 @@import { computed } from 'vue'-import { openCloudConnect } from '@/app/cloud/connect/flow'-import { cloudServerHost } from '@/app/cloud/servers/address'-import { homeCloudServer } from '@/app/cloud/servers/store'-import { cloudConnection } from '@/app/cloud/sessions/connection'-import { signOutOfCloud } from '@/app/cloud/sessions/sign-out'-import { openNewWorkspace } from '@/app/cloud/workspaces/manage'+import { useHomeCloud } from '@/app/cloud/integration'import { openSettingsDialog } from '@/app/settings/dialog'import { homeLocation, type HomeLocation } from './location'@@ -37,23 +32,12 @@ function fromView(location: HomeLocationView): HomeLocation {* reach falls back to Recent.*/export function useHomeLocations() {- const connection = computed(() => {- const server = homeCloudServer.value- return server ? { server, ...cloudConnection(server.id) } : null- })- const signedIn = computed(() =>- connection.value?.state === 'signed-in' ? connection.value : null- )- const account = computed(() => {- const current = signedIn.value- if (!current?.account) return null- return { ...current.account, host: cloudServerHost(current.server.url) }- })- const workspaces = computed(() => signedIn.value?.workspaces ?? [])+ const cloud = useHomeCloud()+ const workspaces = cloud.workspacesconst location = computed<HomeLocation>(() => {const chosen = homeLocation.value- if (chosen.kind === 'shared' && !signedIn.value) return { kind: 'recent' }+ if (chosen.kind === 'shared' && !cloud.signedIn.value) return { kind: 'recent' }if (chosen.kind === 'workspace' && !workspaces.value.some((entry) => entry.id === chosen.id)) {return { kind: 'recent' }}@@ -67,26 +51,19 @@ export function useHomeLocations() {})return {- account,+ account: cloud.account,workspaces,location,workspace,- serverId: computed(() => signedIn.value?.server.id ?? null),+ serverId: cloud.serverId,active: computed(() => toView(location.value)),select(next: HomeLocationView) {homeLocation.value = fromView(next)},- // Signing back in goes straight to the server Home shows; without one, choose a server.- connect: () => openCloudConnect({ serverId: homeCloudServer.value?.id }),+ connect: cloud.connect,accountSettings: () => openSettingsDialog('cloud'),- newWorkspace() {- const server = signedIn.value?.server- if (server) openNewWorkspace(server.id)- },+ newWorkspace: cloud.newWorkspace,storageSettings: () => openSettingsDialog('storage'),- async signOut() {- const current = signedIn.value- if (current?.discovery) await signOutOfCloud(current.server.id, current.discovery)- }+ signOut: cloud.signOut}}diff --git a/src/app/integrations/storage/providers.ts b/src/app/integrations/storage/providers.tsindex a055eb8a1..d18cd9330 100644--- a/src/app/integrations/storage/providers.ts+++ b/src/app/integrations/storage/providers.ts@@ -1,6 +1,5 @@-import { CLOUD_SESSION_FIELD, CLOUD_STORAGE_PROVIDER_ID } from '@/app/cloud/sessions/token'+import { CLOUD_STORAGE_PROVIDERS } from '@/app/cloud/integration/storage'-import { createCloudStorageAdapter } from './cloud/adapter'import { defineStorageProvider, StorageProviderRegistry } from './registry'import { createS3StorageAdapter } from './s3/adapter'@@ -20,17 +19,7 @@ export const S3_STORAGE_PROVIDER = defineStorageProvider({createAdapter: createS3StorageAdapter})-/** Servers are profiles and workspaces containers; signing in replaces typed credentials. */-export const CLOUD_STORAGE_PROVIDER = defineStorageProvider({- id: CLOUD_STORAGE_PROVIDER_ID,- label: 'OpenPencil Cloud',- description: 'Workspaces on OpenPencil Cloud or your team’s own server',- preferenceFields: [],- credentialFields: [{ id: CLOUD_SESSION_FIELD, label: 'Session' }],- createAdapter: (runtime) => createCloudStorageAdapter(runtime)-})-export const storageProviderRegistry = new StorageProviderRegistry([S3_STORAGE_PROVIDER,- CLOUD_STORAGE_PROVIDER+ ...CLOUD_STORAGE_PROVIDERS])diff --git a/src/app/shell/menu/save-actions.ts b/src/app/shell/menu/save-actions.tsindex edd894b6a..8e0640c94 100644--- a/src/app/shell/menu/save-actions.ts+++ b/src/app/shell/menu/save-actions.ts@@ -1,5 +1,5 @@-import { openSaveTo } from '@/app/cloud/documents/save'import type { EditorStore } from '@/app/editor/active-store'+import { openSaveTo } from '@/app/storage/save-to/session'export function createSaveMenuActions(store: EditorStore) {return {diff --git a/src/app/storage/save-to/destinations.ts b/src/app/storage/save-to/destinations.tsnew file mode 100644index 000000000..b58ab9328--- /dev/null+++ b/src/app/storage/save-to/destinations.ts@@ -0,0 +1,34 @@+import { cloudSaveDestinations } from '@/app/cloud/integration'+import {+ activeStorageProviderID,+ isStorageConfigured,+ readStoragePreferences+} from '@/app/integrations/storage'++import { saveDestinationKey, type SaveDestination } from './model'++async function bucketDestinations(): Promise<SaveDestination[]> {+ const providerId = activeStorageProviderID.value+ if (!(await isStorageConfigured(providerId))) return []+ const location = { providerId }+ const bucket = readStoragePreferences(providerId).bucket.trim()+ return [+ {+ key: saveDestinationKey(location),+ location,+ label: bucket || providerId,+ kind: 'bucket',+ place: null+ }+ ]+}++/**+ * Everywhere this device can save a document to now. A source that fails to answer, such as a+ * server that is down, leaves out only its own destinations.+ */+export async function listSaveDestinations(): Promise<SaveDestination[]> {+ const sources = [cloudSaveDestinations(), bucketDestinations()]+ const results = await Promise.allSettled(sources)+ return results.flatMap((result) => (result.status === 'fulfilled' ? result.value : []))+}diff --git a/src/app/storage/save-to/model.ts b/src/app/storage/save-to/model.tsnew file mode 100644index 000000000..e7a5ef7fb--- /dev/null+++ b/src/app/storage/save-to/model.ts@@ -0,0 +1,34 @@+import { storageProfileId, type StorageLocation } from '@/app/integrations/storage'++/** A place Save to can put a document: a Cloud workspace or the storage bucket. */+export type SaveDestination = {+ /** Tells destinations apart, as the dialog's choice. */+ key: string+ location: StorageLocation+ /** What the person picks, such as a workspace's or the bucket's name. */+ label: string+ kind: 'workspace' | 'bucket'+ /** The server it is on, which the dialog groups by; the bucket has none. */+ place: { id: string; label: string } | null+ /** The person's role where it varies; a viewer is shown the place but cannot save there. */+ role?: 'viewer' | 'editor' | 'admin'+}++/** The dialog's key for a location: the provider, then the profile and container it names. */+export function saveDestinationKey(location: StorageLocation): string {+ return [location.providerId, storageProfileId(location), location.containerId ?? ''].join('/')+}++export function canSaveTo(destination: SaveDestination): boolean {+ return destination.role !== 'viewer'+}++/** Why a save did not reach its destination. */+export type SaveFailure =+ | { reason: 'too-large'; limitBytes: number }+ | { reason: 'offline' | 'quota' | 'unavailable' }++export type SaveToState =+ | { kind: 'ready' }+ | { kind: 'saving'; sentBytes: number; totalBytes: number }+ | ({ kind: 'error' } & SaveFailure)diff --git a/src/app/storage/save-to/session.ts b/src/app/storage/save-to/session.tsnew file mode 100644index 000000000..633867973--- /dev/null+++ b/src/app/storage/save-to/session.ts@@ -0,0 +1,121 @@+import { useLocalStorage, useOnline } from '@vueuse/core'+import { markRaw, reactive, ref, shallowRef, type Raw } from 'vue'++import { CLOUD_INCLUDED, cloudUploadFailure, signInToSaveTo } from '@/app/cloud/integration'+import type { EditorStore } from '@/app/editor/session'+import { openSettingsDialog } from '@/app/settings/dialog'+import { getLocalCanvasStore } from '@/app/storage/local-store'+import { followUpload } from '@/app/storage/sync'+import { IS_BROWSER } from '@/constants'++import { listSaveDestinations } from './destinations'+import { canSaveTo, type SaveDestination, type SaveFailure, type SaveToState } from './model'+import { writeDocumentTo } from './write'++/** One Save to, from choosing where the document goes until it is there. */+export type SaveToSession = {+ /** Kept raw: the session is reactive, and the store has refs of its own. */+ store: Raw<EditorStore>+ destinations: SaveDestination[]+ name: string+ /** The chosen destination's key. */+ chosen: string+ state: SaveToState+ /** The dialog shows when there is a choice to make, the save is slow, or it failed. */+ open: boolean+ /** Stops following the upload once the person closes the dialog; the upload goes on. */+ following: AbortController+}++/** How long a save with nothing to choose runs before the dialog shows its progress. */+const QUIET_SAVE_MS = 1000++/** The Save to the dialog shows, if any. */+export const saveToSession = shallowRef<SaveToSession | null>(null)++/** The destination saved to last, chosen first next time. */+const lastDestination = IS_BROWSER ? useLocalStorage('open-pencil:save-destination', '') : ref('')+const online = useOnline()++function fail(session: SaveToSession, failure: SaveFailure): void {+ session.state = { kind: 'error', ...failure }+ session.open = true+}++/**+ * Save to: straight to the only place the document can go, or a choice when there are several.+ * With nowhere to save yet, it signs in to the Cloud server this app knows, or opens the settings+ * where a place to save is set up. While a save is on its way, it shows that one instead.+ */+export async function openSaveTo(store: EditorStore): Promise<void> {+ const current = saveToSession.value+ if (current?.state.kind === 'saving' && !current.following.signal.aborted) {+ current.open = true+ return+ }+ const destinations = await listSaveDestinations()+ const writable = destinations.filter(canSaveTo)+ const first = writable.at(0)+ if (!first) {+ if (!signInToSaveTo()) openSettingsDialog(CLOUD_INCLUDED ? 'cloud' : 'storage')+ return+ }+ const last = writable.find((destination) => destination.key === lastDestination.value)+ saveToSession.value = reactive<SaveToSession>({+ store: markRaw(store),+ destinations,+ name: store.state.documentName || 'Untitled',+ chosen: (last ?? first).key,+ state: { kind: 'ready' },+ open: writable.length > 1,+ following: markRaw(new AbortController())+ })+ if (writable.length === 1) await confirmSaveTo()+}++/**+ * Saves the document to the chosen destination and follows its upload until it is there. The tab+ * moves to the saved copy at once; the file it came from is left as it was.+ */+export async function confirmSaveTo(): Promise<void> {+ const session = saveToSession.value+ const destination = session?.destinations.find(({ key }) => key === session.chosen)+ const name = session?.name.trim()+ if (!session || !destination || !canSaveTo(destination) || !name) return+ if (session.state.kind === 'saving') return+ if (!online.value) return fail(session, { reason: 'offline' })++ session.state = { kind: 'saving', sentBytes: 0, totalBytes: 0 }+ const slow = setTimeout(() => {+ session.open = true+ }, QUIET_SAVE_MS)+ try {+ const binding = await writeDocumentTo(session.store, destination.location, name)+ if (!binding) return fail(session, { reason: 'unavailable' })+ lastDestination.value = destination.key+ const meta = await getLocalCanvasStore().getMeta(binding.documentId)+ const totalBytes = meta?.figSize ?? 0+ const outcome = await followUpload(binding.documentId, {+ signal: session.following.signal,+ onProgress: (sent) => {+ session.state = { kind: 'saving', sentBytes: sent * totalBytes, totalBytes }+ }+ })+ if (outcome === 'failed') {+ const failure = await cloudUploadFailure(destination.location, totalBytes)+ return fail(session, failure ?? { reason: 'unavailable' })+ }+ session.state = { kind: 'ready' }+ session.open = false+ } finally {+ clearTimeout(slow)+ }+}++/** Closes the dialog; a save on its way goes on in the background. */+export function closeSaveTo(): void {+ const session = saveToSession.value+ if (!session) return+ session.following.abort()+ session.open = false+}diff --git a/src/app/storage/save-to/write.ts b/src/app/storage/save-to/write.tsnew file mode 100644index 000000000..add3667ca--- /dev/null+++ b/src/app/storage/save-to/write.ts@@ -0,0 +1,26 @@+import type { EditorStore } from '@/app/editor/session'+import type { StorageDocumentBinding, StorageLocation } from '@/app/integrations/storage'+import { rememberRecentStorageDocument } from '@/app/recent-files'++/**+ * Saves the tab's document to a storage location under a new name, and moves the tab to the saved+ * copy, which this device keeps and uploads from then on. Returns the copy, or null when nothing+ * was saved, in which case the tab keeps the name it had. The file it came from is left as it was.+ */+export async function writeDocumentTo(+ store: EditorStore,+ location: StorageLocation,+ name: string+): Promise<StorageDocumentBinding | null> {+ const previousName = store.state.documentName+ store.state.documentName = name+ // Writing this device's copy or queueing its upload can throw rather than answer false.+ const saved = await store.saveFigFileToStorage(location).catch(() => false)+ const binding = saved ? store.getStorageBinding() : null+ if (!binding) {+ store.state.documentName = previousName+ return null+ }+ rememberRecentStorageDocument(binding, name)+ return binding+}diff --git a/src/app/storage/sync/engine.ts b/src/app/storage/sync/engine.tsindex fffb32a11..454d3ba89 100644--- a/src/app/storage/sync/engine.ts+++ b/src/app/storage/sync/engine.ts@@ -17,7 +17,7 @@ import { getLocalCanvasStore } from '@/app/storage/local-store'import { getOutbox } from '@/app/storage/sync/outbox'import { setUploadProgress } from '@/app/storage/sync/progress'import { setPendingSyncCount, setSyncUI } from '@/app/storage/sync/status'-import type { OutboxJob } from '@/app/storage/sync/types'+import { PARKED_ATTEMPT_AT, type OutboxJob } from '@/app/storage/sync/types'import { emitStorageWorkspaceEvent } from '@/app/storage/workspace/events'const MAX_ATTEMPTS = 8@@ -44,7 +44,7 @@ function backoffMs(attempts: number): number {export function nextSyncWakeDelay(jobs: OutboxJob[], now = Date.now()): number | null {if (jobs.length === 0) return nullconst nextAt = Math.min(...jobs.map((job) => job.nextAttemptAt))- return nextAt === Number.MAX_SAFE_INTEGER ? null : Math.max(250, nextAt - now)+ return nextAt === PARKED_ATTEMPT_AT ? null : Math.max(250, nextAt - now)}function isPermanentError(error: unknown): boolean {@@ -186,7 +186,7 @@ async function pumpOnce(): Promise<void> {conflictRevision: error.currentRevision,lastSyncError: null})- await outbox.update({ ...job, nextAttemptAt: Number.MAX_SAFE_INTEGER })+ await outbox.update({ ...job, nextAttemptAt: PARKED_ATTEMPT_AT })const conflicted = await getLocalCanvasStore().getMeta(job.canvasId)if (conflicted) {emitStorageWorkspaceEvent({@@ -201,7 +201,7 @@ async function pumpOnce(): Promise<void> {if (error instanceof StorageUnavailableError) {await outbox.update({...job,- nextAttemptAt: Number.MAX_SAFE_INTEGER+ nextAttemptAt: PARKED_ATTEMPT_AT})setSyncUI('error', message)return@@ -237,7 +237,7 @@ async function pumpOnce(): Promise<void> {await outbox.update({...job,attempts,- nextAttemptAt: Number.MAX_SAFE_INTEGER+ nextAttemptAt: PARKED_ATTEMPT_AT})}returndiff --git a/src/app/storage/sync/follow.ts b/src/app/storage/sync/follow.tsnew file mode 100644index 000000000..fbed9f1fa--- /dev/null+++ b/src/app/storage/sync/follow.ts@@ -0,0 +1,65 @@+import { effectScope, onScopeDispose, watch } from 'vue'++import { getLocalCanvasStore } from '@/app/storage/local-store'+import { getOutbox } from '@/app/storage/sync/outbox'+import { uploadProgressByCanvas } from '@/app/storage/sync/progress'+import { syncUIState } from '@/app/storage/sync/status'+import { isParkedJob } from '@/app/storage/sync/types'+import { onStorageWorkspaceEvent } from '@/app/storage/workspace/events'++/** How following an upload ended: on its storage, stopped for the person, or no longer followed. */+export type UploadOutcome = 'uploaded' | 'failed' | 'stopped'++/** Whether the document is on its storage, waits for the person, or is still on its way. */+async function uploadState(documentId: string): Promise<'uploaded' | 'failed' | null> {+ const meta = await getLocalCanvasStore().getMeta(documentId)+ if (meta?.syncStatus === 'synced') return 'uploaded'+ if (meta?.syncStatus === 'error') return 'failed'+ // The engine parks a job it cannot finish until the person acts, rather than dropping it.+ const jobs = await getOutbox().list()+ return jobs.some((job) => job.canvasId === documentId && isParkedJob(job)) ? 'failed' : null+}++/**+ * Follows a document's upload until it is on its storage or stops for something the person must+ * do, reporting the share sent so far. Aborting `signal` stops following; the upload goes on.+ */+export function followUpload(+ documentId: string,+ options: { onProgress?: (sent: number) => void; signal?: AbortSignal } = {}+): Promise<UploadOutcome> {+ const { onProgress, signal } = options+ if (signal?.aborted) return Promise.resolve('stopped')+ return new Promise((resolve) => {+ const scope = effectScope(true)+ let finished = false+ const finish = (outcome: UploadOutcome) => {+ if (finished) return+ finished = true+ scope.stop()+ resolve(outcome)+ }+ async function check() {+ const state = await uploadState(documentId)+ if (state) finish(state)+ }+ scope.run(() => {+ watch(uploadProgressByCanvas, (progress) => {+ const sent = progress.get(documentId)+ if (sent !== undefined) onProgress?.(sent)+ })+ // Failures move the engine's state without a document event.+ watch(syncUIState, () => void check())+ onScopeDispose(+ onStorageWorkspaceEvent((event) => {+ if (event.documentId === documentId) void check()+ })+ )+ const stop = () => finish('stopped')+ signal?.addEventListener('abort', stop)+ onScopeDispose(() => signal?.removeEventListener('abort', stop))+ })+ // A small file can finish uploading before anything here is watching.+ void check()+ })+}diff --git a/src/app/storage/sync/index.ts b/src/app/storage/sync/index.tsindex fd6d40d5a..d6077bc02 100644--- a/src/app/storage/sync/index.ts+++ b/src/app/storage/sync/index.ts@@ -12,6 +12,7 @@ export {replaceStoredVersion,takeStoredVersion} from './conflicts'+export { followUpload, type UploadOutcome } from './follow'export { createMemoryOutbox, getOutbox, resetOutboxForTests } from './outbox'export {persistStorageCanvasLocally,diff --git a/src/app/storage/sync/types.ts b/src/app/storage/sync/types.tsindex c1ffad814..172cacf8f 100644--- a/src/app/storage/sync/types.ts+++ b/src/app/storage/sync/types.ts@@ -13,6 +13,16 @@ export type OutboxJob = {export type SyncUIState = 'idle' | 'syncing' | 'offline' | 'error'+/**+ * When a job that waits for the person, such as a conflict or storage that refuses it, would run+ * next: never, until something resets it.+ */+export const PARKED_ATTEMPT_AT = Number.MAX_SAFE_INTEGER++export function isParkedJob(job: OutboxJob): boolean {+ return job.nextAttemptAt === PARKED_ATTEMPT_AT+}+/** Pure helper: drop older putCanvas jobs for same canvas when a newer revision is enqueued. */export function supersedePutCanvasJobs(jobs: OutboxJob[],diff --git a/src/components/cloud/CloudHosts.vue b/src/components/cloud/CloudHosts.vuenew file mode 100644index 000000000..38036838a--- /dev/null+++ b/src/components/cloud/CloudHosts.vue@@ -0,0 +1,15 @@+<script setup lang="ts">+import CloudConnectHost from './connect/CloudConnectHost.vue'+import CloudInvitationHost from './invitation/CloudInvitationHost.vue'+import CloudNewWorkspaceHost from './workspace/CloudNewWorkspaceHost.vue'+import CloudWorkspaceMembersHost from './workspace/CloudWorkspaceMembersHost.vue'++/** Cloud's app-wide dialogs: connecting a server, invitations, and managing workspaces. */+</script>++<template>+ <CloudConnectHost />+ <CloudInvitationHost />+ <CloudNewWorkspaceHost />+ <CloudWorkspaceMembersHost />+</template>diff --git a/src/components/cloud/integration/index.ts b/src/components/cloud/integration/index.tsnew file mode 100644index 000000000..42fd05178--- /dev/null+++ b/src/components/cloud/integration/index.ts@@ -0,0 +1,11 @@+/**+ * Every Cloud component the rest of the app shows. A build with `VITE_OPENPENCIL_CLOUD=off`+ * resolves this module to `./off`, where each renders nothing, so Cloud's components stay out of+ * that build; components outside Cloud's folders import Cloud only from here.+ */+export { default as CloudSharedSection } from '@/components/home/cloud/CloudSharedSection.vue'+export { default as CloudWorkspaceSection } from '@/components/home/cloud/CloudWorkspaceSection.vue'+export { default as CloudSettingsSection } from '@/components/settings/cloud/CloudSettingsSection.vue'+export { default as CloudHosts } from '../CloudHosts.vue'+export { default as CloudShareButton } from '../share/CloudShareButton.vue'+export { default as CloudDocumentStatusHost } from '../status/CloudDocumentStatusHost.vue'diff --git a/src/components/cloud/integration/off.ts b/src/components/cloud/integration/off.tsnew file mode 100644index 000000000..687792bbf--- /dev/null+++ b/src/components/cloud/integration/off.ts@@ -0,0 +1,13 @@+import { defineComponent } from 'vue'++/** A Cloud component in a build without Cloud (`VITE_OPENPENCIL_CLOUD=off`): it renders nothing. */+function absent(name: string) {+ return defineComponent({ name, inheritAttrs: false, render: () => null })+}++export const CloudSharedSection = absent('CloudSharedSection')+export const CloudWorkspaceSection = absent('CloudWorkspaceSection')+export const CloudSettingsSection = absent('CloudSettingsSection')+export const CloudHosts = absent('CloudHosts')+export const CloudShareButton = absent('CloudShareButton')+export const CloudDocumentStatusHost = absent('CloudDocumentStatusHost')diff --git a/src/components/cloud/save/CloudSaveDialog.stories.ts b/src/components/cloud/save/CloudSaveDialog.stories.tsdeleted file mode 100644index 3f4d5d931..000000000--- a/src/components/cloud/save/CloudSaveDialog.stories.ts+++ /dev/null@@ -1,64 +0,0 @@-import type { Meta, StoryObj } from '@storybook/vue3-vite'-import { fn } from 'storybook/test'-import { ref } from 'vue'--import CloudSaveDialog from './CloudSaveDialog.vue'-import type { CloudSaveDestination, CloudSaveState } from './types'--type Args = {- destinations: CloudSaveDestination[]- state: CloudSaveState- destination: string- onSave: () => void-}--const official: CloudSaveDestination = {- kind: 'cloud',- serverId: 'official',- host: 'cloud.openpencil.dev',- workspaces: [- { id: 'design', name: 'Design team', role: 'editor' },- { id: 'personal', name: 'Personal', role: 'admin' },- { id: 'brand', name: 'Brand archive', role: 'viewer' }- ]-}-const team: CloudSaveDestination = {- kind: 'cloud',- serverId: 'acme',- host: 'design.acme.internal',- workspaces: [{ id: 'product', name: 'Product', role: 'editor' }]-}-const bucket: CloudSaveDestination = { kind: 'storage', providerId: 's3', label: 'studio-designs' }--const meta = {- title: 'App/Cloud/Save Dialog',- tags: ['autodocs'],- args: {- destinations: [official],- state: { kind: 'ready' },- destination: 'cloud/official/design',- onSave: fn()- },- render: (args) => ({- components: { CloudSaveDialog },- setup: () => ({ args, name: ref('Onboarding flow'), destination: ref(args.destination) }),- template: `- <div class="h-[680px]">- <CloudSaveDialog :open="true" v-model:name="name" v-model:destination="destination" :destinations="args.destinations" :state="args.state" @save="args.onSave" />- </div>`- })-} satisfies Meta<Args>--export default meta-type Story = StoryObj<typeof meta>--export const ChooseWorkspace: Story = {}-export const TwoServers: Story = { args: { destinations: [official, team] } }-export const WorkspaceOrBucket: Story = { args: { destinations: [official, bucket] } }-export const Uploading: Story = {- args: { state: { kind: 'saving', sentBytes: 14.2 * 1024 ** 2, totalBytes: 38.5 * 1024 ** 2 } }-}-export const TooLarge: Story = {- args: { state: { kind: 'error', reason: 'too-large', limitBytes: 256 * 1024 ** 2 } }-}-export const Offline: Story = { args: { state: { kind: 'error', reason: 'offline' } } }diff --git a/src/components/cloud/save/CloudSaveHost.vue b/src/components/cloud/save/CloudSaveHost.vuedeleted file mode 100644index 0cb860ff4..000000000--- a/src/components/cloud/save/CloudSaveHost.vue+++ /dev/null@@ -1,26 +0,0 @@-<script setup lang="ts">-import {- cloudSaveDestination,- cloudSaveDestinations,- cloudSaveName,- cloudSaveOpen,- cloudSaveState,- saveToDestination-} from '@/app/cloud/documents/save'--import CloudSaveDialog from './CloudSaveDialog.vue'--/** The Save to dialog, driven by the app's save flow for whichever tab opened it. */-</script>--<template>- <CloudSaveDialog- v-model:open="cloudSaveOpen"- v-model:name="cloudSaveName"- v-model:destination="cloudSaveDestination"- :destinations="cloudSaveDestinations"- :state="cloudSaveState"- @save="saveToDestination"- @cancel="cloudSaveOpen = false"- />-</template>diff --git a/src/components/cloud/save/types.ts b/src/components/cloud/save/types.tsdeleted file mode 100644index 34c38ba00..000000000--- a/src/components/cloud/save/types.ts+++ /dev/null@@ -1,15 +0,0 @@-/** Where a document can be saved: a server's workspaces, or the storage bucket. */-export type CloudSaveDestination =- | {- kind: 'cloud'- serverId: string- host: string- workspaces: { id: string; name: string; role: 'viewer' | 'editor' | 'admin' }[]- }- | { kind: 'storage'; providerId: string; label: string }--export type CloudSaveState =- | { kind: 'ready' }- | { kind: 'saving'; sentBytes: number; totalBytes: number }- | { kind: 'error'; reason: 'too-large'; limitBytes: number }- | { kind: 'error'; reason: 'quota' | 'offline' | 'unavailable' }diff --git a/src/components/collab-panel/CollabPanel.vue b/src/components/collab-panel/CollabPanel.vueindex 52a41421b..0f8b37209 100644--- a/src/components/collab-panel/CollabPanel.vue+++ b/src/components/collab-panel/CollabPanel.vue@@ -1,9 +1,9 @@<script setup lang="ts">import { computed } from 'vue'-import { isCloudBinding } from '@/app/cloud/documents/status'+import { isCloudBinding } from '@/app/cloud/integration'import { useEditorStore } from '@/app/editor/active-store'-import CloudShareButton from '@/components/cloud/share/CloudShareButton.vue'+import { CloudShareButton } from '@/components/cloud/integration'import CollabAvatarStack from '@/components/collab-panel/CollabAvatarStack.vue'import CollabSharePopover from '@/components/collab-panel/CollabSharePopover.vue'import { provideCollabPanel } from '@/components/collab-panel/context'diff --git a/src/components/home/HomeWorkspace.vue b/src/components/home/HomeWorkspace.vueindex 5f25d66a8..8b6cbbe24 100644--- a/src/components/home/HomeWorkspace.vue+++ b/src/components/home/HomeWorkspace.vue@@ -4,7 +4,7 @@ import { computed, ref, watch } from 'vue'import { useDocumentWorkspace, useI18n, useViewportKind } from '@open-pencil/vue'-import { CLOUD_STORAGE_PROVIDER_ID } from '@/app/cloud/sessions/token'+import { CLOUD_INCLUDED, CLOUD_STORAGE_PROVIDER_ID } from '@/app/cloud/integration'import { useHomeLocations } from '@/app/home/locations'import {activeStorageProviderID,@@ -30,8 +30,7 @@ import { openFileFromPath } from '@/app/shell/menu/use'import { createStoredDocument } from '@/app/storage/workspace/create'import { activeStorageLocation, createStorageWorkspaceSource } from '@/app/storage/workspace/source'import { openStorageDocumentInNewTab } from '@/app/tabs'-import CloudSharedSection from '@/components/home/cloud/CloudSharedSection.vue'-import CloudWorkspaceSection from '@/components/home/cloud/CloudWorkspaceSection.vue'+import { CloudSharedSection, CloudWorkspaceSection } from '@/components/cloud/integration'import DocumentEntry from '@/components/home/document/DocumentEntry.vue'import HomeLayout from '@/components/home/HomeLayout.vue'import HomeSearchActions from '@/components/home/search/HomeSearchActions.vue'@@ -230,6 +229,7 @@ function formattedDate(updatedAt: string): string {<HomeLayout data-test-id="recent-files-home"><template #sidebar><HomeSidebar+ :cloud="CLOUD_INCLUDED":active="places.active.value":account="places.account.value":workspaces="places.workspaces.value"@@ -245,6 +245,7 @@ function formattedDate(updatedAt: string): string {</template><template #locations><HomeLocationMenu+ :cloud="CLOUD_INCLUDED":active="places.active.value":account="places.account.value":workspaces="places.workspaces.value"diff --git a/src/components/home/sidebar/HomeLocationMenu.vue b/src/components/home/sidebar/HomeLocationMenu.vueindex a9e53f884..cf71af924 100644--- a/src/components/home/sidebar/HomeLocationMenu.vue+++ b/src/components/home/sidebar/HomeLocationMenu.vue@@ -27,9 +27,12 @@ const {account = null,workspaces = [],sharedCount = 0,- storage = null+ storage = null,+ cloud = true} = defineProps<{active: HomeLocation+ /** The build has Cloud, so its sign-in and workspaces have a place. */+ cloud?: booleanaccount?: HomeCloudAccount | nullworkspaces?: { id: string; name: string; documentCount?: number; attention?: boolean }[]sharedCount?: number@@ -84,8 +87,8 @@ const isActive = (location: HomeLocation) =>/></DropdownMenuItem>- <DropdownMenuSeparator :class="menuUI.separator()" />- <DropdownMenuGroup>+ <DropdownMenuSeparator v-if="cloud" :class="menuUI.separator()" />+ <DropdownMenuGroup v-if="cloud"><DropdownMenuLabel :class="menuUI.label()">{{ account ? t.homeCloudOnHost({ host: account.host }) : t.productName }}</DropdownMenuLabel>diff --git a/src/components/home/sidebar/HomeSidebar.vue b/src/components/home/sidebar/HomeSidebar.vueindex 9079b3541..8071ff15f 100644--- a/src/components/home/sidebar/HomeSidebar.vue+++ b/src/components/home/sidebar/HomeSidebar.vue@@ -28,9 +28,12 @@ const {account = null,workspaces = [],sharedCount = 0,- storage = null+ storage = null,+ cloud = true} = defineProps<{active: HomeLocation+ /** The build has Cloud, so its sign-in and workspaces have a place. */+ cloud?: booleanaccount?: HomeCloudAccount | nullworkspaces?: { id: string; name: string; documentCount?: number; attention?: boolean }[]sharedCount?: number@@ -75,7 +78,7 @@ const workspaceLocations = computed(() =></button></div>- <div :class="ui.group()">+ <div v-if="cloud" :class="ui.group()"><div :class="ui.header()"><span :class="ui.title()">{{ t.productName }}</span><div v-if="account" :class="ui.actions()">diff --git a/src/components/save-to/SaveToDialog.stories.ts b/src/components/save-to/SaveToDialog.stories.tsnew file mode 100644index 000000000..8fdf0a46d--- /dev/null+++ b/src/components/save-to/SaveToDialog.stories.ts@@ -0,0 +1,79 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { fn } from 'storybook/test'+import { ref } from 'vue'++import SaveToDialog from './SaveToDialog.vue'+import type { SaveDestination, SaveToState } from './types'++type Args = {+ destinations: SaveDestination[]+ state: SaveToState+ destination: string+ onSave: () => void+}++function workspace(+ server: { id: string; label: string },+ id: string,+ label: string,+ role: 'viewer' | 'editor' | 'admin'+): SaveDestination {+ return {+ key: `${server.id}/${id}`,+ location: { providerId: 'openpencil-cloud', profileId: server.id, containerId: id },+ label,+ kind: 'workspace',+ place: server,+ role+ }+}++const officialServer = { id: 'official', label: 'cloud.openpencil.dev' }+const official = [+ workspace(officialServer, 'design', 'Design team', 'editor'),+ workspace(officialServer, 'personal', 'Personal', 'admin'),+ workspace(officialServer, 'brand', 'Brand archive', 'viewer')+]+const team = [+ workspace({ id: 'acme', label: 'design.acme.internal' }, 'product', 'Product', 'editor')+]+const bucket: SaveDestination = {+ key: 's3',+ location: { providerId: 's3-compatible' },+ label: 'studio-designs',+ kind: 'bucket',+ place: null+}++const meta = {+ title: 'App/Save To/Dialog',+ tags: ['autodocs'],+ args: {+ destinations: official,+ state: { kind: 'ready' },+ destination: 'official/design',+ onSave: fn()+ },+ render: (args) => ({+ components: { SaveToDialog },+ setup: () => ({ args, name: ref('Onboarding flow'), destination: ref(args.destination) }),+ template: `+ <div class="h-[680px]">+ <SaveToDialog :open="true" v-model:name="name" v-model:destination="destination" :destinations="args.destinations" :state="args.state" @save="args.onSave" />+ </div>`+ })+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>++export const ChooseWorkspace: Story = {}+export const TwoServers: Story = { args: { destinations: [...official, ...team] } }+export const WorkspaceOrBucket: Story = { args: { destinations: [...official, bucket] } }+export const Uploading: Story = {+ args: { state: { kind: 'saving', sentBytes: 14.2 * 1024 ** 2, totalBytes: 38.5 * 1024 ** 2 } }+}+export const TooLarge: Story = {+ args: { state: { kind: 'error', reason: 'too-large', limitBytes: 256 * 1024 ** 2 } }+}+export const Offline: Story = { args: { state: { kind: 'error', reason: 'offline' } } }diff --git a/src/components/cloud/save/CloudSaveDialog.vue b/src/components/save-to/SaveToDialog.vuesimilarity index 68%rename from src/components/cloud/save/CloudSaveDialog.vuerename to src/components/save-to/SaveToDialog.vueindex 0692694bc..025c162f4 100644--- a/src/components/cloud/save/CloudSaveDialog.vue+++ b/src/components/save-to/SaveToDialog.vue@@ -1,4 +1,5 @@<script setup lang="ts">+import { groupBy } from 'es-toolkit'import { RadioGroupItem, RadioGroupRoot } from 'reka-ui'import { computed } from 'vue'@@ -12,9 +13,9 @@ import AppDialogHeader from '@/components/ui/dialog/AppDialogHeader.vue'import AppDialogRoot from '@/components/ui/dialog/AppDialogRoot.vue'import AppAlert from '@/components/ui/feedback/AppAlert.vue'import AppInput from '@/components/ui/input/AppInput.vue'-import { cloudSave } from '@/theme/cloud/save'+import { saveTo } from '@/theme/save-to'-import type { CloudSaveDestination, CloudSaveState } from './types'+import type { SaveDestination, SaveToState } from './types'/*** Saving a document from this device to a Cloud workspace or the storage bucket, when there is@@ -22,17 +23,17 @@ import type { CloudSaveDestination, CloudSaveState } from './types'* on; the file on this device is left as it was.*/const { destinations, state } = defineProps<{- destinations: CloudSaveDestination[]- state: CloudSaveState+ destinations: SaveDestination[]+ state: SaveToState}>()const open = defineModel<boolean>('open', { default: false })const name = defineModel<string>('name', { default: '' })-/** `cloud/serverId/workspaceId` or `storage/providerId`: the chosen destination. */+/** The chosen destination's key. */const destination = defineModel<string>('destination', { default: '' })const emit = defineEmits<{ save: []; cancel: [] }>()-const ui = cloudSave()+const ui = saveTo()const t = useCloudMessages()const common = useCommonMessages()const saving = computed(() => state.kind === 'saving')@@ -41,6 +42,15 @@ const progress = computed(() =>? Math.round((state.sentBytes / state.totalBytes) * 100): 0)+/** Destinations by the server they are on; the bucket is a group of its own. */+const groups = computed(() =>+ Object.values(groupBy(destinations, (entry) => entry.place?.id ?? '')).map((entries) => ({+ id: entries[0]?.place?.id ?? '',+ label: entries[0]?.place?.label ?? t.value.saveStorageGroup,+ entries+ }))+)+const chosen = computed(() => destinations.find((entry) => entry.key === destination.value))const roles = computed(() => ({viewer: t.value.viewOnly,editor: t.value.roleEditor,@@ -64,41 +74,30 @@ const errors = computed(() => ({<AppDialogBody><fieldset :class="ui.stack()" :disabled="saving"><div :class="ui.field()">- <label for="cloud-save-name" :class="ui.label()">{{ t.saveName }}</label>- <AppInput id="cloud-save-name" v-model="name" />+ <label for="save-to-name" :class="ui.label()">{{ t.saveName }}</label>+ <AppInput id="save-to-name" v-model="name" /></div><div :class="ui.field()">- <span id="cloud-save-destination" :class="ui.label()">{{ t.saveWhere }}</span>+ <span id="save-to-destination" :class="ui.label()">{{ t.saveWhere }}</span><RadioGroupRootv-model="destination"- aria-labelledby="cloud-save-destination"+ aria-labelledby="save-to-destination":class="ui.choices()">- <template- v-for="group in destinations"- :key="group.kind === 'cloud' ? group.serverId : group.providerId"- >- <span v-if="destinations.length > 1" :class="ui.server()">{{- group.kind === 'cloud' ? group.host : t.saveStorageGroup- }}</span>- <template v-if="group.kind === 'cloud'">- <RadioGroupItem- v-for="workspace in group.workspaces"- :key="workspace.id"- :value="`cloud/${group.serverId}/${workspace.id}`"- :disabled="workspace.role === 'viewer'"- :class="ui.choice()"- >- <icon-lucide-layers :class="ui.choiceIcon()" />- <span :class="ui.choiceLabel()">{{ workspace.name }}</span>- <span :class="ui.choiceRole()">{{ roles[workspace.role] }}</span>- <span :class="ui.choiceMark()" aria-hidden="true" />- </RadioGroupItem>- </template>- <RadioGroupItem v-else :value="`storage/${group.providerId}`" :class="ui.choice()">- <icon-lucide-database :class="ui.choiceIcon()" />- <span :class="ui.choiceLabel()">{{ group.label }}</span>+ <template v-for="group in groups" :key="group.id">+ <span v-if="groups.length > 1" :class="ui.server()">{{ group.label }}</span>+ <RadioGroupItem+ v-for="entry in group.entries"+ :key="entry.key"+ :value="entry.key"+ :disabled="entry.role === 'viewer'"+ :class="ui.choice()"+ >+ <icon-lucide-layers v-if="entry.kind === 'workspace'" :class="ui.choiceIcon()" />+ <icon-lucide-database v-else :class="ui.choiceIcon()" />+ <span :class="ui.choiceLabel()">{{ entry.label }}</span>+ <span v-if="entry.role" :class="ui.choiceRole()">{{ roles[entry.role] }}</span><span :class="ui.choiceMark()" aria-hidden="true" /></RadioGroupItem></template>@@ -142,7 +141,7 @@ const errors = computed(() => ({color="primary"variant="solid":loading="saving"- :disabled="!name.trim() || !destination"+ :disabled="!name.trim() || !chosen || chosen.role === 'viewer'"@click="emit('save')">{{ t.saveAction }}diff --git a/src/components/save-to/SaveToHost.vue b/src/components/save-to/SaveToHost.vuenew file mode 100644index 000000000..095144ee2--- /dev/null+++ b/src/components/save-to/SaveToHost.vue@@ -0,0 +1,21 @@+<script setup lang="ts">+import { closeSaveTo, confirmSaveTo, saveToSession } from '@/app/storage/save-to/session'++import SaveToDialog from './SaveToDialog.vue'++/** The Save to dialog, driven by the app's save flow for whichever tab opened it. */+</script>++<template>+ <SaveToDialog+ v-if="saveToSession"+ v-model:name="saveToSession.name"+ v-model:destination="saveToSession.chosen"+ :open="saveToSession.open"+ :destinations="saveToSession.destinations"+ :state="saveToSession.state"+ @update:open="(open) => !open && closeSaveTo()"+ @save="confirmSaveTo"+ @cancel="closeSaveTo"+ />+</template>diff --git a/src/components/save-to/types.ts b/src/components/save-to/types.tsnew file mode 100644index 000000000..eb1e681c9--- /dev/null+++ b/src/components/save-to/types.ts@@ -0,0 +1,2 @@+// The dialog shows what the save flow offers and reports, so it reads the flow's own types.+export type { SaveDestination, SaveToState } from '@/app/storage/save-to/model'diff --git a/src/components/settings/SettingsDialog.vue b/src/components/settings/SettingsDialog.vueindex 53c79b39f..a99c1029a 100644--- a/src/components/settings/SettingsDialog.vue+++ b/src/components/settings/SettingsDialog.vue@@ -5,6 +5,7 @@ import { computed } from 'vue'import { useI18n, useViewportKind } from '@open-pencil/vue'+import { CLOUD_INCLUDED } from '@/app/cloud/integration'import {settingsDialogOpen,registerSettingsNavigation,@@ -12,8 +13,8 @@ import {type SettingsSection} from '@/app/settings/dialog'import { provideSettingsNavigation } from '@/app/settings/navigation/use'+import { CloudSettingsSection } from '@/components/cloud/integration'import ChatSettingsSection from '@/components/settings/chat/ChatSettingsSection.vue'-import CloudSettingsSection from '@/components/settings/cloud/CloudSettingsSection.vue'import DiagnosticsSettingsPanel from '@/components/settings/diagnostics/DiagnosticsSettingsPanel.vue'import GeneralSettingsPanel from '@/components/settings/general/GeneralSettingsPanel.vue'import SettingsPage from '@/components/settings/layout/SettingsPage.vue'@@ -56,7 +57,7 @@ const sections = computed({ value: 'tools', label: settings.value.toolAccess },{ value: 'media', label: settings.value.media },{ value: 'storage', label: settings.value.storage },- { value: 'cloud', label: settings.value.cloud }+ ...(CLOUD_INCLUDED ? [{ value: 'cloud' as const, label: settings.value.cloud }] : [])] satisfies { value: SettingsSection; label: string }[])function onSectionChange(section: string | number): void {@@ -145,7 +146,7 @@ function onOpenChange(open: boolean): void {<template #leading><icon-lucide-database class="size-3.5" /></template>{{ settings.storage }}</AppTabsTrigger>- <AppTabsTrigger value="cloud" data-test-id="settings-section-cloud">+ <AppTabsTrigger v-if="CLOUD_INCLUDED" value="cloud" data-test-id="settings-section-cloud"><template #leading><icon-lucide-cloud class="size-3.5" /></template>{{ settings.cloud }}</AppTabsTrigger>@@ -185,7 +186,7 @@ function onOpenChange(open: boolean): void {<AppTabsContent value="storage" as-child><StorageSettingsPanel /></AppTabsContent>- <AppTabsContent value="cloud" as-child>+ <AppTabsContent v-if="CLOUD_INCLUDED" value="cloud" as-child><CloudSettingsSection /></AppTabsContent></AppTabsRoot>diff --git a/src/components/shell/AppMenu.vue b/src/components/shell/AppMenu.vueindex 1201ffe96..9109b74ac 100644--- a/src/components/shell/AppMenu.vue+++ b/src/components/shell/AppMenu.vue@@ -38,7 +38,7 @@ import {import { appMenuShortcutLabel } from '@/app/shell/menu/shortcut'import { resolvedAppTheme } from '@/app/shell/theme'import BrandMark from '@/components/brand/BrandMark.vue'-import CloudDocumentStatusHost from '@/components/cloud/status/CloudDocumentStatusHost.vue'+import { CloudDocumentStatusHost } from '@/components/cloud/integration'import { useScrollOverflow } from '@/components/shell/useScrollOverflow'import IconButton from '@/components/ui/button/IconButton.vue'import AppShortcutText from '@/components/ui/menu/AppShortcutText.vue'diff --git a/src/theme/cloud/save.ts b/src/theme/save-to.tssimilarity index 91%rename from src/theme/cloud/save.tsrename to src/theme/save-to.tsindex af1158d21..cab725a02 100644--- a/src/theme/cloud/save.ts+++ b/src/theme/save-to.ts@@ -1,7 +1,7 @@import { tv } from 'tailwind-variants'-/** Choosing where on Cloud a document from this device goes. */-export const cloudSave = tv({+/** Choosing where a document from this device goes: a Cloud workspace or the storage bucket. */+export const saveTo = tv({slots: {field: 'flex flex-col gap-1.5',label: 'text-[11px] font-medium text-muted',diff --git a/tests/app/cloud/integration/off.test.ts b/tests/app/cloud/integration/off.test.tsnew file mode 100644index 000000000..5f01d28d0--- /dev/null+++ b/tests/app/cloud/integration/off.test.ts@@ -0,0 +1,29 @@+import { describe, expect, test } from 'bun:test'++import * as cloud from '@/app/cloud/integration'+import * as off from '@/app/cloud/integration/off'+import * as offStorage from '@/app/cloud/integration/off/storage'+import * as storage from '@/app/cloud/integration/storage'+import * as cloudComponents from '@/components/cloud/integration'+import * as offComponents from '@/components/cloud/integration/off'++// A build without Cloud swaps these modules in for the real ones, so they must type as them.+const offServices: typeof cloud = off+const offProviders: typeof storage = offStorage++describe('the build without Cloud', () => {+ test('offers every name the app imports from Cloud', () => {+ expect(Object.keys(off).sort()).toEqual(Object.keys(cloud).sort())+ expect(Object.keys(offStorage).sort()).toEqual(Object.keys(storage).sort())+ expect(Object.keys(offComponents).sort()).toEqual(Object.keys(cloudComponents).sort())+ })++ test('has no Cloud to show, start, or save to', async () => {+ expect(offServices.CLOUD_INCLUDED).toBe(false)+ expect(offProviders.CLOUD_STORAGE_PROVIDERS).toEqual([])+ expect(offServices.isCloudBinding(null)).toBe(false)+ expect(await offServices.cloudSaveDestinations()).toEqual([])+ expect(offServices.signInToSaveTo()).toBe(false)+ expect(offServices.useHomeCloud().signedIn.value).toBe(false)+ })+})diff --git a/tests/app/storage/save-to/session.test.ts b/tests/app/storage/save-to/session.test.tsnew file mode 100644index 000000000..bcbd417ab--- /dev/null+++ b/tests/app/storage/save-to/session.test.ts@@ -0,0 +1,117 @@+import { afterEach, beforeEach, describe, expect, test } from 'bun:test'++import { markRaw, reactive } from 'vue'++import { createEditorStore } from '@/app/editor/session/create'+import type { StorageDocumentBinding, StorageLocation } from '@/app/integrations/storage'+import { createMemoryLocalCanvasStore, type LocalCanvasStore } from '@/app/storage/local-store'+import { resetLocalCanvasStoreForTests } from '@/app/storage/local-store/store'+import type { SaveDestination } from '@/app/storage/save-to/model'+import {+ closeSaveTo,+ confirmSaveTo,+ saveToSession,+ type SaveToSession+} from '@/app/storage/save-to/session'+import { createMemoryOutbox, getOutbox, resetOutboxForTests } from '@/app/storage/sync'+import { PARKED_ATTEMPT_AT } from '@/app/storage/sync/types'++const bucket: SaveDestination = {+ key: 's3-compatible/default/',+ location: { providerId: 's3-compatible' },+ label: 'studio-designs',+ kind: 'bucket',+ place: null+}++let canvases: LocalCanvasStore++beforeEach(() => {+ canvases = createMemoryLocalCanvasStore()+ resetLocalCanvasStoreForTests(canvases)+ resetOutboxForTests(createMemoryOutbox())+})++afterEach(() => {+ saveToSession.value = null+ resetLocalCanvasStoreForTests()+ resetOutboxForTests()+})++/** An editor whose save to storage writes this device's copy as `upload` leaves it. */+function editorSaving(upload: 'uploaded' | 'waiting' | 'parked' | 'throws') {+ const store = createEditorStore()+ store.state.documentName = 'Draft'+ let binding: StorageDocumentBinding | null = null+ Object.assign(store, {+ getStorageBinding: () => binding,+ saveFigFileToStorage: async (location: StorageLocation) => {+ if (upload === 'throws') throw new Error('The device is out of space')+ binding = { ...location, documentId: 'doc' }+ await canvases.writeCanvas({+ ...location,+ id: 'doc',+ name: store.state.documentName,+ figBytes: new Uint8Array(64),+ syncStatus: upload === 'uploaded' ? 'synced' : 'pending'+ })+ if (upload === 'parked') {+ const job = await getOutbox().enqueue({ canvasId: 'doc', type: 'putCanvas', revision: 1 })+ await getOutbox().update({ ...job, nextAttemptAt: PARKED_ATTEMPT_AT })+ }+ return true+ }+ })+ return store+}++function startSession(store: ReturnType<typeof createEditorStore>, name = 'Poster') {+ const session: SaveToSession = reactive({+ store: markRaw(store),+ destinations: [bucket],+ name,+ chosen: bucket.key,+ state: { kind: 'ready' },+ open: true,+ following: markRaw(new AbortController())+ })+ saveToSession.value = session+ return session+}++describe('Save to', () => {+ test('closes once the document is on its storage, under its new name', async () => {+ const store = editorSaving('uploaded')+ const session = startSession(store)+ await confirmSaveTo()+ expect(session.open).toBe(false)+ expect(session.state).toEqual({ kind: 'ready' })+ expect(store.state.documentName).toBe('Poster')+ })++ test('keeps the old name and says so when nothing could be saved', async () => {+ const store = editorSaving('throws')+ const session = startSession(store)+ await confirmSaveTo()+ expect(store.state.documentName).toBe('Draft')+ expect(session.state).toEqual({ kind: 'error', reason: 'unavailable' })+ expect(session.open).toBe(true)+ })++ test('shows a failure when the upload stops for the person', async () => {+ const session = startSession(editorSaving('parked'))+ await confirmSaveTo()+ expect(session.state).toEqual({ kind: 'error', reason: 'unavailable' })+ expect(session.open).toBe(true)+ })++ test('lets the upload go on in the background when the dialog closes', async () => {+ const session = startSession(editorSaving('waiting'))+ const saving = confirmSaveTo()+ while (!(await canvases.getMeta('doc'))) await Bun.sleep(1)+ closeSaveTo()+ await saving+ expect(session.open).toBe(false)+ expect(session.state).toEqual({ kind: 'ready' })+ })+})diff --git a/tests/app/storage/sync/follow.test.ts b/tests/app/storage/sync/follow.test.tsnew file mode 100644index 000000000..090afdff0--- /dev/null+++ b/tests/app/storage/sync/follow.test.ts@@ -0,0 +1,70 @@+import { afterEach, beforeEach, describe, expect, test } from 'bun:test'++import { createMemoryLocalCanvasStore, type LocalCanvasStore } from '@/app/storage/local-store'+import { resetLocalCanvasStoreForTests } from '@/app/storage/local-store/store'+import {+ createMemoryOutbox,+ followUpload,+ getOutbox,+ resetOutboxForTests,+ setUploadProgress+} from '@/app/storage/sync'+import { PARKED_ATTEMPT_AT } from '@/app/storage/sync/types'+import { emitStorageWorkspaceEvent } from '@/app/storage/workspace/events'++let store: LocalCanvasStore++beforeEach(async () => {+ store = createMemoryLocalCanvasStore()+ resetLocalCanvasStoreForTests(store)+ resetOutboxForTests(createMemoryOutbox())+ await store.writeCanvas({+ id: 'doc',+ providerId: 's3-compatible',+ name: 'Poster',+ figBytes: new Uint8Array([1]),+ syncStatus: 'pending'+ })+})++afterEach(() => {+ resetLocalCanvasStoreForTests()+ resetOutboxForTests()+})++function changed() {+ emitStorageWorkspaceEvent({ providerId: 's3-compatible', documentId: 'doc', kind: 'changed' })+}++describe('following an upload', () => {+ test('ends when the document is on its storage, reporting progress on the way', async () => {+ const sent: number[] = []+ const following = followUpload('doc', { onProgress: (share) => sent.push(share) })+ setUploadProgress('doc', 0.5)+ await store.updateMeta('doc', { syncStatus: 'synced' })+ changed()+ expect(await following).toBe('uploaded')+ expect(sent).toEqual([0.5])+ setUploadProgress('doc', null)+ })++ test('ends at once for a document already uploaded', async () => {+ await store.updateMeta('doc', { syncStatus: 'synced' })+ expect(await followUpload('doc')).toBe('uploaded')+ })++ test('fails when the upload waits for the person', async () => {+ const job = await getOutbox().enqueue({ canvasId: 'doc', type: 'putCanvas', revision: 1 })+ const following = followUpload('doc')+ await getOutbox().update({ ...job, nextAttemptAt: PARKED_ATTEMPT_AT })+ changed()+ expect(await following).toBe('failed')+ })++ test('stops following when asked, leaving the upload be', async () => {+ const stop = new AbortController()+ const following = followUpload('doc', { signal: stop.signal })+ stop.abort()+ expect(await following).toBe('stopped')+ })+})diff --git a/tools/checks/cloud-off/package.json b/tools/checks/cloud-off/package.jsonnew file mode 100644index 000000000..716fc2432--- /dev/null+++ b/tools/checks/cloud-off/package.json@@ -0,0 +1,12 @@+{+ "name": "@open-pencil/cloud-off-tools",+ "private": true,+ "type": "module",+ "scripts": {+ "test": "bun test tests"+ },+ "dependencies": {+ "@open-pencil/package-artifacts-tools": "workspace:*",+ "vite": "8.1.4"+ }+}diff --git a/tools/checks/cloud-off/src/index.ts b/tools/checks/cloud-off/src/index.tsnew file mode 100644index 000000000..73b688444--- /dev/null+++ b/tools/checks/cloud-off/src/index.ts@@ -0,0 +1,46 @@+#!/usr/bin/env bun+/**+ * Builds the editor with `VITE_OPENPENCIL_CLOUD=off` and fails when any of OpenPencil Cloud's+ * modules made it into the bundle. The build is not written to disk.+ *+ * bun tools/checks/cloud-off/src/index.ts+ */+import { resolve } from 'node:path'++import { build } from 'vite'++import { resolveWorkspaceRoot } from '@open-pencil/package-artifacts-tools'++import { cloudModulesIn } from './modules'++const repoRoot = await resolveWorkspaceRoot(process.cwd())+process.env.VITE_OPENPENCIL_CLOUD = 'off'++const moduleIds = new Set<string>()+await build({+ root: repoRoot,+ configFile: resolve(repoRoot, 'vite.config.ts'),+ // Vite's default loader cannot run the config under Bun.+ configLoader: 'native',+ logLevel: 'warn',+ build: { write: false },+ plugins: [+ {+ name: 'open-pencil-cloud-off-modules',+ buildEnd() {+ for (const id of this.getModuleIds()) moduleIds.add(id)+ }+ }+ ]+})++const cloud = cloudModulesIn(moduleIds, repoRoot)+if (cloud.length > 0) {+ console.error('The build without Cloud still bundles Cloud modules:')+ for (const path of cloud) console.error(`- ${path}`)+ console.error(+ 'Reach Cloud only through @/app/cloud/integration or @/components/cloud/integration.'+ )+ process.exit(1)+}+console.log(`The build without Cloud bundles none of its modules (${moduleIds.size} modules).`)diff --git a/tools/checks/cloud-off/src/modules.ts b/tools/checks/cloud-off/src/modules.tsnew file mode 100644index 000000000..f88748e85--- /dev/null+++ b/tools/checks/cloud-off/src/modules.ts@@ -0,0 +1,38 @@+/**+ * Which source modules belong to OpenPencil Cloud, so a build without it can show it bundled none.+ * The protocol in `packages/cloud/src/contract` is shared with peer-to-peer rooms and may stay;+ * Cloud's two entry points stand in for it through their `off` modules.+ */+const CLOUD_MODULES = [+ /^packages\/cloud\/src\//,+ /^src\/app\/cloud\//,+ /^src\/app\/collab\/transport\/cloud\.ts$/,+ /^src\/app\/integrations\/storage\/cloud\//,+ /^src\/components\/cloud\//,+ /^src\/components\/home\/cloud\//,+ /^src\/components\/settings\/cloud\//+]++const ALLOWED_MODULES = [+ /^packages\/cloud\/src\/contract\//,+ /^src\/app\/cloud\/integration\/off\//,+ // The storage provider's identifier, which Home and Save to compare locations with.+ /^src\/app\/cloud\/sessions\/token\.ts$/,+ /^src\/components\/cloud\/integration\/off\.ts$/+]++/** The Cloud modules among a build's module IDs, as repository-relative paths. */+export function cloudModulesIn(moduleIds: Iterable<string>, repoRoot: string): string[] {+ const prefix = `${repoRoot.replace(/\/$/, '')}/`+ const found = new Set<string>()+ for (const id of moduleIds) {+ // Vue compiles a component into several virtual modules that share its path.+ const path = id.split('?')[0] ?? id+ if (!path.startsWith(prefix)) continue+ const relative = path.slice(prefix.length)+ if (!CLOUD_MODULES.some((pattern) => pattern.test(relative))) continue+ if (ALLOWED_MODULES.some((pattern) => pattern.test(relative))) continue+ found.add(relative)+ }+ return [...found].sort()+}diff --git a/tools/checks/cloud-off/tests/modules.test.ts b/tools/checks/cloud-off/tests/modules.test.tsnew file mode 100644index 000000000..a5f51e220--- /dev/null+++ b/tools/checks/cloud-off/tests/modules.test.ts@@ -0,0 +1,59 @@+import { describe, expect, test } from 'bun:test'++import { cloudModulesIn } from '../src/modules'++const ROOT = '/repo'++describe('cloudModulesIn', () => {+ test('finds Cloud modules among a build’s modules', () => {+ expect(+ cloudModulesIn(+ [+ '/repo/src/app/cloud/sessions/connection.ts',+ '/repo/src/components/cloud/share/CloudShareButton.vue?vue&type=script&setup=true&lang.ts',+ '/repo/src/components/cloud/share/CloudShareButton.vue',+ '/repo/packages/cloud/src/client/index.ts',+ '/repo/src/app/collab/transport/cloud.ts',+ '/repo/src/components/home/cloud/CloudSharedSection.vue'+ ],+ ROOT+ )+ ).toEqual([+ 'packages/cloud/src/client/index.ts',+ 'src/app/cloud/sessions/connection.ts',+ 'src/app/collab/transport/cloud.ts',+ 'src/components/cloud/share/CloudShareButton.vue',+ 'src/components/home/cloud/CloudSharedSection.vue'+ ])+ })++ test('allows the protocol, the stand-ins, and the provider’s identifier', () => {+ expect(+ cloudModulesIn(+ [+ '/repo/packages/cloud/src/contract/relay.ts',+ '/repo/src/app/cloud/integration/off/index.ts',+ '/repo/src/app/cloud/integration/off/storage.ts',+ '/repo/src/app/cloud/sessions/token.ts',+ '/repo/src/components/cloud/integration/off.ts',+ '/repo/src/app/storage/save-to.ts',+ '/repo/node_modules/vue/index.js',+ '\0virtual:pwa-register'+ ],+ ROOT+ )+ ).toEqual([])+ })++ test('counts the entry points themselves as Cloud', () => {+ expect(+ cloudModulesIn(+ [+ '/repo/src/app/cloud/integration/index.ts',+ '/repo/src/components/cloud/integration/index.ts'+ ],+ ROOT+ )+ ).toEqual(['src/app/cloud/integration/index.ts', 'src/components/cloud/integration/index.ts'])+ })+})diff --git a/vite.config.ts b/vite.config.tsindex b49b53fe3..1159cde99 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -6,7 +6,7 @@ import vue from '@vitejs/plugin-vue'import IconsResolver from 'unplugin-icons/resolver'import Icons from 'unplugin-icons/vite'import Components from 'unplugin-vue-components/vite'-import { defineConfig } from 'vite'+import { defineConfig, loadEnv } from 'vite'import { ensureBrandAssets } from '@open-pencil/brand-tools'import { ensureDemoDocument } from '@open-pencil/demo-tools'@@ -33,10 +33,12 @@ export default defineConfig(async ({ command, mode }) => {// `--mode cloud-portal` builds only the Cloud server's own pages (`cloud.html`), without the// editor, its demo document, CanvasKit, or the PWA.const cloudPortal = mode === 'cloud-portal'+ // `VITE_OPENPENCIL_CLOUD=off` builds the editor without OpenPencil Cloud.+ const cloud = loadEnv(mode, __dirname, 'VITE_').VITE_OPENPENCIL_CLOUD !== 'off'await Promise.all([ensureBrandAssets(['web']), cloudPortal ? undefined : ensureDemoDocument()])return {resolve: {- alias: createOpenPencilAliases(__dirname)+ alias: createOpenPencilAliases(__dirname, { cloud })},define: {__OPENPENCIL_APP_VERSION__: JSON.stringify(packageJson.version),diff --git a/vite/aliases.ts b/vite/aliases.tsindex f40ff0cfa..71bc508ce 100644--- a/vite/aliases.ts+++ b/vite/aliases.ts@@ -1,11 +1,34 @@import { resolve } from 'node:path'-export function createOpenPencilAliases(rootDir: string) {+/**+ * The modules a build without Cloud (`VITE_OPENPENCIL_CLOUD=off`) uses instead of Cloud's two+ * entry points, so nothing else of Cloud is bundled. They precede the `@` alias, which would+ * otherwise resolve these paths first.+ */+function cloudOffAliases(rootDir: string) {+ return [+ {+ find: /^@\/app\/cloud\/integration$/,+ replacement: resolve(rootDir, 'src/app/cloud/integration/off/index.ts')+ },+ {+ find: /^@\/app\/cloud\/integration\/storage$/,+ replacement: resolve(rootDir, 'src/app/cloud/integration/off/storage.ts')+ },+ {+ find: /^@\/components\/cloud\/integration$/,+ replacement: resolve(rootDir, 'src/components/cloud/integration/off.ts')+ }+ ]+}++export function createOpenPencilAliases(rootDir: string, options: { cloud?: boolean } = {}) {const emptyNodeModule = resolve(rootDir, 'vite/empty-node-module.ts')return [{ find: /^fs$/, replacement: emptyNodeModule },{ find: /^path$/, replacement: emptyNodeModule },+ ...(options.cloud === false ? cloudOffAliases(rootDir) : []),{ find: '@', replacement: resolve(rootDir, 'src') },{ find: '#vue', replacement: resolve(rootDir, 'packages/vue/src') },{ find: '#core', replacement: resolve(rootDir, 'packages/core/src') },