diff --git a/AGENTS.md b/AGENTS.md index 08940b0..6df803b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,9 +6,12 @@ Guidance for AI coding agents working on OpenCollab. OpenCollab is a desktop application that centralizes terminal-based AI agents (Claude Code, OpenCode, Codex, Gemini CLI) in a flexible grid for parallel monitoring and real-time collaboration. -- **Workspace:** top-level project container grouping sessions. Managed on the server. +- **Workspace:** top-level project container grouping sessions. Persisted locally in appdata or on the server depending on the desktop storage mode (`local` vs `cloud`). - **Session:** live shared unit displaying multiple terminal panes in a grid. - **Terminal:** single PTY process running an agent profile or shell. +- **Storage modes (desktop):** + - *Local (`appdata`):* workspaces, sessions, and terminal launch profiles (`workspaces.json`) are stored locally on disk via `FsSnapshotStore`. Collaboration controls remain visible in the UI with an inactive state (`data-collab-inactive="true"`), and relay polling is short-circuited. + - *Cloud (`API`):* workspaces, sessions, and terminal launch profiles synchronize with the authenticated NestJS REST API (`CloudSnapshotStore`). Chosen during first-run Onboarding or switched later in Settings (`storage.json`). Switching from Local to Cloud migrates existing local workspaces to the cloud account one workspace at a time while preserving local files on disk. - **Collaboration model:** - *Workspace member:* persistent team access across workspace sessions. View access enabled by default. - *Session guest:* temporary, session-scoped access. @@ -46,7 +49,7 @@ packages/ - **Transitive builds:** build internal dependencies automatically with `pnpm --filter ^... build`. - **Task runner:** Turborepo handles task orchestration (`turbo.json`). - **Prisma:** schema located at `apps/api/prisma/schema.prisma`. Running `pnpm install` automatically triggers `postinstall: prisma generate`. -- **Desktop development:** run `pnpm desktop:dev` from the root (uses `tauri.dev.conf.json` with identifier `dev.opencollab.app.dev` to run alongside production instances without WebView2 lock contention). +- **Development commands:** run `pnpm dev` from the root to start all apps in parallel (`api`, `web`, `desktop`), or run an individual app via `pnpm desktop:dev`, `pnpm api:dev`, or `pnpm web:dev` (every `apps/*` package also exposes `pnpm dev` locally). Desktop development uses `tauri.dev.conf.json` with identifier `com.opencollab.desktop.dev` and deep-link scheme `opencollab-dev://` registered at runtime to run alongside production instances without WebView2 lock or auth redirect contention. ### Verification commands @@ -94,7 +97,7 @@ packages/ ### Authentication and desktop handoff - **Web client:** routes `/login`, `/register`, `/auth/complete`, and `/account`. Stores access token in memory and refresh token in an `httpOnly` cookie (`oc_refresh`). -- **Desktop handoff:** desktop generates PKCE S256 challenge, opens `/login?client=desktop&code_challenge=...`, and web returns authorization code via `opencollab://auth/callback?code=...`. Desktop exchanges code for tokens and keeps credentials strictly in Rust memory. +- **Desktop handoff:** desktop generates PKCE S256 challenge, opens `/login?client=desktop&code_challenge=...`, and web returns authorization code via `opencollab://auth/callback?code=...` (or `opencollab-dev://` in dev). Desktop exchanges code for tokens, keeps the short-lived `access_token` strictly in Rust memory, and persists the rotating `refresh_token` + user profile in the OS credential store (`keyring`: Windows Credential Manager / macOS Keychain / Linux Secret Service, isolated between `opencollab` and `opencollab-dev`). ### UI rules and component guidelines diff --git a/Cargo.lock b/Cargo.lock index 9b7710b..75680fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -537,6 +537,16 @@ dependencies = [ "version_check", ] +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation" version = "0.10.1" @@ -560,7 +570,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" dependencies = [ "bitflags 2.13.2", - "core-foundation", + "core-foundation 0.10.1", "core-graphics-types", "foreign-types", "libc", @@ -573,7 +583,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" dependencies = [ "bitflags 2.13.2", - "core-foundation", + "core-foundation 0.10.1", "libc", ] @@ -700,6 +710,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "dbus-secret-service" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6" +dependencies = [ + "dbus", + "zeroize", +] + [[package]] name = "defmt" version = "1.1.1" @@ -768,6 +788,7 @@ dependencies = [ "application", "domain", "infrastructure", + "keyring", "protocol", "serde", "serde_json", @@ -1816,8 +1837,10 @@ dependencies = [ "application", "domain", "portable-pty", + "serde", "serde_json", "sysinfo", + "ureq", "uuid", ] @@ -1997,6 +2020,21 @@ dependencies = [ "serde", ] +[[package]] +name = "keyring" +version = "3.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c" +dependencies = [ + "byteorder", + "dbus-secret-service", + "log", + "security-framework 2.11.1", + "security-framework 3.7.0", + "windows-sys 0.60.2", + "zeroize", +] + [[package]] name = "lazy_static" version = "1.5.1" @@ -2958,6 +2996,20 @@ dependencies = [ "web-sys", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rust-ini" version = "0.21.3" @@ -2996,6 +3048,41 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -3068,6 +3155,42 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "security-framework" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.9.4", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "selectors" version = "0.38.0" @@ -3267,6 +3390,12 @@ dependencies = [ "stable_deref_trait", ] +[[package]] +name = "sha1_smol" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + [[package]] name = "sha2" version = "0.10.9" @@ -3428,6 +3557,12 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "swift-rs" version = "1.0.8" @@ -3526,7 +3661,7 @@ checksum = "f37f381f4e048e6cdf038b5705f8cf14ad108279d46eb968140a7b291aba9400" dependencies = [ "bitflags 2.13.2", "block2", - "core-foundation", + "core-foundation 0.10.1", "core-graphics", "crossbeam-channel", "dbus", @@ -4221,6 +4356,41 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc" +dependencies = [ + "base64 0.23.1", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + [[package]] name = "url" version = "2.5.8" @@ -4246,6 +4416,12 @@ dependencies = [ "url", ] +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + [[package]] name = "utf8_iter" version = "1.0.4" @@ -4261,6 +4437,7 @@ dependencies = [ "getrandom 0.4.3", "js-sys", "serde_core", + "sha1_smol", "wasm-bindgen", ] @@ -4475,6 +4652,15 @@ dependencies = [ "system-deps", ] +[[package]] +name = "webpki-roots" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "webview2-com" version = "0.39.1" @@ -4677,6 +4863,15 @@ dependencies = [ "windows-targets 0.42.2", ] +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-sys" version = "0.59.0" @@ -4686,6 +4881,15 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -4719,13 +4923,30 @@ dependencies = [ "windows_aarch64_gnullvm 0.52.6", "windows_aarch64_msvc 0.52.6", "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm", + "windows_i686_gnullvm 0.52.6", "windows_i686_msvc 0.52.6", "windows_x86_64_gnu 0.52.6", "windows_x86_64_gnullvm 0.52.6", "windows_x86_64_msvc 0.52.6", ] +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + [[package]] name = "windows-threading" version = "0.2.1" @@ -4756,6 +4977,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + [[package]] name = "windows_aarch64_msvc" version = "0.42.2" @@ -4768,6 +4995,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + [[package]] name = "windows_i686_gnu" version = "0.42.2" @@ -4780,12 +5013,24 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + [[package]] name = "windows_i686_msvc" version = "0.42.2" @@ -4798,6 +5043,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + [[package]] name = "windows_x86_64_gnu" version = "0.42.2" @@ -4810,6 +5061,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + [[package]] name = "windows_x86_64_gnullvm" version = "0.42.2" @@ -4822,6 +5079,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + [[package]] name = "windows_x86_64_msvc" version = "0.42.2" @@ -4834,6 +5097,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + [[package]] name = "winnow" version = "0.5.40" @@ -5062,6 +5331,26 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerotrie" version = "0.2.5" diff --git a/Cargo.toml b/Cargo.toml index f1dd73a..37e9eea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,7 +22,10 @@ protocol = { path = "apps/desktop/core/protocol" } infrastructure = { path = "apps/desktop/core/infrastructure" } # External -uuid = { version = "1", features = ["v4"] } +uuid = { version = "1", features = ["v4", "v5"] } +# Cliente HTTP bloqueante con TLS (modo nube del snapshot): rustls + ring por +# defecto, sin runtime async. +ureq = "3" thiserror = "2" serde = { version = "1", features = ["derive"] } serde_json = "1" @@ -34,3 +37,4 @@ tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } tauri = { version = "2", features = [] } tauri-build = { version = "2", features = [] } +keyring = { version = "3", features = ["apple-native", "windows-native", "sync-secret-service"] } diff --git a/README.md b/README.md index b78b6c6..6266346 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ ### Key features - **Flexible terminal grid:** dynamic panes with accelerated rendering powered by [xterm.js](https://xtermjs.org/) and native PTYs managed in Rust. +- **Dual storage modes (Local & Cloud):** choose during first-run onboarding or anytime in Settings whether to persist workspaces, sessions, and terminal profiles locally in OS appdata (`workspaces.json`) or synchronize them with the Cloud REST API, with automatic local-to-cloud migration when switching to Cloud. - **Intelligent agent detection:** periodic inspection of child processes and direct hooks to detect active agents and report their lifecycle (working, idle, awaiting approval, running tools). - **Real-time collaboration:** - **Workspaces and sessions:** project containers and shared rooms where multiple collaborators observe terminal streams. @@ -130,25 +131,27 @@ docker compose up -d --build ### 4. Run applications in development mode -Run services individually depending on the area you are working on: +Start the entire stack in parallel (API + Web + Desktop Tauri) from the repository root: -#### Desktop (Tauri) ```bash -# Frontend in the browser (Vite) pnpm dev +``` + +Or run each application individually using the `:dev` convention (or `pnpm dev` inside each app directory): -# Native desktop app with an isolated dev profile +#### Desktop (Tauri) +```bash pnpm desktop:dev ``` #### Relay server / API (NestJS) ```bash -pnpm --filter @opencollab/server start:dev +pnpm api:dev ``` #### Web portal (Vite) ```bash -pnpm --filter @opencollab/web dev +pnpm web:dev ``` --- diff --git a/apps/api/package.json b/apps/api/package.json index 11a2621..26d35b1 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -4,6 +4,7 @@ "private": true, "description": "Servidor de colaboración de OpenCollab (relay): autenticación, sesiones compartidas y retransmisión de streams de PTY.", "scripts": { + "dev": "tsx watch --env-file-if-exists=.env --env-file-if-exists=../../.env src/main.ts", "build": "tsc -p tsconfig.build.json", "typecheck": "tsc --noEmit -p tsconfig.json", "start": "node --env-file-if-exists=.env --env-file-if-exists=../../.env dist/main.js", diff --git a/apps/api/prisma/migrations/20261019000000_terminal_agent_minimized/migration.sql b/apps/api/prisma/migrations/20261019000000_terminal_agent_minimized/migration.sql new file mode 100644 index 0000000..adfdff8 --- /dev/null +++ b/apps/api/prisma/migrations/20261019000000_terminal_agent_minimized/migration.sql @@ -0,0 +1,4 @@ +-- Terminal snapshot metadata (S7): which agent a pane launches (null = plain +-- shell) and its collapsed state, so the desktop's cloud snapshot round-trips. +ALTER TABLE "Terminal" ADD COLUMN "agent" TEXT; +ALTER TABLE "Terminal" ADD COLUMN "minimized" BOOLEAN NOT NULL DEFAULT false; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index a9e5da0..0fb2894 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -172,6 +172,10 @@ model Terminal { command String args String[] cwd String? + // Snapshot metadata (S7): which agent the pane launches (null = plain + // shell) and its collapsed state, so the cloud snapshot round-trips fully. + agent String? + minimized Boolean @default(false) // Always written as [] by the repository: env may hold secrets. env Json @default("[]") diff --git a/apps/api/src/auth/auth.controller.ts b/apps/api/src/auth/auth.controller.ts index fc33a88..0c58caf 100644 --- a/apps/api/src/auth/auth.controller.ts +++ b/apps/api/src/auth/auth.controller.ts @@ -273,6 +273,6 @@ export class AuthController { const presented = refreshCookie(cookies); const userId = presented ? await this.auth.sessionUser(presented) : undefined; if (!userId) throw new UnauthorizedException('Invalid session'); - return { redirectUrl: await this.oauth.issueDesktopCode(userId, body.code_challenge) }; + return { redirectUrl: await this.oauth.issueDesktopCode(userId, body.code_challenge, body.client) }; } } diff --git a/apps/api/src/auth/dto.ts b/apps/api/src/auth/dto.ts index 9cb4732..4cedf41 100644 --- a/apps/api/src/auth/dto.ts +++ b/apps/api/src/auth/dto.ts @@ -27,12 +27,15 @@ export const refreshSchema = z.object({ refreshToken: opaque }).strict(); export const desktopTokenSchema = z.object({ code: opaque, codeVerifier: opaque }).strict(); export const desktopCodeSchema = z - .object({ code_challenge: z.string().refine(isValidCodeChallenge, 'invalid code_challenge') }) + .object({ + code_challenge: z.string().refine(isValidCodeChallenge, 'invalid code_challenge'), + client: z.enum(['desktop', 'desktop-dev']).default('desktop'), + }) .strict(); // Query strings are not strict: providers append their own parameters. export const startQuerySchema = z.object({ - client: z.enum(['web', 'desktop']).default('web'), + client: z.enum(['web', 'desktop', 'desktop-dev']).default('web'), code_challenge: z.string().refine(isValidCodeChallenge, 'invalid code_challenge').optional(), }); diff --git a/apps/api/src/auth/oauth.service.ts b/apps/api/src/auth/oauth.service.ts index 8ca0881..9c19c47 100644 --- a/apps/api/src/auth/oauth.service.ts +++ b/apps/api/src/auth/oauth.service.ts @@ -32,6 +32,7 @@ import { pickAvailableUsername, sanitizeUsername } from './username'; export const DESKTOP_CODE_TTL_MS = 60_000; export const DESKTOP_CALLBACK = 'opencollab://auth/callback'; +export const DESKTOP_DEV_CALLBACK = 'opencollab-dev://auth/callback'; /** A provider authorization URL plus the Set-Cookie that binds the flow to this browser. */ export interface FlowStart { @@ -141,15 +142,16 @@ export class OAuthService { return { url, setCookie: setCookie(flow, bindingValue, this.secure) }; } - start(name: string, client: 'web' | 'desktop', codeChallenge?: string): FlowStart { + start(name: string, client: 'web' | 'desktop' | 'desktop-dev', codeChallenge?: string): FlowStart { const provider = this.provider(name); - if (client === 'desktop' && !codeChallenge) { + const isDesktop = client === 'desktop' || client === 'desktop-dev'; + if (isDesktop && !codeChallenge) { throw new BadRequestException('code_challenge is required for the desktop client'); } return this.authorizationUrl(provider, { intent: 'login', client, - ...(client === 'desktop' ? { codeChallenge } : {}), + ...(isDesktop ? { codeChallenge } : {}), }); } @@ -201,8 +203,11 @@ export class OAuthService { if (state.intent === 'link') return this.link(provider, state, profile); const user = await this.resolveUser(provider, profile); - if (state.client === 'desktop') { - return { kind: 'desktop', redirectUrl: await this.issueDesktopCode(user.id, state.codeChallenge ?? '') }; + if (state.client === 'desktop' || state.client === 'desktop-dev') { + return { + kind: 'desktop', + redirectUrl: await this.issueDesktopCode(user.id, state.codeChallenge ?? '', state.client), + }; } return { kind: 'login', result: await this.authService.start(user, userAgent) }; } @@ -284,7 +289,11 @@ export class OAuthService { * the deep link that carries it. Shared by the OAuth desktop flow and by * `POST /auth/desktop/code` (an already authenticated web session). */ - async issueDesktopCode(userId: UserId, codeChallenge: string): Promise { + async issueDesktopCode( + userId: UserId, + codeChallenge: string, + client: 'desktop' | 'desktop-dev' = 'desktop', + ): Promise { const code = generateToken(); await this.auth.insertDesktopCode({ codeHash: hashToken(code), @@ -292,7 +301,8 @@ export class OAuthService { codeChallenge, expiresAt: new Date(this.clock.now().getTime() + DESKTOP_CODE_TTL_MS), }); - return `${DESKTOP_CALLBACK}?code=${encodeURIComponent(code)}`; + const callback = client === 'desktop-dev' ? DESKTOP_DEV_CALLBACK : DESKTOP_CALLBACK; + return `${callback}?code=${encodeURIComponent(code)}`; } /** Any attempt burns the code first, so a wrong verifier cannot be retried. */ diff --git a/apps/api/src/auth/state.spec.ts b/apps/api/src/auth/state.spec.ts index 408434f..817885e 100644 --- a/apps/api/src/auth/state.spec.ts +++ b/apps/api/src/auth/state.spec.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest'; +import { desktopCodeSchema, startQuerySchema } from './dto'; import { STATE_TTL_SECONDS, pkceVerifierFor, signState, verifyState, type OAuthState } from './state'; const secret = 'test-secret-test-secret-test-secret-1234'; @@ -53,3 +54,14 @@ describe('pkceVerifierFor', () => { expect(v).toMatch(/^[A-Za-z0-9_-]{43,128}$/); }); }); + +describe('desktop client schemas', () => { + const challenge = 'A'.repeat(43); + + it('accepts both desktop and desktop-dev in startQuerySchema and desktopCodeSchema', () => { + expect(startQuerySchema.parse({ client: 'desktop', code_challenge: challenge }).client).toBe('desktop'); + expect(startQuerySchema.parse({ client: 'desktop-dev', code_challenge: challenge }).client).toBe('desktop-dev'); + expect(desktopCodeSchema.parse({ code_challenge: challenge }).client).toBe('desktop'); + expect(desktopCodeSchema.parse({ code_challenge: challenge, client: 'desktop-dev' }).client).toBe('desktop-dev'); + }); +}); diff --git a/apps/api/src/auth/state.ts b/apps/api/src/auth/state.ts index e311692..414a327 100644 --- a/apps/api/src/auth/state.ts +++ b/apps/api/src/auth/state.ts @@ -8,7 +8,7 @@ import type { ProviderName } from './oauth-provider'; export interface OAuthState { provider: ProviderName; intent: 'login' | 'link'; - client: 'web' | 'desktop'; + client: 'web' | 'desktop' | 'desktop-dev'; /** Random per flow; also derives the provider-side PKCE verifier. */ nonce: string; /** Random per flow; names the browser-binding cookie so parallel flows do not clash. */ diff --git a/apps/api/src/collab/dto.ts b/apps/api/src/collab/dto.ts index 7bee89b..680f69b 100644 --- a/apps/api/src/collab/dto.ts +++ b/apps/api/src/collab/dto.ts @@ -1,15 +1,32 @@ import { z } from 'zod'; +// The uuid message names the rule, never the submitted value (S14: ZodPipe +// only emits field paths and messages). +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +// Explicit ids are uuids, normalized to lowercase so the same id string always +// matches the same row regardless of the casing the client chose. +function uuidId() { + return z.string().regex(UUID, { message: 'must be a uuid' }).transform((value) => value.toLowerCase()); +} + // `.strict()` everywhere: unknown fields are rejected, not silently dropped. export const createWorkspaceSchema = z - .object({ name: z.string().trim().min(1).max(100) }) + .object({ + name: z.string().trim().min(1).max(100), + // S7: an explicit uuid makes the create idempotent for its owner. + id: uuidId().optional(), + }) .strict(); export type CreateWorkspaceBody = z.infer; // Session name follows the same rule as the workspace name (S4). export const createSessionSchema = z - .object({ name: z.string().trim().min(1).max(100) }) + .object({ + name: z.string().trim().min(1).max(100), + id: uuidId().optional(), + }) .strict(); export type CreateSessionBody = z.infer; @@ -20,19 +37,56 @@ export type CreateSessionBody = z.infer; // blank check does not echo the submitted value (S14). export const addTerminalSchema = z .object({ + id: uuidId().optional(), name: z.string(), command: z.string().refine((value) => value.trim() !== '', { message: 'command must not be blank' }), args: z.array(z.string()).optional(), cwd: z.string().nullable().optional(), + // Snapshot metadata: which agent the pane launches (null = plain shell). + agent: z.string().nullable().optional(), + minimized: z.boolean().optional(), }) .strict(); export type AddTerminalBody = z.infer; -// S9/S10 body. The uuid message names the rule, never the submitted value -// (S14: ZodPipe only emits field paths and messages). -const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +// S7 bodies. Rename is a rename: `name` is required. The terminal patch is +// partial — absent keys keep the current value, null clears `cwd`/`agent`. +export const renameWorkspaceSchema = z + .object({ name: z.string().trim().min(1).max(100) }) + .strict(); + +export type RenameWorkspaceBody = z.infer; + +export const renameSessionSchema = z + .object({ name: z.string().trim().min(1).max(100) }) + .strict(); + +export type RenameSessionBody = z.infer; + +export const updateTerminalSchema = z + .object({ + name: z.string().optional(), + command: z + .string() + .refine((value) => value.trim() !== '', { message: 'command must not be blank' }) + .optional(), + args: z.array(z.string()).optional(), + cwd: z.string().nullable().optional(), + agent: z.string().nullable().optional(), + minimized: z.boolean().optional(), + }) + .strict(); + +export type UpdateTerminalBody = z.infer; + +export const reorderTerminalsSchema = z + .object({ ids: z.array(uuidId()) }) + .strict(); + +export type ReorderTerminalsBody = z.infer; +// S9/S10 body. export const inviteSchema = z .object({ inviteeId: z.string().regex(UUID, { message: 'must be a uuid' }) }) .strict(); diff --git a/apps/api/src/collab/session.service.ts b/apps/api/src/collab/session.service.ts index c9868a6..35de38b 100644 --- a/apps/api/src/collab/session.service.ts +++ b/apps/api/src/collab/session.service.ts @@ -4,6 +4,7 @@ import { newAgentProfile, Session, type SessionId, + type Terminal, type TerminalId, type UserId, type Workspace, @@ -13,7 +14,7 @@ import { import { SessionRepository } from '../persistence/session.repository'; import { WorkspaceRepository } from '../persistence/workspace.repository'; import { toSessionView, toTerminalView, type SessionView, type TerminalView } from './views'; -import type { AddTerminalBody } from './dto'; +import type { AddTerminalBody, ReorderTerminalsBody, UpdateTerminalBody } from './dto'; // `not-found` covers both a missing workspace and a caller with no relation to // it: sessions endpoints must not leak workspace existence (S4/S5). @@ -21,8 +22,12 @@ export type SessionListResult = | { kind: 'ok'; views: SessionView[] } | { kind: 'not-found' }; +// S7: the explicit-id create answers the current view when the caller already +// owns that id (idempotent), and 409 when someone else owns it. export type SessionCreateResult = | { kind: 'created'; view: SessionView } + | { kind: 'existing'; view: SessionView } + | { kind: 'conflict' } | { kind: 'not-found' } | { kind: 'forbidden' }; @@ -33,10 +38,29 @@ export type SessionDetailResult = | { kind: 'not-found' } | { kind: 'forbidden' }; +// S7: rename/delete are owner actions; a non-owner (member, stranger or guest) +// answers 403 without learning whether the session exists. +export type SessionRenameResult = + | { kind: 'ok'; view: SessionView } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +export type SessionRemoveResult = + | { kind: 'removed' } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + // S7/S8: terminal mutations are owner-only; a non-owner never learns whether // a terminal id exists (owner check runs before terminal existence). export type TerminalCreateResult = | { kind: 'created'; view: TerminalView } + | { kind: 'existing'; view: TerminalView } + | { kind: 'conflict' } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +export type TerminalUpdateResult = + | { kind: 'ok'; view: TerminalView } | { kind: 'not-found' } | { kind: 'forbidden' }; @@ -45,6 +69,14 @@ export type TerminalRemoveResult = | { kind: 'not-found' } | { kind: 'forbidden' }; +// The order body is a request-shape rule (S7): exactly the session's +// terminals, no duplicates, no omissions — anything else is 400. +export type TerminalsOrderResult = + | { kind: 'ok'; views: TerminalView[] } + | { kind: 'bad-request' } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + // The loaded session + its workspace, with the owner check already applied. type OwnedSession = | { kind: 'ok'; session: Session; workspace: Workspace } @@ -69,12 +101,33 @@ export class SessionService { return { kind: 'ok', workspace: ws, owner: ws.isOwner(actor) }; } - async create(actor: UserId, workspaceId: WorkspaceId, name: string): Promise { + async create( + actor: UserId, + workspaceId: WorkspaceId, + input: { name: string; id?: string }, + ): Promise { const acc = await this.access(workspaceId, actor); if (acc.kind === 'not-found') return acc; if (!acc.owner) return { kind: 'forbidden' }; + if (input.id !== undefined) { + const existing = await this.sessions.find(input.id as SessionId); + if (existing) { + const existingWorkspace = await this.workspaces.find(existing.workspaceId); + // The session exists: same owner answers its current view (idempotent), + // another owner's id answers conflict. + if (existingWorkspace && existingWorkspace.isOwner(actor)) { + return { kind: 'existing', view: toSessionView(existing) }; + } + return { kind: 'conflict' }; + } + } // `Session.create` re-checks ownership in the domain (ensureOwner). - const session = Session.create(acc.workspace, actor, name); + const session = Session.create( + acc.workspace, + actor, + input.name, + ...(input.id === undefined ? [] : [input.id as SessionId]), + ); await this.sessions.save(session); return { kind: 'created', view: toSessionView(session) }; } @@ -109,6 +162,15 @@ export class SessionService { async addTerminal(actor: UserId, sessionId: SessionId, body: AddTerminalBody): Promise { const acc = await this.ownedSession(sessionId, actor); if (acc.kind !== 'ok') return acc; + if (body.id !== undefined) { + const existing = await this.sessions.terminalWithOwner(body.id as TerminalId); + if (existing) { + // Same owner answers the current terminal (idempotent; the id may even + // live in another session of the same caller); otherwise 409. + if (existing.ownerId !== actor) return { kind: 'conflict' }; + return { kind: 'existing', view: toTerminalView(existing.terminal) }; + } + } // The domain factory copies args/env and enforces a non-blank command; // env is always empty because the strict schema never accepts it (S7). const profile = newAgentProfile(body.name, body.command, { @@ -116,13 +178,78 @@ export class SessionService { ...(body.cwd == null ? {} : { cwd: body.cwd }), }); // `addTerminal` re-checks ownership in the domain (ensureOwner). - const terminalId = acc.session.addTerminal(acc.workspace, actor, profile); + const terminalId = acc.session.addTerminal(acc.workspace, actor, profile, { + ...(body.id === undefined ? {} : { id: body.id as TerminalId }), + ...(body.agent === undefined ? {} : { agent: body.agent }), + ...(body.minimized === undefined ? {} : { minimized: body.minimized }), + }); await this.sessions.save(acc.session); const terminal = acc.session.terminal(terminalId); if (!terminal) throw new Error('terminal vanished after addTerminal'); // unreachable return { kind: 'created', view: toTerminalView(terminal) }; } + async updateTerminal( + actor: UserId, + sessionId: SessionId, + terminalId: TerminalId, + patch: UpdateTerminalBody, + ): Promise { + const acc = await this.ownedSession(sessionId, actor); + if (acc.kind !== 'ok') return acc; + // TerminalNotInSession → 404 (the owner check already ran above). + const terminal = acc.session.terminal(terminalId); + if (!terminal) return { kind: 'not-found' }; + // The domain factory rebuilds the profile, so a blank command stays + // impossible; the schema's blank check already rejected it anyway. + acc.session.updateTerminal(acc.workspace, actor, terminalId, patch); + await this.sessions.save(acc.session); + const updated = acc.session.terminal(terminalId); + if (!updated || !isTerminal(updated)) throw new Error('terminal vanished after updateTerminal'); // unreachable + return { kind: 'ok', view: toTerminalView(updated) }; + } + + // S7: the ids must be exactly the session's terminals — no duplicates, no + // omissions, no strangers — checked before the aggregate is touched. + async reorderTerminals( + actor: UserId, + sessionId: SessionId, + body: ReorderTerminalsBody, + ): Promise { + const acc = await this.ownedSession(sessionId, actor); + if (acc.kind !== 'ok') return acc; + const stored = acc.session.terminals; + const requested = body.ids as TerminalId[]; + const requestedSet = new Set(requested); + if ( + requested.length !== stored.length || + requestedSet.size !== requested.length || + !stored.every((t) => requestedSet.has(t.id)) + ) { + return { kind: 'bad-request' }; + } + // `reorderTerminals` re-checks ownership and membership in the domain. + acc.session.reorderTerminals(acc.workspace, actor, requested); + await this.sessions.save(acc.session); + return { kind: 'ok', views: acc.session.terminals.map(toTerminalView) }; + } + + async renameSession(actor: UserId, sessionId: SessionId, name: string): Promise { + const acc = await this.ownedSession(sessionId, actor); + if (acc.kind !== 'ok') return acc; + // Unreachable NotOwner: the classification above is the same check. + acc.session.rename(acc.workspace, actor, name); + await this.sessions.save(acc.session); + return { kind: 'ok', view: toSessionView(acc.session) }; + } + + async removeSession(actor: UserId, sessionId: SessionId): Promise { + const acc = await this.ownedSession(sessionId, actor); + if (acc.kind !== 'ok') return acc; + await this.sessions.delete(sessionId); + return { kind: 'removed' }; + } + async removeTerminal( actor: UserId, sessionId: SessionId, @@ -137,3 +264,9 @@ export class SessionService { return { kind: 'removed' }; } } + +// The domain mutators replace the terminal object entirely, so the re-read +// requires the metadata-bearing shape; this keeps the unreachable guard typed. +function isTerminal(value: Terminal | undefined): value is Terminal { + return value !== undefined; +} diff --git a/apps/api/src/collab/sessions.controller.int.spec.ts b/apps/api/src/collab/sessions.controller.int.spec.ts index b514b02..e5e83dd 100644 --- a/apps/api/src/collab/sessions.controller.int.spec.ts +++ b/apps/api/src/collab/sessions.controller.int.spec.ts @@ -44,6 +44,8 @@ async function call(method: string, path: string, body?: unknown, token?: string const get = (path: string, token?: string) => call('GET', path, undefined, token); const post = (path: string, body?: unknown, token?: string) => call('POST', path, body ?? {}, token); +const del = (path: string, token?: string) => call('DELETE', path, undefined, token); +const patch = (path: string, body?: unknown, token?: string) => call('PATCH', path, body ?? {}, token); let counter = 0; async function registerUser(prefix = 'user'): Promise<{ id: string; token: string }> { @@ -234,3 +236,144 @@ describe('GET /sessions/:id', () => { expect((await get('/sessions/00000000-0000-0000-0000-000000000000', owner.token)).status).toBe(404); }); }); + +// S7: explicit session ids power the desktop's idempotent cloud round-trip. +describe('POST /workspaces/:workspaceId/sessions with explicit id', () => { + it('creates the session with the caller-provided id (201)', async () => { + const owner = await registerUser(); + const ws = await createWorkspace(owner.token); + const id = '20000000-0000-4000-8000-000000000001'; + + const res = await post(`/workspaces/${ws.id}/sessions`, { name: 'Con id', id }, owner.token); + expect(res.status).toBe(201); + const body = res.body as { id: string; name: string }; + expect(body.id).toBe(id); + expect(body.name).toBe('Con id'); + }); + + it('returns 200 with the current view for a same-owner retry (idempotent)', async () => { + const owner = await registerUser(); + const ws = await createWorkspace(owner.token); + const id = '20000000-0000-4000-8000-000000000002'; + await post(`/workspaces/${ws.id}/sessions`, { name: 'Original', id }, owner.token); + + const res = await post(`/workspaces/${ws.id}/sessions`, { name: 'Original', id }, owner.token); + expect(res.status).toBe(200); + const body = res.body as { id: string; name: string }; + expect(body.id).toBe(id); + expect(body.name).toBe('Original'); + + const list = (await get(`/workspaces/${ws.id}/sessions`, owner.token)).body as { id: string }[]; + expect(list.filter((s) => s.id === id)).toHaveLength(1); + }); + + it('returns 409 for a session id owned by another workspace owner', async () => { + const owner = await registerUser(); + const other = await registerUser(); + const ws = await createWorkspace(owner.token); + const foreign = await createWorkspace(other.token, 'extranjero'); + const taken = ( + await post(`/workspaces/${foreign.id}/sessions`, { name: 'suyo' }, other.token) + ).body as { id: string }; + + const res = await post(`/workspaces/${ws.id}/sessions`, { name: 'mío', id: taken.id }, owner.token); + expect(res.status).toBe(409); + }); + + it('rejects a non-uuid id with 400', async () => { + const owner = await registerUser(); + const ws = await createWorkspace(owner.token); + expect( + (await post(`/workspaces/${ws.id}/sessions`, { name: 'x', id: 'not-a-uuid' }, owner.token)).status, + ).toBe(400); + }); +}); + +// S7: session rename and delete complete the desktop's snapshot reconciliation. +describe('PATCH /sessions/:id', () => { + it('renames for the owner (200 with the current session view)', async () => { + const owner = await registerUser(); + const ws = await createWorkspace(owner.token); + const session = ( + await post(`/workspaces/${ws.id}/sessions`, { name: 'antes' }, owner.token) + ).body as SessionBody; + + const res = await patch(`/sessions/${session.id}`, { name: 'Renombrada' }, owner.token); + expect(res.status).toBe(200); + const body = res.body as SessionBody; + expect(body.id).toBe(session.id); + expect(body.name).toBe('Renombrada'); + expect(body.terminals).toEqual([]); + + const persisted = await sessions.find(session.id as SessionId); + expect(persisted?.name).toBe('Renombrada'); + }); + + it('returns 403 for a member and a stranger, 404 for unknown, 401 unauthenticated', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const stranger = await registerUser(); + const ws = await createWorkspace(owner.token); + await seedMember(ws.id as WorkspaceId, owner.id as UserId, member.id as UserId); + const session = ( + await post(`/workspaces/${ws.id}/sessions`, { name: 'compartida' }, owner.token) + ).body as SessionBody; + const other = await registerUser(); + const otherWs = await createWorkspace(other.token, 'otro'); + + expect((await patch(`/sessions/${session.id}`, { name: 'x' }, member.token)).status).toBe(403); + expect((await patch(`/sessions/${session.id}`, { name: 'x' }, stranger.token)).status).toBe(403); + expect((await patch('/sessions/00000000-0000-0000-0000-000000000000', { name: 'x' }, owner.token)).status).toBe(404); + // A workspace id is not a session id: an unknown session answers 404. + expect((await patch(`/sessions/${otherWs.id}`, { name: 'x' }, owner.token)).status).toBe(404); + expect((await patch(`/sessions/${session.id}`, { name: 'x' })).status).toBe(401); + }); + + it('rejects a blank name with 400', async () => { + const owner = await registerUser(); + const ws = await createWorkspace(owner.token); + const session = ( + await post(`/workspaces/${ws.id}/sessions`, { name: 's' }, owner.token) + ).body as SessionBody; + expect((await patch(`/sessions/${session.id}`, { name: '' }, owner.token)).status).toBe(400); + expect((await patch(`/sessions/${session.id}`, { name: ' ' }, owner.token)).status).toBe(400); + expect((await patch(`/sessions/${session.id}`, { extra: true }, owner.token)).status).toBe(400); + }); +}); + +describe('DELETE /sessions/:id', () => { + it('deletes for the owner (204) and removes its terminals', async () => { + const owner = await registerUser(); + const ws = await createWorkspace(owner.token); + const session = ( + await post(`/workspaces/${ws.id}/sessions`, { name: 'borrar' }, owner.token) + ).body as SessionBody; + await post(`/sessions/${session.id}/terminals`, { name: 't', command: 'sh' }, owner.token); + expect(await t.prisma.terminal.count()).toBe(1); + + const res = await del(`/sessions/${session.id}`, owner.token); + expect(res.status).toBe(204); + + expect(await t.prisma.terminal.count()).toBe(0); + expect((await get(`/sessions/${session.id}`, owner.token)).status).toBe(404); + // The workspace and the parent grouping survive the session delete. + expect(await t.prisma.workspace.count()).toBe(1); + expect((await get(`/workspaces/${ws.id}/sessions`, owner.token)).body).toEqual([]); + }); + + it('returns 403 for a member and a stranger, 404 for unknown, 401 unauthenticated', async () => { + const owner = await registerUser("owner"); + const member = await registerUser(); + const stranger = await registerUser(); + const ws = await createWorkspace(owner.token); + await seedMember(ws.id as WorkspaceId, owner.id as UserId, member.id as UserId); + const session = ( + await post(`/workspaces/${ws.id}/sessions`, { name: 'protegida' }, owner.token) + ).body as SessionBody; + + expect((await del(`/sessions/${session.id}`, member.token)).status).toBe(403); + expect((await del(`/sessions/${session.id}`, stranger.token)).status).toBe(403); + expect((await del('/sessions/00000000-0000-0000-0000-000000000000', owner.token)).status).toBe(404); + expect((await del(`/sessions/${session.id}`)).status).toBe(401); + }); +}); diff --git a/apps/api/src/collab/sessions.controller.ts b/apps/api/src/collab/sessions.controller.ts index f08a2bb..d7e601d 100644 --- a/apps/api/src/collab/sessions.controller.ts +++ b/apps/api/src/collab/sessions.controller.ts @@ -1,13 +1,18 @@ import { Body, + ConflictException, Controller, + Delete, ForbiddenException, Get, HttpCode, + HttpStatus, Inject, NotFoundException, Param, + Patch, Post, + Res, UseGuards, } from '@nestjs/common'; @@ -15,25 +20,40 @@ import type { SessionId, WorkspaceId } from '@opencollab/domain'; import { AccessGuard, CurrentUser } from '../auth/access.guard'; import { ZodPipe } from '../auth/dto'; import type { UserRecord } from '../persistence/user.repository'; -import { createSessionSchema, type CreateSessionBody } from './dto'; +import { + createSessionSchema, + renameSessionSchema, + type CreateSessionBody, + type RenameSessionBody, +} from './dto'; import { SessionService } from './session.service'; +// Status passthrough for the tri-state create (201/200/409): the existing +// @HttpCode annotation cannot express a dynamic code. +interface Reply { + status(code: number): unknown; +} + @Controller() @UseGuards(AccessGuard) export class SessionsController { constructor(@Inject(SessionService) private readonly service: SessionService) {} - // S4: owner creates; member 403; missing workspace or stranger 404. + // S4/S7: only the workspace owner creates sessions (member 403; missing + // workspace or stranger 404). A fresh id answers 201, an id the caller + // already owns answers its current session as 200, a taken id answers 409. @Post('workspaces/:workspaceId/sessions') - @HttpCode(201) async create( @CurrentUser() user: UserRecord, @Param('workspaceId') workspaceId: string, @Body(new ZodPipe(createSessionSchema)) body: CreateSessionBody, - ) { - const result = await this.service.create(user.id, workspaceId as WorkspaceId, body.name); + @Res({ passthrough: true }) reply: Reply, + ): Promise { + const result = await this.service.create(user.id, workspaceId as WorkspaceId, body); if (result.kind === 'not-found') throw new NotFoundException(); if (result.kind === 'forbidden') throw new ForbiddenException(); + if (result.kind === 'conflict') throw new ConflictException(); + reply.status(result.kind === 'created' ? 201 : 200); return result.view; } @@ -53,4 +73,28 @@ export class SessionsController { if (result.kind === 'forbidden') throw new ForbiddenException(); return result.view; } + + // S7: rename answers the session view; non-owners answer 403 without + // learning whether the session exists; unknown sessions 404. + @Patch('sessions/:id') + async rename( + @CurrentUser() user: UserRecord, + @Param('id') id: string, + @Body(new ZodPipe(renameSessionSchema)) body: RenameSessionBody, + ) { + const result = await this.service.renameSession(user.id, id as SessionId, body.name); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + return result.view; + } + + // S7: delete returns 204 with no body and takes the session's terminals + // with it; non-owners answer 403, unknown sessions 404. + @Delete('sessions/:id') + @HttpCode(HttpStatus.NO_CONTENT) + async remove(@CurrentUser() user: UserRecord, @Param('id') id: string) { + const result = await this.service.removeSession(user.id, id as SessionId); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + } } diff --git a/apps/api/src/collab/terminals.controller.int.spec.ts b/apps/api/src/collab/terminals.controller.int.spec.ts index 1fc48e8..458f5d2 100644 --- a/apps/api/src/collab/terminals.controller.int.spec.ts +++ b/apps/api/src/collab/terminals.controller.int.spec.ts @@ -45,6 +45,8 @@ async function call(method: string, path: string, body?: unknown, token?: string const get = (path: string, token?: string) => call('GET', path, undefined, token); const post = (path: string, body?: unknown, token?: string) => call('POST', path, body ?? {}, token); const del = (path: string, token?: string) => call('DELETE', path, undefined, token); +const patch = (path: string, body?: unknown, token?: string) => call('PATCH', path, body ?? {}, token); +const put = (path: string, body?: unknown, token?: string) => call('PUT', path, body ?? {}, token); let counter = 0; async function registerUser(prefix = 'user'): Promise<{ id: string; token: string }> { @@ -76,7 +78,19 @@ async function seedSession(ownerToken: string, name = 'sess'): Promise<{ wsId: s return { wsId: ws.id, sessionId: session.id }; } -type TerminalBody = { id: string; name: string; command: string; args: string[]; cwd: string | null }; +type TerminalBody = { + id: string; + name: string; + command: string; + args: string[]; + cwd: string | null; + agent: string | null; + minimized: boolean; +}; + +// S7: the terminal view the desktop round-trips — exactly seven fields, never +// seq (DOM order bookkeeping) nor env (secrets stay client-side). +const TERMINAL_FIELDS = ['agent', 'args', 'command', 'cwd', 'id', 'minimized', 'name'] as const; describe('POST /sessions/:id/terminals', () => { it('appends a terminal for the owner and exposes it in the session detail (201)', async () => { @@ -219,3 +233,347 @@ describe('DELETE /sessions/:id/terminals/:terminalId', () => { expect((await del(`/sessions/${sessionId}/terminals/${created.id}`)).status).toBe(401); }); }); + +describe('terminal metadata (S7)', () => { + it('accepts agent and minimized and reflects them in the detail', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + + const res = await post( + `/sessions/${sessionId}/terminals`, + { name: 'claude', command: 'claude', agent: 'claude', minimized: true }, + owner.token, + ); + expect(res.status).toBe(201); + expect(res.body).toMatchObject({ agent: 'claude', minimized: true }); + }); + + it('defaults agent to null and minimized to false', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + + const res = await post(`/sessions/${sessionId}/terminals`, { name: 'sh', command: 'sh' }, owner.token); + expect(res.status).toBe(201); + expect(res.body).toMatchObject({ agent: null, minimized: false }); + + const detail = (await get(`/sessions/${sessionId}`, owner.token)).body as { + terminals: TerminalBody[]; + }; + expect(detail.terminals[0]).toMatchObject({ agent: null, minimized: false }); + }); + + it('accepts an explicit null agent', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + + const res = await post( + `/sessions/${sessionId}/terminals`, + { name: 'sh', command: 'sh', agent: null }, + owner.token, + ); + expect(res.status).toBe(201); + expect((res.body as TerminalBody).agent).toBeNull(); + }); + + it('rejects invalid metadata with 400', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const path = `/sessions/${sessionId}/terminals`; + + expect((await post(path, { name: 's', command: 'x', agent: 42 }, owner.token)).status).toBe(400); + expect((await post(path, { name: 's', command: 'x', minimized: 'yes' }, owner.token)).status).toBe(400); + expect((await post(path, { name: 's', command: 'x', seq: 3 }, owner.token)).status).toBe(400); + expect((await post(path, { name: 's', command: 'x', env: [] }, owner.token)).status).toBe(400); + }); +}); + +// S7: explicit terminal ids — idempotent for a same-owner id, conflict otherwise. +describe('POST /sessions/:id/terminals with explicit id', () => { + it('creates the terminal with the caller-provided id (201)', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const id = '30000000-0000-4000-8000-000000000001'; + + const res = await post( + `/sessions/${sessionId}/terminals`, + { name: 'sh', command: 'sh', id }, + owner.token, + ); + expect(res.status).toBe(201); + expect((res.body as TerminalBody).id).toBe(id); + }); + + it('returns 200 with the current terminal for a same-owner retry (idempotent)', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const id = '30000000-0000-4000-8000-000000000002'; + await post( + `/sessions/${sessionId}/terminals`, + { name: 'sh', command: 'sh', id, agent: 'claude', minimized: true }, + owner.token, + ); + + const res = await post(`/sessions/${sessionId}/terminals`, { name: 'sh', command: 'sh', id }, owner.token); + expect(res.status).toBe(200); + // The current stored terminal comes back, not a second terminal. + expect(res.body).toMatchObject({ id, name: 'sh', agent: 'claude', minimized: true }); + expect(await t.prisma.terminal.count()).toBe(1); + }); + + it('returns 409 for a terminal id owned by another user', async () => { + const owner = await registerUser(); + const other = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const otherSession = await seedSession(other.token); + const taken = ( + await post( + `/sessions/${otherSession.sessionId}/terminals`, + { name: 'suyo', command: 'sh' }, + other.token, + ) + ).body as TerminalBody; + + const res = await post( + `/sessions/${sessionId}/terminals`, + { name: 'mío', command: 'sh', id: taken.id }, + owner.token, + ); + expect(res.status).toBe(409); + }); + + it('rejects a non-uuid id with 400', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + expect( + (await post( + `/sessions/${sessionId}/terminals`, + { name: 's', command: 'x', id: 'nope' }, + owner.token, + )).status, + ).toBe(400); + }); +}); + +describe('PATCH /sessions/:id/terminals/:terminalId', () => { + it('patches one field for the owner and keeps the rest (200)', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const created = ( + await post( + `/sessions/${sessionId}/terminals`, + { name: 'sh', command: 'sh', args: ['-l'], cwd: '/tmp', agent: 'claude' }, + owner.token, + ) + ).body as TerminalBody; + + const res = await patch( + `/sessions/${sessionId}/terminals/${created.id}`, + { name: 'renamed' }, + owner.token, + ); + expect(res.status).toBe(200); + expect(res.body).toEqual({ + id: created.id, + name: 'renamed', + command: 'sh', + args: ['-l'], + cwd: '/tmp', + agent: 'claude', + minimized: false, + }); + + const detail = (await get(`/sessions/${sessionId}`, owner.token)).body as { + terminals: TerminalBody[]; + }; + expect(detail.terminals[0]).toEqual(res.body); + }); + + it('clears agent/minimized/cwd with null and toggles minimized', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const created = ( + await post( + `/sessions/${sessionId}/terminals`, + { name: 'claude', command: 'claude', agent: 'claude', minimized: false, cwd: '/tmp' }, + owner.token, + ) + ).body as TerminalBody; + + const res = await patch( + `/sessions/${sessionId}/terminals/${created.id}`, + { agent: null, minimized: true, cwd: null }, + owner.token, + ); + expect(res.status).toBe(200); + expect(res.body).toEqual({ + id: created.id, + name: 'claude', + command: 'claude', + args: [], + cwd: null, + agent: null, + minimized: true, + }); + }); + + it('never accepts seq or env anywhere in the body (S14)', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const created = ( + await post(`/sessions/${sessionId}/terminals`, { name: 'sh', command: 'sh' }, owner.token) + ).body as TerminalBody; + const path = `/sessions/${sessionId}/terminals/${created.id}`; + + expect((await patch(path, { seq: 3 }, owner.token)).status).toBe(400); + expect((await patch(path, { env: [['K', 'V']] }, owner.token)).status).toBe(400); + }); + + it('rejects invalid partial bodies with 400', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const created = ( + await post(`/sessions/${sessionId}/terminals`, { name: 'sh', command: 'sh' }, owner.token) + ).body as TerminalBody; + const path = `/sessions/${sessionId}/terminals/${created.id}`; + + expect((await patch(path, { name: 42 }, owner.token)).status).toBe(400); + expect((await patch(path, { command: ' ' }, owner.token)).status).toBe(400); + expect((await patch(path, { args: 'x' }, owner.token)).status).toBe(400); + expect((await patch(path, { cwd: 7 }, owner.token)).status).toBe(400); + expect((await patch(path, { minimized: 1 }, owner.token)).status).toBe(400); + // An empty patch is a valid no-op. + expect((await patch(path, {}, owner.token)).status).toBe(200); + }); + + it('keeps the existing access matrix', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const stranger = await registerUser(); + const { wsId, sessionId } = await seedSession(owner.token); + await seedMember(wsId as WorkspaceId, owner.id as UserId, member.id as UserId); + const created = ( + await post(`/sessions/${sessionId}/terminals`, { name: 'sh', command: 'sh' }, owner.token) + ).body as TerminalBody; + const path = `/sessions/${sessionId}/terminals/${created.id}`; + + expect((await patch(path, { name: 'x' }, member.token)).status).toBe(403); + // A stranger probing a terminal id of a session they cannot see gets 403, not 404. + expect((await patch(path, { name: 'x' }, stranger.token)).status).toBe(403); + expect( + (await patch( + `/sessions/${sessionId}/terminals/00000000-0000-0000-0000-000000000000`, + { name: 'x' }, + owner.token, + )).status, + ).toBe(404); + expect( + (await patch( + '/sessions/00000000-0000-0000-0000-000000000000/terminals/00000000-0000-0000-0000-000000000000', + { name: 'x' }, + owner.token, + )).status, + ).toBe(404); + expect((await patch(path, { name: 'x' })).status).toBe(401); + }); +}); + +describe('PUT /sessions/:id/terminals/order', () => { + it('applies the new order and returns the terminal views in it (200)', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + for (const [index, id] of [ + '40000000-0000-4000-8000-000000000001', + '40000000-0000-4000-8000-000000000002', + '40000000-0000-4000-8000-000000000003', + ].entries()) { + await post(`/sessions/${sessionId}/terminals`, { name: `t${index}`, command: 'sh', id }, owner.token); + } + const created = ((await get(`/sessions/${sessionId}`, owner.token)).body as { terminals: TerminalBody[] }) + .terminals; + const want = [created[2]!.id, created[0]!.id, created[1]!.id]; + + const res = await put(`/sessions/${sessionId}/terminals/order`, { ids: want }, owner.token); + expect(res.status).toBe(200); + const views = res.body as TerminalBody[]; + expect(views.map((v) => v.id)).toEqual(want); + expect(views.map((v) => v.name)).toEqual(['t2', 't0', 't1']); + + const detail = (await get(`/sessions/${sessionId}`, owner.token)).body as { + terminals: TerminalBody[]; + }; + expect(detail.terminals.map((tm) => tm.id)).toEqual(want); + + // `position` is atomically rewritten to match the array order. + const rows = await t.prisma.terminal.findMany({ where: { sessionId }, orderBy: { position: 'asc' } }); + expect(rows.map((r) => r.id)).toEqual(want); + expect(rows.map((r) => r.position)).toEqual([0, 1, 2]); + }); + + it('returns 400 for duplicates, an omission or an unknown id', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const first = ( + await post(`/sessions/${sessionId}/terminals`, { name: 'a', command: 'sh' }, owner.token) + ).body as TerminalBody; + const second = ( + await post(`/sessions/${sessionId}/terminals`, { name: 'b', command: 'sh' }, owner.token) + ).body as TerminalBody; + const path = `/sessions/${sessionId}/terminals/order`; + + expect((await put(path, { ids: [first.id, first.id] }, owner.token)).status).toBe(400); + expect((await put(path, { ids: [first.id] }, owner.token)).status).toBe(400); + expect( + (await put(path, { ids: ['40000000-0000-4000-8000-000000009999'] }, owner.token)).status, + ).toBe(400); + expect( + (await put( + path, + { ids: [first.id, second.id, '40000000-0000-4000-8000-000000009999'] }, + owner.token, + )).status, + ).toBe(400); + expect((await put(path, { ids: [] }, owner.token)).status).toBe(400); + expect((await put(path, { ids: [first.id], extra: true }, owner.token)).status).toBe(400); + expect((await put(path, { ids: 'a,b' }, owner.token)).status).toBe(400); + }); + + it('keeps the existing access matrix', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const stranger = await registerUser(); + const { wsId, sessionId } = await seedSession(owner.token); + await seedMember(wsId as WorkspaceId, owner.id as UserId, member.id as UserId); + const created = ( + await post(`/sessions/${sessionId}/terminals`, { name: 'sh', command: 'sh' }, owner.token) + ).body as TerminalBody; + const path = `/sessions/${sessionId}/terminals/order`; + + expect((await put(path, { ids: [created.id] }, member.token)).status).toBe(403); + expect((await put(path, { ids: [created.id] }, stranger.token)).status).toBe(403); + expect( + (await put('/sessions/00000000-0000-0000-0000-000000000000/terminals/order', { ids: [] }, owner.token)) + .status, + ).toBe(404); + expect((await put(path, { ids: [created.id] })).status).toBe(401); + }); +}); + +describe('terminal view shape (additive, never seq/env)', () => { + it('exposes exactly the seven snapshot fields', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const res = await post( + `/sessions/${sessionId}/terminals`, + { name: 'sh', command: 'sh', agent: 'claude', minimized: true }, + owner.token, + ); + expect(Object.keys(res.body as object).sort()).toEqual([...TERMINAL_FIELDS]); + + const detail = (await get(`/sessions/${sessionId}`, owner.token)).body as { + terminals: TerminalBody[]; + }; + expect(Object.keys(detail.terminals[0] as object).sort()).toEqual([...TERMINAL_FIELDS]); + expect(JSON.stringify(detail)).not.toContain('"seq"'); + expect(JSON.stringify(detail)).not.toContain('"env"'); + }); +}); diff --git a/apps/api/src/collab/terminals.controller.ts b/apps/api/src/collab/terminals.controller.ts index 921ec1d..a069f07 100644 --- a/apps/api/src/collab/terminals.controller.ts +++ b/apps/api/src/collab/terminals.controller.ts @@ -1,5 +1,7 @@ import { + BadRequestException, Body, + ConflictException, Controller, Delete, ForbiddenException, @@ -7,7 +9,10 @@ import { Inject, NotFoundException, Param, + Patch, Post, + Put, + Res, UseGuards, } from '@nestjs/common'; @@ -15,28 +20,84 @@ import type { SessionId, TerminalId } from '@opencollab/domain'; import { AccessGuard, CurrentUser } from '../auth/access.guard'; import { ZodPipe } from '../auth/dto'; import type { UserRecord } from '../persistence/user.repository'; -import { addTerminalSchema, type AddTerminalBody } from './dto'; +import { + addTerminalSchema, + reorderTerminalsSchema, + updateTerminalSchema, + type AddTerminalBody, + type ReorderTerminalsBody, + type UpdateTerminalBody, +} from './dto'; import { SessionService } from './session.service'; +// Status passthrough for the tri-state create (201/200/409): the existing +// @HttpCode annotation cannot express a dynamic code. +interface Reply { + status(code: number): unknown; +} + @Controller() @UseGuards(AccessGuard) export class TerminalsController { constructor(@Inject(SessionService) private readonly service: SessionService) {} - // S7: owner only; 403 for anyone else, 404 for an unknown session. + // S7: owner only; 403 for anyone else, 404 for an unknown session. A fresh + // id answers 201, an id the caller already owns answers its current + // terminal as 200 (idempotent), and a taken id answers 409. @Post('sessions/:id/terminals') - @HttpCode(201) async create( @CurrentUser() user: UserRecord, @Param('id') id: string, @Body(new ZodPipe(addTerminalSchema)) body: AddTerminalBody, - ) { + @Res({ passthrough: true }) reply: Reply, + ): Promise { const result = await this.service.addTerminal(user.id, id as SessionId, body); if (result.kind === 'not-found') throw new NotFoundException(); if (result.kind === 'forbidden') throw new ForbiddenException(); + if (result.kind === 'conflict') throw new ConflictException(); + reply.status(result.kind === 'created' ? 201 : 200); + return result.view; + } + + // S7: partial update answers the new terminal view; non-owners answer 403 + // without learning whether the session or terminal exists; unknown sessions, + // sessions missing the terminal, or unknown terminals 404. + @Patch('sessions/:id/terminals/:terminalId') + async update( + @CurrentUser() user: UserRecord, + @Param('id') id: string, + @Param('terminalId') terminalId: string, + @Body(new ZodPipe(updateTerminalSchema)) body: UpdateTerminalBody, + ) { + const result = await this.service.updateTerminal( + user.id, + id as SessionId, + terminalId as TerminalId, + body, + ); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); return result.view; } + // S7: the ids must be exactly the session's terminals; order requests that + // duplicate, omit or add ids answer 400 without touching stored state. + @Put('sessions/:id/terminals/order') + async reorder( + @CurrentUser() user: UserRecord, + @Param('id') id: string, + @Body(new ZodPipe(reorderTerminalsSchema)) body: ReorderTerminalsBody, + ) { + const result = await this.service.reorderTerminals(user.id, id as SessionId, body); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + if (result.kind === 'bad-request') { + // The rule is the message; the submitted ids never echo back. + throw new BadRequestException('order must contain exactly the session terminals'); + } + return result.views; + } + // S8: owner only; 204 on success, 404 for unknown session or terminal, // 403 for anyone else (terminal existence stays hidden from non-owners). @Delete('sessions/:id/terminals/:terminalId') diff --git a/apps/api/src/collab/views.ts b/apps/api/src/collab/views.ts index eff6a73..4c79aed 100644 --- a/apps/api/src/collab/views.ts +++ b/apps/api/src/collab/views.ts @@ -31,6 +31,10 @@ export interface TerminalView { command: string; args: string[]; cwd: string | null; + // Snapshot metadata (S7): which agent the pane launches, and its collapsed + // state. Always present over the wire; never `seq` or `env` (S7/A1). + agent: string | null; + minimized: boolean; } export interface SessionView { @@ -48,6 +52,8 @@ export function toTerminalView(terminal: Terminal): TerminalView { command: terminal.profile.command, args: terminal.profile.args, cwd: terminal.profile.cwd ?? null, + agent: terminal.agent ?? null, + minimized: terminal.minimized ?? false, }; } diff --git a/apps/api/src/collab/workspace.service.ts b/apps/api/src/collab/workspace.service.ts index 4885111..576069c 100644 --- a/apps/api/src/collab/workspace.service.ts +++ b/apps/api/src/collab/workspace.service.ts @@ -11,6 +11,25 @@ export type WorkspaceLookup = | { kind: 'not-found' } | { kind: 'forbidden' }; +// S7: the explicit-id create answers the current view when the caller already +// owns that id (idempotent), and 409 when someone else owns it. +export type WorkspaceCreateResult = + | { kind: 'created'; view: WorkspaceDetail } + | { kind: 'existing'; view: WorkspaceDetail } + | { kind: 'conflict' }; + +// Rename/remove are owner actions: a member who can read still answers 403, +// with the same not-found/forbidden classification as GET detail. +export type WorkspaceRenameResult = + | { kind: 'ok'; view: WorkspaceDetail } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +export type WorkspaceRemoveResult = + | { kind: 'removed' } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + @Injectable() export class WorkspaceService { constructor( @@ -18,10 +37,17 @@ export class WorkspaceService { @Inject(UserRepository) private readonly users: UserRepository, ) {} - async create(actor: UserId, name: string): Promise { - const ws = new Workspace(actor, name); + async create(actor: UserId, input: { name: string; id?: string }): Promise { + if (input.id !== undefined) { + const existing = await this.workspaces.find(input.id as WorkspaceId); + if (existing) { + if (!existing.isOwner(actor)) return { kind: 'conflict' }; + return { kind: 'existing', view: await this.detail(existing) }; + } + } + const ws = new Workspace(actor, input.name, ...(input.id === undefined ? [] : [input.id as WorkspaceId])); await this.workspaces.save(ws); - return this.detail(ws); + return { kind: 'created', view: await this.detail(ws) }; } async listFor(actor: UserId): Promise { @@ -38,6 +64,30 @@ export class WorkspaceService { return { kind: 'ok', workspace: ws }; } + // Mutations are owner actions: members who can read still answer 403. + private async owned(id: WorkspaceId, actor: UserId): Promise { + const ws = await this.workspaces.find(id); + if (!ws) return { kind: 'not-found' }; + if (!ws.isOwner(actor)) return { kind: 'forbidden' }; + return { kind: 'ok', workspace: ws }; + } + + async rename(actor: UserId, id: WorkspaceId, name: string): Promise { + const owned = await this.owned(id, actor); + if (owned.kind !== 'ok') return owned; + // Unreachable NotOwner: the classification above is the same check. + owned.workspace.rename(actor, name); + await this.workspaces.save(owned.workspace); + return { kind: 'ok', view: await this.detail(owned.workspace) }; + } + + async remove(actor: UserId, id: WorkspaceId): Promise { + const owned = await this.owned(id, actor); + if (owned.kind !== 'ok') return owned; + await this.workspaces.delete(id); + return { kind: 'removed' }; + } + async detail(ws: Workspace): Promise { const ids = [ws.owner, ...ws.members.map((m) => m.userId)]; const users = await this.users.findByIds(ids); diff --git a/apps/api/src/collab/workspaces.controller.int.spec.ts b/apps/api/src/collab/workspaces.controller.int.spec.ts index 194a2dd..6aa417b 100644 --- a/apps/api/src/collab/workspaces.controller.int.spec.ts +++ b/apps/api/src/collab/workspaces.controller.int.spec.ts @@ -42,6 +42,8 @@ async function call(method: string, path: string, body?: unknown, token?: string const get = (path: string, token?: string) => call('GET', path, undefined, token); const post = (path: string, body?: unknown, token?: string) => call('POST', path, body ?? {}, token); +const del = (path: string, token?: string) => call('DELETE', path, undefined, token); +const patch = (path: string, body?: unknown, token?: string) => call('PATCH', path, body ?? {}, token); let counter = 0; async function registerUser(prefix = 'user'): Promise<{ id: string; token: string }> { @@ -151,3 +153,123 @@ describe('GET /workspaces/:id', () => { expect((await get(`/workspaces/${ws.id}`, stranger.token)).status).toBe(403); }); }); + +// S7: explicit ids let the desktop create idempotently (cloud round-trip). +describe('POST /workspaces with explicit id', () => { + it('creates the workspace with the caller-provided id (201)', async () => { + const owner = await registerUser(); + const id = '10000000-0000-4000-8000-000000000001'; + const res = await post('/workspaces', { name: 'Con id', id }, owner.token); + expect(res.status).toBe(201); + const body = res.body as { id: string; name: string; owner: string }; + expect(body.id).toBe(id); + expect(body.name).toBe('Con id'); + expect(body.owner).toBe(owner.id); + }); + + it('returns 200 with the current view for a same-owner retry (idempotent)', async () => { + const owner = await registerUser(); + const id = '10000000-0000-4000-8000-000000000002'; + await post('/workspaces', { name: 'Original', id }, owner.token); + + const res = await post('/workspaces', { name: 'Original', id }, owner.token); + expect(res.status).toBe(200); + const body = res.body as { id: string; name: string; owner: string }; + expect(body.id).toBe(id); + expect(body.name).toBe('Original'); + // The retry created nothing extra. + const list = (await get('/workspaces', owner.token)).body as { id: string }[]; + expect(list.filter((w) => w.id === id)).toHaveLength(1); + }); + + it('returns 409 for another owner\'s id', async () => { + const first = await registerUser(); + const second = await registerUser(); + const taken = (await post('/workspaces', { name: 'mine' }, first.token)).body as { id: string }; + + const res = await post('/workspaces', { name: 'other', id: taken.id }, second.token); + expect(res.status).toBe(409); + }); + + it('rejects a non-uuid id with 400', async () => { + const owner = await registerUser(); + const res = await post('/workspaces', { name: 'x', id: 'not-a-uuid' }, owner.token); + expect(res.status).toBe(400); + }); +}); + +// S7: rename is an owner action behind the same classification as GET detail. +describe('PATCH /workspaces/:id', () => { + it('renames for the owner (200 with the current detail view)', async () => { + const owner = await registerUser(); + const wsId = await seedWorkspaceWithMember(owner.id as UserId, (await registerUser()).id as UserId, 'antes'); + + const res = await patch(`/workspaces/${wsId}`, { name: 'Renombrado' }, owner.token); + expect(res.status).toBe(200); + const body = res.body as { id: string; name: string; owner: string; members: unknown[] }; + expect(body.id).toBe(wsId); + expect(body.name).toBe('Renombrado'); + expect(body.owner).toBe(owner.id); + expect(body.members).toHaveLength(1); + + const persisted = await workspaces.find(wsId); + expect(persisted?.name).toBe('Renombrado'); + }); + + it('returns 403 for a member and a stranger, 404 for unknown, 401 unauthenticated', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const stranger = await registerUser(); + const wsId = await seedWorkspaceWithMember(owner.id as UserId, member.id as UserId, 'privado'); + const ws = (await post('/workspaces', { name: 'hidden' }, owner.token)).body as { id: string }; + + expect((await patch(`/workspaces/${wsId}`, { name: 'x' }, member.token)).status).toBe(403); + expect((await patch(`/workspaces/${wsId}`, { name: 'x' }, stranger.token)).status).toBe(403); + // A member only got read access; the name they can see cannot be changed by them. + const memberRead = await get(`/workspaces/${wsId}`, member.token); + expect(memberRead.status).toBe(200); + expect((await patch(`/workspaces/${ws.id}`, { name: 'y' }, stranger.token)).status).toBe(403); + expect((await patch('/workspaces/00000000-0000-0000-0000-000000000000', { name: 'y' }, owner.token)).status).toBe(404); + expect((await patch(`/workspaces/${wsId}`, { name: 'y' })).status).toBe(401); + }); + + it('rejects a blank name with 400', async () => { + const owner = await registerUser(); + const ws = (await post('/workspaces', { name: 'x' }, owner.token)).body as { id: string }; + expect((await patch(`/workspaces/${ws.id}`, { name: '' }, owner.token)).status).toBe(400); + expect((await patch(`/workspaces/${ws.id}`, { name: ' ' }, owner.token)).status).toBe(400); + expect((await patch(`/workspaces/${ws.id}`, { extra: true }, owner.token)).status).toBe(400); + }); +}); + +describe('DELETE /workspaces/:id', () => { + it('deletes for the owner (204) and cascades sessions and terminals', async () => { + const owner = await registerUser(); + const wsId = (await post('/workspaces', { name: 'borrar' }, owner.token)).body as { id: string }; + const session = ( + await post(`/workspaces/${wsId.id}/sessions`, { name: 's' }, owner.token) + ).body as { id: string }; + await post(`/sessions/${session.id}/terminals`, { name: 't', command: 'sh' }, owner.token); + expect(await t.prisma.terminal.count()).toBe(1); + + const res = await del(`/workspaces/${wsId.id}`, owner.token); + expect(res.status).toBe(204); + + expect(await t.prisma.workspace.count()).toBe(0); + expect(await t.prisma.session.count()).toBe(0); + expect(await t.prisma.terminal.count()).toBe(0); + expect((await get(`/workspaces/${wsId.id}`, owner.token)).status).toBe(404); + }); + + it('returns 403 for a member and a stranger, 404 for unknown, 401 unauthenticated', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const stranger = await registerUser(); + const wsId = await seedWorkspaceWithMember(owner.id as UserId, member.id as UserId, 'protegido'); + + expect((await del(`/workspaces/${wsId}`, member.token)).status).toBe(403); + expect((await del(`/workspaces/${wsId}`, stranger.token)).status).toBe(403); + expect((await del('/workspaces/00000000-0000-0000-0000-000000000000', owner.token)).status).toBe(404); + expect((await del(`/workspaces/${wsId}`)).status).toBe(401); + }); +}); diff --git a/apps/api/src/collab/workspaces.controller.ts b/apps/api/src/collab/workspaces.controller.ts index d6c9186..d03a83e 100644 --- a/apps/api/src/collab/workspaces.controller.ts +++ b/apps/api/src/collab/workspaces.controller.ts @@ -1,13 +1,18 @@ import { Body, + ConflictException, Controller, + Delete, ForbiddenException, Get, HttpCode, + HttpStatus, Inject, NotFoundException, Param, + Patch, Post, + Res, UseGuards, } from '@nestjs/common'; @@ -15,21 +20,37 @@ import type { WorkspaceId } from '@opencollab/domain'; import { AccessGuard, CurrentUser } from '../auth/access.guard'; import { ZodPipe } from '../auth/dto'; import type { UserRecord } from '../persistence/user.repository'; -import { createWorkspaceSchema, type CreateWorkspaceBody } from './dto'; +import { + createWorkspaceSchema, + renameWorkspaceSchema, + type CreateWorkspaceBody, + type RenameWorkspaceBody, +} from './dto'; import { WorkspaceService } from './workspace.service'; +// Status passthrough for the tri-state create (201/200/409): the existing +// @HttpCode annotation cannot express a dynamic code. +interface Reply { + status(code: number): unknown; +} + @Controller('workspaces') @UseGuards(AccessGuard) export class WorkspacesController { constructor(@Inject(WorkspaceService) private readonly service: WorkspaceService) {} + // S7: a fresh id answers 201, an id the caller already owns answers its + // current view as 200 (idempotent), and a taken id answers 409. @Post() - @HttpCode(201) - create( + async create( @CurrentUser() user: UserRecord, @Body(new ZodPipe(createWorkspaceSchema)) body: CreateWorkspaceBody, - ) { - return this.service.create(user.id, body.name); + @Res({ passthrough: true }) reply: Reply, + ): Promise { + const result = await this.service.create(user.id, body); + if (result.kind === 'conflict') throw new ConflictException(); + reply.status(result.kind === 'created' ? 201 : 200); + return result.view; } @Get() @@ -44,4 +65,28 @@ export class WorkspacesController { if (result.kind === 'forbidden') throw new ForbiddenException(); return this.service.detail(result.workspace); } + + // S7: rename answers the detail view; members and strangers answer 403, + // unknown workspaces 404 — same classification as GET detail. + @Patch(':id') + async rename( + @CurrentUser() user: UserRecord, + @Param('id') id: string, + @Body(new ZodPipe(renameWorkspaceSchema)) body: RenameWorkspaceBody, + ) { + const result = await this.service.rename(user.id, id as WorkspaceId, body.name); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + return result.view; + } + + // S7: delete returns 204 with no body; members and strangers answer 403, + // unknown workspaces 404. + @Delete(':id') + @HttpCode(HttpStatus.NO_CONTENT) + async remove(@CurrentUser() user: UserRecord, @Param('id') id: string) { + const result = await this.service.remove(user.id, id as WorkspaceId); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + } } diff --git a/apps/api/src/persistence/session.repository.int.spec.ts b/apps/api/src/persistence/session.repository.int.spec.ts index 07ade34..2ddaffb 100644 --- a/apps/api/src/persistence/session.repository.int.spec.ts +++ b/apps/api/src/persistence/session.repository.int.spec.ts @@ -1,6 +1,6 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; -import { Session, Workspace, newAgentProfile, newSessionId } from '@opencollab/domain'; +import { Session, Workspace, newAgentProfile, newSessionId, newTerminalId } from '@opencollab/domain'; import type { PrismaClient } from '../generated/prisma/client'; import { SessionRepository } from './session.repository'; import { openTestClient, truncateAll } from './test-db'; @@ -130,4 +130,47 @@ describe('SessionRepository', () => { const listed = await sessions.listByWorkspace(f.workspace.id); expect(listed.map((s) => s.id).sort()).toEqual([f.session.id, second.id].sort()); }); + + // S7: agent and minimized round-trip through the cloud snapshot too. + it('round-trips terminal agent and minimized metadata', async () => { + const f = await fixture(); + const withMeta = f.session.addTerminal( + f.workspace, + f.owner, + newAgentProfile('claude', 'claude'), + { agent: 'claude', minimized: true }, + ); + const bare = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('shell', 'sh')); + await sessions.save(f.session); + + const rows = await prisma.terminal.findMany({ orderBy: { position: 'asc' } }); + expect(rows[0]).toMatchObject({ id: withMeta, agent: 'claude', minimized: true }); + expect(rows[1]).toMatchObject({ id: bare, agent: null, minimized: false }); + + const loaded = await sessions.find(f.session.id); + expect(loaded?.terminals.find((tm) => tm.id === withMeta)).toEqual({ + id: withMeta, + profile: { name: 'claude', command: 'claude', args: [], env: [] }, + agent: 'claude', + minimized: true, + }); + expect(loaded?.terminals.find((tm) => tm.id === bare)).toEqual({ + id: bare, + profile: { name: 'shell', command: 'sh', args: [], env: [] }, + agent: null, + minimized: false, + }); + }); + + it('resolves the owning workspace owner of a terminal id (idempotent-create check)', async () => { + const f = await fixture(); + const id = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('a', 'sh')); + await sessions.save(f.session); + const owned = await sessions.terminalWithOwner(id); + expect(owned).toEqual({ + ownerId: f.workspace.owner, + terminal: expect.objectContaining({ id }), + }); + expect(await sessions.terminalWithOwner(newTerminalId())).toBeUndefined(); + }); }); diff --git a/apps/api/src/persistence/session.repository.ts b/apps/api/src/persistence/session.repository.ts index 5cc6e6d..b8364a9 100644 --- a/apps/api/src/persistence/session.repository.ts +++ b/apps/api/src/persistence/session.repository.ts @@ -1,5 +1,6 @@ import { Session, + newTerminal, type SessionGuest, type SessionId, type Terminal, @@ -21,7 +22,15 @@ interface SessionRow { id: string; workspaceId: string; name: string; - terminals: { id: string; name: string; command: string; args: string[]; cwd: string | null }[]; + terminals: { + id: string; + name: string; + command: string; + args: string[]; + cwd: string | null; + agent: string | null; + minimized: boolean; + }[]; overrides: { userId: string; access: DbAccessLevel }[]; guests: { userId: string; access: DbAccessLevel }[]; } @@ -50,6 +59,46 @@ export class SessionRepository { return rows.map(restore); } + // Removes the aggregate row; terminals, overrides, guests and invitations + // follow the schema's onDelete cascade. + async delete(id: SessionId): Promise { + // deleteMany over delete: an id raced away between the controller's + // existence check and here must not turn into a P2025 500. + await this.prisma.session.deleteMany({ where: { id } }); + } + + // Ownership projection for idempotent terminal creates (S7): the terminal + // and the owner of the workspace its session belongs to. Undefined when the + // id is free (globally unique primary key). + async terminalWithOwner(id: TerminalId): Promise<{ terminal: Terminal; ownerId: UserId } | undefined> { + const row = await this.prisma.terminal.findUnique({ + where: { id }, + select: { + id: true, + name: true, + command: true, + args: true, + cwd: true, + agent: true, + minimized: true, + session: { select: { workspace: { select: { ownerId: true } } } }, + }, + }); + if (!row) return undefined; + const terminal = newTerminal( + row.id as TerminalId, + { + name: row.name, + command: row.command, + args: row.args, + env: [], + ...(row.cwd === null ? {} : { cwd: row.cwd }), + }, + { agent: row.agent, minimized: row.minimized }, + ); + return { terminal, ownerId: row.session.workspace.ownerId as UserId }; + } + // Upserts the session and replaces its terminals (position = index), // overrides and guests, all in one transaction. async save(session: Session): Promise { @@ -69,6 +118,9 @@ export class SessionRepository { command: t.profile.command, args: t.profile.args, cwd: t.profile.cwd ?? null, + // Snapshot metadata (S7); a missing key means the domain default. + agent: t.agent ?? null, + minimized: t.minimized ?? false, env: [], })), }), @@ -93,16 +145,20 @@ export class SessionRepository { } function restore(row: SessionRow): Session { - const terminals: Terminal[] = row.terminals.map((t) => ({ - id: t.id as TerminalId, - profile: { - name: t.name, - command: t.command, - args: t.args, - env: [], - ...(t.cwd === null ? {} : { cwd: t.cwd }), - }, - })); + // Terminal.env is NOT persisted (secrets): rehydrated as [], always. + const terminals: Terminal[] = row.terminals.map((t) => + newTerminal( + t.id as TerminalId, + { + name: t.name, + command: t.command, + args: t.args, + env: [], + ...(t.cwd === null ? {} : { cwd: t.cwd }), + }, + { agent: t.agent, minimized: t.minimized }, + ), + ); const guests: SessionGuest[] = row.guests.map((g) => ({ userId: g.userId as UserId, access: accessFromDb(g.access), diff --git a/apps/api/src/persistence/workspace.repository.ts b/apps/api/src/persistence/workspace.repository.ts index 881b7b1..e53e25b 100644 --- a/apps/api/src/persistence/workspace.repository.ts +++ b/apps/api/src/persistence/workspace.repository.ts @@ -55,4 +55,12 @@ export class WorkspaceRepository { }), ]); } + + // Removes the aggregate row; members, sessions, terminals and invitations + // follow the schema's onDelete cascade. + async delete(id: WorkspaceId): Promise { + // deleteMany over delete: an id raced away between the controller's + // existence check and here must not turn into a P2025 500. + await this.prisma.workspace.deleteMany({ where: { id } }); + } } diff --git a/apps/desktop/core/application/src/lib.rs b/apps/desktop/core/application/src/lib.rs index 74a9c41..e2cb9b9 100644 --- a/apps/desktop/core/application/src/lib.rs +++ b/apps/desktop/core/application/src/lib.rs @@ -9,6 +9,7 @@ mod collab_status; mod error; pub mod git; pub mod ports; +pub mod storage; mod use_cases; pub use activity::{Activity, ActivityTracker}; @@ -22,6 +23,9 @@ pub use agent_state::AgentState; pub use collab_status::{CheckRelay, RelayStatus, SessionCollaborators}; pub use error::AppError; pub use git::Branch; +pub use storage::{ + StoredPane, StoredSession, StoredWorkspace, WorkspaceSnapshot, SNAPSHOT_VERSION, +}; pub use use_cases::{ ApplyAccessLevel, CloseTerminal, DetectTerminalAgents, InspectBranch, LaunchTerminal, ListSubdirectories, ResizeTerminal, SendTerminalInput, diff --git a/apps/desktop/core/application/src/ports.rs b/apps/desktop/core/application/src/ports.rs index 6d43568..12ffad7 100644 --- a/apps/desktop/core/application/src/ports.rs +++ b/apps/desktop/core/application/src/ports.rs @@ -6,6 +6,7 @@ use std::time::Duration; use crate::agent_detection::ProcessInfo; use crate::git::Branch; +use crate::storage::WorkspaceSnapshot; use domain::{AgentProfile, Session, SessionId, TerminalId}; @@ -84,3 +85,124 @@ pub trait SessionRepository: Send + Sync { fn find_session(&self, id: SessionId) -> Result, PortError>; fn save_session(&self, session: Session) -> Result<(), PortError>; } + +/// Persiste el snapshot completo de la estructura del escritorio (workspaces, +/// sesiones y perfiles de arranque de las terminales). El modo local lo +/// implementa con un archivo en el directorio de datos y el modo nube con la +/// API REST; ambos quedan detrás del mismo puerto. `None` = no hay nada +/// guardado todavía (primera corrida o arranque limpio). +pub trait SnapshotStore: Send + Sync { + fn load_snapshot(&self) -> Result, PortError>; + fn save_snapshot(&self, snapshot: &WorkspaceSnapshot) -> Result<(), PortError>; +} + +/// Token de acceso para la API remota (modo nube). Se consulta por pedido +/// HTTP: si el access ya venció o está por vencer, el proveedor lo refresca +/// antes de devolverlo. +pub trait AccessTokenProvider: Send + Sync { + /// Token vigente, refrescándolo si la sesión lo pide (igual que hace la web). + fn access_token(&self) -> Result; + /// Token apenas refrescado a la fuerza: la API rechazó `rejected` con 401. + /// Si el token corriente ya cambió, otro pedido refrescó y se reutiliza. + fn refreshed_access_token(&self, rejected: &str) -> Result; +} + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + + use super::*; + + /// Fake del puerto: una lista de tokens donde el corriente es el primero. + /// `access_token` devuelve el corriente sin tocar la lista (un pedido no + /// debe refrescar); `refreshed_access_token` descarta el corriente y pasa + /// al siguiente, como haría un refresh real. + struct FakeTokens { + tokens: Mutex>, + } + + impl FakeTokens { + fn new(tokens: &[&str]) -> Self { + Self { + tokens: Mutex::new(tokens.iter().map(|t| t.to_string()).collect()), + } + } + } + + impl AccessTokenProvider for FakeTokens { + fn access_token(&self) -> Result { + let tokens = self.tokens.lock().expect("fake"); + tokens + .first() + .cloned() + .ok_or_else(|| PortError::new("sin token: no hay sesión iniciada")) + } + + fn refreshed_access_token(&self, rejected: &str) -> Result { + let mut tokens = self.tokens.lock().expect("fake"); + let Some(current) = tokens.first() else { + return Err(PortError::new("sin token: no hay sesión iniciada")); + }; + if current != rejected { + return Ok(current.clone()); + } + if tokens.len() > 1 { + tokens.remove(0); + } + Ok(tokens[0].clone()) + } + } + + #[test] + fn cada_pedido_consulta_el_token_vigente() { + let tokens = FakeTokens::new(&["tok-1", "tok-2"]); + // Dos pedidos seguidos reciben el mismo token y no lo consumen. + assert_eq!(tokens.access_token().unwrap(), "tok-1"); + assert_eq!(tokens.access_token().unwrap(), "tok-1"); + } + + #[test] + fn el_refresh_forzado_avanza_al_token_siguiente() { + let tokens = FakeTokens::new(&["tok-1", "tok-2"]); + assert_eq!(tokens.access_token().unwrap(), "tok-1"); + assert_eq!(tokens.refreshed_access_token("tok-1").unwrap(), "tok-2"); + // Y el nuevo pasa a ser el corriente. + assert_eq!(tokens.access_token().unwrap(), "tok-2"); + // Un último token se reutiliza: sin sesión a quién refrescar no existe. + assert_eq!(tokens.refreshed_access_token("tok-2").unwrap(), "tok-2"); + } + + #[test] + fn un_401_viejo_reutiliza_el_token_que_ya_refresco_otro_pedido() { + let tokens = FakeTokens::new(&["tok-2", "tok-3"]); + // El 401 llegó con tok-1, pero otro pedido ya dejó tok-2 vigente. + assert_eq!(tokens.refreshed_access_token("tok-1").unwrap(), "tok-2"); + assert_eq!(tokens.access_token().unwrap(), "tok-2"); + } + + #[test] + fn sin_token_todos_los_caminos_fallan_con_port_error() { + let tokens = FakeTokens::new(&[]); + assert_eq!( + tokens.access_token(), + Err(PortError::new("sin token: no hay sesión iniciada")) + ); + assert_eq!( + tokens.refreshed_access_token("tok-1"), + Err(PortError::new("sin token: no hay sesión iniciada")) + ); + } + + /// Helper que compila solo si el puerto es un trait-objeto `Send + Sync`: + /// el modo nube lo inyecta por `Arc) -> String { + provider.access_token().unwrap() + } + + #[test] + fn el_puerto_se_comparte_como_trait_objeto() { + let provider: Arc = Arc::new(FakeTokens::new(&["tok"])); + assert_eq!(port_is_shared_by_reference(provider), "tok"); + } +} diff --git a/apps/desktop/core/application/src/storage.rs b/apps/desktop/core/application/src/storage.rs new file mode 100644 index 0000000..0c6ffd4 --- /dev/null +++ b/apps/desktop/core/application/src/storage.rs @@ -0,0 +1,160 @@ +//! Snapshot de la estructura del escritorio: workspaces, sesiones y perfiles +//! de arranque de las terminales. Es lo único que se persiste en el modo local +//! (feature desktop-dual-storage, S5/A1): ni `env` ni scrollback ni estado de +//! procesos, solo lo necesario para reconstruir la grilla al arrancar. + +use serde::{Deserialize, Serialize}; + +/// Versión del formato. Un archivo con otra versión no se sabe leer y se pone +/// en cuarentena en vez de bochar la app; cuando haya migraciones reales se +/// agregan acá. +pub const SNAPSHOT_VERSION: u32 = 1; + +/// Una terminal del escritorio: su perfil de arranque y su lugar en la grilla. +/// Espeja al `Pane` de la UI (`packages/ui/src/model.ts`): el orden del DOM es +/// `seq` (estable, para no resetear xterm) y el orden visual es la posición en +/// el array de la sesión. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StoredPane { + pub id: String, + /// Orden de creación. Unicidad global, igual que en la UI. + pub seq: u64, + pub minimized: bool, + /// Carpeta inicial de la shell; `None` = la por defecto del núcleo. + pub initial_cwd: Option, + /// Agente que se lanza al abrir la terminal; `None` = solo la shell. + pub agent: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StoredSession { + pub id: String, + pub name: String, + /// En orden visual (arrastrar paneles reordena este array). + pub panes: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StoredWorkspace { + pub id: String, + pub name: String, + pub sessions: Vec, +} + +/// Toda la estructura persistida del escritorio, de una vez. El backend la +/// guarda y la devuelve completa; no hay lectura por partes. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceSnapshot { + pub version: u32, + pub workspaces: Vec, +} + +impl WorkspaceSnapshot { + /// Snapshot de la versión vigente. + pub fn new(workspaces: Vec) -> Self { + Self { + version: SNAPSHOT_VERSION, + workspaces, + } + } + + /// Es de la versión que sabemos leer. + pub fn is_current_version(&self) -> bool { + self.version == SNAPSHOT_VERSION + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + fn pane() -> StoredPane { + StoredPane { + id: "pane-1".into(), + seq: 7, + minimized: true, + initial_cwd: Some("C:\\repo".into()), + agent: Some("claude-code".into()), + } + } + + #[test] + fn serializes_with_camel_case_keys_like_the_frontend_model() { + let snapshot = WorkspaceSnapshot::new(vec![StoredWorkspace { + id: "ws-1".into(), + name: "OpenCollab".into(), + sessions: vec![StoredSession { + id: "session-1".into(), + name: "Sesión 1".into(), + panes: vec![pane()], + }], + }]); + assert_eq!( + serde_json::to_value(&snapshot).unwrap(), + json!({ + "version": 1, + "workspaces": [{ + "id": "ws-1", + "name": "OpenCollab", + "sessions": [{ + "id": "session-1", + "name": "Sesión 1", + "panes": [{ + "id": "pane-1", + "seq": 7, + "minimized": true, + "initialCwd": "C:\\repo", + "agent": "claude-code" + }] + }] + }] + }) + ); + } + + #[test] + fn round_trips_through_json() { + let snapshot = WorkspaceSnapshot::new(vec![StoredWorkspace { + id: "ws-1".into(), + name: "trabajo".into(), + sessions: vec![ + StoredSession { + id: "session-1".into(), + name: "sin panes".into(), + panes: vec![], + }, + StoredSession { + id: "session-2".into(), + name: "con pane".into(), + panes: vec![StoredPane { + id: "pane-1".into(), + seq: 0, + minimized: false, + initial_cwd: None, + agent: None, + }], + }, + ], + }]); + let back: WorkspaceSnapshot = + serde_json::from_str(&serde_json::to_string(&snapshot).unwrap()).unwrap(); + assert_eq!(back, snapshot); + } + + #[test] + fn version_gate_knows_what_it_can_read() { + let current = WorkspaceSnapshot::new(vec![]); + assert!(current.is_current_version()); + let future = WorkspaceSnapshot { + version: SNAPSHOT_VERSION + 1, + workspaces: vec![], + }; + assert!(!future.is_current_version()); + } +} diff --git a/apps/desktop/core/infrastructure/Cargo.toml b/apps/desktop/core/infrastructure/Cargo.toml index 7e4fa9a..bc31b79 100644 --- a/apps/desktop/core/infrastructure/Cargo.toml +++ b/apps/desktop/core/infrastructure/Cargo.toml @@ -9,7 +9,9 @@ publish.workspace = true [dependencies] domain.workspace = true application.workspace = true +serde.workspace = true +serde_json.workspace = true +ureq.workspace = true portable-pty.workspace = true sysinfo.workspace = true -serde_json.workspace = true uuid.workspace = true diff --git a/apps/desktop/core/infrastructure/src/cloud_store.rs b/apps/desktop/core/infrastructure/src/cloud_store.rs new file mode 100644 index 0000000..11a3caa --- /dev/null +++ b/apps/desktop/core/infrastructure/src/cloud_store.rs @@ -0,0 +1,1605 @@ +//! Backend de nube del snapshot: la API REST de OpenCollab detrás del mismo +//! puerto `SnapshotStore` que el modo local (feature desktop-dual-storage, S6/S7). +//! +//! El HTTP es bloqueante (`ureq` con rustls, sin runtime async, la misma regla +//! de la capa de aplicación). Cada pedido sale con el token vigente del +//! `AccessTokenProvider`; ante un 401 se fuerza un refresh una sola vez y se +//! reintenta el pedido antes de fallar. Los ids que no son UUID derivan un +//! UUID v5 determinista, así el mismo id local crea siempre el mismo recurso +//! en el server (creates idempotentes; la migración T6 reusa el mapeo). +//! +//! `save_snapshot` hace reconciliación: crea lo que falta, renombra/actualiza +//! lo que cambió y borra lo que sobró (primero terminales, después sesiones y +//! al final workspaces, respetando el cascade del server). Cualquier respuesta +//! que no sea 2xx corta el guardado con error: nunca se reporta éxito a +//! medias, y repetir el guardado es seguro porque los ids son idempotentes. + +use std::sync::Arc; +use std::time::Duration; + +use application::agent_detection::KnownAgent; +use application::ports::{AccessTokenProvider, PortError, SnapshotStore}; +use application::storage::{StoredPane, StoredSession, StoredWorkspace, WorkspaceSnapshot}; +use domain::AgentProfile; +use serde::Deserialize; +use uuid::Uuid; + +/// Tope por pedido HTTP: la API puede tardar, pero no debe dejar la llamada +/// bloqueada infinitamente (corre fuera del hilo de la UI). +const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); + +/// Espacio de nombres congelado para derivar UUID v5 de ids locales. Es un +/// valor arbitrario: cambiarlo rompería la relación id local → recurso del +/// server ya guardada (los recursos dejarían de encontrarse entre corridas). +const LOCAL_ID_NAMESPACE: Uuid = Uuid::from_bytes([ + 0x63, 0x2f, 0x9c, 0x11, 0x7f, 0x5e, 0x4d, 0x1c, 0xa2, 0xb5, 0x3e, 0x87, 0x90, 0xd6, 0xf4, 0x55, +]); + +/// UUID del server para un id local: si el id ya es UUID viaja tal cual (en +/// su forma canónica); si no, deriva un UUID v5 del string. Mismo id local +/// produce siempre el mismo UUID, entre corridas y máquinas. +pub fn local_id_to_server_uuid(local_id: &str) -> String { + Uuid::parse_str(local_id) + .unwrap_or_else(|_| Uuid::new_v5(&LOCAL_ID_NAMESPACE, local_id.as_bytes())) + .to_string() +} + +/// Lo que la API devuelve de una terminal. Los campos que pueden no venir se +/// toleran ausentes con `#[serde(default)]`: la API es más nueva que el +/// desktop posible, no al revés. +#[derive(Debug, Clone, Deserialize)] +struct ApiTerminal { + id: String, + name: String, + command: String, + #[serde(default)] + args: Vec, + #[serde(default)] + cwd: Option, + #[serde(default)] + agent: Option, + #[serde(default)] + minimized: bool, +} + +#[derive(Debug, Deserialize)] +struct ApiSession { + id: String, + name: String, + #[serde(default)] + terminals: Vec, +} + +/// Resumen en `GET /workspaces` con las sesiones expandidas (es lo que una +/// reconciliación necesita comparar contra el estado del server). +#[derive(Debug, Deserialize)] +struct ApiWorkspace { + id: String, + name: String, + #[serde(default)] + sessions: Vec, +} + +/// Perfil de arranque derivado de un panel: lo que la API guarda como +/// `name`/`command`/`args` y que el snapshot local no persiste. +#[derive(Debug, Clone, PartialEq, Eq)] +struct TerminalIdentity { + name: String, + command: String, + args: Vec, +} + +/// Perfil determinista de un panel. Con un agente conocido, el perfil es el +/// comando base con el que se lanza (sin los argumentos que cada adaptador +/// agrega por corrida, que llevan destinos y secretos de la sesión: A1). +/// Sin agente —o con un id que la versión actual no conoce— es la shell por +/// defecto, igual que hace la UI al restaurar: un agente removido cae a +/// shell plana en vez de romper. +fn terminal_identity(pane: &StoredPane) -> TerminalIdentity { + match pane.agent.as_deref().and_then(KnownAgent::from_id) { + Some(agent) => TerminalIdentity { + name: agent.id().to_string(), + command: agent.launch_command().to_string(), + args: Vec::new(), + }, + None => { + let shell: AgentProfile = crate::default_shell_profile(None); + TerminalIdentity { + name: shell.name, + command: shell.command, + args: shell.args, + } + } + } +} + +/// Resultado de un intento HTTP. +enum Attempt { + /// Respuesta 2xx con el cuerpo ya leído. + Ok(String), + /// El server contestó un 4xx/5xx: `ureq::Error::StatusCode` trae el número. + Status(u16), + /// Cualquier otro problema (red, URI, cuerpo ilegible). + Failure(String), +} + +pub struct CloudSnapshotStore { + base_url: String, + agent: ureq::Agent, + tokens: Arc, +} + +impl CloudSnapshotStore { + pub fn new(base_url: impl Into, tokens: Arc) -> Self { + Self { + // Sin `/` final: los paths se pegan con `/workspaces` y una barra + // doble cambiaría la ruta. + base_url: base_url.into().trim_end_matches('/').to_string(), + agent: ureq::Agent::config_builder() + .timeout_global(Some(REQUEST_TIMEOUT)) + .build() + .into(), + tokens, + } + } + + fn url(&self, path: &str) -> String { + format!("{}{}", self.base_url, path) + } + + /// Un intento HTTP con un token dado. Los 4xx/5xx no se leen como cuerpo: + /// llegan como `Attempt::Status` con el número, para decidir si es un 401 + /// refrescable. + fn attempt(&self, method: &str, url: &str, token: &str, body: Option<&str>) -> Attempt { + let builder = ureq::http::Request::builder() + .method(method) + .uri(url) + .header("Authorization", format!("Bearer {token}")); + let outcome = match body { + Some(body) => { + let request = builder + .header("Content-Type", "application/json") + .body(body.to_string()); + match request { + Ok(request) => self.agent.run(request), + Err(e) => return Attempt::Failure(format!("pedido inválido: {e}")), + } + } + None => { + let request = builder.body(()); + match request { + Ok(request) => self.agent.run(request), + Err(e) => return Attempt::Failure(format!("pedido inválido: {e}")), + } + } + }; + match outcome { + Ok(mut response) => match response.body_mut().read_to_string() { + Ok(text) => Attempt::Ok(text), + Err(e) => Attempt::Failure(format!("respuesta ilegible: {e}")), + }, + Err(ureq::Error::StatusCode(status)) => Attempt::Status(status), + Err(e) => Attempt::Failure(format!("{e}")), + } + } + + /// Un pedido contra la API: obtiene un token por pedido y, ante 401, fuerza + /// un refresh (una sola vez) y reintenta el pedido idéntico con el token + /// nuevo. Todo otro error es `PortError`; el error nunca se reporta como + /// éxito a las capas de arriba. + fn call(&self, method: &str, path: &str, body: Option<&str>) -> Result { + let url = self.url(path); + let token = self.tokens.access_token()?; + match self.attempt(method, &url, &token, body) { + Attempt::Ok(text) => Ok(text), + Attempt::Status(401) => { + let token = self.tokens.refreshed_access_token(&token)?; + match self.attempt(method, &url, &token, body) { + Attempt::Ok(text) => Ok(text), + Attempt::Status(status) => Err(PortError::new(format!( + "la API rechazó el pedido ({status}) después de refrescar: {method} {path}" + ))), + Attempt::Failure(reason) => Err(PortError::new(format!( + "falló el pedido {method} {path} en el reintento: {reason}" + ))), + } + } + Attempt::Status(status) => Err(PortError::new(format!( + "la API rechazó el pedido ({status}): {method} {path}" + ))), + Attempt::Failure(reason) => Err(PortError::new(format!( + "falló el pedido {method} {path}: {reason}" + ))), + } + } + + /// Estado actual del server: workspaces con las sesiones de cada uno + /// expandidas. Cualquier respuesta inválida es error: nunca se reconcilia + /// contra datos bajo-informados (borrar por error una nube despoblada es + /// irreversible; una lectura fallida no es una estructura vacía). + fn fetch_current(&self) -> Result, PortError> { + let raw = self.call("GET", "/workspaces", None)?; + let mut workspaces: Vec = serde_json::from_str(&raw) + .map_err(|e| PortError::new(format!("respuesta de /workspaces inválida: {e}")))?; + for workspace in &mut workspaces { + let raw = self.call( + "GET", + &format!("/workspaces/{}/sessions", workspace.id), + None, + )?; + workspace.sessions = serde_json::from_str(&raw).map_err(|e| { + PortError::new(format!( + "respuesta de /workspaces/{}/sessions inválida: {e}", + workspace.id + )) + })?; + } + Ok(workspaces) + } + + /// Crea, actualiza y ordena las terminales de la sesión deseada contra + /// `current` (lo que hoy está en el server). + fn reconcile_terminals( + &self, + session_path: &str, + session: &StoredSession, + current: &[ApiTerminal], + ) -> Result<(), PortError> { + // Huerfanas primero: el PUT de orden pide "exactamente las terminales + // de la sesión", así que ninguna huérfana puede seguir viva ahí. + let desired_ids: Vec = session + .panes + .iter() + .map(|pane| local_id_to_server_uuid(&pane.id)) + .collect(); + let mut order_changed = false; + for terminal in current { + if !desired_ids.iter().any(|id| id == &terminal.id) { + self.call( + "DELETE", + &format!("{session_path}/terminals/{}", terminal.id), + None, + )?; + order_changed = true; + } + } + // Creaciones y updates de las deseadas, en el orden visual deseado + // (el server agrega al final: el PUT de orden termina de fijarlo). + for pane in &session.panes { + let terminal_id = local_id_to_server_uuid(&pane.id); + let identity = terminal_identity(pane); + let location = current.iter().find(|termino| termino.id == terminal_id); + match location { + None => { + self.create_terminal(session_path, &terminal_id, pane, &identity)?; + order_changed = true; + } + Some(server_terminal) => { + if let Some(body) = terminal_patch(server_terminal, pane, &identity) { + self.call( + "PATCH", + &format!("{session_path}/terminals/{terminal_id}"), + Some(&body), + )?; + } + } + } + } + // Orden visual: manda el array completo con los ids deseados solo si + // el orden actual difiere, o cambió la composición de la sesión (un + // create/delete reordena el array del server de todos modos). + let current_order: Vec<&str> = current.iter().map(|t| t.id.as_str()).collect(); + let desired_order: Vec<&str> = desired_ids.iter().map(String::as_str).collect(); + if order_changed || current_order != desired_order { + let ids = serde_json::json!({ "ids": desired_ids }).to_string(); + self.call( + "PUT", + &format!("{session_path}/terminals/order"), + Some(&ids), + )?; + } + Ok(()) + } + + /// POST de una terminal nueva: con id explícito (idempotente) y el perfil + /// derivado. Los campos nulos no viajan: el server ya los tiene por + /// default y un null explícito no agrega nada. + fn create_terminal( + &self, + session_path: &str, + terminal_id: &str, + pane: &StoredPane, + identity: &TerminalIdentity, + ) -> Result<(), PortError> { + let mut body = serde_json::Map::new(); + body.insert("id".into(), serde_json::json!(terminal_id)); + body.insert("name".into(), serde_json::json!(identity.name)); + body.insert("command".into(), serde_json::json!(identity.command)); + body.insert("args".into(), serde_json::json!(identity.args)); + if let Some(cwd) = &pane.initial_cwd { + body.insert("cwd".into(), serde_json::json!(cwd)); + } + if let Some(agent) = &pane.agent { + body.insert("agent".into(), serde_json::json!(agent)); + } + if pane.minimized { + body.insert("minimized".into(), serde_json::json!(true)); + } + let body = serde_json::Value::Object(body).to_string(); + self.call("POST", &format!("{session_path}/terminals"), Some(&body))?; + Ok(()) + } + + /// POST de una sesión nueva dentro de un workspace (id idempotente + nombre). + fn create_session(&self, wid: &str, sid: &str, name: &str) -> Result<(), PortError> { + self.call( + "POST", + &format!("/workspaces/{wid}/sessions"), + Some(&serde_json::json!({ "id": sid, "name": name }).to_string()), + )?; + Ok(()) + } + + /// Crea o actualiza un workspace y sus sesiones/terminales contra el estado + /// remoto actual (`current`), sin borrar sesiones ni otros workspaces. + fn upsert_workspace( + &self, + workspace: &StoredWorkspace, + current: &[ApiWorkspace], + ) -> Result<(), PortError> { + let wid = local_id_to_server_uuid(&workspace.id); + let born = current.iter().find(|w| w.id == wid).is_none(); + if born { + self.call( + "POST", + "/workspaces", + Some( + &serde_json::json!({ + "id": wid, + "name": workspace.name, + }) + .to_string(), + ), + )?; + } else { + let server_workspace = current + .iter() + .find(|w| w.id == wid) + .expect("existía en el fetch"); + if server_workspace.name != workspace.name { + self.call( + "PATCH", + &format!("/workspaces/{wid}"), + Some(&serde_json::json!({ "name": workspace.name }).to_string()), + )?; + } + } + for session in &workspace.sessions { + let sid = local_id_to_server_uuid(&session.id); + let server_session = if born { + None + } else { + let server_workspace = current + .iter() + .find(|w| w.id == wid) + .expect("existía en el fetch"); + server_workspace.sessions.iter().find(|s| s.id == sid) + }; + match server_session { + None => self.create_session(&wid, &sid, &session.name)?, + Some(server_session) => { + if server_session.name != session.name { + self.call( + "PATCH", + &format!("/sessions/{sid}"), + Some(&serde_json::json!({ "name": session.name }).to_string()), + )?; + } + } + } + let current_terminals: Vec = match server_session { + Some(server_session) => server_session.terminals.clone(), + None => Vec::new(), + }; + self.reconcile_terminals(&format!("/sessions/{sid}"), session, ¤t_terminals)?; + } + Ok(()) + } + + /// Migra los workspaces locales a la nube uno por uno (S4, A4), sin borrar + /// workspaces ni sesiones que la cuenta ya tuviera en el servidor. + pub fn migrate_snapshot(&self, snapshot: &WorkspaceSnapshot) -> Result<(), PortError> { + if snapshot.workspaces.is_empty() { + return Ok(()); + } + let current = self.fetch_current()?; + for workspace in &snapshot.workspaces { + self.upsert_workspace(workspace, ¤t)?; + } + Ok(()) + } +} + +/// Diferencia entre la terminal del server y el panel deseado: solo los +/// campos que cambian viajan en el PATCH (la API es partial). Un null +/// explícito es la forma de quitar el valor guardado. +fn terminal_patch( + server: &ApiTerminal, + pane: &StoredPane, + identity: &TerminalIdentity, +) -> Option { + let mut changed = serde_json::Map::new(); + if server.name != identity.name { + changed.insert("name".into(), serde_json::json!(identity.name)); + } + if server.command != identity.command { + changed.insert("command".into(), serde_json::json!(identity.command)); + } + if server.args != identity.args { + changed.insert("args".into(), serde_json::json!(identity.args)); + } + if server.cwd.as_deref() != pane.initial_cwd.as_deref() { + changed.insert("cwd".into(), serde_json::json!(pane.initial_cwd)); + } + if server.agent.as_deref() != pane.agent.as_deref() { + changed.insert("agent".into(), serde_json::json!(pane.agent)); + } + if server.minimized != pane.minimized { + changed.insert("minimized".into(), serde_json::json!(pane.minimized)); + } + (!changed.is_empty()).then(|| serde_json::Value::Object(changed).to_string()) +} + +impl SnapshotStore for CloudSnapshotStore { + fn load_snapshot(&self) -> Result, PortError> { + let current = self.fetch_current()?; + if current.is_empty() { + // Cuenta sin workspaces = primera corrida en la nube: arranque + // limpio (la UI arma su default y lo guarda después), tal como + // sucede en modo local sin archivo. + return Ok(None); + } + let mut seq = 0u64; + let mut workspaces = Vec::new(); + for workspace in current { + let mut sessions = Vec::new(); + for session in workspace.sessions { + let mut panes = Vec::new(); + for terminal in session.terminals { + panes.push(StoredPane { + id: terminal.id, + seq, + minimized: terminal.minimized, + initial_cwd: terminal.cwd, + agent: terminal.agent, + }); + seq += 1; + } + sessions.push(StoredSession { + id: session.id, + name: session.name, + panes, + }); + } + workspaces.push(StoredWorkspace { + id: workspace.id, + name: workspace.name, + sessions, + }); + } + Ok(Some(WorkspaceSnapshot::new(workspaces))) + } + + fn save_snapshot(&self, snapshot: &WorkspaceSnapshot) -> Result<(), PortError> { + let current = self.fetch_current()?; + let desired_ws: Vec = snapshot + .workspaces + .iter() + .map(|workspace| local_id_to_server_uuid(&workspace.id)) + .collect(); + + // Fase 1: crear/actualizar lo deseado, workspace por workspace. Si el + // workspace no está en la nube, se crea con sus sesiones desde cero. + for workspace in &snapshot.workspaces { + self.upsert_workspace(workspace, ¤t)?; + } + + // Fase 2: sesiones que sobraron en workspaces conservados. Las + // terminales huérfanas de una sesión conservada ya salieron en la + // fase 1 (la reconciliación borrarlas antes de fijar el orden, para + // que el PUT cuente la composición definitiva); la de una sesión + // enteramente huérfana viaja con el cascade del DELETE de la sesión. + for server_workspace in ¤t { + if !desired_ws.iter().any(|id| id == &server_workspace.id) { + continue; + } + let desired = snapshot + .workspaces + .iter() + .find(|w| local_id_to_server_uuid(&w.id) == server_workspace.id) + .expect("el workspace conservado está en el snapshot"); + for server_session in &server_workspace.sessions { + let wanted = desired + .sessions + .iter() + .any(|s| local_id_to_server_uuid(&s.id) == server_session.id); + if !wanted { + self.call("DELETE", &format!("/sessions/{}", server_session.id), None)?; + } + } + } + + // Fase 3: workspaces que el snapshot ya no menciona. Cada uno arrastra + // sus sesiones y terminales por cascade (204). + for server_workspace in ¤t { + if !desired_ws.iter().any(|id| id == &server_workspace.id) { + self.call( + "DELETE", + &format!("/workspaces/{}", server_workspace.id), + None, + )?; + } + } + Ok(()) + } +} + +/// POST de una sesión nueva dentro de un workspace (id idempotente + nombre). +#[cfg(test)] +mod tests { + use std::collections::VecDeque; + use std::io::{Read, Write}; + use std::net::{Shutdown, TcpListener, TcpStream}; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Mutex; + use std::thread; + + use application::storage::SNAPSHOT_VERSION; + use serde_json::{json, Value}; + + use super::*; + + // -------------------------------------------------------------- mock -- + + /// Pedido HTTP registrado por el servidor de mentira, con lo que los + /// asserts necesitan mirar: método, ruta, token y cuerpo. + #[derive(Debug, Clone, PartialEq)] + struct Recorded { + method: String, + path: String, + auth: Option, + content_type: Option, + body: String, + } + + struct MockReply { + status: u16, + body: String, + } + + /// Respuesta `200` con JSON de cuerpo. + fn ok_reply(body: Value) -> MockReply { + MockReply { + status: 200, + body: body.to_string(), + } + } + + /// Respuesta de error con el cuerpo genérico de la API. + fn error_reply(status: u16) -> MockReply { + MockReply { + status, + body: r#"{"error":{"code":"X","message":"no"}}"#.to_string(), + } + } + + /// Servidor HTTP de mentira: `replies[i]` responde al pedido i (en orden + /// de llegada); lo que supera el guión recibe 500. Cada pedido vive en su + /// propia conexión (`connection: close`) y todos quedan registrados. + struct MockServer { + addr: String, + requests: Arc>>, + } + + impl MockServer { + fn start(replies: Vec) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap().to_string(); + let requests: Arc>> = Arc::new(Mutex::new(Vec::new())); + let requests_for_thread = Arc::clone(&requests); + let queue: Mutex> = Mutex::new(replies.into_iter().collect()); + thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { continue }; + if let Some(recorded) = read_request(&mut stream) { + { + let mut all = requests_for_thread.lock().expect("mock"); + all.push(recorded); + } + let reply = queue + .lock() + .expect("mock") + .pop_front() + .unwrap_or_else(|| error_reply(500)); + write_reply(&mut stream, &reply); + } + let _ = stream.shutdown(Shutdown::Both); + } + }); + Self { addr, requests } + } + + fn url(&self) -> String { + format!("http://{}", self.addr) + } + + fn requests(&self) -> Vec { + self.requests.lock().expect("mock").clone() + } + + fn count(&self) -> usize { + self.requests.lock().expect("mock").len() + } + } + + /// Lee un pedido HTTP del stream: headers y body según Content-Length. + fn read_request(stream: &mut TcpStream) -> Option { + let mut buf = Vec::new(); + let mut chunk = [0u8; 1024]; + loop { + if let Some(recorded) = try_parse(&buf) { + return Some(recorded); + } + match stream.read(&mut chunk) { + Ok(0) => return try_parse(&buf), + Ok(n) => buf.extend_from_slice(&chunk[..n]), + Err(_) => return None, + } + } + } + + /// Parsea el pedido solo si ya está completo; `None` mientras falte leer. + fn try_parse(buf: &[u8]) -> Option { + let headers_end = buf.windows(4).position(|w| w == b"\r\n\r\n")? + 4; + let head = String::from_utf8_lossy(&buf[..headers_end]); + let head = &head[..head.len() - 4]; + let mut lines = head.lines(); + let request_line = lines.next()?; + let mut parts = request_line.split_whitespace(); + let method = parts.next()?.to_string(); + let path = parts.next()?.to_string(); + let mut auth = None; + let mut content_type = None; + let mut content_length = 0usize; + for line in lines { + let (key, value) = line.split_once(':')?; + let key = key.trim().to_ascii_lowercase(); + let value = value.trim(); + match key.as_str() { + "authorization" => auth = Some(value.to_string()), + "content-type" => content_type = Some(value.to_string()), + "content-length" => content_length = value.parse::().ok()?, + _ => {} + } + } + let needed = headers_end + content_length; + if buf.len() < needed { + return None; + } + let body = String::from_utf8_lossy(&buf[headers_end..needed]).to_string(); + Some(Recorded { + method, + path, + auth, + content_type, + body, + }) + } + + fn write_reply(stream: &mut TcpStream, reply: &MockReply) { + if reply.status == 204 { + let _ = stream.write_all(b"HTTP/1.1 204 No Content\r\nconnection: close\r\n\r\n"); + return; + } + let reason = match reply.status { + 200 => "OK", + 201 => "Created", + 400 => "Bad Request", + 401 => "Unauthorized", + 403 => "Forbidden", + 404 => "Not Found", + 409 => "Conflict", + 500 => "Internal Server Error", + _ => "Status", + }; + let head = format!( + "HTTP/1.1 {status} {reason}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n", + reply.body.len(), + status = reply.status, + ); + let _ = stream.write_all(head.as_bytes()); + let _ = stream.write_all(reply.body.as_bytes()); + } + + // ------------------------------------------------------------- fakes -- + + /// Proveedor con dos tokens: el corriente ("tok-1") y el que entrega el + /// refresh forzado ("tok-2"). Anota los refreshes para los asserts; el + /// `Clone` comparte el contador vía `Arc`. + #[derive(Clone)] + struct FakeTokens { + refreshes: Arc, + } + + impl FakeTokens { + fn new() -> Self { + Self { + refreshes: Arc::new(AtomicUsize::new(0)), + } + } + + fn refresh_count(&self) -> usize { + self.refreshes.load(Ordering::SeqCst) + } + } + + impl AccessTokenProvider for FakeTokens { + fn access_token(&self) -> Result { + Ok("tok-1".to_string()) + } + + fn refreshed_access_token(&self, _rejected: &str) -> Result { + self.refreshes.fetch_add(1, Ordering::SeqCst); + Ok("tok-2".to_string()) + } + } + + fn tokens() -> Arc { + Arc::new(FakeTokens::new()) + } + + fn store(server: &MockServer) -> CloudSnapshotStore { + CloudSnapshotStore::new(server.url(), tokens()) + } + + // ---------------------------------------------------------- fixtures -- + + /// Snapshot deseado de prueba: ws-1 "OpenCollab", sesión s-1 "Sesión 1", + /// dos paneles (agente claude-code con cwd; shell minimizada). + fn desired() -> WorkspaceSnapshot { + WorkspaceSnapshot::new(vec![StoredWorkspace { + id: "ws-1".into(), + name: "OpenCollab".into(), + sessions: vec![StoredSession { + id: "session-1".into(), + name: "Sesión 1".into(), + panes: vec![ + StoredPane { + id: "pane-1".into(), + seq: 0, + minimized: false, + initial_cwd: Some("C:\\repo".into()), + agent: Some("claude-code".into()), + }, + StoredPane { + id: "pane-2".into(), + seq: 1, + minimized: true, + initial_cwd: None, + agent: None, + }, + ], + }], + }]) + } + + /// Entrada de `GET /workspaces` (el view del server lleva campos de más: + /// el mapeo solo toma lo que usa). + fn workspace_entry(id: &str, name: &str) -> Value { + json!({ "id": id, "name": name, "owner": "u1", "memberCount": 1 }) + } + + /// View de terminal del server construido con el mismo perfil derivado, + /// para que los asserts de negocio vean solo lo que cambia de verdad. + fn server_terminal(pane: &StoredPane) -> Value { + let identity = terminal_identity(pane); + json!({ + "id": local_id_to_server_uuid(&pane.id), + "name": identity.name, + "command": identity.command, + "args": identity.args, + "cwd": pane.initial_cwd, + "agent": pane.agent, + "minimized": pane.minimized, + }) + } + + fn server_session(id: &str, name: &str, terminals: Vec) -> Value { + json!({ "id": id, "name": name, "terminals": terminals }) + } + + /// Terminal "ajena": un perfil que no corresponde con nada deseado. + fn stray_terminal(id: &str, name: &str) -> Value { + json!({ + "id": id, + "name": name, + "command": "cmd", + "args": [], + "cwd": null, + "agent": null, + "minimized": false, + }) + } + + // -------------------------------------------------------------- tests -- + + #[test] + fn la_derivacion_es_estable_y_los_uuid_viajan_tal_cual() { + // Mismo id local → mismo UUID siempre, entre llamadas e instancias. + let first = local_id_to_server_uuid("ws-1"); + assert_eq!(first, local_id_to_server_uuid("ws-1")); + // Es un UUID y no es el id local crudo. + assert!(Uuid::parse_str(&first).is_ok()); + assert_ne!(first, "ws-1"); + // Dos ids locales distintos no colisionan. + assert_ne!(first, local_id_to_server_uuid("session-1")); + // Un id que ya es UUID viaja igual (forma canónica en minúsculas). + assert_eq!( + local_id_to_server_uuid("E4E0F07E-8B3E-4DC2-A1F0-5B2C9D01AA33"), + "e4e0f07e-8b3e-4dc2-a1f0-5b2c9d01aa33" + ); + assert_eq!( + local_id_to_server_uuid("e4e0f07e-8b3e-4dc2-a1f0-5b2c9d01aa33"), + "e4e0f07e-8b3e-4dc2-a1f0-5b2c9d01aa33" + ); + } + + #[test] + fn load_mapea_views_de_la_api_al_snapshot() { + let wid = local_id_to_server_uuid("ws-1"); + let sid = local_id_to_server_uuid("session-1"); + let tid1 = local_id_to_server_uuid("pane-1"); + let tid2 = local_id_to_server_uuid("pane-2"); + let server = MockServer::start(vec![ + ok_reply(json!([workspace_entry(&wid, "Cloud")])), + ok_reply(json!([{ + "id": sid, + "name": "Trabajo", + "terminals": [ + { + "id": tid1, + "name": "Claude Code", + "command": "claude", + "args": ["--resume"], + "cwd": "C:\\repo", + "agent": "claude-code", + "minimized": false, + }, + { + "id": tid2, + "name": "PowerShell", + "command": "powershell.exe", + "args": [], + "cwd": null, + "agent": null, + "minimized": true, + }, + ], + }])), + ]); + let cloud = store(&server); + + let loaded = cloud.load_snapshot().unwrap().expect("hay snapshot"); + + assert_eq!(loaded.version, SNAPSHOT_VERSION); + assert_eq!(loaded.workspaces.len(), 1); + let workspace = &loaded.workspaces[0]; + assert_eq!(workspace.id, wid); + assert_eq!(workspace.name, "Cloud"); + assert_eq!(workspace.sessions.len(), 1); + let session = &workspace.sessions[0]; + assert_eq!(session.name, "Trabajo"); + // Orden visual = orden del array del view; seq = posición en él. + assert_eq!(session.panes.len(), 2); + assert_eq!( + session.panes[0], + StoredPane { + id: tid1, + seq: 0, + minimized: false, + initial_cwd: Some("C:\\repo".into()), + agent: Some("claude-code".into()), + } + ); + assert_eq!( + session.panes[1], + StoredPane { + id: tid2, + seq: 1, + minimized: true, + initial_cwd: None, + agent: None, + } + ); + // Dos pedidos: la lista y las sesiones del workspace leído. + let all = server.requests(); + assert_eq!(all.len(), 2); + assert_eq!(all[0].method, "GET"); + assert_eq!(all[0].path, "/workspaces"); + assert_eq!(all[0].auth.as_deref(), Some("Bearer tok-1")); + assert_eq!( + all[1].path, + format!("/workspaces/{wid}/sessions"), + "el GET de sesiones usa el id del workspace" + ); + } + + #[test] + fn load_de_una_cuenta_vacia_es_arranque_limpio() { + let server = MockServer::start(vec![ok_reply(json!([]))]); + let cloud = store(&server); + assert_eq!(cloud.load_snapshot().unwrap(), None); + assert_eq!(server.count(), 1, "con la lista vacía no se pide más"); + } + + #[test] + fn load_no_reutiliza_seq_entre_sesiones() { + let (wid, s1, s2) = ( + local_id_to_server_uuid("ws-1"), + local_id_to_server_uuid("s-1"), + local_id_to_server_uuid("s-2"), + ); + let (t1, t2) = ( + local_id_to_server_uuid("p-1"), + local_id_to_server_uuid("p-2"), + ); + let pane = |id: &str| { + json!({ + "id": id, + "name": "PowerShell", + "command": "powershell.exe", + "args": [], + "cwd": null, + "agent": null, + "minimized": false, + }) + }; + let server = MockServer::start(vec![ + ok_reply(json!([workspace_entry(&wid, "Cloud")])), + ok_reply(json!([ + server_session(&s1, "S1", vec![pane(&t1)]), + server_session(&s2, "S2", vec![pane(&t2)]), + ])), + ]); + + let loaded = store(&server).load_snapshot().unwrap().unwrap(); + let seqs: Vec = loaded.workspaces[0] + .sessions + .iter() + .flat_map(|session| session.panes.iter().map(|pane| pane.seq)) + .collect(); + assert_eq!(seqs, vec![0, 1], "Pane.seq es único global"); + } + + #[test] + fn save_crea_lo_que_falta_con_datos_explicitos() { + let wid = local_id_to_server_uuid("ws-1"); + let sid = local_id_to_server_uuid("session-1"); + let tid1 = local_id_to_server_uuid("pane-1"); + let tid2 = local_id_to_server_uuid("pane-2"); + // Nube vacía: la reconciliación crea todo. Los creates contestan 200 + // (recurso ya existía: el caso idempotente del contrato) sin drama. + let server = MockServer::start(vec![ + ok_reply(json!([])), + ok_reply(json!({})), + ok_reply(json!({})), + ok_reply(json!({})), + ok_reply(json!({})), + ok_reply(json!({})), + ]); + let cloud = store(&server); + cloud.save_snapshot(&desired()).unwrap(); + + let all = server.requests(); + let shapes: Vec<(String, String)> = all + .iter() + .map(|r| (r.method.clone(), r.path.clone())) + .collect(); + assert_eq!( + shapes, + vec![ + ("GET".into(), "/workspaces".into()), + ("POST".into(), "/workspaces".into()), + ("POST".into(), format!("/workspaces/{wid}/sessions")), + ("POST".into(), format!("/sessions/{sid}/terminals")), + ("POST".into(), format!("/sessions/{sid}/terminals")), + ("PUT".into(), format!("/sessions/{sid}/terminals/order")), + ] + ); + assert_eq!(all[0].auth.as_deref(), Some("Bearer tok-1")); + + let ws_body: Value = serde_json::from_str(&all[1].body).unwrap(); + assert_eq!(all[1].content_type.as_deref(), Some("application/json")); + assert_eq!(ws_body["id"], Value::String(wid)); + assert_eq!(ws_body["name"], "OpenCollab"); + + let session_body: Value = serde_json::from_str(&all[2].body).unwrap(); + assert_eq!(session_body["id"], Value::String(sid.clone())); + assert_eq!(session_body["name"], "Sesión 1"); + + // Panel con agente conocido: el perfil es el comando base del agente + // (sin los argumentos que cada adaptador agrega por corrida: A1). + let agent_body: Value = serde_json::from_str(&all[3].body).unwrap(); + assert_eq!(agent_body["id"], Value::String(tid1.clone())); + assert_eq!(agent_body["name"], "claude-code"); + assert_eq!(agent_body["command"], "claude"); + assert_eq!(agent_body["args"], json!([])); + assert_eq!(agent_body["agent"], "claude-code"); + assert_eq!(agent_body["cwd"], "C:\\repo"); + // `minimized` falso no viaja: el server ya lo tiene por default. + assert!(agent_body.get("minimized").is_none()); + + // Shell plana: el perfil derivado es la shell por defecto del sistema. + let shell = crate::default_shell_profile(None); + let shell_body: Value = serde_json::from_str(&all[4].body).unwrap(); + assert_eq!(shell_body["id"], Value::String(tid2.clone())); + assert_eq!(shell_body["name"], Value::String(shell.name.clone())); + assert_eq!(shell_body["command"], Value::String(shell.command.clone())); + assert_eq!(shell_body["args"], json!(shell.args)); + assert_eq!(shell_body["minimized"], true); + // Los nulos no viajan: el server ya los tiene por default. + assert!(shell_body.get("cwd").is_none(), "cwd nulo no viaja"); + assert!(shell_body.get("agent").is_none(), "agent nulo no viaja"); + + let order: Value = serde_json::from_str(&all[5].body).unwrap(); + assert_eq!(order, json!({ "ids": [tid1, tid2] })); + } + + #[test] + fn save_renombra_y_actualiza_solo_lo_cambiado() { + let wid = local_id_to_server_uuid("ws-1"); + let sid = local_id_to_server_uuid("session-1"); + let tid1 = local_id_to_server_uuid("pane-1"); + let tid2 = local_id_to_server_uuid("pane-2"); + // Server: mismos recursos con nombres viejos y el cwd de pane-1 vacío. + // El resto del perfil de pane-1 ya coincide: no se PATCHea. + let server = MockServer::start(vec![ + ok_reply(json!([workspace_entry(&wid, "viejo")])), + ok_reply(json!([{ + "id": sid, + "name": "vieja sesión", + "terminals": [{ + "id": tid1, + "name": "claude-code", + "command": "claude", + "args": [], + "cwd": null, + "agent": "claude-code", + "minimized": false, + }], + }])), + ok_reply(json!({})), + ok_reply(json!({})), + ok_reply(json!({})), + ok_reply(json!({})), + ok_reply(json!({})), + ]); + let cloud = store(&server); + cloud.save_snapshot(&desired()).unwrap(); + + // Esperado: lectura (workspaces + sesiones), PATCH ws, PATCH sesión, + // PATCH pane-1 (cwd), create pane-2, PUT de orden. + let all = server.requests(); + let shapes: Vec<(String, String)> = all + .iter() + .map(|r| (r.method.clone(), r.path.clone())) + .collect(); + assert_eq!( + shapes, + vec![ + ("GET".into(), "/workspaces".into()), + ("GET".into(), format!("/workspaces/{wid}/sessions")), + ("PATCH".into(), format!("/workspaces/{wid}")), + ("PATCH".into(), format!("/sessions/{sid}")), + ("PATCH".into(), format!("/sessions/{sid}/terminals/{tid1}")), + ("POST".into(), format!("/sessions/{sid}/terminals")), + ("PUT".into(), format!("/sessions/{sid}/terminals/order")), + ] + ); + + let ws_patch: Value = serde_json::from_str(&all[2].body).unwrap(); + assert_eq!(ws_patch, json!({"name": "OpenCollab"})); + let session_patch: Value = serde_json::from_str(&all[3].body).unwrap(); + assert_eq!(session_patch, json!({"name": "Sesión 1"})); + + // pane-1 existe y solo cambia su cwd; pane-2 (nuevo) se crea después. + let patched: Value = serde_json::from_str(&all[4].body).unwrap(); + assert_eq!(patched, json!({"cwd": "C:\\repo"})); + let created: Value = serde_json::from_str(&all[5].body).unwrap(); + assert_eq!(created["id"], Value::String(tid2.clone())); + assert_eq!(created["minimized"], true); + + let order: Value = serde_json::from_str(&all[6].body).unwrap(); + assert_eq!(order, json!({"ids": [tid1, tid2]})); + } + + #[test] + fn save_borra_huerfanos_terminales_sesiones_y_workspaces() { + let wid = local_id_to_server_uuid("ws-1"); + let sid = local_id_to_server_uuid("session-1"); + let tid1 = local_id_to_server_uuid("pane-1"); + let tid2 = local_id_to_server_uuid("pane-2"); + let wid_b = local_id_to_server_uuid("ws-extra"); + let wid_c = "33333333-3333-4333-8333-333333333333"; + let sid_huerfana = "44444444-4444-4444-8444-444444444444"; + let terminal_huerfana = "55555555-5555-4555-8555-555555555555"; + let panes = desired().workspaces[0].sessions[0].panes.clone(); + + let server = MockServer::start(vec![ + ok_reply(json!([ + workspace_entry(&wid, "OpenCollab"), + workspace_entry(&wid_b, "extra"), + workspace_entry(wid_c, "otro"), + ])), + ok_reply(json!([ + server_session( + &sid, + "Sesión 1", + vec![ + server_terminal(&panes[0]), + stray_terminal(terminal_huerfana, "sobra"), + ] + ), + server_session( + sid_huerfana, + "huérfana", + vec![stray_terminal( + "66666666-6666-4666-8666-666666666666", + "de la sesión huérfana", + )], + ), + ])), + ok_reply(json!([server_session( + "77777777-7777-4777-8777-777777777777", + "de otro workspace", + vec![], + )])), + ok_reply(json!([])), + ok_reply(json!({})), // create pane-2 (pane-1 ya coincide) + ok_reply(json!({})), // PUT de orden (cambió la composición) + ok_reply(json!({})), // DELETE terminal huérfana + ok_reply(json!({})), // DELETE sesión huérfana + ok_reply(json!({})), // DELETE ws_b + ok_reply(json!({})), // DELETE ws_c + ]); + let cloud = store(&server); + cloud.save_snapshot(&desired()).unwrap(); + + let all = server.requests(); + let shapes: Vec<(String, String)> = all + .iter() + .map(|r| (r.method.clone(), r.path.clone())) + .collect(); + assert_eq!(shapes.len(), 10, "{shapes:?}"); + // Fase 1, sesión conservada: DELETE de la terminal huérfana (primero + // ojo: el PUT de orden pide exactamente las que deben quedar), + // create de pane-2 y PUT con el orden final. + assert_eq!( + shapes[4], + ( + "DELETE".into(), + format!("/sessions/{sid}/terminals/{terminal_huerfana}") + ) + ); + assert_eq!( + shapes[5], + ("POST".into(), format!("/sessions/{sid}/terminals")) + ); + assert_eq!( + shapes[6], + ("PUT".into(), format!("/sessions/{sid}/terminals/order")) + ); + let order: Value = serde_json::from_str(&all[6].body).unwrap(); + assert_eq!(order, json!({"ids": [tid1, tid2]})); + // Fase 2: la sesión entera huérfana; su terminal no se borra por + // pedido propio, el cascade de la sesión lo hace. + assert_eq!( + shapes[7], + ("DELETE".into(), format!("/sessions/{sid_huerfana}")) + ); + // Fase 3: los workspaces sobrantes, al final del todo. + assert_eq!(shapes[8], ("DELETE".into(), format!("/workspaces/{wid_b}"))); + assert_eq!(shapes[9], ("DELETE".into(), format!("/workspaces/{wid_c}"))); + // El orden global(respetado en cascada): terminales → sesiones → workspaces. + let explicit_terminal_deletes = shapes + .iter() + .filter(|(m, p)| m == "DELETE" && p.contains("/terminals/")) + .count(); + assert_eq!(explicit_terminal_deletes, 1); + let (x, y, z) = delete_order(&shapes); + assert_eq!(x, 4, "primera DELETE de terminal"); + assert_eq!(y, 7, "primera DELETE de sesión"); + assert_eq!(z, 8, "primera DELETE de workspace"); + // El GET de sesiones tocó todos los workspaces del server. + assert_eq!( + shapes[2], + ("GET".into(), format!("/workspaces/{wid_b}/sessions")) + ); + assert_eq!( + shapes[3], + ("GET".into(), format!("/workspaces/{wid_c}/sessions")) + ); + } + + /// Posiciones de la primera DELETE por cada nivel del cascade. + fn delete_order(shapes: &[(String, String)]) -> (usize, usize, usize) { + let terminal = shapes + .iter() + .position(|(m, p)| m == "DELETE" && p.contains("/terminals/")) + .unwrap(); + let session = shapes + .iter() + .position(|(m, p)| { + m == "DELETE" && p.starts_with("/sessions/") && !p.contains("/terminals/") + }) + .unwrap(); + let workspace = shapes + .iter() + .position(|(m, p)| m == "DELETE" && p.starts_with("/workspaces/")) + .unwrap(); + (terminal, session, workspace) + } + + #[test] + fn save_orden_distinto_manda_put_y_reconstruye_el_orden() { + let wid = local_id_to_server_uuid("ws-1"); + let sid = local_id_to_server_uuid("session-1"); + let tid1 = local_id_to_server_uuid("pane-1"); + let tid2 = local_id_to_server_uuid("pane-2"); + let panes = desired().workspaces[0].sessions[0].panes.clone(); + let server = MockServer::start(vec![ + ok_reply(json!([workspace_entry(&wid, "OpenCollab")])), + ok_reply(json!([server_session( + &sid, + "Sesión 1", + vec![server_terminal(&panes[1]), server_terminal(&panes[0]),] + )])), + ok_reply(json!({})), + ]); + let cloud = store(&server); + cloud.save_snapshot(&desired()).unwrap(); + + // Solo el PUT: sin creates ni patches, los contenidos ya coinciden. + let all = server.requests(); + let shapes: Vec<(String, String)> = all + .iter() + .map(|r| (r.method.clone(), r.path.clone())) + .collect(); + assert_eq!( + shapes, + vec![ + ("GET".into(), "/workspaces".into()), + ("GET".into(), format!("/workspaces/{wid}/sessions")), + ("PUT".into(), format!("/sessions/{sid}/terminals/order")), + ] + ); + let order: Value = serde_json::from_str(&all[2].body).unwrap(); + assert_eq!(order, json!({"ids": [tid1, tid2]})); + } + + #[test] + fn save_con_orden_igual_no_manda_put() { + let wid = local_id_to_server_uuid("ws-1"); + let sid = local_id_to_server_uuid("session-1"); + let panes = desired().workspaces[0].sessions[0].panes.clone(); + let server = MockServer::start(vec![ + ok_reply(json!([workspace_entry(&wid, "OpenCollab")])), + ok_reply(json!([server_session( + &sid, + "Sesión 1", + vec![server_terminal(&panes[0]), server_terminal(&panes[1]),] + )])), + ]); + let cloud = store(&server); + cloud.save_snapshot(&desired()).unwrap(); + assert_eq!(server.count(), 2, "sin cambios: solo las lecturas"); + } + + #[test] + fn un_401_fuerza_un_refresh_y_reintenta_una_vez() { + let tokens = FakeTokens::new(); + let wid = local_id_to_server_uuid("ws-1"); + let sid = local_id_to_server_uuid("session-1"); + let tid1 = local_id_to_server_uuid("pane-1"); + let server = MockServer::start(vec![ + error_reply(401), + ok_reply(json!([workspace_entry(&wid, "Cloud")])), + ok_reply(json!([server_session( + &sid, + "sesión", + vec![json!({ + "id": tid1, + "name": "x", + "command": "cmd", + "args": [], + "cwd": null, + "agent": null, + "minimized": false, + })] + )])), + ]); + let cloud = CloudSnapshotStore::new(server.url(), Arc::new(tokens.clone())); + + let loaded = cloud.load_snapshot().unwrap().expect("cargó tras el retry"); + assert_eq!(loaded.workspaces[0].name, "Cloud"); + assert_eq!(tokens.refresh_count(), 1, "un único refresh"); + + let all = server.requests(); + assert_eq!(all.len(), 3); + assert_eq!(all[0].path, "/workspaces"); + assert_eq!(all[1].path, "/workspaces"); + assert_eq!(all[0].auth.as_deref(), Some("Bearer tok-1")); + assert_eq!( + all[1].auth.as_deref(), + Some("Bearer tok-2"), + "el reintento lleva el token refrescado" + ); + } + + #[test] + fn un_segundo_401_tras_el_reintento_es_error() { + let tokens = FakeTokens::new(); + let server = MockServer::start(vec![error_reply(401), error_reply(401)]); + let cloud = CloudSnapshotStore::new(server.url(), Arc::new(tokens.clone())); + + let err = cloud.load_snapshot().unwrap_err(); + assert!(err.0.contains("401"), "{}", err.0); + assert_eq!(tokens.refresh_count(), 1, "un solo refresh, sin loops"); + assert_eq!(server.count(), 2, "intento + reintento, nada más"); + } + + #[test] + fn los_403_404_500_son_errores_sin_reintento_ni_refresh() { + for status in [403u16, 404, 500] { + let tokens = FakeTokens::new(); + let server = MockServer::start(vec![error_reply(status)]); + let cloud = CloudSnapshotStore::new(server.url(), Arc::new(tokens.clone())); + let err = cloud.load_snapshot().unwrap_err(); + assert!(err.0.contains(&status.to_string()), "{status}: {}", err.0); + assert_eq!(tokens.refresh_count(), 0, "no hay refresh por un 401 ajeno"); + assert_eq!(server.count(), 1); + } + } + + #[test] + fn json_malformado_es_error_sin_panico() { + let server = MockServer::start(vec![MockReply { + status: 200, + body: "esto no es json".to_string(), + }]); + let cloud = store(&server); + let err = cloud.load_snapshot().unwrap_err(); + assert!(err.0.contains("workspaces"), "{}", err.0); + assert!(err.0.contains("inválida"), "{}", err.0); + + // Y con una lista de workspaces a la que le falta un campo fijo. + let server2 = MockServer::start(vec![ok_reply(json!([{"name": "sin id"}]))]); + let cloud2 = store(&server2); + assert!(cloud2.load_snapshot().is_err()); + } + + #[test] + fn un_fallo_de_lectura_no_reporta_exit_ni_borra() { + let wid = local_id_to_server_uuid("ws-1"); + // La segunda lectura (sesiones del workspace) explota: no arrancó + // ninguna escritura y no hay deletes que hagan daño. + let server = MockServer::start(vec![ + ok_reply(json!([workspace_entry(&wid, "otra")])), + error_reply(500), + ]); + let cloud = store(&server); + let err = cloud.save_snapshot(&desired()).unwrap_err(); + assert!(err.0.contains("500"), "{}", err.0); + let all = server.requests(); + assert!( + all.iter().all(|r| r.method == "GET"), + "ninguna escritura se mandó" + ); + } + + #[test] + fn un_fallo_a_la_mitad_del_save_corta_en_seco() { + let sid = local_id_to_server_uuid("session-1"); + let tid1 = local_id_to_server_uuid("pane-1"); + let tid2 = local_id_to_server_uuid("pane-2"); + // El create del primer terminal explota a mitad de la fase 1: el + // guardado es Err y ninguna fase posterior queda colgando. + let server = MockServer::start(vec![ + ok_reply(json!([])), + ok_reply(json!({})), + ok_reply(json!({})), + error_reply(500), + ]); + let cloud = store(&server); + let err = cloud.save_snapshot(&desired()).unwrap_err(); + assert!(err.0.contains("500"), "{}", err.0); + let all = server.requests(); + assert_eq!(all.len(), 4, "ni un pedido más después del fallo"); + assert_eq!(all[3].method, "POST"); + assert_eq!(all[3].path, format!("/sessions/{sid}/terminals")); + assert!( + !all.iter() + .any(|r| r.method == "DELETE" || r.path.contains("/order")), + "sin deletes ni PUT colgado" + ); + let _ = (tid1, tid2); + } + + #[test] + fn guardar_un_snapshot_vacio_borra_todos_los_workspaces() { + let wid = local_id_to_server_uuid("ws-1"); + let sid = local_id_to_server_uuid("session-1"); + let panes = desired().workspaces[0].sessions[0].panes.clone(); + // Snapshot vacío: el DELETE del workspace arrasa el resto por cascade, + // así que no hay deletes de sesiones ni de terminales. + let server = MockServer::start(vec![ + ok_reply(json!([workspace_entry(&wid, "una")])), + ok_reply(json!([server_session( + &sid, + "una", + vec![server_terminal(&panes[0]), server_terminal(&panes[1]),] + )])), + ok_reply(json!({})), // DELETE del workspace huérfano + ]); + let cloud = store(&server); + cloud + .save_snapshot(&WorkspaceSnapshot::new(vec![])) + .unwrap(); + + let all = server.requests(); + let deletes: Vec<&Recorded> = all.iter().filter(|r| r.method == "DELETE").collect(); + assert_eq!(deletes.len(), 1); + assert_eq!(deletes[0].path, format!("/workspaces/{wid}")); + } + + #[test] + fn sin_token_no_se_consulta_la_api() { + struct SinSesion; + impl AccessTokenProvider for SinSesion { + fn access_token(&self) -> Result { + Err(PortError::new( + "no hay sesión iniciada: el modo nube necesita login", + )) + } + + fn refreshed_access_token(&self, _rejected: &str) -> Result { + Err(PortError::new( + "no hay sesión iniciada: el modo nube necesita login", + )) + } + } + let server = MockServer::start(vec![]); + let cloud = CloudSnapshotStore::new(server.url(), Arc::new(SinSesion)); + let err = cloud.load_snapshot().unwrap_err(); + assert!(err.0.contains("no hay sesión"), "{}", err.0); + assert_eq!(server.count(), 0, "la API ni se enteró"); + assert!(cloud.save_snapshot(&desired()).is_err()); + assert_eq!(server.count(), 0); + } + + #[test] + fn base_url_con_barra_final_no_duplica_las_barras() { + let server = MockServer::start(vec![ok_reply(json!([]))]); + let cloud = CloudSnapshotStore::new(format!("{}/", server.url()), tokens()); + cloud.load_snapshot().unwrap(); + assert_eq!(server.requests()[0].path, "/workspaces"); + } + + #[test] + fn un_fallo_de_conexion_es_error_de_puerto() { + // Puerto reservado y soltado: nadie escucha ahí. + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + drop(listener); + let cloud = CloudSnapshotStore::new(url, tokens()); + let err = cloud.load_snapshot().unwrap_err(); + assert!( + err.0.contains("falló el pedido GET /workspaces"), + "{}", + err.0 + ); + } + + #[test] + fn migrar_sube_workspaces_locales_uno_por_uno_sin_borrar_los_que_ya_tenia_la_nube() { + let existing_wid = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; + let existing_sid = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + let local_w1 = local_id_to_server_uuid("w-local-1"); + let local_s1 = local_id_to_server_uuid("s-local-1"); + let local_p1 = local_id_to_server_uuid("p-local-1"); + let local_w2 = local_id_to_server_uuid("w-local-2"); + let local_s2 = local_id_to_server_uuid("s-local-2"); + + let server = MockServer::start(vec![ + // fetch_current: la cuenta ya tiene un workspace previo en la nube. + ok_reply(json!([workspace_entry(existing_wid, "Ya en la nube")])), + ok_reply(json!([server_session(existing_sid, "Remota", vec![])])), + // Workspace local 1: POST workspace + POST session + POST terminal + PUT order. + ok_reply(json!({ "id": local_w1, "name": "Local 1" })), + ok_reply(json!({ "id": local_s1, "name": "Sesión 1", "terminals": [] })), + ok_reply(json!({ "id": local_p1 })), + ok_reply(json!({ "ids": [local_p1] })), + // Workspace local 2: POST workspace + POST session (sin terminales = sin PUT order). + ok_reply(json!({ "id": local_w2, "name": "Local 2" })), + ok_reply(json!({ "id": local_s2, "name": "Sesión 2", "terminals": [] })), + ]); + + let snapshot = WorkspaceSnapshot::new(vec![ + StoredWorkspace { + id: "w-local-1".into(), + name: "Local 1".into(), + sessions: vec![StoredSession { + id: "s-local-1".into(), + name: "Sesión 1".into(), + panes: vec![StoredPane { + id: "p-local-1".into(), + seq: 0, + minimized: false, + initial_cwd: Some("C:\\repo".into()), + agent: Some("codex".into()), + }], + }], + }, + StoredWorkspace { + id: "w-local-2".into(), + name: "Local 2".into(), + sessions: vec![StoredSession { + id: "s-local-2".into(), + name: "Sesión 2".into(), + panes: vec![], + }], + }, + ]); + + let cloud = store(&server); + cloud.migrate_snapshot(&snapshot).unwrap(); + + let requests = server.requests(); + assert!( + requests.iter().all(|r| r.method != "DELETE"), + "la migración nunca debe borrar workspaces o sesiones existentes en la nube: {requests:?}" + ); + let paths: Vec<(&str, &str)> = requests + .iter() + .map(|r| (r.method.as_str(), r.path.as_str())) + .collect(); + let s1_terminals = format!("/workspaces/{local_w1}/sessions"); + let t1_path = format!("/sessions/{local_s1}/terminals"); + let t1_order = format!("/sessions/{local_s1}/terminals/order"); + let s2_sessions = format!("/workspaces/{local_w2}/sessions"); + let existing_sessions = format!("/workspaces/{existing_wid}/sessions"); + assert_eq!( + paths, + vec![ + ("GET", "/workspaces"), + ("GET", existing_sessions.as_str()), + ("POST", "/workspaces"), + ("POST", s1_terminals.as_str()), + ("POST", t1_path.as_str()), + ("PUT", t1_order.as_str()), + ("POST", "/workspaces"), + ("POST", s2_sessions.as_str()), + ] + ); + } + + #[test] + fn migrar_snapshot_vacio_no_consulta_la_api() { + let server = MockServer::start(vec![]); + let cloud = store(&server); + cloud + .migrate_snapshot(&WorkspaceSnapshot::new(vec![])) + .unwrap(); + assert_eq!(server.count(), 0); + } +} diff --git a/apps/desktop/core/infrastructure/src/lib.rs b/apps/desktop/core/infrastructure/src/lib.rs index d4e21aa..ad77534 100644 --- a/apps/desktop/core/infrastructure/src/lib.rs +++ b/apps/desktop/core/infrastructure/src/lib.rs @@ -3,8 +3,10 @@ mod agent_launch; mod claude_adapter; mod claude_hooks; +mod cloud_store; mod directory_browser; mod hook_receiver; +mod local_store; mod memory_repository; mod opencode_adapter; mod opencode_events; @@ -17,8 +19,10 @@ mod sse; pub use agent_launch::{agent_shell_profile, command_exists}; pub use claude_adapter::ClaudeCodeAdapter; +pub use cloud_store::{local_id_to_server_uuid, CloudSnapshotStore}; pub use directory_browser::FsDirectoryBrowser; pub use hook_receiver::HookReceiver; +pub use local_store::FsSnapshotStore; pub use memory_repository::InMemorySessionRepository; pub use opencode_adapter::OpenCodeAdapter; pub use process_inspector::SysinfoProcessInspector; diff --git a/apps/desktop/core/infrastructure/src/local_store.rs b/apps/desktop/core/infrastructure/src/local_store.rs new file mode 100644 index 0000000..e268df9 --- /dev/null +++ b/apps/desktop/core/infrastructure/src/local_store.rs @@ -0,0 +1,254 @@ +//! Backend local del snapshot: un JSON en el directorio de datos de la app. +//! +//! Escritura atómica (temporal + renombre) para que un cierre a medias nunca +//! deje el snapshot corrupto, y cuarentena de archivos ilegibles: un archivo +//! que no se puede leer se renombra a `.corrupt` y la app arranca limpia en +//! vez de no abrir (S5: persistir es una mejora, nunca un obstáculo). + +use std::fs; +use std::path::PathBuf; + +use application::ports::{PortError, SnapshotStore}; +use application::storage::WorkspaceSnapshot; + +const FILE_NAME: &str = "workspaces.json"; +const CORRUPT_EXT: &str = "corrupt"; + +/// Snapshot en `dir/workspaces.json`. `dir` es el directorio de datos de la +/// app (appdata en producción, un temporal en los tests). +pub struct FsSnapshotStore { + path: PathBuf, +} + +impl FsSnapshotStore { + pub fn new(dir: impl Into) -> Self { + Self { + path: dir.into().join(FILE_NAME), + } + } + + pub fn path(&self) -> &std::path::Path { + &self.path + } + + /// Pone el archivo ilegible a un lado con extensión `.corrupt` para no + /// pisarlo con el próximo guardado. Best-effort: si falla, el arranque + /// limpio sigue igual (el próximo guardado lo reemplaza). + fn quarantine(&self) { + let to = self.path.with_extension(CORRUPT_EXT); + let _ = fs::rename(&self.path, &to); + } +} + +impl SnapshotStore for FsSnapshotStore { + fn load_snapshot(&self) -> Result, PortError> { + let data = match fs::read_to_string(&self.path) { + Ok(data) => data, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(PortError::new(format!("no se pudo leer el snapshot: {e}"))), + }; + match serde_json::from_str::(&data) { + Ok(snapshot) if snapshot.is_current_version() => Ok(Some(snapshot)), + // Ilegible o de una versión que no sabemos leer: cuarentena y + // arranque limpio. Nunca frenar la app por un archivo roto. + _ => { + self.quarantine(); + Ok(None) + } + } + } + + fn save_snapshot(&self, snapshot: &WorkspaceSnapshot) -> Result<(), PortError> { + let json = serde_json::to_string(snapshot) + .map_err(|e| PortError::new(format!("no se pudo serializar el snapshot: {e}")))?; + // Escritura atómica: primero al temporal, después renombre. Un cierre + // a medias deja intacto el snapshot anterior. + if let Some(parent) = self.path.parent() { + fs::create_dir_all(parent).map_err(|e| { + PortError::new(format!("no se pudo crear el directorio de datos: {e}")) + })?; + } + let tmp = self.path.with_extension("json.tmp"); + fs::write(&tmp, json) + .map_err(|e| PortError::new(format!("no se pudo escribir el snapshot: {e}")))?; + fs::rename(&tmp, &self.path) + .map_err(|e| PortError::new(format!("no se pudo reemplazar el snapshot: {e}"))) + } +} + +#[cfg(test)] +mod tests { + use std::path::Path; + use std::sync::atomic::{AtomicU64, Ordering}; + + use application::storage::{StoredPane, StoredSession, StoredWorkspace, SNAPSHOT_VERSION}; + + use super::*; + + /// Directorio temporal por test; se borra al salir del scope. + struct TempDir(PathBuf); + + impl TempDir { + fn new(tag: &str) -> Self { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::SeqCst); + let path = std::env::temp_dir().join(format!( + "opencollab-local-store-{tag}-{}-{n}", + std::process::id() + )); + fs::create_dir_all(&path).unwrap(); + Self(path) + } + + fn sub(&self, name: &str) -> PathBuf { + let p = self.0.join(name); + fs::create_dir_all(&p).unwrap(); + p + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + fn snapshot() -> WorkspaceSnapshot { + WorkspaceSnapshot::new(vec![StoredWorkspace { + id: "ws-1".into(), + name: "OpenCollab".into(), + sessions: vec![StoredSession { + id: "session-1".into(), + name: "Sesión 1".into(), + panes: vec![ + StoredPane { + id: "pane-1".into(), + seq: 0, + minimized: false, + initial_cwd: Some("C:\\repo".into()), + agent: Some("claude-code".into()), + }, + StoredPane { + id: "pane-2".into(), + seq: 1, + minimized: true, + initial_cwd: None, + agent: None, + }, + ], + }], + }]) + } + + #[test] + fn round_trips_the_whole_structure() { + let dir = TempDir::new("round-trip"); + let store = FsSnapshotStore::new(dir.0.clone()); + store.save_snapshot(&snapshot()).unwrap(); + let loaded = store.load_snapshot().unwrap(); + assert_eq!(loaded, Some(snapshot())); + } + + #[test] + fn no_file_yet_means_no_snapshot() { + let dir = TempDir::new("missing"); + let store = FsSnapshotStore::new(dir.0.clone()); + assert_eq!(store.load_snapshot().unwrap(), None); + } + + #[test] + fn save_creates_missing_parent_directories() { + let dir = TempDir::new("create-dirs"); + let nested = dir.sub("a").join("b"); // todavía no existe + let store = FsSnapshotStore::new(nested); + store.save_snapshot(&snapshot()).unwrap(); + assert!(store.path().is_file()); + } + + #[test] + fn saving_replaces_the_previous_snapshot() { + let dir = TempDir::new("replace"); + let store = FsSnapshotStore::new(dir.0.clone()); + store.save_snapshot(&snapshot()).unwrap(); + let next = WorkspaceSnapshot::new(vec![StoredWorkspace { + id: "ws-2".into(), + name: "otro".into(), + sessions: vec![], + }]); + store.save_snapshot(&next).unwrap(); + assert_eq!(store.load_snapshot().unwrap(), Some(next)); + } + + #[test] + fn garbage_file_is_quarantined_and_boot_is_fresh() { + let dir = TempDir::new("garbage"); + let store = FsSnapshotStore::new(dir.0.clone()); + fs::write(store.path(), "no es json").unwrap(); + assert_eq!(store.load_snapshot().unwrap(), None); + // El original queda a un lado, recuperable a mano. + let corrupt = store.path().with_extension(CORRUPT_EXT); + assert_eq!(fs::read_to_string(&corrupt).unwrap(), "no es json"); + // Y el segundo arranque ya ni lo ve: el archivo original ya no está. + assert_eq!(store.load_snapshot().unwrap(), None); + } + + #[test] + fn future_version_is_quarantined_and_boot_is_fresh() { + let dir = TempDir::new("future"); + let store = FsSnapshotStore::new(dir.0.clone()); + let future = serde_json::to_string(&WorkspaceSnapshot { + version: SNAPSHOT_VERSION + 1, + workspaces: vec![], + }) + .unwrap(); + fs::write(store.path(), future).unwrap(); + assert_eq!(store.load_snapshot().unwrap(), None); + assert!(store.path().with_extension(CORRUPT_EXT).is_file()); + } + + #[test] + fn empty_file_is_quarantined_and_boot_is_fresh() { + let dir = TempDir::new("empty"); + let store = FsSnapshotStore::new(dir.0.clone()); + fs::write(store.path(), "").unwrap(); + assert_eq!(store.load_snapshot().unwrap(), None); + assert!(store.path().with_extension(CORRUPT_EXT).is_file()); + } + + #[test] + fn save_over_quarantined_leftovers_still_works() { + let dir = TempDir::new("after-corrupt"); + let store = FsSnapshotStore::new(dir.0.clone()); + fs::write(store.path(), "roto").unwrap(); + assert_eq!(store.load_snapshot().unwrap(), None); + // Arrancó limpio: el próximo guardado escribe el archivo de vuelta. + store.save_snapshot(&snapshot()).unwrap(); + assert_eq!(store.load_snapshot().unwrap(), Some(snapshot())); + // La cuarentena del arranque anterior no molesta al nuevo archivo. + assert!(store.path().with_extension(CORRUPT_EXT).is_file()); + } + + #[test] + fn pane_order_survives_the_round_trip() { + let dir = TempDir::new("order"); + let store = FsSnapshotStore::new(dir.0.clone()); + let mut snap = snapshot(); + let StoredWorkspace { sessions, .. } = &mut snap.workspaces[0]; + sessions[0].panes.reverse(); // orden visual distinto al de creación + store.save_snapshot(&snap).unwrap(); + let loaded = store.load_snapshot().unwrap().unwrap(); + let panes = &loaded.workspaces[0].sessions[0].panes; + assert_eq!(panes[0].id, "pane-2"); + assert_eq!(panes[1].id, "pane-1"); + // El seq (orden del DOM) viaja intacto aunque el array esté reordenado. + assert_eq!(panes[0].seq, 1); + assert_eq!(panes[1].seq, 0); + } + + #[test] + fn path_is_inside_the_configured_directory() { + let dir = TempDir::new("path"); + let store = FsSnapshotStore::new(dir.0.clone()); + assert_eq!(store.path(), Path::new(&dir.0).join(FILE_NAME)); + } +} diff --git a/apps/desktop/e2e/run.mjs b/apps/desktop/e2e/run.mjs index d294eab..01cd8d1 100644 --- a/apps/desktop/e2e/run.mjs +++ b/apps/desktop/e2e/run.mjs @@ -19,6 +19,12 @@ import statusBarLive from "./scenarios/status-bar-live.mjs"; import newTerminalHere from "./scenarios/new-terminal-here.mjs"; import launchAgent from "./scenarios/launch-agent.mjs"; import authSignin from "./scenarios/auth-signin.mjs"; +import snapshotLoadError from "./scenarios/snapshot-load-error.mjs"; +import onboarding from "./scenarios/onboarding.mjs"; +import settingsStorage from "./scenarios/settings-storage.mjs"; +import cloudBootSession from "./scenarios/cloud-boot-session.mjs"; +import localCollabInactive from "./scenarios/local-collab-inactive.mjs"; +import localToCloudMigration from "./scenarios/local-to-cloud-migration.mjs"; const scenarios = { "drag & swap de terminales": dragSwap, @@ -29,6 +35,12 @@ const scenarios = { "exit en la shell cierra el panel": exitClosesPane, "status bar con estado real": statusBarLive, "login vía la web": authSignin, + "fallo de carga no pisa el snapshot": snapshotLoadError, + "primera corrida elige almacenamiento": onboarding, + "ajustes de almacenamiento": settingsStorage, + "reinicio cloud sin sesión": cloudBootSession, + "colaboración visible pero inactiva en modo local": localCollabInactive, + "migración local a cloud al cambiar de modo": localToCloudMigration, }; function chromePath() { diff --git a/apps/desktop/e2e/scenarios/cloud-boot-session.mjs b/apps/desktop/e2e/scenarios/cloud-boot-session.mjs new file mode 100644 index 0000000..58efba9 --- /dev/null +++ b/apps/desktop/e2e/scenarios/cloud-boot-session.mjs @@ -0,0 +1,58 @@ +// Reinicio en modo cloud: la config persiste pero los tokens viven solo en +// memoria, así que sin login no se monta la grilla ni se guarda nada. Al +// iniciar sesión se carga el snapshot de la cuenta; logout vuelve al gate y el +// siguiente login lo recupera. +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); + +const cloudSnapshot = { + version: 1, + workspaces: [ + { + id: "w-cloud", + name: "Nube", + sessions: [ + { + id: "s-cloud", + name: "Sesión nube", + panes: [{ id: "p-cloud", seq: 0, minimized: false, initialCwd: null, agent: null }], + }, + ], + }, + ], +}; + +export default async function cloudBootSession(page, checks) { + const base = page.url().split("?")[0]; + await page.goto(`${base}?mockCloud=1`, { waitUntil: "networkidle0" }); + await wait(300); + + checks["cloud sin sesión no monta la grilla"] = (await page.$(".app")) === null; + checks["cloud sin sesión pide login"] = await page.evaluate(() => + document.body.textContent.includes("Sign in to load your workspace structure"), + ); + checks["cloud sin sesión no guarda el default"] = + (await page.evaluate(() => window.__mock.savedSnapshot)) === null; + + await page.evaluate((snapshot) => window.__mock.setSnapshot(snapshot), cloudSnapshot); + await page.evaluate(() => window.__mock.signIn()); + await wait(600); + + checks["el login carga la nube"] = await page.evaluate(() => + document.body.textContent.includes("Nube"), + ); + checks["la grilla usa el snapshot de la cuenta"] = await page.evaluate( + () => window.__mock.savedSnapshot?.workspaces?.[0]?.id === "w-cloud", + ); + + await page.evaluate(() => window.__mock.signOut()); + await wait(300); + checks["logout vuelve al gate"] = + (await page.$(".app")) === null && + (await page.evaluate(() => document.body.textContent.includes("Sign in"))); + + await page.evaluate(() => window.__mock.signIn()); + await wait(600); + checks["re-login recupera la nube"] = await page.evaluate(() => + document.body.textContent.includes("Nube"), + ); +} diff --git a/apps/desktop/e2e/scenarios/local-collab-inactive.mjs b/apps/desktop/e2e/scenarios/local-collab-inactive.mjs new file mode 100644 index 0000000..48176e8 --- /dev/null +++ b/apps/desktop/e2e/scenarios/local-collab-inactive.mjs @@ -0,0 +1,90 @@ +// Modo local (S3): la colaboración sigue visible en TopBar, Sidebar y +// StatusBar pero permanece inactiva hasta cambiar a almacenamiento Cloud. +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); + +export default async function localCollabInactive(page, checks) { + await wait(300); + + const initial = await page.evaluate(() => { + const invite = [...document.querySelectorAll(".topbar-actions button")].find((b) => + b.textContent.includes("Invite"), + ); + const wsMeta = document.querySelector(".sidebar .ws-meta"); + const userCard = document.querySelector(".sidebar .user"); + const statusItems = [...document.querySelectorAll(".statusbar-item")]; + return { + inviteVisible: !!invite && invite.offsetParent !== null, + inviteDisabled: invite instanceof HTMLButtonElement && invite.disabled, + inviteInactive: invite?.getAttribute("data-collab-inactive") === "true", + inviteTitle: invite?.getAttribute("title") ?? "", + wsMetaVisible: !!wsMeta && wsMeta.offsetParent !== null, + wsMetaInactive: wsMeta?.getAttribute("data-collab-inactive") === "true", + userVisible: !!userCard && userCard.offsetParent !== null, + userInactive: userCard?.getAttribute("data-collab-inactive") === "true", + userText: userCard?.textContent ?? "", + statusCount: statusItems.length, + statusInactive: statusItems.every((el) => el.getAttribute("data-collab-inactive") === "true"), + statusTexts: statusItems.map((el) => el.textContent.trim()), + }; + }); + + checks["Invite sigue visible pero deshabilitado en modo local"] = + initial.inviteVisible && initial.inviteDisabled && initial.inviteInactive; + checks["Invite explica que el modo local no invita"] = initial.inviteTitle.includes("Modo local"); + checks["el contador de miembros del workspace sigue visible e inactivo"] = + initial.wsMetaVisible && initial.wsMetaInactive; + checks["la tarjeta de cuenta indica colaboración inactiva en modo local"] = + initial.userVisible && + initial.userInactive && + initial.userText.includes("Colaboración inactiva en modo local"); + checks["la status bar mantiene visibles los indicadores en estado inactivo"] = + initial.statusCount === 2 && + initial.statusInactive && + initial.statusTexts[0] === "Local · relay no conectado" && + initial.statusTexts[1] === "1 collaborator"; + + // Incluso con sesión iniciada, el modo local no aparece como Online. + await page.evaluate(() => window.__mock.signIn()); + await wait(200); + const signedInLocal = await page.evaluate(() => ({ + userText: document.querySelector(".sidebar .user")?.textContent ?? "", + userInactive: + document.querySelector(".sidebar .user")?.getAttribute("data-collab-inactive") === "true", + })); + checks["con cuenta iniciada en modo local muestra colaboración inactiva (no Online)"] = + signedInLocal.userInactive && + signedInLocal.userText.includes("Local · colaboración inactiva") && + !signedInLocal.userText.includes("Online"); + + // Cambiar a Cloud en Settings activa los indicadores de colaboración. + await page.click('button[aria-label="Settings"]'); + await wait(200); + await page.evaluate(() => { + const [, cloud] = document.querySelectorAll(".settings-mode input"); + cloud.click(); + }); + await wait(100); + await page.click(".modal-actions .btn--primary"); + await wait(400); + + const inCloud = await page.evaluate(() => { + const invite = [...document.querySelectorAll(".topbar-actions button")].find((b) => + b.textContent.includes("Invite"), + ); + const userCard = document.querySelector(".sidebar .user"); + const wsMeta = document.querySelector(".sidebar .ws-meta"); + return { + inviteInactive: invite?.getAttribute("data-collab-inactive"), + inviteTitle: invite?.getAttribute("title") ?? "", + userInactive: userCard?.getAttribute("data-collab-inactive"), + userText: userCard?.textContent ?? "", + wsMetaInactive: wsMeta?.getAttribute("data-collab-inactive"), + }; + }); + checks["al pasar a Cloud la colaboración deja de figurar inactiva"] = + inCloud.inviteInactive === null && + inCloud.userInactive === null && + inCloud.wsMetaInactive === null && + inCloud.userText.includes("Online") && + inCloud.inviteTitle.includes("Requiere el relay"); +} diff --git a/apps/desktop/e2e/scenarios/local-to-cloud-migration.mjs b/apps/desktop/e2e/scenarios/local-to-cloud-migration.mjs new file mode 100644 index 0000000..b59d934 --- /dev/null +++ b/apps/desktop/e2e/scenarios/local-to-cloud-migration.mjs @@ -0,0 +1,76 @@ +// Cambio de modo local → cloud (S4, A4): migra los workspaces, sesiones y +// terminales locales a la cuenta cloud sin borrar los que la cuenta ya tenía, +// y conserva intacto el archivo local. +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); + +const preExistingCloud = { + version: 1, + workspaces: [ + { + id: "w-cloud-existing", + name: "Equipo Cloud", + sessions: [ + { + id: "s-cloud-existing", + name: "Sesión compartida", + panes: [{ id: "p-cloud-1", seq: 0, minimized: false, initialCwd: null, agent: null }], + }, + ], + }, + ], +}; + +export default async function localToCloudMigration(page, checks) { + await wait(300); + + // Creamos un segundo workspace en modo local para verificar que viaja toda + // la estructura local al cambiar a Cloud. + await page.click(".ws-current"); + await wait(150); + await page.click(".ws-menu-new"); + await wait(300); + + const localBeforeSwitch = await page.evaluate(() => window.__mock.localSnapshot); + checks["en modo local se persisten los workspaces creados"] = + Array.isArray(localBeforeSwitch?.workspaces) && localBeforeSwitch.workspaces.length === 2; + + // La cuenta cloud ya tiene un workspace previo ("Equipo Cloud"). + await page.evaluate((cloud) => { + window.__mock.setCloudSnapshot(cloud); + window.__mock.signIn(); + }, preExistingCloud); + await wait(200); + + await page.click('button[aria-label="Settings"]'); + await wait(200); + await page.evaluate(() => { + const [, cloud] = document.querySelectorAll(".settings-mode input"); + cloud.click(); + }); + await wait(100); + + checks["Settings avisa que los datos locales se migran y el archivo local se conserva"] = + await page.evaluate(() => { + const hint = document.querySelector(".settings-hint")?.textContent ?? ""; + return hint.includes("migrated to your cloud account") && hint.includes("Local files are kept"); + }); + + await page.click(".modal-actions .btn--primary"); + await wait(500); + + const afterMigration = await page.evaluate(() => ({ + mode: window.__mock.storageConfig.mode, + localWorkspaces: window.__mock.localSnapshot?.workspaces?.map((w) => w.name) ?? [], + cloudWorkspaces: window.__mock.cloudSnapshot?.workspaces?.map((w) => w.name) ?? [], + })); + + checks["el cambio pasa a modo cloud"] = afterMigration.mode === "cloud"; + checks["la nube conserva su workspace previo y suma los migrados desde local"] = + afterMigration.cloudWorkspaces.includes("Equipo Cloud") && + afterMigration.cloudWorkspaces.includes("OpenCollab") && + afterMigration.cloudWorkspaces.includes("Workspace 2"); + checks["el archivo local se conserva intacto tras la migración (A4)"] = + afterMigration.localWorkspaces.length === 2 && + afterMigration.localWorkspaces.includes("OpenCollab") && + afterMigration.localWorkspaces.includes("Workspace 2"); +} diff --git a/apps/desktop/e2e/scenarios/onboarding.mjs b/apps/desktop/e2e/scenarios/onboarding.mjs new file mode 100644 index 0000000..9426963 --- /dev/null +++ b/apps/desktop/e2e/scenarios/onboarding.mjs @@ -0,0 +1,29 @@ +// Primera corrida: sin configuración completa la app muestra el onboarding y +// no monta la grilla. Elegir local persiste el modo y crea el snapshot default. +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); + +export default async function onboarding(page, checks) { + const base = page.url().split("?")[0]; + await page.goto(`${base}?mockFirstRun=1`, { waitUntil: "networkidle0" }); + await wait(300); + + checks["la primera corrida muestra el onboarding"] = (await page.$(".onboarding")) !== null; + checks["el onboarding reemplaza la grilla"] = (await page.$(".app")) === null; + + const clicked = await page.evaluate(() => { + const button = [...document.querySelectorAll(".onboarding-mode")].find((b) => + b.textContent.includes("Local"), + ); + if (button) button.click(); + return !!button; + }); + checks["ofrece elegir almacenamiento local"] = clicked; + await wait(500); + + checks["elegir local entra a la app"] = (await page.$(".app")) !== null; + checks["persiste el modo local"] = await page.evaluate( + () => window.__mock.storageConfig.onboardingComplete && window.__mock.storageConfig.mode === "local", + ); + checks["crea el snapshot default"] = + (await page.evaluate(() => window.__mock.savedSnapshot)) !== null; +} diff --git a/apps/desktop/e2e/scenarios/settings-storage.mjs b/apps/desktop/e2e/scenarios/settings-storage.mjs new file mode 100644 index 0000000..66d753c --- /dev/null +++ b/apps/desktop/e2e/scenarios/settings-storage.mjs @@ -0,0 +1,38 @@ +// Settings: el engranaje del TopBar abre el modal y guardar persiste la base +// URL vía `storage_config_set`. Con sesión anónima, cloud queda bloqueado. +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); + +export default async function settingsStorage(page, checks) { + await wait(300); + await page.click('button[aria-label="Settings"]'); + await wait(200); + checks["el engranaje abre Settings"] = (await page.$(".modal")) !== null; + checks["Settings muestra las dos opciones"] = + (await page.$$(".settings-mode")).length === 2; + + await page.evaluate(() => { + const input = document.querySelector(".settings-field input"); + const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set; + setter.call(input, "http://localhost:9999"); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + await page.click(".modal-actions .btn--primary"); + await wait(400); + + checks["guardar persiste la base URL"] = await page.evaluate( + () => window.__mock.storageConfig.apiBaseUrl === "http://localhost:9999", + ); + checks["guardar cierra el modal"] = (await page.$(".modal")) === null; + + await page.click('button[aria-label="Settings"]'); + await wait(200); + await page.evaluate(() => { + const [, cloud] = document.querySelectorAll(".settings-mode input"); + cloud.click(); + }); + await wait(100); + checks["cloud sin sesión no se puede guardar"] = await page.evaluate(() => { + const save = document.querySelector(".modal-actions .btn--primary"); + return save instanceof HTMLButtonElement && save.disabled; + }); +} diff --git a/apps/desktop/e2e/scenarios/snapshot-load-error.mjs b/apps/desktop/e2e/scenarios/snapshot-load-error.mjs new file mode 100644 index 0000000..39b3d57 --- /dev/null +++ b/apps/desktop/e2e/scenarios/snapshot-load-error.mjs @@ -0,0 +1,28 @@ +// Regresión de R4-load-error-destroys-snapshot: si el núcleo falla al cargar +// el snapshot, la app sigue con la estructura default pero NO debe habilitar +// el guardado; de lo contrario la primera mutación pisa el archivo válido. +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); + +export default async function snapshotLoadError(page, checks) { + const base = page.url().split("?")[0]; + await page.goto(`${base}?mockSnapshotLoadError=1`, { waitUntil: "networkidle0" }); + await wait(300); + + checks["el fallo de carga deja la estructura default"] = + (await page.$$(".pane:not([hidden])")).length === 1; + + // Primera mutación estructural después del fallo: abrir otra terminal. + await page.click(".topbar .btn--primary"); + await wait(300); + + checks["una mutación posterior al fallo no persiste el default"] = + (await page.evaluate(() => window.__mock.savedSnapshot)) === null; + + // Sin el fallo inyectado, la persistencia vuelve a funcionar en la carga siguiente. + await page.goto(base, { waitUntil: "networkidle0" }); + await wait(300); + await page.click(".topbar .btn--primary"); + await wait(300); + checks["sin el fallo, la mutación vuelve a persistir"] = + (await page.evaluate(() => window.__mock.savedSnapshot)) !== null; +} diff --git a/apps/desktop/e2e/tauri-mock.js b/apps/desktop/e2e/tauri-mock.js index 25d5920..bc71b74 100644 --- a/apps/desktop/e2e/tauri-mock.js +++ b/apps/desktop/e2e/tauri-mock.js @@ -11,6 +11,11 @@ // agentState(id, patch) emite terminal-agent-state con el estado completo (patch sobre el vacío) // branches carpeta -> { name, detached } devuelto por git_branch (sin entrada = no es un repo) // prompt(id, path) como la shell integration: OSC 7 + prompt (cambia la carpeta de la terminal) +// savedSnapshot último payload de snapshot_save (versión 1 estampada por el mock) +// storageConfig modo/base URL vigentes (storage_config_get/set) +// signIn()/signOut() simula el deep link de login / logout (emite auth-changed) +// setSnapshot(snap) precarga el snapshot que devuelve snapshot_load +// snapshotLoads cantidad de snapshot_load ejecutados export function installTauriMock() { const listeners = {}; // evento -> [id de callback] let callbacks = 0; @@ -19,6 +24,19 @@ export function installTauriMock() { const opened = []; const closed = []; const branches = {}; + let localSaved = null; // snapshot local (workspaces.json) + let cloudSaved = null; // snapshot cloud (API REST) + const params = new URLSearchParams(location.search); + // ?mockFirstRun=1 simula la primera corrida; ?mockCloud=1 arranca en cloud + // con la configuración completa pero sin sesión en memoria (reinicio real). + let signedIn = false; + let snapshotLoads = 0; + let storageConfig = { + version: 1, + mode: params.get("mockCloud") === "1" ? "cloud" : "local", + apiBaseUrl: "http://127.0.0.1:8787", + onboardingComplete: params.get("mockFirstRun") !== "1", + }; const encoder = new TextEncoder(); const emit = (event, payload) => @@ -51,7 +69,48 @@ export function installTauriMock() { }, }); - window.__mock = { emit, agentState, prompt, writes, opened, closed, branches }; + const user = { id: "u1", username: "tester", email: null, displayName: "Tester" }; + const signIn = () => { + signedIn = true; + emit("auth-changed", { user }); + }; + const signOut = () => { + signedIn = false; + emit("auth-changed", { user: null }); + }; + window.__mock = { + emit, + agentState, + prompt, + writes, + opened, + closed, + branches, + signIn, + signOut, + setSnapshot(snapshot) { + if (storageConfig.mode === "cloud") cloudSaved = snapshot; + else localSaved = snapshot; + }, + setCloudSnapshot(snapshot) { + cloudSaved = snapshot; + }, + get savedSnapshot() { + return storageConfig.mode === "cloud" ? cloudSaved : localSaved; + }, + get localSnapshot() { + return localSaved; + }, + get cloudSnapshot() { + return cloudSaved; + }, + get storageConfig() { + return storageConfig; + }, + get snapshotLoads() { + return snapshotLoads; + }, + }; window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} }; window.__TAURI_INTERNALS__ = { metadata: { @@ -90,6 +149,63 @@ export function installTauriMock() { closed.push(args.terminalId); setTimeout(() => emit("terminal-exit", { terminalId: args.terminalId }), 20); return null; + case "snapshot_load": + // Fallo de carga inyectado por el escenario de regresión (?mockSnapshotLoadError=1). + if (new URLSearchParams(location.search).get("mockSnapshotLoadError") === "1") + throw new Error("snapshot_load failed (e2e)"); + snapshotLoads += 1; + // Cloud sin tokens en memoria: el núcleo real responde sin sesión. + if (storageConfig.mode === "cloud" && !signedIn) + throw new Error("no hay sesión iniciada"); + // Sin snapshot guardado: primera corrida / arranque limpio. + { + const active = storageConfig.mode === "cloud" ? cloudSaved : localSaved; + return active ? JSON.parse(JSON.stringify(active)) : null; + } + case "snapshot_save": + // Guardado en memoria: los escenarios lo inspeccionan en __mock.savedSnapshot. + if (storageConfig.mode === "cloud") { + cloudSaved = { version: 1, workspaces: args.workspaces }; + } else { + localSaved = { version: 1, workspaces: args.workspaces }; + } + return null; + case "storage_config_get": + return { ...storageConfig }; + case "storage_config_set": { + // Migrar local → cloud (S4, A4): sube los workspaces locales uno por + // uno sin borrar los que ya tenía la nube y conserva `localSaved`. + if ( + storageConfig.onboardingComplete && + storageConfig.mode === "local" && + args.mode === "cloud" + ) { + if (new URLSearchParams(location.search).get("mockMigrateError") === "1") { + throw new Error("falló la migración local a cloud (e2e)"); + } + if (localSaved?.workspaces?.length) { + const existing = cloudSaved?.workspaces + ? JSON.parse(JSON.stringify(cloudSaved.workspaces)) + : []; + for (const ws of JSON.parse(JSON.stringify(localSaved.workspaces))) { + const idx = existing.findIndex((item) => item.id === ws.id); + if (idx >= 0) existing[idx] = ws; + else existing.push(ws); + } + cloudSaved = { version: 1, workspaces: existing }; + } + } + storageConfig = { + version: 1, + mode: args.mode, + apiBaseUrl: args.apiBaseUrl, + onboardingComplete: true, + }; + if (args.mode === "local") { + emit("collab-status", { connected: false, syncMs: null, collaborators: 1 }); + } + return { ...storageConfig }; + } case "collab_status": // Como el núcleo sin relay: desconectado, sin latencia, solo el usuario local. return { connected: false, syncMs: null, collaborators: 1 }; @@ -97,11 +213,13 @@ export function installTauriMock() { // Como el núcleo: guarda el verifier y abre la web (acá solo devuelve la URL). return `http://localhost:1421/login?client=desktop&code_challenge=${args.challenge}`; case "auth_finish": - return { id: "u1", username: "tester", email: null, displayName: "Tester" }; + signedIn = true; + return user; case "auth_status": // Sin sesión: anónimo (los E2E emiten `auth-changed` para simular el login). - return null; + return signedIn ? user : null; case "auth_logout": + signOut(); return null; case "git_branch": return branches[args.path] ?? null; diff --git a/apps/desktop/package.json b/apps/desktop/package.json index b77d4f0..29fd40f 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -4,7 +4,8 @@ "version": "0.4.0", "type": "module", "scripts": { - "dev": "vite", + "dev": "tauri dev -c src-tauri/tauri.dev.conf.json", + "dev:vite": "vite", "dev:desktop": "tauri dev -c src-tauri/tauri.dev.conf.json", "build": "tsc --noEmit && vite build", "preview": "vite preview", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 85364dd..f572f9d 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -17,5 +17,6 @@ protocol.workspace = true tauri.workspace = true tauri-plugin-deep-link = "2" tauri-plugin-single-instance = { version = "2", features = ["deep-link"] } +keyring.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/apps/desktop/src-tauri/src/auth.rs b/apps/desktop/src-tauri/src/auth.rs index 8913cc3..b0262b6 100644 --- a/apps/desktop/src-tauri/src/auth.rs +++ b/apps/desktop/src-tauri/src/auth.rs @@ -7,15 +7,19 @@ //! app. El frontend extrae el `code` y llama `auth_finish`, que lo canjea en //! `POST /auth/desktop/token`. //! -//! Los tokens viven **solo en la memoria del núcleo**; el frontend recibe el +//! El `access_token` de corta vida vive **solo en la memoria del núcleo** y el +//! `refresh_token` junto al usuario se persisten en el llavero seguro del +//! sistema operativo (`keyring`: Windows Credential Manager / macOS Keychain / +//! Linux Secret Service) siguiendo RFC 8252. El frontend recibe únicamente el //! usuario y el evento `auth-changed`. El HTTP va con `std::net`, sin runtime //! async (como `HttpRelayProbe`): el relay escucha en HTTP local sin TLS. use std::io::{Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; +use application::ports::{AccessTokenProvider, PortError}; use serde::{Deserialize, Serialize}; use tauri::{AppHandle, Emitter, State}; @@ -74,17 +78,108 @@ struct Session { user: UserView, } +/// Datos de la sesión que se persisten en el llavero del sistema operativo +/// (RFC 8252: el `access_token` de corta vida nunca sale de la memoria RAM). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PersistedSession { + pub refresh_token: String, + pub user: UserView, +} + +/// Puerto de almacenamiento seguro para la sesión de larga vida (`refresh_token` + usuario). +pub trait SessionVault: Send + Sync { + fn load(&self) -> Option; + fn save(&self, session: &PersistedSession); + fn clear(&self); +} + +struct NoopVault; + +impl SessionVault for NoopVault { + fn load(&self) -> Option { + None + } + fn save(&self, _session: &PersistedSession) {} + fn clear(&self) {} +} + +const KEYRING_USER: &str = "session"; + +/// Implementación de `SessionVault` sobre el almacén nativo de credenciales del SO. +struct KeyringVault { + service: &'static str, +} + +impl KeyringVault { + fn new(service: &'static str) -> Self { + Self { service } + } + + fn entry(&self) -> Result { + keyring::Entry::new(self.service, KEYRING_USER) + } +} + +impl SessionVault for KeyringVault { + fn load(&self) -> Option { + let raw = self.entry().ok()?.get_password().ok()?; + let persisted: PersistedSession = serde_json::from_str(&raw).ok()?; + if persisted.refresh_token.is_empty() || persisted.user.id.is_empty() { + return None; + } + Some(persisted) + } + + fn save(&self, session: &PersistedSession) { + let Ok(raw) = serde_json::to_string(session) else { + return; + }; + if let Ok(entry) = self.entry() { + let _ = entry.set_password(&raw); + } + } + + fn clear(&self) { + if let Ok(entry) = self.entry() { + let _ = entry.delete_credential(); + } + } +} + struct Inner { verifier: Option, session: Option, } -/// Sesión del desktop: dirección del relay, origen de la web y estado mutable -/// (verifier pendiente + tokens). Todo queda en memoria del proceso. +/// Resultado de consultar/renovar la sesión. `Fresh` no toca la red; `Refreshed` +/// ya actualizó el par de tokens; `Rejected` cerró la sesión (el relay rechazó +/// el refresh); `Malformed` conserva la sesión (respuesta ilegible o fallo transitorio). +enum RefreshOutcome { + Fresh { + user: UserView, + access_token: String, + }, + Refreshed { + user: UserView, + access_token: String, + }, + NoSession, + Rejected, + Malformed, +} + +/// Sesión del desktop: dirección del relay, origen de la web, llavero y estado +/// mutable (`access_token` y verifier PKCE solo en memoria; `refresh_token` en el llavero). pub struct AuthStore { api_addr: String, web_origin: String, + client: &'static str, + vault: Arc, inner: Mutex, + /// Serializa los refresh: si dos pedidos reciben 401 a la vez, el segundo + /// espera y reutiliza el token que renovó el primero. + refresh_lock: Mutex<()>, } impl AuthStore { @@ -93,20 +188,209 @@ impl AuthStore { Self { api_addr, web_origin, + client: "desktop", + vault: Arc::new(NoopVault), inner: Mutex::new(Inner { verifier: None, session: None, }), + refresh_lock: Mutex::new(()), + } + } + + /// Selecciona el identificador de cliente enviado a `/login` (`desktop-dev` + /// cuando la app corre bajo el perfil `com.opencollab.desktop.dev`, para que la + /// web devuelva el esquema aislado `opencollab-dev://`). + pub fn with_dev_client(mut self, is_dev: bool) -> Self { + self.client = if is_dev { "desktop-dev" } else { "desktop" }; + self + } + + /// Nombre del servicio en el llavero del SO (`opencollab` en producción y + /// `opencollab-dev` en desarrollo, igual que el esquema del deep link), + /// aislado para que sus rotaciones de `refresh_token` no se pisen mutuamente. + pub fn keyring_service(&self) -> &'static str { + if self.client == "desktop-dev" { + "opencollab-dev" + } else { + "opencollab" + } + } + + /// Conecta el llavero nativo del sistema operativo e hidrata la sesión si existe. + pub fn with_os_keyring(self) -> Self { + let service = self.keyring_service(); + self.with_vault(Arc::new(KeyringVault::new(service))) + } + + /// Conecta un `SessionVault` (llavero real o doble de pruebas) e hidrata la + /// sesión guardada con `access_token` vacío y vencimiento inmediato para que + /// el primer pedido o `auth_status` rote el `refresh_token` contra el relay. + pub fn with_vault(mut self, vault: Arc) -> Self { + if let Some(persisted) = vault.load() { + if !persisted.refresh_token.is_empty() { + self.inner.lock().expect("auth").session = Some(Session { + access_token: String::new(), + refresh_token: persisted.refresh_token, + expires_at: Instant::now(), + user: persisted.user, + }); + } } + self.vault = vault; + self + } + + /// Elimina la sesión de la memoria y del llavero, devolviendo el `refresh_token` + /// vigente para avisar al relay en `/auth/logout`. + pub fn clear_session(&self) -> Option { + let refresh_token = self + .inner + .lock() + .expect("auth") + .session + .take() + .map(|session| session.refresh_token); + self.vault.clear(); + refresh_token + } + + /// Hay una sesión en memoria (puede estar vencida: el refresh lo decide + /// el pedido). El modo nube exige al menos esto para configurarse. + pub fn has_session(&self) -> bool { + self.inner.lock().expect("auth").session.is_some() } /// URL de la web donde el usuario hace el login para esta máquina. pub fn login_url(&self, challenge: &str) -> String { format!( - "{}/login?client=desktop&code_challenge={challenge}", - self.web_origin + "{}/login?client={}&code_challenge={challenge}", + self.web_origin, self.client ) } + + /// Token para un pedido a la API: si el access venció o está por vencer, + /// renueva el par antes de devolverlo. Sin sesión (o refresh rechazado) es + /// un error: el modo nube nunca manda un pedido sin credencial. + pub fn access_token_for_request(&self) -> Result { + match self.refresh_now(false, None) { + RefreshOutcome::Fresh { access_token, .. } + | RefreshOutcome::Refreshed { access_token, .. } => Ok(access_token), + RefreshOutcome::NoSession | RefreshOutcome::Rejected => { + Err("no hay sesión iniciada".to_string()) + } + RefreshOutcome::Malformed => Err("respuesta del relay inválida".to_string()), + } + } + + /// Igual que `access_token_for_request`, pero fuerza el refresh si el + /// token rechazado sigue siendo el vigente. Si otro pedido ya renovó + /// (`rejected` quedó viejo), devuelve el token nuevo sin otra red. + pub fn refreshed_access_token_for_request(&self, rejected: &str) -> Result { + match self.refresh_now(true, Some(rejected)) { + RefreshOutcome::Fresh { access_token, .. } + | RefreshOutcome::Refreshed { access_token, .. } => Ok(access_token), + RefreshOutcome::NoSession | RefreshOutcome::Rejected => { + Err("no hay sesión iniciada".to_string()) + } + RefreshOutcome::Malformed => Err("respuesta del relay inválida".to_string()), + } + } + + /// Estado de la sesión y, si corresponde, refresh contra el relay. Es la + /// única implementación del refresh: la comparten `auth_status` y el + /// proveedor de tokens del modo nube. + fn refresh_now(&self, force: bool, rejected: Option<&str>) -> RefreshOutcome { + let _refresh = self.refresh_lock.lock().expect("refresh lock"); + let refresh_token = { + let inner = self.inner.lock().expect("auth"); + let Some(session) = inner.session.as_ref() else { + return RefreshOutcome::NoSession; + }; + if let Some(rejected) = rejected { + if !session.access_token.is_empty() && session.access_token != rejected { + return RefreshOutcome::Fresh { + user: session.user.clone(), + access_token: session.access_token.clone(), + }; + } + } + if !force + && !session.access_token.is_empty() + && session.expires_at.saturating_duration_since(Instant::now()) > REFRESH_MARGIN + { + return RefreshOutcome::Fresh { + user: session.user.clone(), + access_token: session.access_token.clone(), + }; + } + session.refresh_token.clone() + }; + let body = format!("{{\"refreshToken\":\"{}\"}}", json_escape(&refresh_token)); + match post_json(self, "/auth/refresh", &body) { + Ok((200, raw)) => match serde_json::from_slice::(&raw) { + Ok(pair) => { + let (outcome, persisted) = { + let mut inner = self.inner.lock().expect("auth"); + let Some(session) = inner.session.as_mut() else { + return RefreshOutcome::NoSession; + }; + session.access_token = pair.access_token; + session.refresh_token = pair.refresh_token; + session.expires_at = Instant::now() + Duration::from_secs(pair.expires_in); + let persisted = PersistedSession { + refresh_token: session.refresh_token.clone(), + user: session.user.clone(), + }; + ( + RefreshOutcome::Refreshed { + user: session.user.clone(), + access_token: session.access_token.clone(), + }, + persisted, + ) + }; + self.vault.save(&persisted); + outcome + } + Err(_) => RefreshOutcome::Malformed, + }, + Ok((400 | 401 | 403, _)) => { + let should_clear = { + let mut inner = self.inner.lock().expect("auth"); + if inner + .session + .as_ref() + .is_some_and(|s| s.refresh_token == refresh_token) + { + inner.session = None; + true + } else { + false + } + }; + if should_clear { + self.vault.clear(); + } + RefreshOutcome::Rejected + } + // Fallos de red (`Err`) o errores transitorios del servidor (`5xx`, `429`): + // se preserva la sesión en memoria y en el llavero para no desloguear al + // usuario cuando el relay local todavía está arrancando o hay microcortes. + _ => RefreshOutcome::Malformed, + } + } +} + +impl AccessTokenProvider for AuthStore { + fn access_token(&self) -> Result { + self.access_token_for_request().map_err(PortError::new) + } + + fn refreshed_access_token(&self, rejected: &str) -> Result { + self.refreshed_access_token_for_request(rejected) + .map_err(PortError::new) + } } /// Resuelve el origen de la web para el login: @@ -159,10 +443,13 @@ fn is_valid_code(value: &str) -> bool { .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') } -/// `code` del deep link `opencollab://auth/callback?code=…`; `None` si la URL no -/// es un callback de login (nunca confiar en un deep link con otra forma). +/// `code` del deep link `opencollab://auth/callback?code=…` (o +/// `opencollab-dev://auth/callback?code=…` en dev); `None` si la URL no es un +/// callback de login (nunca confiar en un deep link con otra forma). pub fn parse_callback_code(url: &str) -> Option { - let rest = url.strip_prefix("opencollab://")?; + let rest = url + .strip_prefix("opencollab://") + .or_else(|| url.strip_prefix("opencollab-dev://"))?; let (path, query) = rest.split_once('?')?; if path != "auth/callback" { return None; @@ -281,6 +568,10 @@ fn emit_changed(app: &AppHandle, user: Option) { } fn adopt_session(store: &AuthStore, result: AuthResultBody) -> UserView { + let persisted = PersistedSession { + refresh_token: result.refresh_token.clone(), + user: result.user.clone(), + }; let session = Session { access_token: result.access_token, refresh_token: result.refresh_token, @@ -288,6 +579,7 @@ fn adopt_session(store: &AuthStore, result: AuthResultBody) -> UserView { user: result.user.clone(), }; store.inner.lock().expect("auth").session = Some(session); + store.vault.save(&persisted); result.user } @@ -349,63 +641,32 @@ pub fn auth_finish( /// lo renueva una vez (igual que la web); si el refresh falla, cierra la sesión. #[tauri::command(async)] pub fn auth_status(app: AppHandle, state: State<'_, AppState>) -> Result, String> { - if let Some(user) = fresh_user(&state.auth) { - return Ok(Some(user)); - } - let Some(refresh_token) = refresh_due(&state.auth) else { - return Ok(state + match state.auth.refresh_now(false, None) { + RefreshOutcome::Fresh { user, .. } => Ok(Some(user)), + RefreshOutcome::Refreshed { user, .. } => { + emit_changed(&app, Some(user.clone())); + Ok(Some(user)) + } + RefreshOutcome::NoSession => Ok(None), + RefreshOutcome::Rejected => { + emit_changed(&app, None); + Ok(None) + } + RefreshOutcome::Malformed => Ok(state .auth .inner .lock() .expect("auth") .session .as_ref() - .map(|s| s.user.clone())); - }; - let body = format!("{{\"refreshToken\":\"{}\"}}", json_escape(&refresh_token)); - match post_json(&state.auth, "/auth/refresh", &body) { - Ok((200, raw)) => match serde_json::from_slice::(&raw) { - Ok(pair) => { - let mut inner = state.auth.inner.lock().expect("auth"); - if let Some(session) = inner.session.as_mut() { - session.access_token = pair.access_token; - session.refresh_token = pair.refresh_token; - session.expires_at = Instant::now() + Duration::from_secs(pair.expires_in); - let user = session.user.clone(); - drop(inner); - emit_changed(&app, Some(user.clone())); - return Ok(Some(user)); - } - Ok(None) - } - Err(_) => Ok(state - .auth - .inner - .lock() - .expect("auth") - .session - .as_ref() - .map(|s| s.user.clone())), - }, - _ => { - state.auth.inner.lock().expect("auth").session = None; - emit_changed(&app, None); - Ok(None) - } + .map(|s| s.user.clone())), } } -/// Cierra la sesión (avisa al relay sin bloquear) y emite `auth-changed` sin usuario. +/// Cierra la sesión (avisa al relay sin bloquear), limpia el llavero y emite `auth-changed` sin usuario. #[tauri::command(async)] pub fn auth_logout(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> { - let refresh_token = state - .auth - .inner - .lock() - .expect("auth") - .session - .take() - .map(|session| session.refresh_token); + let refresh_token = state.auth.clear_session(); if let Some(refresh_token) = refresh_token { let body = format!("{{\"refreshToken\":\"{}\"}}", json_escape(&refresh_token)); let _ = post_json(&state.auth, "/auth/logout", &body); @@ -414,29 +675,6 @@ pub fn auth_logout(app: AppHandle, state: State<'_, AppState>) -> Result<(), Str Ok(()) } -fn fresh_user(store: &AuthStore) -> Option { - let inner = store.inner.lock().expect("auth"); - inner.session.as_ref().and_then(|session| { - if session.expires_at.saturating_duration_since(Instant::now()) > REFRESH_MARGIN { - Some(session.user.clone()) - } else { - None - } - }) -} - -/// Refresh token si la sesión existe y el access está vencido o por vencer. -fn refresh_due(store: &AuthStore) -> Option { - let inner = store.inner.lock().expect("auth"); - inner.session.as_ref().and_then(|session| { - if session.expires_at.saturating_duration_since(Instant::now()) <= REFRESH_MARGIN { - Some(session.refresh_token.clone()) - } else { - None - } - }) -} - #[cfg(test)] mod tests { use super::*; @@ -455,10 +693,13 @@ mod tests { let store = AuthStore { api_addr: "127.0.0.1:8787".to_string(), web_origin: "https://app.example.com".to_string(), + client: "desktop", + vault: Arc::new(NoopVault), inner: Mutex::new(Inner { verifier: None, session: None, }), + refresh_lock: Mutex::new(()), }; assert_eq!( store.login_url(&"a".repeat(43)), @@ -467,6 +708,14 @@ mod tests { "a".repeat(43) ) ); + let dev_store = store.with_dev_client(true); + assert_eq!( + dev_store.login_url(&"a".repeat(43)), + format!( + "https://app.example.com/login?client=desktop-dev&code_challenge={}", + "a".repeat(43) + ) + ); } #[test] @@ -485,6 +734,10 @@ mod tests { parse_callback_code("opencollab://auth/callback?code=abc123"), Some("abc123".to_string()) ); + assert_eq!( + parse_callback_code("opencollab-dev://auth/callback?code=dev123"), + Some("dev123".to_string()) + ); // Parámetros extra no molestan; el primero que vale es el code. assert_eq!( parse_callback_code("opencollab://auth/callback?foo=1&code=xyz"), @@ -558,4 +811,321 @@ mod tests { }); assert_eq!(origin, "http://localhost:1421"); } + + fn store_with_session(access_token: &str, refresh_token: &str) -> AuthStore { + AuthStore { + api_addr: "127.0.0.1:1".to_string(), + web_origin: DEFAULT_WEB_ORIGIN.to_string(), + client: "desktop", + vault: Arc::new(NoopVault), + inner: Mutex::new(Inner { + verifier: None, + session: Some(Session { + access_token: access_token.to_string(), + refresh_token: refresh_token.to_string(), + expires_at: Instant::now() + Duration::from_secs(600), + user: UserView { + id: "u1".to_string(), + username: "ana".to_string(), + email: None, + display_name: "Ana".to_string(), + }, + }), + }), + refresh_lock: Mutex::new(()), + } + } + + #[test] + fn fresh_session_token_comes_from_memory_without_the_relay() { + // El relay apunta a un puerto cerrado a propósito: un token vigente no + // debe intentar red, ni por el método propio ni por el puerto. + let store = store_with_session("access-1", "refresh-1"); + assert_eq!(store.access_token_for_request().unwrap(), "access-1"); + assert_eq!( + AccessTokenProvider::access_token(&store).unwrap(), + "access-1" + ); + } + + #[test] + fn no_session_cannot_produce_a_token() { + let store = AuthStore { + api_addr: "127.0.0.1:1".to_string(), + web_origin: DEFAULT_WEB_ORIGIN.to_string(), + client: "desktop", + vault: Arc::new(NoopVault), + inner: Mutex::new(Inner { + verifier: None, + session: None, + }), + refresh_lock: Mutex::new(()), + }; + assert_eq!( + store.access_token_for_request(), + Err("no hay sesión iniciada".to_string()) + ); + assert!(AccessTokenProvider::access_token(&store).is_err()); + assert!(store.refreshed_access_token_for_request("stale").is_err()); + assert!(!store.has_session()); + } + + #[test] + fn a_stale_rejected_token_reuses_the_concurrent_refresh_without_network() { + // El relay apunta a un puerto cerrado: si el short-circuit no ocurre, + // este test falla por timeout de red en vez de devolver el token nuevo. + let store = store_with_session("access-2", "refresh-2"); + // El 401 llegó con "access-1", pero otro pedido ya renovó a "access-2". + assert_eq!( + store + .refreshed_access_token_for_request("access-1") + .unwrap(), + "access-2" + ); + assert!(store.has_session()); + } + + #[test] + fn dos_401_concurrentes_comparten_un_solo_refresh() { + use std::io::{Read, Write}; + use std::net::TcpListener; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::{Arc, Barrier}; + + let listener = TcpListener::bind("127.0.0.1:0").expect("listener"); + let addr = listener.local_addr().expect("addr").to_string(); + let hits = Arc::new(AtomicUsize::new(0)); + let hits_server = Arc::clone(&hits); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { continue }; + let mut buf = [0u8; 4096]; + let _ = stream.read(&mut buf); + hits_server.fetch_add(1, Ordering::SeqCst); + let body = + r#"{"accessToken":"access-2","refreshToken":"refresh-2","expiresIn":600}"#; + let response = format!( + "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}", + body.len(), + body + ); + let _ = stream.write_all(response.as_bytes()); + } + }); + + let store = Arc::new(AuthStore { + api_addr: addr, + web_origin: DEFAULT_WEB_ORIGIN.to_string(), + client: "desktop", + vault: Arc::new(NoopVault), + inner: Mutex::new(Inner { + verifier: None, + session: Some(Session { + access_token: "access-1".to_string(), + refresh_token: "refresh-1".to_string(), + expires_at: Instant::now() + Duration::from_secs(600), + user: UserView { + id: "u1".to_string(), + username: "ana".to_string(), + email: None, + display_name: "Ana".to_string(), + }, + }), + }), + refresh_lock: Mutex::new(()), + }); + + let barrier = Arc::new(Barrier::new(2)); + let handles: Vec<_> = (0..2) + .map(|_| { + let store = Arc::clone(&store); + let barrier = Arc::clone(&barrier); + std::thread::spawn(move || { + barrier.wait(); + store.refreshed_access_token_for_request("access-1") + }) + }) + .collect(); + for handle in handles { + assert_eq!(handle.join().expect("hilo"), Ok("access-2".to_string())); + } + assert_eq!( + hits.load(Ordering::SeqCst), + 1, + "un solo refresh para dos 401" + ); + } + + #[derive(Default)] + struct MemoryVault { + stored: Mutex>, + } + + impl MemoryVault { + fn with(session: PersistedSession) -> Arc { + Arc::new(Self { + stored: Mutex::new(Some(session)), + }) + } + } + + impl SessionVault for MemoryVault { + fn load(&self) -> Option { + self.stored.lock().expect("vault").clone() + } + fn save(&self, session: &PersistedSession) { + *self.stored.lock().expect("vault") = Some(session.clone()); + } + fn clear(&self) { + *self.stored.lock().expect("vault") = None; + } + } + + fn sample_user() -> UserView { + UserView { + id: "u1".to_string(), + username: "ana".to_string(), + email: Some("ana@example.com".to_string()), + display_name: "Ana".to_string(), + } + } + + fn serve_once(status_line: &'static str, response_body: &'static str) -> String { + use std::io::{Read, Write}; + use std::net::TcpListener; + + let listener = TcpListener::bind("127.0.0.1:0").expect("listener"); + let addr = listener.local_addr().expect("addr").to_string(); + std::thread::spawn(move || { + if let Ok((mut stream, _)) = listener.accept() { + let mut buf = [0u8; 4096]; + let _ = stream.read(&mut buf); + let response = format!( + "HTTP/1.1 {status_line}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{response_body}", + response_body.len() + ); + let _ = stream.write_all(response.as_bytes()); + } + }); + addr + } + + #[test] + fn servicio_del_llavero_aisla_produccion_y_desarrollo() { + let prod = AuthStore::new("127.0.0.1:8787".to_string()); + assert_eq!(prod.keyring_service(), "opencollab"); + let dev = AuthStore::new("127.0.0.1:8787".to_string()).with_dev_client(true); + assert_eq!(dev.keyring_service(), "opencollab-dev"); + } + + #[test] + fn adopt_session_guarda_refresh_y_usuario_en_el_llavero_y_logout_lo_limpia() { + let vault = Arc::new(MemoryVault::default()); + let store = AuthStore::new("127.0.0.1:1".to_string()).with_vault(vault.clone()); + let user = sample_user(); + + let returned = adopt_session( + &store, + AuthResultBody { + access_token: "access-secreto".to_string(), + refresh_token: "refresh-1".to_string(), + expires_in: 900, + user: user.clone(), + }, + ); + assert_eq!(returned, user); + assert_eq!( + vault.load(), + Some(PersistedSession { + refresh_token: "refresh-1".to_string(), + user, + }) + ); + + let cleared = store.clear_session(); + assert_eq!(cleared.as_deref(), Some("refresh-1")); + assert!(!store.has_session()); + assert_eq!(vault.load(), None); + } + + #[test] + fn restaura_la_sesion_del_llavero_y_renueva_el_access_en_el_primer_pedido() { + let addr = serve_once( + "200 OK", + r#"{"accessToken":"access-nuevo","refreshToken":"refresh-rotado","expiresIn":600}"#, + ); + let vault = MemoryVault::with(PersistedSession { + refresh_token: "refresh-guardado".to_string(), + user: sample_user(), + }); + let store = AuthStore::new(addr).with_vault(vault.clone()); + assert!( + store.has_session(), + "debe hidratar la sesión del llavero al iniciar" + ); + + let token = store + .access_token_for_request() + .expect("refresh al iniciar"); + assert_eq!(token, "access-nuevo"); + assert_eq!( + vault.load().map(|s| s.refresh_token), + Some("refresh-rotado".to_string()), + "el refresh rotado debe persistirse en el llavero" + ); + } + + #[test] + fn fallo_de_red_o_5xx_preserva_la_sesion_en_memoria_y_en_el_llavero() { + let vault = MemoryVault::with(PersistedSession { + refresh_token: "refresh-vivo".to_string(), + user: sample_user(), + }); + // 1. Relay caído (puerto cerrado) + let store_down = AuthStore::new("127.0.0.1:1".to_string()).with_vault(vault.clone()); + assert!(store_down.access_token_for_request().is_err()); + assert!( + store_down.has_session(), + "un fallo de conexión no debe cerrar la sesión local" + ); + assert_eq!( + vault.load().map(|s| s.refresh_token), + Some("refresh-vivo".to_string()), + "un fallo de conexión no debe borrar el llavero" + ); + + // 2. Relay responde 503 Service Unavailable + let addr_503 = serve_once("503 Service Unavailable", r#"{"message":"starting"}"#); + let store_503 = AuthStore::new(addr_503).with_vault(vault.clone()); + assert!(store_503.access_token_for_request().is_err()); + assert!( + store_503.has_session(), + "un 5xx del relay no debe cerrar la sesión local" + ); + assert_eq!( + vault.load().map(|s| s.refresh_token), + Some("refresh-vivo".to_string()), + "un 5xx del relay no debe borrar el llavero" + ); + } + + #[test] + fn rechazo_401_del_relay_borra_la_sesion_de_memoria_y_del_llavero() { + let addr_401 = serve_once("401 Unauthorized", r#"{"message":"Invalid refresh token"}"#); + let vault = MemoryVault::with(PersistedSession { + refresh_token: "refresh-revocado".to_string(), + user: sample_user(), + }); + let store = AuthStore::new(addr_401).with_vault(vault.clone()); + assert_eq!( + store.access_token_for_request(), + Err("no hay sesión iniciada".to_string()) + ); + assert!(!store.has_session()); + assert_eq!( + vault.load(), + None, + "un 401 explícito del relay debe limpiar el llavero" + ); + } } diff --git a/apps/desktop/src-tauri/src/collab_status.rs b/apps/desktop/src-tauri/src/collab_status.rs index e3e8659..2d1f09a 100644 --- a/apps/desktop/src-tauri/src/collab_status.rs +++ b/apps/desktop/src-tauri/src/collab_status.rs @@ -9,6 +9,7 @@ use serde::Serialize; use tauri::{AppHandle, Emitter, Manager}; use crate::state::AppState; +use crate::storage_config::StorageMode; pub const COLLAB_STATUS_EVENT: &str = "collab-status"; const INTERVAL: Duration = Duration::from_secs(3); @@ -47,15 +48,28 @@ impl CollabStatusPayload { /// colaboradores. No falla: si el conteo da error, el estado del relay se /// sigue reportando con el último conteo conocido (`last_collaborators`). pub fn snapshot(state: &AppState, last_collaborators: Option) -> CollabStatusPayload { - let collaborators = state.session_collaborators.execute(state.session_id); + snapshot_for_mode( + state.storage_config().mode, + || state.check_relay.execute(), + || state.session_collaborators.execute(state.session_id), + last_collaborators, + ) +} + +fn snapshot_for_mode( + mode: StorageMode, + probe_relay: impl FnOnce() -> RelayStatus, + count_collaborators: impl FnOnce() -> Result, + last_collaborators: Option, +) -> CollabStatusPayload { + if mode == StorageMode::Local { + return CollabStatusPayload::new(RelayStatus::Disconnected, 1); + } + let collaborators = count_collaborators(); if let Err(e) = &collaborators { eprintln!("estado de colaboración: {e}"); } - compose( - state.check_relay.execute(), - collaborators, - last_collaborators, - ) + compose(probe_relay(), collaborators, last_collaborators) } /// Arma el estado sin dejar que un error del conteo tape el del relay: usa el @@ -184,4 +198,39 @@ mod tests { let json = serde_json::to_value(disconnected(1)).unwrap(); assert_eq!(json["syncMs"], serde_json::Value::Null); } + + #[test] + fn local_mode_keeps_collaboration_inactive_without_probing_the_relay() { + let mut probed = false; + let mut counted = false; + let payload = snapshot_for_mode( + StorageMode::Local, + || { + probed = true; + RelayStatus::Connected { latency_ms: 11 } + }, + || { + counted = true; + Ok(4) + }, + Some(3), + ); + assert_eq!(payload, disconnected(1)); + assert!(!probed, "el modo local no debe sondear el relay"); + assert!( + !counted, + "el modo local no debe consultar colaboradores remotos" + ); + } + + #[test] + fn cloud_mode_probes_the_relay_and_counts_collaborators() { + let payload = snapshot_for_mode( + StorageMode::Cloud, + || RelayStatus::Connected { latency_ms: 18 }, + || Ok(3), + Some(1), + ); + assert_eq!(payload, connected(18, 3)); + } } diff --git a/apps/desktop/src-tauri/src/commands.rs b/apps/desktop/src-tauri/src/commands.rs index 3a01385..819c229 100644 --- a/apps/desktop/src-tauri/src/commands.rs +++ b/apps/desktop/src-tauri/src/commands.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use std::time::Instant; use application::ports::{TerminalOutputSink, TerminalSize}; +use application::storage::{StoredWorkspace, WorkspaceSnapshot}; use domain::TerminalId; use serde::Serialize; use tauri::{AppHandle, Emitter, State}; @@ -15,6 +16,7 @@ use application::{exit_event, ActivityTracker, AgentAdapters, AgentStates, Known use crate::agent_events::TauriAgentEvents; use crate::collab_status::{self, CollabStatusPayload}; use crate::state::AppState; +use crate::storage_config::{StorageConfig, StorageMode}; pub const TERMINAL_OUTPUT_EVENT: &str = "terminal-output"; pub const TERMINAL_EXIT_EVENT: &str = "terminal-exit"; @@ -247,3 +249,64 @@ pub fn resize_terminal( ) .map_err(|e| e.to_string()) } + +// Snapshot de la estructura del escritorio (S5 del feature desktop-dual-storage). +// Disco: `async` para no frenar la UI; las escrituras las encola el frontend +// (una cola de promesas), así que acá no hace falta serializarlas más. + +/// El snapshot guardado; `None` si no hay nada (primera corrida, arranque +/// limpio o cuarentena del archivo corrupto anterior). +#[tauri::command(async)] +pub fn snapshot_load(state: State<'_, AppState>) -> Result, String> { + state + .snapshot_store() + .load_snapshot() + .map_err(|e| e.to_string()) +} + +/// Guarda la estructura completa. La versión del formato la maneja el núcleo +/// (`WorkspaceSnapshot::new` estampa `SNAPSHOT_VERSION`). Un snapshot vacío se +/// rechaza: un estado sin hidratar no debe borrar la nube. +#[tauri::command(async)] +pub fn snapshot_save( + state: State<'_, AppState>, + workspaces: Vec, +) -> Result<(), String> { + if workspaces.is_empty() { + return Err("se rechazó guardar un snapshot vacío".to_string()); + } + let snapshot = WorkspaceSnapshot::new(workspaces); + state + .snapshot_store() + .save_snapshot(&snapshot) + .map_err(|e| e.to_string()) +} + +/// Configuración vigente de almacenamiento (modo, base URL, onboarding). +#[tauri::command] +pub fn storage_config_get(state: State<'_, AppState>) -> StorageConfig { + state.storage_config() +} + +/// Cambia el modo de almacenamiento y persiste la configuración. Cloud exige +/// una sesión iniciada; el store se reemplaza antes de devolver el resultado. +#[tauri::command(async)] +pub fn storage_config_set( + app: AppHandle, + state: State<'_, AppState>, + mode: StorageMode, + api_base_url: String, +) -> Result { + let current = state.storage_config(); + let updated = state.set_storage_config(StorageConfig { + version: current.version, + mode, + api_base_url, + onboarding_complete: current.onboarding_complete, + })?; + let _ = app.emit( + collab_status::COLLAB_STATUS_EVENT, + collab_status::snapshot(&state, None), + ); + Ok(updated) +} diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index 0edb912..aceeb54 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -8,6 +8,7 @@ mod collab_status; mod commands; mod env; mod state; +mod storage_config; use tauri::Manager; @@ -32,7 +33,21 @@ fn main() { let _ = window.set_icon(icon.clone()); } } - app.manage(state::AppState::bootstrap()?); + // appdata del bundle (app_data_dir une el identificador del + // tauri.conf.json a la carpeta de datos del usuario). + let data_dir = app + .path() + .app_data_dir() + .map_err(|e| format!("no se pudo resolver el directorio de datos: {e}"))?; + let is_dev_app = app.config().identifier.ends_with(".dev"); + #[cfg(any(windows, target_os = "linux"))] + if is_dev_app { + use tauri_plugin_deep_link::DeepLinkExt; + if let Err(e) = app.deep_link().register("opencollab-dev") { + eprintln!("no se pudo registrar el esquema opencollab-dev://: {e}"); + } + } + app.manage(state::AppState::bootstrap(data_dir, is_dev_app)?); agent_watcher::spawn(app.handle().clone()); collab_status::spawn(app.handle().clone()); Ok(()) @@ -43,6 +58,10 @@ fn main() { commands::write_terminal, commands::resize_terminal, commands::close_terminal, + commands::snapshot_load, + commands::snapshot_save, + commands::storage_config_get, + commands::storage_config_set, commands::list_subdirectories, commands::git_branch, commands::collab_status, diff --git a/apps/desktop/src-tauri/src/state.rs b/apps/desktop/src-tauri/src/state.rs index 9708d87..2977f1a 100644 --- a/apps/desktop/src-tauri/src/state.rs +++ b/apps/desktop/src-tauri/src/state.rs @@ -1,7 +1,12 @@ -use std::sync::Arc; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, RwLock}; use std::time::Duration; -use application::ports::{ProcessInspector, PtyPort, RelayProbe, SessionRepository}; +use application::ports::{ + AccessTokenProvider, PortError, ProcessInspector, PtyPort, RelayProbe, SessionRepository, + SnapshotStore, +}; +use application::storage::WorkspaceSnapshot; use application::{ ActivityTracker, AgentAdapter, AgentAdapters, AgentStates, AppError, CheckRelay, CloseTerminal, DetectTerminalAgents, InspectBranch, LaunchTerminal, ListSubdirectories, ResizeTerminal, @@ -9,16 +14,18 @@ use application::{ }; use domain::{Session, SessionId, UserId}; use infrastructure::{ - ClaudeCodeAdapter, FsDirectoryBrowser, FsRepositoryInspector, HookReceiver, HttpRelayProbe, - InMemorySessionRepository, OpenCodeAdapter, PortablePtyAdapter, SysinfoProcessInspector, + ClaudeCodeAdapter, CloudSnapshotStore, FsDirectoryBrowser, FsRepositoryInspector, + FsSnapshotStore, HookReceiver, HttpRelayProbe, InMemorySessionRepository, OpenCodeAdapter, + PortablePtyAdapter, SysinfoProcessInspector, }; use crate::auth::AuthStore; +use crate::storage_config::{StorageConfig, StorageMode}; /// Silencio de un PTY a partir del cual se considera inactivo. const ACTIVITY_IDLE_AFTER: Duration = Duration::from_secs(3); -/// Dependencias cableadas de la app. Mientras no haya cuentas ni persistencia, -/// arranca con un usuario local dueño de una sesión. +/// Dependencias cableadas de la app. El usuario local sigue siendo el dueño de +/// la sesión de arranque; la persistencia la elige `storage_config`. pub struct AppState { pub local_user: UserId, pub session_id: SessionId, @@ -38,8 +45,14 @@ pub struct AppState { pub adapters: Arc, pub check_relay: CheckRelay, pub session_collaborators: SessionCollaborators, - /// Sesión del desktop (tokens solo en memoria) + verifier PKCE pendiente. - pub auth: AuthStore, + /// Sesión del desktop (`access_token` y verifier PKCE en memoria; `refresh_token` en el llavero del SO). + pub auth: Arc, + /// Persistencia de la estructura del escritorio (snapshot de workspaces, + /// sesiones y perfiles de arranque). Se reemplaza al cambiar de modo. + pub snapshot_store: RwLock>, + /// Modo y base URL vigentes; se persisten en appdata. + pub storage_config: RwLock, + data_dir: PathBuf, } /// Adaptadores ricos disponibles. Si uno no puede arrancar (p. ej. no abre su @@ -55,7 +68,11 @@ fn agent_adapters() -> Vec> { } impl AppState { - pub fn bootstrap() -> Result { + /// `data_dir` es el directorio de datos de la app (appdata resuelto por + /// Tauri en el setup); el port lo implanta en un archivo, no lo crea. + /// Cuando `is_dev_app` es `true`, el login usa `client=desktop-dev` para + /// regresar por el esquema aislado `opencollab-dev://`. + pub fn bootstrap(data_dir: std::path::PathBuf, is_dev_app: bool) -> Result { crate::env::load_dot_env(); let repo: Arc = Arc::new(InMemorySessionRepository::new()); let pty: Arc = Arc::new(PortablePtyAdapter::new()); @@ -71,6 +88,15 @@ impl AppState { let session_id = session.id(); repo.save_session(session)?; + let auth = Arc::new( + AuthStore::new(relay_addr.clone()) + .with_dev_client(is_dev_app) + .with_os_keyring(), + ); + let default_api_base_url = format!("http://{relay_addr}"); + let config = StorageConfig::load(&data_dir, &default_api_base_url); + let snapshot_store = build_snapshot_store(&config, &data_dir, auth.clone()); + Ok(Self { local_user, session_id, @@ -87,9 +113,64 @@ impl AppState { adapters: Arc::new(AgentAdapters::new(agent_adapters())), check_relay: CheckRelay::new(relay_probe), session_collaborators: SessionCollaborators::new(repo), - auth: AuthStore::new(relay_addr), + auth, + snapshot_store: RwLock::new(snapshot_store), + storage_config: RwLock::new(config), + data_dir, }) } + + /// Store vigente; se clona el `Arc` para no sostener el lock durante I/O. + pub fn snapshot_store(&self) -> Arc { + self.snapshot_store.read().expect("snapshot store").clone() + } + + pub fn storage_config(&self) -> StorageConfig { + self.storage_config.read().expect("storage config").clone() + } + + /// Persiste el modo/base URL, valida que cloud tenga sesión y cambia el + /// store antes de devolver la configuración ya completa. Al pasar de local + /// a cloud migra el snapshot local a la cuenta (S4, A4) dejando el archivo + /// local intacto. + pub fn set_storage_config(&self, mut config: StorageConfig) -> Result { + config.validate()?; + if config.mode == StorageMode::Cloud && !self.auth.has_session() { + return Err("iniciá sesión antes de usar el modo nube".to_string()); + } + let current = self.storage_config(); + let store: Arc = match config.mode { + StorageMode::Local => Arc::new(FsSnapshotStore::new(self.data_dir.clone())), + StorageMode::Cloud => { + let tokens: Arc = self.auth.clone(); + let cloud = Arc::new(CloudSnapshotStore::new(config.api_base_url.clone(), tokens)); + let local = FsSnapshotStore::new(self.data_dir.clone()); + migrate_local_snapshot_if_needed(¤t, config.mode, &local, |snapshot| { + cloud.migrate_snapshot(snapshot) + })?; + cloud + } + }; + config.onboarding_complete = true; + config.save(&self.data_dir)?; + *self.snapshot_store.write().expect("snapshot store") = store; + *self.storage_config.write().expect("storage config") = config.clone(); + Ok(config) + } +} + +fn build_snapshot_store( + config: &StorageConfig, + data_dir: &Path, + auth: Arc, +) -> Arc { + match config.mode { + StorageMode::Local => Arc::new(FsSnapshotStore::new(data_dir.to_path_buf())), + StorageMode::Cloud => { + let tokens: Arc = auth; + Arc::new(CloudSnapshotStore::new(config.api_base_url.clone(), tokens)) + } + } } /// Nombre del ejecutable de esta app: la detección de agentes no baja por otra @@ -100,3 +181,152 @@ fn own_executable_name() -> Option { .file_name() .map(|name| name.to_string_lossy().into_owned()) } + +fn migrate_local_snapshot_if_needed( + previous: &StorageConfig, + target_mode: StorageMode, + local_store: &dyn SnapshotStore, + migrate: impl FnOnce(&WorkspaceSnapshot) -> Result<(), PortError>, +) -> Result<(), String> { + if !previous.onboarding_complete + || previous.mode != StorageMode::Local + || target_mode != StorageMode::Cloud + { + return Ok(()); + } + if let Some(snapshot) = local_store.load_snapshot().map_err(|e| e.to_string())? { + if !snapshot.workspaces.is_empty() { + migrate(&snapshot).map_err(|e| e.to_string())?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use application::storage::{StoredPane, StoredSession, StoredWorkspace}; + use std::sync::atomic::{AtomicU64, Ordering}; + + fn temp_dir(tag: &str) -> PathBuf { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::SeqCst); + let dir = std::env::temp_dir().join(format!( + "opencollab-state-migrate-{tag}-{}-{n}", + std::process::id() + )); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn sample_snapshot() -> WorkspaceSnapshot { + WorkspaceSnapshot::new(vec![StoredWorkspace { + id: "w1".into(), + name: "Local".into(), + sessions: vec![StoredSession { + id: "s1".into(), + name: "Sesión".into(), + panes: vec![StoredPane { + id: "p1".into(), + seq: 0, + minimized: false, + initial_cwd: None, + agent: None, + }], + }], + }]) + } + + #[test] + fn switching_from_completed_local_to_cloud_migrates_and_keeps_local_file() { + let dir = temp_dir("local-to-cloud"); + let local = FsSnapshotStore::new(&dir); + let expected = sample_snapshot(); + local.save_snapshot(&expected).unwrap(); + + let previous = StorageConfig { + version: 1, + mode: StorageMode::Local, + api_base_url: "http://127.0.0.1:8787".into(), + onboarding_complete: true, + }; + let mut migrated: Option = None; + migrate_local_snapshot_if_needed(&previous, StorageMode::Cloud, &local, |snap| { + migrated = Some(snap.clone()); + Ok(()) + }) + .unwrap(); + + assert_eq!(migrated.as_ref(), Some(&expected)); + assert_eq!( + local.load_snapshot().unwrap().as_ref(), + Some(&expected), + "el archivo local debe conservarse intacto tras migrar (A4)" + ); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn migration_error_fails_closed_and_keeps_local_file() { + let dir = temp_dir("migrate-error"); + let local = FsSnapshotStore::new(&dir); + let expected = sample_snapshot(); + local.save_snapshot(&expected).unwrap(); + + let previous = StorageConfig { + version: 1, + mode: StorageMode::Local, + api_base_url: "http://127.0.0.1:8787".into(), + onboarding_complete: true, + }; + let err = migrate_local_snapshot_if_needed(&previous, StorageMode::Cloud, &local, |_| { + Err(PortError::new("fallo de red al migrar")) + }) + .unwrap_err(); + + assert!(err.contains("fallo de red al migrar"), "{err}"); + assert_eq!(local.load_snapshot().unwrap().as_ref(), Some(&expected)); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn first_run_or_non_local_source_does_not_migrate() { + let dir = temp_dir("skip-migrate"); + let local = FsSnapshotStore::new(&dir); + local.save_snapshot(&sample_snapshot()).unwrap(); + + let first_run = StorageConfig { + version: 1, + mode: StorageMode::Local, + api_base_url: "http://127.0.0.1:8787".into(), + onboarding_complete: false, + }; + let mut called = false; + migrate_local_snapshot_if_needed(&first_run, StorageMode::Cloud, &local, |_| { + called = true; + Ok(()) + }) + .unwrap(); + assert!( + !called, + "el primer arranque no debe migrar como cambio de modo" + ); + + let already_cloud = StorageConfig { + version: 1, + mode: StorageMode::Cloud, + api_base_url: "http://127.0.0.1:8787".into(), + onboarding_complete: true, + }; + migrate_local_snapshot_if_needed(&already_cloud, StorageMode::Cloud, &local, |_| { + called = true; + Ok(()) + }) + .unwrap(); + assert!( + !called, + "cloud -> cloud no debe volver a migrar el archivo local" + ); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/apps/desktop/src-tauri/src/storage_config.rs b/apps/desktop/src-tauri/src/storage_config.rs new file mode 100644 index 0000000..3abe827 --- /dev/null +++ b/apps/desktop/src-tauri/src/storage_config.rs @@ -0,0 +1,230 @@ +//! Configuración de almacenamiento del desktop: modo local/cloud y base URL +//! de la API. Vive en appdata junto al snapshot local y sobrevive reinicios. + +use std::fs; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +const CONFIG_FILE: &str = "storage.json"; +const CONFIG_VERSION: u32 = 1; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum StorageMode { + Local, + Cloud, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StorageConfig { + pub version: u32, + pub mode: StorageMode, + pub api_base_url: String, + #[serde(default)] + pub onboarding_complete: bool, +} + +impl StorageConfig { + /// Default seguro: local, onboarding pendiente y la API del relay. + pub fn local(default_api_base_url: &str) -> Self { + Self { + version: CONFIG_VERSION, + mode: StorageMode::Local, + api_base_url: default_api_base_url.to_string(), + onboarding_complete: false, + } + } + + pub fn path(data_dir: &Path) -> PathBuf { + data_dir.join(CONFIG_FILE) + } + + /// Lee la configuración. Archivo ausente, ilegible, de otra versión o con + /// una URL inválida cae al default local: nunca impide arrancar. + pub fn load(data_dir: &Path, default_api_base_url: &str) -> Self { + let fallback = Self::local(default_api_base_url); + let Ok(raw) = fs::read_to_string(Self::path(data_dir)) else { + return fallback; + }; + let Ok(mut config) = serde_json::from_str::(&raw) else { + return fallback; + }; + if config.version != CONFIG_VERSION { + return fallback; + } + let Ok(url) = normalize_api_base_url(&config.api_base_url) else { + // Una config inválida no debe dejar cloud + onboarding completo: + // el fallback es el default seguro completo, no solo la URL. + return fallback; + }; + config.api_base_url = url; + config + } + + /// Valida y normaliza los campos editables. El modo cloud requiere una + /// base URL http(s) absoluta; el valor se guarda sin barra final. + pub fn validate(&mut self) -> Result<(), String> { + self.api_base_url = normalize_api_base_url(&self.api_base_url)?; + self.version = CONFIG_VERSION; + Ok(()) + } + + /// Persiste la configuración de forma atómica (tmp + rename). El + /// `onboarding_complete` lo decide quien llama y ya viene validado. + pub fn save(&self, data_dir: &Path) -> Result<(), String> { + fs::create_dir_all(data_dir) + .map_err(|e| format!("no se pudo crear el directorio de datos: {e}"))?; + let json = serde_json::to_string_pretty(self) + .map_err(|e| format!("no se pudo serializar la configuración: {e}"))?; + let path = Self::path(data_dir); + let tmp = path.with_extension("json.tmp"); + fs::write(&tmp, json).map_err(|e| format!("no se pudo escribir la configuración: {e}"))?; + fs::rename(&tmp, &path).map_err(|e| format!("no se pudo reemplazar la configuración: {e}")) + } +} + +fn normalize_api_base_url(value: &str) -> Result { + let trimmed = value.trim().trim_end_matches('/'); + let rest = trimmed + .strip_prefix("http://") + .or_else(|| trimmed.strip_prefix("https://")) + .ok_or_else(|| "la URL de la API debe empezar con http:// o https://".to_string())?; + if rest.is_empty() || rest.chars().any(char::is_whitespace) { + return Err("la URL de la API no es válida".to_string()); + } + // Autoridad con host: rechaza `http://:8787` y `http:///path`. + let authority = rest.split('/').next().unwrap_or_default(); + if authority.is_empty() || authority.starts_with(':') { + return Err("la URL de la API no es válida".to_string()); + } + if trimmed.contains(['?', '#']) { + return Err("la URL de la API no puede tener query ni fragmento".to_string()); + } + Ok(trimmed.to_string()) +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + use std::sync::atomic::{AtomicU64, Ordering}; + + use super::*; + + struct TempDir(PathBuf); + + impl TempDir { + fn new(tag: &str) -> Self { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::SeqCst); + let path = std::env::temp_dir().join(format!( + "opencollab-storage-config-{tag}-{}-{n}", + std::process::id() + )); + fs::create_dir_all(&path).unwrap(); + Self(path) + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + fn default_url() -> &'static str { + "http://127.0.0.1:8787" + } + + #[test] + fn missing_file_is_local_and_pending_onboarding() { + let dir = TempDir::new("missing"); + let config = StorageConfig::load(&dir.0, default_url()); + assert_eq!(config.mode, StorageMode::Local); + assert_eq!(config.api_base_url, default_url()); + assert!(!config.onboarding_complete); + } + + #[test] + fn round_trips_the_storage_config() { + let dir = TempDir::new("roundtrip"); + let mut config = StorageConfig { + version: CONFIG_VERSION, + mode: StorageMode::Cloud, + api_base_url: "https://api.example.com/".into(), + onboarding_complete: true, + }; + config.validate().unwrap(); + config.save(&dir.0).unwrap(); + assert_eq!(StorageConfig::load(&dir.0, default_url()), config); + } + + #[test] + fn malformed_or_future_config_falls_back_to_local() { + let dir = TempDir::new("malformed"); + fs::write(StorageConfig::path(&dir.0), "not json").unwrap(); + let malformed = StorageConfig::load(&dir.0, default_url()); + assert_eq!(malformed.mode, StorageMode::Local); + assert!(!malformed.onboarding_complete); + + fs::write( + StorageConfig::path(&dir.0), + r#"{"version":99,"mode":"cloud","apiBaseUrl":"https://api.example.com","onboardingComplete":true}"#, + ) + .unwrap(); + let future = StorageConfig::load(&dir.0, default_url()); + assert_eq!(future.mode, StorageMode::Local); + assert_eq!(future.api_base_url, default_url()); + } + + #[test] + fn invalid_api_base_url_falls_back_to_local_and_pending_onboarding() { + let dir = TempDir::new("invalid"); + fs::write( + StorageConfig::path(&dir.0), + r#"{"version":1,"mode":"cloud","apiBaseUrl":"not-a-url","onboardingComplete":true}"#, + ) + .unwrap(); + let config = StorageConfig::load(&dir.0, default_url()); + assert_eq!(config, StorageConfig::local(default_url())); + } + + #[test] + fn missing_version_is_treated_as_malformed() { + let dir = TempDir::new("version"); + fs::write( + StorageConfig::path(&dir.0), + r#"{"mode":"cloud","apiBaseUrl":"https://api.example.com","onboardingComplete":true}"#, + ) + .unwrap(); + assert_eq!( + StorageConfig::load(&dir.0, default_url()), + StorageConfig::local(default_url()) + ); + } + + #[test] + fn validates_and_normalizes_the_api_base_url() { + let mut config = StorageConfig { + version: 1, + mode: StorageMode::Cloud, + api_base_url: " https://api.example.com/ ".into(), + onboarding_complete: false, + }; + config.validate().unwrap(); + assert_eq!(config.api_base_url, "https://api.example.com"); + assert_eq!(config.version, CONFIG_VERSION); + + config.api_base_url = "ftp://api.example.com".into(); + assert!(config.validate().is_err()); + config.api_base_url = "http://".into(); + assert!(config.validate().is_err()); + config.api_base_url = "http://:8787".into(); + assert!(config.validate().is_err()); + config.api_base_url = "http:///path".into(); + assert!(config.validate().is_err()); + config.api_base_url = "http://api.example.com?token=1".into(); + assert!(config.validate().is_err()); + } +} diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 2295405..d6b1c7f 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,9 +2,9 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "OpenCollab", "version": "0.4.0", - "identifier": "dev.opencollab.app", + "identifier": "com.opencollab.desktop", "build": { - "beforeDevCommand": "pnpm dev", + "beforeDevCommand": "pnpm dev:vite", "devUrl": "http://localhost:1420", "beforeBuildCommand": "pnpm build", "frontendDist": "../dist" diff --git a/apps/desktop/src-tauri/tauri.dev.conf.json b/apps/desktop/src-tauri/tauri.dev.conf.json index 9c6cecd..16ea50e 100644 --- a/apps/desktop/src-tauri/tauri.dev.conf.json +++ b/apps/desktop/src-tauri/tauri.dev.conf.json @@ -1,12 +1,19 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "OpenCollab Dev", - "identifier": "dev.opencollab.app.dev", + "identifier": "com.opencollab.desktop.dev", "app": { "windows": [ { "title": "OpenCollab (Dev)" } ] + }, + "plugins": { + "deep-link": { + "desktop": { + "schemes": ["opencollab-dev"] + } + } } } diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index 52b742b..646eea2 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -20,8 +20,19 @@ import { type Session, type Workspace, } from "@opencollab/ui"; +import { CloudGate } from "./components/CloudGate"; import { TerminalPane } from "./components/TerminalPane"; +import { Onboarding } from "./components/Onboarding"; +import { SettingsDialog } from "./components/SettingsDialog"; import { useAuth, useCollabStatus, usePaneDrag } from "./hooks"; +import { loadSnapshot, saveSnapshot, flushSnapshotSaves } from "./services/snapshot"; +import { + DEFAULT_STORAGE_CONFIG, + loadStorageConfig, + saveStorageConfig, + type StorageConfig, + type StorageMode, +} from "./services/storage"; function initialWorkspaces(): Workspace[] { const ws = newWorkspace("OpenCollab"); @@ -46,6 +57,173 @@ export function App() { const [statuses, setStatuses] = useState>({}); const [meta, setMeta] = useState>({}); const searchRef = useRef(null); + const [storage, setStorage] = useState(null); + const [storageBusy, setStorageBusy] = useState(false); + const [storageError, setStorageError] = useState(null); + const [settingsOpen, setSettingsOpen] = useState(false); + const activeWorkspaceIdRef = useRef(activeWorkspaceId); + useEffect(() => { + activeWorkspaceIdRef.current = activeWorkspaceId; + }, [activeWorkspaceId]); + + // La estructura arranca con el default y a los valores reemplaza el snapshot + // guardado del núcleo (S5 del feature desktop-dual-storage): mientras carga, + // todo lo que asume `workspaces[0]` sigue funcionando. + const hydratedRef = useRef(false); + // Descarta una carga que quedó en vuelo cuando ya empezó otra (cambio de + // modo durante el arranque): su resultado pertenece a otro store. + const hydrationGeneration = useRef(0); + // La grilla cloud no se muestra hasta que el snapshot cloud terminó de + // cargar: un default visible con persistencia apagada perdería mutaciones. + const [hydrationReady, setHydrationReady] = useState(false); + const [hydrationError, setHydrationError] = useState(null); + const hydratingRef = useRef(false); + // `applyStorage` hidrata el store nuevo directamente; este flag evita que el + // efecto de boot lance una segunda carga para el mismo cambio. + const skipHydrationEffect = useRef(false); + + /// Reemplaza la estructura y, si el workspace activo no existe en el store + /// nuevo, reapunta la selección al primero (cambio local ↔ cloud). + const adoptWorkspaces = useCallback((next: Workspace[]) => { + setWorkspaces(next); + if (next.length === 0) return; + if (next.some((w) => w.id === activeWorkspaceIdRef.current)) return; + const first = next[0]; + const firstSession = first.sessions[0]; + setActiveWorkspaceId(first.id); + setActiveSessionByWs({ [first.id]: firstSession.id }); + setFocusedPaneId(firstSession.panes[0]?.id ?? null); + setMaximizedPaneId(null); + }, []); + + /// Carga el snapshot del store que el núcleo ya tiene seleccionado. En un + /// cambio de modo, `resetWhenMissing` evita reenviar la estructura local al + /// store vacío: T6 es quien migra, no un efecto implícito de T4. + const hydrate = useCallback( + async (resetWhenMissing = false) => { + const generation = ++hydrationGeneration.current; + hydratingRef.current = true; + hydratedRef.current = false; + setHydrationReady(false); + setHydrationError(null); + try { + const loaded = await loadSnapshot(); + if (generation !== hydrationGeneration.current) return false; + if (loaded && loaded.length > 0) adoptWorkspaces(loaded); + else if (resetWhenMissing) adoptWorkspaces(initialWorkspaces()); + else setWorkspaces((current: Workspace[]) => [...current]); + hydratedRef.current = true; + setHydrationReady(true); + return true; + } catch (error) { + if (generation !== hydrationGeneration.current) return false; + // Error inesperado del núcleo al cargar: la persistencia queda apagada + // para no pisar un snapshot que todavía puede ser válido. La cuarentena + // de un archivo corrupto la resuelve el núcleo y llega como `null`, no + // como rechazo, así que este camino nunca habilita el guardado. + console.error("no se pudo cargar el snapshot de workspaces:", error); + setHydrationError(error instanceof Error ? error.message : String(error)); + return false; + } finally { + if (generation === hydrationGeneration.current) hydratingRef.current = false; + } + }, + [adoptWorkspaces], + ); + + // Primero la configuración: el snapshot se carga recién cuando el núcleo ya + // apunta al store elegido. Sin configuración (navegador/E2E viejo) entra en + // local completo para no bloquear la app. + useEffect(() => { + let cancelled = false; + void loadStorageConfig() + .then((config) => { + if (!cancelled) setStorage(config); + }) + .catch((error) => { + console.error("no se pudo cargar la configuración de almacenamiento:", error); + if (!cancelled) setStorage({ ...DEFAULT_STORAGE_CONFIG, onboardingComplete: true }); + }); + return () => { + cancelled = true; + }; + }, []); + + // El snapshot cloud solo se carga con sesión. Al perder la sesión se apaga + // la persistencia y se vuelve al gate de login; al recuperarla se recarga el + // store cloud. Para local, una única carga alcanza. + useEffect(() => { + if (!storage?.onboardingComplete) return; + if (storage.mode === "cloud" && auth.state.status !== "authenticated") { + // Cancela una carga en vuelo: su resultado pertenece a una sesión que ya + // no existe y no debe volver a habilitar el guardado. + hydrationGeneration.current += 1; + hydratingRef.current = false; + hydratedRef.current = false; + skipHydrationEffect.current = false; + setHydrationReady(false); + return; + } + if (skipHydrationEffect.current) { + skipHydrationEffect.current = false; + return; + } + if (hydrationReady || hydratingRef.current || hydrationError) return; + void hydrate(); + }, [storage, auth.state.status, hydrate, hydrationReady, hydrationError]); + + /// Guarda el modo/base URL y recarga el store nuevo. `true` si el núcleo + /// aceptó el cambio (cloud exige sesión y URL válida). + const applyStorage = useCallback( + async (mode: StorageMode, apiBaseUrl: string) => { + setStorageBusy(true); + setStorageError(null); + const wasHydrated = hydratedRef.current; + const wasReady = hydrationReady; + // Nada nuevo se guarda mientras se cambia de store; lo ya encolado + // termina en el store viejo antes de que el núcleo lo reemplace. + hydratedRef.current = false; + setHydrationReady(false); + setHydrationError(null); + try { + await flushSnapshotSaves(); + const next = await saveStorageConfig(mode, apiBaseUrl); + // El efecto de boot no debe lanzar una segunda carga: la de acá abajo + // es la que corresponde a este cambio de store. + skipHydrationEffect.current = true; + setStorage(next); + if (!(await hydrate(true))) { + setStorageError("No se pudo cargar el almacenamiento seleccionado."); + return; + } + setSettingsOpen(false); + } catch (error) { + hydratedRef.current = wasHydrated; + setHydrationReady(wasReady); + setStorageError(error instanceof Error ? error.message : String(error)); + } finally { + setStorageBusy(false); + } + }, + [hydrate, hydrationReady], + ); + + const retryHydration = useCallback(() => { + setHydrationError(null); + void hydrate(); + }, [hydrate]); + + const useLocalStorage = useCallback(() => { + if (!storage) return; + void applyStorage("local", storage.apiBaseUrl); + }, [applyStorage, storage]); + + // Persistencia en cada mutación de la estructura; la cola del servicio + // (`saveSnapshot`) garantiza que dos guardados nunca se cruzan. + useEffect(() => { + if (!hydratedRef.current) return; + void saveSnapshot(workspaces); + }, [workspaces]); const activeWorkspace = workspaces.find((w) => w.id === activeWorkspaceId) ?? workspaces[0]; const activeSession = @@ -207,6 +385,71 @@ export function App() { return { terminals: panes.length, live }; }, [activeSession.panes, statuses]); + if (!storage) { + return
Loading…
; + } + + if (!storage.onboardingComplete) { + return ( + void applyStorage(mode, storage.apiBaseUrl)} + onSignIn={() => void auth.beginLogin()} + onCancelLogin={auth.cancelLogin} + /> + ); + } + + // Cloud sin sesión no monta la grilla: sin tokens, cada mutación se + // descartaría en silencio. El login rearma el store y recién ahí se hidrata. + if (storage.mode === "cloud") { + if (auth.state.status === "unknown") { + return
Loading…
; + } + if (auth.state.status !== "authenticated") { + return ( + void auth.beginLogin()} + onCancelLogin={auth.cancelLogin} + onSignOut={() => void auth.logout()} + onRetry={retryHydration} + onUseLocal={useLocalStorage} + /> + ); + } + if (!hydrationReady) { + if (!hydrationError) { + return
Loading your cloud workspace…
; + } + return ( + void auth.beginLogin()} + onCancelLogin={auth.cancelLogin} + onSignOut={() => void auth.logout()} + onRetry={retryHydration} + onUseLocal={useLocalStorage} + /> + ); + } + } + return (
{ setLayout(l); setMaximizedPaneId(null); }} onNewTerminal={() => addTerminal()} + onOpenSettings={() => { + setStorageError(null); + setSettingsOpen(true); + }} />
- +
+ + {settingsOpen && ( + setSettingsOpen(false)} + onSave={(mode, apiBaseUrl) => void applyStorage(mode, apiBaseUrl)} + onSignIn={() => void auth.beginLogin()} + onCancelLogin={auth.cancelLogin} + /> + )} ); } diff --git a/apps/desktop/src/components/CloudGate.tsx b/apps/desktop/src/components/CloudGate.tsx new file mode 100644 index 0000000..88a8ce4 --- /dev/null +++ b/apps/desktop/src/components/CloudGate.tsx @@ -0,0 +1,72 @@ +import { Button, opencollabLogoTransparent, type AuthState } from "@opencollab/ui"; + +import { StorageAuth } from "./StorageAuth"; + +type Props = { + auth: AuthState; + authBusy: boolean; + authError: string | null; + loginUrl: string | null; + busy: boolean; + error: string | null; + onSignIn: () => void; + onCancelLogin: () => void; + onSignOut: () => void; + onRetry: () => void; + onUseLocal: () => void; +}; + +/// Gate del modo cloud: sin sesión no se monta la grilla, y si el snapshot +/// cloud no carga se ofrece reintentar o volver a local. Evita arrancar en +/// cloud con la persistencia apagada y perder mutaciones en silencio. +export function CloudGate(props: Props) { + const signedIn = props.auth.status === "authenticated"; + return ( +
+
+ OpenCollab +

OpenCollab Cloud

+

+ {signedIn + ? "We couldn't load your cloud workspace." + : "Sign in to load your workspace structure from the cloud."} +

+ + + + {props.error && ( +

+ {props.error} +

+ )} + +
+ {props.error && ( + + )} + {signedIn && ( + + )} + +
+ +

+ Cloud storage needs an account. Local storage stays on this computer. +

+
+
+ ); +} diff --git a/apps/desktop/src/components/Onboarding.tsx b/apps/desktop/src/components/Onboarding.tsx new file mode 100644 index 0000000..32ae222 --- /dev/null +++ b/apps/desktop/src/components/Onboarding.tsx @@ -0,0 +1,69 @@ +import { opencollabLogoTransparent, type AuthState } from "@opencollab/ui"; +import type { StorageMode } from "../services/storage"; +import { StorageAuth } from "./StorageAuth"; + +type Props = { + auth: AuthState; + authBusy: boolean; + authError: string | null; + loginUrl: string | null; + busy: boolean; + error: string | null; + onChoose: (mode: StorageMode) => void; + onSignIn: () => void; + onCancelLogin: () => void; +}; + +/// Primera corrida: el usuario elige dónde vive la estructura del escritorio. +/// Cloud exige sesión; ambas opciones persisten la elección antes de entrar. +export function Onboarding(props: Props) { + const signedIn = props.auth.status === "authenticated"; + return ( +
+
+ OpenCollab +

Welcome to OpenCollab

+

Choose where your workspace structure lives.

+ +
+ + +
+ + {!signedIn && ( + + )} + + {props.error && ( +

+ {props.error} +

+ )} +

You can change this later in Settings.

+
+
+ ); +} diff --git a/apps/desktop/src/components/SettingsDialog.tsx b/apps/desktop/src/components/SettingsDialog.tsx new file mode 100644 index 0000000..4777cdb --- /dev/null +++ b/apps/desktop/src/components/SettingsDialog.tsx @@ -0,0 +1,145 @@ +import { useEffect, useState } from "react"; +import { Button, Close, IconButton, type AuthState } from "@opencollab/ui"; + +import type { StorageConfig, StorageMode } from "../services/storage"; +import { StorageAuth } from "./StorageAuth"; + +type Props = { + storage: StorageConfig; + auth: AuthState; + authBusy: boolean; + authError: string | null; + loginUrl: string | null; + busy: boolean; + error: string | null; + onClose: () => void; + onSave: (mode: StorageMode, apiBaseUrl: string) => void; + onSignIn: () => void; + onCancelLogin: () => void; +}; + +/// Ajustes de almacenamiento: modo y base URL de la API. El guardado lo hace +/// el núcleo (valida URL y exige sesión para cloud); acá solo se edita. +export function SettingsDialog(props: Props) { + const [mode, setMode] = useState(props.storage.mode); + const [apiBaseUrl, setApiBaseUrl] = useState(props.storage.apiBaseUrl); + + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") props.onClose(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [props.onClose]); + + const signedIn = props.auth.status === "authenticated"; + const invalidUrl = mode === "cloud" && !/^https?:\/\/\S+$/.test(apiBaseUrl.trim()); + const cloudNeedsLogin = mode === "cloud" && !signedIn; + const saveDisabled = props.busy || invalidUrl || cloudNeedsLogin; + + return ( +
props.onClose()} + > +
e.stopPropagation()} + > +
+

Settings

+ } title="Close settings" onClick={props.onClose} /> +
+ +
+

Storage

+ + +
+ + + + {cloudNeedsLogin && ( +
+

Sign in before switching to cloud storage.

+ +
+ )} + + {props.storage.mode === "local" && mode === "cloud" && ( +

+ Your local workspaces, sessions, and terminals will be migrated to your cloud account. + Local files are kept on this computer. +

+ )} + + {invalidUrl && ( +

+ Enter an absolute http:// or https:// URL. +

+ )} + {props.error && ( +

+ {props.error} +

+ )} + +
+ + +
+
+
+ ); +} diff --git a/apps/desktop/src/components/StorageAuth.tsx b/apps/desktop/src/components/StorageAuth.tsx new file mode 100644 index 0000000..4455a55 --- /dev/null +++ b/apps/desktop/src/components/StorageAuth.tsx @@ -0,0 +1,47 @@ +import { Button, type AuthState } from "@opencollab/ui"; + +type Props = { + auth: AuthState; + busy: boolean; + error: string | null; + loginUrl: string | null; + onSignIn: () => void; + onCancelLogin: () => void; +}; + +/// Bloque de login reutilizado por el onboarding y Settings: el modo nube +/// necesita una sesión, y el login siempre ocurre en el navegador. +export function StorageAuth(props: Props) { + if (props.auth.status === "authenticated") { + return ( +

+ Signed in as {props.auth.user.displayName || props.auth.user.username} +

+ ); + } + if (props.auth.status === "unknown") { + return

Checking session…

; + } + return ( +
+
+ {props.busy ? ( + + ) : ( + + )} + {props.busy ? "Finish sign-in in your browser" : "Sign in to use cloud storage"} +
+ {props.error && ( +

+ {props.error} +

+ )} + {props.busy && props.loginUrl && ( + + Open login page + + )} +
+ ); +} diff --git a/apps/desktop/src/services/auth.test.ts b/apps/desktop/src/services/auth.test.ts index a454467..566bd49 100644 --- a/apps/desktop/src/services/auth.test.ts +++ b/apps/desktop/src/services/auth.test.ts @@ -3,8 +3,9 @@ import { describe, expect, it } from "vitest"; import { createPkcePair, initialsOf, isAuthCallback, type AuthUser } from "./auth"; describe("isAuthCallback", () => { - it("acepta el callback del desktop", () => { + it("acepta el callback del desktop (producción y dev)", () => { expect(isAuthCallback("opencollab://auth/callback?code=abc123")).toBe(true); + expect(isAuthCallback("opencollab-dev://auth/callback?code=abc123")).toBe(true); }); it("rechaza deep links ajenos", () => { diff --git a/apps/desktop/src/services/auth.ts b/apps/desktop/src/services/auth.ts index a55c152..ad8486e 100644 --- a/apps/desktop/src/services/auth.ts +++ b/apps/desktop/src/services/auth.ts @@ -11,7 +11,7 @@ export function isAuthCallback(url: string): boolean { try { const parsed = new URL(url); return ( - parsed.protocol === "opencollab:" && + (parsed.protocol === "opencollab:" || parsed.protocol === "opencollab-dev:") && parsed.host === "auth" && parsed.pathname === "/callback" && parsed.searchParams.get("code") !== null diff --git a/apps/desktop/src/services/snapshot.test.ts b/apps/desktop/src/services/snapshot.test.ts new file mode 100644 index 0000000..e441f2b --- /dev/null +++ b/apps/desktop/src/services/snapshot.test.ts @@ -0,0 +1,229 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { invoke } from "@tauri-apps/api/core"; +import { newPane, newSession, newWorkspace } from "@opencollab/ui"; + +import { + flushSnapshotSaves, + fromSavedSnapshot, + saveSnapshot, + toSavedWorkspaces, + type SavedSnapshot, +} from "./snapshot"; + +vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() })); +const mockedInvoke = vi.mocked(invoke); + +// Espejo del payload camelCase que serializa el núcleo Rust +// (`WorkspaceSnapshot::new` → serde). Candados del formato: solo perfil de +// arranque de las terminales, nunca `env` ni scrollback (A1 del feature). +const saved: SavedSnapshot = { + workspaces: [ + { + id: "ws-1", + name: "trabajo", + sessions: [ + { + id: "session-1", + name: "con pane", + panes: [ + { + id: "pane-1", + seq: 500, + minimized: true, + initialCwd: "C:\\repo", + agent: "claude-code", + }, + ], + }, + { id: "session-2", name: "sin panes", panes: [] }, + ], + }, + ], +}; + +function uiWorkspaceWithSavedPanes() { + const ws = newWorkspace("local"); + ws.members = 3; + ws.sessions.push(newSession("extra")); + ws.sessions[0].panes.push(newPane("C:\\repo", "opencode")); + return ws; +} + +describe("toSavedWorkspaces", () => { + it("deja solo los campos persistentes, con las claves camelCase del núcleo", () => { + const ws = uiWorkspaceWithSavedPanes(); + const [savedWs] = toSavedWorkspaces([ws]); + + // `members` y todo estado volátil de la UI no viajan al snapshot. + expect(savedWs).toEqual({ + id: ws.id, + name: "local", + sessions: [ + { + id: ws.sessions[0].id, + name: "Sesión 1", + panes: [ + { + id: ws.sessions[0].panes[0].id, + seq: ws.sessions[0].panes[0].seq, + minimized: false, + initialCwd: "C:\\repo", + agent: "opencode", + }, + ], + }, + { id: ws.sessions[1].id, name: "extra", panes: [] }, + ], + }); + }); +}); + +describe("fromSavedSnapshot", () => { + beforeEach(() => { + mockedInvoke.mockReset(); + }); + + it("reconstruye workspaces de la UI; `members` vuelve al default local", () => { + const [ws] = fromSavedSnapshot(saved)!; + expect(ws).toEqual({ + id: "ws-1", + name: "trabajo", + members: 1, + sessions: [ + { + id: "session-1", + name: "con pane", + panes: [ + { + id: "pane-1", + seq: 500, + minimized: true, + initialCwd: "C:\\repo", + agent: "claude-code", + }, + ], + }, + { id: "session-2", name: "sin panes", panes: [] }, + ], + }); + }); + + it("rebasa el contador de seq: nuevos paneles no colisionan con los restaurados", () => { + fromSavedSnapshot(saved); + expect(newPane().seq).toBeGreaterThan(500); + }); + + it("un agente que ya no está en el catálogo cae a `null` (shell plana)", () => { + const peninsula = { + ...saved, + workspaces: [ + { + ...saved.workspaces[0], + sessions: [ + { + ...saved.workspaces[0].sessions[0], + panes: [{ ...saved.workspaces[0].sessions[0].panes[0], agent: "agente-fantasma" }], + }, + ], + }, + ], + } satisfies SavedSnapshot; + const [ws] = fromSavedSnapshot(peninsula)!; + expect(ws.sessions[0].panes[0].agent).toBeNull(); + }); + + it("caída a `null` ante un payload inválido", () => { + expect(fromSavedSnapshot(null)).toBeNull(); + expect(fromSavedSnapshot({} as SavedSnapshot)).toBeNull(); + expect(fromSavedSnapshot({ workspaces: [] })).toBeNull(); + expect(fromSavedSnapshot({ workspaces: [null as never] })).toBeNull(); + expect( + fromSavedSnapshot({ + workspaces: [{ id: "ws-1", name: "x", sessions: [{ id: "s-1", name: "y", panes: [{}] as never }] }], + }), + ).toBeNull(); + }); +}); + +describe("loadSnapshot/saveSnapshot", () => { + beforeEach(() => { + mockedInvoke.mockReset(); + }); + + it("sin datos guardados devuelve `null` (primera corrida / arranque limpio)", async () => { + mockedInvoke.mockResolvedValueOnce(null); + expect(await (await import("./snapshot")).loadSnapshot()).toBeNull(); + }); + + it("el guardado siguiente espera al anterior: nunca se cruzan los writes", async () => { + let release: (() => void) | undefined; + let firstDone = false; + try { + const marks: ("after" | "before")[] = []; + mockedInvoke + // Primera escritura que depende de un `release` manual y segunda rápida: + // si el guardado no se encadenara, a la segunda no le importaría la primera. + .mockImplementationOnce( + () => + new Promise((res) => { + release = () => { + firstDone = true; + res(null); + }; + }), + ) + .mockImplementationOnce(() => { + marks.push(firstDone ? "after" : "before"); + return Promise.resolve(null); + }); + const first = saveSnapshot([uiWorkspaceWithSavedPanes()]); + const second = saveSnapshot([]); + // Un turno corto de timers: bastante para que la cola despache al primero + // y encadene al segundo detrás de su resolución. + await new Promise((r) => setTimeout(r, 10)); + expect(mockedInvoke).toHaveBeenCalledTimes(1); + release!(); + await Promise.all([first, second]); + expect(firstDone).toBe(true); + expect(marks).toEqual(["after"]); + expect(mockedInvoke).toHaveBeenCalledTimes(2); + expect(mockedInvoke.mock.calls[0][0]).toBe("snapshot_save"); + expect(mockedInvoke.mock.calls[0][1]).toEqual({ + workspaces: expect.any(Array), + }); + } finally { + release?.(); + await Promise.resolve(); + } + }); + + it("un guardado que falla no bloquea los siguientes", async () => { + mockedInvoke.mockRejectedValueOnce(new Error("disk full")); + const first = saveSnapshot([uiWorkspaceWithSavedPanes()]); + const second = saveSnapshot([uiWorkspaceWithSavedPanes()]); + await expect(first).resolves.toBeUndefined(); + await expect(second).resolves.toBeUndefined(); + expect(mockedInvoke).toHaveBeenCalledTimes(2); + }); + + it("flush espera el guardado en vuelo antes de cambiar de store", async () => { + let release: (() => void) | undefined; + mockedInvoke.mockImplementationOnce( + () => + new Promise((res) => { + release = () => res(null); + }), + ); + const pending = saveSnapshot([uiWorkspaceWithSavedPanes()]); + let flushed = false; + const flush = flushSnapshotSaves().then(() => { + flushed = true; + }); + await new Promise((r) => setTimeout(r, 10)); + expect(flushed).toBe(false); + release!(); + await Promise.all([pending, flush]); + expect(flushed).toBe(true); + }); +}); diff --git a/apps/desktop/src/services/snapshot.ts b/apps/desktop/src/services/snapshot.ts new file mode 100644 index 0000000..6128eb7 --- /dev/null +++ b/apps/desktop/src/services/snapshot.ts @@ -0,0 +1,136 @@ +import { invoke } from "@tauri-apps/api/core"; +import { adoptPaneSeq, isAgentId, type Pane, type Session, type Workspace } from "@opencollab/ui"; + +// Espeja StoredPane/StoredSession/StoredWorkspace del núcleo Rust +// (apps/desktop/core/application/src/storage.ts): solo el perfil de arranque +// de las terminales, nunca `env` ni scrollback (regla A1 del feature +// desktop-dual-storage). El `SNAPSHOT_VERSION` lo maneja el núcleo: acá viaja +// solo el array de workspaces. +export type SavedPane = { + id: string; + seq: number; + minimized: boolean; + initialCwd: string | null; + agent: string | null; +}; + +export type SavedSession = { id: string; name: string; panes: SavedPane[] }; + +export type SavedWorkspace = { id: string; name: string; sessions: SavedSession[] }; + +export type SavedSnapshot = { workspaces: SavedWorkspace[] }; + +const savedPaneOf = (pane: Pane): SavedPane => ({ + id: pane.id, + seq: pane.seq, + minimized: pane.minimized, + initialCwd: pane.initialCwd, + agent: pane.agent, +}); + +const savedSessionOf = (session: Session): SavedSession => ({ + id: session.id, + name: session.name, + panes: session.panes.map(savedPaneOf), +}); + +export function toSavedWorkspaces(workspaces: Workspace[]): SavedWorkspace[] { + return workspaces.map((ws) => ({ + id: ws.id, + name: ws.name, + // `members` (y cualquier otro estado volátil de la UI) queda fuera del snapshot. + sessions: ws.sessions.map(savedSessionOf), + })); +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null; +} + +function paneOf(raw: unknown): Pane | null { + if (!isRecord(raw)) return null; + const { id, seq, minimized, initialCwd, agent } = raw; + if (typeof id !== "string" || typeof seq !== "number" || typeof minimized !== "boolean") + return null; + if (initialCwd !== null && typeof initialCwd !== "string") return null; + if (agent !== null && typeof agent !== "string") return null; + // Un agente que ya no existe en el catálogo (snapshot viejo) pasa a + // `null`: la terminal apertura plana en vez de romper la UI. + return { id, seq, minimized, initialCwd, agent: isAgentId(agent) ? agent : null }; +} + +function sessionOf(raw: unknown): Session | null { + if (!isRecord(raw)) return null; + const { id, name, panes } = raw; + if (typeof id !== "string" || typeof name !== "string" || !Array.isArray(panes)) return null; + const restored: Pane[] = []; + for (const item of panes) { + const pane = paneOf(item); + if (!pane) return null; + // Los seq restaurados reservan su lugar: los `newPane` de esta corrida + // generan seq mayores y no chocan (el orden visual del grid queda estable). + adoptPaneSeq(pane.seq); + restored.push(pane); + } + return { id, name, panes: restored }; +} + +function workspaceOf(raw: unknown): Workspace | null { + if (!isRecord(raw)) return null; + const { id, name, sessions } = raw; + if (typeof id !== "string" || typeof name !== "string" || !Array.isArray(sessions)) return null; + const restored: Session[] = []; + for (const item of sessions) { + const session = sessionOf(item); + if (!session) return null; + restored.push(session); + } + return { id, name, members: 1, sessions: restored }; +} + +/// Reconstruye los workspaces de la UI desde el payload del núcleo. +/// Todo payload inválido cae a `null` y quien llama arranca con el default: +/// el archivo lo valida antes Rust (quarentena de lo ilegible/versión futura), +/// así que acá solo queda blindarse ante un shape inesperado. +export function fromSavedSnapshot(saved: unknown): Workspace[] | null { + if (!isRecord(saved) || !Array.isArray(saved.workspaces) || saved.workspaces.length === 0) + return null; + const restored: Workspace[] = []; + for (const item of saved.workspaces) { + const ws = workspaceOf(item); + if (!ws) return null; + restored.push(ws); + } + return restored; +} + +/// Snapshot guardado del arranque anterior; `null` si no hay nada (primera +/// corrida, arranque limpio o cuarentena del último archivo corrupto). +export async function loadSnapshot(): Promise { + const saved = await invoke("snapshot_load"); + return fromSavedSnapshot(saved); +} + +// Los guardados se encadenan: el snapshot chico escribe en milisegundos, pero +// dos writes concurrentes sobre el mismo archivo no deben cruzarse jamás. +let saveQueue: Promise = Promise.resolve(); + +/// Espera los guardados ya encolados antes de cambiar de store: un write +/// pendiente del modo viejo nunca debe aterrizar en el store nuevo. +export function flushSnapshotSaves(): Promise { + return saveQueue.then(() => undefined); +} + +/// Guarda el estado persistente de los workspaces. Nunca rechaza: un error del +/// disco no debe tumbar la app (el próximo guardado lo reintenta igual). +export async function saveSnapshot(workspaces: Workspace[]): Promise { + const saved = toSavedWorkspaces(workspaces); + const next = saveQueue + .then(() => invoke("snapshot_save", { workspaces: saved })) + .then( + () => undefined, + (error) => console.error("no se pudo guardar el snapshot:", error), + ); + saveQueue = next; + return next; +} diff --git a/apps/desktop/src/services/storage.ts b/apps/desktop/src/services/storage.ts new file mode 100644 index 0000000..509b186 --- /dev/null +++ b/apps/desktop/src/services/storage.ts @@ -0,0 +1,29 @@ +import { invoke } from "@tauri-apps/api/core"; + +export type StorageMode = "local" | "cloud"; + +export type StorageConfig = { + version: number; + mode: StorageMode; + apiBaseUrl: string; + onboardingComplete: boolean; +}; + +/// Fallback para navegador/E2E sin núcleo: mismo default que Rust. +export const DEFAULT_STORAGE_CONFIG: StorageConfig = { + version: 1, + mode: "local", + apiBaseUrl: "http://127.0.0.1:8787", + onboardingComplete: false, +}; + +export function loadStorageConfig(): Promise { + return invoke("storage_config_get"); +} + +export function saveStorageConfig( + mode: StorageMode, + apiBaseUrl: string, +): Promise { + return invoke("storage_config_set", { mode, apiBaseUrl }); +} diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.css index d36cfeb..17d7125 100644 --- a/apps/desktop/src/styles.css +++ b/apps/desktop/src/styles.css @@ -228,6 +228,12 @@ kbd { color: var(--text-muted); } +.ws-meta[data-collab-inactive="true"], +.user--collab-inactive .user-status, +.statusbar-item--inactive { + color: var(--text-faint); +} + .ws-menu { position: absolute; z-index: 10; @@ -1240,3 +1246,257 @@ button.cwd-item:hover { color: var(--text-faint); } + +/* ---------- Onboarding y ajustes de almacenamiento ---------- */ + +.boot { + display: grid; + place-items: center; + height: 100%; + color: var(--text-muted); +} + +.onboarding { + display: grid; + place-items: center; + min-height: 100%; + padding: 32px; + background: + radial-gradient(circle at 50% 20%, rgba(124, 92, 255, 0.16), transparent 55%), + var(--bg); +} + +.onboarding-card { + width: min(560px, 100%); + padding: 28px; + border: 1px solid var(--border); + border-radius: 12px; + background: var(--surface); + box-shadow: 0 24px 60px rgba(0, 0, 0, 0.35); +} + +.onboarding-logo { + width: 64px; + height: 64px; + margin-bottom: 12px; + filter: drop-shadow(0 0 18px rgba(124, 92, 255, 0.35)); +} + +.onboarding-card h1 { + margin: 0 0 6px; + font-size: 24px; +} + +.onboarding-lead, +.onboarding-footnote { + margin: 0; + color: var(--text-muted); +} + +.onboarding-modes { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; + margin: 20px 0; +} + +.onboarding-mode { + display: flex; + flex-direction: column; + gap: 6px; + padding: 14px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface-2); + text-align: left; +} + +.onboarding-mode:hover:not(:disabled) { + border-color: var(--accent); + background: var(--surface-3); +} + +.onboarding-mode span { + color: var(--text-muted); + font-size: 12px; + line-height: 1.4; +} + +.onboarding-footnote { + margin-top: 16px; + font-size: 11px; +} + +.onboarding-actions { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 16px; +} + +.storage-auth { + display: flex; + flex-direction: column; + gap: 8px; + padding: 12px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface-2); + color: var(--text-muted); + font-size: 12px; +} + +.storage-auth--ok { + color: var(--green); +} + +.storage-auth-row { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; +} + +.modal-backdrop { + position: fixed; + inset: 0; + z-index: 50; + display: grid; + place-items: center; + padding: 24px; + background: rgba(0, 0, 0, 0.62); +} + +.modal { + display: flex; + flex-direction: column; + gap: 18px; + width: min(520px, 100%); + max-height: calc(100vh - 48px); + overflow-y: auto; + padding: 20px; + border: 1px solid var(--border-strong); + border-radius: 12px; + background: var(--surface); + box-shadow: 0 24px 60px rgba(0, 0, 0, 0.45); +} + +.modal-head { + display: flex; + align-items: center; + justify-content: space-between; +} + +.modal-head h2 { + margin: 0; + font-size: 18px; +} + +.modal-section h3 { + margin: 0 0 8px; + color: var(--text-muted); + font-size: 11px; + font-weight: 600; + letter-spacing: 0.06em; + text-transform: uppercase; +} + +.settings-mode { + display: flex; + align-items: flex-start; + gap: 10px; + padding: 10px 12px; + border: 1px solid var(--border); + border-radius: var(--radius); + cursor: pointer; +} + +.settings-mode + .settings-mode { + margin-top: 8px; +} + +.settings-mode:has(input:checked) { + border-color: var(--accent); + background: rgba(124, 92, 255, 0.08); +} + +.settings-mode input { + margin-top: 3px; + accent-color: var(--accent); +} + +.settings-mode span { + display: flex; + flex-direction: column; + gap: 3px; +} + +.settings-mode small, +.settings-field small { + color: var(--text-muted); + font-size: 11px; +} + +.settings-field { + display: flex; + flex-direction: column; + gap: 6px; +} + +.settings-field > span { + font-weight: 500; +} + +.settings-field input { + height: 32px; + padding: 0 10px; + border: 1px solid var(--border-strong); + border-radius: var(--radius); + background: var(--surface-2); + color: var(--text); + font: inherit; +} + +.settings-field input:focus { + outline: none; + border-color: var(--accent); +} + +.settings-auth { + display: flex; + flex-direction: column; + gap: 8px; +} + +.settings-warning, +.settings-error { + margin: 0; + font-size: 12px; +} + +.settings-hint { + margin: 0; + color: var(--text-muted); + font-size: 12px; + line-height: 1.4; +} + +.settings-warning { + color: var(--amber); +} + +.settings-error { + color: var(--red); +} + +.modal-actions { + display: flex; + justify-content: flex-end; + gap: 8px; +} + +@media (max-width: 520px) { + .onboarding-modes { + grid-template-columns: 1fr; + } +} diff --git a/apps/web/src/services/authClient.ts b/apps/web/src/services/authClient.ts index 5e3a311..ecec4d8 100644 --- a/apps/web/src/services/authClient.ts +++ b/apps/web/src/services/authClient.ts @@ -231,8 +231,10 @@ export function createAuthClient(overrides: Partial = {}) { if (state.status === "authenticated") set({ ...state, user }); return user; }, - async desktopCode(codeChallenge: string): Promise { - const response = await webPost("desktop-code", { code_challenge: codeChallenge }); + async desktopCode(codeChallenge: string, client?: "desktop" | "desktop-dev"): Promise { + const body = + client && client !== "desktop" ? { code_challenge: codeChallenge, client } : { code_challenge: codeChallenge }; + const response = await webPost("desktop-code", body); if (!response.ok) throw await errorOf(response); return ((await response.json()) as { redirectUrl: string }).redirectUrl; }, diff --git a/apps/web/src/services/handoff.test.ts b/apps/web/src/services/handoff.test.ts index 61e6705..ca61e1c 100644 --- a/apps/web/src/services/handoff.test.ts +++ b/apps/web/src/services/handoff.test.ts @@ -81,6 +81,17 @@ describe("runPendingHandoff", () => { expect(readPendingHandoff()).toBeNull(); }); + it("supports client=desktop-dev and redirects to opencollab-dev://", async () => { + expect(captureHandoff(`?client=desktop-dev&code_challenge=${challenge}`)).toBe(true); + expect(readPendingHandoff()).toBe(challenge); + const desktopCode = vi.fn(async () => "opencollab-dev://auth/callback?code=xyz"); + const assign = vi.fn(); + expect(await runPendingHandoff({ desktopCode }, assign)).toBe(true); + expect(desktopCode).toHaveBeenCalledWith(challenge, "desktop-dev"); + expect(assign).toHaveBeenCalledWith("opencollab-dev://auth/callback?code=xyz"); + expect(readPendingHandoff()).toBeNull(); + }); + it("refuses to navigate to anything but the opencollab deep link", async () => { captureHandoff(`?client=desktop&code_challenge=${challenge}`); const assign = vi.fn(); diff --git a/apps/web/src/services/handoff.ts b/apps/web/src/services/handoff.ts index b684a3d..c56f760 100644 --- a/apps/web/src/services/handoff.ts +++ b/apps/web/src/services/handoff.ts @@ -3,7 +3,10 @@ // survives the OAuth round trip; tokens never touch storage. const KEY = "opencollab.handoff.challenge"; -const DEEP_LINK_PREFIX = "opencollab://"; +const CLIENT_KEY = "opencollab.handoff.client"; +const DEEP_LINK_PREFIXES = ["opencollab://", "opencollab-dev://"]; + +export type DesktopHandoffClient = "desktop" | "desktop-dev"; // S256 challenge: base64url of a 32-byte digest is always 43 chars. export const isValidCodeChallenge = (value: string): boolean => /^[A-Za-z0-9_-]{43}$/.test(value); @@ -17,9 +20,18 @@ export function readPendingHandoff(): string | null { } } +export function readPendingHandoffClient(): DesktopHandoffClient { + try { + return sessionStorage.getItem(CLIENT_KEY) === "desktop-dev" ? "desktop-dev" : "desktop"; + } catch { + return "desktop"; + } +} + export function clearPendingHandoff(): void { try { sessionStorage.removeItem(KEY); + sessionStorage.removeItem(CLIENT_KEY); } catch { // Storage unavailable: nothing was persisted. } @@ -36,9 +48,14 @@ export function captureHandoff(search: string): boolean { const client = params.get("client"); const challenge = params.get("code_challenge"); if (client === null && challenge === null) return false; - if (client === "desktop" && challenge !== null && isValidCodeChallenge(challenge)) { + if ((client === "desktop" || client === "desktop-dev") && challenge !== null && isValidCodeChallenge(challenge)) { try { sessionStorage.setItem(KEY, challenge); + if (client === "desktop-dev") { + sessionStorage.setItem(CLIENT_KEY, "desktop-dev"); + } else { + sessionStorage.removeItem(CLIENT_KEY); + } } catch { // Without storage the handoff only survives password login (no OAuth trip). } @@ -50,13 +67,17 @@ export function captureHandoff(search: string): boolean { /** Exchanges the pending challenge for a deep link and navigates to it. Returns whether a handoff ran. */ export async function runPendingHandoff( - api: { desktopCode(challenge: string): Promise }, + api: { desktopCode(challenge: string, client?: DesktopHandoffClient): Promise }, assign: (url: string) => void, ): Promise { const challenge = readPendingHandoff(); if (!challenge) return false; - const redirectUrl = await api.desktopCode(challenge); - if (!redirectUrl.startsWith(DEEP_LINK_PREFIX)) throw new Error("Unexpected redirect target"); + const client = readPendingHandoffClient(); + const redirectUrl = + client === "desktop-dev" ? await api.desktopCode(challenge, "desktop-dev") : await api.desktopCode(challenge); + if (!DEEP_LINK_PREFIXES.some((prefix) => redirectUrl.startsWith(prefix))) { + throw new Error("Unexpected redirect target"); + } clearPendingHandoff(); assign(redirectUrl); return true; diff --git a/odd/tasks/desktop-dual-storage.md b/odd/tasks/desktop-dual-storage.md new file mode 100644 index 0000000..c1acd8e --- /dev/null +++ b/odd/tasks/desktop-dual-storage.md @@ -0,0 +1,59 @@ +# Desktop dual storage mode — local (appdata) vs cloud (API) + +Objective: give the desktop two storage options for workspaces/sessions/terminals — persist everything locally (appdata) or store everything in the cloud through the REST API built in feature `api-rest-crud` — with mode selection on Onboarding + Settings, collaboration visible-but-inactive in local mode, and a local→cloud migration path on switch. +Branch: feature/desktop-dual-storage (from develop c647c6f) | Delivery: PRs to develop (strategy `feature-branch-chain`, user-chosen 2026-10-19 — slices accumulate on this branch; chained PRs open at slice close, api-rest-crud style) | Test runner: `cargo test --workspace` + `cargo clippy --workspace --all-targets -- -D warnings` + `pnpm -r test` + `pnpm -r typecheck` + +## Specs + +- S1 (user, verbatim from the original request): "Lo ideal es que el usuario tenga 2 opciones al usar la aplicación, almacenar todo local (podria ser en appdata) o guardar todo en "cloud" que seria que se interactue con la API." — Two storage modes for the same desktop data. +- S2 (user decision, verbatim): Mode selection = "Onboarding + Settings" — the user picks the mode on first run (onboarding) and can change it later from Settings. +- S3 (user decision, verbatim): Collaboration in local mode = "Visibles pero inactivas" — collaboration UI stays visible but inactive when there is no cloud behind it. +- S4 (user decision, verbatim): Switching local→cloud = "Migrar local → cloud" — changing the mode from local to cloud migrates existing local data to the API. +- S5: In local mode the desktop's workspaces, sessions and terminal profiles survive restarts: they are written to appdata and restored on launch (today they are plain React state, `App.tsx` `useState`, lost on close). +- S6: In cloud mode the same workspace/session/terminal structure is stored through the authenticated REST API from feature `api-rest-crud` (develop 0dd8d1c): workspaces, sessions and terminals endpoints; the desktop's existing PKCE auth session provides the token. +- S7 (user decision 2026-10-19, verbatim): "Extender la API (Recommended)" — cloud mode must round-trip the full desktop snapshot faithfully; extend the REST API (rename/delete workspaces and sessions, terminal update/reorder/metadata, stable IDs) instead of accepting a lossy subset or adding a whole-snapshot endpoint. + +Assumptions (marked as such, not user requirements — challenge or confirm anytime): +- A1: Persisted per-terminal data = launch profile only: name/command/args/cwd/agent id, plus pane order (`Pane.seq` semantics: DOM order stable, visual order = array order) and minimized flag. Never `env` (secrets rule shared with the API), never PTY scrollback or process state. +- A2: The storage port lives in the desktop Rust core — `packages/ui/src/model.ts` already says "Workspaces y sesiones viven acá hasta que el núcleo exponga comandos para ellos" — with a local file backend (JSON under the OS appdata dir) and a cloud backend (HTTP client to the API) behind one port, exposed to the frontend through Tauri commands. +- A3: Window-level UI state (layout choice grid/columns/single, focused pane, maximized pane) is NOT persisted in this feature — only workspace/session/terminal structure. Can be a follow-up. +- A4: Migration (S4) = on mode switch to cloud, local workspaces/sessions/terminals are pushed to the API one workspace at a time; local files are kept (not deleted) after a successful migration. +- A5: Cloud mode requires a signed-in user (existing PKCE flow); switching to cloud without a session prompts login first. +- A6: The REST API base URL is configurable in Settings (dev default `http://localhost:3000`-style local API); the exact default comes from the existing desktop relay/API configuration during T3. + +## Tasks + +- T1 (S5, A1-A2): Rust core storage port (`WorkspaceSnapshot` load/save) + local appdata JSON backend + unit tests (round-trip, malformed file recovery). route: inline — DONE (RED 8/8 failing → GREEN 87/87; clippy -D warnings 0 workspace-wide; typecheck 0 post-incident recovery). Review assess: medium, under budget (no review due alone) +- T2 (S5): Tauri commands exposing the port (load on launch, save on change) + frontend bootstraps workspaces from the backend instead of `initialWorkspaces()` + persistence on every mutation. route: inline — DONE (RED 4/4 failing stub → GREEN 8/8 snapshot service; desktop suite 20/20; e2e 8 escenarios OK; `cargo test --workspace` 0 failed; clippy -D warnings 0; fmt clean; desktop `tsc --noEmit` OK). Review assess: high (`process_boundary` main.rs), review_due → native review found 1 CRITICAL (R4-load-error-destroys-snapshot) → corrected, see L10 +- T3a (S6, S7, A5): API extensions for full snapshot fidelity — PATCH/DELETE `/workspaces/:id`, PATCH/DELETE `/sessions/:id`, `PATCH /sessions/:id/terminals/:terminalId`, `PUT /sessions/:id/terminals/order`, explicit optional `id` on creates (UUID, idempotent per owner), terminal `agent`/`minimized` columns (Prisma migration) and views; domain factories accept optional id; int/unit tests per endpoint + regressions. route: delegated — parallel writer (Writer trigger: T3a/T3b independent units with disjoint edit surfaces, each several files / >100 lines). Status: DONE (commit `1b4494c`; API typecheck 0, unit 166/166, integration 190/190, domain 58/58; fixed DELETE 204 and a stale repository test; verifier T3: no blockers, L16) +- T3b (S6, S7, A2, A5): Rust cloud backend — `AccessTokenProvider` application port + `AuthStore` impl with refresh-on-demand, blocking HTTP client with TLS consuming the frozen T3 contract, `CloudSnapshotStore` behind the existing `SnapshotStore` port (load mapping, save reconciliation create/update/delete/reorder, deterministic UUID v5 mapping for local IDs), mock-server tests + error mapping. route: delegated — parallel writer (Writer trigger, same as T3a). Status: DONE (commits `313306f` + `aeb53e7`; `cargo test --workspace` 238 passed, clippy -D warnings 0, fmt clean, desktop 24/24; fixed ureq 3 API and stale tests; seq global fix + regression, L16) +- T4 (S2, A6): Onboarding on first run + Settings mode switch (mode persisted); wire `AppState.snapshot_store` to the selected backend; base URL configurable in Settings with default from the existing relay/API config; refuse empty/unhydrated cloud saves and add single-flight token refresh before exposing the provider. route: inline — DONE (commits `0c025af` + `ab7b45b`; verifier T4 found B1 cloud boot without session and B2 invalid-URL partial fallback, both fixed in `ab7b45b` with `CloudGate`, full config fallback, auth single-flight concurrency tests, and `cloud-boot-session.mjs` E2E, L18) +- T5 (S3): Local-mode collaboration visible-but-inactive. route: inline — DONE (commit `e4b4045`; RED 1/12 Rust + 1/7 UI → GREEN 12/12 `collab_status` + 65/65 UI + 21/21 desktop + 13/13 E2E incl. `local-collab-inactive.mjs`; clippy -D warnings 0; fmt clean; typecheck 0, L19-L20) +- T6 (S4, A4): Local→cloud migration on switch. route: inline — DONE (commit `6e79869`; RED 2/2 `infrastructure` + 2/2 `desktop::state` → GREEN 2/2 `migrar_` + 3/3 `state::tests` + 14/14 E2E incl. `local-to-cloud-migration.mjs`; clippy -D warnings 0; fmt clean; independent verifier `ae925551`: PASS on S4/A4, 0 blockers, L21-L22) +- T7 (S1-S6): Full verification: cargo test/clippy/fmt, pnpm test/typecheck/build, help/docs updated. route: inline — DONE (commit `67140cf`; `cargo fmt --all --check` 0, `cargo clippy --workspace --all-targets -- -D warnings` 0, `cargo test --workspace` 254 passed / 0 failed / 6 ignored, `pnpm -r typecheck` 5/5, `pnpm -r test` 406/406 across 37 files, `pnpm -r build` 6/6, desktop E2E 14/14 scenarios / 107 assertions; `AGENTS.md` + `README.md` updated, L23) + +## Log + +- L1 (2026-10-15, user kickoff, verbatim): "podrias ir haciendolo vos?" — continue the delegated flow autonomously: merge the api-rest-crud PR chain (done, see L2) and start this next feature (per the scope decision recorded in `odd/tasks/api-rest-crud.md` L3/L4). Original product request (verbatim, carried over): "Lo ideal es que el usuario tenga 2 opciones al usar la aplicación, almacenar todo local (podria ser en appdata) o guardar todo en "cloud" que seria que se interactue con la API." +- L2 (2026-10-15, delivery closed): api-rest-crud landed on develop via tracker PR #16 (merge commit 0dd8d1c, CI green on all slices). #13 auto-merged; #14/#15 closed with landing comments. develop docs commit c647c6f. This branch forks from develop c647c6f. +- L3 (2026-10-15, exploration findings): (a) Desktop workspaces/sessions/panes are pure React state (`apps/desktop/src/App.tsx`, `packages/ui/src/model.ts`) initialized from a hardcoded "OpenCollab" workspace — zero persistence today. (b) `model.ts` documents the planned move: core should expose commands for workspaces/sessions. (c) Rust core already has the domain parity model (`apps/desktop/core/domain`: Session/Terminal/AgentProfile with owner+access) — the same model the API persists. (d) Desktop auth (PKCE, tokens in Rust memory via `AuthStore`) already exists in `apps/desktop/src-tauri/src/auth.rs`. (e) The REST surface to consume: POST/GET /workspaces, GET /workspaces/:id, POST/GET /workspaces/:id/sessions, GET /sessions/:id, POST/DELETE /sessions/:id/terminals (env never persisted server-side). +- L4 (2026-10-15, carried-over product decisions, verbatim): Mode selection = "Onboarding + Settings"; collaboration in local mode = "Visibles pero inactivas"; switching local→cloud = "Migrar local → cloud". +- L5 (2026-10-15, T1 done): `application::storage` (WorkspaceSnapshot + Stored{Workspace,Session,Pane}, `SNAPSHOT_VERSION=1`, camelCase serde mirroring the frontend `Pane` model; `is_current_version` gate) + `SnapshotStore` port in `ports.rs` (sync by house rule: "la capa de aplicación no depende de un runtime async") + `infrastructure::FsSnapshotStore` (`workspaces.json` under the configured dir): atomic write (tmp + rename; `fs::rename` replaces on Windows), quarantine of unreadable/future-version files to `.corrupt` with fresh boot (`Ok(None)`), best-effort quarantine so a broken file never blocks the app. House patterns followed: PortError, `Fs*` adapter naming, in-module Spanish-commented tests, `serve_once`-style fixtures. Evidence: RED with stubbed store (8 behavioral tests failing) → GREEN 87/87 (`cargo test -p application -p infrastructure --lib`); `cargo clippy --workspace --all-targets -- -D warnings` exit 0; `cargo fmt --all` clean. +- L6 (2026-10-15, ENVIRONMENT INCIDENT during T1): something external wiped `packages/*` tracked files, ALL `node_modules`, `dist/` builds and left empty dirs (`.git`, root `target/`, `apps/`, `odd/` untouched; docker-compose exonerated — postgres uses a named volume, no bind mounts). Most likely OneDrive (repo lives inside OneDrive; pnpm's symlinked node_modules is a known OneDrive hazard) or Storage Sense. Recovery: `git restore packages/` (68 files), `pnpm install`, `pnpm --filter @opencollab/server^... build`; canary `pnpm -r typecheck` exit 0. OPEN RISK: this WILL recur while the repo stays inside OneDrive — relocation of the repo outside OneDrive (or excluding the folder) is a user decision, surfaced. +- L7 (2026-10-19, T2 done): bootstrapping + persistence wired end to end. Rust: `AppState.snapshot_store: Arc` (new field); `bootstrap(data_dir: PathBuf)` — the appdata dir is resolved in `main.rs` setup via `app.path().app_data_dir()` (Tauri v2: joins the bundle identifier to the OS data dir) and passed in; commands `snapshot_load` / `snapshot_save` in `commands.rs` (`#[tauri::command(async)]`, file IO off the UI thread; save takes `Vec` and the core stamps `SNAPSHOT_VERSION` via `WorkspaceSnapshot::new`). Frontend: `apps/desktop/src/services/snapshot.ts` — wire types mirroring the Rust `Stored*` structs (camelCase, `members` excluded), `toSavedWorkspaces`/`fromSavedSnapshot` (shape-validated, anything invalid → `null` fallback), `loadSnapshot`/`saveSnapshot` (save writes chained through a promise queue: two concurrent saves can never cross; failures logged, never thrown). `App.tsx`: starts with `initialWorkspaces()`, hydrates from `snapshot_load` on mount (default stays until load resolves so every `workspaces[0]` assumption holds; even a null result re-emits state once to persist the first-run baseline) and persists on every `workspaces` change gated by `hydratedRef` (a pending save must never overwrite the file with the default). Seq counter: restoring old panes would collide with `newPane()` seqs (`packages/ui/src/model.ts` counter has no setter) → new exported `adoptPaneSeq(seq)` raises the counter past the restored max. Agent ids: `packages/ui/src/agents.ts` exports `isAgentId`; a snapshot naming a removed agent restores a plain shell (`agent: null`) instead of breaking the UI. Mock: `tauri-mock.js` handles `snapshot_load` (null = clean boot) and `snapshot_save` (records, exposes `__mock.savedSnapshot`). Evidence: RED stub 4 behavioral failures → GREEN 8/8 service tests; desktop suite 20/20; e2e "Todos los E2E pasaron"; `cargo test --workspace` 13 suites 0 failed; clippy `-D warnings` 0 (one unused-import fix: `dyn` trait methods don't need the trait imported); `cargo fmt --all` clean; desktop `tsc --noEmit` OK. Authored lines T2: ~177 (git diff 7 files + 2 new service files). Running count: ~648. +- L8 (2026-10-19, delivery budget crossed): running count passed ~400 at T1 (471) and again after T2. Strategy question for the PR chain is owed before the next commit (user to choose `stacked-to-main` or `feature-branch-chain` over PRs to develop). +- L9 (2026-10-19, delivery strategy decided): user chose `feature-branch-chain` (same pattern as api-rest-crud) — feature branch keeps accumulating slices; chained PRs to develop are opened at slice close (planned: PR1 = T1+T2, PR2 = T3, PR3 = T4+T5, PR4 = T6, PR5 = T7/docs, each ≤~400 authored lines). +- L10 (2026-10-19, native review T1+T2 → correction): assess `high` (15 paths / 918 lines, reason `process_boundary` main.rs); lineage `review-be1a9a18389844a7`, target `sha256:a6b14bc5…`; one deterministic CRITICAL finding `R4-load-error-destroys-snapshot` (resilience): `App.tsx:65-70` enabled persistence after a failed `snapshot_load`, so the next mutation overwrote a still-valid snapshot with the default structure. Fix: on load rejection keep `hydratedRef` false (no quarantine/no backup needed — corrupt files arrive as `null` from the core, only unexpected errors reject); regression: e2e scenario `snapshot-load-error` (mock fails `snapshot_load` via `?mockSnapshotLoadError=1`; asserts no save after mutation and save resumes without the injected fault). Evidence: desktop vitest 20/20; `tsc --noEmit` + vite build OK; e2e 9/9 scenarios (3 new checks) OK. +- L11 (2026-10-19, native review closure BLOCKED by provider defect): successor lineage `review-9e1ebbdc684ede40` (generation 2 after `scope_changed`; target `sha256:6b1fbc38…`; correction commit `e593bac`, 50/200 correction lines). The four lenses re-ran on the corrected candidate and all were admitted (`admission_decision: completed` for risk, resilience, readability, reliability). The next bound `review.status --next-transition` returned `gentle-ai.review-integration.failure/v2`: operation `review.status`, phase `pre_native`, code `operation_timeout`, message "The negotiated review operation exceeded its aggregate time budget.", `mutation_outcome: not_started`, `authority_applicability: not_evaluated`, `retry_safe: false`, `replayability: manual_action_required`, `next_action: stop`, cause `context deadline exceeded`. One attempt only; no retry (`retry_safe: false`). State preserved: lineage stays in `reviewing` with its four admitted results; no abandon/reset/recover, no RDD toggle, no substitute command. With user consent the occurrence was reported on the open equivalent tracker: https://github.com/Gentleman-Programming/gentle-ai/issues/5422#issuecomment-6272771664 — no verifiable published fix was identified (#5094 closed by maintainer disposition without root cause; #5422 open follow-up; #5595 recurrence). No captured decline invocation exists for this lineage, so the consumer continuation fails closed. PR1 (T1+T2) remains pending review closure; implementation evidence is intact. NEXT: user decision on how to proceed (continue T3 under ordinary policy with the lineage preserved, wait for maintainer guidance, or clone-scope RDD disable). +- L12 (2026-10-19, T3 read-only exploration): the current REST API (feature api-rest-crud) exposes only POST/GET workspaces, GET workspace by id, POST/GET sessions, GET session, and POST/DELETE terminals. It has no rename/delete for workspaces or sessions, no terminal update, and no fields for pane `agent` or `minimized` (only `name`/`command`/`args`/`cwd`; strict DTOs reject `env`). `seq` is derivable from terminal array order. Desktop IDs are non-UUID strings while API IDs are UUIDs, with no mapping defined. Auth: `AuthStore` has no token getter; refresh runs only inside `auth_status` on mount while the access JWT TTL is 15 minutes. No HTTP client dependency exists; the existing clients are hand-rolled blocking `std::net` without TLS. Conclusion: cloud mode cannot faithfully round-trip the snapshot under the current API. OPEN DECISION (user): (1) extend the API for full fidelity (recommended), (2) add a whole-snapshot JSON endpoint, or (3) accept a lossy subset. T3 stays route TBD until this is decided. +- L13 (2026-10-19, T3 decision): user chose verbatim "Extender la API (Recommended)" — full-fidelity cloud round-trip via extended REST endpoints; no whole-snapshot endpoint, no lossy subset. Consequence: T3 splits into T3a (API) and T3b (Rust cloud backend), launched as parallel writers with disjoint surfaces. +- L14 (2026-10-19, T3 frozen contract v1): T3a extends the API behind the existing AccessGuard (write requires Write access; inaccessible = 404, no existence leak): `PATCH /workspaces/:id` `{name}`; `DELETE /workspaces/:id` (204, cascades members/sessions/terminals); `PATCH /sessions/:id` `{name}`; `DELETE /sessions/:id` (204, cascades terminals); `POST` creates accept optional explicit UUID `id` (idempotent for the same owner: existing same-owner resource → 200 with current view, another owner's id → 409); `POST /sessions/:id/terminals` body adds `agent?`/`minimized?`; new `PATCH /sessions/:id/terminals/:terminalId` (partial `name`/`command`/`args`/`cwd`/`agent`/`minimized`, `agent` may be null) and `PUT /sessions/:id/terminals/order` `{ids: string[]}` (exactly the session's terminals, atomic reorder); all terminal views gain `agent`/`minimized`; no `seq`/`env` fields ever (A1). Prisma: add `agent String?` and `minimized Boolean @default(false)` to Terminal + new migration (int tests apply real migrations via `prisma migrate deploy`); `position` already exists. Domain: factories accept optional ids; `Terminal` gains optional metadata; defaults keep every existing call site and test behavior unchanged. ID strategy (frozen): Rust derives a deterministic UUID v5 from each non-UUID local id (fixed namespace constant; an id that already parses as UUID is used as-is), so creates are idempotent across restarts and T6 migration reuses the mapping; server-generated ids remain for web clients. T3b: new sync `AccessTokenProvider` port in application with `AuthStore` impl that checks expiry and refreshes on demand (extracted from `auth_status`); `CloudSnapshotStore` in infrastructure using a blocking HTTP client with TLS (`ureq` 3 + rustls preferred; no async runtime) and a configurable base URL (existing relay address); `load_snapshot` = GET workspaces + GET sessions per workspace; `save_snapshot` = reconcile create/update/delete/reorder, fail closed on any non-2xx (PortError, never partial silent state), reorder only when array order differs. Mode selection/wiring stays in T4 — T3b delivers the adapter and tests; local remains the constructive default. Open follow-up (T5/S3): the snapshot carries no access level; cloud load includes all workspaces the API returns and unpermitted mutations fail closed at the API (403) — read-only UI semantics belong to T5. Route: T3a/T3b delegated parallel writers; verification: writer self-check + independent verifier (high-risk items: auth/permissions, new dependency) + seam check. +- L15 (2026-10-20, T3a/T3b implementation + verification): both writers were cancelled after writing their units, so the parent completed and verified the work inline. T3a commit `1b4494c` (API+domain, 20 files); T3b commit `313306f` (Rust cloud client+auth, 7 files). Fixes applied: `@HttpCode(204)` on workspace/session DELETE (Nest defaulted to 200), `sessions.save` before `terminalWithOwner` in the repository test, ureq 3 request builder (`http::Request` + `agent.run`), `Clone` on `ApiTerminal`, `Result<(), PortError>` returns, mock Arc clone, stale GET-sessions and DELETE-order expectations; auth adapter added (`RefreshOutcome`, `refresh_now`, `AccessTokenProvider`) and old helpers removed. Evidence: API `typecheck` 0; API unit 166/166; API integration 190/190 with real migrations (Postgres compose, `DATABASE_URL` set for the test DB); domain 58/58; desktop 20/20; `pnpm -r typecheck` 0; `pnpm -r test` 403/403; Rust `cargo test --workspace` 237 passed + 6 ignored e2e; `cargo clippy --workspace --all-targets -- -D warnings` 0; `cargo fmt --all --check` clean; seam checked against L14 (paths/bodies/status, no seq/env). Open follow-up: native review pending the provider defect (L11); independent verifier result and seq correction in L16. Next: T4. +- L16 (2026-10-20, T3 independent verification + seq correction): read-only verifier on candidate `d880187` (base `e593bac`) reproduced no change-caused blockers in any user-reachable path; all Rust/TS/API probes green (238 Rust + 6 ignored, 403 TS, 190 integration). Eight advisories: (a) save reconciliation is destructive and an empty/unhydrated snapshot wipes the cloud — T4 must refuse those saves; (b) `seq` restarted per session on cloud load — fixed in `aeb53e7` by a single global counter + regression `load_no_reutiliza_seq_entre_sesiones`; (c) latent double-refresh race in `AuthStore` — T4 single-flight; (d) rare v5 cross-account collision from timestamp/counter ids; (e) derived profile clobber for cross-client edits; (f) pre-existing terminal table delete+recreate on save; (g) 403-vs-404 existence oracle ambiguity inherited from baseline; (h) `cargo audit` unavailable offline, so the new ureq/rustls tree has no advisory scan. A6 remains unmet at the T3 layer: only a constructor base URL exists, no Settings field/relay-derived default — moved to T4. Review assess: `high` (28 paths / 3403 lines, `hot_path` auth.rs), `review_due: high_risk`; preflight stops at `intended_untracked_selection_required` for `.gga`; no native review started, PR1/T3 closure still blocked by L11. PR2 exceeds the ~400-line slice target; evaluate split at delivery. Next: T4. +- L17 (2026-10-20, T4 frozen contract): config file `storage.json` under appdata, `{version:1, mode:"local"|"cloud", apiBaseUrl, onboardingComplete}`; missing/malformed file falls back to local + `http://` (default 8787) + onboarding incomplete. Core: `AppState.auth: Arc`, `storage_config: RwLock`, `snapshot_store: RwLock>`; commands `storage_config_get` and `storage_config_set {mode, apiBaseUrl}` validate the URL, require a session for cloud (`AuthStore::has_session`), persist, swap the store, and return the complete config; `snapshot_save` rejects an empty workspace list. Refresh single-flight: `AuthStore` serializes refreshes and compares the rejected access token, so a concurrent 401 reuses the winner's token; the `AccessTokenProvider` refresh method receives the rejected token. UI: first-run onboarding screen (Local vs Cloud; Cloud needs sign-in, inline auth prompt) and a Settings modal opened from the TopBar `Sliders` button (mode + API base URL + sign-in when needed); boot waits for the config before loading a snapshot; switching reloads the target store. T6 owns local→cloud migration — T4 only switches and leaves the local file intact. Tests: storage config unit tests, auth rejected-token short-circuit, E2E first-run onboarding; no Writer trigger (sequential core→UI), route inline. +- L18 (2026-10-22, T4 implementation + independent verification + fix closed): initial implementation in `0c025af` (`storage_config.rs`, `state.rs`, `commands.rs`, `auth.rs` single-flight refresh, `Onboarding.tsx`, `SettingsDialog.tsx`, `StorageAuth.tsx`, `TopBar.tsx`, E2E `onboarding.mjs` + `settings-storage.mjs`). Independent read-only verifier (`#570`) reported two blockers: (B1) a persisted cloud config with no in-memory session mounted the grid without a login gate and never re-hydrated on `auth-changed`, dropping mutations; (B2) an invalid `apiBaseUrl` in `storage.json` reset only the URL while preserving `mode: Cloud` and `onboardingComplete: true`. Both fixed in `ab7b45b`: added `CloudGate.tsx` (sign-in or switch to Local) and re-hydration when auth transitions to authenticated, full safe fallback in `storage_config.rs` on invalid URL, multithreaded single-flight refresh tests in `auth.rs`, and E2E scenario `cloud-boot-session.mjs`. Next: T5 (S3: local-mode collaboration visible-but-inactive). +- L19 (2026-10-22, T5 contract): S3 requires collaboration UI to remain visible but inactive in local mode. Core: `collab_status::snapshot` short-circuits in `StorageMode::Local` to `CollabStatusPayload { connected: false, sync_ms: None, collaborators: 1 }` without probing the relay; `storage_config_set` emits `collab-status` on mode switch. UI (`@opencollab/ui` `TopBar`, `Sidebar`, `StatusBar` + `App.tsx`): pass `storageMode?: "local" | "cloud"`; in local mode `Invite` stays visible and disabled with local-mode tooltip + `data-collab-inactive="true"`, `Sidebar` `.ws-meta` and `.user` stay visible with `data-collab-inactive="true"` (signed-in status shows `Local · colaboración inactiva` instead of `Online`; anonymous status shows local-mode collaboration inactive hint while preserving sign-in for Cloud switch), and `StatusBar` items stay visible with `data-collab-inactive="true"` when disconnected in local mode. Route: inline (sequential core→UI, no Writer trigger). +- L20 (2026-10-22, T5 done): implemented in `e4b4045` (13 files, +279/-20). Observed RED in `collab_status::tests::local_mode_keeps_collaboration_inactive_without_probing_the_relay` and `describeCollabMode` → GREEN 12/12 `collab_status` Rust tests, 65/65 `@opencollab/ui` tests, 21/21 `@opencollab/desktop` tests, 13/13 E2E scenarios (`local-collab-inactive.mjs` 7/7 checks + JS error check), `cargo clippy --workspace --all-targets -- -D warnings` 0, `cargo fmt --all --check` 0, `pnpm -r typecheck` 0. Risk: none (optional `storageMode` prop in `@opencollab/ui` defaults to `"cloud"`). Next: T6 (S4, A4: local→cloud migration on switch). +- L21 (2026-10-22, T6 contract): S4 + A4 require migrating existing local data to the API when switching from Local to Cloud while keeping local files intact. Core: `CloudSnapshotStore::migrate_snapshot(&WorkspaceSnapshot)` pushes each workspace in `snapshot.workspaces` one workspace at a time (reusing Phase 1 upsert + deterministic UUID v5 mapping from `local_id_to_server_uuid`) without deleting unrelated cloud workspaces already in the account (no Phase 3 workspace deletion during migration); `AppState::set_storage_config` triggers migration on `Local -> Cloud` transition when `current.onboarding_complete && current.mode == StorageMode::Local` and `FsSnapshotStore::load_snapshot()` returns a non-empty snapshot, failing closed before saving `storage.json` or swapping `snapshot_store` if migration fails, and leaving `workspaces.json` untouched on disk. UI: `SettingsDialog.tsx` local→cloud hint updated to state that local data is migrated to the cloud account and local files are kept. Route: inline (sequential core→UI, no Writer trigger); Verification trigger fires after implementation (Risk item 1: local→cloud data migration). +- L22 (2026-10-22, T6 implementation + independent verification closed): implemented in `6e79869` (7 files, +446/-78). Observed RED in `infrastructure` (`migrar_`) and `desktop::state::tests` → GREEN 2/2 `cargo test -p infrastructure migrar_`, 3/3 `cargo test -p desktop state::tests`, 14/14 E2E scenarios (`local-to-cloud-migration.mjs` 5/5 checks + 0 JS errors), `cargo clippy --workspace --all-targets -- -D warnings` 0, `cargo fmt --all --check` 0. Independent read-only verifier (`ae925551`) verified S4 and A4 on `6e79869`: PASS (0 blockers, 0 advisories). Risk: item 1 (data migration: local workspaces/sessions/terminals snapshot pushed to Cloud REST API on Local -> Cloud mode switch). Next: T7 (S1-S6: full verification + docs). +- L23 (2026-10-22, T7 full verification + docs closed): updated `AGENTS.md` and `README.md` in `67140cf` to document Local (`appdata` `workspaces.json`) vs Cloud (`CloudSnapshotStore` REST API) storage modes, first-run Onboarding and Settings (`storage.json`), local-mode visible-but-inactive collaboration (`data-collab-inactive="true"`), and additive local→cloud migration. Full suite runner (`5862a3df`) observed all checks green: `cargo fmt --all --check` exit 0; `cargo clippy --workspace --all-targets -- -D warnings` exit 0; `cargo test --workspace` 254 passed, 0 failed, 6 ignored (`application` 89, `desktop` 37, `domain` 12, `infrastructure` 108, `protocol` 8); `pnpm -r typecheck` 5/5 projects exit 0; `pnpm -r test` 37 files / 406 tests passed (`domain` 58, `ui` 65, `contracts` 6, `web` 90, `desktop` 21, `api` 166); `pnpm -r build` 6/6 packages built exit 0; `pnpm --filter @opencollab/desktop test:e2e` 14/14 scenarios (107 assertions) passed exit 0. All tasks T1–T7 DONE; ready for user decision on PR chain delivery to `develop`. diff --git a/package.json b/package.json index 404e29b..f49c54b 100644 --- a/package.json +++ b/package.json @@ -5,8 +5,10 @@ "description": "Monorepo de OpenCollab: desktop (Tauri), server (NestJS) y web (Vite). El core Rust vive en crates/ y se maneja con Cargo.", "packageManager": "pnpm@11.1.1", "scripts": { - "dev": "pnpm --filter @opencollab/desktop dev", - "desktop:dev": "pnpm --filter @opencollab/desktop dev:desktop", + "dev": "pnpm --filter \"./packages/*\" build && pnpm --parallel --stream --filter \"./apps/*\" dev", + "desktop:dev": "pnpm --filter @opencollab/desktop dev", + "api:dev": "pnpm --filter @opencollab/server dev", + "web:dev": "pnpm --filter @opencollab/web dev", "test": "pnpm -r test", "build": "pnpm -r build", "typecheck": "pnpm -r --if-present typecheck", diff --git a/packages/domain/src/session.spec.ts b/packages/domain/src/session.spec.ts index dcfcc70..ab27987 100644 --- a/packages/domain/src/session.spec.ts +++ b/packages/domain/src/session.spec.ts @@ -300,4 +300,136 @@ describe('Session', () => { guests.push({ userId: newUserId(), access: 'view' }); expect(session.guests).toEqual([{ userId: guests[0].userId, access: 'view' }]); }); + + it('create honors an explicit id', () => { + const f = fixture(); + const id = newSessionId(); + const session = Session.create(f.workspace, f.owner, 'con id', id); + expect(session.id).toBe(id); + }); + + it('addTerminal honors an explicit id and metadata', () => { + const f = fixture(); + const id = newTerminalId(); + f.session.addTerminal(f.workspace, f.owner, newAgentProfile('claude', 'claude'), { + id, + agent: 'claude', + minimized: true, + }); + expect(f.session.terminal(id)).toEqual({ + id, + profile: { name: 'claude', command: 'claude', args: [], env: [] }, + agent: 'claude', + minimized: true, + }); + }); + + it('addTerminal without options keeps the legacy shape with default metadata', () => { + const f = fixture(); + const id = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('shell', 'sh')); + expect(f.session.terminal(id)).toEqual({ + id, + profile: { name: 'shell', command: 'sh', args: [], env: [] }, + agent: null, + minimized: false, + }); + }); + + it('updateTerminal applies a partial patch and keeps untouched fields', () => { + const f = fixture(); + const id = f.session.addTerminal( + f.workspace, + f.owner, + newAgentProfile('shell', 'sh', { args: ['-l'], cwd: '/tmp' }), + ); + f.session.updateTerminal(f.workspace, f.owner, id, { name: 'renamed', minimized: true }); + expect(f.session.terminal(id)).toEqual({ + id, + profile: { name: 'renamed', command: 'sh', args: ['-l'], env: [], cwd: '/tmp' }, + agent: null, + minimized: true, + }); + }); + + it('updateTerminal replaces args, cwd and agent', () => { + const f = fixture(); + const id = f.session.addTerminal( + f.workspace, + f.owner, + newAgentProfile('claude', 'claude', { cwd: '/old' }), + { agent: 'claude', minimized: true }, + ); + f.session.updateTerminal(f.workspace, f.owner, id, { + args: ['--new'], + cwd: null, + agent: null, + minimized: false, + }); + expect(f.session.terminal(id)).toEqual({ + id, + profile: { name: 'claude', command: 'claude', args: ['--new'], env: [] }, + agent: null, + minimized: false, + }); + }); + + it('updateTerminal rejects a blank command like creation does', () => { + const f = fixture(); + const id = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('shell', 'sh')); + expectDomainError(() => f.session.updateTerminal(f.workspace, f.owner, id, { command: ' ' }), { + code: 'EmptyCommand', + }); + }); + + it('updateTerminal keeps owner-only rules and rejects unknown terminals', () => { + const f = fixture(); + const id = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('shell', 'sh')); + expectDomainError( + () => f.session.updateTerminal(f.workspace, f.member, id, { name: 'x' }), + { code: 'NotOwner' }, + ); + const unknown = newTerminalId(); + expectDomainError( + () => f.session.updateTerminal(f.workspace, f.owner, unknown, { name: 'x' }), + { code: 'TerminalNotInSession', terminal: unknown }, + ); + // A forbidden patch never leaks: the terminal stays untouched. + expect(f.session.terminal(id)?.profile.name).toBe('shell'); + }); + + it('reorderTerminals reorders the terminals by the given ids', () => { + const f = fixture(); + const a = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('a', 'sh')); + const b = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('b', 'sh')); + const c = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('c', 'sh')); + f.session.reorderTerminals(f.workspace, f.owner, [c, a, b]); + expect(f.session.terminals.map((t) => t.id)).toEqual([c, a, b]); + // Reordering twice with the same list is stable (idempotent). + f.session.reorderTerminals(f.workspace, f.owner, [b, c, a]); + expect(f.session.terminals.map((t) => t.id)).toEqual([b, c, a]); + }); + + it('reorderTerminals keeps owner-only rules and rejects unknown terminals', () => { + const f = fixture(); + const a = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('a', 'sh')); + const b = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('b', 'sh')); + expectDomainError( + () => f.session.reorderTerminals(f.workspace, f.member, [b, a]), + { code: 'NotOwner' }, + ); + const unknown = newTerminalId(); + expectDomainError( + () => f.session.reorderTerminals(f.workspace, f.owner, [a, unknown]), + { code: 'TerminalNotInSession', terminal: unknown }, + ); + // A rejected reorder never mutates the stored order. + expect(f.session.terminals.map((t) => t.id)).toEqual([a, b]); + }); + + it('rename changes the session name in place, owner-only', () => { + const f = fixture(); + expectDomainError(() => f.session.rename(f.workspace, f.member, 'no'), { code: 'NotOwner' }); + f.session.rename(f.workspace, f.owner, 'renombrada'); + expect(f.session.name).toBe('renombrada'); + }); }); diff --git a/packages/domain/src/session.ts b/packages/domain/src/session.ts index f4bcd61..a71f8df 100644 --- a/packages/domain/src/session.ts +++ b/packages/domain/src/session.ts @@ -17,7 +17,14 @@ import { withWrite, type AccessLevel, } from './permission'; -import type { AgentProfile, Terminal } from './terminal'; +import { + newAgentProfile, + newTerminal, + type AgentProfile, + type Terminal, + type TerminalCreateOptions, + type TerminalPatch, +} from './terminal'; import type { Workspace } from './workspace'; // Temporary guest: access to this session only, never the rest of the workspace. @@ -45,12 +52,14 @@ export class Session { private constructor( readonly id: SessionId, readonly workspaceId: WorkspaceId, - readonly name: string, + private _name: string, ) {} - static create(workspace: Workspace, actor: UserId, name: string): Session { + static create(workspace: Workspace, actor: UserId, name: string, id?: SessionId): Session { workspace.ensureOwner(actor); - return new Session(newSessionId(), workspace.id, name); + // An explicit id (S7) lets a client retry its create without duplicating + // the aggregate; the caller still runs the ownership/idempotency checks. + return new Session(id ?? newSessionId(), workspace.id, name); } // Rebuilds an aggregate from persisted state: no creation-time checks. @@ -75,6 +84,10 @@ export class Session { return [...this.memberOverrides]; } + get name(): string { + return this._name; + } + get terminals(): readonly Terminal[] { return this._terminals; } @@ -206,12 +219,55 @@ export class Session { this._guests.push({ userId: invitation.invitee, access: DEFAULT_ACCESS }); } - addTerminal(workspace: Workspace, actor: UserId, profile: AgentProfile): TerminalId { + addTerminal( + workspace: Workspace, + actor: UserId, + profile: AgentProfile, + opts: TerminalCreateOptions = {}, + ): TerminalId { + this.ensureBelongsTo(workspace); + workspace.ensureOwner(actor); + const terminal = newTerminal(opts.id ?? newTerminalId(), profile, opts); + this._terminals.push(terminal); + return terminal.id; + } + + // Owner-only partial update (S7): absent patch keys keep the current value, + // explicit nulls clear `cwd`/`agent`. The profile is rebuilt through the + // factory so a blank command stays impossible. + updateTerminal(workspace: Workspace, actor: UserId, id: TerminalId, patch: TerminalPatch): void { + this.ensureBelongsTo(workspace); + workspace.ensureOwner(actor); + const terminal = this.terminal(id); + if (!terminal) throw new DomainError({ code: 'TerminalNotInSession', terminal: id }); + const p = terminal.profile; + const cwd = patch.cwd === undefined ? (p.cwd ?? null) : patch.cwd; + this._terminals[this._terminals.indexOf(terminal)] = newTerminal( + id, + newAgentProfile(patch.name ?? p.name, patch.command ?? p.command, { + args: patch.args ?? p.args, + ...(cwd === null ? {} : { cwd }), + }), + { + agent: patch.agent === undefined ? (terminal.agent ?? null) : patch.agent, + minimized: patch.minimized === undefined ? (terminal.minimized ?? false) : patch.minimized, + }, + ); + } + + // Owner-only reorder (S7): `ids` is the exact new order. The caller must pass + // the session's terminals exactly (the REST layer turns a mismatch into 400); + // the domain still refuses to reorder around unknown or duplicated ids. + reorderTerminals(workspace: Workspace, actor: UserId, ids: readonly TerminalId[]): void { this.ensureBelongsTo(workspace); workspace.ensureOwner(actor); - const id = newTerminalId(); - this._terminals.push({ id, profile }); - return id; + for (const id of ids) this.ensureHasTerminal(id); + if (new Set(ids).size !== ids.length || ids.length !== this._terminals.length) { + throw new Error('reorderTerminals requires exactly the session terminals, without duplicates'); + } + const byId = new Map(this._terminals.map((t) => [t.id, t] as const)); + this._terminals.length = 0; + for (const id of ids) this._terminals.push(byId.get(id)!); } // Like adding them, removing terminals is owner-only. @@ -223,6 +279,13 @@ export class Session { this._terminals.splice(index, 1); } + // Owner-only rename (S7); persistence re-saves the aggregate afterwards. + rename(workspace: Workspace, actor: UserId, name: string): void { + this.ensureBelongsTo(workspace); + workspace.ensureOwner(actor); + this._name = name; + } + ensureHasTerminal(id: TerminalId): void { if (!this.terminal(id)) throw new DomainError({ code: 'TerminalNotInSession', terminal: id }); } diff --git a/packages/domain/src/terminal.ts b/packages/domain/src/terminal.ts index 5ae69d4..87cad99 100644 --- a/packages/domain/src/terminal.ts +++ b/packages/domain/src/terminal.ts @@ -27,4 +27,39 @@ export function newAgentProfile( export interface Terminal { readonly id: TerminalId; readonly profile: AgentProfile; + // Snapshot metadata (S7): which agent the pane launches (null = plain shell) + // and its collapsed state. Optional so legacy shapes still typecheck; the + // factories below always produce the canonical defaults. + readonly agent?: string | null; + readonly minimized?: boolean; +} + +// Creation input for a terminal: the explicit id powers the desktop's +// idempotent create (S7); the metadata mirrors the saved pane state. +export interface TerminalCreateOptions { + readonly id?: TerminalId; + readonly agent?: string | null; + readonly minimized?: boolean; +} + +// Partial terminal update (S7). Absent keys keep the current value; explicit +// nulls clear `cwd` and `agent`. +export interface TerminalPatch { + readonly name?: string; + readonly command?: string; + readonly args?: string[]; + readonly cwd?: string | null; + readonly agent?: string | null; + readonly minimized?: boolean; +} + +// Canonical terminal constructor: metadata is always present in memory, so +// views and persistence never branch on missing keys. +export function newTerminal(id: TerminalId, profile: AgentProfile, opts: TerminalCreateOptions = {}): Terminal { + return { + id, + profile, + agent: opts.agent ?? null, + minimized: opts.minimized ?? false, + }; } diff --git a/packages/domain/src/workspace.spec.ts b/packages/domain/src/workspace.spec.ts index 388964f..d728159 100644 --- a/packages/domain/src/workspace.spec.ts +++ b/packages/domain/src/workspace.spec.ts @@ -81,4 +81,19 @@ describe('Workspace', () => { ws.addMember(owner, invitee); expect(ws.isMember(invitee)).toBe(true); }); + + it('accepts an explicit id and keeps generating one by default', () => { + const owner = newUserId(); + const id = newWorkspaceId(); + expect(new Workspace(owner, 'con id', id).id).toBe(id); + expect(new Workspace(owner, 'generado').id).toBeTruthy(); + }); + + it('rename changes the workspace name in place, owner-only', () => { + const owner = newUserId(); + const ws = new Workspace(owner, 'antes'); + expectDomainError(() => ws.rename(newUserId(), 'no'), { code: 'NotOwner' }); + ws.rename(owner, 'después'); + expect(ws.name).toBe('después'); + }); }); diff --git a/packages/domain/src/workspace.ts b/packages/domain/src/workspace.ts index 25abe1b..b151b95 100644 --- a/packages/domain/src/workspace.ts +++ b/packages/domain/src/workspace.ts @@ -12,7 +12,7 @@ export class Workspace { constructor( readonly owner: UserId, - readonly name: string, + private _name: string, readonly id: WorkspaceId = newWorkspaceId(), ) {} @@ -28,6 +28,16 @@ export class Workspace { return ws; } + get name(): string { + return this._name; + } + + // Owner-only rename (S7); persistence re-saves the aggregate afterwards. + rename(actor: UserId, name: string): void { + this.ensureOwner(actor); + this._name = name; + } + get members(): readonly WorkspaceMember[] { return this._members; } diff --git a/packages/ui/src/agents.ts b/packages/ui/src/agents.ts index 2260921..70b15ed 100644 --- a/packages/ui/src/agents.ts +++ b/packages/ui/src/agents.ts @@ -22,3 +22,10 @@ const catalog: Record = { export function agentInfo(id: AgentId) { return catalog[id]; } + +/// ¿`value` es un id de agente vigente? Para validar datos guardados: el +/// scheduler de un snapshot viejo podría nombrar un agente que la versión de +/// hoy ya no conoce; ese caso cae a `null` (shell plana) en vez de romper. +export function isAgentId(value: unknown): value is AgentId { + return typeof value === "string" && value in catalog; +} diff --git a/packages/ui/src/collabStatus.test.ts b/packages/ui/src/collabStatus.test.ts index 4a374b2..e18e2dd 100644 --- a/packages/ui/src/collabStatus.test.ts +++ b/packages/ui/src/collabStatus.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { DEFAULT_COLLAB_STATUS, parseCollabStatus } from "./collabStatus"; +import { DEFAULT_COLLAB_STATUS, describeCollabMode, parseCollabStatus } from "./collabStatus"; describe("DEFAULT_COLLAB_STATUS", () => { it("es honesto: desconectado, sin latencia y solo el usuario local", () => { @@ -30,3 +30,25 @@ describe("parseCollabStatus", () => { expect(parseCollabStatus({ connected: "sí", collaborators: -3 })).toEqual(DEFAULT_COLLAB_STATUS); }); }); + +describe("describeCollabMode", () => { + it("en modo local marca la colaboración como inactiva con textos explícitos", () => { + const local = describeCollabMode("local"); + expect(local.inactive).toBe(true); + expect(local.inviteTitle).toContain("Modo local"); + expect(local.workspaceMetaTitle).toBe("Colaboración inactiva en modo local"); + expect(local.onlineLabel).toBe("Local · colaboración inactiva"); + expect(local.anonymousHint).toBe("Colaboración inactiva en modo local"); + expect(local.statusBarTitle).toBe("Colaboración inactiva en modo local"); + }); + + it("en modo cloud mantiene la colaboración activa", () => { + const cloud = describeCollabMode("cloud"); + expect(cloud.inactive).toBe(false); + expect(cloud.inviteTitle).toBe("Requiere el relay: todavía no está conectado"); + expect(cloud.workspaceMetaTitle).toBeUndefined(); + expect(cloud.onlineLabel).toBe("Online"); + expect(cloud.anonymousHint).toBe("Sign in to collaborate"); + expect(cloud.statusBarTitle).toBeUndefined(); + }); +}); diff --git a/packages/ui/src/collabStatus.ts b/packages/ui/src/collabStatus.ts index fd48449..04d70bd 100644 --- a/packages/ui/src/collabStatus.ts +++ b/packages/ui/src/collabStatus.ts @@ -9,6 +9,38 @@ export type CollabStatus = { collaborators: number; }; +export type StorageMode = "local" | "cloud"; + +export type CollabModeCopy = { + inactive: boolean; + inviteTitle: string; + workspaceMetaTitle: string | undefined; + onlineLabel: string; + anonymousHint: string; + statusBarTitle: string | undefined; +}; + +export function describeCollabMode(mode: StorageMode = "cloud"): CollabModeCopy { + if (mode === "local") { + return { + inactive: true, + inviteTitle: "Modo local: cambiá a Cloud en Settings para invitar colaboradores", + workspaceMetaTitle: "Colaboración inactiva en modo local", + onlineLabel: "Local · colaboración inactiva", + anonymousHint: "Colaboración inactiva en modo local", + statusBarTitle: "Colaboración inactiva en modo local", + }; + } + return { + inactive: false, + inviteTitle: "Requiere el relay: todavía no está conectado", + workspaceMetaTitle: undefined, + onlineLabel: "Online", + anonymousHint: "Sign in to collaborate", + statusBarTitle: undefined, + }; +} + export const DEFAULT_COLLAB_STATUS: CollabStatus = { connected: false, syncMs: null, collaborators: 1 }; /// Convierte el payload del núcleo (`collab_status` / evento `collab-status`) en un diff --git a/packages/ui/src/components/Sidebar.tsx b/packages/ui/src/components/Sidebar.tsx index b6f2810..fcd8614 100644 --- a/packages/ui/src/components/Sidebar.tsx +++ b/packages/ui/src/components/Sidebar.tsx @@ -5,6 +5,7 @@ import { VscTerminal } from "react-icons/vsc"; import { agentInfo } from "../agents"; import { opencollabLogoRounded } from "../brand"; import { initialsOf, type AuthState } from "../authTypes"; +import { describeCollabMode, type CollabModeCopy, type StorageMode } from "../collabStatus"; import { Check, ChevronDown, Plus, Search, SignOut } from "../icons"; import { sessionSummary, @@ -32,6 +33,7 @@ type Props = { onSelectSession: (id: string) => void; onSelectTerminal: (sessionId: string, paneId: string) => void; onCreateSession: () => void; + storageMode?: StorageMode; auth: AuthState; authBusy: boolean; authError: string | null; @@ -43,6 +45,7 @@ type Props = { export function Sidebar(props: Props) { const { workspaces, activeWorkspace, activeSessionId, statuses, meta } = props; + const collab = describeCollabMode(props.storageMode); const [switcherOpen, setSwitcherOpen] = useState(false); const [query, setQuery] = useState(""); const switcherRef = useRef(null); @@ -74,7 +77,11 @@ export function Sidebar(props: Props) { {activeWorkspace.name} - + Workspace · {activeWorkspace.members} member{activeWorkspace.members === 1 ? "" : "s"} @@ -233,6 +240,7 @@ export function Sidebar(props: Props) { {/* Cuenta del desktop: anónima ofrece el login vía la web; autenticada muestra el usuario real (antes era la cuenta local fija, oculta). */} void; onSignOut: () => void; }) { - const { auth, busy } = props; + const { auth, busy, collab } = props; if (auth.status === "authenticated") { return ( -
+
{initialsOf(auth.user)} {auth.user.displayName || auth.user.username} - Online + {collab.onlineLabel} } title="Sign out" onClick={props.onSignOut} /> @@ -270,7 +282,10 @@ function AuthCard(props: { ); } return ( -
+
{auth.status === "unknown" ? "Loading…" : busy ? "Waiting for browser…" : "Not signed in"} @@ -281,7 +296,7 @@ function AuthCard(props: { ) : ( - {busy ? "Finish sign-in in your browser" : "Sign in to collaborate"} + {busy ? "Finish sign-in in your browser" : collab.anonymousHint} )} diff --git a/packages/ui/src/components/StatusBar.tsx b/packages/ui/src/components/StatusBar.tsx index 38ccec1..b017ea6 100644 --- a/packages/ui/src/components/StatusBar.tsx +++ b/packages/ui/src/components/StatusBar.tsx @@ -1,20 +1,29 @@ -import { DEFAULT_COLLAB_STATUS } from "../collabStatus"; +import { DEFAULT_COLLAB_STATUS, describeCollabMode, type StorageMode } from "../collabStatus"; import { modKey, shiftKey } from "../shortcuts"; type Props = { connected?: boolean; syncMs?: number | null; collaborators?: number; + storageMode?: StorageMode; }; export function StatusBar({ connected = DEFAULT_COLLAB_STATUS.connected, syncMs = DEFAULT_COLLAB_STATUS.syncMs, collaborators = DEFAULT_COLLAB_STATUS.collaborators, + storageMode, }: Props = {}) { + const collab = describeCollabMode(storageMode); + const inactive = collab.inactive && !connected; + const itemClass = `statusbar-item ${inactive ? "statusbar-item--inactive" : ""}`.trim(); return (