From 4053dcb25d21145e00eb6bd9d0bebdbdf2b47cf8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Thu, 5 Nov 2026 13:30:06 +0100 Subject: [PATCH 01/34] feat(remote): open a remote CodeNomad project in a tab of the local window Issue #1236 lets one CodeNomad window work on projects that run elsewhere (container, MicroVM, remote host) next to local projects. A remote project is served by a CodeNomad server running where the project lives, so its conversations, files, Git, settings and Missions keep working unchanged. Remotes, on the home page and in the new-instance launcher, lists the saved CodeNomad servers. Its field adds one from a pasted pairing link or address (links carrying credentials are refused) through the existing probe. Choosing a server opens a project tab: a native view placed over the tab's content shows the server's own UI in an embedded single-project mode, where the user picks the folder. The tab shows the server icon and the project name, the project joins the mixed recents (server, folder and name only) and tabs come back with the restored app state. Profiles that skip TLS verification, and Tauri outside Windows, keep their separate remote window. The embedded mode (`/?codenomadEmbed=project[&folder=]`) hides the title bar, tab bar and home page, offers a folder picker until a project opens, records the folder in its address and the project name in its title, and never sets the native badge. A server without this mode simply shows its full interface; the host only accepts a title change from the server's origin with a folder. The view reuses the storage of that server's remote window (Electron partition, Tauri data directory), so an existing session or paired device cookie works without signing in again. It has the remote preload/capability: of native access only notifications reach the host. Navigation stays on the server's origin (the public help site opens in the system browser) and the bare root that ends login or pairing returns to the tab's entry. The view opens when its tab first shows, follows the placeholder's bounds and hides while the tab is hidden or a local dialog, menu or list is open (the browser previews' overlay rule, now shared). Reloading or closing the owning page closes its views. Web clients, Remote Control devices, remote windows and embedded pages never offer remote tabs, so nothing rebounds through a host. Electron uses a WebContentsView per tab (`electron/main/remote-view.ts`); Tauri a child webview labelled `remote-view-*` (`src-tauri/src/remote_view.rs`) that inherits the remote windows' capability. Validation: UI and Electron typechecks; UI unit tests (state codec, partitions, tabs, restore, embedded mode, link classification, recents, host guard); browser tests on the real app (`remote-project-tabs.test.ts`: embedded page without chrome, folder picker and direct folder, full interface without the parameter, no Remotes on web or remote pages, tab opening and relabelling, overlay hiding, unverified-certificate window, pasted pairing link, restore); Electron `remote-view.test.ts` and preload tests; Rust tests for navigation, ownership and the child label's ACL; offline Tauri release build; help tests. --- .github/workflows/pr-build.yml | 4 + AGENTS.md | 2 +- dev-docs/PROJECTS.md | 3 +- dev-docs/REMOTE_CONTROL.md | 4 + docs/help/de/remote-access.md | 9 + docs/help/en/remote-access.md | 9 + docs/help/es/remote-access.md | 9 + docs/help/fr/remote-access.md | 9 + docs/help/he/remote-access.md | 9 + docs/help/ja/remote-access.md | 9 + docs/help/ne/remote-access.md | 9 + docs/help/ru/remote-access.md | 9 + docs/help/tr/remote-access.md | 9 + docs/help/zh-Hans/remote-access.md | 9 + packages/electron-app/electron/main/ipc.ts | 18 +- packages/electron-app/electron/main/main.ts | 23 +- .../main/remote-recovery.electron-fixture.ts | 1 + .../electron/main/remote-view.test.ts | 136 ++++++ .../electron-app/electron/main/remote-view.ts | 208 +++++++++ .../electron-app/electron/preload/index.cjs | 8 + .../electron/preload/index.test.ts | 29 ++ packages/electron-app/package.json | 2 +- packages/tauri-app/src-tauri/build.rs | 3 + .../src-tauri/capabilities/main-window.json | 5 +- .../autogenerated/remote_view_close.toml | 11 + .../autogenerated/remote_view_open.toml | 11 + .../autogenerated/remote_view_update.toml | 11 + packages/tauri-app/src-tauri/src/main.rs | 73 ++- .../tauri-app/src-tauri/src/remote_view.rs | 440 ++++++++++++++++++ packages/ui/src/App.tsx | 55 ++- packages/ui/src/components/browser-frame.tsx | 3 +- .../components/embedded-project-picker.tsx | 57 +++ .../src/components/folder-selection-view.tsx | 101 ++-- packages/ui/src/components/instance-tabs.tsx | 15 +- .../src/components/new-instance-launcher.tsx | 36 +- .../ui/src/components/remote-project-menu.tsx | 156 +++++++ .../ui/src/components/remote-project-view.tsx | 127 +++++ packages/ui/src/lib/codenomad-link.test.ts | 32 ++ packages/ui/src/lib/codenomad-link.ts | 33 ++ packages/ui/src/lib/embed-mode.test.ts | 35 ++ packages/ui/src/lib/embed-mode.ts | 80 ++++ .../src/lib/hooks/use-app-session-capture.ts | 4 + .../src/lib/hooks/use-app-session-restore.ts | 26 +- .../lib/hooks/use-remote-server-profiles.ts | 30 +- .../lib/i18n/messages/de/folderSelection.ts | 7 + .../lib/i18n/messages/en/folderSelection.ts | 7 + .../lib/i18n/messages/es/folderSelection.ts | 7 + .../lib/i18n/messages/fr/folderSelection.ts | 7 + .../lib/i18n/messages/he/folderSelection.ts | 7 + .../lib/i18n/messages/ja/folderSelection.ts | 7 + .../lib/i18n/messages/ne/folderSelection.ts | 7 + .../lib/i18n/messages/ru/folderSelection.ts | 7 + .../lib/i18n/messages/tr/folderSelection.ts | 7 + .../i18n/messages/zh-Hans/folderSelection.ts | 7 + packages/ui/src/lib/native/browser.ts | 5 + packages/ui/src/lib/native/remote-view.ts | 66 +++ .../ui/src/lib/notification-icon-badge.ts | 5 +- .../ui/src/lib/remote-project-recents.test.ts | 70 +++ packages/ui/src/lib/remote-project-recents.ts | 95 ++++ .../src/stores/app-session-snapshot-merge.ts | 2 +- packages/ui/src/stores/app-tabs.test.ts | 6 +- packages/ui/src/stores/app-tabs.ts | 40 +- packages/ui/src/stores/client-state-codec.ts | 14 +- .../ui/src/stores/client-state-partitions.ts | 6 + packages/ui/src/stores/preferences.tsx | 30 +- packages/ui/src/stores/remote-project-open.ts | 34 ++ .../ui/src/stores/remote-project-tabs.test.ts | 86 ++++ packages/ui/src/stores/remote-project-tabs.ts | 61 +++ .../styles/components/remote-project-menu.css | 112 +++++ packages/ui/src/styles/controls.css | 1 + packages/ui/src/types/global.d.ts | 4 + .../browser/new-instance-launcher.test.ts | 3 +- .../tests/browser/remote-project-tabs.test.ts | 230 +++++++++ 73 files changed, 2704 insertions(+), 108 deletions(-) create mode 100644 packages/electron-app/electron/main/remote-view.test.ts create mode 100644 packages/electron-app/electron/main/remote-view.ts create mode 100644 packages/tauri-app/src-tauri/permissions/autogenerated/remote_view_close.toml create mode 100644 packages/tauri-app/src-tauri/permissions/autogenerated/remote_view_open.toml create mode 100644 packages/tauri-app/src-tauri/permissions/autogenerated/remote_view_update.toml create mode 100644 packages/tauri-app/src-tauri/src/remote_view.rs create mode 100644 packages/ui/src/components/embedded-project-picker.tsx create mode 100644 packages/ui/src/components/remote-project-menu.tsx create mode 100644 packages/ui/src/components/remote-project-view.tsx create mode 100644 packages/ui/src/lib/codenomad-link.test.ts create mode 100644 packages/ui/src/lib/codenomad-link.ts create mode 100644 packages/ui/src/lib/embed-mode.test.ts create mode 100644 packages/ui/src/lib/embed-mode.ts create mode 100644 packages/ui/src/lib/native/remote-view.ts create mode 100644 packages/ui/src/lib/remote-project-recents.test.ts create mode 100644 packages/ui/src/lib/remote-project-recents.ts create mode 100644 packages/ui/src/stores/remote-project-open.ts create mode 100644 packages/ui/src/stores/remote-project-tabs.test.ts create mode 100644 packages/ui/src/stores/remote-project-tabs.ts create mode 100644 packages/ui/src/styles/components/remote-project-menu.css create mode 100644 packages/ui/tests/browser/remote-project-tabs.test.ts diff --git a/.github/workflows/pr-build.yml b/.github/workflows/pr-build.yml index 4b1122f391..9615b4d095 100644 --- a/.github/workflows/pr-build.yml +++ b/.github/workflows/pr-build.yml @@ -370,6 +370,9 @@ jobs: packages/ui/src/lib/retained-size.test.ts packages/ui/src/lib/provider-auth.test.ts packages/ui/src/lib/remote-pairing-link.test.ts + packages/ui/src/lib/codenomad-link.test.ts + packages/ui/src/lib/embed-mode.test.ts + packages/ui/src/lib/remote-project-recents.test.ts packages/ui/src/lib/native/browser.test.ts packages/ui/src/lib/runtime-env.test.ts packages/ui/src/lib/session-transcript-lru.test.ts @@ -485,6 +488,7 @@ jobs: packages/ui/src/stores/instance-startup-priority.test.ts packages/ui/src/stores/session-list-startup.test.ts packages/ui/src/stores/app-tabs.test.ts + packages/ui/src/stores/remote-project-tabs.test.ts packages/ui/src/stores/forms.test.ts packages/ui/src/stores/preferences-favorites-mode.test.ts packages/ui/src/stores/instances-restore-ownership.test.ts diff --git a/AGENTS.md b/AGENTS.md index 40d1b18c60..86ad3339e2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,7 +33,7 @@ Paths are under `packages/ui/src/` or `packages/server/src/` unless stated. - **Session state and recovery** (`stores/session-state.ts`, `stores/session-generation-recovery.ts`): `dev-docs/SESSION_RECOVERY.md`. - **Dialogs, utility windows, icon toggles, surfaces and scrollbars** (`alert-dialog.tsx`, `dismissible-window.tsx`, auth recovery, `styles/utilities.css`, `index.css`): `dev-docs/UI_CONVENTIONS.md`. - **Settings and Preferences** (settings rows/actions, Preferences window and project context, Providers/Web search, Stats, notifications, bug report): `dev-docs/SETTINGS.md`; provider accounts and usage `dev-docs/PROVIDER_ACCOUNTS.md`; hotkeys `dev-docs/HOTKEYS.md`; palettes `dev-docs/PALETTE_SOURCES.md`; plugin controls `dev-docs/PLUGIN_CONTROLS.md`; right-panel customization and panel extensions `dev-docs/PANEL_EXTENSIONS.md`. -- **Projects and tabs** (closing tabs, temporary workspaces, new-instance launcher, Git-unavailable mode): `dev-docs/PROJECTS.md`. +- **Projects and tabs** (closing tabs, temporary workspaces, new-instance launcher, Git-unavailable mode, remote project tabs and embedded single-project mode): `dev-docs/PROJECTS.md`. - **Files panel and Git** (Workspace/Changes/Commits, file watches, Git init, whitespace filter): `dev-docs/FILES_PANEL.md`. - **Worktrees and event ownership** (`workspaces/native-worktrees.ts`, `workspaces/worktree-inventory.ts`): `dev-docs/WORKTREE_SESSION_PLACEMENT.md`. - **OpenCode runtime, setup, upgrades and OpenCode settings**: `dev-docs/OPENCODE_RUNTIME_SETUP.md`; bundled plugin builds, provisioning, presence readiness, the event relay and the Design agent and skills (`opencode/design/`): `dev-docs/OPENCODE_COMPATIBILITY.md`; connection budget: `dev-docs/CACHE_REFRESH_CONVENTIONS.md`; session environment: `dev-docs/SESSION_ENVIRONMENT.md`; pruning: `dev-docs/SESSION_PRUNING_RPC.md`. diff --git a/dev-docs/PROJECTS.md b/dev-docs/PROJECTS.md index c05c97abd2..5e6b737919 100644 --- a/dev-docs/PROJECTS.md +++ b/dev-docs/PROJECTS.md @@ -7,5 +7,6 @@ Closing project tabs, temporary workspaces, the new-instance launcher and the Gi - Closing a project tab detaches it immediately and requests deletion of that occurrence's logical backend workspace record; failures notify and never retry automatically. Separate occurrences of the same folder are independent. A `workspace.stopped` deletion closes the same record in other windows and notifies only windows displaying it that did not initiate the close. CodeNomad never evicts native Locations; OpenCode sessions keep running and reopening finds them. Whole-window close, app quit, renderer reload and backend shutdown keep existing restoration behavior. Temporary discard and server stop events use local-only tab detachment, not another DELETE; Keep closes the retained project normally. - Git is a full-functionality prerequisite, with directory-only degraded conversations when the backend cannot find Git. Only the explicitly opened physical folder is session authority in that mode; never infer sibling worktrees from native project IDs. Keep ancestor/descendant mutation identities covered by the deletion fence across Git availability changes. Inform agents through the owned native `codenomad.git-availability` instruction before prompts/custom commands, remove stale context after recovery, and keep this advisory separate from fail-closed environment synchronization. Do not add a blocking Git setup UI. Validate with `scripts/test-git-degraded-native.mjs` using an isolated CLI/database and provider. - Temporary instances (`workspaces/temporary-workspaces.ts`, UI `stores/temporary-instances.ts`) are ordinary non-Git workspaces on CodeNomad-created direct children of `/temporary-workspaces`. Registry membership (`temporary-workspaces.json`), not location, makes a folder temporary; keeping only unregisters it and adds a named recent project. Discard deletes only registered children of that root, refuses running conversations and other open tabs of the folder, removes conversations deepest-first, closes the workspace before deleting the folder and keeps failed removals registered; such a folder is reachable only by browsing to it. Closing a temporary tab from the UI asks Keep/Discard/Cancel, except that an untouched one (no conversation, file or unsent draft) closes and is discarded silently (`onlyIfEmpty`: the server refuses with `temporary_has_conversations`/`temporary_not_empty`, and any failure of that quiet discard returns the choice without an error). Before the server stops it, a visible temporary tab yields to its neighbour (or closes if alone) and a refusal restores it in place; `workspace.stopped` likewise closes the tab first and clears the instance in a microtask, because clearing a visible shell's state in the same update as its tab freezes the window. Same-minute names get a `(n)` suffix. Registry changes broadcast `workspace.temporaryChanged`, which clears kept marks in every window. Open temporary tabs are saved and restored with the app state like any project tab (still marked temporary). Only the choice dialog overrides initial focus (to its last, non-destructive choice); confirms keep focus on Cancel. Refusals use stable `temporary_*` codes localized by the client. Validate with `scripts/test-temporary-workspaces-native.mjs` against an isolated CLI. -- The tab-bar new-instance button follows the last tab like a browser: the instance `TabScroll` frame only spans its tabs and the button sits after it, outside the scroller (so focusing it never scrolls the strip), ending up at the strip's end once tabs overflow. Dragged tabs stay visually within the tab list like a browser's (`KeepDraggedTabInStrip`), while the drop slot follows the pointer's unbounded position (`closestUnboundedCenter`). The button keeps its click (full home page, Cmd/Ctrl+N) while a long press, right-click, Alt+Down, Shift+F10 or Menu opens the anchored `NewInstanceLauncher` (`lib/long-press.ts`; only Escape returns focus to the button, never over another surface or the home page): search-first recent projects (an open project switches to its tab) and Browse/Temporary/Clone only. Remote servers, SideCar and management (rename/remove recents, servers, settings) stay on the home page. Browse/clone flows live once in `components/new-instance-dialogs.tsx` (with optional home-only add-server setup) and recent-folder display helpers in `lib/recent-folder-display.ts`, shared with `FolderSelectionView`; styles in `styles/components/new-instance-launcher.css`. +- The tab-bar new-instance button follows the last tab like a browser: the instance `TabScroll` frame only spans its tabs and the button sits after it, outside the scroller (so focusing it never scrolls the strip), ending up at the strip's end once tabs overflow. Dragged tabs stay visually within the tab list like a browser's (`KeepDraggedTabInStrip`), while the drop slot follows the pointer's unbounded position (`closestUnboundedCenter`). The button keeps its click (full home page, Cmd/Ctrl+N) while a long press, right-click, Alt+Down, Shift+F10 or Menu opens the anchored `NewInstanceLauncher` (`lib/long-press.ts`; only Escape returns focus to the button, never over another surface or the home page): search-first recent projects (an open project switches to its tab), Browse/Temporary/Clone and the folded Remotes list. SideCar and management (rename/remove recents, servers, settings) stay on the home page. Browse/clone flows live once in `components/new-instance-dialogs.tsx` (with optional home-only add-server setup) and recent-folder display helpers in `lib/recent-folder-display.ts`, shared with `FolderSelectionView`; styles in `styles/components/new-instance-launcher.css`. +- Remote project tabs show one project of a saved remote CodeNomad server inside a local window. Remotes (`components/remote-project-menu.tsx`, home page and launcher, host windows only: `canOpenRemoteWindows()`) lists the saved server profiles; its field adds one from a pasted pairing link or address (`lib/codenomad-link.ts`, refusing links with credentials) through the existing probe. Choosing a server opens a `remote-project` app tab (`stores/remote-project-tabs.ts`, actions in `stores/remote-project-open.ts`) whose `RemoteProjectView` places a native view (Electron `WebContentsView`, `electron/main/remote-view.ts`; Tauri child webview on Windows, `src-tauri/src/remote_view.rs`) over its content area; elsewhere, and for profiles that skip TLS verification, the server keeps its separate remote window. The view uses that server's remote-window storage (Electron partition, Tauri data directory), so its session or paired device cookie is reused without signing in again, and the remote preload/capability: of native access only notifications reach the host (badges and every local command are refused). It stays on the server's origin, the public help site opening in the system browser; a navigation to the bare root (end of login or pairing) returns to the tab's entry. The view opens the first time its tab shows, follows the placeholder's bounds and hides while its tab is hidden or a local dialog, menu or list is open (`localOverlayOpen()`, shared with browser previews); a reload or close of the owning page closes its views. The remote page runs in embedded single-project mode (`lib/embed-mode.ts`, `/?codenomadEmbed=project[&folder=…]`): no title bar, tab bar or home page, a folder picker (`components/embedded-project-picker.tsx`) until a project opens, no native badge; it records the folder in its address and the project name in `document.title`. The host accepts a title change only from the server's origin with a folder in the address, so a server without this mode shows its full interface and the tab keeps the server's name. Tabs restore as `{kind: "remote-project", profileId, folder?}` (a removed or window-only server drops its tab); projects opened in tabs join this host's recents beside local folders (`ui` state `remoteProjectRecents`, server, folder and name only; removing a server forgets them and closes its tabs). Covered by `tests/browser/remote-project-tabs.test.ts`, `electron/main/remote-view.test.ts` and `remote_view.rs` tests (navigation, ownership, ACL of the child label). - The clone dialog (`components/new-instance-dialogs.tsx`) suggests the repository's `git clone` folder name (`lib/clone-destination.ts`) inside a parent: the folder chosen with Browse, else the server-scoped `ui` state `lastCloneParent` (the folder above the last successful clone), else the folder above the most recent project. A destination the user types is kept as entered and sent unchanged; the server creates it. diff --git a/dev-docs/REMOTE_CONTROL.md b/dev-docs/REMOTE_CONTROL.md index 7463c51dd2..55098004a9 100644 --- a/dev-docs/REMOTE_CONTROL.md +++ b/dev-docs/REMOTE_CONTROL.md @@ -89,6 +89,10 @@ browser ─TLS─▶ OpenTunnel relay (forwards ciphertext) ─▶ OpenTunnel SD The code is never stored with the server; re-pairing a saved server reuses its window storage, which keeps the device cookie across launches. Covered by `tests/browser/remote-server-pairing.test.ts`. + Pasted into Remotes, the same link opens a remote project tab whose view + pairs on its first load with the remote window's storage + ([PROJECTS.md](PROJECTS.md#agent-conventions)); the tab never relays the + tunnel through the host. - `--connect-server` opens a saved server or URL at launch through that same connect flow ([architecture.md](architecture.md#native-profiles-windows-and-client-state)). It refuses URLs with user info or a fragment, so a pairing code or password diff --git a/docs/help/de/remote-access.md b/docs/help/de/remote-access.md index 0ebc515927..57040ec24e 100644 --- a/docs/help/de/remote-access.md +++ b/docs/help/de/remote-access.md @@ -94,3 +94,12 @@ Um einen gespeicherten Server direkt von der Befehlszeile zu öffnen, starten Si Ein Remote-Fenster lässt immer einen Weg zurück zu diesem Computer. Wenn Sie das letzte lokale Fenster schließen, während Remote-Fenster geöffnet bleiben, behält es seine Tabs: **Fenster → Neues Fenster** in einem Remote-Fenster oder ein erneuter Start von CodeNomad öffnet es wieder. Kann ein Server nicht geladen werden, zeigt sein Fenster das an und bietet **Erneut versuchen**, **Lokales Fenster öffnen** und **Fenster schließen**; in der Tauri-Version verwenden Sie die Schaltfläche zum Neuladen der Seite und **Fenster → Neues Fenster**. Fügen Sie für Fernsteuerung stattdessen einen frischen Kopplungslink in **Server-URL** ein. Das Lesezeichen behält nur die Tunnel-Origin, nie den Einmal-Kopplungscode; siehe [Fernsteuerung](remote-control.md) zur erneuten Kopplung nach Verlust des Geräte-Cookies. + +## Ein Remote-Projekt in einem Tab öffnen {#remote-project-tabs} + +In der Desktop-App (Electron oder Tauri unter Windows) kann ein gespeicherter Server eines seiner Projekte auch in einem Tab dieses Fensters öffnen, neben Ihren lokalen Projekten: + +1. Öffnen Sie auf der Startseite oder im Starter **Neue Instanz** den Bereich **Remote** und wählen Sie einen Server, oder fügen Sie einen Kopplungslink oder eine Serveradresse in **Kopplungslink oder Adresse** ein. +2. Wählen Sie den Ordner im Tab. Der Tab zeigt dann das Serversymbol und den Projektnamen, und das Projekt erscheint unter **Letzte Ordner**: Dort ausgewählt, öffnet es diesen Server und Ordner direkt wieder. + +Der Tab zeigt nur dieses Projekt; seine Unterhaltungen, Dateien, Git, Einstellungen und Missions laufen auf dem Remote-Server. Er nutzt den Speicher des Remote-Fensters dieses Servers, sodass eine bestehende Anmeldung oder ein gekoppeltes Gerät wiederverwendet wird, und Remote-Tabs kehren zurück, wenn CodeNomad Ihre Tabs wiederherstellt. Ein Server ohne diesen Modus zeigt im Tab seine vollständige Oberfläche. Server, die die TLS-Prüfung überspringen, sowie der Tauri-Build unter macOS und Linux öffnen weiterhin ein Remote-Fenster. Die Seite in einem Tab kann Benachrichtigungen anzeigen, hat aber sonst keinen Zugriff auf diesen Computer und bleibt auf ihrem Server. Webclients und Remote-Control-Geräte haben keine Remote-Tabs. **Gespeicherten Server entfernen** im Kontextmenü eines Servers schließt auch seine Tabs. diff --git a/docs/help/en/remote-access.md b/docs/help/en/remote-access.md index 8dc6b30532..2573875a5d 100644 --- a/docs/help/en/remote-access.md +++ b/docs/help/en/remote-access.md @@ -94,3 +94,12 @@ To open a saved server straight from the command line, start the desktop app wit A remote window always leaves a way back to this computer. Closing the last local window while remote windows stay open keeps its tabs: **Window → New Window** in a remote window, or starting CodeNomad again, reopens it. If a server cannot be loaded, its window says so and offers **Try again**, **Open a local window** and **Close window**; in the Tauri build, use the page's reload button and **Window → New Window**. For Remote Control, paste a fresh pairing link into **Server URL** instead. The bookmark retains only the tunnel origin, never the one-use pairing code; see [Remote Control](remote-control.md) for re-pairing after device-cookie loss. + +## Open a remote project in a tab {#remote-project-tabs} + +In the desktop app (Electron, or Tauri on Windows), a saved server can also open one of its projects in a tab of this window, beside your local projects: + +1. On the home page or in the **New instance** launcher, open **Remotes** and choose a server, or paste a pairing link or server address into **Pairing link or address**. +2. Pick the folder in the tab. The tab then shows the server icon and the project name, and the project joins **Recent Folders**: choosing it there reopens that server and folder directly. + +The tab shows only that project; its conversations, files, Git, settings and Missions run on the remote server. It uses the storage of the server's remote window, so an existing sign-in or paired device is reused, and remote tabs come back when CodeNomad restores your tabs. A server without this mode shows its full interface in the tab. Servers that skip TLS verification, and the Tauri build on macOS and Linux, keep opening a remote window. The page in a tab can show notifications but has no other access to this computer and stays on its server. Web clients and Remote Control devices have no remote tabs. **Remove saved server**, in a server's context menu, also closes its tabs. diff --git a/docs/help/es/remote-access.md b/docs/help/es/remote-access.md index c0c4dc829d..8ebdfd94ac 100644 --- a/docs/help/es/remote-access.md +++ b/docs/help/es/remote-access.md @@ -94,3 +94,12 @@ Para abrir un servidor guardado directamente desde la línea de comandos, inicia Una ventana remota siempre deja una forma de volver a este equipo. Cerrar la última ventana local mientras siguen abiertas ventanas remotas conserva sus pestañas: **Ventana → Nueva ventana** en una ventana remota, o iniciar CodeNomad de nuevo, la vuelve a abrir. Si un servidor no se puede cargar, su ventana lo indica y ofrece **Reintentar**, **Abrir una ventana local** y **Cerrar ventana**; en la versión Tauri, usa el botón de recarga de la página y **Ventana → Nueva ventana**. Para Control remoto, pega en su lugar un enlace de emparejamiento nuevo en **URL del servidor**. El marcador conserva solo el origen del túnel, nunca el código de un solo uso; consulta [Control remoto](remote-control.md) para volver a emparejar tras perder la cookie del dispositivo. + +## Abrir un proyecto remoto en una pestaña {#remote-project-tabs} + +En la aplicación de escritorio (Electron, o Tauri en Windows), un servidor guardado también puede abrir uno de sus proyectos en una pestaña de esta ventana, junto a tus proyectos locales: + +1. En la página de inicio o en el lanzador **Nueva instancia**, abre **Remotos** y elige un servidor, o pega un enlace de emparejamiento o la dirección de un servidor en **Enlace de emparejamiento o dirección**. +2. Elige la carpeta en la pestaña. La pestaña muestra entonces el icono de servidor y el nombre del proyecto, y el proyecto se suma a **Carpetas recientes**: elegirlo allí vuelve a abrir directamente ese servidor y esa carpeta. + +La pestaña muestra solo ese proyecto; sus conversaciones, archivos, Git, ajustes y Missions se ejecutan en el servidor remoto. Usa el almacenamiento de la ventana remota del servidor, así que se reutiliza un inicio de sesión o un dispositivo emparejado existente, y las pestañas remotas vuelven cuando CodeNomad restaura tus pestañas. Un servidor sin este modo muestra su interfaz completa en la pestaña. Los servidores que omiten la verificación TLS, y la versión Tauri en macOS y Linux, siguen abriendo una ventana remota. La página de una pestaña puede mostrar notificaciones, pero no tiene otro acceso a este equipo y permanece en su servidor. Los clientes web y los dispositivos de Remote Control no tienen pestañas remotas. **Eliminar servidor guardado**, en el menú contextual de un servidor, también cierra sus pestañas. diff --git a/docs/help/fr/remote-access.md b/docs/help/fr/remote-access.md index 75304cf7ea..06d1cee3f0 100644 --- a/docs/help/fr/remote-access.md +++ b/docs/help/fr/remote-access.md @@ -94,3 +94,12 @@ Pour ouvrir un serveur enregistré directement depuis la ligne de commande, lanc Une fenêtre distante laisse toujours un moyen de revenir sur cet ordinateur. Fermer la dernière fenêtre locale alors que des fenêtres distantes restent ouvertes conserve ses onglets : **Fenêtre → Nouvelle fenêtre** dans une fenêtre distante, ou un nouveau lancement de CodeNomad, la rouvre. Si un serveur ne peut pas être chargé, sa fenêtre l’indique et propose **Réessayer**, **Ouvrir une fenêtre locale** et **Fermer la fenêtre** ; dans la version Tauri, utilisez le bouton d’actualisation de la page et **Fenêtre → Nouvelle fenêtre**. Pour le Contrôle à distance, collez plutôt un lien d’appairage récent dans **URL du serveur**. Le favori ne conserve que l’origine du tunnel, jamais le code d’appairage à usage unique ; voir [Contrôle à distance](remote-control.md) pour le réappairage après perte du cookie de l’appareil. + +## Ouvrir un projet distant dans un onglet {#remote-project-tabs} + +Dans l'application de bureau (Electron, ou Tauri sous Windows), un serveur enregistré peut aussi ouvrir l'un de ses projets dans un onglet de cette fenêtre, à côté de vos projets locaux : + +1. Sur l'accueil ou dans le lanceur **Nouvelle instance**, ouvrez **Distants** et choisissez un serveur, ou collez un lien d'appairage ou l'adresse d'un serveur dans **Lien d'appairage ou adresse**. +2. Choisissez le dossier dans l'onglet. L'onglet affiche alors l'icône serveur et le nom du projet, et le projet rejoint **Dossiers récents** : le choisir à cet endroit rouvre directement ce serveur et ce dossier. + +L'onglet n'affiche que ce projet ; ses conversations, fichiers, Git, paramètres et Missions s'exécutent sur le serveur distant. Il utilise le stockage de la fenêtre distante du serveur : une connexion ou un appareil appairé existant est donc réutilisé, et les onglets distants reviennent quand CodeNomad restaure vos onglets. Un serveur sans ce mode affiche son interface complète dans l'onglet. Les serveurs qui ignorent la vérification TLS, ainsi que la version Tauri sous macOS et Linux, continuent d'ouvrir une fenêtre distante. La page d'un onglet peut afficher des notifications, sans autre accès à cet ordinateur, et reste sur son serveur. Les clients web et les appareils Remote Control n'ont pas d'onglets distants. **Supprimer le serveur enregistré**, dans le menu contextuel d'un serveur, ferme aussi ses onglets. diff --git a/docs/help/he/remote-access.md b/docs/help/he/remote-access.md index 589f5cae6a..06907e2d35 100644 --- a/docs/help/he/remote-access.md +++ b/docs/help/he/remote-access.md @@ -94,3 +94,12 @@ codenomad --host 127.0.0.1 --https=false --http=true חלון מרוחק תמיד משאיר דרך לחזור למחשב הזה. סגירת החלון המקומי האחרון בזמן שחלונות מרוחקים נשארים פתוחים שומרת את הלשוניות שלו: **חלון → חלון חדש** בחלון מרוחק, או הפעלה מחדש של CodeNomad, פותחים אותו שוב. אם לא ניתן לטעון שרת, החלון שלו מציין זאת ומציע **נסו שוב**, **פתיחת חלון מקומי** ו**סגירת החלון**; בגרסת Tauri, השתמשו בכפתור הרענון של הדף וב־**חלון → חלון חדש**. לשליטה מרחוק, הדביקו במקום זאת קישור צימוד חדש ב־**כתובת השרת**. הסימנייה שומרת רק את מקור המנהרה, לעולם לא את קוד הצימוד החד־פעמי; ראו [שליטה מרחוק](remote-control.md) לצימוד מחדש לאחר אובדן עוגיית המכשיר. + +## פתיחת פרויקט מרוחק בלשונית {#remote-project-tabs} + +ביישום שולחן העבודה (Electron, או Tauri ב-Windows), שרת שמור יכול לפתוח גם אחד מהפרויקטים שלו בלשונית של החלון הזה, לצד הפרויקטים המקומיים שלך: + +1. בדף הבית או במפעיל **מופע חדש**, פתחו את **מרוחקים** ובחרו שרת, או הדביקו קישור צימוד או כתובת שרת בשדה **קישור צימוד או כתובת**. +2. בחרו את התיקייה בלשונית. הלשונית מציגה אז את סמל השרת ואת שם הפרויקט, והפרויקט מצטרף ל-**תיקיות אחרונות**: בחירה בו שם פותחת מחדש ישירות את השרת והתיקייה האלה. + +הלשונית מציגה רק את הפרויקט הזה; השיחות, הקבצים, Git, ההגדרות וה-Missions שלו פועלים בשרת המרוחק. היא משתמשת באחסון של החלון המרוחק של השרת, כך שהתחברות קיימת או מכשיר מצומד נעשים בהם שימוש חוזר, והלשוניות המרוחקות חוזרות כש-CodeNomad משחזר את הלשוניות שלך. שרת ללא מצב זה מציג בלשונית את הממשק המלא שלו. שרתים שמדלגים על אימות TLS, וגרסת Tauri ב-macOS וב-Linux, ממשיכים לפתוח חלון מרוחק. הדף שבלשונית יכול להציג התראות, אך אין לו גישה אחרת למחשב הזה והוא נשאר בשרת שלו. ללקוחות אינטרנט ולמכשירי Remote Control אין לשוניות מרוחקות. **הסר שרת שמור**, בתפריט ההקשר של שרת, סוגר גם את הלשוניות שלו. diff --git a/docs/help/ja/remote-access.md b/docs/help/ja/remote-access.md index abc13919b6..d2b476d17a 100644 --- a/docs/help/ja/remote-access.md +++ b/docs/help/ja/remote-access.md @@ -94,3 +94,12 @@ HTTPS が有効で鍵/証明書のペアを指定していない場合、CodeN リモートウィンドウからは、いつでもこのコンピューターに戻れます。リモートウィンドウを開いたまま最後のローカルウィンドウを閉じても、そのタブは保持されます。リモートウィンドウの **ウィンドウ → 新規ウィンドウ**、または CodeNomad の再起動で再び開きます。サーバーを読み込めない場合は、そのウィンドウにその旨が表示され、**再試行**、**ローカルウィンドウを開く**、**ウィンドウを閉じる** を選べます。Tauri 版では、ページの再読み込みボタンと **ウィンドウ → 新規ウィンドウ** を使用します。 リモートコントロールでは、代わりに新しいペアリングリンクを **サーバー URL** に貼り付けます。ブックマークはトンネルのオリジンだけを保持し、使い捨てのペアリングコードは保持しません。端末 Cookie 消失後の再ペアリングは、[リモートコントロール](remote-control.md)を参照してください。 + +## リモートプロジェクトをタブで開く {#remote-project-tabs} + +デスクトップアプリ(Electron、または Windows の Tauri)では、保存済みサーバーのプロジェクトを、ローカルプロジェクトと並べてこのウィンドウのタブで開くこともできます。 + +1. ホームページまたは **新しいインスタンス** ランチャーで **リモート** を開いてサーバーを選ぶか、ペアリングリンクまたはサーバーアドレスを **ペアリングリンクまたはアドレス** に貼り付けます。 +2. タブ内でフォルダーを選びます。タブにはサーバーアイコンとプロジェクト名が表示され、プロジェクトは **最近使ったフォルダ** に加わります。そこで選ぶと、そのサーバーとフォルダーが直接開き直されます。 + +タブにはそのプロジェクトだけが表示され、会話、ファイル、Git、設定、Missions はリモートサーバーで動作します。タブはそのサーバーのリモートウィンドウと同じストレージを使うため、既存のサインインやペアリング済みデバイスがそのまま使われ、CodeNomad がタブを復元するとリモートタブも戻ります。このモードを持たないサーバーは、タブに完全なインターフェースを表示します。TLS 検証を省略するサーバーと、macOS・Linux の Tauri ビルドでは、引き続きリモートウィンドウが開きます。タブ内のページは通知を表示できますが、このコンピューターへのその他のアクセスはなく、自分のサーバーから離れません。Web クライアントと Remote Control デバイスにはリモートタブはありません。サーバーのコンテキストメニューの **保存したサーバーを削除** は、そのタブも閉じます。 diff --git a/docs/help/ne/remote-access.md b/docs/help/ne/remote-access.md index 5dce2174de..34d7dd1649 100644 --- a/docs/help/ne/remote-access.md +++ b/docs/help/ne/remote-access.md @@ -94,3 +94,12 @@ certificate चेतावनी आए रोकिएर hostname, SAN, trust रिमोट विन्डोले यो कम्प्युटरमा फर्कने बाटो सधैँ छोड्छ। रिमोट विन्डोहरू खुला रहँदा अन्तिम स्थानीय विन्डो बन्द गर्दा त्यसका ट्याबहरू रहन्छन्: रिमोट विन्डोमा **सञ्झ्याल → नयाँ विन्डो**, वा CodeNomad फेरि सुरु गर्दा त्यो फेरि खुल्छ। सर्भर लोड गर्न नसकिँदा त्यसको विन्डोले त्यो देखाउँछ र **फेरि प्रयास गर्नुहोस्**, **स्थानीय विन्डो खोल्नुहोस्** र **विन्डो बन्द गर्नुहोस्** दिन्छ; Tauri संस्करणमा पृष्ठको रिलोड बटन र **सञ्झ्याल → नयाँ विन्डो** प्रयोग गर्नुहोस्। Remote Control मा **सर्भर URL** मा नयाँ pairing link paste गर्नुहोस्। bookmark ले tunnel origin मात्र राख्छ, one-use code कहिल्यै होइन; device-cookie हराएपछि पुनःpair गर्न [Remote Control](remote-control.md) हेर्नुहोस्। + +## रिमोट परियोजना ट्याबमा खोल्नुहोस् {#remote-project-tabs} + +डेस्कटप एपमा (Electron, वा Windows मा Tauri), बचत गरिएको सर्भरले आफ्नो कुनै परियोजना यो सञ्झ्यालको ट्याबमा, तपाईंका स्थानीय परियोजनाहरूसँगै, खोल्न पनि सक्छ: + +1. गृह पृष्ठमा वा **नयाँ उदाहरण** लन्चरमा **रिमोटहरू** खोल्नुहोस् र सर्भर छान्नुहोस्, वा पेयरिङ लिङ्क वा सर्भर ठेगाना **पेयरिङ लिङ्क वा ठेगाना** मा टाँस्नुहोस्। +2. ट्याबमा फोल्डर छान्नुहोस्। त्यसपछि ट्याबले सर्भर आइकन र परियोजनाको नाम देखाउँछ, र परियोजना **भर्खरका फोल्डरहरू** मा थपिन्छ: त्यहाँ छान्दा त्यही सर्भर र फोल्डर सिधै फेरि खुल्छ। + +ट्याबले त्यही परियोजना मात्र देखाउँछ; यसका कुराकानी, फाइल, Git, सेटिङ र Missions रिमोट सर्भरमा चल्छन्। यसले सर्भरको रिमोट सञ्झ्यालकै भण्डारण प्रयोग गर्छ, त्यसैले भइरहेको साइन-इन वा पेयर गरिएको उपकरण फेरि प्रयोग हुन्छ, र CodeNomad ले तपाईंका ट्याब पुनर्स्थापना गर्दा रिमोट ट्याबहरू पनि फर्कन्छन्। यो मोड नभएको सर्भरले ट्याबमा आफ्नो पूर्ण इन्टरफेस देखाउँछ। TLS प्रमाणीकरण छोड्ने सर्भरहरू, र macOS तथा Linux मा Tauri बिल्डले, रिमोट सञ्झ्याल नै खोलिरहन्छन्। ट्याबको पृष्ठले सूचना देखाउन सक्छ, तर यो कम्प्युटरमा अरू पहुँच हुँदैन र यो आफ्नै सर्भरमा रहन्छ। वेब क्लाइन्ट र Remote Control उपकरणहरूमा रिमोट ट्याब हुँदैन। सर्भरको सन्दर्भ मेनुको **बचत गरिएको सर्भर हटाउनुहोस्** ले यसका ट्याबहरू पनि बन्द गर्छ। diff --git a/docs/help/ru/remote-access.md b/docs/help/ru/remote-access.md index 1188844a07..1bc0324d70 100644 --- a/docs/help/ru/remote-access.md +++ b/docs/help/ru/remote-access.md @@ -94,3 +94,12 @@ codenomad --host 127.0.0.1 --https=false --http=true Из удалённого окна всегда можно вернуться на этот компьютер. Если закрыть последнее локальное окно, пока удалённые окна остаются открытыми, его вкладки сохраняются: **Окно → Новое окно** в удалённом окне или повторный запуск CodeNomad открывает его снова. Если сервер не удаётся загрузить, его окно сообщает об этом и предлагает **Повторить**, **Открыть локальное окно** и **Закрыть окно**; в версии Tauri используйте кнопку перезагрузки страницы и **Окно → Новое окно**. Для удалённого управления вместо этого вставьте свежую ссылку сопряжения в **URL сервера**. Закладка хранит только origin туннеля, никогда одноразовый код; повторное сопряжение после потери cookie устройства описано в [удалённом управлении](remote-control.md). + +## Открыть удалённый проект во вкладке {#remote-project-tabs} + +В настольном приложении (Electron или Tauri в Windows) сохранённый сервер может также открыть один из своих проектов во вкладке этого окна, рядом с локальными проектами: + +1. На главной странице или в панели запуска **Новый экземпляр** откройте **Удалённые** и выберите сервер или вставьте ссылку для сопряжения либо адрес сервера в поле **Ссылка для сопряжения или адрес**. +2. Выберите папку во вкладке. Вкладка покажет значок сервера и имя проекта, а проект появится в **Недавние папки**: выбор там сразу снова открывает этот сервер и папку. + +Вкладка показывает только этот проект; его беседы, файлы, Git, настройки и Missions работают на удалённом сервере. Она использует хранилище удалённого окна сервера, поэтому существующий вход или сопряжённое устройство используются повторно, а удалённые вкладки возвращаются, когда CodeNomad восстанавливает вкладки. Сервер без этого режима показывает во вкладке свой полный интерфейс. Серверы, пропускающие проверку TLS, и сборка Tauri в macOS и Linux по-прежнему открывают удалённое окно. Страница во вкладке может показывать уведомления, но не имеет другого доступа к этому компьютеру и остаётся на своём сервере. У веб-клиентов и устройств Remote Control удалённых вкладок нет. **Удалить сохраненный сервер** в контекстном меню сервера также закрывает его вкладки. diff --git a/docs/help/tr/remote-access.md b/docs/help/tr/remote-access.md index 0a8464c58e..51ea1243e5 100644 --- a/docs/help/tr/remote-access.md +++ b/docs/help/tr/remote-access.md @@ -94,3 +94,12 @@ Kayıtlı bir sunucuyu doğrudan komut satırından açmak için masaüstü uygu Uzak pencere bu bilgisayara dönmenin bir yolunu her zaman bırakır. Uzak pencereler açık kalırken son yerel pencereyi kapatmak sekmelerini korur: uzak penceredeki **Pencere → Yeni pencere** ya da CodeNomad'ı yeniden başlatmak onu yeniden açar. Bir sunucu yüklenemezse penceresi bunu bildirir ve **Yeniden dene**, **Yerel pencere aç** ve **Pencereyi kapat** seçeneklerini sunar; Tauri sürümünde sayfanın yeniden yükleme düğmesini ve **Pencere → Yeni pencere** öğesini kullanın. Uzaktan Kontrol için bunun yerine **Sunucu URL'si** öğesine yeni bir eşleştirme bağlantısı yapıştırın. Yer imi yalnızca tünelin kökenini korur, asla tek kullanımlık eşleştirme kodunu içermez; Cihaz çerezi kaybından sonra yeniden eşleştirme için bkz. [Uzaktan Kontrol](remote-control.md). + +## Uzak bir projeyi sekmede açın {#remote-project-tabs} + +Masaüstü uygulamasında (Electron veya Windows'ta Tauri), kayıtlı bir sunucu projelerinden birini yerel projelerinizin yanında bu pencerenin bir sekmesinde de açabilir: + +1. Ana sayfada veya **Yeni instance** başlatıcısında **Uzaklar** bölümünü açıp bir sunucu seçin ya da bir eşleştirme bağlantısını veya sunucu adresini **Eşleştirme bağlantısı veya adres** alanına yapıştırın. +2. Klasörü sekmede seçin. Sekme ardından sunucu simgesini ve proje adını gösterir ve proje **Son Klasörler** listesine eklenir: oradan seçmek o sunucuyu ve klasörü doğrudan yeniden açar. + +Sekme yalnızca o projeyi gösterir; konuşmaları, dosyaları, Git'i, ayarları ve Missions uzak sunucuda çalışır. Sekme sunucunun uzak penceresiyle aynı depolamayı kullanır; böylece mevcut bir oturum veya eşleştirilmiş cihaz yeniden kullanılır ve CodeNomad sekmelerinizi geri yüklediğinde uzak sekmeler de geri gelir. Bu modu olmayan bir sunucu sekmede tam arayüzünü gösterir. TLS doğrulamasını atlayan sunucular ile macOS ve Linux'taki Tauri sürümü uzak pencere açmaya devam eder. Sekmedeki sayfa bildirim gösterebilir, ancak bu bilgisayara başka erişimi yoktur ve kendi sunucusunda kalır. Web istemcilerinde ve Remote Control cihazlarında uzak sekme yoktur. Bir sunucunun bağlam menüsündeki **Kayıtlı sunucuyu kaldır** onun sekmelerini de kapatır. diff --git a/docs/help/zh-Hans/remote-access.md b/docs/help/zh-Hans/remote-access.md index daccd613e6..d5f20c7f7b 100644 --- a/docs/help/zh-Hans/remote-access.md +++ b/docs/help/zh-Hans/remote-access.md @@ -94,3 +94,12 @@ codenomad --host 127.0.0.1 --https=false --http=true 远程窗口始终保留返回本机的途径。在远程窗口仍打开时关闭最后一个本地窗口,会保留其标签页:在远程窗口中使用 **窗口 → 新建窗口**,或再次启动 CodeNomad,即可重新打开它。如果无法加载某个服务器,其窗口会说明情况,并提供 **重试**、**打开本地窗口** 和 **关闭窗口**;在 Tauri 版本中,请使用页面的重新加载按钮和 **窗口 → 新建窗口**。 使用远程控制时,改为将新配对链接粘贴到**服务器 URL**。书签仅保留隧道来源,绝不保留一次性配对码;设备 cookie 丢失后的重新配对请参阅[远程控制](remote-control.md)。 + +## 在标签页中打开远程项目 {#remote-project-tabs} + +在桌面应用中(Electron,或 Windows 上的 Tauri),已保存的服务器也可以在此窗口的标签页中打开其某个项目,与本地项目并列: + +1. 在主页或 **新建实例** 启动器中打开 **远程** 并选择服务器,或将配对链接或服务器地址粘贴到 **配对链接或地址** 中。 +2. 在标签页中选择文件夹。标签页随后显示服务器图标和项目名称,该项目也会加入 **最近的文件夹**:在那里选择它会直接重新打开该服务器和文件夹。 + +标签页只显示该项目;其对话、文件、Git、设置和 Missions 都在远程服务器上运行。它使用该服务器远程窗口的存储,因此会沿用已有的登录或已配对设备;CodeNomad 恢复标签页时,远程标签页也会恢复。没有此模式的服务器会在标签页中显示其完整界面。跳过 TLS 验证的服务器,以及 macOS 和 Linux 上的 Tauri 版本,仍然打开远程窗口。标签页中的页面可以显示通知,但对这台计算机没有其他访问权限,并始终停留在其服务器上。Web 客户端和 Remote Control 设备没有远程标签页。服务器上下文菜单中的 **删除已保存服务器** 也会关闭它的标签页。 diff --git a/packages/electron-app/electron/main/ipc.ts b/packages/electron-app/electron/main/ipc.ts index 0bc569ce6f..a58c7cc907 100644 --- a/packages/electron-app/electron/main/ipc.ts +++ b/packages/electron-app/electron/main/ipc.ts @@ -7,6 +7,7 @@ import { popupTitlebarMenu, setWorkspaceMenuEnabled, type TitlebarMenu } from ". import { requireHttpUrl } from "./navigation-security" import { validateMainFrame } from "./ipc-security" import type { BrowserController } from "./browser-controller" +import { validateRemoteViewId, validateRemoteViewOpen, type RemoteViewRegistry, type RemoteViewUpdateRequest } from "./remote-view" interface LocalSender { id: string @@ -30,6 +31,7 @@ interface CliIPCDependencies { nextConnection(windowId: string): { target: string; failure?: string; hidden: boolean } | null acknowledgeConnection(windowId: string, target: string, failure: string | null, handOff: boolean): void browserController: BrowserController + remoteViews: Pick } interface DialogOpenRequest { @@ -162,6 +164,19 @@ export function setupCliIPC(cliManager: CliProcessManager, dependencies: CliIPCD return { ok: true } }) + // Remote project tabs belong to the local window that asks for them. + ipcMain.handle("remote-view:open", async (event, payload: unknown) => { + dependencies.remoteViews.open(local(event).window, validateRemoteViewOpen(payload)) + }) + ipcMain.handle("remote-view:update", async (event, payload: unknown) => { + const request = payload as Partial | null + if (!request || typeof request.visible !== "boolean") throw new Error("Invalid remote view update") + dependencies.remoteViews.update(local(event).window, { viewId: validateRemoteViewId(request.viewId), bounds: request.bounds, visible: request.visible }) + }) + ipcMain.handle("remote-view:close", async (event, viewId: unknown) => { + dependencies.remoteViews.close(local(event).window, validateRemoteViewId(viewId)) + }) + ipcMain.handle("dialog:open", async (event, request: DialogOpenRequest): Promise => { const window = settings(event) if (!request || (request.mode !== "directory" && request.mode !== "file")) throw new Error("Invalid dialog request") @@ -246,7 +261,8 @@ export function setupCliIPC(cliManager: CliProcessManager, dependencies: CliIPCD return { ok: true } }) ipcMain.handle("notifications:show", async (event, payload: { title?: unknown; body?: unknown }): Promise<{ ok: boolean; reason?: string }> => { - anyTrusted(event) + // Notifications are the only native access a remote project tab's page has. + if (!dependencies.remoteViews.resolve(event)) anyTrusted(event) if (!Notification.isSupported()) return { ok: false, reason: "unsupported" } try { new Notification({ title: typeof payload?.title === "string" ? payload.title : "CodeNomad", body: typeof payload?.body === "string" ? payload.body : "" }).show() diff --git a/packages/electron-app/electron/main/main.ts b/packages/electron-app/electron/main/main.ts index faf0d82410..eb9a64de2b 100644 --- a/packages/electron-app/electron/main/main.ts +++ b/packages/electron-app/electron/main/main.ts @@ -1,5 +1,5 @@ import "./process-output" -import { app, BrowserWindow, dialog, ipcMain, nativeImage, screen, session } from "electron" +import { app, BrowserWindow, dialog, ipcMain, nativeImage, screen, session, WebContentsView } from "electron" import http from "node:http" import https from "node:https" import { createHash, randomUUID } from "node:crypto" @@ -38,6 +38,7 @@ import { resolveProfileRoots } from "./data-profile-cleanup" import { setupDataProfileCleanupIPC } from "./data-profile-cleanup-ipc" import { openExternalWithFeedback } from "./open-external" import { RemoteRecoveryPages, showRemoteUnavailable } from "./remote-recovery" +import { RemoteViewRegistry } from "./remote-view" const mainDirname = dirname(fileURLToPath(import.meta.url)) const isMac = process.platform === "darwin" @@ -179,6 +180,17 @@ function runPrimary(firstIntent: LaunchIntent) { request.on("error", (error) => console.warn("[electron] failed to clean up remote proxy session", sessionId, error)) request.end() }) + // Remote project tabs: the remote window's storage and preload, inside a local window. + const remoteViews = new RemoteViewRegistry({ + createView: (profileId) => new WebContentsView({ + webPreferences: { + session: session.fromPartition(resolveRemoteSessionPartition(profileId)), preload: getPreloadPath(), + contextIsolation: true, nodeIntegration: false, spellcheck: !isMac, additionalArguments: ["--codenomad-window-context=remote"], + }, + }), + openHelp: (url) => { void openExternalWithFeedback(url) }, + zoomFactor: (owner) => owner.webContents.getZoomFactor(), + }) // The unavailable-server documents the host loads in remote windows whose server could not be loaded. const remoteRecovery = new RemoteRecoveryPages() const preferencesWindows = new PreferencesWindowRegistry() @@ -354,11 +366,15 @@ function runPrimary(firstIntent: LaunchIntent) { return { action: "deny" } }) }) - window.webContents.on("did-start-navigation", (_event, _url, _isInPlace, isMainFrame) => { - if (isMainFrame) setWorkspaceMenuEnabled(window, false) + window.webContents.on("did-start-navigation", (_event, _url, isInPlace, isMainFrame) => { + if (!isMainFrame) return + setWorkspaceMenuEnabled(window, false) + // A reloaded or replaced renderer reopens its tabs' views. + if (!isInPlace) remoteViews.closeOwner(window) }) window.on("focus", () => registry.markFocused(windowId)) window.on("closed", () => { + remoteViews.closeOwner(window) registry.remove(windowId) clearWorkspaceMenuWindow(webContentsId) remoteOrigins.delete(nativeWindowId) @@ -434,6 +450,7 @@ function runPrimary(firstIntent: LaunchIntent) { void acknowledgeLaunchConnection(connectLaunchHost, id, target, failure, handOff).catch(reportLaunchConnectionError) }, browserController, + remoteViews, }) const profileRoots = resolveProfileRoots(baseUserDataPath) setupDataProfileCleanupIPC(ipcMain, { diff --git a/packages/electron-app/electron/main/remote-recovery.electron-fixture.ts b/packages/electron-app/electron/main/remote-recovery.electron-fixture.ts index 00daac3526..8687360439 100644 --- a/packages/electron-app/electron/main/remote-recovery.electron-fixture.ts +++ b/packages/electron-app/electron/main/remote-recovery.electron-fixture.ts @@ -24,6 +24,7 @@ setupCliIPC({} as never, { nextFolder: () => null, acknowledgeFolder: () => {}, nextConnection: () => null, acknowledgeConnection: () => {}, browserController: {} as never, + remoteViews: { open: () => {}, update: () => {}, close: () => {}, resolve: () => undefined }, }) // "/" is the server's own document; "/no-content" answers 204, so a retry commits no document. diff --git a/packages/electron-app/electron/main/remote-view.test.ts b/packages/electron-app/electron/main/remote-view.test.ts new file mode 100644 index 0000000000..2f05077118 --- /dev/null +++ b/packages/electron-app/electron/main/remote-view.test.ts @@ -0,0 +1,136 @@ +import assert from "node:assert/strict" +import { EventEmitter } from "node:events" +import test from "node:test" +import { + decideRemoteViewNavigation, + isRemoteHelpUrl, + remoteViewEntry, + RemoteViewRegistry, + validateRemoteViewBounds, + validateRemoteViewOpen, +} from "./remote-view" + +const origin = "https://box.example" +const entry = `${origin}/?codenomadEmbed=project&folder=%2Fsrv%2Fapp` + +test("remote views stay on their server; a bare root returns to the project entry", () => { + assert.equal(decideRemoteViewNavigation(`${origin}/?codenomadEmbed=project`, origin), "allow") + assert.equal(decideRemoteViewNavigation(`${origin}/login`, origin), "allow") + assert.equal(decideRemoteViewNavigation(`${origin}/`, origin), "entry") + assert.equal(decideRemoteViewNavigation(`${origin}/#x`, origin), "entry") + assert.equal(decideRemoteViewNavigation("about:blank", origin), "allow") + assert.equal(decideRemoteViewNavigation("https://evil.example/", origin), "deny") + assert.equal(decideRemoteViewNavigation("http://box.example/", origin), "deny") + assert.equal(decideRemoteViewNavigation("file:///C:/Windows", origin), "deny") + assert.equal(decideRemoteViewNavigation("javascript:alert(1)", origin), "deny") + assert.equal(decideRemoteViewNavigation("https://neuralnomadsai.github.io/CodeNomad/en/", origin), "help") + assert.equal(isRemoteHelpUrl("https://neuralnomadsai.github.io/Other/"), false) + assert.equal(isRemoteHelpUrl("https://user@neuralnomadsai.github.io/CodeNomad/"), false) + assert.equal(isRemoteHelpUrl("https://neuralnomadsai.github.io/CodeNomad/%2e%2e/"), false) + assert.equal(remoteViewEntry(entry, origin), entry) + assert.equal(remoteViewEntry(`${origin}/remote-pair#code`, origin), `${origin}/?codenomadEmbed=project`) +}) + +test("open requests carry a view id, integer bounds and an address on the server's origin", () => { + const request = { viewId: "tab-1", profileId: "box", baseUrl: origin, url: entry, bounds: { x: 0, y: 40, width: 800, height: 600 } } + assert.deepEqual(validateRemoteViewOpen(request), { ...request, url: new URL(entry).toString() }) + assert.throws(() => validateRemoteViewOpen({ ...request, url: "https://evil.example/" }), /origin/) + assert.throws(() => validateRemoteViewOpen({ ...request, url: "file:///etc/passwd" }), /HTTP/) + assert.throws(() => validateRemoteViewOpen({ ...request, viewId: "../x" }), /view id/) + assert.throws(() => validateRemoteViewBounds({ x: 0.5, y: 0, width: 10, height: 10 }), /bounds/) + assert.throws(() => validateRemoteViewBounds({ x: 0, y: 0, width: 0, height: 10 }), /bounds/) +}) + +class FakeContents extends EventEmitter { + url = "" + closed = false + loaded: string[] = [] + mainFrame = { url: "" } + windowOpenHandler?: (details: { url: string }) => { action: string } + isDestroyed() { return this.closed } + getURL() { return this.url } + async loadURL(url: string) { this.loaded.push(url); this.url = url; this.mainFrame.url = url } + setWindowOpenHandler(handler: (details: { url: string }) => { action: string }) { this.windowOpenHandler = handler } + close() { this.closed = true } +} + +function harness() { + const views: Array<{ webContents: FakeContents; bounds?: unknown; visible: boolean; setBounds(b: unknown): void; setVisible(v: boolean): void }> = [] + const help: string[] = [] + const sent: unknown[][] = [] + const children = new Set() + const owner = { + id: 7, + isDestroyed: () => false, + webContents: { send: (...args: unknown[]) => sent.push(args), getZoomFactor: () => 1.25 }, + contentView: { addChildView: (view: unknown) => children.add(view), removeChildView: (view: unknown) => children.delete(view) }, + } + const registry = new RemoteViewRegistry({ + createView: () => { + const view = { webContents: new FakeContents(), visible: true, setBounds(b: unknown) { this.bounds = b }, setVisible(v: boolean) { this.visible = v } } as (typeof views)[number] + views.push(view) + return view as never + }, + openHelp: (url) => help.push(url), + zoomFactor: (window) => (window as unknown as typeof owner).webContents.getZoomFactor(), + }) + return { registry, owner: owner as never, views, help, sent, children } +} + +test("a view is placed in the owner's zoomed coordinates, guarded and closed with its owner", async () => { + const h = harness() + h.registry.open(h.owner, { viewId: "tab-1", profileId: "box", baseUrl: origin, url: `${origin}/remote-pair#code`, bounds: { x: 0, y: 40, width: 800, height: 600 } }) + const view = h.views[0]! + const contents = view.webContents + assert.equal(h.children.size, 1) + assert.deepEqual(view.bounds, { x: 0, y: 50, width: 1000, height: 750 }) + assert.deepEqual(contents.loaded, [`${origin}/remote-pair#code`]) + + const navigate = (url: string) => { + let prevented = false + contents.emit("will-navigate", { preventDefault: () => { prevented = true } }, url) + return prevented + } + assert.equal(navigate("https://evil.example/"), true) + assert.equal(navigate(`${origin}/login`), false) + // Pairing and login end on the bare root: the view returns to the single-project entry. + assert.equal(navigate(`${origin}/`), true) + await new Promise((resolve) => setImmediate(resolve)) + assert.equal(contents.loaded.at(-1), `${origin}/?codenomadEmbed=project`) + assert.equal(navigate("https://neuralnomadsai.github.io/CodeNomad/en/"), true) + assert.deepEqual(h.help, ["https://neuralnomadsai.github.io/CodeNomad/en/"]) + assert.deepEqual(contents.windowOpenHandler!({ url: "https://evil.example/" }), { action: "deny" }) + + let attachPrevented = false + contents.emit("will-attach-webview", { preventDefault: () => { attachPrevented = true } }) + assert.equal(attachPrevented, true) + + contents.url = entry + contents.emit("page-title-updated", {}, "App") + assert.deepEqual(h.sent, [["remote-view:updated", { viewId: "tab-1", url: entry, title: "App" }]]) + // Once it shows a project, that project is where the view returns. + navigate(`${origin}/`) + await new Promise((resolve) => setImmediate(resolve)) + assert.equal(contents.loaded.at(-1), entry) + + h.registry.update(h.owner, { viewId: "tab-1", visible: false }) + assert.equal(view.visible, false) + assert.throws(() => h.registry.update(h.owner, { viewId: "other", visible: false }), /no longer available/) + h.registry.closeOwner(h.owner) + assert.equal(contents.closed, true) + assert.equal(h.children.size, 0) +}) + +test("only the committed main frame of a view on its server's origin is a remote view sender", async () => { + const h = harness() + h.registry.open(h.owner, { viewId: "tab-1", profileId: "box", baseUrl: origin, url: entry, bounds: { x: 0, y: 0, width: 10, height: 10 } }) + const contents = h.views[0]!.webContents + await Promise.resolve() + assert.ok(h.registry.resolve({ sender: contents as never, senderFrame: contents.mainFrame as never })) + assert.equal(h.registry.resolve({ sender: contents as never, senderFrame: { url: entry } as never }), undefined) + assert.equal(h.registry.resolve({ sender: new FakeContents() as never, senderFrame: contents.mainFrame as never }), undefined) + contents.mainFrame.url = "https://evil.example/" + assert.equal(h.registry.resolve({ sender: contents as never, senderFrame: contents.mainFrame as never }), undefined) + h.registry.close(h.owner, "tab-1") + assert.equal(contents.closed, true) +}) diff --git a/packages/electron-app/electron/main/remote-view.ts b/packages/electron-app/electron/main/remote-view.ts new file mode 100644 index 0000000000..058e7a85f3 --- /dev/null +++ b/packages/electron-app/electron/main/remote-view.ts @@ -0,0 +1,208 @@ +import type { BrowserWindow, IpcMainInvokeEvent, WebContents, WebContentsView } from "electron" +import { requireHttpUrl } from "./navigation-security" + +/** + * Remote CodeNomad project tabs: a WebContentsView per tab, inside the local + * window that owns it, on the storage of that server's remote window. The view + * has the remote preload, and of native IPC only notifications. + */ +export interface RemoteViewBounds { + x: number + y: number + width: number + height: number +} + +export interface RemoteViewOpenRequest { + viewId: string + profileId: string + baseUrl: string + url: string + bounds: RemoteViewBounds +} + +export interface RemoteViewUpdateRequest { + viewId: string + bounds?: RemoteViewBounds + visible: boolean +} + +export type RemoteViewNavigation = "allow" | "entry" | "help" | "deny" + +const VIEW_ID = /^[A-Za-z0-9_-]{1,128}$/ +const MAX_COORDINATE = 100_000 + +export function validateRemoteViewId(value: unknown): string { + if (typeof value !== "string" || !VIEW_ID.test(value)) throw new Error("Invalid remote view id") + return value +} + +export function validateRemoteViewBounds(value: unknown): RemoteViewBounds { + const bounds = value as Partial | null + const valid = (number: unknown, min: number) => typeof number === "number" && Number.isInteger(number) && number >= min && number <= MAX_COORDINATE + if (!bounds || !valid(bounds.x, 0) || !valid(bounds.y, 0) || !valid(bounds.width, 1) || !valid(bounds.height, 1)) { + throw new Error("Invalid remote view bounds") + } + return { x: bounds.x!, y: bounds.y!, width: bounds.width!, height: bounds.height! } +} + +export function validateRemoteViewOpen(value: unknown): RemoteViewOpenRequest { + const request = value as Partial | null + if (!request || typeof request.profileId !== "string" || !request.profileId.trim() || typeof request.baseUrl !== "string" || typeof request.url !== "string") { + throw new Error("Invalid remote view request") + } + const base = requireHttpUrl(request.baseUrl, "baseUrl") + const target = requireHttpUrl(request.url, "url") + if (target.origin !== base.origin) throw new Error("Remote view must open on its server's origin") + return { + viewId: validateRemoteViewId(request.viewId), + profileId: request.profileId, + baseUrl: base.origin, + url: target.toString(), + bounds: validateRemoteViewBounds(request.bounds), + } +} + +/** The public help site is the only page a remote page may hand to the system browser. */ +export function isRemoteHelpUrl(value: string): boolean { + let url: URL + try { url = new URL(value) } catch { return false } + return url.protocol === "https:" && url.hostname === "neuralnomadsai.github.io" && (url.port === "" || url.port === "443") + && !url.username && !url.password && url.pathname.startsWith("/CodeNomad/") && !url.pathname.includes("%") +} + +/** + * A view stays on its server's origin. Login and pairing pages end on the bare + * root: that returns to the tab's single-project entry instead. + */ +export function decideRemoteViewNavigation(value: string, origin: string): RemoteViewNavigation { + let url: URL + try { url = new URL(value) } catch { return "deny" } + if (url.href === "about:blank") return "allow" + if ((url.protocol === "http:" || url.protocol === "https:") && url.origin === origin) { + return url.pathname === "/" && url.search === "" ? "entry" : "allow" + } + return isRemoteHelpUrl(value) ? "help" : "deny" +} + +/** The single-project address a view returns to: its own when it has one, else the server's bare entry. */ +export function remoteViewEntry(url: string, origin: string): string { + try { + if (new URL(url).searchParams.get("codenomadEmbed") === "project") return url + } catch {} + return `${origin}/?codenomadEmbed=project` +} + +interface RemoteViewRecord { + view: WebContentsView + owner: BrowserWindow + origin: string + /** The single-project address the view returns to; follows the project it shows. */ + entryUrl: string +} + +export interface RemoteViewDependencies { + createView(profileId: string): WebContentsView + openHelp(url: string): void + /** The owner's page zoom: views are placed in window coordinates. */ + zoomFactor(owner: BrowserWindow): number +} + +export class RemoteViewRegistry { + private readonly records = new Map() + + constructor(private readonly dependencies: RemoteViewDependencies) {} + + private key(owner: BrowserWindow, viewId: string) { + return `${owner.id}:${viewId}` + } + + /** The view whose committed main frame sent this IPC, on its server's origin; never another frame. */ + resolve(event: Pick): RemoteViewRecord | undefined { + const record = [...this.records.values()].find((candidate) => candidate.view.webContents === event.sender) + if (!record || record.view.webContents.isDestroyed() || event.senderFrame !== record.view.webContents.mainFrame) return undefined + try { + return new URL(record.view.webContents.mainFrame.url).origin === record.origin ? record : undefined + } catch { + return undefined + } + } + + isRemoteView(contents: WebContents): boolean { + return [...this.records.values()].some((record) => record.view.webContents === contents) + } + + open(owner: BrowserWindow, request: RemoteViewOpenRequest): void { + const key = this.key(owner, request.viewId) + this.close(owner, request.viewId) + const view = this.dependencies.createView(request.profileId) + const record: RemoteViewRecord = { view, owner, origin: request.baseUrl, entryUrl: remoteViewEntry(request.url, request.baseUrl) } + this.records.set(key, record) + const contents = view.webContents + const guard = (event: Electron.Event, url: string) => { + const decision = decideRemoteViewNavigation(url, record.origin) + if (decision === "allow") return + event.preventDefault() + if (decision === "entry") queueMicrotask(() => { if (!contents.isDestroyed()) void contents.loadURL(record.entryUrl).catch(() => {}) }) + else if (decision === "help") this.dependencies.openHelp(url) + } + contents.on("will-navigate", guard) + contents.on("will-redirect", guard) + contents.on("will-attach-webview", (event) => event.preventDefault()) + contents.setWindowOpenHandler(({ url }) => { + if (isRemoteHelpUrl(url)) this.dependencies.openHelp(url) + return { action: "deny" } + }) + contents.on("page-title-updated", (_event, title) => { + const url = contents.getURL() + try { + const current = new URL(url) + if (current.origin === record.origin && current.searchParams.get("codenomadEmbed") === "project") record.entryUrl = url + } catch {} + if (!owner.isDestroyed()) owner.webContents.send("remote-view:updated", { viewId: request.viewId, url, title }) + }) + owner.contentView.addChildView(view) + this.place(record, request.bounds) + void contents.loadURL(request.url).catch((error) => console.warn("[electron] failed to load remote view", error)) + } + + update(owner: BrowserWindow, request: RemoteViewUpdateRequest): void { + const record = this.records.get(this.key(owner, validateRemoteViewId(request.viewId))) + if (!record) throw new Error("Remote view is no longer available") + if (!request.visible) { + record.view.setVisible(false) + return + } + this.place(record, validateRemoteViewBounds(request.bounds)) + record.view.setVisible(true) + } + + close(owner: BrowserWindow, viewId: string): void { + const key = this.key(owner, validateRemoteViewId(viewId)) + const record = this.records.get(key) + if (!record) return + this.records.delete(key) + if (!owner.isDestroyed()) owner.contentView.removeChildView(record.view) + if (!record.view.webContents.isDestroyed()) record.view.webContents.close() + } + + /** A closed or reloaded owner page takes its views with it. */ + closeOwner(owner: BrowserWindow): void { + for (const [key, record] of [...this.records]) { + if (record.owner !== owner) continue + this.records.delete(key) + if (!owner.isDestroyed()) owner.contentView.removeChildView(record.view) + if (!record.view.webContents.isDestroyed()) record.view.webContents.close() + } + } + + private place(record: RemoteViewRecord, bounds: RemoteViewBounds): void { + const zoom = this.dependencies.zoomFactor(record.owner) || 1 + record.view.setBounds({ + x: Math.round(bounds.x * zoom), + y: Math.round(bounds.y * zoom), + width: Math.max(1, Math.round(bounds.width * zoom)), + height: Math.max(1, Math.round(bounds.height * zoom)), + }) + } +} diff --git a/packages/electron-app/electron/preload/index.cjs b/packages/electron-app/electron/preload/index.cjs index 148dc5d087..29a9de5665 100644 --- a/packages/electron-app/electron/preload/index.cjs +++ b/packages/electron-app/electron/preload/index.cjs @@ -96,6 +96,14 @@ const localElectronAPI = { ipcRenderer.on("browser-target:open", handler) return () => ipcRenderer.removeListener("browser-target:open", handler) }, + openRemoteView: (payload) => ipcRenderer.invoke("remote-view:open", payload), + updateRemoteView: (payload) => ipcRenderer.invoke("remote-view:update", payload), + closeRemoteView: (viewId) => ipcRenderer.invoke("remote-view:close", viewId), + onRemoteViewUpdated: (callback) => { + const handler = (_event, payload) => callback(payload) + ipcRenderer.on("remote-view:updated", handler) + return () => ipcRenderer.removeListener("remote-view:updated", handler) + }, } const remoteElectronAPI = { diff --git a/packages/electron-app/electron/preload/index.test.ts b/packages/electron-app/electron/preload/index.test.ts index 180011307a..1c4942e78c 100644 --- a/packages/electron-app/electron/preload/index.test.ts +++ b/packages/electron-app/electron/preload/index.test.ts @@ -142,6 +142,35 @@ test("native titlebar controls remain local and obsolete automation toggles are } }) +test("remote project tabs are managed only from local windows, never from the remote pages they show", () => { + const source = readFileSync(new URL("./index.cjs", import.meta.url), "utf8") + const expose = (argv: string[], calls: unknown[][] = []) => { + let api: Record | undefined + vm.runInNewContext(source, { + require: () => ({ + contextBridge: { exposeInMainWorld(name: string, value: Record) { if (name === "electronAPI") api = value } }, + ipcRenderer: { invoke: (...args: unknown[]) => calls.push(args), on() {}, removeListener() {} }, webUtils: {}, + }), + process: { argv }, + }) + return api! + } + const operations = ["openRemoteView", "updateRemoteView", "closeRemoteView", "onRemoteViewUpdated"] + for (const context of ["remote", "preferences"]) { + for (const operation of operations) assert.equal(expose([`--codenomad-window-context=${context}`])[operation], undefined, `${context}:${operation}`) + } + // The page inside a tab has the remote windows' bridge: notifications, badge, microphone, wake lock, recovery. + assert.deepEqual(Object.keys(expose(["--codenomad-window-context=remote"])).sort(), [ + "openLocalWindow", "requestMicrophoneAccess", "retryRemoteWindow", "setNotificationBadge", "setWakeLock", "showNotification", + ]) + const calls: unknown[][] = [] + const local = expose([], calls) + local.openRemoteView({ viewId: "v" }) + local.updateRemoteView({ viewId: "v", visible: false }) + local.closeRemoteView("v") + assert.deepEqual(calls, [["remote-view:open", { viewId: "v" }], ["remote-view:update", { viewId: "v", visible: false }], ["remote-view:close", "v"]]) +}) + test("local windows choose the next launch's profile and relaunch through fixed channels", () => { const calls: unknown[][] = [] let api: Record | undefined diff --git a/packages/electron-app/package.json b/packages/electron-app/package.json index def3ec0f71..946acf45dd 100644 --- a/packages/electron-app/package.json +++ b/packages/electron-app/package.json @@ -24,7 +24,7 @@ "prebuild": "npm run prepare:resources", "build": "electron-vite build", "typecheck": "tsc --noEmit -p tsconfig.json", - "test:native": "node --import tsx --test electron/main/browser-controller.test.ts electron/main/browser-webview-security.test.ts electron/main/client-state-cross-host.test.ts electron/main/client-state-process.test.ts electron/main/client-state.test.ts electron/main/client-state-ipc.test.ts electron/main/client-state-navigation.test.ts electron/main/connect-launch.test.ts electron/main/data-profile.test.ts electron/main/data-profile-cleanup.test.ts electron/main/data-profile-cleanup-ipc.test.ts electron/main/developer-mode.test.ts electron/main/local-window-registry.test.ts electron/main/menu-target.test.ts electron/main/multiwindow-lifecycle.test.ts electron/main/native-request.test.ts electron/main/native-service-start.test.ts electron/main/navigation-security.test.ts electron/main/notification-badge.test.ts electron/main/opener-startup-state.test.ts electron/main/preferences-ipc.test.ts electron/main/preferences-window.test.ts electron/main/process-exit.test.ts electron/main/profile-transition.test.ts electron/main/process-output.test.ts electron/main/process-stop.test.ts electron/main/remote-recovery.test.ts electron/main/remote-window-registry.test.ts electron/main/renderer-client-state-flush.test.ts electron/main/renderer-origin.test.ts electron/main/serialized-lifecycle.test.ts electron/main/startup.test.ts electron/main/user-shell.test.ts electron/main/window-state.test.ts electron/main/workspace-open.test.ts electron/preload/index.test.ts", + "test:native": "node --import tsx --test electron/main/browser-controller.test.ts electron/main/browser-webview-security.test.ts electron/main/client-state-cross-host.test.ts electron/main/client-state-process.test.ts electron/main/client-state.test.ts electron/main/client-state-ipc.test.ts electron/main/client-state-navigation.test.ts electron/main/connect-launch.test.ts electron/main/data-profile.test.ts electron/main/data-profile-cleanup.test.ts electron/main/data-profile-cleanup-ipc.test.ts electron/main/developer-mode.test.ts electron/main/local-window-registry.test.ts electron/main/menu-target.test.ts electron/main/multiwindow-lifecycle.test.ts electron/main/native-request.test.ts electron/main/native-service-start.test.ts electron/main/navigation-security.test.ts electron/main/notification-badge.test.ts electron/main/opener-startup-state.test.ts electron/main/preferences-ipc.test.ts electron/main/preferences-window.test.ts electron/main/process-exit.test.ts electron/main/profile-transition.test.ts electron/main/process-output.test.ts electron/main/process-stop.test.ts electron/main/remote-recovery.test.ts electron/main/remote-view.test.ts electron/main/remote-window-registry.test.ts electron/main/renderer-client-state-flush.test.ts electron/main/renderer-origin.test.ts electron/main/serialized-lifecycle.test.ts electron/main/startup.test.ts electron/main/user-shell.test.ts electron/main/window-state.test.ts electron/main/workspace-open.test.ts electron/preload/index.test.ts", "preview": "electron-vite preview", "build:binaries": "node scripts/build.js", "build:mac": "node scripts/build.js mac", diff --git a/packages/tauri-app/src-tauri/build.rs b/packages/tauri-app/src-tauri/build.rs index ecce044115..efd1ffded7 100644 --- a/packages/tauri-app/src-tauri/build.rs +++ b/packages/tauri-app/src-tauri/build.rs @@ -95,6 +95,9 @@ fn main() { "browser_target_unregister", "browser_target_claim_open", "browser_target_release_open", + "remote_view_open", + "remote_view_update", + "remote_view_close", ]), )) .expect("build Tauri application and command ACL") diff --git a/packages/tauri-app/src-tauri/capabilities/main-window.json b/packages/tauri-app/src-tauri/capabilities/main-window.json index 47ffa1f450..c374a5d7f5 100644 --- a/packages/tauri-app/src-tauri/capabilities/main-window.json +++ b/packages/tauri-app/src-tauri/capabilities/main-window.json @@ -54,6 +54,9 @@ "allow-browser-target-action", "allow-browser-target-unregister", "allow-browser-target-claim-open", - "allow-browser-target-release-open" + "allow-browser-target-release-open", + "allow-remote-view-open", + "allow-remote-view-update", + "allow-remote-view-close" ] } diff --git a/packages/tauri-app/src-tauri/permissions/autogenerated/remote_view_close.toml b/packages/tauri-app/src-tauri/permissions/autogenerated/remote_view_close.toml new file mode 100644 index 0000000000..c111d4f0e4 --- /dev/null +++ b/packages/tauri-app/src-tauri/permissions/autogenerated/remote_view_close.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-remote-view-close" +description = "Enables the remote_view_close command without any pre-configured scope." +commands.allow = ["remote_view_close"] + +[[permission]] +identifier = "deny-remote-view-close" +description = "Denies the remote_view_close command without any pre-configured scope." +commands.deny = ["remote_view_close"] diff --git a/packages/tauri-app/src-tauri/permissions/autogenerated/remote_view_open.toml b/packages/tauri-app/src-tauri/permissions/autogenerated/remote_view_open.toml new file mode 100644 index 0000000000..04e71c2147 --- /dev/null +++ b/packages/tauri-app/src-tauri/permissions/autogenerated/remote_view_open.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-remote-view-open" +description = "Enables the remote_view_open command without any pre-configured scope." +commands.allow = ["remote_view_open"] + +[[permission]] +identifier = "deny-remote-view-open" +description = "Denies the remote_view_open command without any pre-configured scope." +commands.deny = ["remote_view_open"] diff --git a/packages/tauri-app/src-tauri/permissions/autogenerated/remote_view_update.toml b/packages/tauri-app/src-tauri/permissions/autogenerated/remote_view_update.toml new file mode 100644 index 0000000000..32a8c998e6 --- /dev/null +++ b/packages/tauri-app/src-tauri/permissions/autogenerated/remote_view_update.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-remote-view-update" +description = "Enables the remote_view_update command without any pre-configured scope." +commands.allow = ["remote_view_update"] + +[[permission]] +identifier = "deny-remote-view-update" +description = "Denies the remote_view_update command without any pre-configured scope." +commands.deny = ["remote_view_update"] diff --git a/packages/tauri-app/src-tauri/src/main.rs b/packages/tauri-app/src-tauri/src/main.rs index fd3cc3d660..5bbab14aae 100644 --- a/packages/tauri-app/src-tauri/src/main.rs +++ b/packages/tauri-app/src-tauri/src/main.rs @@ -28,6 +28,7 @@ mod notification_badge_lifetime; mod preferences_window; mod profile_selection_dialog; mod profile_transition; +mod remote_view; mod shutdown; mod title_bar; mod update_releases; @@ -569,6 +570,43 @@ fn browser_target_claim_open( Ok(claimed) } +#[tauri::command] +async fn remote_view_open( + webview: tauri::Webview, + app: AppHandle, + state: tauri::State<'_, AppState>, + views: tauri::State<'_, remote_view::RemoteViews>, + payload: remote_view::RemoteViewOpen, +) -> Result<(), String> { + require_local_app_webview(&webview, &state)?; + let window = webview.window(); + views.open(&app, &window, webview.label(), payload) +} + +#[tauri::command] +fn remote_view_update( + webview: tauri::Webview, + app: AppHandle, + state: tauri::State<'_, AppState>, + views: tauri::State<'_, remote_view::RemoteViews>, + payload: remote_view::RemoteViewUpdate, +) -> Result<(), String> { + require_local_app_webview(&webview, &state)?; + views.update(&app, webview.label(), payload) +} + +#[tauri::command] +fn remote_view_close( + webview: tauri::Webview, + app: AppHandle, + state: tauri::State<'_, AppState>, + views: tauri::State<'_, remote_view::RemoteViews>, + view_id: String, +) -> Result<(), String> { + require_local_app_webview(&webview, &state)?; + views.close(&app, webview.label(), &view_id) +} + #[tauri::command] fn browser_target_release_open( webview: tauri::Webview, @@ -1031,15 +1069,7 @@ fn open_remote_window_locked( Some(session_id) => format!("{}\0{session_id}", payload.id), None => payload.id.clone(), }; - let profile_hash = Sha256::digest(profile_key.as_bytes()) - .iter() - .map(|byte| format!("{byte:02x}")) - .collect::(); - let data_directory = app - .state::() - .webview_data_directory - .join("remote") - .join(profile_hash); + let data_directory = remote_profile_data_directory(&app, &profile_key); let badge_binding = notification_badge::prepare_window(&app, &label); let external_app = app.clone(); let external_label = label.clone(); @@ -1171,6 +1201,18 @@ fn open_remote_window_locked( Ok(()) } +/// A saved server's webview storage, shared by its remote window and its project tabs. +pub(crate) fn remote_profile_data_directory(app: &AppHandle, profile_key: &str) -> std::path::PathBuf { + let profile_hash = Sha256::digest(profile_key.as_bytes()) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + app.state::() + .webview_data_directory + .join("remote") + .join(profile_hash) +} + fn set_remote_window_metadata( app: &AppHandle, label: &str, @@ -1866,6 +1908,7 @@ fn main() { .plugin(tauri_plugin_notification::init()) .plugin(navigation_guard) .manage(local_windows::LocalWindows::default()) + .manage(remote_view::RemoteViews::default()) .manage(notification_badge::NotificationBadge::default()) .manage(window_constraints::WindowConstraints::default()) .manage(preferences_window::PreferencesWindow::default()) @@ -1921,6 +1964,10 @@ fn main() { .state::() .browser_controller .renderer_page_started(webview); + webview + .app_handle() + .state::() + .renderer_page_started(webview); } if identity::local_window_id(webview.label()).is_ok() && payload.event() == PageLoadEvent::Started @@ -2049,7 +2096,10 @@ fn main() { browser_target_action, browser_target_unregister, browser_target_claim_open, - browser_target_release_open + browser_target_release_open, + remote_view_open, + remote_view_update, + remote_view_close ]) .on_menu_event(|app_handle, event| { match event.id().0.as_str() { @@ -2322,6 +2372,9 @@ fn main() { .state::() .browser_controller .remove_window(&app_handle, &label); + app_handle + .state::() + .remove_window(&app_handle, &label); if let Ok(window_id) = identity::local_window_id(&label) { app_handle .state::() diff --git a/packages/tauri-app/src-tauri/src/remote_view.rs b/packages/tauri-app/src-tauri/src/remote_view.rs new file mode 100644 index 0000000000..e0a938ece3 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/remote_view.rs @@ -0,0 +1,440 @@ +//! Remote CodeNomad project tabs: a child webview per tab, inside the local +//! window that owns it, on the storage of that server's remote window. Its +//! `remote-view-*` label gives it the remote windows' capability (notifications +//! and the badge command, which refuses child webviews) and nothing local. +use serde::Deserialize; +use serde_json::json; +use std::collections::HashMap; +use std::sync::Mutex; +use tauri::{AppHandle, Emitter, Manager, PhysicalPosition, PhysicalSize, Runtime, Url}; + +pub(crate) const LABEL_PREFIX: &str = "remote-view-"; +const EMBED_PARAM: &str = "codenomadEmbed"; +const EMBED_PROJECT: &str = "project"; +const MAX_COORDINATE: i64 = 100_000; + +#[derive(Clone, Copy, Debug, Deserialize, PartialEq)] +pub(crate) struct RemoteViewBounds { + x: i32, + y: i32, + width: u32, + height: u32, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct RemoteViewOpen { + view_id: String, + profile_id: String, + base_url: String, + url: String, + bounds: RemoteViewBounds, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct RemoteViewUpdate { + view_id: String, + bounds: Option, + visible: bool, +} + +#[derive(Clone, Debug, PartialEq)] +struct Record { + owner: String, + origin: String, + /// The single-project address the view returns to; follows the project it shows. + entry: String, +} + +#[derive(Default)] +pub(crate) struct RemoteViews { + records: Mutex>, +} + +#[derive(Debug, PartialEq)] +pub(crate) enum Navigation { + Allow, + Entry, + Help, + Deny, +} + +fn validate_id(value: &str) -> Result<(), String> { + if value.is_empty() + || value.len() > 128 + || !value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_') + { + return Err("Invalid remote view id".into()); + } + Ok(()) +} + +fn validate_bounds(bounds: RemoteViewBounds) -> Result { + let valid = |value: i64, min: i64| value >= min && value <= MAX_COORDINATE; + if !valid(bounds.x.into(), 0) + || !valid(bounds.y.into(), 0) + || !valid(bounds.width.into(), 1) + || !valid(bounds.height.into(), 1) + { + return Err("Invalid remote view bounds".into()); + } + Ok(bounds) +} + +pub(crate) fn view_label(owner: &str, view_id: &str) -> Result { + validate_id(view_id)?; + Ok(format!("{LABEL_PREFIX}{owner}-{view_id}")) +} + +fn http_url(value: &str) -> Result { + let url = Url::parse(value).map_err(|error| error.to_string())?; + if !matches!(url.scheme(), "http" | "https") { + return Err("Remote view addresses must use HTTP or HTTPS".into()); + } + Ok(url) +} + +/// A view stays on its server's origin. Login and pairing pages end on the bare +/// root: that returns to the tab's single-project entry instead. +pub(crate) fn decide(url: &Url, origin: &str) -> Navigation { + if url.as_str() == "about:blank" { + return Navigation::Allow; + } + if matches!(url.scheme(), "http" | "https") && url.origin().ascii_serialization() == origin { + return if url.path() == "/" && url.query().is_none() { + Navigation::Entry + } else { + Navigation::Allow + }; + } + if crate::open_remote_external_url(url, |_| {}) { + Navigation::Help + } else { + Navigation::Deny + } +} + +fn is_embedded_entry(url: &Url) -> bool { + url.query_pairs() + .any(|(key, value)| key == EMBED_PARAM && value == EMBED_PROJECT) +} + +/// The view's own single-project address, else the server's bare entry. +pub(crate) fn entry_for(url: &Url, origin: &str) -> String { + if is_embedded_entry(url) { + url.to_string() + } else { + format!("{origin}/?{EMBED_PARAM}={EMBED_PROJECT}") + } +} + +impl RemoteViews { + fn record(&self, label: &str) -> Option { + self.records.lock().ok()?.get(label).cloned() + } + + fn owned(&self, owner: &str, view_id: &str) -> Result { + let label = view_label(owner, view_id)?; + match self.record(&label) { + Some(record) if record.owner == owner => Ok(label), + _ => Err("Remote view is no longer available".into()), + } + } + + /// A page that loads again in the owning window reopens its tabs' views. + pub(crate) fn renderer_page_started(&self, webview: &tauri::Webview) { + if webview.label() == webview.window().label() + && crate::identity::local_window_id(webview.label()).is_ok() + { + self.remove_window(webview.app_handle(), webview.label()); + } + } + + pub(crate) fn remove_window(&self, app: &AppHandle, owner: &str) { + let labels = match self.records.lock() { + Ok(mut records) => { + let labels = records + .iter() + .filter(|(_, record)| record.owner == owner) + .map(|(label, _)| label.clone()) + .collect::>(); + for label in &labels { + records.remove(label); + } + labels + } + Err(_) => return, + }; + for label in labels { + if let Some(view) = app.get_webview(&label) { + let _ = view.close(); + } + } + } + + pub(crate) fn update( + &self, + app: &AppHandle, + owner: &str, + input: RemoteViewUpdate, + ) -> Result<(), String> { + let label = self.owned(owner, &input.view_id)?; + let view = app + .get_webview(&label) + .ok_or("Remote view is no longer available")?; + if !input.visible { + return view.hide().map_err(|error| error.to_string()); + } + let bounds = validate_bounds(input.bounds.ok_or("Visible remote view bounds are required")?)?; + view.set_position(PhysicalPosition::new(bounds.x, bounds.y)) + .and_then(|()| view.set_size(PhysicalSize::new(bounds.width, bounds.height))) + .and_then(|()| view.show()) + .map_err(|error| error.to_string()) + } + + pub(crate) fn close(&self, app: &AppHandle, owner: &str, view_id: &str) -> Result<(), String> { + let Ok(label) = self.owned(owner, view_id) else { + return Ok(()); + }; + if let Ok(mut records) = self.records.lock() { + records.remove(&label); + } + if let Some(view) = app.get_webview(&label) { + view.close().map_err(|error| error.to_string())?; + } + Ok(()) + } + + #[cfg(windows)] + pub(crate) fn open( + &self, + app: &AppHandle, + window: &tauri::Window, + owner: &str, + input: RemoteViewOpen, + ) -> Result<(), String> { + use tauri::webview::{NewWindowResponse, WebviewBuilder}; + use tauri::WebviewUrl; + + let base = http_url(&input.base_url)?; + let target = http_url(&input.url)?; + let origin = base.origin().ascii_serialization(); + if target.origin().ascii_serialization() != origin { + return Err("Remote view must open on its server's origin".into()); + } + if input.profile_id.trim().is_empty() { + return Err("Remote view requires a saved server".into()); + } + let bounds = validate_bounds(input.bounds)?; + let label = view_label(owner, &input.view_id)?; + let _ = self.close(app, owner, &input.view_id); + let record = Record { + owner: owner.to_string(), + origin: origin.clone(), + entry: entry_for(&target, &origin), + }; + self.records + .lock() + .map_err(|error| error.to_string())? + .insert(label.clone(), record); + + let navigation_app = app.clone(); + let navigation_label = label.clone(); + let navigation_origin = origin.clone(); + let help_app = app.clone(); + let title_app = app.clone(); + let title_label = label.clone(); + let title_owner = owner.to_string(); + let title_view_id = input.view_id.clone(); + let builder = WebviewBuilder::new(label.clone(), WebviewUrl::External(target)) + // The remote window's storage: its sessions and paired device cookie. + .data_directory(crate::remote_profile_data_directory(app, &input.profile_id)) + .initialization_script(crate::REMOTE_WINDOW_CONTEXT_SCRIPT) + .on_navigation(move |url| match decide(url, &navigation_origin) { + Navigation::Allow => true, + Navigation::Entry => { + let app = navigation_app.clone(); + let label = navigation_label.clone(); + tauri::async_runtime::spawn(async move { + let views = app.state::(); + let Some(entry) = views.record(&label).and_then(|record| Url::parse(&record.entry).ok()) else { + return; + }; + if let Some(view) = app.get_webview(&label) { + let _ = view.navigate(entry); + } + }); + false + } + Navigation::Help => { + if let Err(error) = crate::external_open::open_url(&navigation_app, url.as_str()) { + eprintln!("[tauri] failed to open help: {error}"); + } + false + } + Navigation::Deny => false, + }) + .on_new_window(move |url, _| { + crate::open_remote_external_url(&url, |url| { + let _ = crate::external_open::open_url(&help_app, url.as_str()); + }); + NewWindowResponse::Deny + }) + .on_download(|_, _| false) + .on_document_title_changed(move |view, title| { + let Ok(url) = view.url() else { return }; + let views = title_app.state::(); + if let Ok(mut records) = views.records.lock() { + if let Some(record) = records.get_mut(&title_label) { + if url.origin().ascii_serialization() == record.origin && is_embedded_entry(&url) { + record.entry = url.to_string(); + } + } + } + let _ = title_app.emit_to( + tauri::EventTarget::webview(title_owner.clone()), + "remote-view:updated", + json!({ "viewId": title_view_id, "url": url.as_str(), "title": title }), + ); + }); + let view = match window.add_child( + builder, + PhysicalPosition::new(bounds.x, bounds.y), + PhysicalSize::new(bounds.width, bounds.height), + ) { + Ok(view) => view, + Err(error) => { + if let Ok(mut records) = self.records.lock() { + records.remove(&label); + } + return Err(format!("failed to create remote view: {error}")); + } + }; + crate::windows_browser_accelerators::bind(&view); + view.show().map_err(|error| error.to_string()) + } + + #[cfg(not(windows))] + pub(crate) fn open( + &self, + _app: &AppHandle, + _window: &tauri::Window, + _owner: &str, + _input: RemoteViewOpen, + ) -> Result<(), String> { + Err("Remote project tabs are available on Windows only".into()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const ORIGIN: &str = "https://box.example"; + + fn url(value: &str) -> Url { + Url::parse(value).unwrap() + } + + #[test] + fn remote_views_stay_on_their_server_and_return_to_their_entry() { + assert_eq!(decide(&url("https://box.example/?codenomadEmbed=project"), ORIGIN), Navigation::Allow); + assert_eq!(decide(&url("https://box.example/login"), ORIGIN), Navigation::Allow); + assert_eq!(decide(&url("https://box.example/"), ORIGIN), Navigation::Entry); + assert_eq!(decide(&url("about:blank"), ORIGIN), Navigation::Allow); + assert_eq!(decide(&url("https://evil.example/"), ORIGIN), Navigation::Deny); + assert_eq!(decide(&url("http://box.example/"), ORIGIN), Navigation::Deny); + assert_eq!(decide(&url("file:///C:/Windows"), ORIGIN), Navigation::Deny); + assert_eq!( + decide(&url("https://neuralnomadsai.github.io/CodeNomad/en/"), ORIGIN), + Navigation::Help + ); + let project = url("https://box.example/?codenomadEmbed=project&folder=%2Fsrv"); + assert_eq!(entry_for(&project, ORIGIN), project.to_string()); + assert_eq!( + entry_for(&url("https://box.example/remote-pair#code"), ORIGIN), + "https://box.example/?codenomadEmbed=project" + ); + } + + #[test] + fn remote_view_labels_and_bounds_are_validated() { + let owner = "local-11111111-1111-4111-8111-111111111111"; + let label = view_label(owner, "tab_1-a").unwrap(); + assert!(label.starts_with("remote-view-local-")); + // The remote windows' capability pattern, never a local window's. + assert!(label.starts_with("remote-")); + assert!(crate::identity::local_window_id(&label).is_err()); + assert!(view_label(owner, "../x").is_err()); + assert!(view_label(owner, "").is_err()); + assert!(validate_bounds(RemoteViewBounds { x: 0, y: 0, width: 0, height: 1 }).is_err()); + assert!(validate_bounds(RemoteViewBounds { x: -1, y: 0, width: 1, height: 1 }).is_err()); + assert!(validate_bounds(RemoteViewBounds { x: 0, y: 40, width: 800, height: 600 }).is_ok()); + } + + #[test] + fn remote_view_children_have_only_the_remote_windows_capability() { + use std::collections::BTreeMap; + use tauri::utils::acl::{capability::Capability, manifest::Manifest, resolved::Resolved}; + let manifests: BTreeMap = + serde_json::from_str(include_str!("../gen/schemas/acl-manifests.json")).unwrap(); + let capabilities: BTreeMap = + serde_json::from_str(include_str!("../gen/schemas/capabilities.json")).unwrap(); + let resolved = Resolved::resolve( + &manifests, + capabilities, + tauri::utils::platform::Target::current(), + ) + .unwrap(); + let authority = tauri::runtime_authority!(manifests, resolved); + let owner = "local-11111111-1111-4111-8111-111111111111"; + let child = view_label(owner, "tab").unwrap(); + let remote = tauri::ipc::Origin::Remote { + url: "https://box.example/?codenomadEmbed=project".parse().unwrap(), + }; + assert!(authority + .resolve_access("plugin:notification|notify", owner, &child, &remote) + .is_some()); + for command in [ + "remote_view_open", + "remote_view_update", + "remote_view_close", + "open_remote_window", + "open_external_url", + "browser_target_register", + "client_state_load", + "cli_restart", + "window_control", + "plugin:dialog|open", + "plugin:event|listen", + ] { + assert!( + authority.resolve_access(command, owner, &child, &remote).is_none(), + "remote view gained {command}" + ); + } + let local = tauri::ipc::Origin::Remote { + url: "http://127.0.0.1:32123/app".parse().unwrap(), + }; + assert!(authority + .resolve_access("remote_view_open", owner, owner, &local) + .is_some()); + } + + #[test] + fn remote_views_belong_to_their_owner_window() { + let views = RemoteViews::default(); + let owner = "local-a"; + let label = view_label(owner, "tab").unwrap(); + views.records.lock().unwrap().insert( + label.clone(), + Record { owner: owner.into(), origin: ORIGIN.into(), entry: format!("{ORIGIN}/?codenomadEmbed=project") }, + ); + assert_eq!(views.owned(owner, "tab").unwrap(), label); + assert!(views.owned("local-b", "tab").is_err()); + assert!(views.owned(owner, "other").is_err()); + } +} diff --git a/packages/ui/src/App.tsx b/packages/ui/src/App.tsx index 47e57b5468..0f88a74c50 100644 --- a/packages/ui/src/App.tsx +++ b/packages/ui/src/App.tsx @@ -18,6 +18,10 @@ import { SettingsScreen } from "./components/settings-screen" import { NativeTitlebar, hasNativeTitlebar } from "./components/native-titlebar" import { SideCarPickerDialog } from "./components/sidecar-picker-dialog" import { SideCarView } from "./components/sidecar-view" +import { RemoteProjectView } from "./components/remote-project-view" +import { EmbeddedProjectPicker } from "./components/embedded-project-picker" +import { embeddedProject, publishEmbeddedProject } from "./lib/embed-mode" +import { closeRemoteProjectTab } from "./stores/remote-project-tabs" import { InstanceMetadataProvider } from "./lib/contexts/instance-metadata-context" import { showAlertDialog } from "./stores/alerts" import { initGithubStars } from "./stores/github-stars" @@ -64,6 +68,7 @@ import { refreshVolatileInstanceState, syncLoadedSessionInboxes, syncPendingRequests, + waitForInitialWorkspaceLoad, } from "./stores/instances" import { getSessions, @@ -510,6 +515,17 @@ const App: Component = () => { useDesktopFolderLaunch(handleSelectFolder) useDesktopConnectionLaunch() + // The embedded single-project page opens its folder once workspaces are known, + // then publishes the project it shows for its host tab. + if (embeddedProject) { + const folder = embeddedProject.folder + if (folder) onMount(() => void waitForInitialWorkspaceLoad().catch(() => {}).then(() => handleSelectFolder(folder))) + createEffect(() => { + const instance = activeInstance() + if (instance && !instance.temporary) publishEmbeddedProject(instance.folder, getProjectNameForFolder(instance.folder)) + }) + } + async function handleNewTemporaryInstance(): Promise { clearLaunchError() setIsSelectingFolder(true) @@ -634,6 +650,8 @@ const App: Component = () => { if (tab.kind === "instance") { closeInstanceTab(tab.instance.id) + } else if (tab.kind === "remote-project") { + closeRemoteProjectTab(tab.remoteProjectTab.token) } else { closeSidecarTab(tab.sidecarTab.token) } @@ -766,7 +784,7 @@ const App: Component = () => {
- + @@ -786,7 +804,8 @@ const App: Component = () => { when={appTabs().length === 0} fallback={ <> - + {/* The embedded single-project page shows its project only, never the tab bar. */} + { {(tab) => { - const isVisible = () => activeAppTabId() === tab.id && !showFolderSelection() + const isVisible = () => activeAppTabId() === tab.id && (!showFolderSelection() || Boolean(embeddedProject)) return tab.kind === "instance" ? (
{ />
+ ) : tab.kind === "remote-project" ? ( +
+ +
) : (
{ } > - void handleNewTemporaryInstance()} - isLoading={isSelectingFolder() || shouldShowAppRestoreLoading(loadedRestorableSession())} - onOpenSidecar={handleOpenSidecarPicker} - /> + void handleSelectFolder(path)} /> + }> + void handleNewTemporaryInstance()} + isLoading={isSelectingFolder() || shouldShowAppRestoreLoading(loadedRestorableSession())} + onOpenSidecar={handleOpenSidecarPicker} + /> + - +
= (props) => { } const bounds = () => { if (props.active === false) return null - if (viewportMenuOpen() || document.querySelector('[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]')) return null + if (viewportMenuOpen() || localOverlayOpen()) return null const rect = element.getBoundingClientRect() const clip = frameWrapRef?.getBoundingClientRect() ?? rect const left = Math.max(rect.left, clip.left, 0) diff --git a/packages/ui/src/components/embedded-project-picker.tsx b/packages/ui/src/components/embedded-project-picker.tsx new file mode 100644 index 0000000000..27c3153144 --- /dev/null +++ b/packages/ui/src/components/embedded-project-picker.tsx @@ -0,0 +1,57 @@ +import { For, Show, type Component } from "solid-js" +import { Folder, FolderPlus } from "lucide-solid" +import { useI18n } from "../lib/i18n" +import { getDisplayPath, getProjectDisplayName } from "../lib/recent-folder-display" +import { useConfig } from "../stores/preferences" +import { createNewInstanceDialogs } from "./new-instance-dialogs" + +interface EmbeddedProjectPickerProps { + isLoading: boolean + onSelectFolder: (path: string) => void +} + +/** The embedded single-project page before it shows a project: this server's recent folders and its folder browser. */ +export const EmbeddedProjectPicker: Component = (props) => { + const { t } = useI18n() + const { recentFolders } = useConfig() + const select = (path: string) => { if (!props.isLoading) props.onSelectFolder(path) } + const dialogs = createNewInstanceDialogs({ + defaultPath: () => recentFolders()[0]?.path, + isLoading: () => props.isLoading, + onSelectFolder: select, + }) + + return ( +
+
+ + 0}> +
+
+

{t("folderSelection.recent.title")}

+
+
+ + {(folder) => ( + + )} + +
+
+
+
+ +
+ ) +} diff --git a/packages/ui/src/components/folder-selection-view.tsx b/packages/ui/src/components/folder-selection-view.tsx index 6bbcd75a74..88a8cd1203 100644 --- a/packages/ui/src/components/folder-selection-view.tsx +++ b/packages/ui/src/components/folder-selection-view.tsx @@ -1,6 +1,9 @@ import { Component, createSignal, Show, For, onMount, onCleanup, createEffect } from "solid-js" -import { Folder, Clock, Trash2, FolderPlus, Settings, ChevronRight, MonitorUp, Star, X, Globe, Loader2, GitBranch, Pencil, Hourglass } from "lucide-solid" -import { useConfig } from "../stores/preferences" +import { Folder, Clock, Trash2, FolderPlus, Settings, ChevronRight, MonitorUp, Star, X, Globe, Loader2, GitBranch, Pencil, Hourglass, Server } from "lucide-solid" +import { removeRemoteProjectRecent, useConfig } from "../stores/preferences" +import { launchableRecents, openRemoteProject } from "../stores/remote-project-open" +import { recentKey, type LaunchableRecent } from "../lib/remote-project-recents" +import RemoteProjectMenu from "./remote-project-menu" import { isHotkeyRecording, matchesHotkey, withHotkey } from "../lib/hotkeys" import ProjectRenameDialog from "./project-rename-dialog" import { useFolderDrop } from "../lib/hooks/use-folder-drop" @@ -38,10 +41,7 @@ interface FolderSelectionViewProps { } const FolderSelectionView: Component = (props) => { - const { - recentFolders, - removeRecentFolder, - } = useConfig() + const { removeRecentFolder } = useConfig() const { remoteServers, connectingServerId, saveServer, connectSavedServer, removeRemoteServerProfile } = useRemoteServerProfiles() const { t } = useI18n() const [selectedIndex, setSelectedIndex] = createSignal(0) @@ -55,7 +55,8 @@ const FolderSelectionView: Component = (props) => { let actionsColumnRef: HTMLDivElement | undefined let recentListRef: HTMLDivElement | undefined - const folders = () => recentFolders() + // This computer's folders and the remote projects this window reopens, newest first. + const folders = () => launchableRecents() const serverList = () => remoteServers() const isLoading = () => Boolean(props.isLoading) const canUseRemoteServerWindows = () => canOpenRemoteWindows() @@ -168,9 +169,7 @@ const FolderSelectionView: Component = (props) => { if (activeTab() === "local") { const folder = folders()[index] - if (folder) { - handleFolderSelect(folder.path) - } + if (folder) openRecent(folder) return } @@ -262,6 +261,12 @@ const FolderSelectionView: Component = (props) => { props.onSelectFolder(path) } + function openRecent(folder: LaunchableRecent) { + if (isLoading()) return + if (folder.remote) openRemoteProject(folder.remote.profileId, { folder: folder.path }) + else handleFolderSelect(folder.path) + } + function handleExistingInstanceSelect(instanceId: string, recentPath: string) { if (isLoading()) return props.onSelectExistingInstance(instanceId, recentPath) @@ -281,7 +286,7 @@ const FolderSelectionView: Component = (props) => { } const dialogs = createNewInstanceDialogs({ - defaultPath: () => folders()[0]?.path, + defaultPath: () => folders().find((folder) => !folder.remote)?.path, isLoading, onSelectFolder: handleFolderSelect, onSaveServer: saveServer, @@ -299,10 +304,11 @@ const FolderSelectionView: Component = (props) => { await dialogs.browse() } - function handleRemove(path: string, e?: Event) { + function handleRemove(folder: LaunchableRecent, e?: Event) { if (isLoading()) return e?.stopPropagation() - removeRecentFolder(path) + if (folder.remote) removeRemoteProjectRecent(folder.remote.profileId, folder.path) + else removeRecentFolder(folder.path) const folderList = folders() if (selectedIndex() >= folderList.length && folderList.length > 0) { @@ -607,7 +613,9 @@ const FolderSelectionView: Component = (props) => { > {(folder, index) => { - const existingInstance = () => getExistingInstanceForFolder(folder.path) + const key = recentKey(folder) + // A remote project reopens its tab from the row itself. + const existingInstance = () => folder.remote ? undefined : getExistingInstanceForFolder(folder.path) const projectName = () => getProjectDisplayName(folder.path, folder.projectName) const projectLabelId = () => `recent-folder-${index()}-name` const openActionLabelId = () => `recent-folder-${index()}-open-action` @@ -618,8 +626,9 @@ const FolderSelectionView: Component = (props) => { "panel-list-item-highlight": focusMode() === "recent" && selectedIndex() === index(), "panel-list-item-disabled": isLoading(), "folder-home-recent-item-action-active": - hoveredRecentActionPath() === folder.path || focusedRecentActionPath() === folder.path, + hoveredRecentActionPath() === key || focusedRecentActionPath() === key, }} + data-remote-server={folder.remote?.profileId} onMouseEnter={() => { if (isLoading()) return setFocusMode("recent") @@ -634,7 +643,7 @@ const FolderSelectionView: Component = (props) => { class="folder-home-recent-primary-action" disabled={isLoading()} aria-labelledby={projectLabelId()} - onClick={() => handleFolderSelect(folder.path)} + onClick={() => openRecent(folder)} onFocus={() => { setFocusMode("recent") setSelectedIndex(index()) @@ -643,7 +652,9 @@ const FolderSelectionView: Component = (props) => {
- + }> + + {projectName()} @@ -652,8 +663,8 @@ const FolderSelectionView: Component = (props) => { let ownsHoverState = false let ownsFocusState = false onCleanup(() => { - if (ownsHoverState) setRecentActionHovered(folder.path, false) - if (ownsFocusState) setRecentActionFocused(folder.path, false) + if (ownsHoverState) setRecentActionHovered(key, false) + if (ownsFocusState) setRecentActionFocused(key, false) }) return (
+ + {(remote) => {remote().serverName}} + {getDisplayPath(folder.path)} @@ -695,30 +709,33 @@ const FolderSelectionView: Component = (props) => {
- + {/* A remote project is renamed on its server. */} + + + @@ -806,6 +823,8 @@ const FolderSelectionView: Component = (props) => {
+ +
{/* OpenCode settings section */} diff --git a/packages/ui/src/components/instance-tabs.tsx b/packages/ui/src/components/instance-tabs.tsx index c6f8268f02..a73fba4f6d 100644 --- a/packages/ui/src/components/instance-tabs.tsx +++ b/packages/ui/src/components/instance-tabs.tsx @@ -15,7 +15,8 @@ import AppActions from "./app-actions" import { appActionsInTitlebar } from "./native-titlebar" import ProjectRenameDialog from "./project-rename-dialog" import { renameProject } from "../stores/project-names" -import { Plus } from "lucide-solid" +import { Plus, Server } from "lucide-solid" +import { remoteProjectTabLabel } from "../stores/remote-project-open" import { withHotkey } from "../lib/hotkeys" import { createLongPressHandlers } from "../lib/long-press" import { useI18n } from "../lib/i18n" @@ -43,6 +44,9 @@ interface SortableAppTabProps { const AppTabContent: Component = (props) => { const { t } = useI18n() + const label = () => props.tab.kind === "sidecar" + ? props.tab.sidecarTab.name + : props.tab.kind === "remote-project" ? remoteProjectTabLabel(props.tab.remoteProjectTab) : "" return ( <> {props.tab.kind === "instance" ? ( @@ -66,8 +70,11 @@ const AppTabContent: Component = (props) => { props.onSelect(props.tab.id) }} > - - {props.tab.sidecarTab.name} + + + + {label()}
+ diff --git a/packages/ui/src/components/remote-project-menu.tsx b/packages/ui/src/components/remote-project-menu.tsx new file mode 100644 index 0000000000..003ab9cae2 --- /dev/null +++ b/packages/ui/src/components/remote-project-menu.tsx @@ -0,0 +1,156 @@ +import { ContextMenu } from "@kobalte/core/context-menu" +import { For, Show, createSignal } from "solid-js" +import { ChevronRight, Loader2, Plus, Server, Trash2 } from "lucide-solid" +import type { RemoteServerProfile } from "../../../server/src/api-types" +import { useI18n } from "../lib/i18n" +import { classifyCodeNomadLink, codeNomadLinkName } from "../lib/codenomad-link" +import { useRemoteServerProfiles } from "../lib/hooks/use-remote-server-profiles" +import { canOpenRemoteWindows } from "../lib/runtime-env" +import { showConfirmDialog } from "../stores/alerts" +import { openRemoteProject, opensRemoteProjectTab } from "../stores/remote-project-open" + +interface RemoteProjectMenuProps { + isLoading: boolean + /** Called once a server opened, e.g. to dismiss the launcher. */ + onOpened?: () => void +} + +/** + * Remotes: the saved CodeNomad servers. A server opens a project tab whose view + * picks the folder; a pasted pairing link or address adds one. Only host windows + * (never a web client, a Remote Control device or a remote page) list or manage them. + */ +export default function RemoteProjectMenu(props: RemoteProjectMenuProps) { + const { t } = useI18n() + const { remoteServers, saveProfile, saveServer, connectSavedServer, markRemoteServerConnected, removeRemoteServerProfile } = useRemoteServerProfiles() + const [expanded, setExpanded] = createSignal(false) + const [busy, setBusy] = createSignal(false) + const [address, setAddress] = createSignal("") + const [addError, setAddError] = createSignal() + let toggleRef: HTMLButtonElement | undefined + let bodyRef: HTMLDivElement | undefined + + const navItems = () => [...(bodyRef?.querySelectorAll("[data-remote-nav]") ?? [])].filter((item) => !item.hasAttribute("disabled")) + const focusFirst = () => queueMicrotask(() => navItems()[0]?.focus()) + + function open(profile: RemoteServerProfile, entryUrl?: string) { + if (opensRemoteProjectTab(profile)) { + openRemoteProject(profile.id, entryUrl ? { entryUrl } : {}) + void markRemoteServerConnected(profile.id).catch(() => {}) + } else { + void connectSavedServer(profile.id) + } + props.onOpened?.() + } + + async function add(text: string) { + const value = text.trim() + if (!value || busy()) return + setAddError(undefined) + const link = classifyCodeNomadLink(value) + if (!link) return setAddError(t("folderSelection.servers.dialog.errorConnect")) + const existing = remoteServers().find((server) => server.baseUrl === link.baseUrl) + const input = { id: existing?.id, name: existing?.name ?? codeNomadLinkName(link.baseUrl), baseUrl: value, skipTlsVerify: false } + setBusy(true) + try { + if (opensRemoteProjectTab(input)) { + const { profile, entryUrl } = await saveProfile(input) + open(profile, entryUrl) + } else { + // Without tabs, a pairing link still pairs in the server's own window. + await saveServer(input, link.kind === "pairing") + props.onOpened?.() + } + setAddress("") + } catch (error) { + setAddError(error instanceof Error && error.message ? error.message : t("folderSelection.servers.dialog.errorConnect")) + } finally { + setBusy(false) + } + } + + async function remove(profile: RemoteServerProfile) { + const confirmed = await showConfirmDialog(t("folderSelection.remoteProject.removeConfirm", { name: profile.name }), { + title: t("folderSelection.servers.remove"), + variant: "warning", + confirmLabel: t("folderSelection.servers.remove"), + }) + if (!confirmed) return + removeRemoteServerProfile(profile.id) + } + + function handleKeyDown(event: KeyboardEvent) { + if (event.defaultPrevented || event.isComposing) return + const items = navItems() + const index = items.indexOf(document.activeElement as HTMLElement) + const move = (next: number) => { event.preventDefault(); items[(next + items.length) % items.length]?.focus() } + if (event.key === "ArrowDown") move(index + 1) + else if (event.key === "ArrowUp") move(index - 1) + else if (event.key === "Escape") { + event.preventDefault() + setExpanded(false) + toggleRef?.focus() + } + } + + return ( + + + +
+ + {(profile) => ( + // Removal lives in the row's context menu (right-click, Shift+F10, Menu key). + + open(profile)} + aria-label={t("folderSelection.remoteProject.openProject", { name: profile.name })}> + + + + void remove(profile)}> + + {t("folderSelection.servers.remove")} + + + + + )} + +
{ event.preventDefault(); void add(address()) }}> + { setAddress(event.currentTarget.value); setAddError(undefined) }} + onPaste={(event) => { + const text = event.clipboardData?.getData("text") ?? "" + if (!classifyCodeNomadLink(text)) return + event.preventDefault() + setAddress(text.trim()) + void add(text) + }} /> + +
+ {(message) => } +
+
+
+ ) +} diff --git a/packages/ui/src/components/remote-project-view.tsx b/packages/ui/src/components/remote-project-view.tsx new file mode 100644 index 0000000000..49da3ce629 --- /dev/null +++ b/packages/ui/src/components/remote-project-view.tsx @@ -0,0 +1,127 @@ +import { Show, createEffect, createSignal, onCleanup, onMount, type Component } from "solid-js" +import { useI18n } from "../lib/i18n" +import { embeddedProjectUrl, readEmbeddedProjectReport } from "../lib/embed-mode" +import { localOverlayOpen } from "../lib/native/browser" +import { closeRemoteView, onRemoteViewUpdated, openRemoteView, updateRemoteView } from "../lib/native/remote-view" +import { getLogger } from "../lib/logger" +import { recordRemoteProjectRecent, remoteServers } from "../stores/preferences" +import { patchRemoteProjectTab, type RemoteProjectTabRecord } from "../stores/remote-project-tabs" + +const log = getLogger("actions") + +interface RemoteProjectViewProps { + tab: RemoteProjectTabRecord + /** The tab is the one on screen. */ + active: boolean +} + +/** + * Holds the place of the native view showing the remote page. The view opens the + * first time its tab shows, follows this element's bounds and hides whenever the + * tab is not shown or a local dialog or menu would lie under it. + */ +export const RemoteProjectView: Component = (props) => { + const { t } = useI18n() + const [error, setError] = createSignal() + let element!: HTMLDivElement + + onMount(() => { + const token = props.tab.token + const profileId = props.tab.profileId + let disposed = false + let opened = false + let pending = false + let failed = false + let lastBounds = "" + let unlisten = () => {} + + const fail = (cause: unknown) => { + failed = true + pending = false + log.warn("Remote project view failed", { profileId, cause }) + if (!disposed) setError(cause instanceof Error ? cause.message : String(cause)) + } + + const visibleRect = (): DOMRect | null => { + if (!props.active || localOverlayOpen()) return null + const rect = element.getBoundingClientRect() + return rect.width >= 1 && rect.height >= 1 ? rect : null + } + + const sync = () => { + if (disposed || pending || failed) return + const rect = visibleRect() + const key = rect ? [rect.x, rect.y, rect.width, rect.height].map(Math.round).join(",") : "" + if (!opened) { + if (!rect) return + const profile = remoteServers().find((entry) => entry.id === profileId) + if (!profile) return fail(new Error(t("folderSelection.remoteProject.serverMissing"))) + pending = true + const origin = new URL(profile.baseUrl).origin + void onRemoteViewUpdated((update) => { + if (update.viewId !== token) return + const report = readEmbeddedProjectReport(update.url, update.title, origin) + if (!report) return + patchRemoteProjectTab(token, report) + recordRemoteProjectRecent({ profileId, folder: report.folder, projectName: report.title }) + }).then(async (stop) => { + if (disposed) return stop() + unlisten = stop + await openRemoteView({ + viewId: token, + profileId, + baseUrl: profile.baseUrl, + url: props.tab.entryUrl ?? embeddedProjectUrl(profile.baseUrl, props.tab.folder), + }, rect) + opened = true + lastBounds = key + pending = false + // A pairing code is single-use: a later reopen loads the project entry. + patchRemoteProjectTab(token, { entryUrl: undefined }) + if (disposed) void closeRemoteView(token).catch(() => {}) + else sync() + }).catch(fail) + return + } + if (key === lastBounds) return + lastBounds = key + pending = true + void updateRemoteView(token, rect).then(() => { + pending = false + sync() + }).catch(fail) + } + + const resizeObserver = new ResizeObserver(sync) + const overlayObserver = new MutationObserver(sync) + resizeObserver.observe(element) + overlayObserver.observe(document.body, { attributes: true, childList: true, subtree: true }) + window.addEventListener("resize", sync) + createEffect(() => { + void props.active + sync() + }) + queueMicrotask(sync) + + onCleanup(() => { + disposed = true + resizeObserver.disconnect() + overlayObserver.disconnect() + window.removeEventListener("resize", sync) + unlisten() + if (opened) void closeRemoteView(token).catch((cause) => log.warn("Failed to close remote project view", { cause })) + }) + }) + + return ( +
+ + {(message) => ( + + )} + +
+ ) +} diff --git a/packages/ui/src/lib/codenomad-link.test.ts b/packages/ui/src/lib/codenomad-link.test.ts new file mode 100644 index 0000000000..e45e09b822 --- /dev/null +++ b/packages/ui/src/lib/codenomad-link.test.ts @@ -0,0 +1,32 @@ +import assert from "node:assert/strict" +import { describe, it } from "node:test" +import { classifyCodeNomadLink, codeNomadLinkName } from "./codenomad-link.ts" + +describe("pasted CodeNomad links", () => { + it("recognizes a Remote Control pairing link and keeps its code out of the saved address", () => { + assert.deepEqual(classifyCodeNomadLink(" https://abc.opentunnel.xyz/remote-pair#code-123 "), { + kind: "pairing", + baseUrl: "https://abc.opentunnel.xyz", + entryUrl: "https://abc.opentunnel.xyz/remote-pair#code-123", + }) + }) + + it("reduces a direct-access address to its origin", () => { + assert.deepEqual(classifyCodeNomadLink("http://192.168.1.20:9898/some/page?x=1"), { kind: "address", baseUrl: "http://192.168.1.20:9898" }) + assert.deepEqual(classifyCodeNomadLink("https://box.example"), { kind: "address", baseUrl: "https://box.example" }) + }) + + it("refuses text, other schemes and links carrying credentials", () => { + assert.equal(classifyCodeNomadLink("my server"), null) + assert.equal(classifyCodeNomadLink("ftp://box.example"), null) + assert.equal(classifyCodeNomadLink("http://user:secret@box.example:4096"), null) + assert.equal(classifyCodeNomadLink("http://user@box.example"), null) + // An http pairing page is not a Remote Control link: it is probed as an address. + assert.deepEqual(classifyCodeNomadLink("http://box.example/remote-pair#x"), { kind: "address", baseUrl: "http://box.example" }) + }) + + it("names a new server after its host", () => { + assert.equal(codeNomadLinkName("https://abc.opentunnel.xyz"), "abc.opentunnel.xyz") + assert.equal(codeNomadLinkName("http://127.0.0.1:9898"), "127.0.0.1:9898") + }) +}) diff --git a/packages/ui/src/lib/codenomad-link.ts b/packages/ui/src/lib/codenomad-link.ts new file mode 100644 index 0000000000..641c4a5bda --- /dev/null +++ b/packages/ui/src/lib/codenomad-link.ts @@ -0,0 +1,33 @@ +import { splitPairingLink } from "./remote-pairing-link" + +/** + * A pasted CodeNomad link: a Remote Control pairing link, or a server address + * (direct access) for the existing probe. Links carrying credentials are refused: + * nothing secret is ever saved with a server. + */ +export type CodeNomadLink = + | { kind: "pairing"; baseUrl: string; entryUrl: string } + | { kind: "address"; baseUrl: string } + +export function classifyCodeNomadLink(input: string): CodeNomadLink | null { + const text = input.trim() + const pairing = splitPairingLink(text) + if (pairing) return { kind: "pairing", ...pairing } + let url: URL + try { + url = new URL(text) + } catch { + return null + } + if ((url.protocol !== "http:" && url.protocol !== "https:") || url.username || url.password) return null + return { kind: "address", baseUrl: url.origin } +} + +/** A server's display name before it reports one: its host. */ +export function codeNomadLinkName(baseUrl: string): string { + try { + return new URL(baseUrl).host + } catch { + return baseUrl + } +} diff --git a/packages/ui/src/lib/embed-mode.test.ts b/packages/ui/src/lib/embed-mode.test.ts new file mode 100644 index 0000000000..9b84f5fc66 --- /dev/null +++ b/packages/ui/src/lib/embed-mode.test.ts @@ -0,0 +1,35 @@ +import assert from "node:assert/strict" +import { describe, it } from "node:test" +import { embeddedProjectUrl, readEmbeddedProject, readEmbeddedProjectReport } from "./embed-mode.ts" + +describe("embedded single-project mode", () => { + it("is selected only by its exact parameter and keeps a bounded folder", () => { + assert.equal(readEmbeddedProject(""), null) + assert.equal(readEmbeddedProject("?codenomadEmbed=full"), null) + assert.equal(readEmbeddedProject("?embed=project"), null) + assert.deepEqual(readEmbeddedProject("?codenomadEmbed=project"), {}) + assert.deepEqual(readEmbeddedProject("?codenomadEmbed=project&folder=%2Fsrv%2Fapp"), { folder: "/srv/app" }) + assert.deepEqual(readEmbeddedProject("?codenomadEmbed=project&folder=%20%20"), {}) + assert.deepEqual(readEmbeddedProject(`?codenomadEmbed=project&folder=${"a".repeat(4097)}`), {}) + }) + + it("builds the entry at the server root, dropping any path, query or fragment", () => { + assert.equal(embeddedProjectUrl("https://box.example:8443/old/path?x=1#y"), "https://box.example:8443/?codenomadEmbed=project") + const withFolder = new URL(embeddedProjectUrl("http://127.0.0.1:9900", "C:\\work\\app & co")) + assert.equal(withFolder.origin, "http://127.0.0.1:9900") + assert.deepEqual(readEmbeddedProject(withFolder.search), { folder: "C:\\work\\app & co" }) + }) + + it("lets a host accept only a same-origin report that names a folder", () => { + const origin = "https://box.example" + const entry = embeddedProjectUrl(origin, "/srv/app") + assert.deepEqual(readEmbeddedProjectReport(entry, " App ", origin), { folder: "/srv/app", title: "App" }) + // An older server keeps the bare entry: its own title never relabels the tab. + assert.equal(readEmbeddedProjectReport(embeddedProjectUrl(origin), "CodeNomad", origin), null) + assert.equal(readEmbeddedProjectReport(entry, "App", "https://other.example"), null) + assert.equal(readEmbeddedProjectReport(entry, " ", origin), null) + assert.equal(readEmbeddedProjectReport("not a url", "App", origin), null) + assert.equal(readEmbeddedProjectReport(`${origin}/?folder=%2Fsrv`, "App", origin), null) + assert.equal(readEmbeddedProjectReport(entry, "x".repeat(400), origin)?.title.length, 256) + }) +}) diff --git a/packages/ui/src/lib/embed-mode.ts b/packages/ui/src/lib/embed-mode.ts new file mode 100644 index 0000000000..a52cab9299 --- /dev/null +++ b/packages/ui/src/lib/embed-mode.ts @@ -0,0 +1,80 @@ +/** + * The single-project view a desktop host shows in a remote CodeNomad project tab. + * The host loads `/?codenomadEmbed=project[&folder=…]`; the embedded page keeps + * the folder it shows in its address and the project name in its document title. + * A server that does not know the parameter shows its full interface instead. + */ +export const EMBED_PARAM = "codenomadEmbed" +export const EMBED_PROJECT = "project" +export const EMBED_FOLDER_PARAM = "folder" +const MAX_FOLDER_LENGTH = 4096 +const MAX_TITLE_LENGTH = 256 + +export interface EmbeddedProjectTarget { + folder?: string +} + +function readFolder(params: URLSearchParams): string | undefined { + const folder = params.get(EMBED_FOLDER_PARAM)?.trim() + return folder && folder.length <= MAX_FOLDER_LENGTH ? folder : undefined +} + +export function readEmbeddedProject(search: string): EmbeddedProjectTarget | null { + const params = new URLSearchParams(search) + if (params.get(EMBED_PARAM) !== EMBED_PROJECT) return null + const folder = readFolder(params) + return folder ? { folder } : {} +} + +/** Read once: the embedded page never leaves this mode. */ +export const embeddedProject: EmbeddedProjectTarget | null = + typeof window === "undefined" ? null : readEmbeddedProject(window.location.search) + +export const isEmbeddedProjectView = () => embeddedProject !== null + +/** The entry the host loads for a server, at its root. */ +export function embeddedProjectUrl(baseUrl: string, folder?: string): string { + const url = new URL(baseUrl) + url.pathname = "/" + url.search = "" + url.hash = "" + url.searchParams.set(EMBED_PARAM, EMBED_PROJECT) + if (folder) url.searchParams.set(EMBED_FOLDER_PARAM, folder) + return url.toString() +} + +/** The embedded page records what it shows; replacing the entry keeps history and reloads on this project. */ +export function publishEmbeddedProject(folder: string, title: string): void { + if (typeof window === "undefined") return + const url = new URL(window.location.href) + if (url.searchParams.get(EMBED_FOLDER_PARAM) !== folder) { + url.searchParams.set(EMBED_PARAM, EMBED_PROJECT) + url.searchParams.set(EMBED_FOLDER_PARAM, folder) + window.history.replaceState(window.history.state, "", url) + } + // The host reads the address when the title changes: set it last. + document.title = title +} + +export interface EmbeddedProjectReport { + folder: string + title: string +} + +/** + * What a host accepts from an embedded page's title change: only an address on + * the server's origin that names a folder. An older server keeps the bare entry + * address, so its own title (its brand) never relabels the tab. + */ +export function readEmbeddedProjectReport(url: string, title: string, origin: string): EmbeddedProjectReport | null { + let parsed: URL + try { + parsed = new URL(url) + } catch { + return null + } + if (parsed.origin !== origin || parsed.searchParams.get(EMBED_PARAM) !== EMBED_PROJECT) return null + const folder = readFolder(parsed.searchParams) + const name = title.trim().slice(0, MAX_TITLE_LENGTH) + return folder && name ? { folder, title: name } : null +} diff --git a/packages/ui/src/lib/hooks/use-app-session-capture.ts b/packages/ui/src/lib/hooks/use-app-session-capture.ts index ce85d0b641..83bc96ea6d 100644 --- a/packages/ui/src/lib/hooks/use-app-session-capture.ts +++ b/packages/ui/src/lib/hooks/use-app-session-capture.ts @@ -80,6 +80,10 @@ function captureState(scrollAuthority: ReadonlyMap>) } const restorableTabs: RestorableTabState[] = tabs.map((tab) => { if (tab.kind === "sidecar") return { kind: "sidecar", sidecarId: tab.sidecarTab.sidecarId } + if (tab.kind === "remote-project") { + const { profileId, folder } = tab.remoteProjectTab + return { kind: "remote-project", profileId, ...(folder ? { folder } : {}) } + } const id = tab.instance.id const parentId = activeParentSessionId().get(id) const sessionId = activeSessionId().get(id) diff --git a/packages/ui/src/lib/hooks/use-app-session-restore.ts b/packages/ui/src/lib/hooks/use-app-session-restore.ts index 002ab48b7e..0c8dbf4dd7 100644 --- a/packages/ui/src/lib/hooks/use-app-session-restore.ts +++ b/packages/ui/src/lib/hooks/use-app-session-restore.ts @@ -14,8 +14,11 @@ import { import { getAbortReason, runAbortable } from "../../stores/app-session-restore-timeout" import { activeAppTabId, appTabs, appTabOrderRevision, appTabSelectionRevision, attachInstanceTab, getInstanceAppTabId, - getSidecarAppTabId, selectAppTab, setAppTabOrder, + getRemoteProjectAppTabId, getSidecarAppTabId, selectAppTab, setAppTabOrder, } from "../../stores/app-tabs" +import { openRemoteProjectTab } from "../../stores/remote-project-tabs" +import { opensRemoteProjectTab } from "../../stores/remote-project-open" +import { remoteServers, waitForConfigLoad } from "../../stores/preferences" import { createInstance, releaseRestoreCreatedInstance, instances, waitForInitialWorkspaceLoad, waitForInstanceInitialSessionHydration, @@ -69,7 +72,9 @@ function hasLocalRestoredTab(capture: AppSessionCaptureController, index: number const waitForWorkspaceMountAdoption = () => new Promise((resolve) => setTimeout(resolve, 0)) async function restoreTabs(context: RestoreContext, retryIndexes?: ReadonlyMap boolean>): Promise { const { snapshot, signal, capture } = context - const sidecars = retryIndexes ? [] : snapshot.tabs.map((tab, index) => tab.kind === "sidecar" ? restoreSidecar(tab, index) : undefined) + const sidecars = retryIndexes ? [] : snapshot.tabs.map((tab, index) => tab.kind === "sidecar" + ? restoreSidecar(tab, index) + : tab.kind === "remote-project" ? restoreRemoteProject(tab, index) : undefined) try { await runAbortable(async (operationSignal) => { await waitForInitialWorkspaceLoad(operationSignal) @@ -201,6 +206,23 @@ async function restoreTabs(context: RestoreContext, retryIndexes?: ReadonlyMap, + index: number) { + if (signal.aborted) return + await waitForConfigLoad() + const profile = remoteServers().find((entry) => entry.id === tab.profileId) + if (signal.aborted) return + if (!profile || !opensRemoteProjectTab(profile)) { + capture.recordRestoredTab(index, null, new Set()) + return + } + const opened = openRemoteProjectTab(profile.id, tab.folder ? { folder: tab.folder } : {}) + const tabId = getRemoteProjectAppTabId(opened.token) + capture.recordRestoredTab(index, tabId, new Set()) + if (index === snapshot.activeTabIndex) context.selectActive(tabId, true) + } const restoreMissing = () => runWithSerializedCommits( [...missing].sort((a, b) => Number(b.tabIndex === snapshot.activeTabIndex) - Number(a.tabIndex === snapshot.activeTabIndex) || a.tabIndex - b.tabIndex), (match, waitForCommit, finishCommit) => restoreWorkspace(match, waitForCommit, finishCommit), diff --git a/packages/ui/src/lib/hooks/use-remote-server-profiles.ts b/packages/ui/src/lib/hooks/use-remote-server-profiles.ts index e7ab885c94..3921e1a50a 100644 --- a/packages/ui/src/lib/hooks/use-remote-server-profiles.ts +++ b/packages/ui/src/lib/hooks/use-remote-server-profiles.ts @@ -6,6 +6,7 @@ import { splitPairingLink } from "../remote-pairing-link" import { canOpenRemoteWindows, isTauriHost } from "../runtime-env" import { showAlertDialog } from "../../stores/alerts" import { useConfig } from "../../stores/preferences" +import { closeRemoteProjectTabsForServer } from "../../stores/remote-project-tabs" export type RemoteServerInput = { id?: string @@ -19,14 +20,9 @@ export function useRemoteServerProfiles() { const { remoteServers, saveRemoteServerProfile, markRemoteServerConnected, removeRemoteServerProfile } = useConfig() const [connectingServerId, setConnectingServerId] = createSignal(null) - const saveServer = async (input: RemoteServerInput, requestedWindow: boolean, windowOptions: RemoteWindowOpenOptions = {}) => { - // A Remote Control pairing code is consumed by the window that opens it, so a pairing link opens one where possible. + /** Probes and saves a server; a pairing link's single-use entry is returned, never saved. */ + const saveProfile = async (input: RemoteServerInput) => { const pairing = splitPairingLink(input.baseUrl) - const openWindow = requestedWindow || (pairing !== null && canOpenRemoteWindows()) - if (openWindow && !canOpenRemoteWindows()) { - throw new Error("Remote server windows can only be opened from a local desktop window") - } - const name = input.name.trim() const baseUrl = pairing?.baseUrl ?? input.baseUrl.trim() if (!name || !baseUrl) throw new Error(t("folderSelection.servers.dialog.errorRequired")) @@ -44,6 +40,18 @@ export function useRemoteServerProfiles() { baseUrl: probe.normalizedUrl, skipTlsVerify, }) + return { profile, entryUrl: pairing?.entryUrl } + } + + const saveServer = async (input: RemoteServerInput, requestedWindow: boolean, windowOptions: RemoteWindowOpenOptions = {}) => { + // A Remote Control pairing code is consumed by the window that opens it, so a pairing link opens one where possible. + const pairing = splitPairingLink(input.baseUrl) + const openWindow = requestedWindow || (pairing !== null && canOpenRemoteWindows()) + if (openWindow && !canOpenRemoteWindows()) { + throw new Error("Remote server windows can only be opened from a local desktop window") + } + + const { profile } = await saveProfile(input) if (openWindow) { const proxySession = @@ -81,5 +89,11 @@ export function useRemoteServerProfiles() { } } - return { remoteServers, connectingServerId, saveServer, connectSavedServer, removeRemoteServerProfile } + // A removed server's project tabs close with it. + const removeServer = (id: string) => { + closeRemoteProjectTabsForServer(id) + removeRemoteServerProfile(id) + } + + return { remoteServers, connectingServerId, saveProfile, saveServer, connectSavedServer, markRemoteServerConnected, removeRemoteServerProfile: removeServer } } diff --git a/packages/ui/src/lib/i18n/messages/de/folderSelection.ts b/packages/ui/src/lib/i18n/messages/de/folderSelection.ts index 1ce3889788..3219fc9051 100644 --- a/packages/ui/src/lib/i18n/messages/de/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/de/folderSelection.ts @@ -120,4 +120,11 @@ export const folderSelectionMessages = { "projectRenameDialog.actions.cancel": "Abbrechen", "projectRenameDialog.actions.rename": "Umbenennen", "projectRenameDialog.actions.renaming": "Umbenennung läuft...", + "folderSelection.remoteProject.title": "Remote", + "folderSelection.remoteProject.project": "Projekt", + "folderSelection.remoteProject.openProject": "Projekt auf {name} öffnen", + "folderSelection.remoteProject.add": "Server hinzufügen", + "folderSelection.remoteProject.addPlaceholder": "Kopplungslink oder Adresse", + "folderSelection.remoteProject.removeConfirm": "{name} entfernen?", + "folderSelection.remoteProject.serverMissing": "Server nicht gefunden", } as const diff --git a/packages/ui/src/lib/i18n/messages/en/folderSelection.ts b/packages/ui/src/lib/i18n/messages/en/folderSelection.ts index 8689a59383..3ecd628e76 100644 --- a/packages/ui/src/lib/i18n/messages/en/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/en/folderSelection.ts @@ -120,4 +120,11 @@ export const folderSelectionMessages = { "projectRenameDialog.actions.cancel": "Cancel", "projectRenameDialog.actions.rename": "Rename", "projectRenameDialog.actions.renaming": "Renaming...", + "folderSelection.remoteProject.title": "Remotes", + "folderSelection.remoteProject.project": "Project", + "folderSelection.remoteProject.openProject": "Open a project on {name}", + "folderSelection.remoteProject.add": "Add server", + "folderSelection.remoteProject.addPlaceholder": "Pairing link or address", + "folderSelection.remoteProject.removeConfirm": "Remove {name}?", + "folderSelection.remoteProject.serverMissing": "Server not found", } as const diff --git a/packages/ui/src/lib/i18n/messages/es/folderSelection.ts b/packages/ui/src/lib/i18n/messages/es/folderSelection.ts index ca35fdf723..6612a5f9c9 100644 --- a/packages/ui/src/lib/i18n/messages/es/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/es/folderSelection.ts @@ -120,4 +120,11 @@ export const folderSelectionMessages = { "projectRenameDialog.actions.cancel": "Cancelar", "projectRenameDialog.actions.rename": "Renombrar", "projectRenameDialog.actions.renaming": "Renombrando...", + "folderSelection.remoteProject.title": "Remotos", + "folderSelection.remoteProject.project": "Proyecto", + "folderSelection.remoteProject.openProject": "Abrir un proyecto en {name}", + "folderSelection.remoteProject.add": "Añadir servidor", + "folderSelection.remoteProject.addPlaceholder": "Enlace de emparejamiento o dirección", + "folderSelection.remoteProject.removeConfirm": "¿Quitar {name}?", + "folderSelection.remoteProject.serverMissing": "Servidor no encontrado", } as const diff --git a/packages/ui/src/lib/i18n/messages/fr/folderSelection.ts b/packages/ui/src/lib/i18n/messages/fr/folderSelection.ts index 77d1df387f..c023a3fbfb 100644 --- a/packages/ui/src/lib/i18n/messages/fr/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/fr/folderSelection.ts @@ -120,4 +120,11 @@ export const folderSelectionMessages = { "projectRenameDialog.actions.cancel": "Annuler", "projectRenameDialog.actions.rename": "Renommer", "projectRenameDialog.actions.renaming": "Renommage...", + "folderSelection.remoteProject.title": "Distants", + "folderSelection.remoteProject.project": "Projet", + "folderSelection.remoteProject.openProject": "Ouvrir un projet sur {name}", + "folderSelection.remoteProject.add": "Ajouter un serveur", + "folderSelection.remoteProject.addPlaceholder": "Lien d'appairage ou adresse", + "folderSelection.remoteProject.removeConfirm": "Retirer {name} ?", + "folderSelection.remoteProject.serverMissing": "Serveur introuvable", } as const diff --git a/packages/ui/src/lib/i18n/messages/he/folderSelection.ts b/packages/ui/src/lib/i18n/messages/he/folderSelection.ts index 1c3b945a01..76998c848f 100644 --- a/packages/ui/src/lib/i18n/messages/he/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/he/folderSelection.ts @@ -120,4 +120,11 @@ export const folderSelectionMessages = { "projectRenameDialog.actions.cancel": "ביטול", "projectRenameDialog.actions.rename": "שנה שם", "projectRenameDialog.actions.renaming": "משנה שם...", + "folderSelection.remoteProject.title": "מרוחקים", + "folderSelection.remoteProject.project": "פרויקט", + "folderSelection.remoteProject.openProject": "פתיחת פרויקט בשרת {name}", + "folderSelection.remoteProject.add": "הוספת שרת", + "folderSelection.remoteProject.addPlaceholder": "קישור צימוד או כתובת", + "folderSelection.remoteProject.removeConfirm": "להסיר את {name}?", + "folderSelection.remoteProject.serverMissing": "השרת לא נמצא", } as const diff --git a/packages/ui/src/lib/i18n/messages/ja/folderSelection.ts b/packages/ui/src/lib/i18n/messages/ja/folderSelection.ts index 6405c7e06d..bb7f5856c3 100644 --- a/packages/ui/src/lib/i18n/messages/ja/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/ja/folderSelection.ts @@ -120,4 +120,11 @@ export const folderSelectionMessages = { "projectRenameDialog.actions.cancel": "キャンセル", "projectRenameDialog.actions.rename": "名前を変更", "projectRenameDialog.actions.renaming": "変更中...", + "folderSelection.remoteProject.title": "リモート", + "folderSelection.remoteProject.project": "プロジェクト", + "folderSelection.remoteProject.openProject": "{name} でプロジェクトを開く", + "folderSelection.remoteProject.add": "サーバーを追加", + "folderSelection.remoteProject.addPlaceholder": "ペアリングリンクまたはアドレス", + "folderSelection.remoteProject.removeConfirm": "{name} を削除しますか?", + "folderSelection.remoteProject.serverMissing": "サーバーが見つかりません", } as const diff --git a/packages/ui/src/lib/i18n/messages/ne/folderSelection.ts b/packages/ui/src/lib/i18n/messages/ne/folderSelection.ts index c9501b307b..3a76170b7f 100644 --- a/packages/ui/src/lib/i18n/messages/ne/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/ne/folderSelection.ts @@ -120,4 +120,11 @@ export const folderSelectionMessages = { "projectRenameDialog.actions.cancel": "रद्द गर्नुहोस्", "projectRenameDialog.actions.rename": "पुन: नामकरण गर्नुहोस्", "projectRenameDialog.actions.renaming": "पुन: नामकरण गर्दै...", + "folderSelection.remoteProject.title": "रिमोटहरू", + "folderSelection.remoteProject.project": "परियोजना", + "folderSelection.remoteProject.openProject": "{name} मा परियोजना खोल्नुहोस्", + "folderSelection.remoteProject.add": "सर्भर थप्नुहोस्", + "folderSelection.remoteProject.addPlaceholder": "पेयरिङ लिङ्क वा ठेगाना", + "folderSelection.remoteProject.removeConfirm": "{name} हटाउने?", + "folderSelection.remoteProject.serverMissing": "सर्भर फेला परेन", } as const diff --git a/packages/ui/src/lib/i18n/messages/ru/folderSelection.ts b/packages/ui/src/lib/i18n/messages/ru/folderSelection.ts index e8efbae8ba..3686031308 100644 --- a/packages/ui/src/lib/i18n/messages/ru/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/ru/folderSelection.ts @@ -120,4 +120,11 @@ export const folderSelectionMessages = { "projectRenameDialog.actions.cancel": "Отмена", "projectRenameDialog.actions.rename": "Переименовать", "projectRenameDialog.actions.renaming": "Переименование...", + "folderSelection.remoteProject.title": "Удалённые", + "folderSelection.remoteProject.project": "Проект", + "folderSelection.remoteProject.openProject": "Открыть проект на {name}", + "folderSelection.remoteProject.add": "Добавить сервер", + "folderSelection.remoteProject.addPlaceholder": "Ссылка для сопряжения или адрес", + "folderSelection.remoteProject.removeConfirm": "Удалить {name}?", + "folderSelection.remoteProject.serverMissing": "Сервер не найден", } as const diff --git a/packages/ui/src/lib/i18n/messages/tr/folderSelection.ts b/packages/ui/src/lib/i18n/messages/tr/folderSelection.ts index e0f54999ee..cb9a6bf174 100644 --- a/packages/ui/src/lib/i18n/messages/tr/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/tr/folderSelection.ts @@ -108,4 +108,11 @@ export const folderSelectionMessages = { "projectRenameDialog.actions.cancel": "İptal", "projectRenameDialog.actions.rename": "Yeniden adlandır", "projectRenameDialog.actions.renaming": "Yeniden adlandırılıyor...", + "folderSelection.remoteProject.title": "Uzaklar", + "folderSelection.remoteProject.project": "Proje", + "folderSelection.remoteProject.openProject": "{name} üzerinde proje aç", + "folderSelection.remoteProject.add": "Sunucu ekle", + "folderSelection.remoteProject.addPlaceholder": "Eşleştirme bağlantısı veya adres", + "folderSelection.remoteProject.removeConfirm": "{name} kaldırılsın mı?", + "folderSelection.remoteProject.serverMissing": "Sunucu bulunamadı", } as const diff --git a/packages/ui/src/lib/i18n/messages/zh-Hans/folderSelection.ts b/packages/ui/src/lib/i18n/messages/zh-Hans/folderSelection.ts index 9104b280f9..ac967eca74 100644 --- a/packages/ui/src/lib/i18n/messages/zh-Hans/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/zh-Hans/folderSelection.ts @@ -120,4 +120,11 @@ export const folderSelectionMessages = { "projectRenameDialog.actions.cancel": "取消", "projectRenameDialog.actions.rename": "重命名", "projectRenameDialog.actions.renaming": "正在重命名...", + "folderSelection.remoteProject.title": "远程", + "folderSelection.remoteProject.project": "项目", + "folderSelection.remoteProject.openProject": "在 {name} 上打开项目", + "folderSelection.remoteProject.add": "添加服务器", + "folderSelection.remoteProject.addPlaceholder": "配对链接或地址", + "folderSelection.remoteProject.removeConfirm": "移除 {name}?", + "folderSelection.remoteProject.serverMissing": "找不到服务器", } as const diff --git a/packages/ui/src/lib/native/browser.ts b/packages/ui/src/lib/native/browser.ts index e82f1743e1..7e3558c144 100644 --- a/packages/ui/src/lib/native/browser.ts +++ b/packages/ui/src/lib/native/browser.ts @@ -30,6 +30,11 @@ export function nativeBrowserHost( return undefined } +/** Native views sit above the page: they hide while a local dialog, menu or list is open. */ +export function localOverlayOpen(root: ParentNode = document): boolean { + return Boolean(root.querySelector('[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]')) +} + export function physicalBrowserBounds(rect: Pick, scale: number): BrowserTargetBounds { return { x: Math.round(rect.x * scale), diff --git a/packages/ui/src/lib/native/remote-view.ts b/packages/ui/src/lib/native/remote-view.ts new file mode 100644 index 0000000000..6c18df41fe --- /dev/null +++ b/packages/ui/src/lib/native/remote-view.ts @@ -0,0 +1,66 @@ +import { invoke } from "@tauri-apps/api/core" +import { listen } from "@tauri-apps/api/event" +import { detectRuntimeEnvironment, type RuntimeEnvironment } from "../runtime-env" +import { isEmbeddedProjectView } from "../embed-mode" +import { nativeBrowserHost, physicalBrowserBounds, type BrowserTargetBounds } from "./browser" + +/** + * A remote CodeNomad page shown inside a local window's tab, with the storage of + * that server's remote window and the remote windows' native access only. + */ +export interface RemoteViewOpenPayload { + viewId: string + profileId: string + baseUrl: string + url: string +} + +export interface RemoteViewUpdate { + viewId: string + url: string + title: string +} + +/** + * Local desktop windows host remote project tabs (Electron; Tauri on Windows, as + * browser previews). Never the web host, a Remote Control device, a remote window + * or an embedded page: a remote tab never opens another server. + */ +export function remoteViewHost( + environment: Pick = detectRuntimeEnvironment(), + userAgent?: string, +): "electron" | "tauri" | undefined { + if (isEmbeddedProjectView()) return undefined + return nativeBrowserHost(environment, userAgent) +} + +export const canOpenRemoteProjectTabs = () => remoteViewHost() !== undefined + +/** Electron places views in window coordinates (DIP); Tauri in physical pixels. */ +function viewBounds(rect: Pick): BrowserTargetBounds { + if (remoteViewHost() === "tauri") return physicalBrowserBounds(rect, window.devicePixelRatio) + return physicalBrowserBounds(rect, 1) +} + +export async function openRemoteView(payload: RemoteViewOpenPayload, rect: DOMRect): Promise { + const bounds = viewBounds(rect) + if (remoteViewHost() === "electron") return window.electronAPI!.openRemoteView!({ ...payload, bounds }) + await invoke("remote_view_open", { payload: { ...payload, bounds } }) +} + +/** Without `rect` the view is hidden. */ +export async function updateRemoteView(viewId: string, rect: DOMRect | null): Promise { + const bounds = rect ? viewBounds(rect) : undefined + if (remoteViewHost() === "electron") return window.electronAPI!.updateRemoteView!({ viewId, bounds, visible: Boolean(rect) }) + await invoke("remote_view_update", { payload: { viewId, bounds, visible: Boolean(rect) } }) +} + +export async function closeRemoteView(viewId: string): Promise { + if (remoteViewHost() === "electron") return window.electronAPI!.closeRemoteView!(viewId) + await invoke("remote_view_close", { viewId }) +} + +export async function onRemoteViewUpdated(callback: (update: RemoteViewUpdate) => void): Promise<() => void> { + if (remoteViewHost() === "electron") return window.electronAPI!.onRemoteViewUpdated!(callback) + return listen("remote-view:updated", (event) => callback(event.payload)) +} diff --git a/packages/ui/src/lib/notification-icon-badge.ts b/packages/ui/src/lib/notification-icon-badge.ts index 85e74de94a..7b5a98b894 100644 --- a/packages/ui/src/lib/notification-icon-badge.ts +++ b/packages/ui/src/lib/notification-icon-badge.ts @@ -1,6 +1,7 @@ import iconUrl from "../images/CodeNomad-Icon.png" import { getUnreadToastCount, subscribeToastHistory } from "./notifications" import { setNativeNotificationBadge } from "./native/notification-badge" +import { isEmbeddedProjectView } from "./embed-mode" /** Follow the bell's in-memory history, not session status or OS notifications. */ export function startNotificationIconBadge(): () => void { @@ -59,6 +60,8 @@ export function startNotificationIconBadge(): () => void { if (stopped || next === count) return count = next paint() + // A page inside a host's tab has no icon of its own: its host keeps the badge. + if (isEmbeddedProjectView()) return void setNativeNotificationBadge(count).catch(error => { console.warn("[notifications] native icon badge unavailable", error) }) @@ -74,6 +77,6 @@ export function startNotificationIconBadge(): () => void { image.onload = null restore() if (!originals.length) links[0].remove() - void setNativeNotificationBadge(0).catch(() => {}) + if (!isEmbeddedProjectView()) void setNativeNotificationBadge(0).catch(() => {}) } } diff --git a/packages/ui/src/lib/remote-project-recents.test.ts b/packages/ui/src/lib/remote-project-recents.test.ts new file mode 100644 index 0000000000..17eb603810 --- /dev/null +++ b/packages/ui/src/lib/remote-project-recents.test.ts @@ -0,0 +1,70 @@ +import assert from "node:assert/strict" +import { describe, it } from "node:test" +import { + MAX_REMOTE_PROJECT_RECENTS, + mixRecents, + normalizeRemoteProjectRecents, + recentKey, + withoutRemoteProjectRecent, + withRemoteProjectRecent, +} from "./remote-project-recents.ts" + +describe("remote project recents", () => { + it("normalizes saved entries: valid, distinct, bounded and newest first", () => { + const saved = [ + { profileId: "a", folder: "/one", lastAccessed: 1 }, + { profileId: "a", folder: "/one", lastAccessed: 9 }, + { profileId: "b", folder: "/two", projectName: " Two ", lastAccessed: 5 }, + { profileId: "", folder: "/x" }, + { profileId: "c" }, + "junk", + { profileId: "c", folder: "/three", password: "never kept" }, + ] + assert.deepEqual(normalizeRemoteProjectRecents(saved), [ + { profileId: "b", folder: "/two", projectName: "Two", lastAccessed: 5 }, + { profileId: "a", folder: "/one", lastAccessed: 1 }, + { profileId: "c", folder: "/three", lastAccessed: 0 }, + ]) + assert.deepEqual(normalizeRemoteProjectRecents({}), []) + const many = Array.from({ length: 30 }, (_, index) => ({ profileId: "a", folder: `/${index}`, lastAccessed: index })) + assert.equal(normalizeRemoteProjectRecents(many).length, MAX_REMOTE_PROJECT_RECENTS) + }) + + it("moves a reopened project first and keeps its known name", () => { + const list = [ + { profileId: "a", folder: "/one", projectName: "One", lastAccessed: 1 }, + { profileId: "a", folder: "/two", lastAccessed: 2 }, + ] + assert.deepEqual(withRemoteProjectRecent(list, { profileId: "a", folder: "/one" }, 10), [ + { profileId: "a", folder: "/one", projectName: "One", lastAccessed: 10 }, + { profileId: "a", folder: "/two", lastAccessed: 2 }, + ]) + }) + + it("forgets one project, or every project of a removed server", () => { + const list = [ + { profileId: "a", folder: "/one", lastAccessed: 1 }, + { profileId: "a", folder: "/two", lastAccessed: 2 }, + { profileId: "b", folder: "/one", lastAccessed: 3 }, + ] + assert.deepEqual(withoutRemoteProjectRecent(list, "a", "/one").map(recentFolder), ["a:/two", "b:/one"]) + assert.deepEqual(withoutRemoteProjectRecent(list, "a").map(recentFolder), ["b:/one"]) + }) + + it("mixes this computer's folders with projects of saved servers only, newest first", () => { + const local = [{ path: "/local", lastAccessed: 5 }, { path: "/older", lastAccessed: 1 }] + const remote = [ + { profileId: "box", folder: "/srv", projectName: "Srv", lastAccessed: 3 }, + { profileId: "gone", folder: "/lost", lastAccessed: 9 }, + ] + const mixed = mixRecents(local, remote, [{ id: "box", name: "Box" }]) + assert.deepEqual(mixed.map((entry) => entry.path), ["/local", "/srv", "/older"]) + assert.deepEqual(mixed[1].remote, { profileId: "box", serverName: "Box" }) + assert.notEqual(recentKey({ path: "/srv" }), recentKey(mixed[1])) + assert.deepEqual(mixRecents(local, [], []), local) + }) +}) + +function recentFolder(entry: { profileId: string; folder: string }) { + return `${entry.profileId}:${entry.folder}` +} diff --git a/packages/ui/src/lib/remote-project-recents.ts b/packages/ui/src/lib/remote-project-recents.ts new file mode 100644 index 0000000000..70a8db285d --- /dev/null +++ b/packages/ui/src/lib/remote-project-recents.ts @@ -0,0 +1,95 @@ +/** + * Projects opened in remote CodeNomad tabs, kept by this host beside its own + * recent folders: a saved server, a folder on it and its name, no secret. + */ +export interface RemoteProjectRecent { + profileId: string + folder: string + projectName?: string + lastAccessed: number +} + +export const MAX_REMOTE_PROJECT_RECENTS = 20 +const MAX_TEXT = 4096 + +const text = (value: unknown, max = MAX_TEXT): string | undefined => + typeof value === "string" && value.trim() && value.length <= max ? value.trim() : undefined + +export function normalizeRemoteProjectRecents(value: unknown): RemoteProjectRecent[] { + if (!Array.isArray(value)) return [] + const seen = new Set() + const result: RemoteProjectRecent[] = [] + for (const entry of value) { + if (!entry || typeof entry !== "object") continue + const record = entry as Record + const profileId = text(record.profileId, 256) + const folder = text(record.folder) + if (!profileId || !folder) continue + const key = `${profileId}\0${folder}` + if (seen.has(key)) continue + seen.add(key) + const projectName = text(record.projectName, 256) + result.push({ + profileId, + folder, + ...(projectName ? { projectName } : {}), + lastAccessed: typeof record.lastAccessed === "number" && Number.isFinite(record.lastAccessed) ? record.lastAccessed : 0, + }) + if (result.length >= MAX_REMOTE_PROJECT_RECENTS) break + } + return result.sort((left, right) => right.lastAccessed - left.lastAccessed) +} + +export function withRemoteProjectRecent( + list: readonly RemoteProjectRecent[], + entry: Omit, + now = Date.now(), +): RemoteProjectRecent[] { + const rest = list.filter((item) => item.profileId !== entry.profileId || item.folder !== entry.folder) + const previous = list.find((item) => item.profileId === entry.profileId && item.folder === entry.folder) + const projectName = entry.projectName ?? previous?.projectName + return [{ profileId: entry.profileId, folder: entry.folder, ...(projectName ? { projectName } : {}), lastAccessed: now }, ...rest] + .slice(0, MAX_REMOTE_PROJECT_RECENTS) +} + +export interface LaunchableRecent { + path: string + lastAccessed: number + projectName?: string + /** A project on a saved remote server; absent for this computer's folders. */ + remote?: { profileId: string; serverName: string } +} + +/** One recent list, newest first: local folders, then remote projects of servers still saved. */ +export function mixRecents( + local: ReadonlyArray<{ path: string; lastAccessed: number; projectName?: string }>, + remote: readonly RemoteProjectRecent[], + servers: ReadonlyArray<{ id: string; name: string }>, +): LaunchableRecent[] { + const names = new Map(servers.map((server) => [server.id, server.name])) + const remoteItems: LaunchableRecent[] = remote.flatMap((entry) => { + const serverName = names.get(entry.profileId) + if (!serverName) return [] + return [{ + path: entry.folder, + lastAccessed: entry.lastAccessed, + ...(entry.projectName ? { projectName: entry.projectName } : {}), + remote: { profileId: entry.profileId, serverName }, + }] + }) + if (!remoteItems.length) return [...local] + return [...local, ...remoteItems].sort((left, right) => right.lastAccessed - left.lastAccessed) +} + +/** Distinct keys for a local folder and the same path on a server. */ +export const recentKey = (recent: Pick) => + recent.remote ? `${recent.remote.profileId}\0${recent.path}` : recent.path + +/** Without `folder`, forgets every project of that server. */ +export function withoutRemoteProjectRecent( + list: readonly RemoteProjectRecent[], + profileId: string, + folder?: string, +): RemoteProjectRecent[] { + return list.filter((item) => item.profileId !== profileId || (folder !== undefined && item.folder !== folder)) +} diff --git a/packages/ui/src/stores/app-session-snapshot-merge.ts b/packages/ui/src/stores/app-session-snapshot-merge.ts index d864225774..98afc22870 100644 --- a/packages/ui/src/stores/app-session-snapshot-merge.ts +++ b/packages/ui/src/stores/app-session-snapshot-merge.ts @@ -36,7 +36,7 @@ function mapTabIdentities(tabs: readonly RestorableTabState[]): TabIdentity[] { return tabs.map((tab) => { const key = tab.kind === "workspace" ? `workspace:${normalizeWorkspacePath(tab.folder)}` - : `sidecar:${tab.sidecarId}` + : tab.kind === "remote-project" ? `remote-project:${tab.profileId}:${tab.folder ?? ""}` : `sidecar:${tab.sidecarId}` const inferred = nextOccurrences.get(key) ?? 0 const occurrence = tab.kind === "workspace" ? tab.occurrence ?? inferred : inferred nextOccurrences.set(key, Math.max(inferred, occurrence) + 1) diff --git a/packages/ui/src/stores/app-tabs.test.ts b/packages/ui/src/stores/app-tabs.test.ts index cf37142e33..d2cb27754a 100644 --- a/packages/ui/src/stores/app-tabs.test.ts +++ b/packages/ui/src/stores/app-tabs.test.ts @@ -60,9 +60,9 @@ function workspace(folder: string): RestorableWorkspaceTabState { } function captureTabs(): RestorableSessionState { - const tabs = appTabs().map((tab) => tab.kind === "instance" - ? workspace(tab.instance.folder) - : { kind: "sidecar" as const, sidecarId: tab.sidecarTab.sidecarId }) + const tabs = appTabs().flatMap((tab): RestorableSessionState["tabs"] => tab.kind === "instance" + ? [workspace(tab.instance.folder)] + : tab.kind === "sidecar" ? [{ kind: "sidecar", sidecarId: tab.sidecarTab.sidecarId }] : []) return { tabs, activeTabIndex: appTabs().findIndex((tab) => tab.id === activeAppTabId()) } } diff --git a/packages/ui/src/stores/app-tabs.ts b/packages/ui/src/stores/app-tabs.ts index b91f5a84d1..0eadfdc88f 100644 --- a/packages/ui/src/stores/app-tabs.ts +++ b/packages/ui/src/stores/app-tabs.ts @@ -2,6 +2,12 @@ import { createMemo, createSignal } from "solid-js" import type { Instance } from "../types/instance" import { activeInstanceId, claimRestoreCreatedInstanceForUser, closeWorkspace, instances, setActiveInstanceId } from "./instances" import { activeSidecarToken, setActiveSidecarToken, sidecarTabs, type SideCarTabRecord } from "./sidecars" +import { + activeRemoteProjectToken, + remoteProjectTabs, + setActiveRemoteProjectToken, + type RemoteProjectTabRecord, +} from "./remote-project-tabs" import { appSessionRestoreGateActive } from "./app-session-restore-gate" import { attachInstanceTabMembership, @@ -24,7 +30,13 @@ export interface SideCarAppTab { sidecarTab: SideCarTabRecord } -export type AppTabRecord = InstanceAppTab | SideCarAppTab +export interface RemoteProjectAppTab { + id: string + kind: "remote-project" + remoteProjectTab: RemoteProjectTabRecord +} + +export type AppTabRecord = InstanceAppTab | SideCarAppTab | RemoteProjectAppTab function getInstanceAppTabId(instanceId: string): string { return `instance:${instanceId}` @@ -34,6 +46,10 @@ function getSidecarAppTabId(token: string): string { return `sidecar:${token}` } +function getRemoteProjectAppTabId(token: string): string { + return `remote-project:${token}` +} + function getAdjacentAppTabId(tabId: string): string | null { const tabs = appTabs() const index = tabs.findIndex((tab) => tab.id === tabId) @@ -47,6 +63,9 @@ function getPreferredTabId(): string | null { return getSidecarAppTabId(sidecarToken) } + const remoteToken = activeRemoteProjectToken() + if (remoteToken) return getRemoteProjectAppTabId(remoteToken) + const instanceId = activeInstanceId() if (instanceId) { return getInstanceAppTabId(instanceId) @@ -81,6 +100,11 @@ const appTabs = createMemo((previous = []) => { kind: "sidecar" as const, get sidecarTab() { return sidecarTabs().find((tab) => tab.token === sidecarTab.token) ?? sidecarTab }, })), + ...remoteProjectTabs().map((remoteTab) => previousById.get(getRemoteProjectAppTabId(remoteTab.token)) ?? ({ + id: getRemoteProjectAppTabId(remoteTab.token), + kind: "remote-project" as const, + get remoteProjectTab() { return remoteProjectTabs().find((tab) => tab.token === remoteTab.token) ?? remoteTab }, + })), ] const tabsById = new Map(currentTabs.map((tab) => [tab.id, tab])) @@ -103,6 +127,7 @@ function selectAppTab(tabId: string | null, options?: { source?: "restore" }) { setActiveAppTabId(null) setActiveInstanceId(null) setActiveSidecarToken(null) + setActiveRemoteProjectToken(null) return } @@ -120,14 +145,25 @@ function selectAppTab(tabId: string | null, options?: { source?: "restore" }) { if (tab.kind === "instance") { if (options?.source !== "restore") claimRestoreCreatedInstanceForUser(tab.instance.id) setActiveSidecarToken(null) + setActiveRemoteProjectToken(null) setActiveInstanceId(tab.instance.id) return } setActiveInstanceId(null) + if (tab.kind === "remote-project") { + setActiveSidecarToken(null) + setActiveRemoteProjectToken(tab.remoteProjectTab.token) + return + } + setActiveRemoteProjectToken(null) setActiveSidecarToken(tab.sidecarTab.token) } +function selectRemoteProjectTab(token: string) { + selectAppTab(getRemoteProjectAppTabId(token)) +} + function selectInstanceTab(instanceId: string) { if (!instances().has(instanceId)) return attachInstanceTab(instanceId) @@ -277,6 +313,7 @@ export { getAdjacentAppTabId, getAppTabById, getInstanceAppTabId, + getRemoteProjectAppTabId, getSidecarAppTabId, markAppTabUserInteraction, moveAppTab, @@ -286,5 +323,6 @@ export { selectInstanceTab, selectNextAppTab, selectPreviousAppTab, + selectRemoteProjectTab, selectSidecarTab, } diff --git a/packages/ui/src/stores/client-state-codec.ts b/packages/ui/src/stores/client-state-codec.ts index 5118e594f7..f2e735d1f0 100644 --- a/packages/ui/src/stores/client-state-codec.ts +++ b/packages/ui/src/stores/client-state-codec.ts @@ -17,7 +17,9 @@ export interface RestorableWorkspaceTabState { } export interface RestorableSidecarTabState { kind: "sidecar"; sidecarId: string } -export type RestorableTabState = RestorableWorkspaceTabState | RestorableSidecarTabState +/** A remote CodeNomad project tab: its saved server and the folder its page last showed. */ +export interface RestorableRemoteProjectTabState { kind: "remote-project"; profileId: string; folder?: string } +export type RestorableTabState = RestorableWorkspaceTabState | RestorableSidecarTabState | RestorableRemoteProjectTabState export interface RestorableSessionState { tabs: RestorableTabState[]; activeTabIndex: number; homeActive?: boolean } export interface ClientSnapshotV1 { version: 1; revision: number; savedAt: number @@ -215,7 +217,7 @@ interface WorkspaceIdentity { prioritySessionIds: string[]; priorityDrafts: Record priorityAttachments: Record } -type TabIdentity = WorkspaceIdentity | RestorableSidecarTabState +type TabIdentity = WorkspaceIdentity | RestorableSidecarTabState | RestorableRemoteProjectTabState function normalizeIdentity(value: unknown, budget: StringBudget): TabIdentity | null { if (!isRecord(value)) return null @@ -224,6 +226,12 @@ function normalizeIdentity(value: unknown, budget: StringBudget): TabIdentity | const sidecarId = takeString(value.sidecarId, MAX_ID, budget) return sidecarId === undefined ? null : { kind, sidecarId } } + if (kind === "remote-project") { + const profileId = takeString(value.profileId, MAX_ID, budget) + if (profileId === undefined) return null + const folder = value.folder === undefined ? undefined : takeString(value.folder, MAX_PATH, budget) + return { kind, profileId, ...(folder === undefined ? {} : { folder }) } + } if (kind !== "workspace" && kind !== "instance") return null if (!["drafts", "attachments", "scrollSnapshots", "unseenIdleSince", "generationRecovery"] .every((key) => isRecord(value[key] ?? {}))) return null @@ -287,7 +295,7 @@ function normalizeSession(value: unknown, budget: StringBudget): RestorableSessi const normalizeTabAt = (originalIndex: number, prioritizeDrafts: boolean) => { const identity = identityByIndex.get(originalIndex) if (!identity) return - const tab = identity.kind === "sidecar" + const tab = identity.kind !== "workspace" ? identity : normalizeWorkspaceTab(identity.value, identity, budget, prioritizeDrafts) if (tab) normalizedByIndex.set(originalIndex, tab) diff --git a/packages/ui/src/stores/client-state-partitions.ts b/packages/ui/src/stores/client-state-partitions.ts index 61b8ae23d5..3115724839 100644 --- a/packages/ui/src/stores/client-state-partitions.ts +++ b/packages/ui/src/stores/client-state-partitions.ts @@ -127,6 +127,7 @@ async function encodeSessionGraph(session: RestorableSessionState | null) { const encodedSession = session === null ? null : { tabs: await Promise.all(session.tabs.map(async (tab) => { if (tab.kind === "sidecar") return { kind: tab.kind, sidecarId: tab.sidecarId } + if (tab.kind === "remote-project") return { kind: tab.kind, profileId: tab.profileId, ...(tab.folder ? { folder: tab.folder } : {}) } const sessionIds = new Set([ ...Object.keys(tab.drafts), @@ -368,6 +369,11 @@ async function decodeGraph( tabs.push({ kind: shell.kind, sidecarId: shell.sidecarId }) continue } + if (shell.kind === "remote-project") { + if (!hasExactKeys(shell, ["kind", "profileId"], ["folder"])) return + tabs.push({ kind: shell.kind, profileId: shell.profileId, ...(hasOwn(shell, "folder") ? { folder: shell.folder } : {}) }) + continue + } if (shell.kind !== "workspace" || !hasExactKeys(shell, ["kind", "folder", "workspacePartition"], ["occurrence", "projectName", "binaryPath"])) return if (typeof shell.workspacePartition !== "string" || !PARTITION_KEY.test(shell.workspacePartition)) return diff --git a/packages/ui/src/stores/preferences.tsx b/packages/ui/src/stores/preferences.tsx index 5fe7455967..b205b910bd 100644 --- a/packages/ui/src/stores/preferences.tsx +++ b/packages/ui/src/stores/preferences.tsx @@ -2,6 +2,12 @@ import { createContext, createMemo, createSignal, onMount, useContext } from "so import type { Accessor, ParentComponent } from "solid-js" import { storage, ConfigOwnerReconciliationPendingError, type OwnerBucket } from "../lib/storage" import type { RemoteServerProfile, UpdateFeed } from "../../../server/src/api-types" +import { + normalizeRemoteProjectRecents, + withoutRemoteProjectRecent, + withRemoteProjectRecent, + type RemoteProjectRecent, +} from "../lib/remote-project-recents" import { ensureInstanceConfigLoaded, getInstanceConfig, @@ -196,6 +202,7 @@ interface UiStateBucket { lastCloneParent?: string opencodeBinaries?: OpenCodeBinary[] remoteServers?: RemoteServerProfile[] + remoteProjectRecents?: unknown models?: { recents?: ModelPreference[] favorites?: ModelPreference[] @@ -209,6 +216,7 @@ interface NormalizedUiState { lastCloneParent?: string opencodeBinaries: OpenCodeBinary[] remoteServers: RemoteServerProfile[] + remoteProjectRecents: RemoteProjectRecent[] models: { recents: ModelPreference[] favorites: ModelPreference[] @@ -510,6 +518,7 @@ function normalizeUiState(input?: UiStateBucket | null): NormalizedUiState { const right = b.lastConnectedAt ?? b.updatedAt return right.localeCompare(left) }), + remoteProjectRecents: normalizeRemoteProjectRecents(source.remoteProjectRecents), models: { recents: cloneArray((source.models as any)?.recents, (m) => { if (!m || typeof m !== "object") return null @@ -688,6 +697,7 @@ const preferences = uiSettings const recentFolders = createMemo(() => uiState().recentFolders) const opencodeBinaries = createMemo(() => uiState().opencodeBinaries) const remoteServers = createMemo(() => uiState().remoteServers) +const remoteProjectRecents = createMemo(() => uiState().remoteProjectRecents) let loadPromise: Promise | null = null @@ -1163,7 +1173,20 @@ async function markRemoteServerConnected(id: string): Promise { function removeRemoteServerProfile(id: string): void { const next = remoteServers().filter((entry) => entry.id !== id) - void patchStateOwner("ui", { remoteServers: next }).catch((error) => log.error("Failed to remove remote server", error)) + void patchStateOwner("ui", { + remoteServers: next, + remoteProjectRecents: withoutRemoteProjectRecent(remoteProjectRecents(), id), + }).catch((error) => log.error("Failed to remove remote server", error)) +} + +function recordRemoteProjectRecent(entry: Omit): void { + void patchStateOwner("ui", { remoteProjectRecents: withRemoteProjectRecent(remoteProjectRecents(), entry) }) + .catch((error) => log.error("Failed to record remote project", error)) +} + +function removeRemoteProjectRecent(profileId: string, folder: string): void { + void patchStateOwner("ui", { remoteProjectRecents: withoutRemoteProjectRecent(remoteProjectRecents(), profileId, folder) }) + .catch((error) => log.error("Failed to remove remote project", error)) } function recordWorkspaceLaunch(folderPath: string, aliasPath?: string): void { @@ -1563,6 +1586,11 @@ export { rememberCloneParent, serverSettings, recentFolders, + ensureLoaded as waitForConfigLoad, + remoteServers, + remoteProjectRecents, + recordRemoteProjectRecent, + removeRemoteProjectRecent, opencodeBinaries, themePreference, setThemePreference, diff --git a/packages/ui/src/stores/remote-project-open.ts b/packages/ui/src/stores/remote-project-open.ts new file mode 100644 index 0000000000..33c913d575 --- /dev/null +++ b/packages/ui/src/stores/remote-project-open.ts @@ -0,0 +1,34 @@ +import type { RemoteServerProfile } from "../../../server/src/api-types" +import { canOpenRemoteProjectTabs } from "../lib/native/remote-view" +import { mixRecents, type LaunchableRecent } from "../lib/remote-project-recents" +import { selectRemoteProjectTab } from "./app-tabs" +import { recentFolders, remoteProjectRecents, remoteServers } from "./preferences" +import { openRemoteProjectTab, remoteProjectTabs, type RemoteProjectTabRecord } from "./remote-project-tabs" +import { setShowFolderSelection } from "./ui" + +/** A server opens in a tab unless its certificate is unverified: that one keeps its separate window. */ +export const opensRemoteProjectTab = (profile: Pick) => + !profile.skipTlsVerify && canOpenRemoteProjectTabs() + +export function openRemoteProject(profileId: string, options: { folder?: string; entryUrl?: string } = {}): void { + const tab = openRemoteProjectTab(profileId, options) + selectRemoteProjectTab(tab.token) + setShowFolderSelection(false) +} + +/** This computer's recent folders with the remote projects this window can reopen. */ +export function launchableRecents(): LaunchableRecent[] { + if (!canOpenRemoteProjectTabs()) return recentFolders() + return mixRecents(recentFolders(), remoteProjectRecents(), remoteServers().filter(opensRemoteProjectTab)) +} + +/** The project name the embedded page reported, else its server's name. */ +export function remoteProjectTabLabel(tab: Pick): string { + return tab.title ?? remoteServers().find((server) => server.id === tab.profileId)?.name ?? tab.profileId +} + +export function openRemoteProjectTabFor(recent: LaunchableRecent): string | undefined { + const remote = recent.remote + if (!remote) return undefined + return remoteProjectTabs().find((tab) => tab.profileId === remote.profileId && tab.folder === recent.path)?.token +} diff --git a/packages/ui/src/stores/remote-project-tabs.test.ts b/packages/ui/src/stores/remote-project-tabs.test.ts new file mode 100644 index 0000000000..4057c48810 --- /dev/null +++ b/packages/ui/src/stores/remote-project-tabs.test.ts @@ -0,0 +1,86 @@ +import assert from "node:assert/strict" +import { describe, it } from "node:test" +import { decodeClientSnapshot, normalizeRestorableSession, type ClientSnapshotV1 } from "./client-state-codec.ts" +import { decodeClientSnapshotV2, encodeClientSnapshotV2 } from "./client-state-partitions.ts" +import { activeAppTabId, appTabs, selectAppTab, selectRemoteProjectTab } from "./app-tabs.ts" +import { releaseAppSessionRestoreGate } from "./app-session-restore-gate.ts" +import { + activeRemoteProjectToken, + closeRemoteProjectTab, + closeRemoteProjectTabsForServer, + openRemoteProjectTab, + patchRemoteProjectTab, + remoteProjectTabs, +} from "./remote-project-tabs.ts" +import { remoteViewHost } from "../lib/native/remote-view.ts" + +const snapshot = (tabs: unknown[]): ClientSnapshotV1 => ({ + version: 1, revision: 1, savedAt: 1, layout: {}, + session: { tabs, activeTabIndex: 0 } as ClientSnapshotV1["session"], +}) + +describe("remote project tabs", () => { + it("restore as their server and folder, nothing else", () => { + const normalized = normalizeRestorableSession({ + activeTabIndex: 0, + tabs: [ + { kind: "remote-project", profileId: "box", folder: "/srv/app", entryUrl: "https://t.example/remote-pair#code" }, + { kind: "remote-project", profileId: "box" }, + { kind: "remote-project", folder: "/no-server" }, + ], + }) + assert.deepEqual(normalized?.tabs, [ + { kind: "remote-project", profileId: "box", folder: "/srv/app" }, + { kind: "remote-project", profileId: "box" }, + ]) + assert.deepEqual(decodeClientSnapshot(snapshot([{ kind: "remote-project", profileId: "box" }]))?.session?.tabs, + [{ kind: "remote-project", profileId: "box" }]) + }) + + it("survive the partitioned native snapshot", async () => { + const source = snapshot([ + { kind: "remote-project", profileId: "box", folder: "/srv/app" }, + { kind: "remote-project", profileId: "other" }, + ]) + const encoded = await encodeClientSnapshotV2(source) + const decoded = await decodeClientSnapshotV2(encoded.root, 1, async (key) => encoded.partitions[key] ?? null) + assert.deepEqual(decoded?.session?.tabs, source.session?.tabs) + }) + + it("join the tab bar, reuse a tab for the same project and close with their server", () => { + releaseAppSessionRestoreGate() + const first = openRemoteProjectTab("box", { folder: "/srv/app" }) + assert.equal(openRemoteProjectTab("box", { folder: "/srv/app" }).token, first.token) + const picker = openRemoteProjectTab("box") + const pairing = openRemoteProjectTab("box", { entryUrl: "https://t.example/remote-pair#code" }) + assert.notEqual(picker.token, pairing.token) + selectRemoteProjectTab(first.token) + assert.equal(activeAppTabId(), `remote-project:${first.token}`) + assert.equal(activeRemoteProjectToken(), first.token) + assert.equal(appTabs().filter((tab) => tab.kind === "remote-project").length, 3) + + patchRemoteProjectTab(pairing.token, { entryUrl: undefined, folder: "/srv/other", title: "Other" }) + assert.deepEqual(remoteProjectTabs().find((tab) => tab.token === pairing.token), { + token: pairing.token, profileId: "box", folder: "/srv/other", title: "Other", + }) + + closeRemoteProjectTab(first.token) + assert.equal(activeRemoteProjectToken(), null) + closeRemoteProjectTabsForServer("box") + assert.equal(remoteProjectTabs().length, 0) + selectAppTab(null) + }) + + it("exist only in local desktop windows that host native views", () => { + const windows = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)" + const mac = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0)" + assert.equal(remoteViewHost({ host: "electron", windowContext: "local" }, mac), "electron") + assert.equal(remoteViewHost({ host: "tauri", windowContext: "local" }, windows), "tauri") + assert.equal(remoteViewHost({ host: "tauri", windowContext: "local" }, mac), undefined) + // A web client, a Remote Control device, a remote window or Preferences never opens one. + assert.equal(remoteViewHost({ host: "web", windowContext: "remote" }, windows), undefined) + assert.equal(remoteViewHost({ host: "electron", windowContext: "remote" }, windows), undefined) + assert.equal(remoteViewHost({ host: "tauri", windowContext: "remote" }, windows), undefined) + assert.equal(remoteViewHost({ host: "electron", windowContext: "preferences" }, windows), undefined) + }) +}) diff --git a/packages/ui/src/stores/remote-project-tabs.ts b/packages/ui/src/stores/remote-project-tabs.ts new file mode 100644 index 0000000000..415c4ba9b9 --- /dev/null +++ b/packages/ui/src/stores/remote-project-tabs.ts @@ -0,0 +1,61 @@ +import { createSignal } from "solid-js" + +/** + * A tab showing one project of a saved remote CodeNomad server in a native view. + * `folder` and `title` are what the embedded page last reported; `entryUrl` is a + * single-use first address (a pairing link), dropped once the view opened it. + */ +export interface RemoteProjectTabRecord { + token: string + profileId: string + folder?: string + title?: string + entryUrl?: string +} + +const [remoteProjectTabs, setRemoteProjectTabs] = createSignal([]) +const [activeRemoteProjectToken, setActiveRemoteProjectToken] = createSignal(null) +let sequence = 0 + +function openRemoteProjectTab(profileId: string, options: { folder?: string; entryUrl?: string } = {}): RemoteProjectTabRecord { + if (options.folder && !options.entryUrl) { + const existing = remoteProjectTabs().find((tab) => tab.profileId === profileId && tab.folder === options.folder) + if (existing) return existing + } + const record: RemoteProjectTabRecord = { + token: `${Date.now().toString(36)}-${(sequence++).toString(36)}`, + profileId, + ...(options.folder ? { folder: options.folder } : {}), + ...(options.entryUrl ? { entryUrl: options.entryUrl } : {}), + } + setRemoteProjectTabs((tabs) => [...tabs, record]) + return record +} + +function patchRemoteProjectTab(token: string, patch: Partial>): void { + setRemoteProjectTabs((tabs) => tabs.map((tab) => { + if (tab.token !== token) return tab + const next = { ...tab, ...patch } + for (const key of Object.keys(patch) as Array) if (patch[key] === undefined) delete next[key] + return next + })) +} + +function closeRemoteProjectTab(token: string): void { + setRemoteProjectTabs((tabs) => tabs.filter((tab) => tab.token !== token)) + if (activeRemoteProjectToken() === token) setActiveRemoteProjectToken(null) +} + +function closeRemoteProjectTabsForServer(profileId: string): void { + for (const tab of remoteProjectTabs()) if (tab.profileId === profileId) closeRemoteProjectTab(tab.token) +} + +export { + activeRemoteProjectToken, + closeRemoteProjectTab, + closeRemoteProjectTabsForServer, + openRemoteProjectTab, + patchRemoteProjectTab, + remoteProjectTabs, + setActiveRemoteProjectToken, +} diff --git a/packages/ui/src/styles/components/remote-project-menu.css b/packages/ui/src/styles/components/remote-project-menu.css new file mode 100644 index 0000000000..daf2fa2794 --- /dev/null +++ b/packages/ui/src/styles/components/remote-project-menu.css @@ -0,0 +1,112 @@ +/* Remotes disclosure shared by the home page and the new-instance launcher. */ +.remote-project-toggle { + display: flex; + align-items: center; + gap: var(--space-xs); + border: 0; + background: transparent; + text-align: start; + cursor: pointer; +} + +.remote-project-toggle:focus-visible { + outline: 1px solid var(--focus-ring-color); + outline-offset: 2px; +} + +.remote-project-menu { + display: flex; + flex-direction: column; + min-height: 0; + background-color: var(--surface-overlay); + border: 1px solid color-mix(in srgb, var(--border-base) 50%, transparent); + color: var(--text-secondary); + text-align: start; +} + +.remote-project-row { + display: flex; + align-items: center; + gap: var(--space-sm); + width: 100%; + min-height: 2.25rem; + padding: var(--space-xs) var(--space-sm); + border: 0; + background: transparent; + color: inherit; + text-align: start; + cursor: pointer; +} + +.remote-project-row:hover:not(:disabled), +.remote-project-row:focus-visible, +.remote-project-row[data-expanded] { + background-color: var(--menu-item-hover-bg); + outline: none; +} + +.remote-project-row:focus-visible { + box-shadow: inset 0 0 0 1px var(--list-item-highlight-border); +} + +.remote-project-row:disabled { + cursor: default; + opacity: 0.6; +} + +.remote-project-name { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + color: var(--text-primary); + font-size: var(--font-size-sm); +} + +.remote-project-add { + display: flex; + align-items: center; + gap: var(--space-xs); + padding-inline-start: var(--space-sm); + background-color: var(--surface-field); + border-top: 1px solid color-mix(in srgb, var(--border-base) 50%, transparent); +} + +.remote-project-add-input { + flex: 1 1 auto; + min-width: 0; + min-height: 2.25rem; + background: transparent; + border: 0; + outline: none; + color: var(--text-primary); + font-size: var(--font-size-sm); +} + +.remote-project-error { + margin: 0; + padding: var(--space-sm); + font-size: var(--font-size-sm); + color: var(--status-error-fg); + overflow-wrap: anywhere; +} + +/* The launcher keeps its compact spacing. */ +.new-instance-launcher .remote-project-toggle { + margin-bottom: var(--space-xs); +} + +.new-instance-launcher .remote-project-menu { + margin: 0 var(--window-inline-padding) var(--space-xs); +} + +/* The embedded single-project page, before a project is chosen. */ +.embedded-project-picker { + display: flex; + flex-direction: column; + gap: var(--space-sm); + width: min(32rem, 100%); + margin: auto; + padding: var(--space-lg); +} diff --git a/packages/ui/src/styles/controls.css b/packages/ui/src/styles/controls.css index 1a73e37521..0b22ee083a 100644 --- a/packages/ui/src/styles/controls.css +++ b/packages/ui/src/styles/controls.css @@ -49,3 +49,4 @@ @import "./components/composer-notice.css"; @import "./components/integration-attachment.css"; @import "./components/integration-catalog.css"; +@import "./components/remote-project-menu.css"; diff --git a/packages/ui/src/types/global.d.ts b/packages/ui/src/types/global.d.ts index d44d59ba06..0baae4dcc0 100644 --- a/packages/ui/src/types/global.d.ts +++ b/packages/ui/src/types/global.d.ts @@ -85,6 +85,10 @@ declare global { claimBrowserOpen?: (requestID: string) => Promise releaseBrowserOpen?: (requestID: string) => Promise onBrowserOpenRequest?: (callback: (payload: { sessionID: string; url: string; requestID: string }) => void) => () => void + openRemoteView?: (payload: import("../lib/native/remote-view").RemoteViewOpenPayload & { bounds: import("../lib/native/browser").BrowserTargetBounds }) => Promise + updateRemoteView?: (payload: { viewId: string; bounds?: import("../lib/native/browser").BrowserTargetBounds; visible: boolean }) => Promise + closeRemoteView?: (viewId: string) => Promise + onRemoteViewUpdated?: (callback: (update: import("../lib/native/remote-view").RemoteViewUpdate) => void) => () => void showNotification?: (payload: { title: string; body: string }) => Promise<{ ok: boolean; reason?: string }> openRemoteWindow?: (payload: { diff --git a/packages/ui/tests/browser/new-instance-launcher.test.ts b/packages/ui/tests/browser/new-instance-launcher.test.ts index 01b24f2911..b954067a63 100644 --- a/packages/ui/tests/browser/new-instance-launcher.test.ts +++ b/packages/ui/tests/browser/new-instance-launcher.test.ts @@ -70,7 +70,8 @@ test("a click keeps the full home page while a long press opens the launcher", a assert.match(await options(page).nth(2).innerText(), /Blender tools/) assert.equal(await launcher(page).locator("footer, .new-instance-launcher-servers").count(), 0) assert.equal(await launcher(page).getByRole("button", { name: /Remote servers|SideCar|Full home page|Add a server/ }).count(), 0) - assert.deepEqual(await launcher(page).getByRole("button").allTextContents(), ["Browse…", "Temporary", "Clone…"]) + // Remotes stays folded: listing saved CodeNomad servers reads and probes nothing. + assert.deepEqual(await launcher(page).getByRole("button").allTextContents(), ["Browse…", "Temporary", "Clone…", "Remotes"]) assert.deepEqual(remoteRequests, [], "saved profiles do not trigger launcher remote reads or probes") if (process.env.CODENOMAD_LAUNCHER_CAPTURE) await page.screenshot({ path: process.env.CODENOMAD_LAUNCHER_CAPTURE }) assert.deepEqual(errors, []) diff --git a/packages/ui/tests/browser/remote-project-tabs.test.ts b/packages/ui/tests/browser/remote-project-tabs.test.ts new file mode 100644 index 0000000000..a9cef6ab49 --- /dev/null +++ b/packages/ui/tests/browser/remote-project-tabs.test.ts @@ -0,0 +1,230 @@ +import assert from "node:assert/strict" +import { after, before, test } from "node:test" +import { armFixtureNavigationBudget } from "./fixture-navigation-budget" +import { borrowFixture } from "./fixture-borrow" +import { chromium, type Browser, type Page } from "playwright" + +// The real application (src/main.tsx) in three roles: the page a remote server +// serves inside a host tab (?codenomadEmbed=project), a web or Remote Control +// client, and a local Electron window hosting remote project tabs. +let browser: Browser, url: string +before(async () => { + const fixture = await borrowFixture({ + name: "remote-project-tabs", + routes: [{ path: "/fixture", html: "
" }], + }) + url = fixture.url + browser = await chromium.launch({ executablePath: process.env.CODENOMAD_BROWSER_PATH || undefined }) + armFixtureNavigationBudget(browser) +}) +after(async () => { await browser?.close() }) + +const BOX = "https://box.example" +const server = (id: string, extra: Record = {}) => ({ + id, name: id === "box" ? "Box" : id, baseUrl: id === "box" ? BOX : `https://${id}.example`, skipTlsVerify: false, + createdAt: "2026-11-01T10:00:00.000Z", updatedAt: "2026-11-01T10:00:00.000Z", ...extra, +}) + +interface Scenario { + context?: "local" | "remote" + host?: "electron" | "web" + uiState?: Record + /** A saved native session, restored by a local Electron window. */ + restore?: unknown +} + +async function open(page: Page, path: string, scenario: Scenario) { + const { context, host = "web", uiState = {}, restore } = scenario + await page.addInitScript({ content: `{ + const w = window, context = ${JSON.stringify(context ?? null)}, host = ${JSON.stringify(host)}, restore = ${JSON.stringify(restore ?? null)} + if (context) w.__CODENOMAD_WINDOW_CONTEXT__ = context + if (host !== "web") w.__CODENOMAD_RUNTIME_HOST__ = host + w.fixtureViews = { opened: [], updates: [], closed: [], listeners: [], windows: [] } + w.EventSource = class extends EventTarget { close() {} } + // Fixture shim: the session list's virtualizer reads defaultView from nodes the dev + // server's templates create in an inert document before they are inserted. + const defaultView = Object.getOwnPropertyDescriptor(Document.prototype, "defaultView") + Object.defineProperty(Document.prototype, "defaultView", { configurable: true, get() { return defaultView.get.call(this) ?? w } }) + if (host === "electron" && context === "local") { + const known = { + claimClientStateAccess: async () => Boolean(restore), + loadClientState: async () => ({ isPrimary: true, restoreEnabled: true, snapshot: restore }), + openRemoteView: async (payload) => { w.fixtureViews.opened.push(payload) }, + updateRemoteView: async (payload) => { w.fixtureViews.updates.push(payload) }, + closeRemoteView: async (viewId) => { w.fixtureViews.closed.push(viewId) }, + onRemoteViewUpdated: (callback) => { w.fixtureViews.listeners.push(callback); return () => {} }, + openRemoteWindow: async (payload) => { w.fixtureViews.windows.push(payload) }, + getZoomFactor: () => 1, + } + // Every other host call resolves to nothing and every subscription to a no-op disposer. + w.electronAPI = new Proxy(known, { get: (target, key) => key in target ? target[key] + : typeof key !== "string" ? undefined : /^on[A-Z]/.test(key) ? () => () => {} : async () => undefined }) + } + }` }) + const created: string[] = [] + let state = uiState + await page.route(/\/(?:api|workspaces)\//, async route => { + const request = route.request() + const pathname = new URL(request.url()).pathname + if (pathname === "/api/workspaces" && request.method() === "POST") { + const body = request.postDataJSON() as { path: string } + created.push(body.path) + return route.fulfill({ json: { + id: `ws-${created.length}`, path: body.path, status: "starting", proxyPath: `/workspaces/ws-${created.length}/instance`, + binaryId: "fixture", binaryLabel: "fixture", createdAt: new Date(0).toISOString(), updatedAt: new Date(0).toISOString(), + } }) + } + if (pathname === "/api/remote-servers/probe") { + const { baseUrl, skipTlsVerify } = request.postDataJSON() as { baseUrl: string; skipTlsVerify?: boolean } + return route.fulfill({ json: { ok: true, reachable: true, normalizedUrl: baseUrl, skipTlsVerify: Boolean(skipTlsVerify), requiresAuth: true, authenticated: false } }) + } + if (pathname === "/api/storage/state/ui" && request.method() === "PATCH") { + state = { ...state, ...(request.postDataJSON() as Record) } + return route.fulfill({ json: state }) + } + const body = pathname === "/api/workspaces" ? [] + : pathname === "/api/storage/config/ui" ? { settings: { locale: "en" } } + : pathname === "/api/storage/state/ui" ? state : {} + await route.fulfill({ json: body }) + }) + await page.goto(`${url}${path}`) + return { created, state: () => state } +} + +const views = (page: Page) => page.evaluate(() => (window as any).fixtureViews as { + opened: Array<{ viewId: string; profileId: string; baseUrl: string; url: string; bounds: { width: number; height: number } }> + updates: Array<{ viewId: string; visible: boolean }>; closed: string[]; windows: Array<{ id: string }> +}) + +test("the embedded page shows no tab bar or home, only a folder picker that opens one project", async () => { + const page = await browser.newPage({ viewport: { width: 1000, height: 700 }, locale: "en-US" }) + try { + const fixture = await open(page, "?codenomadEmbed=project", { + context: "remote", host: "electron", + uiState: { recentFolders: [{ path: "/srv/app", projectName: "App", lastAccessed: 2 }] }, + }) + const picker = page.locator("[data-embedded-project-picker]") + await picker.waitFor() + assert.equal(await page.locator(".tab-bar-instance").count(), 0) + assert.equal(await page.locator(".folder-home-root").count(), 0) + assert.equal(await page.getByRole("button", { name: "Remotes" }).count(), 0) + await picker.getByRole("button", { name: "Browse Folders" }).waitFor() + await picker.getByRole("button", { name: /App/ }).click() + await page.waitForFunction(() => document.title === "App") + assert.deepEqual(fixture.created, ["/srv/app"]) + const search = new URL(page.url()).searchParams + assert.equal(search.get("codenomadEmbed"), "project") + assert.equal(search.get("folder"), "/srv/app") + assert.equal(await page.locator(".tab-bar-instance").count(), 0) + } finally { await page.close() } +}) + +test("an embedded entry with a folder opens that project directly", async () => { + const page = await browser.newPage({ viewport: { width: 1000, height: 700 }, locale: "en-US" }) + try { + const fixture = await open(page, `?codenomadEmbed=project&folder=${encodeURIComponent("/srv/other")}`, { context: "remote", host: "electron" }) + await page.waitForFunction(() => document.title === "other") + assert.deepEqual(fixture.created, ["/srv/other"]) + assert.equal(await page.locator("[data-embedded-project-picker]").count(), 0) + } finally { await page.close() } +}) + +test("without the parameter a remote page keeps its full interface and lists no remote servers", async () => { + for (const scenario of [{ context: "remote", host: "electron" }, {}] as Scenario[]) { + const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: "en-US" }) + try { + await open(page, "", { ...scenario, uiState: { remoteServers: [server("box")] } }) + await page.locator(".folder-home-root").waitFor() + // A web client or Remote Control device never opens another server (no rebound). + assert.equal(await page.getByRole("button", { name: "Remotes" }).count(), 0) + } finally { await page.close() } + } +}) + +test("a local window opens a saved server as a project tab whose view follows the project it shows", async () => { + const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: "en-US" }) + try { + const fixture = await open(page, "", { context: "local", host: "electron", uiState: { remoteServers: [server("box"), server("lab", { skipTlsVerify: true })] } }) + await page.getByRole("button", { name: "Remotes" }).click() + await page.getByRole("button", { name: "Open a project on Box" }).click() + const tab = page.locator(".tab-pill", { hasText: "Box" }) + await tab.waitFor() + await page.waitForFunction(() => (window as any).fixtureViews.opened.length === 1) + const [opened] = (await views(page)).opened + assert.equal(opened.profileId, "box") + assert.equal(opened.baseUrl, BOX) + assert.equal(opened.url, `${BOX}/?codenomadEmbed=project`) + assert.ok(opened.bounds.width > 100 && opened.bounds.height > 100) + + // The embedded page reports its project: the tab takes its name and the host remembers it. + await page.evaluate(({ viewId, base }) => { + for (const listener of (window as any).fixtureViews.listeners) listener({ viewId, url: `${base}/?codenomadEmbed=project&folder=%2Fsrv%2Fapp`, title: "App" }) + // An older server's own title never relabels the tab. + for (const listener of (window as any).fixtureViews.listeners) listener({ viewId, url: `${base}/?codenomadEmbed=project`, title: "CodeNomad" }) + }, { viewId: opened.viewId, base: BOX }) + const projectTab = page.locator(".tab-pill", { hasText: "App" }) + await projectTab.waitFor() + // The server icon marks a remote project. + assert.equal(await projectTab.locator("svg").count() >= 1, true) + type Saved = { remoteProjectRecents?: Array<{ profileId: string; folder: string; projectName?: string }> } + for (let attempt = 0; attempt < 50 && !(fixture.state() as Saved).remoteProjectRecents?.length; attempt++) await page.waitForTimeout(100) + const recents = (fixture.state() as Saved).remoteProjectRecents + assert.deepEqual(recents?.map(({ profileId, folder, projectName }) => ({ profileId, folder, projectName })), [{ profileId: "box", folder: "/srv/app", projectName: "App" }]) + + // A local overlay (the home page) hides the native view; it never covers local dialogs. + await page.locator(".new-instance-button").click() + await page.waitForFunction((viewId) => (window as any).fixtureViews.updates.some((update: { viewId: string; visible: boolean }) => update.viewId === viewId && !update.visible), opened.viewId) + + // A server with an unverified certificate keeps its separate window. + await page.getByRole("button", { name: "Remotes" }).click() + await page.getByRole("button", { name: "Open a project on lab" }).click() + await page.waitForFunction(() => (window as any).fixtureViews.windows.length === 1) + assert.equal((await views(page)).windows[0].id, "lab") + assert.equal((await views(page)).opened.length, 1) + } finally { await page.close() } +}) + +test("a pasted pairing link adds the server and pairs in its new tab; other text is refused", async () => { + const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: "en-US" }) + try { + const fixture = await open(page, "", { context: "local", host: "electron" }) + await page.getByRole("button", { name: "Remotes" }).click() + const field = page.getByRole("textbox", { name: "Add server" }) + await field.fill("http://user:secret@box.example:4096") + await field.press("Enter") + await page.getByRole("alert").waitFor() + assert.equal((await views(page)).opened.length, 0) + + const tunnel = "https://desk.opentunnel.test" + await field.fill(`${tunnel}/remote-pair#single-use-code`) + await field.press("Enter") + await page.locator(".tab-pill", { hasText: "desk.opentunnel.test" }).waitFor() + await page.waitForFunction(() => (window as any).fixtureViews.opened.length === 1) + const [opened] = (await views(page)).opened + // The code is consumed by the view's first load and never saved with the server. + assert.equal(opened.url, `${tunnel}/remote-pair#single-use-code`) + assert.equal(opened.baseUrl, tunnel) + assert.equal(JSON.stringify(fixture.state()).includes("single-use-code"), false) + assert.deepEqual((fixture.state() as { remoteServers: Array<{ baseUrl: string }> }).remoteServers.map((entry) => entry.baseUrl), [tunnel]) + } finally { await page.close() } +}) + +test("a restored window reopens its remote project tabs on their server and folder", async () => { + const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: "en-US" }) + try { + await open(page, "", { + context: "local", host: "electron", + uiState: { remoteServers: [server("box")] }, + restore: { version: 1, revision: 1, savedAt: 1, layout: {}, session: { + activeTabIndex: 0, + tabs: [{ kind: "remote-project", profileId: "box", folder: "/srv/app" }, { kind: "remote-project", profileId: "removed" }], + } }, + }) + await page.locator(".tab-pill", { hasText: "Box" }).waitFor() + await page.waitForFunction(() => (window as any).fixtureViews.opened.length === 1) + const [opened] = (await views(page)).opened + assert.equal(opened.url, `${BOX}/?codenomadEmbed=project&folder=%2Fsrv%2Fapp`) + // A removed server's tab is dropped. + assert.equal(await page.locator(".tab-pill").count(), 1) + } finally { await page.close() } +}) From 25394d942bf0655b7efc8e21517f937f111e245c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Thu, 5 Nov 2026 13:52:00 +0100 Subject: [PATCH 02/34] fix(tauri): let the app-wide navigation guard admit remote project views In the first native trial a remote project tab stayed black: its child webview existed, at the right place and on top, but its document was about:blank. Tauri passes every navigation of every webview to the `external-link-guard` plugin after the webview's own handler. For a `remote-view-*` label that guard found no browser preview and no registered remote window origin, fell back to the internal-origin rule and cancelled the view's first load of its server. `intercept_navigation` now asks `RemoteViews::navigation_allowed` first: a registered view is admitted exactly where its own handler allows it (its server's origin, about:blank); other webviews, including a closed view, keep the window rules. The bare root and the help site stay refused there, since the view's handler already sends them to the entry or the browser. The developer-mode source test followed the remote window's data directory through a statement the shared `remote_profile_data_directory` helper replaced; it now checks the helper and that the remote window and the view both keep the default WebView2 options their shared storage requires. Validation: `cargo test --release` 311/311, including a test reproducing the refusal (window-origin fallback denies the view's entry) and the guard's verdicts for entry, login, pairing, other origins, bare root and help; offline `tauri build --no-bundle`. --- dev-docs/PROJECTS.md | 2 +- .../tauri-app/src-tauri/src/developer_mode.rs | 15 ++++- packages/tauri-app/src-tauri/src/main.rs | 7 +++ .../tauri-app/src-tauri/src/remote_view.rs | 55 +++++++++++++++++++ 4 files changed, 76 insertions(+), 3 deletions(-) diff --git a/dev-docs/PROJECTS.md b/dev-docs/PROJECTS.md index 5e6b737919..2dfa597d5b 100644 --- a/dev-docs/PROJECTS.md +++ b/dev-docs/PROJECTS.md @@ -8,5 +8,5 @@ Closing project tabs, temporary workspaces, the new-instance launcher and the Gi - Git is a full-functionality prerequisite, with directory-only degraded conversations when the backend cannot find Git. Only the explicitly opened physical folder is session authority in that mode; never infer sibling worktrees from native project IDs. Keep ancestor/descendant mutation identities covered by the deletion fence across Git availability changes. Inform agents through the owned native `codenomad.git-availability` instruction before prompts/custom commands, remove stale context after recovery, and keep this advisory separate from fail-closed environment synchronization. Do not add a blocking Git setup UI. Validate with `scripts/test-git-degraded-native.mjs` using an isolated CLI/database and provider. - Temporary instances (`workspaces/temporary-workspaces.ts`, UI `stores/temporary-instances.ts`) are ordinary non-Git workspaces on CodeNomad-created direct children of `/temporary-workspaces`. Registry membership (`temporary-workspaces.json`), not location, makes a folder temporary; keeping only unregisters it and adds a named recent project. Discard deletes only registered children of that root, refuses running conversations and other open tabs of the folder, removes conversations deepest-first, closes the workspace before deleting the folder and keeps failed removals registered; such a folder is reachable only by browsing to it. Closing a temporary tab from the UI asks Keep/Discard/Cancel, except that an untouched one (no conversation, file or unsent draft) closes and is discarded silently (`onlyIfEmpty`: the server refuses with `temporary_has_conversations`/`temporary_not_empty`, and any failure of that quiet discard returns the choice without an error). Before the server stops it, a visible temporary tab yields to its neighbour (or closes if alone) and a refusal restores it in place; `workspace.stopped` likewise closes the tab first and clears the instance in a microtask, because clearing a visible shell's state in the same update as its tab freezes the window. Same-minute names get a `(n)` suffix. Registry changes broadcast `workspace.temporaryChanged`, which clears kept marks in every window. Open temporary tabs are saved and restored with the app state like any project tab (still marked temporary). Only the choice dialog overrides initial focus (to its last, non-destructive choice); confirms keep focus on Cancel. Refusals use stable `temporary_*` codes localized by the client. Validate with `scripts/test-temporary-workspaces-native.mjs` against an isolated CLI. - The tab-bar new-instance button follows the last tab like a browser: the instance `TabScroll` frame only spans its tabs and the button sits after it, outside the scroller (so focusing it never scrolls the strip), ending up at the strip's end once tabs overflow. Dragged tabs stay visually within the tab list like a browser's (`KeepDraggedTabInStrip`), while the drop slot follows the pointer's unbounded position (`closestUnboundedCenter`). The button keeps its click (full home page, Cmd/Ctrl+N) while a long press, right-click, Alt+Down, Shift+F10 or Menu opens the anchored `NewInstanceLauncher` (`lib/long-press.ts`; only Escape returns focus to the button, never over another surface or the home page): search-first recent projects (an open project switches to its tab), Browse/Temporary/Clone and the folded Remotes list. SideCar and management (rename/remove recents, servers, settings) stay on the home page. Browse/clone flows live once in `components/new-instance-dialogs.tsx` (with optional home-only add-server setup) and recent-folder display helpers in `lib/recent-folder-display.ts`, shared with `FolderSelectionView`; styles in `styles/components/new-instance-launcher.css`. -- Remote project tabs show one project of a saved remote CodeNomad server inside a local window. Remotes (`components/remote-project-menu.tsx`, home page and launcher, host windows only: `canOpenRemoteWindows()`) lists the saved server profiles; its field adds one from a pasted pairing link or address (`lib/codenomad-link.ts`, refusing links with credentials) through the existing probe. Choosing a server opens a `remote-project` app tab (`stores/remote-project-tabs.ts`, actions in `stores/remote-project-open.ts`) whose `RemoteProjectView` places a native view (Electron `WebContentsView`, `electron/main/remote-view.ts`; Tauri child webview on Windows, `src-tauri/src/remote_view.rs`) over its content area; elsewhere, and for profiles that skip TLS verification, the server keeps its separate remote window. The view uses that server's remote-window storage (Electron partition, Tauri data directory), so its session or paired device cookie is reused without signing in again, and the remote preload/capability: of native access only notifications reach the host (badges and every local command are refused). It stays on the server's origin, the public help site opening in the system browser; a navigation to the bare root (end of login or pairing) returns to the tab's entry. The view opens the first time its tab shows, follows the placeholder's bounds and hides while its tab is hidden or a local dialog, menu or list is open (`localOverlayOpen()`, shared with browser previews); a reload or close of the owning page closes its views. The remote page runs in embedded single-project mode (`lib/embed-mode.ts`, `/?codenomadEmbed=project[&folder=…]`): no title bar, tab bar or home page, a folder picker (`components/embedded-project-picker.tsx`) until a project opens, no native badge; it records the folder in its address and the project name in `document.title`. The host accepts a title change only from the server's origin with a folder in the address, so a server without this mode shows its full interface and the tab keeps the server's name. Tabs restore as `{kind: "remote-project", profileId, folder?}` (a removed or window-only server drops its tab); projects opened in tabs join this host's recents beside local folders (`ui` state `remoteProjectRecents`, server, folder and name only; removing a server forgets them and closes its tabs). Covered by `tests/browser/remote-project-tabs.test.ts`, `electron/main/remote-view.test.ts` and `remote_view.rs` tests (navigation, ownership, ACL of the child label). +- Remote project tabs show one project of a saved remote CodeNomad server inside a local window. Remotes (`components/remote-project-menu.tsx`, home page and launcher, host windows only: `canOpenRemoteWindows()`) lists the saved server profiles; its field adds one from a pasted pairing link or address (`lib/codenomad-link.ts`, refusing links with credentials) through the existing probe. Choosing a server opens a `remote-project` app tab (`stores/remote-project-tabs.ts`, actions in `stores/remote-project-open.ts`) whose `RemoteProjectView` places a native view (Electron `WebContentsView`, `electron/main/remote-view.ts`; Tauri child webview on Windows, `src-tauri/src/remote_view.rs`) over its content area; elsewhere, and for profiles that skip TLS verification, the server keeps its separate remote window. The view uses that server's remote-window storage (Electron partition, Tauri data directory), so its session or paired device cookie is reused without signing in again, and the remote preload/capability: of native access only notifications reach the host (badges and every local command are refused). It stays on the server's origin, the public help site opening in the system browser; a navigation to the bare root (end of login or pairing) returns to the tab's entry. Under Tauri every navigation also passes the app-wide `external-link-guard` plugin after the view's own handler: `intercept_navigation` asks `RemoteViews::navigation_allowed` first for registered `remote-view-*` labels, since the window-origin rules would cancel the view's first load. The view opens the first time its tab shows, follows the placeholder's bounds and hides while its tab is hidden or a local dialog, menu or list is open (`localOverlayOpen()`, shared with browser previews); a reload or close of the owning page closes its views. The remote page runs in embedded single-project mode (`lib/embed-mode.ts`, `/?codenomadEmbed=project[&folder=…]`): no title bar, tab bar or home page, a folder picker (`components/embedded-project-picker.tsx`) until a project opens, no native badge; it records the folder in its address and the project name in `document.title`. The host accepts a title change only from the server's origin with a folder in the address, so a server without this mode shows its full interface and the tab keeps the server's name. Tabs restore as `{kind: "remote-project", profileId, folder?}` (a removed or window-only server drops its tab); projects opened in tabs join this host's recents beside local folders (`ui` state `remoteProjectRecents`, server, folder and name only; removing a server forgets them and closes its tabs). Covered by `tests/browser/remote-project-tabs.test.ts`, `electron/main/remote-view.test.ts` and `remote_view.rs` tests (navigation, ownership, ACL of the child label). - The clone dialog (`components/new-instance-dialogs.tsx`) suggests the repository's `git clone` folder name (`lib/clone-destination.ts`) inside a parent: the folder chosen with Browse, else the server-scoped `ui` state `lastCloneParent` (the folder above the last successful clone), else the folder above the most recent project. A destination the user types is kept as entered and sent unchanged; the server creates it. diff --git a/packages/tauri-app/src-tauri/src/developer_mode.rs b/packages/tauri-app/src-tauri/src/developer_mode.rs index 55b41f8b55..77f5273fc2 100644 --- a/packages/tauri-app/src-tauri/src/developer_mode.rs +++ b/packages/tauri-app/src-tauri/src/developer_mode.rs @@ -249,14 +249,25 @@ mod tests { // windows use a distinct profile without additional debugging arguments. let setup = source.split(".setup(move |app| {").nth(1).unwrap(); assert!(setup.contains("developer_mode.prepare_profile()?")); + let profile = source + .split("fn remote_profile_data_directory(") + .nth(1) + .unwrap() + .split("\n}") + .next() + .unwrap(); + assert!(profile.contains(".join(\"remote\")")); let remote = source - .split("let data_directory = app") + .split("let data_directory = remote_profile_data_directory(") .nth(1) .unwrap() .split("let window = match builder.build()") .next() .unwrap(); - assert!(remote.contains(".join(\"remote\")")); assert!(!remote.contains("additional_browser_args")); + // Remote project tabs share that storage: same default WebView2 options. + let view = include_str!("remote_view.rs"); + assert!(view.contains(".data_directory(crate::remote_profile_data_directory(")); + assert!(!view.contains("additional_browser_args")); } } diff --git a/packages/tauri-app/src-tauri/src/main.rs b/packages/tauri-app/src-tauri/src/main.rs index 5bbab14aae..b077386761 100644 --- a/packages/tauri-app/src-tauri/src/main.rs +++ b/packages/tauri-app/src-tauri/src/main.rs @@ -874,6 +874,13 @@ fn intercept_navigation(webview: &Webview, url: &Url) -> bool { { return allowed; } + if let Some(allowed) = webview + .app_handle() + .state::() + .navigation_allowed(&window_label, url) + { + return allowed; + } if should_allow_window_origin(&webview.app_handle(), &window_label, url) { return true; } diff --git a/packages/tauri-app/src-tauri/src/remote_view.rs b/packages/tauri-app/src-tauri/src/remote_view.rs index e0a938ece3..2a18bb53d2 100644 --- a/packages/tauri-app/src-tauri/src/remote_view.rs +++ b/packages/tauri-app/src-tauri/src/remote_view.rs @@ -144,6 +144,17 @@ impl RemoteViews { } } + /// The app-wide navigation guard runs after a view's own handler: it admits + /// exactly what that handler allows (its server's origin). `None` for any + /// webview that is not a registered view: the window rules then apply. + pub(crate) fn navigation_allowed(&self, label: &str, url: &Url) -> Option { + if !label.starts_with(LABEL_PREFIX) { + return None; + } + self.record(label) + .map(|record| decide(url, &record.origin) == Navigation::Allow) + } + /// A page that loads again in the owning window reopens its tabs' views. pub(crate) fn renderer_page_started(&self, webview: &tauri::Webview) { if webview.label() == webview.window().label() @@ -424,6 +435,50 @@ mod tests { .is_some()); } + #[test] + fn the_app_wide_navigation_guard_admits_a_views_server_pages() { + // Tauri runs the `external-link-guard` plugin after the view's own handler. + // Its window-origin fallback knows only local, Preferences and remote + // windows: alone, it cancels the view's first load, leaving it on about:blank. + let initial = url("http://127.0.0.1:9911/?codenomadEmbed=project"); + assert!(!crate::should_allow_registered_origin(None, &initial)); + + let views = RemoteViews::default(); + let owner = "local-11111111-1111-4111-8111-111111111111"; + let label = view_label(owner, "mw3j1qg1-0").unwrap(); + views.records.lock().unwrap().insert( + label.clone(), + Record { + owner: owner.into(), + origin: "http://127.0.0.1:9911".into(), + entry: initial.to_string(), + }, + ); + for allowed in [ + "http://127.0.0.1:9911/?codenomadEmbed=project", + "http://127.0.0.1:9911/login", + "http://127.0.0.1:9911/remote-pair", + "about:blank", + ] { + assert_eq!(views.navigation_allowed(&label, &url(allowed)), Some(true), "{allowed}"); + } + for refused in [ + "http://127.0.0.1:9898/", + "https://evil.example/", + // The view's own handler sends these to the entry or the system browser. + "http://127.0.0.1:9911/", + "https://neuralnomadsai.github.io/CodeNomad/en/", + ] { + assert_eq!(views.navigation_allowed(&label, &url(refused)), Some(false), "{refused}"); + } + // A closed view and every other webview fall back to the window rules, + // which refuse a remote page. + let closed = view_label(owner, "closed").unwrap(); + assert_eq!(views.navigation_allowed(&closed, &initial), None); + assert_eq!(views.navigation_allowed(owner, &initial), None); + assert_eq!(views.navigation_allowed("remote-profile", &initial), None); + } + #[test] fn remote_views_belong_to_their_owner_window() { let views = RemoteViews::default(); From 51d27db24e57019da8fa7327150c7184fa1c0950 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Thu, 5 Nov 2026 14:35:08 +0100 Subject: [PATCH 03/34] fix(auth): keep a password sign-in for seven days across browser restarts A remote project tab asked for the server password again each time the host restarted, although the server kept running: the direct-access session cookie had no Max-Age, so the view's WebView2 dropped it with the view, while the server-side session itself never expired. A password login now creates a session lasting PASSWORD_SESSION_TTL_MS (seven days) and its cookie carries the matching Max-Age; HttpOnly, SameSite=Lax, Path=/ and Secure over HTTPS are unchanged. The server refuses and forgets an expired session and prunes expired ones on each new login. Logout now revokes the session on the server as well as clearing the cookie. Desktop bootstrap token sessions keep a browser-session cookie and no expiry, so a long-running desktop app never loses access to its own backend. A backend restart still invalidates every direct session. Validation: session-manager.test.ts (exact expiry, pruning, revocation, no expiry for token sessions) and auth-session-lifetime.test.ts on the real routes (login cookie attributes and Max-Age, logout revocation, token cookie without Max-Age); existing auth, request-path, Remote Control surface and SideCar proxy tests; help security page updated in ten locales. --- docs/help/de/security.md | 2 +- docs/help/en/security.md | 2 +- docs/help/es/security.md | 2 +- docs/help/fr/security.md | 2 +- docs/help/he/security.md | 2 +- docs/help/ja/security.md | 2 +- docs/help/ne/security.md | 2 +- docs/help/ru/security.md | 2 +- docs/help/tr/security.md | 2 +- docs/help/zh-Hans/security.md | 2 +- packages/server/src/auth/manager.ts | 17 +++++- .../server/src/auth/session-manager.test.ts | 30 ++++++++++ packages/server/src/auth/session-manager.ts | 43 +++++++++++++- .../routes/auth-session-lifetime.test.ts | 59 +++++++++++++++++++ packages/server/src/server/routes/auth.ts | 6 +- 15 files changed, 157 insertions(+), 18 deletions(-) create mode 100644 packages/server/src/auth/session-manager.test.ts create mode 100644 packages/server/src/server/routes/auth-session-lifetime.test.ts diff --git a/docs/help/de/security.md b/docs/help/de/security.md index 0e5d7a17b8..c39c9b6885 100644 --- a/docs/help/de/security.md +++ b/docs/help/de/security.md @@ -29,7 +29,7 @@ Ersteinrichtung wird nur vom eigenen Loopback-Listener des Hosts angenommen, nic ## Browsersitzungen und Widerruf {#sessions} -Direkte Anmeldung erzeugt eine undurchsichtige Backend-Sitzung im Arbeitsspeicher und ein `codenomad_session`-Cookie (oder den konfigurierten Cookie-Namen). Cookies sind `HttpOnly`, `SameSite=Lax`, auf `/` begrenzt und bei Ausgabe über HTTPS als `Secure` markiert. Es sind Browsersitzungs-Cookies; ein Backend-Neustart macht die Sitzungen im Speicher ungültig. Authentifizieren Sie sich bei Aufforderung an Ort und Stelle neu, statt fehlgeschlagene Änderungen erneut zu senden. +Direkte Anmeldung erzeugt eine undurchsichtige Backend-Sitzung im Arbeitsspeicher und ein `codenomad_session`-Cookie (oder den konfigurierten Cookie-Namen). Cookies sind `HttpOnly`, `SameSite=Lax`, auf `/` begrenzt und bei Ausgabe über HTTPS als `Secure` markiert. Eine Anmeldung gilt sieben Tage, auch über Neustarts von Browser und Desktop-App hinweg; Abmelden beendet sie im Backend, und ein Backend-Neustart macht alle direkten Sitzungen ungültig. Authentifizieren Sie sich bei Aufforderung an Ort und Stelle neu, statt fehlgeschlagene Änderungen erneut zu senden. Ein Passwortwechsel ändert spätere Zugangsdatenprüfungen; er macht bereits ausgegebene Direkt-Sitzungen oder Fernsteuerungsgeräte **nicht** ungültig. Bei Kompromittierungsverdacht: diff --git a/docs/help/en/security.md b/docs/help/en/security.md index 96edc61bc7..a72fe7fc76 100644 --- a/docs/help/en/security.md +++ b/docs/help/en/security.md @@ -29,7 +29,7 @@ Bootstrap is accepted only from the host's own loopback listener, not from a LAN ## Browser sessions and revocation {#sessions} -Direct sign-in creates an opaque in-memory backend session and a `codenomad_session` cookie (or the configured cookie name). Cookies are `HttpOnly`, `SameSite=Lax`, scoped to `/`, and marked `Secure` when issued over HTTPS. They are browser-session cookies; backend restart invalidates the in-memory sessions. Reauthenticate in place when asked rather than resending failed mutations. +Direct sign-in creates an opaque in-memory backend session and a `codenomad_session` cookie (or the configured cookie name). Cookies are `HttpOnly`, `SameSite=Lax`, scoped to `/`, and marked `Secure` when issued over HTTPS. A sign-in lasts seven days, also across browser and desktop restarts; signing out ends it on the backend, and a backend restart invalidates every direct session. Reauthenticate in place when asked rather than resending failed mutations. Changing a password changes subsequent credential checks; it does **not** invalidate already issued direct sessions or Remote Control devices. For suspected compromise: diff --git a/docs/help/es/security.md b/docs/help/es/security.md index 21def004f8..33ac4d2dfe 100644 --- a/docs/help/es/security.md +++ b/docs/help/es/security.md @@ -29,7 +29,7 @@ La inicialización se acepta solo desde el listener loopback del propio anfitri ## Sesiones de navegador y revocación {#sessions} -El inicio de sesión directo crea una sesión opaca en memoria del backend y una cookie `codenomad_session` (o el nombre de cookie configurado). Las cookies son `HttpOnly`, `SameSite=Lax`, tienen ámbito `/` y se marcan `Secure` al emitirse por HTTPS. Son cookies de sesión del navegador; reiniciar el backend invalida las sesiones en memoria. Vuelve a autenticarte sin abandonar la vista cuando se solicite, en lugar de reenviar modificaciones fallidas. +El inicio de sesión directo crea una sesión opaca en memoria del backend y una cookie `codenomad_session` (o el nombre de cookie configurado). Las cookies son `HttpOnly`, `SameSite=Lax`, tienen ámbito `/` y se marcan `Secure` al emitirse por HTTPS. Un inicio de sesión dura siete días, también tras reiniciar el navegador o la aplicación de escritorio; cerrar sesión lo termina en el backend, y reiniciar el backend invalida todas las sesiones directas. Vuelve a autenticarte sin abandonar la vista cuando se solicite, en lugar de reenviar modificaciones fallidas. Cambiar una contraseña cambia las comprobaciones de credenciales posteriores; **no** invalida las sesiones directas ya emitidas ni los dispositivos de Control remoto. Si sospechas una intrusión: diff --git a/docs/help/fr/security.md b/docs/help/fr/security.md index e4beed5856..84f5e0ef37 100644 --- a/docs/help/fr/security.md +++ b/docs/help/fr/security.md @@ -29,7 +29,7 @@ L’initialisation n’est acceptée que depuis l’écoute de boucle locale de ## Sessions navigateur et révocation {#sessions} -La connexion directe crée une session opaque en mémoire du backend et un cookie `codenomad_session` (ou le nom configuré). Les cookies sont `HttpOnly`, `SameSite=Lax`, limités à `/` et marqués `Secure` s’ils sont émis en HTTPS. Ce sont des cookies de session navigateur ; le redémarrage du backend invalide les sessions en mémoire. Réauthentifiez-vous sur place si demandé plutôt que de renvoyer les modifications échouées. +La connexion directe crée une session opaque en mémoire du backend et un cookie `codenomad_session` (ou le nom configuré). Les cookies sont `HttpOnly`, `SameSite=Lax`, limités à `/` et marqués `Secure` s’ils sont émis en HTTPS. Une connexion dure sept jours, y compris après un redémarrage du navigateur ou de l’application de bureau ; la déconnexion y met fin côté backend, et le redémarrage du backend invalide toutes les sessions directes. Réauthentifiez-vous sur place si demandé plutôt que de renvoyer les modifications échouées. Changer un mot de passe change les vérifications futures ; cela n’invalide **pas** les sessions directes déjà émises ni les appareils de Contrôle à distance. En cas de compromission suspectée : diff --git a/docs/help/he/security.md b/docs/help/he/security.md index 5aa882d7bf..e981812761 100644 --- a/docs/help/he/security.md +++ b/docs/help/he/security.md @@ -29,7 +29,7 @@ ## סשנים בדפדפן וביטול גישה {#sessions} -התחברות ישירה יוצרת סשן אטום בזיכרון שרת הקצה ועוגיית `codenomad_session` (או בשם העוגייה שהוגדר). העוגיות הן `HttpOnly`, `SameSite=Lax`, תחומות ל־`/`, ומסומנות `Secure` כשמונפקות ב־HTTPS. אלו עוגיות סשן דפדפן; הפעלה מחדש של שרת הקצה מבטלת את הסשנים בזיכרון. התחברו מחדש במקום כשמתבקשים, במקום לשלוח שוב פעולות שינוי שנכשלו. +התחברות ישירה יוצרת סשן אטום בזיכרון שרת הקצה ועוגיית `codenomad_session` (או בשם העוגייה שהוגדר). העוגיות הן `HttpOnly`, `SameSite=Lax`, תחומות ל־`/`, ומסומנות `Secure` כשמונפקות ב־HTTPS. התחברות נשמרת שבעה ימים, גם אחרי הפעלה מחדש של הדפדפן או של יישום שולחן העבודה; התנתקות מסיימת אותה בשרת הקצה, והפעלה מחדש של שרת הקצה מבטלת את כל הסשנים הישירים. התחברו מחדש במקום כשמתבקשים, במקום לשלוח שוב פעולות שינוי שנכשלו. שינוי סיסמה משנה בדיקות אישורים עתידיות; הוא **אינו** מבטל סשנים ישירים או מכשירי שליטה מרחוק שכבר אושרו. בחשד לפריצה: diff --git a/docs/help/ja/security.md b/docs/help/ja/security.md index af7dd1f1f5..6619be5798 100644 --- a/docs/help/ja/security.md +++ b/docs/help/ja/security.md @@ -29,7 +29,7 @@ CodeNomad へのアクセスにより、OpenCode を通じてバックエンド ## ブラウザーセッションと失効 {#sessions} -直接ログインは、バックエンドのメモリ内に不透明なセッションを作成し、`codenomad_session` Cookie(または設定した Cookie 名)を発行します。Cookie は `HttpOnly`、`SameSite=Lax`、範囲 `/` で、HTTPS 発行時は `Secure` です。ブラウザーセッション Cookie であり、バックエンドの再起動でメモリ内セッションは無効になります。要求されたら、その場で再認証し、失敗した変更操作を再送しないでください。 +直接ログインは、バックエンドのメモリ内に不透明なセッションを作成し、`codenomad_session` Cookie(または設定した Cookie 名)を発行します。Cookie は `HttpOnly`、`SameSite=Lax`、範囲 `/` で、HTTPS 発行時は `Secure` です。ログインはブラウザーやデスクトップアプリを再起動しても 7 日間有効です。ログアウトするとバックエンド側でも終了し、バックエンドの再起動ですべての直接セッションが無効になります。要求されたら、その場で再認証し、失敗した変更操作を再送しないでください。 パスワード変更は、以後の認証情報チェックを変えますが、発行済みの直接セッションやリモートコントロール端末を無効化 **しません**。侵害が疑われる場合: diff --git a/docs/help/ne/security.md b/docs/help/ne/security.md index d77ce14e0b..9d3de5b25d 100644 --- a/docs/help/ne/security.md +++ b/docs/help/ne/security.md @@ -29,7 +29,7 @@ bootstrap host कै loopback listener बाट मात्र स्वी ## browser session र revocation {#sessions} -direct sign-in ले opaque in-memory backend session र `codenomad_session` cookie (वा configured नाम) बनाउँछ। cookie `HttpOnly`, `SameSite=Lax`, `/` दायराका र HTTPS बाट जारी हुँदा `Secure` हुन्छन्। browser-session cookie हुन्; backend restart ले in-memory session अमान्य गर्छ। माग्दा असफल परिवर्तन फेरि पठाउनुको सट्टा त्यहीं reauthenticate गर्नुहोस्। +direct sign-in ले opaque in-memory backend session र `codenomad_session` cookie (वा configured नाम) बनाउँछ। cookie `HttpOnly`, `SameSite=Lax`, `/` दायराका र HTTPS बाट जारी हुँदा `Secure` हुन्छन्। sign-in सात दिनसम्म रहन्छ, browser वा desktop app restart पछि पनि; sign out ले यसलाई backend मा अन्त्य गर्छ, र backend restart ले सबै direct session अमान्य गर्छ। माग्दा असफल परिवर्तन फेरि पठाउनुको सट्टा त्यहीं reauthenticate गर्नुहोस्। password बदल्दा पछिका credential जाँच बदलिन्छन्; जारी भइसकेका direct session वा Remote Control device अमान्य **हुँदैनन्**। compromise शङ्का भए: diff --git a/docs/help/ru/security.md b/docs/help/ru/security.md index 7e1b97316f..44a7569d74 100644 --- a/docs/help/ru/security.md +++ b/docs/help/ru/security.md @@ -29,7 +29,7 @@ ## Браузерные сессии и отзыв {#sessions} -Прямой вход создаёт непрозрачную сессию в памяти серверной части и cookie `codenomad_session` (или настроенное имя). Cookie имеют `HttpOnly`, `SameSite=Lax`, область `/` и `Secure` при выдаче через HTTPS. Это сессионные cookies браузера; перезапуск серверной части делает сессии в памяти недействительными. При запросе войдите заново на месте, а не повторяйте неудачные изменения. +Прямой вход создаёт непрозрачную сессию в памяти серверной части и cookie `codenomad_session` (или настроенное имя). Cookie имеют `HttpOnly`, `SameSite=Lax`, область `/` и `Secure` при выдаче через HTTPS. Вход действует семь дней, в том числе после перезапуска браузера или настольного приложения; выход завершает его на серверной части, а перезапуск серверной части делает все прямые сессии недействительными. При запросе войдите заново на месте, а не повторяйте неудачные изменения. Изменение пароля меняет последующие проверки данных; **не** аннулирует уже выданные прямые сессии или устройства удалённого управления. При подозрении на компрометацию: diff --git a/docs/help/tr/security.md b/docs/help/tr/security.md index f8f843f252..612deb95ce 100644 --- a/docs/help/tr/security.md +++ b/docs/help/tr/security.md @@ -29,7 +29,7 @@ Komut bağımsız değişkenlerine veya kabuk geçmişine parola eklemek yerine ## Tarayıcı oturumları ve iptali {#sessions} -Doğrudan giriş, arka uç belleğinde opak bir oturum ve `codenomad_session` çerezi (veya yapılandırılan adla çerez) oluşturur. Çerezler `HttpOnly`, `SameSite=Lax` özelliklerine sahiptir, `/` kapsamındadır ve HTTPS üzerinden verildiğinde `Secure` olarak işaretlenir. Bunlar tarayıcı oturumu çerezleridir; arka ucun yeniden başlatılması bellekteki oturumları geçersiz kılar. Başarısız değişiklik işlemlerini yeniden göndermek yerine istendiğinde aynı sayfada yeniden kimlik doğrulayın. +Doğrudan giriş, arka uç belleğinde opak bir oturum ve `codenomad_session` çerezi (veya yapılandırılan adla çerez) oluşturur. Çerezler `HttpOnly`, `SameSite=Lax` özelliklerine sahiptir, `/` kapsamındadır ve HTTPS üzerinden verildiğinde `Secure` olarak işaretlenir. Bir giriş, tarayıcı veya masaüstü uygulaması yeniden başlatılsa da yedi gün geçerlidir; oturumu kapatmak onu arka uçta da sonlandırır ve arka ucun yeniden başlatılması tüm doğrudan oturumları geçersiz kılar. Başarısız değişiklik işlemlerini yeniden göndermek yerine istendiğinde aynı sayfada yeniden kimlik doğrulayın. Parolayı değiştirmek sonraki kimlik bilgisi kontrollerini değiştirir; önceden verilmiş doğrudan oturumları veya Uzaktan Kontrol cihazlarını **geçersiz kılmaz**. Yetkisiz erişimden şüpheleniyorsanız: diff --git a/docs/help/zh-Hans/security.md b/docs/help/zh-Hans/security.md index ca7714e193..5509a6b446 100644 --- a/docs/help/zh-Hans/security.md +++ b/docs/help/zh-Hans/security.md @@ -29,7 +29,7 @@ ## 浏览器会话与撤销 {#sessions} -直接登录会创建不透明的后端内存会话和 `codenomad_session` cookie(或配置的 cookie 名)。cookie 为 `HttpOnly`、`SameSite=Lax`,作用域为 `/`,通过 HTTPS 签发时标记为 `Secure`。它们是浏览器会话 cookie;后端重启使内存会话失效。收到提示时请就地重新认证,而非重发失败的修改操作。 +直接登录会创建不透明的后端内存会话和 `codenomad_session` cookie(或配置的 cookie 名)。cookie 为 `HttpOnly`、`SameSite=Lax`,作用域为 `/`,通过 HTTPS 签发时标记为 `Secure`。登录有效期为七天,浏览器或桌面应用重启后依然有效;退出登录会在后端结束该会话,后端重启会使所有直接会话失效。收到提示时请就地重新认证,而非重发失败的修改操作。 更改密码会改变后续凭据检查;**不会**使已签发的直接会话或远程控制设备失效。怀疑被入侵时: diff --git a/packages/server/src/auth/manager.ts b/packages/server/src/auth/manager.ts index 3892f3a6fe..439608a3fe 100644 --- a/packages/server/src/auth/manager.ts +++ b/packages/server/src/auth/manager.ts @@ -4,6 +4,7 @@ import type { Logger } from "../logger" import { AuthStore } from "./auth-store" import { TokenManager } from "./token-manager" import { SessionManager } from "./session-manager" +export { PASSWORD_SESSION_TTL_MS } from "./session-manager" import { parseCookies } from "./http-auth" import { isLocalRequest, isRemoteRequest, remoteDeviceOf } from "../remote-control/request-origin" @@ -79,11 +80,19 @@ export class AuthManager { return this.requireAuthStore().validateCredentials(username, password) } - createSession(username: string) { + /** `ttlMs` makes the session (and its cookie) expire; without it, it ends with the server. */ + createSession(username: string, options: { ttlMs?: number } = {}) { if (!this.authEnabled) { return { id: "auth-disabled", createdAt: Date.now(), username: this.init.username } } - return this.sessionManager.createSession(username) + return this.sessionManager.createSession(username, options) + } + + /** Logout ends the server-side session too, not only the browser's cookie. */ + revokeSessionFromRequest(request: FastifyRequest): void { + if (!this.authEnabled || isRemoteRequest(request)) return + const cookieHeader = Array.isArray(request.headers.cookie) ? request.headers.cookie.join("; ") : request.headers.cookie + this.sessionManager.revokeSession(parseCookies(cookieHeader)[this.cookieName]) } getStatus() { @@ -133,8 +142,10 @@ export class AuthManager { reply.header("Set-Cookie", buildSessionCookie(this.cookieName, sessionId)) } + /** An expiring session's cookie lasts exactly as long as the session. */ setSessionCookieWithOptions(reply: FastifyReply, sessionId: string, options?: { secure?: boolean }) { - reply.header("Set-Cookie", buildSessionCookie(this.cookieName, sessionId, options)) + const maxAgeSeconds = this.authEnabled ? this.sessionManager.remainingSeconds(sessionId) : undefined + reply.header("Set-Cookie", buildSessionCookie(this.cookieName, sessionId, { ...options, maxAgeSeconds })) } clearSessionCookie(reply: FastifyReply) { diff --git a/packages/server/src/auth/session-manager.test.ts b/packages/server/src/auth/session-manager.test.ts new file mode 100644 index 0000000000..466badedd5 --- /dev/null +++ b/packages/server/src/auth/session-manager.test.ts @@ -0,0 +1,30 @@ +import assert from "node:assert/strict" +import { it } from "node:test" +import { PASSWORD_SESSION_TTL_MS, SessionManager } from "./session-manager" + +it("expires a password session exactly at its lifetime and forgets it", () => { + let now = 1_000_000 + const sessions = new SessionManager(() => now) + const session = sessions.createSession("user", { ttlMs: PASSWORD_SESSION_TTL_MS }) + assert.equal(sessions.remainingSeconds(session.id), PASSWORD_SESSION_TTL_MS / 1000) + now += PASSWORD_SESSION_TTL_MS - 1 + assert.equal(sessions.getSession(session.id)?.username, "user") + now += 1 + assert.equal(sessions.getSession(session.id), undefined) + assert.equal(sessions.remainingSeconds(session.id), undefined) +}) + +it("keeps sessions without lifetime until the server ends, prunes expired ones and revokes on demand", () => { + let now = 0 + const sessions = new SessionManager(() => now) + const token = sessions.createSession("desktop") + const short = sessions.createSession("user", { ttlMs: 10 }) + now = 1_000_000_000 + assert.equal(sessions.getSession(token.id)?.username, "desktop") + assert.equal(sessions.remainingSeconds(token.id), undefined) + // A later login prunes the expired one even if its cookie never comes back. + sessions.createSession("other") + assert.equal((sessions as unknown as { sessions: Map }).sessions.has(short.id), false) + sessions.revokeSession(token.id) + assert.equal(sessions.getSession(token.id), undefined) +}) diff --git a/packages/server/src/auth/session-manager.ts b/packages/server/src/auth/session-manager.ts index e952ae1bfc..f060d74c84 100644 --- a/packages/server/src/auth/session-manager.ts +++ b/packages/server/src/auth/session-manager.ts @@ -1,23 +1,60 @@ import crypto from "crypto" +/** + * A password login lasts this long: its cookie gets the same Max-Age, so a browser + * or desktop view keeps it across restarts and the server refuses it afterwards. + */ +export const PASSWORD_SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000 + export interface SessionInfo { id: string createdAt: number username: string + /** Absent for sessions that end with the server (desktop bootstrap token). */ + expiresAt?: number } export class SessionManager { private sessions = new Map() - createSession(username: string): SessionInfo { + constructor(private readonly now: () => number = Date.now) {} + + createSession(username: string, options: { ttlMs?: number } = {}): SessionInfo { + this.pruneExpired() const id = crypto.randomBytes(32).toString("base64url") - const info: SessionInfo = { id, createdAt: Date.now(), username } + const createdAt = this.now() + const info: SessionInfo = { + id, createdAt, username, + ...(options.ttlMs === undefined ? {} : { expiresAt: createdAt + options.ttlMs }), + } this.sessions.set(id, info) return info } getSession(id: string | undefined): SessionInfo | undefined { if (!id) return undefined - return this.sessions.get(id) + const session = this.sessions.get(id) + if (session && session.expiresAt !== undefined && session.expiresAt <= this.now()) { + this.sessions.delete(id) + return undefined + } + return session + } + + /** Seconds left before an expiring session ends; undefined for one without expiry. */ + remainingSeconds(id: string): number | undefined { + const expiresAt = this.getSession(id)?.expiresAt + return expiresAt === undefined ? undefined : Math.max(0, Math.floor((expiresAt - this.now()) / 1000)) + } + + revokeSession(id: string | undefined): void { + if (id) this.sessions.delete(id) + } + + private pruneExpired(): void { + const now = this.now() + for (const [id, session] of this.sessions) { + if (session.expiresAt !== undefined && session.expiresAt <= now) this.sessions.delete(id) + } } } diff --git a/packages/server/src/server/routes/auth-session-lifetime.test.ts b/packages/server/src/server/routes/auth-session-lifetime.test.ts new file mode 100644 index 0000000000..11ae589cad --- /dev/null +++ b/packages/server/src/server/routes/auth-session-lifetime.test.ts @@ -0,0 +1,59 @@ +import assert from "node:assert/strict" +import fs from "node:fs/promises" +import os from "node:os" +import path from "node:path" +import { it } from "node:test" +import Fastify from "fastify" +import pino from "pino" +import { AuthManager, PASSWORD_SESSION_TTL_MS } from "../../auth/manager" +import { registerAuthRoutes } from "./auth" + +async function fixture(generateToken = false) { + const tempRoot = path.join(os.tmpdir(), "opencode") + await fs.mkdir(tempRoot, { recursive: true }) + const directory = await fs.mkdtemp(path.join(tempRoot, "codenomad-auth-lifetime-")) + const manager = new AuthManager({ + configPath: path.join(directory, "config.yaml"), username: "user", password: "fixture-password", generateToken, + }, pino({ level: "silent" })) + const app = Fastify({ logger: false }) + registerAuthRoutes(app, { authManager: manager }) + return { app, manager, async close() { await app.close(); await fs.rm(directory, { recursive: true, force: true }) } } +} + +const cookieOf = (header: string | string[] | number | undefined) => String(Array.isArray(header) ? header[0] : header) + +it("a password login cookie outlives the browser for the session's lifetime, keeping its protections", async () => { + const f = await fixture() + try { + const login = await f.app.inject({ method: "POST", url: "/api/auth/login", payload: { username: "user", password: "fixture-password" } }) + assert.equal(login.statusCode, 200) + const cookie = cookieOf(login.headers["set-cookie"]) + const parts = cookie.split("; ") + assert.ok(parts.includes("HttpOnly")) + assert.ok(parts.includes("SameSite=Lax")) + assert.ok(parts.includes("Path=/")) + // Plain HTTP stays without Secure, exactly as before. + assert.ok(!parts.includes("Secure")) + assert.ok(parts.includes(`Max-Age=${PASSWORD_SESSION_TTL_MS / 1000}`), cookie) + + const value = parts[0]! + const status = await f.app.inject({ method: "GET", url: "/api/auth/status", headers: { cookie: value } }) + assert.equal(status.json().authenticated, true) + + // Logging out ends the session on the server, not only in this browser. + const logout = await f.app.inject({ method: "POST", url: "/api/auth/logout", headers: { cookie: value } }) + assert.match(cookieOf(logout.headers["set-cookie"]), /Max-Age=0/) + const after = await f.app.inject({ method: "GET", url: "/api/auth/status", headers: { cookie: value } }) + assert.equal(after.json().authenticated, false) + } finally { await f.close() } +}) + +it("a desktop bootstrap token session keeps a browser-session cookie that lasts as long as the server", async () => { + const f = await fixture(true) + try { + const token = f.manager.issueBootstrapToken()! + const response = await f.app.inject({ method: "POST", url: "/api/auth/token", payload: { token }, remoteAddress: "127.0.0.1" }) + assert.equal(response.statusCode, 200) + assert.doesNotMatch(cookieOf(response.headers["set-cookie"]), /Max-Age/) + } finally { await f.close() } +}) diff --git a/packages/server/src/server/routes/auth.ts b/packages/server/src/server/routes/auth.ts index 2c77b74383..5f364bd857 100644 --- a/packages/server/src/server/routes/auth.ts +++ b/packages/server/src/server/routes/auth.ts @@ -1,7 +1,7 @@ import type { FastifyInstance } from "fastify" import fs from "fs" import { z } from "zod" -import type { AuthManager } from "../../auth/manager" +import { PASSWORD_SESSION_TTL_MS, type AuthManager } from "../../auth/manager" import { isRemoteRequest } from "../../remote-control/request-origin" interface RouteDeps { @@ -105,7 +105,8 @@ export function registerAuthRoutes(app: FastifyInstance, deps: RouteDeps) { return } - const session = deps.authManager.createSession(body.username) + // A password login survives browser and desktop restarts for a bounded time. + const session = deps.authManager.createSession(body.username, { ttlMs: PASSWORD_SESSION_TTL_MS }) deps.authManager.setSessionCookieWithOptions(reply, session.id, { secure: isSecureRequest(request) }) reply.send({ ok: true }) }) @@ -135,6 +136,7 @@ export function registerAuthRoutes(app: FastifyInstance, deps: RouteDeps) { }) app.post("/api/auth/logout", async (request, reply) => { + deps.authManager.revokeSessionFromRequest(request) deps.authManager.clearSessionCookieWithOptions(reply, { secure: isSecureRequest(request) }) reply.send({ ok: true }) }) From ce7f77a9b7c3b64be263d7c6599d1d8483ef1ea3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Thu, 5 Nov 2026 14:35:08 +0100 Subject: [PATCH 04/34] fix(remote): reselect the embedded project's active session after a restart After the host restarted, a remote project tab came back on its project but showed "Start a conversation" instead of the session that was open: the embedded page runs in a remote window context without client state. The embedded page keeps its active session per folder in its own storage, which persists with the server's remote-window storage (the same that keeps its sign-in). On reopening it selects that session with the hydration a restored local tab uses (restoreEmbeddedSession), unless the user picked one meanwhile; the empty startup selection never overwrites the remembered one. Malformed identifiers are neither written nor trusted. Validation: embed-mode unit tests (per-folder memory, validation, unavailable storage) and browser tests on the real app (the remembered session is read back on opening and kept; a folder without one reads none). --- dev-docs/PROJECTS.md | 2 +- packages/ui/src/App.tsx | 26 +++++++++++- packages/ui/src/lib/embed-mode.test.ts | 40 ++++++++++++++++++- packages/ui/src/lib/embed-mode.ts | 25 ++++++++++++ .../ui/src/stores/embedded-project-session.ts | 27 +++++++++++++ .../tests/browser/remote-project-tabs.test.ts | 23 ++++++++++- 6 files changed, 138 insertions(+), 5 deletions(-) create mode 100644 packages/ui/src/stores/embedded-project-session.ts diff --git a/dev-docs/PROJECTS.md b/dev-docs/PROJECTS.md index 2dfa597d5b..6d52360842 100644 --- a/dev-docs/PROJECTS.md +++ b/dev-docs/PROJECTS.md @@ -8,5 +8,5 @@ Closing project tabs, temporary workspaces, the new-instance launcher and the Gi - Git is a full-functionality prerequisite, with directory-only degraded conversations when the backend cannot find Git. Only the explicitly opened physical folder is session authority in that mode; never infer sibling worktrees from native project IDs. Keep ancestor/descendant mutation identities covered by the deletion fence across Git availability changes. Inform agents through the owned native `codenomad.git-availability` instruction before prompts/custom commands, remove stale context after recovery, and keep this advisory separate from fail-closed environment synchronization. Do not add a blocking Git setup UI. Validate with `scripts/test-git-degraded-native.mjs` using an isolated CLI/database and provider. - Temporary instances (`workspaces/temporary-workspaces.ts`, UI `stores/temporary-instances.ts`) are ordinary non-Git workspaces on CodeNomad-created direct children of `/temporary-workspaces`. Registry membership (`temporary-workspaces.json`), not location, makes a folder temporary; keeping only unregisters it and adds a named recent project. Discard deletes only registered children of that root, refuses running conversations and other open tabs of the folder, removes conversations deepest-first, closes the workspace before deleting the folder and keeps failed removals registered; such a folder is reachable only by browsing to it. Closing a temporary tab from the UI asks Keep/Discard/Cancel, except that an untouched one (no conversation, file or unsent draft) closes and is discarded silently (`onlyIfEmpty`: the server refuses with `temporary_has_conversations`/`temporary_not_empty`, and any failure of that quiet discard returns the choice without an error). Before the server stops it, a visible temporary tab yields to its neighbour (or closes if alone) and a refusal restores it in place; `workspace.stopped` likewise closes the tab first and clears the instance in a microtask, because clearing a visible shell's state in the same update as its tab freezes the window. Same-minute names get a `(n)` suffix. Registry changes broadcast `workspace.temporaryChanged`, which clears kept marks in every window. Open temporary tabs are saved and restored with the app state like any project tab (still marked temporary). Only the choice dialog overrides initial focus (to its last, non-destructive choice); confirms keep focus on Cancel. Refusals use stable `temporary_*` codes localized by the client. Validate with `scripts/test-temporary-workspaces-native.mjs` against an isolated CLI. - The tab-bar new-instance button follows the last tab like a browser: the instance `TabScroll` frame only spans its tabs and the button sits after it, outside the scroller (so focusing it never scrolls the strip), ending up at the strip's end once tabs overflow. Dragged tabs stay visually within the tab list like a browser's (`KeepDraggedTabInStrip`), while the drop slot follows the pointer's unbounded position (`closestUnboundedCenter`). The button keeps its click (full home page, Cmd/Ctrl+N) while a long press, right-click, Alt+Down, Shift+F10 or Menu opens the anchored `NewInstanceLauncher` (`lib/long-press.ts`; only Escape returns focus to the button, never over another surface or the home page): search-first recent projects (an open project switches to its tab), Browse/Temporary/Clone and the folded Remotes list. SideCar and management (rename/remove recents, servers, settings) stay on the home page. Browse/clone flows live once in `components/new-instance-dialogs.tsx` (with optional home-only add-server setup) and recent-folder display helpers in `lib/recent-folder-display.ts`, shared with `FolderSelectionView`; styles in `styles/components/new-instance-launcher.css`. -- Remote project tabs show one project of a saved remote CodeNomad server inside a local window. Remotes (`components/remote-project-menu.tsx`, home page and launcher, host windows only: `canOpenRemoteWindows()`) lists the saved server profiles; its field adds one from a pasted pairing link or address (`lib/codenomad-link.ts`, refusing links with credentials) through the existing probe. Choosing a server opens a `remote-project` app tab (`stores/remote-project-tabs.ts`, actions in `stores/remote-project-open.ts`) whose `RemoteProjectView` places a native view (Electron `WebContentsView`, `electron/main/remote-view.ts`; Tauri child webview on Windows, `src-tauri/src/remote_view.rs`) over its content area; elsewhere, and for profiles that skip TLS verification, the server keeps its separate remote window. The view uses that server's remote-window storage (Electron partition, Tauri data directory), so its session or paired device cookie is reused without signing in again, and the remote preload/capability: of native access only notifications reach the host (badges and every local command are refused). It stays on the server's origin, the public help site opening in the system browser; a navigation to the bare root (end of login or pairing) returns to the tab's entry. Under Tauri every navigation also passes the app-wide `external-link-guard` plugin after the view's own handler: `intercept_navigation` asks `RemoteViews::navigation_allowed` first for registered `remote-view-*` labels, since the window-origin rules would cancel the view's first load. The view opens the first time its tab shows, follows the placeholder's bounds and hides while its tab is hidden or a local dialog, menu or list is open (`localOverlayOpen()`, shared with browser previews); a reload or close of the owning page closes its views. The remote page runs in embedded single-project mode (`lib/embed-mode.ts`, `/?codenomadEmbed=project[&folder=…]`): no title bar, tab bar or home page, a folder picker (`components/embedded-project-picker.tsx`) until a project opens, no native badge; it records the folder in its address and the project name in `document.title`. The host accepts a title change only from the server's origin with a folder in the address, so a server without this mode shows its full interface and the tab keeps the server's name. Tabs restore as `{kind: "remote-project", profileId, folder?}` (a removed or window-only server drops its tab); projects opened in tabs join this host's recents beside local folders (`ui` state `remoteProjectRecents`, server, folder and name only; removing a server forgets them and closes its tabs). Covered by `tests/browser/remote-project-tabs.test.ts`, `electron/main/remote-view.test.ts` and `remote_view.rs` tests (navigation, ownership, ACL of the child label). +- Remote project tabs show one project of a saved remote CodeNomad server inside a local window. Remotes (`components/remote-project-menu.tsx`, home page and launcher, host windows only: `canOpenRemoteWindows()`) lists the saved server profiles; its field adds one from a pasted pairing link or address (`lib/codenomad-link.ts`, refusing links with credentials) through the existing probe. Choosing a server opens a `remote-project` app tab (`stores/remote-project-tabs.ts`, actions in `stores/remote-project-open.ts`) whose `RemoteProjectView` places a native view (Electron `WebContentsView`, `electron/main/remote-view.ts`; Tauri child webview on Windows, `src-tauri/src/remote_view.rs`) over its content area; elsewhere, and for profiles that skip TLS verification, the server keeps its separate remote window. The view uses that server's remote-window storage (Electron partition, Tauri data directory), so its session or paired device cookie is reused without signing in again, and the remote preload/capability: of native access only notifications reach the host (badges and every local command are refused). It stays on the server's origin, the public help site opening in the system browser; a navigation to the bare root (end of login or pairing) returns to the tab's entry. Under Tauri every navigation also passes the app-wide `external-link-guard` plugin after the view's own handler: `intercept_navigation` asks `RemoteViews::navigation_allowed` first for registered `remote-view-*` labels, since the window-origin rules would cancel the view's first load. The view opens the first time its tab shows, follows the placeholder's bounds and hides while its tab is hidden or a local dialog, menu or list is open (`localOverlayOpen()`, shared with browser previews); a reload or close of the owning page closes its views. The remote page runs in embedded single-project mode (`lib/embed-mode.ts`, `/?codenomadEmbed=project[&folder=…]`): no title bar, tab bar or home page, a folder picker (`components/embedded-project-picker.tsx`) until a project opens, no native badge; it records the folder in its address and the project name in `document.title`, and keeps its active session per folder in its own persistent storage (`rememberEmbeddedSession`), reselected on reopening through the restored-tab hydration (`stores/embedded-project-session.ts`). A direct-access password sign-in lasts `PASSWORD_SESSION_TTL_MS` (seven days) with a matching cookie `Max-Age`, so the view stays signed in across host restarts while the server runs; logout revokes it server-side; bootstrap-token sessions keep browser-session cookies. The host accepts a title change only from the server's origin with a folder in the address, so a server without this mode shows its full interface and the tab keeps the server's name. Tabs restore as `{kind: "remote-project", profileId, folder?}` (a removed or window-only server drops its tab); projects opened in tabs join this host's recents beside local folders (`ui` state `remoteProjectRecents`, server, folder and name only; removing a server forgets them and closes its tabs). Covered by `tests/browser/remote-project-tabs.test.ts`, `electron/main/remote-view.test.ts` and `remote_view.rs` tests (navigation, ownership, ACL of the child label). - The clone dialog (`components/new-instance-dialogs.tsx`) suggests the repository's `git clone` folder name (`lib/clone-destination.ts`) inside a parent: the folder chosen with Browse, else the server-scoped `ui` state `lastCloneParent` (the folder above the last successful clone), else the folder above the most recent project. A destination the user types is kept as entered and sent unchanged; the server creates it. diff --git a/packages/ui/src/App.tsx b/packages/ui/src/App.tsx index 0f88a74c50..d88acd6321 100644 --- a/packages/ui/src/App.tsx +++ b/packages/ui/src/App.tsx @@ -20,7 +20,8 @@ import { SideCarPickerDialog } from "./components/sidecar-picker-dialog" import { SideCarView } from "./components/sidecar-view" import { RemoteProjectView } from "./components/remote-project-view" import { EmbeddedProjectPicker } from "./components/embedded-project-picker" -import { embeddedProject, publishEmbeddedProject } from "./lib/embed-mode" +import { embeddedProject, publishEmbeddedProject, rememberEmbeddedSession, rememberedEmbeddedSession } from "./lib/embed-mode" +import { restoreEmbeddedSession } from "./stores/embedded-project-session" import { closeRemoteProjectTab } from "./stores/remote-project-tabs" import { InstanceMetadataProvider } from "./lib/contexts/instance-metadata-context" import { showAlertDialog } from "./stores/alerts" @@ -519,11 +520,32 @@ const App: Component = () => { // then publishes the project it shows for its host tab. if (embeddedProject) { const folder = embeddedProject.folder - if (folder) onMount(() => void waitForInitialWorkspaceLoad().catch(() => {}).then(() => handleSelectFolder(folder))) + // Until the remembered session is restored, the empty startup selection is not the user's choice. + const [sessionRestorePending, setSessionRestorePending] = createSignal(Boolean(folder)) + if (folder) onMount(() => void (async () => { + try { + await waitForInitialWorkspaceLoad().catch(() => {}) + if (!await handleSelectFolder(folder)) return + const instance = activeInstance() + const remembered = instance ? rememberedEmbeddedSession(instance.folder) : undefined + if (instance && remembered) await restoreEmbeddedSession(instance.id, instance.folder, remembered) + } catch (error) { + log.warn("Failed to restore the embedded project's session", error) + } finally { + setSessionRestorePending(false) + } + })()) createEffect(() => { const instance = activeInstance() if (instance && !instance.temporary) publishEmbeddedProject(instance.folder, getProjectNameForFolder(instance.folder)) }) + createEffect(() => { + const instance = activeInstance() + const sessionId = activeSessionIdForInstance() + if (instance && !instance.temporary && sessionId && sessionId !== "info" && !sessionRestorePending()) { + rememberEmbeddedSession(instance.folder, sessionId) + } + }) } async function handleNewTemporaryInstance(): Promise { diff --git a/packages/ui/src/lib/embed-mode.test.ts b/packages/ui/src/lib/embed-mode.test.ts index 9b84f5fc66..3564a668b0 100644 --- a/packages/ui/src/lib/embed-mode.test.ts +++ b/packages/ui/src/lib/embed-mode.test.ts @@ -1,6 +1,44 @@ import assert from "node:assert/strict" import { describe, it } from "node:test" -import { embeddedProjectUrl, readEmbeddedProject, readEmbeddedProjectReport } from "./embed-mode.ts" +import { + embeddedProjectUrl, readEmbeddedProject, readEmbeddedProjectReport, rememberEmbeddedSession, rememberedEmbeddedSession, +} from "./embed-mode.ts" + +function memoryStorage(): Storage { + const values = new Map() + return { + get length() { return values.size }, + clear: () => values.clear(), + getItem: (key) => values.get(key) ?? null, + key: (index) => [...values.keys()][index] ?? null, + removeItem: (key) => { values.delete(key) }, + setItem: (key, value) => { values.set(key, String(value)) }, + } +} + +describe("embedded active session memory", () => { + it("keeps one valid session per folder in the page's own storage", () => { + const storage = memoryStorage() + assert.equal(rememberedEmbeddedSession("/srv/app", storage), undefined) + rememberEmbeddedSession("/srv/app", "ses_abc-1", storage) + rememberEmbeddedSession("/srv/other", "ses_other", storage) + assert.equal(rememberedEmbeddedSession("/srv/app", storage), "ses_abc-1") + rememberEmbeddedSession("/srv/app", "ses_newer", storage) + assert.equal(rememberedEmbeddedSession("/srv/app", storage), "ses_newer") + assert.equal(rememberedEmbeddedSession("/srv/other", storage), "ses_other") + // Malformed identifiers are neither written nor trusted when read back. + rememberEmbeddedSession("/srv/app", "../../x", storage) + assert.equal(rememberedEmbeddedSession("/srv/app", storage), "ses_newer") + storage.setItem("codenomad:embedded-session:/srv/bad", "` let server: ViteDevServer, browser: Browser, url: string @@ -34,34 +34,33 @@ before(async () => { }) after(async () => { await browser?.close(); await server?.close() }) -async function submit(page: Page, address: string, button: "Save" | "Connect") { - await page.getByLabel("Name").fill("Desk") - await page.getByLabel("Server URL").fill(address) - await page.getByRole("button", { name: button, exact: true }).click() +// Settings → Servers' inline field: Enter adds the address or link. +async function add(page: Page, address: string) { + const field = page.getByRole("textbox", { name: "Server address or link" }) + await field.fill(address) + await field.press("Enter") } const opened = (page: Page) => page.evaluate(() => (window as unknown as { opened: Array<{ id: string; baseUrl: string; entryUrl?: string }> }).opened) -test("a pasted pairing link saves only the server and pairs in the window it opens", async () => { +test("a pairing link saves only the server and pairs in the window it opens, even where adding only saves", async () => { const page = await browser.newPage({ viewport: { width: 900, height: 900 }, locale: "en-US" }) const errors: string[] = [] page.on("pageerror", error => errors.push(error.message)) try { await page.goto(url) - await page.getByText("A server address, or a Remote Control pairing link created on that computer.", { exact: true }).waitFor() - // Skipping TLS checks would later route Tauri through the incognito proxy store and lose the pairing. - await page.getByLabel("Skip TLS verification for self-signed certificates.").check() - // Save, not Connect: the single-use code would otherwise be lost. - await submit(page, LINK, "Save") + await add(page, LINK) await page.waitForFunction(() => (window as unknown as { opened: unknown[] }).opened.length === 1) const [payload] = await opened(page) assert.equal(payload.baseUrl, TUNNEL) assert.equal(payload.entryUrl, LINK) + // Skipping TLS checks would later route Tauri through the incognito proxy store and lose the pairing. assert.equal((payload as { skipTlsVerify?: boolean }).skipTlsVerify, false) assert.deepEqual(await page.evaluate(() => (window as unknown as { probes: string[] }).probes), [`${TUNNEL} skipTls=false`]) const state = JSON.parse(await page.evaluate(() => (window as unknown as { uiState: () => string }).uiState())) assert.equal(JSON.stringify(state).includes("single-use-code"), false) - assert.deepEqual(state.remoteServers.map((server: { baseUrl: string; skipTlsVerify: boolean }) => [server.baseUrl, server.skipTlsVerify]), [[TUNNEL, false]]) + assert.deepEqual(state.remoteServers.map((server: { baseUrl: string; skipTlsVerify: boolean; name: string }) => [server.baseUrl, server.skipTlsVerify]), [[TUNNEL, false]]) + assert.equal(await page.getByRole("textbox", { name: "Server address or link" }).inputValue(), "", "the field clears once added") assert.deepEqual(errors, []) } finally { await page.close() } }) @@ -71,19 +70,19 @@ test("pairing a saved server again reuses it instead of adding a duplicate", asy try { await page.goto(`${url}?scenario=saved`) await page.getByTestId("servers").getByText(`saved-tunnel ${TUNNEL}`).waitFor() - await submit(page, LINK, "Connect") + await add(page, LINK) await page.waitForFunction(() => (window as unknown as { opened: unknown[] }).opened.length === 1) assert.equal((await opened(page))[0].id, "saved-tunnel") assert.equal(await page.getByTestId("servers").locator("li").count(), 1) } finally { await page.close() } }) -test("an ordinary address saved without Connect opens no window", async () => { +test("an ordinary address added in Settings is saved without opening a window", async () => { const page = await browser.newPage({ viewport: { width: 900, height: 900 }, locale: "en-US" }) try { await page.goto(url) - await submit(page, "https://server.example.com", "Save") + await add(page, "https://server.example.com") await page.getByTestId("servers").getByText("https://server.example.com").waitFor() assert.deepEqual(await opened(page), []) } finally { await page.close() } -}) +}) \ No newline at end of file From 3cf7f910b81e74adaaf3b50c195bc721badda505 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Thu, 5 Nov 2026 21:54:15 +0100 Subject: [PATCH 16/34] docs(remote): add servers through Browse's inline field Remote Access: servers are added by pasting an address or pairing link into Server address or link under Browse (also in Settings -> Servers); a failed certificate check offers Skip TLS verification under the field and opens the server in its own window; servers are renamed in Settings -> Servers. Remote Control: a desktop pairs by pasting the link into that field. The --connect-server paragraph no longer names the removed Connect button. All ten locales use their UI labels. PROJECTS.md and REMOTE_CONTROL.md describe the inline field and the edit-only server dialog. Validation: npm run test:help passes. --- dev-docs/PROJECTS.md | 4 ++-- dev-docs/REMOTE_CONTROL.md | 8 ++++---- docs/help/de/remote-access.md | 12 ++++++------ docs/help/de/remote-control.md | 2 +- docs/help/en/remote-access.md | 12 ++++++------ docs/help/en/remote-control.md | 2 +- docs/help/es/remote-access.md | 12 ++++++------ docs/help/es/remote-control.md | 2 +- docs/help/fr/remote-access.md | 12 ++++++------ docs/help/fr/remote-control.md | 2 +- docs/help/he/remote-access.md | 12 ++++++------ docs/help/he/remote-control.md | 2 +- docs/help/ja/remote-access.md | 12 ++++++------ docs/help/ja/remote-control.md | 2 +- docs/help/ne/remote-access.md | 12 ++++++------ docs/help/ne/remote-control.md | 2 +- docs/help/ru/remote-access.md | 12 ++++++------ docs/help/ru/remote-control.md | 2 +- docs/help/tr/remote-access.md | 12 ++++++------ docs/help/tr/remote-control.md | 2 +- docs/help/zh-Hans/remote-access.md | 12 ++++++------ docs/help/zh-Hans/remote-control.md | 2 +- 22 files changed, 76 insertions(+), 76 deletions(-) diff --git a/dev-docs/PROJECTS.md b/dev-docs/PROJECTS.md index 6309b516b5..99d2f39beb 100644 --- a/dev-docs/PROJECTS.md +++ b/dev-docs/PROJECTS.md @@ -7,6 +7,6 @@ Closing project tabs, temporary workspaces, the new-instance launcher and the Gi - Closing a project tab detaches it immediately and requests deletion of that occurrence's logical backend workspace record; failures notify and never retry automatically. Separate occurrences of the same folder are independent. A `workspace.stopped` deletion closes the same record in other windows and notifies only windows displaying it that did not initiate the close. CodeNomad never evicts native Locations; OpenCode sessions keep running and reopening finds them. Whole-window close, app quit, renderer reload and backend shutdown keep existing restoration behavior. Temporary discard and server stop events use local-only tab detachment, not another DELETE; Keep closes the retained project normally. - Git is a full-functionality prerequisite, with directory-only degraded conversations when the backend cannot find Git. Only the explicitly opened physical folder is session authority in that mode; never infer sibling worktrees from native project IDs. Keep ancestor/descendant mutation identities covered by the deletion fence across Git availability changes. Inform agents through the owned native `codenomad.git-availability` instruction before prompts/custom commands, remove stale context after recovery, and keep this advisory separate from fail-closed environment synchronization. Do not add a blocking Git setup UI. Validate with `scripts/test-git-degraded-native.mjs` using an isolated CLI/database and provider. - Temporary instances (`workspaces/temporary-workspaces.ts`, UI `stores/temporary-instances.ts`) are ordinary non-Git workspaces on CodeNomad-created direct children of `/temporary-workspaces`. Registry membership (`temporary-workspaces.json`), not location, makes a folder temporary; keeping only unregisters it and adds a named recent project. Discard deletes only registered children of that root, refuses running conversations and other open tabs of the folder, removes conversations deepest-first, closes the workspace before deleting the folder and keeps failed removals registered; such a folder is reachable only by browsing to it. Closing a temporary tab from the UI asks Keep/Discard/Cancel, except that an untouched one (no conversation, file or unsent draft) closes and is discarded silently (`onlyIfEmpty`: the server refuses with `temporary_has_conversations`/`temporary_not_empty`, and any failure of that quiet discard returns the choice without an error). Before the server stops it, a visible temporary tab yields to its neighbour (or closes if alone) and a refusal restores it in place; `workspace.stopped` likewise closes the tab first and clears the instance in a microtask, because clearing a visible shell's state in the same update as its tab freezes the window. Same-minute names get a `(n)` suffix. Registry changes broadcast `workspace.temporaryChanged`, which clears kept marks in every window. Open temporary tabs are saved and restored with the app state like any project tab (still marked temporary). Only the choice dialog overrides initial focus (to its last, non-destructive choice); confirms keep focus on Cancel. Refusals use stable `temporary_*` codes localized by the client. Validate with `scripts/test-temporary-workspaces-native.mjs` against an isolated CLI. -- The tab-bar new-instance button follows the last tab like a browser: the instance `TabScroll` frame only spans its tabs and the button sits after it, outside the scroller (so focusing it never scrolls the strip), ending up at the strip's end once tabs overflow. Dragged tabs stay visually within the tab list like a browser's (`KeepDraggedTabInStrip`), while the drop slot follows the pointer's unbounded position (`closestUnboundedCenter`). The button keeps its click (full home page, Cmd/Ctrl+N) while a long press, right-click, Alt+Down, Shift+F10 or Menu opens the anchored `NewInstanceLauncher` (`lib/long-press.ts`; only Escape returns focus to the button, never over another surface or the home page): titled Open a tab, it is the home page's logic in short: the search, the collapsible Recent section (unfolded by default and kept per window; chevron first, like Browse; Escape on its title folds it without closing the launcher; typing or an arrow in the search unfolds it; an open project switches to its tab), the folded Browse section, then Clone and New temporary tab only. Recents are local projects, remote projects and SideCars (`launchableRecents`, `filterRecents` for both search fields, `components/recent-tab-icon.tsx`); a SideCar joins them when it opens (`stores/sidecar-open.ts`), stored as `ui` state `sidecarRecents` with its id and time only, never an address or proxy token, and listed while still configured. The home page's right card has two tabs, Recent (with the same search; arrows move between the tabs) and Browse (the list always open); its left column holds only the creation buttons of `components/new-tab-actions.tsx`: Clone a Git repository, New temporary tab, New server (host windows only; the server dialog) and New SideCar (`openSettingsRow("sidecars", "sidecar-add")`, the SideCar form's name field). The launcher's `variant` keeps only the first two. Renaming and removing recent tabs stay on the home page; servers are managed in Settings → Servers, SideCars in Settings → SideCars. Browse/clone flows live once in `components/new-instance-dialogs.tsx` and recent-folder display helpers in `lib/recent-folder-display.ts`, shared with `FolderSelectionView`; styles in `styles/components/new-instance-launcher.css`. -- Remote project tabs show one project of a saved remote CodeNomad server inside a local window. Browse (`components/browse-menu.tsx`, the home page's Browse tab with `alwaysOpen` and the launcher's folded section, its disclosure state shared per window) lists This computer (the native dialog or folder browser), then, in host windows only (`canOpenRemoteWindows()`), each saved server profile, then each configured SideCar with its state (a stopped one cannot open), then, in host windows, Add server… last; it offers no management (no context menu). Add server… and the home page's New server (`components/new-tab-actions.tsx`) open `RemoteServerDialog` through `components/remote-server-editor.tsx` (state `stores/remote-server-editor.ts`), mounted once in `App` because the launcher unmounts as it closes. The dialog takes an address or a pairing link (`lib/remote-pairing-link.ts`); the name is optional (`codeNomadLinkName`), an address carrying credentials is refused, an address already saved reuses its profile, and a probe failing with `tls_error` shows its error so the user can skip TLS verification, which saves a window-only profile. Settings → Servers (`settings/servers-settings-section.tsx`, host windows only) is the one management surface: open, edit and remove (confirmed) each server, and add one, through the same dialog with `submitServer` (`lib/hooks/use-remote-server-profiles.ts`). Saving keeps the profile id, so its storage and sign-in stay, and a rename with the same URL and TLS setting skips the probe (`saveProfile`). Opening from the native Preferences window, which has no tabs, opens the server's window. Sign-in happens on the server's own page; the view's storage keeps it across launches. Servers read as `serverDisplayName` (`lib/codenomad-link.ts`): the saved name, or the host name when that name is a raw address (pasted servers are saved under `url.host`), with the port only when another saved server shares the host name; Browse, recents, Settings → Servers and a tab whose project is not chosen yet use it. Choosing a server opens a `remote-project` app tab (`stores/remote-project-tabs.ts`, actions in `stores/remote-project-open.ts`) whose `RemoteProjectView` places a native view (Electron `WebContentsView`, `electron/main/remote-view.ts`; Tauri child webview on Windows, `src-tauri/src/remote_view.rs`) over its content area; elsewhere, and for profiles that skip TLS verification, the server keeps its separate remote window. The view uses that server's remote-window storage (Electron partition, Tauri data directory), so its session or paired device cookie is reused without signing in again, and the remote preload/capability: of native access only notifications reach the host (badges and every local command are refused). It stays on the server's origin, the public help site opening in the system browser; a navigation to the bare root (end of login or pairing) returns to the tab's entry. Under Tauri every navigation also passes the app-wide `external-link-guard` plugin after the view's own handler: `intercept_navigation` asks `RemoteViews::navigation_allowed` first for registered `remote-view-*` labels, since the window-origin rules would cancel the view's first load. The view opens the first time its tab shows, follows the placeholder's bounds and hides while its tab is hidden or a local dialog, menu or list is open (`localOverlayOpen()`, shared with browser previews); a reload or close of the owning page closes its views. The remote page runs in embedded single-project mode (`lib/embed-mode.ts`, `/?codenomadEmbed=project[&folder=…]`): no title bar, tab bar or home page, a folder picker (`components/embedded-project-picker.tsx`) until a project opens, no native badge; it records the folder in its address and the project name in `document.title`, and keeps its active session per folder in its own persistent storage (`rememberEmbeddedSession`), reselected on reopening through the restored-tab hydration (`stores/embedded-project-session.ts`). A direct-access password sign-in lasts `PASSWORD_SESSION_TTL_MS` (seven days) with a matching cookie `Max-Age`, so the view stays signed in across host restarts while the server runs; logout revokes it server-side; bootstrap-token sessions keep browser-session cookies. The host accepts a title change only from the server's origin with a folder in the address, so a server without this mode shows its full interface and the tab keeps the server's name. Tabs restore as `{kind: "remote-project", profileId, folder?}` (a removed or window-only server drops its tab); projects opened in tabs join this host's recents beside local folders (`ui` state `remoteProjectRecents`, server, folder and name only; removing a server forgets them and closes its tabs). Covered by `tests/browser/remote-project-tabs.test.ts`, `electron/main/remote-view.test.ts` and `remote_view.rs` tests (navigation, ownership, ACL of the child label). +- The tab-bar new-instance button follows the last tab like a browser: the instance `TabScroll` frame only spans its tabs and the button sits after it, outside the scroller (so focusing it never scrolls the strip), ending up at the strip's end once tabs overflow. Dragged tabs stay visually within the tab list like a browser's (`KeepDraggedTabInStrip`), while the drop slot follows the pointer's unbounded position (`closestUnboundedCenter`). The button keeps its click (full home page, Cmd/Ctrl+N) while a long press, right-click, Alt+Down, Shift+F10 or Menu opens the anchored `NewInstanceLauncher` (`lib/long-press.ts`; only Escape returns focus to the button, never over another surface or the home page): titled Open a tab, it is the home page's logic in short: the search, the collapsible Recent section (unfolded by default and kept per window; chevron first, like Browse; Escape on its title folds it without closing the launcher; typing or an arrow in the search unfolds it; an open project switches to its tab), the folded Browse section, then Clone and New temporary tab only. Recents are local projects, remote projects and SideCars (`launchableRecents`, `filterRecents` for both search fields, `components/recent-tab-icon.tsx`); a SideCar joins them when it opens (`stores/sidecar-open.ts`), stored as `ui` state `sidecarRecents` with its id and time only, never an address or proxy token, and listed while still configured. The home page's right card has two tabs, Recent (with the same search; arrows move between the tabs) and Browse (the list always open); its left column holds only the creation buttons of `components/new-tab-actions.tsx`: Clone a Git repository, New temporary tab and New SideCar (`openSettingsRow("sidecars", "sidecar-add")`, the SideCar form's name field); servers are added in Browse. The launcher's `variant` keeps only the first two. Renaming and removing recent tabs stay on the home page; servers are managed in Settings → Servers, SideCars in Settings → SideCars. Browse/clone flows live once in `components/new-instance-dialogs.tsx` and recent-folder display helpers in `lib/recent-folder-display.ts`, shared with `FolderSelectionView`; styles in `styles/components/new-instance-launcher.css`. +- Remote project tabs show one project of a saved remote CodeNomad server inside a local window. Browse (`components/browse-menu.tsx`, the home page's Browse tab with `alwaysOpen` and the launcher's folded section, its disclosure state shared per window) lists This computer (the native dialog or folder browser), then, in host windows only (`canOpenRemoteWindows()`), each saved server profile, then each configured SideCar with its state (a stopped one cannot open), then, in host windows, the inline address field last; it offers no management (no context menu). Servers are added only through that field (`components/server-add-field.tsx`), never a floating dialog: an address or a Remote Control pairing link (`lib/codenomad-link.ts`, `lib/remote-pairing-link.ts`) goes through `submitServer` (`lib/hooks/use-remote-server-profiles.ts`) and the probe, is saved under its host (`codeNomadLinkName`) and opens at once (its tab, else its window; the launcher closes then). Pasting a valid link adds it immediately; Enter or + submits typed text. An address already saved reuses its profile; an address carrying credentials or unreadable text shows a short error under the field; only a probe failing with `tls_error` on an address adds the Skip TLS verification checkbox, confirmed through the same field, which saves a window-only profile. Settings → Servers (`settings/servers-settings-section.tsx`, host windows only) is the one management surface: the same field adds a server without opening it (`open={false}`; a pairing link still opens, since that consumes its code), and each server is opened, edited through `RemoteServerDialog` (edit only: address, name, certificate check) and removed (confirmed). Saving keeps the profile id, so its storage and sign-in stay, and a rename with the same URL and TLS setting skips the probe (`saveProfile`). Opening from the native Preferences window, which has no tabs, opens the server's window. Sign-in happens on the server's own page; the view's storage keeps it across launches. Servers read as `serverDisplayName` (`lib/codenomad-link.ts`): the saved name, or the host name when that name is a raw address (pasted servers are saved under `url.host`), with the port only when another saved server shares the host name; Browse, recents, Settings → Servers and a tab whose project is not chosen yet use it. Choosing a server opens a `remote-project` app tab (`stores/remote-project-tabs.ts`, actions in `stores/remote-project-open.ts`) whose `RemoteProjectView` places a native view (Electron `WebContentsView`, `electron/main/remote-view.ts`; Tauri child webview on Windows, `src-tauri/src/remote_view.rs`) over its content area; elsewhere, and for profiles that skip TLS verification, the server keeps its separate remote window. The view uses that server's remote-window storage (Electron partition, Tauri data directory), so its session or paired device cookie is reused without signing in again, and the remote preload/capability: of native access only notifications reach the host (badges and every local command are refused). It stays on the server's origin, the public help site opening in the system browser; a navigation to the bare root (end of login or pairing) returns to the tab's entry. Under Tauri every navigation also passes the app-wide `external-link-guard` plugin after the view's own handler: `intercept_navigation` asks `RemoteViews::navigation_allowed` first for registered `remote-view-*` labels, since the window-origin rules would cancel the view's first load. The view opens the first time its tab shows, follows the placeholder's bounds and hides while its tab is hidden or a local dialog, menu or list is open (`localOverlayOpen()`, shared with browser previews); a reload or close of the owning page closes its views. The remote page runs in embedded single-project mode (`lib/embed-mode.ts`, `/?codenomadEmbed=project[&folder=…]`): no title bar, tab bar or home page, a folder picker (`components/embedded-project-picker.tsx`) until a project opens, no native badge; it records the folder in its address and the project name in `document.title`, and keeps its active session per folder in its own persistent storage (`rememberEmbeddedSession`), reselected on reopening through the restored-tab hydration (`stores/embedded-project-session.ts`). A direct-access password sign-in lasts `PASSWORD_SESSION_TTL_MS` (seven days) with a matching cookie `Max-Age`, so the view stays signed in across host restarts while the server runs; logout revokes it server-side; bootstrap-token sessions keep browser-session cookies. The host accepts a title change only from the server's origin with a folder in the address, so a server without this mode shows its full interface and the tab keeps the server's name. Tabs restore as `{kind: "remote-project", profileId, folder?}` (a removed or window-only server drops its tab); projects opened in tabs join this host's recents beside local folders (`ui` state `remoteProjectRecents`, server, folder and name only; removing a server forgets them and closes its tabs). Covered by `tests/browser/remote-project-tabs.test.ts`, `electron/main/remote-view.test.ts` and `remote_view.rs` tests (navigation, ownership, ACL of the child label). - The clone dialog (`components/new-instance-dialogs.tsx`) suggests the repository's `git clone` folder name (`lib/clone-destination.ts`) inside a parent: the folder chosen with Browse, else the server-scoped `ui` state `lastCloneParent` (the folder above the last successful clone), else the folder above the most recent project. A destination the user types is kept as entered and sent unchanged; the server creates it. diff --git a/dev-docs/REMOTE_CONTROL.md b/dev-docs/REMOTE_CONTROL.md index 7d8b593877..e8125e17a6 100644 --- a/dev-docs/REMOTE_CONTROL.md +++ b/dev-docs/REMOTE_CONTROL.md @@ -82,9 +82,9 @@ browser ─TLS─▶ OpenTunnel relay (forwards ciphertext) ─▶ OpenTunnel SD only once Remote Control is used. - Remote devices authenticate even with `--dangerously-skip-auth`, and the local session cookie is never accepted on the ingress. -- A desktop CodeNomad pairs as a device: pasting a pairing link into the server - dialog (New server on the home page or in the launcher, or Settings → Servers) saves only the tunnel - origin and opens the server once on the link, even from Save +- A desktop CodeNomad pairs as a device: pasting a pairing link into the inline server + field (Browse on the home page or in the launcher, or Settings → Servers) saves only the tunnel + origin and opens the server once on the link, even where adding only saves (`lib/remote-pairing-link.ts`). The profile keeps TLS verification on, since a Tauri TLS-proxy window uses an incognito store without the device cookie. The code is never stored with the server; @@ -97,7 +97,7 @@ browser ─TLS─▶ OpenTunnel relay (forwards ciphertext) ─▶ OpenTunnel SD - `--connect-server` opens a saved server or URL at launch through that same connect flow ([architecture.md](architecture.md#native-profiles-windows-and-client-state)). It refuses URLs with user info or a fragment, so a pairing code or password - never travels on a command line; pair from New server instead. + never travels on a command line; pair from Browse instead. ## Validation diff --git a/docs/help/de/remote-access.md b/docs/help/de/remote-access.md index 52019111b1..858baf1a7c 100644 --- a/docs/help/de/remote-access.md +++ b/docs/help/de/remote-access.md @@ -83,23 +83,23 @@ Meldet ein Client eine Zertifikatswarnung, halten Sie an und prüfen Sie Hostnam ## Remote-Server speichern {#saved-servers} -1. Wählen Sie auf der Desktop-Startseite **Neuer Server** oder am Ende von **Durchsuchen** den Eintrag **Server hinzufügen…**, auf der Startseite oder im Starter **Tab öffnen**. **Einstellungen → Server** bietet dasselbe mit **Server hinzufügen…**. -2. Geben Sie in **Mit Server verbinden** unter **Server-URL** einen vertrauenswürdigen HTTPS-Ursprung oder einen Kopplungslink ein. **Servername** ist optional; ohne ihn zeigt der Server seinen Hostnamen. Lassen Sie **TLS-Verifizierung für selbstsignierte Zertifikate überspringen.** deaktiviert; stellen Sie stattdessen Vertrauen her. Besteht das Zertifikat die Prüfung nicht, meldet der Dialog dies. -3. Wählen Sie **Speichern** für ein Lesezeichen oder **Verbinden** zum Speichern und Öffnen. Melden Sie sich auf diesem Server an. +1. Öffnen Sie auf der Desktop-Startseite oder im Starter **Tab öffnen** den Bereich **Durchsuchen**, fügen Sie die Adresse des Servers oder einen Kopplungslink in **Serveradresse oder -link** ein und drücken Sie die Eingabetaste: Der Server wird unter seinem Hostnamen gespeichert und öffnet sich. **Einstellungen → Server** bietet dasselbe Feld. +2. Verwenden Sie einen vertrauenswürdigen HTTPS-Ursprung. Besteht sein Zertifikat die Prüfung nicht, erscheint der Fehler unter dem Feld mit **TLS-Prüfung überspringen**: Aktivieren Sie dies nur für einen vertrauenswürdigen Server und drücken Sie erneut die Eingabetaste; dieser Server öffnet sich in einem eigenen Fenster. +3. Melden Sie sich auf diesem Server an. Benennen Sie ihn um oder ändern Sie seine Adresse mit **Server bearbeiten** unter **Einstellungen → Server**. Gespeicherte Server stehen unter **Durchsuchen**: Wählen Sie einen, um ihn erneut zu öffnen. In **Einstellungen → Server** öffnen, bearbeiten (**Server bearbeiten**: Name, Adresse, Zertifikatsprüfung) und entfernen (**Gespeicherten Server entfernen**) Sie sie. Lesezeichen gehören zu dieser CodeNomad-Konfiguration, nicht den Projekten des Remote-Servers. Eine URL zu speichern startet keinen Server und gewährt keinen Zugriff. **Gespeicherten Server entfernen** entfernt das Lesezeichen, nicht entfernte Unterhaltungen, Backend oder Zugangsdaten. -Um einen gespeicherten Server direkt von der Befehlszeile zu öffnen, starten Sie die Desktop-App mit `--connect-server ` (oder `--connect-server=`) und dem gespeicherten Namen des Servers oder seiner `https://`-URL. CodeNomad öffnet nur das Remote-Fenster, mit denselben Prüfungen und derselben Anmeldung wie **Verbinden**; läuft CodeNomad bereits, öffnet sein aktuelles Fenster den Server statt eines neuen Fensters. Eine URL, die zu keinem gespeicherten Server passt, wird unter ihrem Hostnamen gespeichert. Startwerte enthalten nie Zugangsdaten: Eine URL mit Benutzername, Passwort oder Kopplungscode wird abgelehnt. Ist der Name unbekannt, die URL ungültig oder schlägt die Verbindung fehl, startet CodeNomad normal und zeigt den Fehler an. Braucht die Verbindung eine Bestätigung, etwa die Installation des lokalen Zertifikats für einen selbstsignierten Server, startet CodeNomad ebenfalls normal und fragt dort nach. Unter Windows startet der Tauri-Build nicht, wenn ein Startargument `|` enthält; verwenden Sie stattdessen die URL des Servers oder benennen Sie den Server um. +Um einen gespeicherten Server direkt von der Befehlszeile zu öffnen, starten Sie die Desktop-App mit `--connect-server ` (oder `--connect-server=`) und dem gespeicherten Namen des Servers oder seiner `https://`-URL. CodeNomad öffnet nur das Remote-Fenster, mit denselben Prüfungen und derselben Anmeldung wie **Durchsuchen**; läuft CodeNomad bereits, öffnet sein aktuelles Fenster den Server statt eines neuen Fensters. Eine URL, die zu keinem gespeicherten Server passt, wird unter ihrem Hostnamen gespeichert. Startwerte enthalten nie Zugangsdaten: Eine URL mit Benutzername, Passwort oder Kopplungscode wird abgelehnt. Ist der Name unbekannt, die URL ungültig oder schlägt die Verbindung fehl, startet CodeNomad normal und zeigt den Fehler an. Braucht die Verbindung eine Bestätigung, etwa die Installation des lokalen Zertifikats für einen selbstsignierten Server, startet CodeNomad ebenfalls normal und fragt dort nach. Unter Windows startet der Tauri-Build nicht, wenn ein Startargument `|` enthält; verwenden Sie stattdessen die URL des Servers oder benennen Sie den Server um. Ein Remote-Fenster lässt immer einen Weg zurück zu diesem Computer. Wenn Sie das letzte lokale Fenster schließen, während Remote-Fenster geöffnet bleiben, behält es seine Tabs: **Fenster → Neues Fenster** in einem Remote-Fenster oder ein erneuter Start von CodeNomad öffnet es wieder. Kann ein Server nicht geladen werden, zeigt sein Fenster das an und bietet **Erneut versuchen**, **Lokales Fenster öffnen** und **Fenster schließen**; in der Tauri-Version verwenden Sie die Schaltfläche zum Neuladen der Seite und **Fenster → Neues Fenster**. -Fügen Sie für Fernsteuerung stattdessen einen frischen Kopplungslink in **Server-URL** ein. Das Lesezeichen behält nur die Tunnel-Origin, nie den Einmal-Kopplungscode; siehe [Fernsteuerung](remote-control.md) zur erneuten Kopplung nach Verlust des Geräte-Cookies. +Fügen Sie für Fernsteuerung stattdessen einen frischen Kopplungslink in **Serveradresse oder -link** ein. Das Lesezeichen behält nur die Tunnel-Origin, nie den Einmal-Kopplungscode; siehe [Fernsteuerung](remote-control.md) zur erneuten Kopplung nach Verlust des Geräte-Cookies. ## Ein Remote-Projekt in einem Tab öffnen {#remote-project-tabs} In der Desktop-App (Electron oder Tauri unter Windows) kann ein gespeicherter Server eines seiner Projekte auch in einem Tab dieses Fensters öffnen, neben Ihren lokalen Projekten: -1. Öffnen Sie auf der Startseite oder im Starter **Tab öffnen** den Bereich **Durchsuchen** und wählen Sie einen Server oder **Server hinzufügen…**, um einen hinzuzufügen. +1. Öffnen Sie auf der Startseite oder im Starter **Tab öffnen** den Bereich **Durchsuchen** und wählen Sie einen Server, oder fügen Sie eine Adresse oder einen Kopplungslink in **Serveradresse oder -link** ein. 2. Wählen Sie den Ordner im Tab. Der Tab zeigt dann das Serversymbol und den Projektnamen, und das Projekt erscheint unter **Zuletzt verwendet**: Dort ausgewählt, öffnet es diesen Server und Ordner direkt wieder. Der Tab zeigt nur dieses Projekt; seine Unterhaltungen, Dateien, Git, Einstellungen und Missions laufen auf dem Remote-Server. Er nutzt den Speicher des Remote-Fensters dieses Servers, sodass eine bestehende Anmeldung oder ein gekoppeltes Gerät wiederverwendet wird, und Remote-Tabs kehren zurück, wenn CodeNomad Ihre Tabs wiederherstellt. Ein Server ohne diesen Modus zeigt im Tab seine vollständige Oberfläche. Server, die die TLS-Prüfung überspringen, sowie der Tauri-Build unter macOS und Linux öffnen weiterhin ein Remote-Fenster. Die Seite in einem Tab kann Benachrichtigungen anzeigen, hat aber sonst keinen Zugriff auf diesen Computer und bleibt auf ihrem Server. Webclients und Remote-Control-Geräte haben keine Remote-Tabs. **Gespeicherten Server entfernen** in **Einstellungen → Server** schließt auch seine Tabs. Bevor ein Projekt gewählt ist, zeigt der Tab den Namen des Servers. Melden Sie sich auf der Seite des Servers im Tab an; CodeNomad verwendet diese Anmeldung bei späteren Starts wieder. diff --git a/docs/help/de/remote-control.md b/docs/help/de/remote-control.md index 62c17a780b..cb08726def 100644 --- a/docs/help/de/remote-control.md +++ b/docs/help/de/remote-control.md @@ -11,7 +11,7 @@ Fernsteuerung ermöglicht einem gekoppelten Browser- oder Desktop-Client die Nut Der Link gilt **fünf Minuten** und funktioniert **einmal**. Behandeln Sie ihn als Zugangsdaten: Wer ihn einlöst, kann ein gekoppeltes Gerät werden. Der Code steht im URL-Fragment, nicht in der Abfragezeichenfolge. **Neuen Kopplungslink erstellen** macht den vorherigen ungenutzten Link sofort ungültig. Stop, Backend-Ende und Tunnelfehler stornieren offene Kopplungslinks. -Um einen weiteren CodeNomad-Desktop zu koppeln, wählen Sie auf dessen Startseite **Neuer Server** und fügen den Link in **Server-URL** ein: Der Server öffnet sich und wird gekoppelt, auch über **Speichern**, weil das Öffnen den Code einlöst. Nur die Tunnel-Origin wird als Lesezeichen gespeichert; der Code bleibt nicht erhalten. TLS-Prüfung bleibt für Kopplungslinks aktiviert. +Um einen weiteren CodeNomad-Desktop zu koppeln, öffnen Sie auf dessen Startseite **Durchsuchen** und fügen den Link in **Serveradresse oder -link** ein: Der Server öffnet sich und wird gekoppelt. Nur die Tunnel-Origin wird als Lesezeichen gespeichert; der Code bleibt nicht erhalten. TLS-Prüfung bleibt für Kopplungslinks aktiviert. ## Gekoppelte Geräte verwalten {#paired-devices} diff --git a/docs/help/en/remote-access.md b/docs/help/en/remote-access.md index 97cf6e0c1f..5c8fdd64ba 100644 --- a/docs/help/en/remote-access.md +++ b/docs/help/en/remote-access.md @@ -83,23 +83,23 @@ If a client reports a certificate warning, stop and check the hostname, SANs, tr ## Save a remote server {#saved-servers} -1. On the desktop home page, choose **New server**, or choose **Add server…** at the end of **Browse**, on the home page or in the **Open a tab** launcher. **Settings → Servers** offers the same with **Add server…**. -2. In **Connect to Server**, enter **Server URL**: a trusted HTTPS origin, or a pairing link. **Server name** is optional; without it the server shows its host name. Leave **Skip TLS verification for self-signed certificates.** unchecked; establish trust instead. If the certificate fails the check, the dialog says so. -3. Choose **Save** to bookmark, or **Connect** to save and open it. Sign in on that server. +1. On the desktop home page or in the **Open a tab** launcher, open **Browse** and paste the server's address or a pairing link into **Server address or link**, then press Enter: the server is saved under its host name and opens. **Settings → Servers** offers the same field. +2. Use a trusted HTTPS origin. If its certificate fails the check, the error shows under the field with **Skip TLS verification**: tick it only for a server you trust, then press Enter again; that server opens in its own window. +3. Sign in on that server. Rename it or change its address with **Edit server** in **Settings → Servers**. Saved servers are listed under **Browse**: choose one to open it again. **Settings → Servers** is where you open, edit (**Edit server**: name, address, certificate check) and remove (**Remove saved server**) them. Bookmarks belong to this CodeNomad configuration, not the remote server's projects. Saving a URL does not start the server or grant access. **Remove saved server** removes the bookmark, not remote conversations, the backend or its credentials. -To open a saved server straight from the command line, start the desktop app with `--connect-server ` (or `--connect-server=`), using the server's saved name, or with its `https://` URL. CodeNomad opens only the remote window, with the same checks and sign-in as **Connect**; when CodeNomad is already running, its current window opens it instead of a new one. A URL that matches no saved server is saved under its host name. Launch values never carry credentials: a URL with a user name, password or pairing code is refused. If the name is unknown, the URL is invalid or the connection fails, CodeNomad starts normally and shows the error. When the connection needs a confirmation, such as installing the local certificate for a self-signed server, CodeNomad also starts normally and asks there. On Windows, the Tauri build refuses to start when a launch argument contains `|`; use the server's URL instead, or rename the server. +To open a saved server straight from the command line, start the desktop app with `--connect-server ` (or `--connect-server=`), using the server's saved name, or with its `https://` URL. CodeNomad opens only the remote window, with the same checks and sign-in as **Browse**; when CodeNomad is already running, its current window opens it instead of a new one. A URL that matches no saved server is saved under its host name. Launch values never carry credentials: a URL with a user name, password or pairing code is refused. If the name is unknown, the URL is invalid or the connection fails, CodeNomad starts normally and shows the error. When the connection needs a confirmation, such as installing the local certificate for a self-signed server, CodeNomad also starts normally and asks there. On Windows, the Tauri build refuses to start when a launch argument contains `|`; use the server's URL instead, or rename the server. A remote window always leaves a way back to this computer. Closing the last local window while remote windows stay open keeps its tabs: **Window → New Window** in a remote window, or starting CodeNomad again, reopens it. If a server cannot be loaded, its window says so and offers **Try again**, **Open a local window** and **Close window**; in the Tauri build, use the page's reload button and **Window → New Window**. -For Remote Control, paste a fresh pairing link into **Server URL** instead. The bookmark retains only the tunnel origin, never the one-use pairing code; see [Remote Control](remote-control.md) for re-pairing after device-cookie loss. +For Remote Control, paste a fresh pairing link into **Server address or link** instead. The bookmark retains only the tunnel origin, never the one-use pairing code; see [Remote Control](remote-control.md) for re-pairing after device-cookie loss. ## Open a remote project in a tab {#remote-project-tabs} In the desktop app (Electron, or Tauri on Windows), a saved server can also open one of its projects in a tab of this window, beside your local projects: -1. On the home page or in the **Open a tab** launcher, open **Browse** and choose a server, or **Add server…** to add one. +1. On the home page or in the **Open a tab** launcher, open **Browse** and choose a server, or paste an address or a pairing link into **Server address or link**. 2. Pick the folder in the tab. The tab then shows the server icon and the project name, and the project joins **Recent**: choosing it there reopens that server and folder directly. The tab shows only that project; its conversations, files, Git, settings and Missions run on the remote server. It uses the storage of the server's remote window, so an existing sign-in or paired device is reused, and remote tabs come back when CodeNomad restores your tabs. A server without this mode shows its full interface in the tab. Servers that skip TLS verification, and the Tauri build on macOS and Linux, keep opening a remote window. The page in a tab can show notifications but has no other access to this computer and stays on its server. Web clients and Remote Control devices have no remote tabs. **Remove saved server**, in **Settings → Servers**, also closes its tabs. Before a project is chosen, the tab shows the server's name. Sign in on the server's page in the tab; CodeNomad reuses that sign-in on later launches. diff --git a/docs/help/en/remote-control.md b/docs/help/en/remote-control.md index fb2728c0e5..6f35246e8e 100644 --- a/docs/help/en/remote-control.md +++ b/docs/help/en/remote-control.md @@ -11,7 +11,7 @@ Remote Control lets a paired browser or desktop client use your running CodeNoma The link is valid for **five minutes** and succeeds **once**. Treat it as a credential: anyone who consumes it can become a paired device. The code lives in the URL fragment, not the query string. **Create new pairing link** immediately invalidates the preceding unused link. Stop, backend shutdown and tunnel failure cancel outstanding pairing links. -To pair another desktop CodeNomad, choose **New server** on its home page and paste the link into **Server URL**: the server opens and pairs, even from **Save**, because opening it consumes the code. Only the tunnel origin is saved as the bookmark; the code is not retained. TLS verification stays enabled for pairing links. +To pair another desktop CodeNomad, open **Browse** on its home page and paste the link into **Server address or link**: the server opens and pairs. Only the tunnel origin is saved as the bookmark; the code is not retained. TLS verification stays enabled for pairing links. ## Manage paired devices {#paired-devices} diff --git a/docs/help/es/remote-access.md b/docs/help/es/remote-access.md index 118fd2ceeb..16073e3bf8 100644 --- a/docs/help/es/remote-access.md +++ b/docs/help/es/remote-access.md @@ -83,23 +83,23 @@ Si un cliente muestra una advertencia de certificado, detente y comprueba el nom ## Guardar un servidor remoto {#saved-servers} -1. En la página de inicio de escritorio, elige **Nuevo servidor**, o **Añadir servidor…** al final de **Explorar**, en la página de inicio o en el lanzador **Abrir una pestaña**. **Configuración → Servidores** ofrece lo mismo con **Añadir servidor…**. -2. En **Conectar a un servidor**, introduce en **URL del servidor** un origen HTTPS de confianza o un enlace de emparejamiento. **Nombre del servidor** es opcional; sin él, el servidor muestra su nombre de host. Deja **Omitir la verificación TLS para certificados autofirmados.** sin marcar; establece la confianza en su lugar. Si el certificado no supera la verificación, el diálogo lo indica. -3. Elige **Guardar** para crear un marcador o **Conectar** para guardarlo y abrirlo. Inicia sesión en ese servidor. +1. En la página de inicio de escritorio o en el lanzador **Abrir una pestaña**, abre **Explorar**, pega la dirección del servidor o un enlace de emparejamiento en **Dirección o enlace del servidor** y pulsa Intro: el servidor se guarda con su nombre de host y se abre. **Configuración → Servidores** ofrece el mismo campo. +2. Usa un origen HTTPS de confianza. Si su certificado no supera la verificación, el error aparece bajo el campo con **Omitir la verificación TLS**: márcala solo para un servidor de confianza y vuelve a pulsar Intro; ese servidor se abre en su propia ventana. +3. Inicia sesión en ese servidor. Cambia su nombre o su dirección con **Editar servidor** en **Configuración → Servidores**. Los servidores guardados aparecen en **Explorar**: elige uno para volver a abrirlo. En **Configuración → Servidores** se abren, se editan (**Editar servidor**: nombre, dirección, verificación del certificado) y se quitan (**Eliminar servidor guardado**). Los marcadores pertenecen a esta configuración de CodeNomad, no a los proyectos del servidor remoto. Guardar una URL no inicia el servidor ni concede acceso. **Eliminar servidor guardado** elimina el marcador, no las conversaciones remotas, el backend ni sus credenciales. -Para abrir un servidor guardado directamente desde la línea de comandos, inicia la aplicación de escritorio con `--connect-server ` (o `--connect-server=`), usando el nombre guardado del servidor o su URL `https://`. CodeNomad abre solo la ventana remota, con las mismas comprobaciones e inicio de sesión que **Conectar**; si CodeNomad ya se está ejecutando, su ventana actual lo abre en lugar de una nueva. Una URL que no coincide con ningún servidor guardado se guarda con su nombre de host. Los valores de inicio nunca llevan credenciales: se rechaza una URL con nombre de usuario, contraseña o código de emparejamiento. Si el nombre es desconocido, la URL no es válida o la conexión falla, CodeNomad se inicia con normalidad y muestra el error. Cuando la conexión necesita una confirmación, como instalar el certificado local para un servidor autofirmado, CodeNomad también se inicia con normalidad y la pide allí. En Windows, la compilación Tauri no se inicia si un argumento de inicio contiene `|`; usa en su lugar la URL del servidor o cambia el nombre del servidor. +Para abrir un servidor guardado directamente desde la línea de comandos, inicia la aplicación de escritorio con `--connect-server ` (o `--connect-server=`), usando el nombre guardado del servidor o su URL `https://`. CodeNomad abre solo la ventana remota, con las mismas comprobaciones e inicio de sesión que **Explorar**; si CodeNomad ya se está ejecutando, su ventana actual lo abre en lugar de una nueva. Una URL que no coincide con ningún servidor guardado se guarda con su nombre de host. Los valores de inicio nunca llevan credenciales: se rechaza una URL con nombre de usuario, contraseña o código de emparejamiento. Si el nombre es desconocido, la URL no es válida o la conexión falla, CodeNomad se inicia con normalidad y muestra el error. Cuando la conexión necesita una confirmación, como instalar el certificado local para un servidor autofirmado, CodeNomad también se inicia con normalidad y la pide allí. En Windows, la compilación Tauri no se inicia si un argumento de inicio contiene `|`; usa en su lugar la URL del servidor o cambia el nombre del servidor. Una ventana remota siempre deja una forma de volver a este equipo. Cerrar la última ventana local mientras siguen abiertas ventanas remotas conserva sus pestañas: **Ventana → Nueva ventana** en una ventana remota, o iniciar CodeNomad de nuevo, la vuelve a abrir. Si un servidor no se puede cargar, su ventana lo indica y ofrece **Reintentar**, **Abrir una ventana local** y **Cerrar ventana**; en la versión Tauri, usa el botón de recarga de la página y **Ventana → Nueva ventana**. -Para Control remoto, pega en su lugar un enlace de emparejamiento nuevo en **URL del servidor**. El marcador conserva solo el origen del túnel, nunca el código de un solo uso; consulta [Control remoto](remote-control.md) para volver a emparejar tras perder la cookie del dispositivo. +Para Control remoto, pega en su lugar un enlace de emparejamiento nuevo en **Dirección o enlace del servidor**. El marcador conserva solo el origen del túnel, nunca el código de un solo uso; consulta [Control remoto](remote-control.md) para volver a emparejar tras perder la cookie del dispositivo. ## Abrir un proyecto remoto en una pestaña {#remote-project-tabs} En la aplicación de escritorio (Electron, o Tauri en Windows), un servidor guardado también puede abrir uno de sus proyectos en una pestaña de esta ventana, junto a tus proyectos locales: -1. En la página de inicio o en el lanzador **Abrir una pestaña**, abre **Explorar** y elige un servidor, o **Añadir servidor…** para añadir uno. +1. En la página de inicio o en el lanzador **Abrir una pestaña**, abre **Explorar** y elige un servidor, o pega una dirección o un enlace de emparejamiento en **Dirección o enlace del servidor**. 2. Elige la carpeta en la pestaña. La pestaña muestra entonces el icono de servidor y el nombre del proyecto, y el proyecto se suma a **Recientes**: elegirlo allí vuelve a abrir directamente ese servidor y esa carpeta. La pestaña muestra solo ese proyecto; sus conversaciones, archivos, Git, ajustes y Missions se ejecutan en el servidor remoto. Usa el almacenamiento de la ventana remota del servidor, así que se reutiliza un inicio de sesión o un dispositivo emparejado existente, y las pestañas remotas vuelven cuando CodeNomad restaura tus pestañas. Un servidor sin este modo muestra su interfaz completa en la pestaña. Los servidores que omiten la verificación TLS, y la versión Tauri en macOS y Linux, siguen abriendo una ventana remota. La página de una pestaña puede mostrar notificaciones, pero no tiene otro acceso a este equipo y permanece en su servidor. Los clientes web y los dispositivos de Remote Control no tienen pestañas remotas. **Eliminar servidor guardado**, en **Configuración → Servidores**, también cierra sus pestañas. Antes de elegir un proyecto, la pestaña muestra el nombre del servidor. Inicia sesión en la página del servidor, dentro de la pestaña; CodeNomad reutiliza ese inicio de sesión en los siguientes arranques. diff --git a/docs/help/es/remote-control.md b/docs/help/es/remote-control.md index 4c3bc3c4bf..35f4d7caf9 100644 --- a/docs/help/es/remote-control.md +++ b/docs/help/es/remote-control.md @@ -11,7 +11,7 @@ Control remoto permite a un navegador o cliente de escritorio emparejado usar tu El enlace es válido durante **cinco minutos** y funciona **una vez**. Trátalo como una credencial: cualquiera que lo consuma puede convertirse en un dispositivo emparejado. El código está en el fragmento de la URL, no en la cadena de consulta. **Crear nuevo enlace de emparejamiento** invalida inmediatamente el enlace anterior sin usar. Detener, apagar el backend y los fallos del túnel cancelan los enlaces de emparejamiento pendientes. -Para emparejar otro CodeNomad de escritorio, elige **Nuevo servidor** en su página de inicio y pega el enlace en **URL del servidor**: el servidor se abre y se empareja, incluso desde **Guardar**, porque abrirlo consume el código. Solo se guarda el origen del túnel como marcador; el código no se conserva. La verificación TLS permanece activada para enlaces de emparejamiento. +Para emparejar otro CodeNomad de escritorio, abre **Explorar** en su página de inicio y pega el enlace en **Dirección o enlace del servidor**: el servidor se abre y se empareja. Solo se guarda el origen del túnel como marcador; el código no se conserva. La verificación TLS permanece activada para enlaces de emparejamiento. ## Gestionar dispositivos emparejados {#paired-devices} diff --git a/docs/help/fr/remote-access.md b/docs/help/fr/remote-access.md index 55921a4db0..986e3e4c23 100644 --- a/docs/help/fr/remote-access.md +++ b/docs/help/fr/remote-access.md @@ -83,23 +83,23 @@ Si un client signale un avertissement de certificat, arrêtez-vous et vérifiez ## Enregistrer un serveur distant {#saved-servers} -1. Sur l’accueil de bureau, choisissez **Nouveau serveur**, ou **Ajouter un serveur…** en fin de **Parcourir**, sur l’accueil ou dans le lanceur **Ouvrir un onglet**. **Paramètres → Serveurs** propose la même chose avec **Ajouter un serveur…**. -2. Dans **Se connecter à un serveur**, saisissez **URL du serveur** : une origine HTTPS de confiance, ou un lien d’appairage. **Nom du serveur** est facultatif ; sans lui, le serveur affiche son nom d’hôte. Laissez **Ignorer la vérification TLS pour les certificats auto-signés.** décoché ; établissez plutôt la confiance. Si le certificat échoue à la vérification, le dialogue l’indique. -3. Choisissez **Enregistrer** pour ajouter un favori, ou **Se connecter** pour l’enregistrer et l’ouvrir. Connectez-vous sur ce serveur. +1. Sur l’accueil de bureau ou dans le lanceur **Ouvrir un onglet**, ouvrez **Parcourir** et collez l’adresse du serveur ou un lien d’appairage dans **Adresse ou lien du serveur**, puis appuyez sur Entrée : le serveur est enregistré sous son nom d’hôte et s’ouvre. **Paramètres → Serveurs** propose le même champ. +2. Utilisez une origine HTTPS de confiance. Si son certificat échoue à la vérification, l’erreur s’affiche sous le champ avec **Ignorer la vérification TLS** : cochez-la seulement pour un serveur de confiance, puis appuyez de nouveau sur Entrée ; ce serveur s’ouvre dans sa propre fenêtre. +3. Connectez-vous sur ce serveur. Renommez-le ou changez son adresse avec **Modifier le serveur** dans **Paramètres → Serveurs**. Les serveurs enregistrés sont listés sous **Parcourir** : choisissez-en un pour l’ouvrir de nouveau. **Paramètres → Serveurs** permet de les ouvrir, de les modifier (**Modifier le serveur** : nom, adresse, vérification du certificat) et de les retirer (**Supprimer le serveur enregistré**). Les favoris appartiennent à cette configuration CodeNomad, pas aux projets du serveur distant. Enregistrer une URL ne démarre pas le serveur et n’accorde pas l’accès. **Supprimer le serveur enregistré** retire le favori, pas les conversations distantes, le backend ou ses identifiants. -Pour ouvrir un serveur enregistré directement depuis la ligne de commande, lancez l’application de bureau avec `--connect-server ` (ou `--connect-server=`), en indiquant le nom enregistré du serveur ou son URL `https://`. CodeNomad n’ouvre que la fenêtre distante, avec les mêmes vérifications et la même connexion que **Se connecter** ; si CodeNomad est déjà lancé, sa fenêtre actuelle l’ouvre au lieu d’une nouvelle fenêtre. Une URL qui ne correspond à aucun serveur enregistré est enregistrée sous son nom d’hôte. Les valeurs de lancement ne portent jamais d’identifiants : une URL avec un nom d’utilisateur, un mot de passe ou un code d’appairage est refusée. Si le nom est inconnu, l’URL invalide ou la connexion échoue, CodeNomad démarre normalement et affiche l’erreur. Quand la connexion demande une confirmation, comme l’installation du certificat local pour un serveur auto-signé, CodeNomad démarre aussi normalement et la demande là. Sous Windows, la version Tauri refuse de démarrer quand un argument de lancement contient `|` ; utilisez plutôt l’URL du serveur, ou renommez le serveur. +Pour ouvrir un serveur enregistré directement depuis la ligne de commande, lancez l’application de bureau avec `--connect-server ` (ou `--connect-server=`), en indiquant le nom enregistré du serveur ou son URL `https://`. CodeNomad n’ouvre que la fenêtre distante, avec les mêmes vérifications et la même connexion que **Parcourir** ; si CodeNomad est déjà lancé, sa fenêtre actuelle l’ouvre au lieu d’une nouvelle fenêtre. Une URL qui ne correspond à aucun serveur enregistré est enregistrée sous son nom d’hôte. Les valeurs de lancement ne portent jamais d’identifiants : une URL avec un nom d’utilisateur, un mot de passe ou un code d’appairage est refusée. Si le nom est inconnu, l’URL invalide ou la connexion échoue, CodeNomad démarre normalement et affiche l’erreur. Quand la connexion demande une confirmation, comme l’installation du certificat local pour un serveur auto-signé, CodeNomad démarre aussi normalement et la demande là. Sous Windows, la version Tauri refuse de démarrer quand un argument de lancement contient `|` ; utilisez plutôt l’URL du serveur, ou renommez le serveur. Une fenêtre distante laisse toujours un moyen de revenir sur cet ordinateur. Fermer la dernière fenêtre locale alors que des fenêtres distantes restent ouvertes conserve ses onglets : **Fenêtre → Nouvelle fenêtre** dans une fenêtre distante, ou un nouveau lancement de CodeNomad, la rouvre. Si un serveur ne peut pas être chargé, sa fenêtre l’indique et propose **Réessayer**, **Ouvrir une fenêtre locale** et **Fermer la fenêtre** ; dans la version Tauri, utilisez le bouton d’actualisation de la page et **Fenêtre → Nouvelle fenêtre**. -Pour le Contrôle à distance, collez plutôt un lien d’appairage récent dans **URL du serveur**. Le favori ne conserve que l’origine du tunnel, jamais le code d’appairage à usage unique ; voir [Contrôle à distance](remote-control.md) pour le réappairage après perte du cookie de l’appareil. +Pour le Contrôle à distance, collez plutôt un lien d’appairage récent dans **Adresse ou lien du serveur**. Le favori ne conserve que l’origine du tunnel, jamais le code d’appairage à usage unique ; voir [Contrôle à distance](remote-control.md) pour le réappairage après perte du cookie de l’appareil. ## Ouvrir un projet distant dans un onglet {#remote-project-tabs} Dans l'application de bureau (Electron, ou Tauri sous Windows), un serveur enregistré peut aussi ouvrir l'un de ses projets dans un onglet de cette fenêtre, à côté de vos projets locaux : -1. Sur l’accueil ou dans le lanceur **Ouvrir un onglet**, ouvrez **Parcourir** et choisissez un serveur, ou **Ajouter un serveur…** pour en ajouter un. +1. Sur l’accueil ou dans le lanceur **Ouvrir un onglet**, ouvrez **Parcourir** et choisissez un serveur, ou collez une adresse ou un lien d’appairage dans **Adresse ou lien du serveur**. 2. Choisissez le dossier dans l'onglet. L'onglet affiche alors l'icône serveur et le nom du projet, et le projet rejoint **Récents** : le choisir à cet endroit rouvre directement ce serveur et ce dossier. L'onglet n'affiche que ce projet ; ses conversations, fichiers, Git, paramètres et Missions s'exécutent sur le serveur distant. Il utilise le stockage de la fenêtre distante du serveur : une connexion ou un appareil appairé existant est donc réutilisé, et les onglets distants reviennent quand CodeNomad restaure vos onglets. Un serveur sans ce mode affiche son interface complète dans l'onglet. Les serveurs qui ignorent la vérification TLS, ainsi que la version Tauri sous macOS et Linux, continuent d'ouvrir une fenêtre distante. La page d'un onglet peut afficher des notifications, sans autre accès à cet ordinateur, et reste sur son serveur. Les clients web et les appareils Remote Control n'ont pas d'onglets distants. **Supprimer le serveur enregistré**, dans **Paramètres → Serveurs**, ferme aussi ses onglets. Avant le choix d’un projet, l’onglet affiche le nom du serveur. Connectez-vous sur la page du serveur, dans l’onglet ; CodeNomad réutilise cette connexion aux lancements suivants. diff --git a/docs/help/fr/remote-control.md b/docs/help/fr/remote-control.md index e21349411c..b8d78f38e7 100644 --- a/docs/help/fr/remote-control.md +++ b/docs/help/fr/remote-control.md @@ -11,7 +11,7 @@ Le Contrôle à distance permet à un navigateur ou client de bureau appairé d Le lien est valable **cinq minutes** et réussit **une seule fois**. Traitez-le comme un identifiant : quiconque le consomme peut devenir un appareil appairé. Le code se trouve dans le fragment d’URL, pas dans la chaîne de requête. **Créer un nouveau lien d’appairage** invalide immédiatement le lien inutilisé précédent. L’arrêt, la fermeture du backend et une panne du tunnel annulent les liens d’appairage en attente. -Pour appairer un autre CodeNomad de bureau, choisissez **Nouveau serveur** sur son accueil et collez le lien dans **URL du serveur** : le serveur s’ouvre et s’appaire, même depuis **Enregistrer**, car l’ouvrir consomme le code. Seule l’origine du tunnel est enregistrée comme favori ; le code n’est pas conservé. La vérification TLS reste activée pour les liens d’appairage. +Pour appairer un autre CodeNomad de bureau, ouvrez **Parcourir** sur son accueil et collez le lien dans **Adresse ou lien du serveur** : le serveur s’ouvre et s’appaire. Seule l’origine du tunnel est enregistrée comme favori ; le code n’est pas conservé. La vérification TLS reste activée pour les liens d’appairage. ## Gérer les appareils appairés {#paired-devices} diff --git a/docs/help/he/remote-access.md b/docs/help/he/remote-access.md index 51f8cff264..4789668387 100644 --- a/docs/help/he/remote-access.md +++ b/docs/help/he/remote-access.md @@ -83,23 +83,23 @@ codenomad --host 127.0.0.1 --https=false --http=true ## שמירת שרת מרוחק {#saved-servers} -1. בדף הבית בשולחן העבודה, בחרו **שרת חדש**, או **הוספת שרת…** בסוף **עיון**, בדף הבית או במפעיל **פתיחת לשונית**. **הגדרות → שרתים** מציע את אותו הדבר באמצעות **הוספת שרת…**. -2. ב־**התחבר לשרת**, הזינו ב־**כתובת השרת** מקור HTTPS מהימן או קישור צימוד. **שם השרת** הוא אופציונלי; בלעדיו השרת מוצג בשם המארח שלו. השאירו את **דלג על אימות TLS עבור תעודות בחתימה עצמית.** לא מסומן; במקום זאת בססו אמון. אם התעודה נכשלת בבדיקה, תיבת הדו־שיח מציינת זאת. -3. בחרו **שמור** לסימנייה, או **התחבר** לשמירה ולפתיחה. התחברו באותו שרת. +1. בדף הבית בשולחן העבודה או במפעיל **פתיחת לשונית**, פתחו את **עיון**, הדביקו את כתובת השרת או קישור צימוד בשדה **כתובת או קישור של השרת** והקישו Enter: השרת נשמר בשם המארח שלו ונפתח. **הגדרות → שרתים** מציע את אותו השדה. +2. השתמשו במקור HTTPS מהימן. אם התעודה שלו נכשלת בבדיקה, השגיאה מופיעה מתחת לשדה עם **דילוג על אימות TLS**: סמנו זאת רק עבור שרת מהימן והקישו Enter שוב; השרת הזה נפתח בחלון משלו. +3. התחברו לשרת הזה. שנו את שמו או את כתובתו באמצעות **עריכת שרת** ב־**הגדרות → שרתים**. שרתים שמורים מופיעים תחת **עיון**: בחרו שרת כדי לפתוח אותו שוב. ב־**הגדרות → שרתים** פותחים אותם, עורכים אותם (**עריכת שרת**: שם, כתובת, בדיקת תעודה) ומסירים אותם (**הסר שרת שמור**). סימניות שייכות לתצורת CodeNomad זו, לא לפרויקטי השרת המרוחק. שמירת כתובת אינה מפעילה שרת או מעניקה גישה. **הסר שרת שמור** מסיר את הסימנייה, לא שיחות מרוחקות, את שרת הקצה או את פרטי ההתחברות שלו. -כדי לפתוח שרת שמור ישירות משורת הפקודה, הפעילו את אפליקציית שולחן העבודה עם `--connect-server ` (או `--connect-server=`), עם השם השמור של השרת או עם כתובת ה־`https://` שלו. CodeNomad פותח רק את החלון המרוחק, עם אותן בדיקות ואותה התחברות כמו **התחבר**; כש־CodeNomad כבר פועל, החלון הנוכחי שלו פותח אותו במקום חלון חדש. כתובת שאינה תואמת אף שרת שמור נשמרת בשם המארח שלה. ערכי הפעלה לעולם אינם נושאים פרטי התחברות: כתובת עם שם משתמש, סיסמה או קוד צימוד נדחית. אם השם אינו מוכר, הכתובת אינה תקינה או שהחיבור נכשל, CodeNomad מופעל כרגיל ומציג את השגיאה. כשהחיבור דורש אישור, כמו התקנת התעודה המקומית לשרת בחתימה עצמית, CodeNomad גם מופעל כרגיל ומבקש אותו שם. ב־Windows, גרסת Tauri מסרבת לעלות כשארגומנט הפעלה מכיל `|`; השתמשו במקום זאת בכתובת השרת, או שנו את שם השרת. +כדי לפתוח שרת שמור ישירות משורת הפקודה, הפעילו את אפליקציית שולחן העבודה עם `--connect-server ` (או `--connect-server=`), עם השם השמור של השרת או עם כתובת ה־`https://` שלו. CodeNomad פותח רק את החלון המרוחק, עם אותן בדיקות ואותה התחברות כמו **עיון**; כש־CodeNomad כבר פועל, החלון הנוכחי שלו פותח אותו במקום חלון חדש. כתובת שאינה תואמת אף שרת שמור נשמרת בשם המארח שלה. ערכי הפעלה לעולם אינם נושאים פרטי התחברות: כתובת עם שם משתמש, סיסמה או קוד צימוד נדחית. אם השם אינו מוכר, הכתובת אינה תקינה או שהחיבור נכשל, CodeNomad מופעל כרגיל ומציג את השגיאה. כשהחיבור דורש אישור, כמו התקנת התעודה המקומית לשרת בחתימה עצמית, CodeNomad גם מופעל כרגיל ומבקש אותו שם. ב־Windows, גרסת Tauri מסרבת לעלות כשארגומנט הפעלה מכיל `|`; השתמשו במקום זאת בכתובת השרת, או שנו את שם השרת. חלון מרוחק תמיד משאיר דרך לחזור למחשב הזה. סגירת החלון המקומי האחרון בזמן שחלונות מרוחקים נשארים פתוחים שומרת את הלשוניות שלו: **חלון → חלון חדש** בחלון מרוחק, או הפעלה מחדש של CodeNomad, פותחים אותו שוב. אם לא ניתן לטעון שרת, החלון שלו מציין זאת ומציע **נסו שוב**, **פתיחת חלון מקומי** ו**סגירת החלון**; בגרסת Tauri, השתמשו בכפתור הרענון של הדף וב־**חלון → חלון חדש**. -לשליטה מרחוק, הדביקו במקום זאת קישור צימוד חדש ב־**כתובת השרת**. הסימנייה שומרת רק את מקור המנהרה, לעולם לא את קוד הצימוד החד־פעמי; ראו [שליטה מרחוק](remote-control.md) לצימוד מחדש לאחר אובדן עוגיית המכשיר. +לשליטה מרחוק, הדביקו במקום זאת קישור צימוד חדש ב־**כתובת או קישור של השרת**. הסימנייה שומרת רק את מקור המנהרה, לעולם לא את קוד הצימוד החד־פעמי; ראו [שליטה מרחוק](remote-control.md) לצימוד מחדש לאחר אובדן עוגיית המכשיר. ## פתיחת פרויקט מרוחק בלשונית {#remote-project-tabs} ביישום שולחן העבודה (Electron, או Tauri ב-Windows), שרת שמור יכול לפתוח גם אחד מהפרויקטים שלו בלשונית של החלון הזה, לצד הפרויקטים המקומיים שלך: -1. בדף הבית או במפעיל **פתיחת לשונית**, פתחו את **עיון** ובחרו שרת, או **הוספת שרת…** כדי להוסיף שרת. +1. בדף הבית או במפעיל **פתיחת לשונית**, פתחו את **עיון** ובחרו שרת, או הדביקו כתובת או קישור צימוד בשדה **כתובת או קישור של השרת**. 2. בחרו את התיקייה בלשונית. הלשונית מציגה אז את סמל השרת ואת שם הפרויקט, והפרויקט מצטרף ל-**אחרונים**: בחירה בו שם פותחת מחדש ישירות את השרת והתיקייה האלה. הלשונית מציגה רק את הפרויקט הזה; השיחות, הקבצים, Git, ההגדרות וה-Missions שלו פועלים בשרת המרוחק. היא משתמשת באחסון של החלון המרוחק של השרת, כך שהתחברות קיימת או מכשיר מצומד נעשים בהם שימוש חוזר, והלשוניות המרוחקות חוזרות כש-CodeNomad משחזר את הלשוניות שלך. שרת ללא מצב זה מציג בלשונית את הממשק המלא שלו. שרתים שמדלגים על אימות TLS, וגרסת Tauri ב-macOS וב-Linux, ממשיכים לפתוח חלון מרוחק. הדף שבלשונית יכול להציג התראות, אך אין לו גישה אחרת למחשב הזה והוא נשאר בשרת שלו. ללקוחות אינטרנט ולמכשירי Remote Control אין לשוניות מרוחקות. **הסר שרת שמור**, ב־**הגדרות → שרתים**, סוגר גם את הלשוניות שלו. לפני בחירת פרויקט, הלשונית מציגה את שם השרת. התחברו בדף של השרת בתוך הלשונית; CodeNomad משתמש שוב בהתחברות זו בהפעלות הבאות. diff --git a/docs/help/he/remote-control.md b/docs/help/he/remote-control.md index ee3335a450..3cbff9c281 100644 --- a/docs/help/he/remote-control.md +++ b/docs/help/he/remote-control.md @@ -11,7 +11,7 @@ הקישור תקף ל־**חמש דקות** ומצליח **פעם אחת**. התייחסו אליו כאישור גישה: כל מי שמנצל אותו יכול להפוך למכשיר מצומד. הקוד נמצא במקטע הכתובת, לא במחרוזת השאילתה. **צור קישור צימוד חדש** מבטל מיד את הקישור הקודם שלא נוצל. עצירה, כיבוי שרת הקצה וכשל במנהרה מבטלים קישורי צימוד שטרם נוצלו. -לצימוד CodeNomad נוסף לשולחן העבודה, בחרו **שרת חדש** בדף הבית שלו והדביקו את הקישור בשדה **כתובת השרת**: השרת נפתח ומצומד, גם מ־**שמור**, כי פתיחתו מנצלת את הקוד. רק מקור המנהרה נשמר כסימנייה; הקוד אינו נשמר. אימות TLS נשאר פעיל לקישורי צימוד. +לצימוד CodeNomad נוסף לשולחן העבודה, פתחו את **עיון** בדף הבית שלו והדביקו את הקישור בשדה **כתובת או קישור של השרת**: השרת נפתח ומצומד. רק מקור המנהרה נשמר כסימנייה; הקוד אינו נשמר. אימות TLS נשאר פעיל לקישורי צימוד. ## ניהול מכשירים מצומדים {#paired-devices} diff --git a/docs/help/ja/remote-access.md b/docs/help/ja/remote-access.md index f6851f86c3..2cf9c6b831 100644 --- a/docs/help/ja/remote-access.md +++ b/docs/help/ja/remote-access.md @@ -83,23 +83,23 @@ HTTPS が有効で鍵/証明書のペアを指定していない場合、CodeN ## リモートサーバーを保存する {#saved-servers} -1. デスクトップのホームページで **新しいサーバー** を選ぶか、ホームページまたは **タブを開く** ランチャーの **参照** の最後にある **サーバーを追加…** を選びます。**設定 → サーバー** でも **サーバーを追加…** で同じ操作ができます。 -2. **サーバーに接続** で **サーバー URL** に信頼できる HTTPS オリジンまたはペアリングリンクを入力します。**サーバー名** は省略でき、省略するとサーバーはホスト名で表示されます。**自己署名証明書の TLS 検証をスキップします。** はオフのままにし、代わりに信頼を確立してください。証明書が検証に失敗した場合は、ダイアログにそのことが表示されます。 -3. ブックマークには **保存**、保存して開くには **接続** を選び、そのサーバーでログインします。 +1. デスクトップのホームページまたは **タブを開く** ランチャーで **参照** を開き、サーバーのアドレスまたはペアリングリンクを **サーバーのアドレスまたはリンク** に貼り付けて Enter を押します。サーバーはホスト名で保存されて開きます。**設定 → サーバー** にも同じ入力欄があります。 +2. 信頼できる HTTPS オリジンを使用してください。証明書が検証に失敗した場合は、入力欄の下にエラーと **TLS 検証をスキップ** が表示されます。信頼できるサーバーの場合にのみオンにして、もう一度 Enter を押します。そのサーバーは専用のウィンドウで開きます。 +3. そのサーバーでサインインします。名前やアドレスは **設定 → サーバー** の **サーバーを編集** で変更できます。 保存したサーバーは **参照** に表示され、選ぶと再び開きます。**設定 → サーバー** では、サーバーを開く、編集する(**サーバーを編集**:名前、アドレス、証明書の検証)、削除する(**保存したサーバーを削除**)ことができます。ブックマークは、この CodeNomad 設定に属し、リモートサーバーのプロジェクトに属するわけではありません。URL の保存はサーバーの起動やアクセス許可を行いません。**保存したサーバーを削除** はブックマークを削除しますが、リモートの会話、バックエンド、認証情報は削除しません。 -保存したサーバーをコマンドラインから直接開くには、サーバーの保存名か `https://` URL を指定して、デスクトップアプリを `--connect-server `(または `--connect-server=`)付きで起動します。CodeNomad はリモートウィンドウだけを開き、**接続** と同じ確認とログインを行います。CodeNomad がすでに起動している場合は、新しいウィンドウではなく現在のウィンドウから開きます。どの保存済みサーバーにも一致しない URL は、ホスト名で保存されます。起動時の値に認証情報は含められません。ユーザー名、パスワード、ペアリングコードを含む URL は拒否されます。名前が不明な場合、URL が無効な場合、または接続に失敗した場合、CodeNomad は通常どおり起動してエラーを表示します。 自己署名サーバー用のローカル証明書のインストールなど、接続に確認が必要な場合も、CodeNomad は通常どおり起動してそこで確認します。 Windows では、起動引数に `|` が含まれると Tauri 版は起動しません。代わりにサーバーの URL を使うか、サーバー名を変更してください。 +保存したサーバーをコマンドラインから直接開くには、サーバーの保存名か `https://` URL を指定して、デスクトップアプリを `--connect-server `(または `--connect-server=`)付きで起動します。CodeNomad はリモートウィンドウだけを開き、**参照** と同じ確認とログインを行います。CodeNomad がすでに起動している場合は、新しいウィンドウではなく現在のウィンドウから開きます。どの保存済みサーバーにも一致しない URL は、ホスト名で保存されます。起動時の値に認証情報は含められません。ユーザー名、パスワード、ペアリングコードを含む URL は拒否されます。名前が不明な場合、URL が無効な場合、または接続に失敗した場合、CodeNomad は通常どおり起動してエラーを表示します。 自己署名サーバー用のローカル証明書のインストールなど、接続に確認が必要な場合も、CodeNomad は通常どおり起動してそこで確認します。 Windows では、起動引数に `|` が含まれると Tauri 版は起動しません。代わりにサーバーの URL を使うか、サーバー名を変更してください。 リモートウィンドウからは、いつでもこのコンピューターに戻れます。リモートウィンドウを開いたまま最後のローカルウィンドウを閉じても、そのタブは保持されます。リモートウィンドウの **ウィンドウ → 新規ウィンドウ**、または CodeNomad の再起動で再び開きます。サーバーを読み込めない場合は、そのウィンドウにその旨が表示され、**再試行**、**ローカルウィンドウを開く**、**ウィンドウを閉じる** を選べます。Tauri 版では、ページの再読み込みボタンと **ウィンドウ → 新規ウィンドウ** を使用します。 -リモートコントロールでは、代わりに新しいペアリングリンクを **サーバー URL** に貼り付けます。ブックマークはトンネルのオリジンだけを保持し、使い捨てのペアリングコードは保持しません。端末 Cookie 消失後の再ペアリングは、[リモートコントロール](remote-control.md)を参照してください。 +リモートコントロールでは、代わりに新しいペアリングリンクを **サーバーのアドレスまたはリンク** に貼り付けます。ブックマークはトンネルのオリジンだけを保持し、使い捨てのペアリングコードは保持しません。端末 Cookie 消失後の再ペアリングは、[リモートコントロール](remote-control.md)を参照してください。 ## リモートプロジェクトをタブで開く {#remote-project-tabs} デスクトップアプリ(Electron、または Windows の Tauri)では、保存済みサーバーのプロジェクトを、ローカルプロジェクトと並べてこのウィンドウのタブで開くこともできます。 -1. ホームページまたは **タブを開く** ランチャーで **参照** を開いてサーバーを選ぶか、**サーバーを追加…** で追加します。 +1. ホームページまたは **タブを開く** ランチャーで **参照** を開いてサーバーを選ぶか、アドレスまたはペアリングリンクを **サーバーのアドレスまたはリンク** に貼り付けます。 2. タブ内でフォルダーを選びます。タブにはサーバーアイコンとプロジェクト名が表示され、プロジェクトは **最近** に加わります。そこで選ぶと、そのサーバーとフォルダーが直接開き直されます。 タブにはそのプロジェクトだけが表示され、会話、ファイル、Git、設定、Missions はリモートサーバーで動作します。タブはそのサーバーのリモートウィンドウと同じストレージを使うため、既存のサインインやペアリング済みデバイスがそのまま使われ、CodeNomad がタブを復元するとリモートタブも戻ります。このモードを持たないサーバーは、タブに完全なインターフェースを表示します。TLS 検証を省略するサーバーと、macOS・Linux の Tauri ビルドでは、引き続きリモートウィンドウが開きます。タブ内のページは通知を表示できますが、このコンピューターへのその他のアクセスはなく、自分のサーバーから離れません。Web クライアントと Remote Control デバイスにはリモートタブはありません。**設定 → サーバー** の **保存したサーバーを削除** は、そのタブも閉じます。プロジェクトを選ぶ前のタブにはサーバー名が表示されます。タブ内のサーバーのページでサインインしてください。CodeNomad は次回以降の起動でもそのサインインを再利用します。 diff --git a/docs/help/ja/remote-control.md b/docs/help/ja/remote-control.md index d5f6149fba..f54f6002f5 100644 --- a/docs/help/ja/remote-control.md +++ b/docs/help/ja/remote-control.md @@ -11,7 +11,7 @@ リンクの有効期間は **5 分**、成功するのは **1 回** です。利用した人はペアリング済み端末になれるため、認証情報として扱ってください。コードはクエリ文字列ではなく URL フラグメントに入ります。**新しいペアリングリンクを作成** は、直前の未使用リンクを即座に無効化します。停止、バックエンドの終了、トンネル障害は、未使用のペアリングリンクをキャンセルします。 -別のデスクトップ CodeNomad をペアリングするには、そのホームページで **新しいサーバー** を選び、リンクを **サーバー URL** に貼り付けます。リンクを開くとコードが消費されるため、**保存** からでもサーバーが開いてペアリングされます。ブックマークにはトンネルのオリジンのみを保存し、コードは保持しません。ペアリングリンクでは TLS 検証を有効のまま維持します。 +別のデスクトップ CodeNomad をペアリングするには、そのホームページで **参照** を開き、リンクを **サーバーのアドレスまたはリンク** に貼り付けます。サーバーが開いてペアリングされます。ブックマークにはトンネルのオリジンのみを保存し、コードは保持しません。ペアリングリンクでは TLS 検証を有効のまま維持します。 ## ペアリング済み端末を管理する {#paired-devices} diff --git a/docs/help/ne/remote-access.md b/docs/help/ne/remote-access.md index e3b251ede4..b347ccf796 100644 --- a/docs/help/ne/remote-access.md +++ b/docs/help/ne/remote-access.md @@ -83,23 +83,23 @@ certificate चेतावनी आए रोकिएर hostname, SAN, trust ## remote server बचत {#saved-servers} -1. desktop गृह पृष्ठमा **नयाँ सर्भर** छान्नुहोस्, वा गृह पृष्ठ वा **ट्याब खोल्नुहोस्** लन्चरको **ब्राउज गर्नुहोस्** को अन्तिममा रहेको **सर्भर थप्नुहोस्…** छान्नुहोस्। **सेटिङहरू → सर्भरहरू** मा **सर्भर थप्नुहोस्…** बाट पनि यही गर्न सकिन्छ। -2. **सर्भरमा जडान गर्नुहोस्** मा **सर्भर URL** मा विश्वसनीय HTTPS origin वा pairing link प्रविष्ट गर्नुहोस्। **सर्भरको नाम** ऐच्छिक हो; यो नभए सर्भरले आफ्नो host name देखाउँछ। **स्व-हस्ताक्षरित प्रमाणपत्रहरूको लागि TLS प्रमाणीकरण छोड्नुहोस्।** अनचेक नै राख्नुहोस्; बरु विश्वास स्थापित गर्नुहोस्। प्रमाणपत्र जाँचमा असफल भए संवादले त्यो देखाउँछ। -3. bookmark गर्न **बचत गर्नुहोस्**, वा बचत र खोल्न **जडान गर्नुहोस्** रोज्नुहोस्। त्यो server मा sign in गर्नुहोस्। +1. desktop गृह पृष्ठमा वा **ट्याब खोल्नुहोस्** लन्चरमा **ब्राउज गर्नुहोस्** खोल्नुहोस्, सर्भरको ठेगाना वा pairing link **सर्भरको ठेगाना वा लिङ्क** मा टाँस्नुहोस् र Enter थिच्नुहोस्: सर्भर आफ्नो host name मा बचत भई खुल्छ। **सेटिङहरू → सर्भरहरू** मा पनि यही फिल्ड छ। +2. विश्वसनीय HTTPS origin प्रयोग गर्नुहोस्। यसको प्रमाणपत्र जाँचमा असफल भए फिल्डमुनि त्रुटि र **TLS प्रमाणीकरण छोड्नुहोस्** देखिन्छ: विश्वसनीय सर्भरका लागि मात्र यसलाई चिन्ह लगाएर फेरि Enter थिच्नुहोस्; त्यो सर्भर आफ्नै विन्डोमा खुल्छ। +3. त्यो सर्भरमा sign in गर्नुहोस्। यसको नाम वा ठेगाना **सेटिङहरू → सर्भरहरू** मा **सर्भर सम्पादन गर्नुहोस्** बाट बदल्नुहोस्। बचत गरिएका सर्भरहरू **ब्राउज गर्नुहोस्** मा देखिन्छन्: फेरि खोल्न एउटा छान्नुहोस्। **सेटिङहरू → सर्भरहरू** मा तिनलाई खोल्न, सम्पादन गर्न (**सर्भर सम्पादन गर्नुहोस्**: नाम, ठेगाना, प्रमाणपत्र जाँच) र हटाउन (**बचत गरिएको सर्भर हटाउनुहोस्**) सकिन्छ। bookmark यो CodeNomad कन्फिगरेसनका हुन्, remote server का project होइनन्। URL बचतले server सुरु वा access प्रदान गर्दैन। **बचत गरिएको सर्भर हटाउनुहोस्** ले bookmark हटाउँछ, remote कुराकानी, backend वा credential होइन। -सुरक्षित सर्भर command line बाट सिधै खोल्न, सर्भरको सुरक्षित नाम वा यसको `https://` URL सहित desktop app लाई `--connect-server ` (वा `--connect-server=`) सँग सुरु गर्नुहोस्। CodeNomad ले remote window मात्र खोल्छ, **जडान गर्नुहोस्** जस्तै उही जाँच र sign in सहित; CodeNomad पहिले नै चलिरहेको छ भने, नयाँ window को सट्टा यसको हालको window ले त्यसलाई खोल्छ। कुनै सुरक्षित सर्भरसँग नमिल्ने URL यसको host नाममा बचत हुन्छ। सुरु गर्दा दिइने मानमा credential कहिल्यै हुँदैन: user नाम, password वा pairing code भएको URL अस्वीकार हुन्छ। नाम अज्ञात भए, URL अमान्य भए वा जडान असफल भए, CodeNomad सामान्य रूपमा सुरु हुन्छ र त्रुटि देखाउँछ। स्व-हस्ताक्षरित सर्भरका लागि स्थानीय प्रमाणपत्र स्थापना जस्ता पुष्टि जडानलाई चाहिँदा पनि, CodeNomad सामान्य रूपमा सुरु हुन्छ र त्यहीँ सोध्छ। Windows मा, सुरु गर्ने argument मा `|` भए Tauri build सुरु हुँदैन; बरु सर्भरको URL प्रयोग गर्नुहोस्, वा सर्भरको नाम बदल्नुहोस्। +सुरक्षित सर्भर command line बाट सिधै खोल्न, सर्भरको सुरक्षित नाम वा यसको `https://` URL सहित desktop app लाई `--connect-server ` (वा `--connect-server=`) सँग सुरु गर्नुहोस्। CodeNomad ले remote window मात्र खोल्छ, **ब्राउज गर्नुहोस्** जस्तै उही जाँच र sign in सहित; CodeNomad पहिले नै चलिरहेको छ भने, नयाँ window को सट्टा यसको हालको window ले त्यसलाई खोल्छ। कुनै सुरक्षित सर्भरसँग नमिल्ने URL यसको host नाममा बचत हुन्छ। सुरु गर्दा दिइने मानमा credential कहिल्यै हुँदैन: user नाम, password वा pairing code भएको URL अस्वीकार हुन्छ। नाम अज्ञात भए, URL अमान्य भए वा जडान असफल भए, CodeNomad सामान्य रूपमा सुरु हुन्छ र त्रुटि देखाउँछ। स्व-हस्ताक्षरित सर्भरका लागि स्थानीय प्रमाणपत्र स्थापना जस्ता पुष्टि जडानलाई चाहिँदा पनि, CodeNomad सामान्य रूपमा सुरु हुन्छ र त्यहीँ सोध्छ। Windows मा, सुरु गर्ने argument मा `|` भए Tauri build सुरु हुँदैन; बरु सर्भरको URL प्रयोग गर्नुहोस्, वा सर्भरको नाम बदल्नुहोस्। रिमोट विन्डोले यो कम्प्युटरमा फर्कने बाटो सधैँ छोड्छ। रिमोट विन्डोहरू खुला रहँदा अन्तिम स्थानीय विन्डो बन्द गर्दा त्यसका ट्याबहरू रहन्छन्: रिमोट विन्डोमा **सञ्झ्याल → नयाँ विन्डो**, वा CodeNomad फेरि सुरु गर्दा त्यो फेरि खुल्छ। सर्भर लोड गर्न नसकिँदा त्यसको विन्डोले त्यो देखाउँछ र **फेरि प्रयास गर्नुहोस्**, **स्थानीय विन्डो खोल्नुहोस्** र **विन्डो बन्द गर्नुहोस्** दिन्छ; Tauri संस्करणमा पृष्ठको रिलोड बटन र **सञ्झ्याल → नयाँ विन्डो** प्रयोग गर्नुहोस्। -Remote Control मा **सर्भर URL** मा नयाँ pairing link paste गर्नुहोस्। bookmark ले tunnel origin मात्र राख्छ, one-use code कहिल्यै होइन; device-cookie हराएपछि पुनःpair गर्न [Remote Control](remote-control.md) हेर्नुहोस्। +Remote Control मा **सर्भरको ठेगाना वा लिङ्क** मा नयाँ pairing link paste गर्नुहोस्। bookmark ले tunnel origin मात्र राख्छ, one-use code कहिल्यै होइन; device-cookie हराएपछि पुनःpair गर्न [Remote Control](remote-control.md) हेर्नुहोस्। ## रिमोट परियोजना ट्याबमा खोल्नुहोस् {#remote-project-tabs} डेस्कटप एपमा (Electron, वा Windows मा Tauri), बचत गरिएको सर्भरले आफ्नो कुनै परियोजना यो सञ्झ्यालको ट्याबमा, तपाईंका स्थानीय परियोजनाहरूसँगै, खोल्न पनि सक्छ: -1. गृह पृष्ठमा वा **ट्याब खोल्नुहोस्** लन्चरमा **ब्राउज गर्नुहोस्** खोलेर सर्भर छान्नुहोस्, वा थप्न **सर्भर थप्नुहोस्…** छान्नुहोस्। +1. गृह पृष्ठमा वा **ट्याब खोल्नुहोस्** लन्चरमा **ब्राउज गर्नुहोस्** खोलेर सर्भर छान्नुहोस्, वा ठेगाना वा pairing link **सर्भरको ठेगाना वा लिङ्क** मा टाँस्नुहोस्। 2. ट्याबमा फोल्डर छान्नुहोस्। त्यसपछि ट्याबले सर्भर आइकन र परियोजनाको नाम देखाउँछ, र परियोजना **हालका** मा थपिन्छ: त्यहाँ छान्दा त्यही सर्भर र फोल्डर सिधै फेरि खुल्छ। ट्याबले त्यही परियोजना मात्र देखाउँछ; यसका कुराकानी, फाइल, Git, सेटिङ र Missions रिमोट सर्भरमा चल्छन्। यसले सर्भरको रिमोट सञ्झ्यालकै भण्डारण प्रयोग गर्छ, त्यसैले भइरहेको साइन-इन वा पेयर गरिएको उपकरण फेरि प्रयोग हुन्छ, र CodeNomad ले तपाईंका ट्याब पुनर्स्थापना गर्दा रिमोट ट्याबहरू पनि फर्कन्छन्। यो मोड नभएको सर्भरले ट्याबमा आफ्नो पूर्ण इन्टरफेस देखाउँछ। TLS प्रमाणीकरण छोड्ने सर्भरहरू, र macOS तथा Linux मा Tauri बिल्डले, रिमोट सञ्झ्याल नै खोलिरहन्छन्। ट्याबको पृष्ठले सूचना देखाउन सक्छ, तर यो कम्प्युटरमा अरू पहुँच हुँदैन र यो आफ्नै सर्भरमा रहन्छ। वेब क्लाइन्ट र Remote Control उपकरणहरूमा रिमोट ट्याब हुँदैन। **सेटिङहरू → सर्भरहरू** मा रहेको **बचत गरिएको सर्भर हटाउनुहोस्** ले यसका ट्याबहरू पनि बन्द गर्छ। परियोजना छान्नुअघि ट्याबले सर्भरको नाम देखाउँछ। ट्याबभित्र सर्भरकै पृष्ठमा sign in गर्नुहोस्; CodeNomad ले पछिका सुरुवातहरूमा त्यही sign-in फेरि प्रयोग गर्छ। diff --git a/docs/help/ne/remote-control.md b/docs/help/ne/remote-control.md index 5e762a3ae9..e31dda2819 100644 --- a/docs/help/ne/remote-control.md +++ b/docs/help/ne/remote-control.md @@ -11,7 +11,7 @@ Remote Control ले paired browser वा desktop client लाई inbound net link **पाँच मिनेट** मान्य हुन्छ र **एकपटक** सफल हुन्छ। credential झैं लिनुहोस्: प्रयोग गर्ने जोकोही paired device बन्न सक्छ। code URL fragment मा हुन्छ, query string मा होइन। **नयाँ जोडी लिंक बनाउनुहोस्** ले अघिल्लो unused link तुरुन्त अमान्य गर्छ। Stop, backend shutdown र tunnel failure ले बाँकी pairing link रद्द गर्छन्। -अर्को desktop CodeNomad pair गर्न त्यसको गृह पृष्ठमा **नयाँ सर्भर** छान्नुहोस् र link **सर्भर URL** मा टाँस्नुहोस्: सर्भर खुल्छ र pair हुन्छ, **बचत गर्नुहोस्** बाट पनि, किनकि खोल्दा नै code खपत हुन्छ। bookmark मा tunnel origin मात्र बचत हुन्छ; code रहँदैन। pairing link मा TLS verification enabled रहन्छ। +अर्को desktop CodeNomad pair गर्न त्यसको गृह पृष्ठमा **ब्राउज गर्नुहोस्** खोली link **सर्भरको ठेगाना वा लिङ्क** मा टाँस्नुहोस्: सर्भर खुल्छ र pair हुन्छ। bookmark मा tunnel origin मात्र बचत हुन्छ; code रहँदैन। pairing link मा TLS verification enabled रहन्छ। ## paired device व्यवस्थापन {#paired-devices} diff --git a/docs/help/ru/remote-access.md b/docs/help/ru/remote-access.md index 47dfb73a22..c46405e9f3 100644 --- a/docs/help/ru/remote-access.md +++ b/docs/help/ru/remote-access.md @@ -83,23 +83,23 @@ codenomad --host 127.0.0.1 --https=false --http=true ## Сохранение удалённого сервера {#saved-servers} -1. На главной странице настольного приложения выберите **Новый сервер** или **Добавить сервер…** в конце **Обзор** — на главной странице или в панели запуска **Открыть вкладку**. То же доступно в **Настройки → Серверы** через **Добавить сервер…**. -2. В **Подключиться к серверу** введите в поле **URL сервера** доверенный HTTPS-источник или ссылку сопряжения. **Имя сервера** указывать необязательно; без него сервер показывается под именем хоста. Оставьте **Пропустить проверку TLS для самоподписанных сертификатов.** выключенным; вместо этого установите доверие. Если сертификат не прошёл проверку, диалог сообщит об этом. -3. Нажмите **Сохранить** для закладки или **Подключиться** для сохранения и открытия. Войдите на этом сервере. +1. На главной странице настольного приложения или в панели запуска **Открыть вкладку** откройте **Обзор**, вставьте адрес сервера или ссылку сопряжения в поле **Адрес или ссылка сервера** и нажмите Enter: сервер сохранится под именем хоста и откроется. В **Настройки → Серверы** есть то же поле. +2. Используйте доверенный HTTPS-источник. Если его сертификат не прошёл проверку, под полем появится ошибка и **Пропустить проверку TLS**: включайте это только для доверенного сервера и снова нажмите Enter; такой сервер открывается в отдельном окне. +3. Войдите на этом сервере. Переименуйте его или измените адрес через **Изменить сервер** в **Настройки → Серверы**. Сохранённые серверы перечислены в **Обзор**: выберите сервер, чтобы снова открыть его. В **Настройки → Серверы** их можно открыть, изменить (**Изменить сервер**: имя, адрес, проверка сертификата) и удалить (**Удалить сохраненный сервер**). Закладки принадлежат этой конфигурации CodeNomad, не проектам удалённого сервера. Сохранение URL не запускает сервер и не предоставляет доступ. **Удалить сохраненный сервер** удаляет закладку, не удалённые разговоры, серверную часть или её учётные данные. -Чтобы открыть сохранённый сервер прямо из командной строки, запустите настольное приложение с `--connect-server ` (или `--connect-server=`), указав сохранённое имя сервера или его URL `https://`. CodeNomad открывает только удалённое окно, с теми же проверками и входом, что и **Подключиться**; если CodeNomad уже запущен, сервер открывает его текущее окно, а не новое. URL, не совпадающий ни с одним сохранённым сервером, сохраняется под именем своего хоста. Значения запуска никогда не содержат учётных данных: URL с именем пользователя, паролем или кодом сопряжения отклоняется. Если имя неизвестно, URL недействителен или подключение не удалось, CodeNomad запускается как обычно и показывает ошибку. Если подключению нужно подтверждение, например установка локального сертификата для самоподписанного сервера, CodeNomad тоже запускается как обычно и запрашивает его там. В Windows сборка Tauri не запускается, если аргумент запуска содержит `|`; используйте URL сервера или переименуйте сервер. +Чтобы открыть сохранённый сервер прямо из командной строки, запустите настольное приложение с `--connect-server ` (или `--connect-server=`), указав сохранённое имя сервера или его URL `https://`. CodeNomad открывает только удалённое окно, с теми же проверками и входом, что и **Обзор**; если CodeNomad уже запущен, сервер открывает его текущее окно, а не новое. URL, не совпадающий ни с одним сохранённым сервером, сохраняется под именем своего хоста. Значения запуска никогда не содержат учётных данных: URL с именем пользователя, паролем или кодом сопряжения отклоняется. Если имя неизвестно, URL недействителен или подключение не удалось, CodeNomad запускается как обычно и показывает ошибку. Если подключению нужно подтверждение, например установка локального сертификата для самоподписанного сервера, CodeNomad тоже запускается как обычно и запрашивает его там. В Windows сборка Tauri не запускается, если аргумент запуска содержит `|`; используйте URL сервера или переименуйте сервер. Из удалённого окна всегда можно вернуться на этот компьютер. Если закрыть последнее локальное окно, пока удалённые окна остаются открытыми, его вкладки сохраняются: **Окно → Новое окно** в удалённом окне или повторный запуск CodeNomad открывает его снова. Если сервер не удаётся загрузить, его окно сообщает об этом и предлагает **Повторить**, **Открыть локальное окно** и **Закрыть окно**; в версии Tauri используйте кнопку перезагрузки страницы и **Окно → Новое окно**. -Для удалённого управления вместо этого вставьте свежую ссылку сопряжения в **URL сервера**. Закладка хранит только origin туннеля, никогда одноразовый код; повторное сопряжение после потери cookie устройства описано в [удалённом управлении](remote-control.md). +Для удалённого управления вместо этого вставьте свежую ссылку сопряжения в **Адрес или ссылка сервера**. Закладка хранит только origin туннеля, никогда одноразовый код; повторное сопряжение после потери cookie устройства описано в [удалённом управлении](remote-control.md). ## Открыть удалённый проект во вкладке {#remote-project-tabs} В настольном приложении (Electron или Tauri в Windows) сохранённый сервер может также открыть один из своих проектов во вкладке этого окна, рядом с локальными проектами: -1. На главной странице или в панели запуска **Открыть вкладку** откройте **Обзор** и выберите сервер или **Добавить сервер…**, чтобы добавить его. +1. На главной странице или в панели запуска **Открыть вкладку** откройте **Обзор** и выберите сервер или вставьте адрес или ссылку сопряжения в поле **Адрес или ссылка сервера**. 2. Выберите папку во вкладке. Вкладка покажет значок сервера и имя проекта, а проект появится в **Недавние**: выбор там сразу снова открывает этот сервер и папку. Вкладка показывает только этот проект; его беседы, файлы, Git, настройки и Missions работают на удалённом сервере. Она использует хранилище удалённого окна сервера, поэтому существующий вход или сопряжённое устройство используются повторно, а удалённые вкладки возвращаются, когда CodeNomad восстанавливает вкладки. Сервер без этого режима показывает во вкладке свой полный интерфейс. Серверы, пропускающие проверку TLS, и сборка Tauri в macOS и Linux по-прежнему открывают удалённое окно. Страница во вкладке может показывать уведомления, но не имеет другого доступа к этому компьютеру и остаётся на своём сервере. У веб-клиентов и устройств Remote Control удалённых вкладок нет. **Удалить сохраненный сервер** в **Настройки → Серверы** также закрывает его вкладки. Пока проект не выбран, вкладка показывает имя сервера. Входите на странице сервера в самой вкладке; CodeNomad повторно использует этот вход при следующих запусках. diff --git a/docs/help/ru/remote-control.md b/docs/help/ru/remote-control.md index e2a9bc46d8..dba21d9e13 100644 --- a/docs/help/ru/remote-control.md +++ b/docs/help/ru/remote-control.md @@ -11,7 +11,7 @@ Ссылка действует **пять минут** и срабатывает **один раз**. Считайте её учётными данными: любой использовавший её может стать сопряжённым устройством. Код находится во фрагменте URL, не в строке запроса. **Создать новую ссылку сопряжения** немедленно делает предыдущую неиспользованную ссылку недействительной. Остановка, завершение серверной части и сбой туннеля отменяют ожидающие ссылки сопряжения. -Для сопряжения другого настольного CodeNomad выберите **Новый сервер** на его главной странице и вставьте ссылку в поле **URL сервера**: сервер откроется и будет сопряжён, даже по **Сохранить**, потому что её открытие использует код. В закладке сохраняется только origin туннеля; код не хранится. Проверка TLS для ссылок сопряжения остаётся включённой. +Для сопряжения другого настольного CodeNomad откройте **Обзор** на его главной странице и вставьте ссылку в поле **Адрес или ссылка сервера**: сервер откроется и будет сопряжён. В закладке сохраняется только origin туннеля; код не хранится. Проверка TLS для ссылок сопряжения остаётся включённой. ## Управление сопряжёнными устройствами {#paired-devices} diff --git a/docs/help/tr/remote-access.md b/docs/help/tr/remote-access.md index 94f07fbe34..fb61c4fc89 100644 --- a/docs/help/tr/remote-access.md +++ b/docs/help/tr/remote-access.md @@ -83,23 +83,23 @@ Bir istemci bir sertifika uyarısı bildirirse, durdurun ve ana bilgisayar adın ## Uzak sunucuyu kaydedin {#saved-servers} -1. Masaüstü ana sayfasında **Yeni sunucu** seçin ya da ana sayfada veya **Sekme aç** başlatıcısında **Gözat** listesinin sonundaki **Sunucu ekle…** seçeneğini seçin. **Ayarlar → Sunucular** de **Sunucu ekle…** ile aynısını sunar. -2. **Sunucuya Bağlan** içinde **Sunucu URL'si** alanına güvenilir bir HTTPS kaynağı veya eşleştirme bağlantısı girin. **Sunucu adı** isteğe bağlıdır; girilmezse sunucu ana bilgisayar adıyla görünür. **Kendinden imzalı sertifikalar için TLS doğrulamasını atla.** seçeneğini işaretsiz bırakın; bunun yerine güven oluşturun. Sertifika doğrulamayı geçemezse iletişim kutusu bunu belirtir. -3. Yer imlerine eklemek için **Kaydet** öğesini veya kaydedip açmak için **Bağlan** öğesini seçin. Bu sunucuda oturum açın. +1. Masaüstü ana sayfasında veya **Sekme aç** başlatıcısında **Gözat** bölümünü açın, sunucunun adresini veya bir eşleştirme bağlantısını **Sunucu adresi veya bağlantısı** alanına yapıştırın ve Enter'a basın: sunucu ana bilgisayar adıyla kaydedilir ve açılır. **Ayarlar → Sunucular** de aynı alanı sunar. +2. Güvenilir bir HTTPS kaynağı kullanın. Sertifikası doğrulamayı geçemezse hata, alanın altında **TLS doğrulamasını atla** ile görünür: bunu yalnızca güvendiğiniz bir sunucu için işaretleyin ve yeniden Enter'a basın; bu sunucu kendi penceresinde açılır. +3. O sunucuda oturum açın. Adını veya adresini **Ayarlar → Sunucular** içindeki **Sunucuyu düzenle** ile değiştirin. Kayıtlı sunucular **Gözat** altında listelenir: yeniden açmak için birini seçin. **Ayarlar → Sunucular** bölümünde sunucuları açabilir, düzenleyebilir (**Sunucuyu düzenle**: ad, adres, sertifika doğrulaması) ve kaldırabilirsiniz (**Kayıtlı sunucuyu kaldır**). Yer imleri uzak sunucunun projelerine değil, bu CodeNomad yapılandırmasına aittir. Bir URL'nin kaydedilmesi sunucuyu başlatmaz veya erişim sağlamaz. **Kayıtlı sunucuyu kaldır**, uzak konuşmaları, arka ucu veya kimlik bilgilerini değil, yer işaretini kaldırır. -Kayıtlı bir sunucuyu doğrudan komut satırından açmak için masaüstü uygulamasını sunucunun kayıtlı adıyla veya `https://` URL'siyle `--connect-server ` (ya da `--connect-server=`) seçeneğiyle başlatın. CodeNomad yalnızca uzak pencereyi açar; denetimler ve oturum açma **Bağlan** ile aynıdır. CodeNomad zaten çalışıyorsa sunucuyu yeni bir pencere yerine geçerli penceresi açar. Hiçbir kayıtlı sunucuyla eşleşmeyen bir URL, ana bilgisayar adıyla kaydedilir. Başlatma değerleri hiçbir zaman kimlik bilgisi taşımaz: kullanıcı adı, parola veya eşleştirme kodu içeren bir URL reddedilir. Ad bilinmiyorsa, URL geçersizse veya bağlantı başarısız olursa CodeNomad normal şekilde başlar ve hatayı gösterir. Bağlantı, kendinden imzalı bir sunucu için yerel sertifikanın yüklenmesi gibi bir onay gerektirdiğinde de CodeNomad normal şekilde başlar ve onayı orada ister. Windows'ta bir başlatma bağımsız değişkeni `|` içerdiğinde Tauri derlemesi başlamaz; bunun yerine sunucunun URL'sini kullanın veya sunucuyu yeniden adlandırın. +Kayıtlı bir sunucuyu doğrudan komut satırından açmak için masaüstü uygulamasını sunucunun kayıtlı adıyla veya `https://` URL'siyle `--connect-server ` (ya da `--connect-server=`) seçeneğiyle başlatın. CodeNomad yalnızca uzak pencereyi açar; denetimler ve oturum açma **Gözat** ile aynıdır. CodeNomad zaten çalışıyorsa sunucuyu yeni bir pencere yerine geçerli penceresi açar. Hiçbir kayıtlı sunucuyla eşleşmeyen bir URL, ana bilgisayar adıyla kaydedilir. Başlatma değerleri hiçbir zaman kimlik bilgisi taşımaz: kullanıcı adı, parola veya eşleştirme kodu içeren bir URL reddedilir. Ad bilinmiyorsa, URL geçersizse veya bağlantı başarısız olursa CodeNomad normal şekilde başlar ve hatayı gösterir. Bağlantı, kendinden imzalı bir sunucu için yerel sertifikanın yüklenmesi gibi bir onay gerektirdiğinde de CodeNomad normal şekilde başlar ve onayı orada ister. Windows'ta bir başlatma bağımsız değişkeni `|` içerdiğinde Tauri derlemesi başlamaz; bunun yerine sunucunun URL'sini kullanın veya sunucuyu yeniden adlandırın. Uzak pencere bu bilgisayara dönmenin bir yolunu her zaman bırakır. Uzak pencereler açık kalırken son yerel pencereyi kapatmak sekmelerini korur: uzak penceredeki **Pencere → Yeni pencere** ya da CodeNomad'ı yeniden başlatmak onu yeniden açar. Bir sunucu yüklenemezse penceresi bunu bildirir ve **Yeniden dene**, **Yerel pencere aç** ve **Pencereyi kapat** seçeneklerini sunar; Tauri sürümünde sayfanın yeniden yükleme düğmesini ve **Pencere → Yeni pencere** öğesini kullanın. -Uzaktan Kontrol için bunun yerine **Sunucu URL'si** öğesine yeni bir eşleştirme bağlantısı yapıştırın. Yer imi yalnızca tünelin kökenini korur, asla tek kullanımlık eşleştirme kodunu içermez; Cihaz çerezi kaybından sonra yeniden eşleştirme için bkz. [Uzaktan Kontrol](remote-control.md). +Uzaktan Kontrol için bunun yerine **Sunucu adresi veya bağlantısı** öğesine yeni bir eşleştirme bağlantısı yapıştırın. Yer imi yalnızca tünelin kökenini korur, asla tek kullanımlık eşleştirme kodunu içermez; Cihaz çerezi kaybından sonra yeniden eşleştirme için bkz. [Uzaktan Kontrol](remote-control.md). ## Uzak bir projeyi sekmede açın {#remote-project-tabs} Masaüstü uygulamasında (Electron veya Windows'ta Tauri), kayıtlı bir sunucu projelerinden birini yerel projelerinizin yanında bu pencerenin bir sekmesinde de açabilir: -1. Ana sayfada veya **Sekme aç** başlatıcısında **Gözat** bölümünü açıp bir sunucu seçin ya da eklemek için **Sunucu ekle…** seçin. +1. Ana sayfada veya **Sekme aç** başlatıcısında **Gözat** bölümünü açıp bir sunucu seçin ya da bir adresi veya eşleştirme bağlantısını **Sunucu adresi veya bağlantısı** alanına yapıştırın. 2. Klasörü sekmede seçin. Sekme ardından sunucu simgesini ve proje adını gösterir ve proje **Son kullanılanlar** listesine eklenir: oradan seçmek o sunucuyu ve klasörü doğrudan yeniden açar. Sekme yalnızca o projeyi gösterir; konuşmaları, dosyaları, Git'i, ayarları ve Missions uzak sunucuda çalışır. Sekme sunucunun uzak penceresiyle aynı depolamayı kullanır; böylece mevcut bir oturum veya eşleştirilmiş cihaz yeniden kullanılır ve CodeNomad sekmelerinizi geri yüklediğinde uzak sekmeler de geri gelir. Bu modu olmayan bir sunucu sekmede tam arayüzünü gösterir. TLS doğrulamasını atlayan sunucular ile macOS ve Linux'taki Tauri sürümü uzak pencere açmaya devam eder. Sekmedeki sayfa bildirim gösterebilir, ancak bu bilgisayara başka erişimi yoktur ve kendi sunucusunda kalır. Web istemcilerinde ve Remote Control cihazlarında uzak sekme yoktur. **Ayarlar → Sunucular** içindeki **Kayıtlı sunucuyu kaldır** sunucunun sekmelerini de kapatır. Proje seçilmeden önce sekme sunucunun adını gösterir. Sekmenin içinde sunucunun sayfasında oturum açın; CodeNomad bu oturumu sonraki açılışlarda yeniden kullanır. diff --git a/docs/help/tr/remote-control.md b/docs/help/tr/remote-control.md index 271f713902..99996c31d1 100644 --- a/docs/help/tr/remote-control.md +++ b/docs/help/tr/remote-control.md @@ -11,7 +11,7 @@ Uzaktan Kontrol, eşleştirilmiş bir tarayıcının veya masaüstü istemcisini Bağlantı **beş dakika** süreyle geçerlidir ve **bir kez** başarılı olur. Bunu bir kimlik bilgisi olarak değerlendirin: Bunu tüketen herkes eşleştirilmiş bir cihaz haline gelebilir. Kod, sorgu dizesinde değil, URL parçasında bulunur. **Yeni eşleştirme bağlantısı oluştur**, önceki kullanılmayan bağlantıyı anında geçersiz kılar. Durdurma, arka uç kapatma ve tünel arızası, bekleyen eşleştirme bağlantılarını iptal eder. -Başka masaüstü CodeNomad istemcisini eşleştirmek için onun ana sayfasında **Yeni sunucu** seçin ve bağlantıyı **Sunucu URL'si** alanına yapıştırın: sunucu açılır ve eşleşir, **Kaydet** ile bile, çünkü bağlantıyı açmak kodu tüketir. Yer imi yalnızca tünelin origin adresini saklar; kod saklanmaz. Eşleştirme bağlantılarında TLS doğrulaması etkin kalır. +Başka masaüstü CodeNomad istemcisini eşleştirmek için onun ana sayfasında **Gözat** bölümünü açın ve bağlantıyı **Sunucu adresi veya bağlantısı** alanına yapıştırın: sunucu açılır ve eşleşir. Yer imi yalnızca tünelin origin adresini saklar; kod saklanmaz. Eşleştirme bağlantılarında TLS doğrulaması etkin kalır. ## Eşleştirilmiş cihazları yönetin {#paired-devices} diff --git a/docs/help/zh-Hans/remote-access.md b/docs/help/zh-Hans/remote-access.md index 4d1b6fc64a..3197d0b99d 100644 --- a/docs/help/zh-Hans/remote-access.md +++ b/docs/help/zh-Hans/remote-access.md @@ -83,23 +83,23 @@ codenomad --host 127.0.0.1 --https=false --http=true ## 保存远程服务器 {#saved-servers} -1. 在桌面主页选择 **新建服务器**,或在主页或 **打开标签页** 启动器中选择 **浏览** 末尾的 **添加服务器…**。**设置 → 服务器** 中的 **添加服务器…** 也提供相同操作。 -2. 在 **连接到服务器** 中,于 **服务器 URL** 输入受信任的 HTTPS 源或配对链接。**服务器名称** 可选;不填写时服务器显示其主机名。请保持 **为自签名证书跳过 TLS 验证。** 未勾选,改为建立信任。证书未通过检查时,对话框会给出提示。 -3. 选择**保存**添加书签,或选择**连接**保存并打开。在该服务器上登录。 +1. 在桌面主页或 **打开标签页** 启动器中打开 **浏览**,将服务器地址或配对链接粘贴到 **服务器地址或链接** 并按 Enter:服务器以其主机名保存并打开。**设置 → 服务器** 也提供相同的输入框。 +2. 请使用受信任的 HTTPS 源。如果其证书未通过检查,输入框下方会显示错误和 **跳过 TLS 验证**:仅对可信的服务器勾选,然后再次按 Enter;该服务器会在单独的窗口中打开。 +3. 在该服务器上登录。可在 **设置 → 服务器** 中通过 **编辑服务器** 重命名或更改其地址。 已保存的服务器列在 **浏览** 中:选择一个即可再次打开。在 **设置 → 服务器** 中可以打开、编辑(**编辑服务器**:名称、地址、证书检查)和移除(**删除已保存服务器**)服务器。书签属于此 CodeNomad 配置,而非远程服务器项目。保存 URL 不会启动服务器或授予访问。**删除已保存服务器**移除书签,而非远程对话、后端或凭据。 -要直接从命令行打开已保存的服务器,请使用服务器的保存名称或其 `https://` URL,以 `--connect-server `(或 `--connect-server=`)启动桌面应用。CodeNomad 只打开远程窗口,检查和登录与**连接**相同;如果 CodeNomad 已在运行,则由其当前窗口打开,而不是新建窗口。未匹配任何已保存服务器的 URL 会以其主机名保存。启动值绝不携带凭据:包含用户名、密码或配对码的 URL 会被拒绝。如果名称未知、URL 无效或连接失败,CodeNomad 会正常启动并显示错误。 当连接需要确认(例如为自签名服务器安装本地证书)时,CodeNomad 同样会正常启动并在其中询问。 在 Windows 上,如果启动参数包含 `|`,Tauri 版本会拒绝启动;请改用服务器的 URL,或重命名该服务器。 +要直接从命令行打开已保存的服务器,请使用服务器的保存名称或其 `https://` URL,以 `--connect-server `(或 `--connect-server=`)启动桌面应用。CodeNomad 只打开远程窗口,检查和登录与**浏览**相同;如果 CodeNomad 已在运行,则由其当前窗口打开,而不是新建窗口。未匹配任何已保存服务器的 URL 会以其主机名保存。启动值绝不携带凭据:包含用户名、密码或配对码的 URL 会被拒绝。如果名称未知、URL 无效或连接失败,CodeNomad 会正常启动并显示错误。 当连接需要确认(例如为自签名服务器安装本地证书)时,CodeNomad 同样会正常启动并在其中询问。 在 Windows 上,如果启动参数包含 `|`,Tauri 版本会拒绝启动;请改用服务器的 URL,或重命名该服务器。 远程窗口始终保留返回本机的途径。在远程窗口仍打开时关闭最后一个本地窗口,会保留其标签页:在远程窗口中使用 **窗口 → 新建窗口**,或再次启动 CodeNomad,即可重新打开它。如果无法加载某个服务器,其窗口会说明情况,并提供 **重试**、**打开本地窗口** 和 **关闭窗口**;在 Tauri 版本中,请使用页面的重新加载按钮和 **窗口 → 新建窗口**。 -使用远程控制时,改为将新配对链接粘贴到**服务器 URL**。书签仅保留隧道来源,绝不保留一次性配对码;设备 cookie 丢失后的重新配对请参阅[远程控制](remote-control.md)。 +使用远程控制时,改为将新配对链接粘贴到**服务器地址或链接**。书签仅保留隧道来源,绝不保留一次性配对码;设备 cookie 丢失后的重新配对请参阅[远程控制](remote-control.md)。 ## 在标签页中打开远程项目 {#remote-project-tabs} 在桌面应用中(Electron,或 Windows 上的 Tauri),已保存的服务器也可以在此窗口的标签页中打开其某个项目,与本地项目并列: -1. 在主页或 **打开标签页** 启动器中打开 **浏览** 并选择一个服务器,或选择 **添加服务器…** 添加服务器。 +1. 在主页或 **打开标签页** 启动器中打开 **浏览** 并选择一个服务器,或将地址或配对链接粘贴到 **服务器地址或链接** 中。 2. 在标签页中选择文件夹。标签页随后显示服务器图标和项目名称,该项目也会加入 **最近**:在那里选择它会直接重新打开该服务器和文件夹。 标签页只显示该项目;其对话、文件、Git、设置和 Missions 都在远程服务器上运行。它使用该服务器远程窗口的存储,因此会沿用已有的登录或已配对设备;CodeNomad 恢复标签页时,远程标签页也会恢复。没有此模式的服务器会在标签页中显示其完整界面。跳过 TLS 验证的服务器,以及 macOS 和 Linux 上的 Tauri 版本,仍然打开远程窗口。标签页中的页面可以显示通知,但对这台计算机没有其他访问权限,并始终停留在其服务器上。Web 客户端和 Remote Control 设备没有远程标签页。**设置 → 服务器** 中的 **删除已保存服务器** 也会关闭它的标签页。选择项目之前,标签页显示服务器名称。请在标签页中的服务器页面登录;CodeNomad 会在之后的启动中继续使用该登录。 diff --git a/docs/help/zh-Hans/remote-control.md b/docs/help/zh-Hans/remote-control.md index a418fcb3e0..2d16c24177 100644 --- a/docs/help/zh-Hans/remote-control.md +++ b/docs/help/zh-Hans/remote-control.md @@ -11,7 +11,7 @@ 链接有效期为**五分钟**,只能成功使用**一次**。请将其视为凭据:任何消费它的人都能成为配对设备。配对码位于 URL 片段,而非查询字符串。**创建新的配对链接**会立即使上一个未使用链接失效。停止、后端关闭和隧道失败会取消未使用的配对链接。 -要配对另一个桌面 CodeNomad,在其主页选择 **新建服务器**,将链接粘贴到 **服务器 URL** 中:服务器随即打开并完成配对,即使选择 **保存** 也是如此,因为打开链接才会消费配对码。书签仅保存隧道来源;不保留配对码。配对链接始终启用 TLS 验证。 +要配对另一个桌面 CodeNomad,在其主页打开 **浏览**,将链接粘贴到 **服务器地址或链接** 中:服务器随即打开并完成配对。书签仅保存隧道来源;不保留配对码。配对链接始终启用 TLS 验证。 ## 管理配对设备 {#paired-devices} From cbc499b1ebc6d250b3121a33b94168d35419b013 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Thu, 5 Nov 2026 22:09:54 +0100 Subject: [PATCH 17/34] feat(tabs): open disposable blank tabs from the tab-bar plus button Give a simple click on + or New instance its own empty tab, with focused search, Recent and Browse choices and the existing clone and temporary actions. Keep the compact launcher gestures, and open Home from the CodeNomad logo on native and web hosts. Home and blank tabs show localized item counts, and Home links to the existing Sponsor page with a heart action. Share recent choices with the launcher and replace only the originating blank slot after local, remote or SideCar opening. Capture the origin before asynchronous server probes and preserve it through folder/clone callbacks. Blank tabs own no backend record and are excluded from restoration; their close action stays local. Validated UI TypeScript, 1,623 UI unit checks, and six related browser files (94 passed, one platform-dependent Electron check skipped), including delayed server connection and the Tauri Sponsor command. The offline Tauri no-bundle release build succeeds without launching it. --- packages/ui/src/App.tsx | 32 ++- packages/ui/src/components/blank-tab-view.tsx | 41 ++++ packages/ui/src/components/browse-menu.tsx | 4 + packages/ui/src/components/entry-count.tsx | 7 + .../src/components/folder-selection-view.tsx | 17 +- packages/ui/src/components/instance-tabs.tsx | 13 +- .../ui/src/components/native-titlebar.tsx | 8 +- .../src/components/new-instance-launcher.tsx | 219 ++---------------- .../ui/src/components/recent-tabs-menu.tsx | 114 +++++++++ .../src/lib/hooks/use-app-session-capture.ts | 2 +- .../lib/hooks/use-remote-server-profiles.ts | 8 +- .../lib/i18n/messages/de/folderSelection.ts | 5 + .../lib/i18n/messages/en/folderSelection.ts | 5 + .../lib/i18n/messages/es/folderSelection.ts | 5 + .../lib/i18n/messages/fr/folderSelection.ts | 5 + .../lib/i18n/messages/he/folderSelection.ts | 5 + .../lib/i18n/messages/ja/folderSelection.ts | 5 + .../lib/i18n/messages/ne/folderSelection.ts | 5 + .../lib/i18n/messages/ru/folderSelection.ts | 5 + .../lib/i18n/messages/tr/folderSelection.ts | 5 + .../i18n/messages/zh-Hans/folderSelection.ts | 5 + packages/ui/src/stores/app-tabs.test.ts | 27 +++ packages/ui/src/stores/app-tabs.ts | 37 ++- packages/ui/src/stores/remote-project-open.ts | 5 +- packages/ui/src/stores/sidecar-open.ts | 4 +- .../ui/src/styles/components/blank-tab.css | 35 +++ packages/ui/src/styles/controls.css | 1 + .../browser/new-instance-launcher.test.ts | 6 +- .../tests/browser/remote-project-tabs.test.ts | 125 +++++++++- 29 files changed, 523 insertions(+), 232 deletions(-) create mode 100644 packages/ui/src/components/blank-tab-view.tsx create mode 100644 packages/ui/src/components/entry-count.tsx create mode 100644 packages/ui/src/components/recent-tabs-menu.tsx create mode 100644 packages/ui/src/styles/components/blank-tab.css diff --git a/packages/ui/src/App.tsx b/packages/ui/src/App.tsx index fd1d8a5bb4..c87fa60ba4 100644 --- a/packages/ui/src/App.tsx +++ b/packages/ui/src/App.tsx @@ -16,6 +16,8 @@ import InstanceDisconnectedModal from "./components/instance-disconnected-modal" import InstanceShell from "./components/instance/instance-shell2" import { SettingsScreen } from "./components/settings-screen" import { NativeTitlebar, hasNativeTitlebar } from "./components/native-titlebar" +import BlankTabView from "./components/blank-tab-view" +import { activeBlankTabId, openBlankTab, closeBlankTab, replaceBlankTab, getInstanceAppTabId } from "./stores/app-tabs" import { SideCarView } from "./components/sidecar-view" import { RemoteProjectView } from "./components/remote-project-view" import { EmbeddedProjectPicker } from "./components/embedded-project-picker" @@ -457,7 +459,7 @@ const App: Component = () => { return recent?.projectName?.trim() || getPathBasename(folderPath) } - async function handleSelectFolder(folderPath: string): Promise { + async function handleSelectFolder(folderPath: string, blankId = activeBlankTabId()): Promise { if (!folderPath) { return false } @@ -472,12 +474,14 @@ const App: Component = () => { recordWorkspaceLaunch(instances().get(result.instanceId)?.folder ?? folderPath, folderPath) if (result.reused) { selectInstanceTab(result.instanceId) + replaceBlankTab(blankId, getInstanceAppTabId(result.instanceId)) setShowFolderSelection(false) log.info("Selected reused instance", { instanceId: result.instanceId, folderPath }) return true } selectInstanceTab(result.instanceId) + replaceBlankTab(blankId, getInstanceAppTabId(result.instanceId)) setShowFolderSelection(false) log.info("Created instance", { @@ -494,7 +498,7 @@ const App: Component = () => { ) const missingBinary = isMissingBinaryMessage(message) if (missingBinary || message.includes("opencode_update_required")) { - openOpenCodeSetup(() => handleSelectFolder(folderPath)) + openOpenCodeSetup(() => handleSelectFolder(folderPath, blankId)) return false } showLaunchError({ source: "create", message, binaryPath: selectedBinary, missingBinary }) @@ -540,11 +544,13 @@ const App: Component = () => { }) } - async function handleNewTemporaryInstance(): Promise { + async function handleNewTemporaryInstance(blankId = activeBlankTabId()): Promise { clearLaunchError() setIsSelectingFolder(true) try { - selectInstanceTab(await openTemporaryInstance()) + const id = await openTemporaryInstance() + selectInstanceTab(id) + replaceBlankTab(blankId, getInstanceAppTabId(id)) setShowFolderSelection(false) } catch (error) { const message = formatLaunchErrorMessage( @@ -555,7 +561,7 @@ const App: Component = () => { ) const missingBinary = isMissingBinaryMessage(message) if (missingBinary || message.includes("opencode_update_required")) { - openOpenCodeSetup(() => handleNewTemporaryInstance()) + openOpenCodeSetup(() => handleNewTemporaryInstance(blankId)) return } showLaunchError({ source: "create", message, binaryPath: serverSettings().opencodeBinary || "opencode2", missingBinary }) @@ -566,10 +572,12 @@ const App: Component = () => { } function handleSelectExistingInstance(instanceId: string, recentPath: string) { + const blankId = activeBlankTabId() const instance = instances().get(instanceId) if (!instance) return recordWorkspaceLaunch(instance.folder, recentPath) selectInstanceTab(instanceId) + replaceBlankTab(blankId, getInstanceAppTabId(instanceId)) setShowFolderSelection(false) log.info("Selected existing instance", { instanceId, folderPath: instance.folder }) } @@ -584,7 +592,8 @@ const App: Component = () => { } function handleNewInstanceRequest() { - setShowFolderSelection(true) + openBlankTab() + setShowFolderSelection(false) } const [launcherOpen, setLauncherOpen] = createSignal(false) @@ -645,6 +654,8 @@ const App: Component = () => { closeInstanceTab(tab.instance.id) } else if (tab.kind === "remote-project") { closeRemoteProjectTab(tab.remoteProjectTab.token) + } else if (tab.kind === "blank") { + closeBlankTab(tab.id) } else { closeSidecarTab(tab.sidecarTab.token) } @@ -778,7 +789,7 @@ const App: Component = () => {
- + setShowFolderSelection(true)} />
@@ -856,6 +867,13 @@ const App: Component = () => { >
+ ) : tab.kind === "blank" ? ( +
+ void handleSelectFolder(path, tab.id)} onSelectExistingInstance={handleSelectExistingInstance} + onNewTemporaryInstance={() => void handleNewTemporaryInstance(tab.id)} /> +
) : (
void + onSelectExistingInstance: (id: string, path: string) => void + onNewTemporaryInstance: () => void +}) { + const { t } = useI18n() + const dialogs = createNewInstanceDialogs({ + defaultPath: () => launchableRecents().find((entry) => !entry.remote && !entry.sidecar)?.path, + isLoading: () => props.isLoading, + onSelectFolder: props.onSelectFolder, + }) + return ( +
+
+
+ +
+
+

{t("folderSelection.browseMenu.title")}

+
+ void dialogs.browse()} /> +
+
+
+ +
+ ) +} diff --git a/packages/ui/src/components/browse-menu.tsx b/packages/ui/src/components/browse-menu.tsx index 6741897fe3..887598cbeb 100644 --- a/packages/ui/src/components/browse-menu.tsx +++ b/packages/ui/src/components/browse-menu.tsx @@ -8,6 +8,7 @@ import { useRemoteServerProfiles } from "../lib/hooks/use-remote-server-profiles import { canOpenRemoteWindows } from "../lib/runtime-env" import { openSidecar } from "../stores/sidecar-open" import ServerAddField from "./server-add-field" +import { remoteServers as savedServers } from "../stores/preferences" import { ensureSidecarsLoaded, sidecars } from "../stores/sidecars" interface BrowseMenuProps { @@ -23,6 +24,9 @@ interface BrowseMenuProps { // One disclosure state per window for the launcher's section. const [expanded, setExpanded] = createSignal(false) +/** Choices only: this computer, available saved servers and configured SideCars (the add field is an action). */ +export const browseEntryCount = () => 1 + (canOpenRemoteWindows() ? savedServers().length : 0) + sidecars().size + /** * Browse, shared by the home page (a tab) and the new-instance launcher (a * folded section): this computer's folders, each saved CodeNomad server, whose diff --git a/packages/ui/src/components/entry-count.tsx b/packages/ui/src/components/entry-count.tsx new file mode 100644 index 0000000000..9fc54c8419 --- /dev/null +++ b/packages/ui/src/components/entry-count.tsx @@ -0,0 +1,7 @@ +import { useI18n } from "../lib/i18n" + +/** The home page's and blank tab's section counters. */ +export default function EntryCount(props: { count: number }) { + const { t } = useI18n() + return

{t(props.count === 1 ? "newTab.items.one" : "newTab.items.other", { count: props.count })}

+} diff --git a/packages/ui/src/components/folder-selection-view.tsx b/packages/ui/src/components/folder-selection-view.tsx index b23969323a..e8c3acaaa8 100644 --- a/packages/ui/src/components/folder-selection-view.tsx +++ b/packages/ui/src/components/folder-selection-view.tsx @@ -3,7 +3,11 @@ import { Clock, Trash2, FolderPlus, Settings, ChevronRight, MonitorUp, Star, X, import { removeRemoteProjectRecent, removeSideCarRecent, useConfig } from "../stores/preferences" import { launchableRecents, openRemoteProject } from "../stores/remote-project-open" import { recentKey, type LaunchableRecent } from "../lib/remote-project-recents" -import BrowseMenu from "./browse-menu" +import BrowseMenu, { browseEntryCount } from "./browse-menu" +import EntryCount from "./entry-count" +import { ensureSidecarsLoaded } from "../stores/sidecars" +import { helpUrl } from "../lib/help-url" +import { Heart } from "lucide-solid" import NewTabActions from "./new-tab-actions" import RecentTabIcon from "./recent-tab-icon" import { openSidecar } from "../stores/sidecar-open" @@ -39,7 +43,8 @@ interface FolderSelectionViewProps { const FolderSelectionView: Component = (props) => { const { removeRecentFolder } = useConfig() - const { t } = useI18n() + const { t, locale } = useI18n() + onMount(() => void ensureSidecarsLoaded()) const [selectedIndex, setSelectedIndex] = createSignal(0) const [hoveredRecentActionPath, setHoveredRecentActionPath] = createSignal(null) const [focusedRecentActionPath, setFocusedRecentActionPath] = createSignal(null) @@ -393,6 +398,12 @@ const FolderSelectionView: Component = (props) => {

CodeNomad

+ { event.preventDefault(); void openExternalUrl(helpUrl(locale(), "sponsor"), "help").then((opened) => { + if (!opened) showAlertDialog(t("commands.openSponsor.failed", { url: helpUrl(locale(), "sponsor") }), { variant: "warning" }) + }) }}> + = (props) => { )} diff --git a/packages/ui/src/components/instance-tabs.tsx b/packages/ui/src/components/instance-tabs.tsx index a73fba4f6d..3439258219 100644 --- a/packages/ui/src/components/instance-tabs.tsx +++ b/packages/ui/src/components/instance-tabs.tsx @@ -12,7 +12,9 @@ import { import InstanceTab from "./instance-tab" import TabScroll from "./tab-scroll" import AppActions from "./app-actions" -import { appActionsInTitlebar } from "./native-titlebar" +import { appActionsInTitlebar, hasNativeTitlebar } from "./native-titlebar" +import { BrandLogo } from "./brand-logo" +import { setShowFolderSelection } from "../stores/ui" import ProjectRenameDialog from "./project-rename-dialog" import { renameProject } from "../stores/project-names" import { Plus, Server } from "lucide-solid" @@ -46,7 +48,8 @@ const AppTabContent: Component = (props) => { const { t } = useI18n() const label = () => props.tab.kind === "sidecar" ? props.tab.sidecarTab.name - : props.tab.kind === "remote-project" ? remoteProjectTabLabel(props.tab.remoteProjectTab) : "" + : props.tab.kind === "remote-project" ? remoteProjectTabLabel(props.tab.remoteProjectTab) + : props.tab.kind === "blank" ? t("newTab.title") : "" return ( <> {props.tab.kind === "instance" ? ( @@ -224,6 +227,12 @@ const InstanceTabs: Component = (props) => { return ( <>
+ + +
diff --git a/packages/ui/src/components/native-titlebar.tsx b/packages/ui/src/components/native-titlebar.tsx index cdc073a55a..7152675e04 100644 --- a/packages/ui/src/components/native-titlebar.tsx +++ b/packages/ui/src/components/native-titlebar.tsx @@ -15,6 +15,7 @@ interface NativeTitlebarProps { /** Hold the app actions on macOS (see `appActionsInTitlebar`). */ actions?: boolean onClose?: () => void | Promise + onHome?: () => void } const menus: NativeTitlebarMenu[] = ["file", "edit", "view", "window", "help"] @@ -63,7 +64,12 @@ export const NativeTitlebar: Component = (props) => { >
{props.title}}> -
diff --git a/packages/ui/src/components/new-instance-launcher.tsx b/packages/ui/src/components/new-instance-launcher.tsx index d18ef8cd7c..8e4a23b164 100644 --- a/packages/ui/src/components/new-instance-launcher.tsx +++ b/packages/ui/src/components/new-instance-launcher.tsx @@ -1,233 +1,50 @@ import { Popover } from "@kobalte/core/popover" -import { For, Show, createEffect, createMemo, createSignal, on } from "solid-js" -import { ChevronRight, Search } from "lucide-solid" +import { useI18n } from "../lib/i18n" +import { launchableRecents } from "../stores/remote-project-open" import { createNewInstanceDialogs } from "./new-instance-dialogs" import BrowseMenu from "./browse-menu" +import RecentTabsMenu from "./recent-tabs-menu" import NewTabActions from "./new-tab-actions" -import RecentTabIcon from "./recent-tab-icon" -import { useI18n } from "../lib/i18n" -import { filterRecents, formatRelativeTime, getDisplayPath, getProjectDisplayName } from "../lib/recent-folder-display" -import { openSidecar } from "../stores/sidecar-open" -import type { LaunchableRecent } from "../lib/remote-project-recents" -import { getExistingInstanceForFolder } from "../stores/instances" -import { launchableRecents, openRemoteProject, openRemoteProjectTabFor } from "../stores/remote-project-open" interface NewInstanceLauncherProps { open: boolean - /** The new-instance button the popup is anchored to. */ anchor?: HTMLElement isLoading: boolean onOpenChange: (open: boolean) => void onSelectFolder: (path: string) => void - onSelectExistingInstance: (instanceId: string, recentPath: string) => void + onSelectExistingInstance: (id: string, path: string) => void onNewTemporaryInstance: () => void } -/** - * Compact launcher opened by a long press, right-click or Alt+Down on the - * new-instance button, the home page's logic in short: the search, the - * collapsible Recent section (projects, remote projects and SideCars; type to - * filter, Enter to open), the folded Browse section, then Clone and New - * temporary tab. Managing recents stays on the full home page, servers and - * SideCars in Settings. - */ -// The recents section's disclosure, unfolded by default and kept per window. -const [recentsExpanded, setRecentsExpanded] = createSignal(true) - +/** The compact + launcher: search, Recent, Browse, Clone and New temporary tab. */ export default function NewInstanceLauncher(props: NewInstanceLauncherProps) { const { t } = useI18n() - const [query, setQuery] = createSignal("") - const [activeIndex, setActiveIndex] = createSignal(0) - let listRef: HTMLDivElement | undefined - const recentFolders = () => launchableRecents() - const dialogs = createNewInstanceDialogs({ - defaultPath: () => recentFolders().find((folder) => !folder.remote && !folder.sidecar)?.path, + defaultPath: () => launchableRecents().find((entry) => !entry.remote && !entry.sidecar)?.path, isLoading: () => props.isLoading, - onSelectFolder: (path) => props.onSelectFolder(path), + onSelectFolder: props.onSelectFolder, }) - - const matches = createMemo(() => filterRecents(recentFolders(), query())) - - // Only Escape returns focus to the button: actions, outside clicks, other - // windows and the home page all hand it elsewhere. - let returnFocus = false - let contentRef: HTMLDivElement | undefined - - // Each opening starts from an empty filter on the most recent project. - createEffect(on(() => props.open, (open) => { - if (!open) return - setQuery("") - setActiveIndex(0) - returnFocus = false - })) - createEffect(on(matches, () => setActiveIndex(0), { defer: true })) - // Keep the highlighted project visible, including after the filter changes. - createEffect(on([activeIndex, matches], ([index]) => { - listRef?.querySelector(`[data-launcher-index="${index}"]`)?.scrollIntoView({ block: "nearest" }) - })) - const close = () => props.onOpenChange(false) - // Close first so the launched flow (dialog, tab, home page) owns focus. - const run = (action: () => void) => { - if (props.isLoading) return - close() - action() - } - - const isOpen = (folder: LaunchableRecent) => - folder.sidecar ? false - : folder.remote ? Boolean(openRemoteProjectTabFor(folder)) : Boolean(getExistingInstanceForFolder(folder.path)) - - function openRecent(folder: LaunchableRecent) { - const sidecar = folder.sidecar - if (sidecar) return run(() => void openSidecar(sidecar.sidecarId)) - const remote = folder.remote - if (remote) return run(() => openRemoteProject(remote.profileId, { folder: folder.path })) - const existing = getExistingInstanceForFolder(folder.path) - run(() => existing ? props.onSelectExistingInstance(existing.id, folder.path) : props.onSelectFolder(folder.path)) - } - - function moveActive(delta: number) { - const count = matches().length - if (!count) return - setActiveIndex((activeIndex() + delta + count) % count) - } - - function handleSearchKeyDown(event: KeyboardEvent) { - // A folded list unfolds on the first arrow. - if ((event.key === "ArrowDown" || event.key === "ArrowUp") && !recentsExpanded()) { - event.preventDefault() - setRecentsExpanded(true) - } - else if (event.key === "ArrowDown") { event.preventDefault(); moveActive(1) } - else if (event.key === "ArrowUp") { event.preventDefault(); moveActive(-1) } - else if (event.key === "Enter" && recentsExpanded()) { - const folder = matches()[activeIndex()] - if (folder) { event.preventDefault(); openRecent(folder) } - } - } - - // Escape folds an unfolded section without closing the launcher, as in Browse; Down returns to the search. - function handleRecentsToggleKeyDown(event: KeyboardEvent) { - if (event.key === "Escape" && recentsExpanded()) { - event.preventDefault() - setRecentsExpanded(false) - } else if (event.key === "ArrowDown" && recentsExpanded()) { - event.preventDefault() - contentRef?.querySelector(".new-instance-launcher-search-input")?.focus() - } - } - - const optionId = (index: number) => `new-instance-launcher-option-${index}` - + let returnFocus = false + let content: HTMLDivElement | undefined return ( <> - props.anchor} - placement="bottom-start" - gutter={6} - > + props.anchor} placement="bottom-start" gutter={6}> - { returnFocus = true }} - onCloseAutoFocus={(event) => { - // The popup has an anchor, not a Kobalte trigger: restore focus ourselves, - // unless another surface has taken it meanwhile. + { returnFocus = true }} onCloseAutoFocus={(event) => { event.preventDefault() const active = document.activeElement - const unclaimed = !active || active === document.body || Boolean(contentRef?.contains(active)) - if (returnFocus && unclaimed) props.anchor?.focus() + if (returnFocus && (!active || active === document.body || content?.contains(active))) props.anchor?.focus() returnFocus = false }}> -
- {t("newInstanceLauncher.title")} -
+
{t("newInstanceLauncher.title")}
{t("newInstanceLauncher.description")} - - - - {/* A folded section titled like Browse; the search keeps driving its list. */} - - -
- - {t(recentFolders().length ? "newInstanceLauncher.noMatch" : "newInstanceLauncher.empty")} -

} - > - {(folder, index) => { - const existing = () => isOpen(folder) - return ( -
setActiveIndex(index())} - onClick={() => openRecent(folder)} - > - - {getProjectDisplayName(folder.path, folder.projectName)} - - {folder.sidecar ? t("folderSelection.recent.sidecar") - : folder.remote ? `${folder.remote.serverName} · ${getDisplayPath(folder.path)}` : getDisplayPath(folder.path)} - - {formatRelativeTime(t, folder.lastAccessed)}} - > - - - -
- ) - }} -
-
-
- + void dialogs.browse()} /> -
- -
+
diff --git a/packages/ui/src/components/recent-tabs-menu.tsx b/packages/ui/src/components/recent-tabs-menu.tsx new file mode 100644 index 0000000000..0cdbdb74d1 --- /dev/null +++ b/packages/ui/src/components/recent-tabs-menu.tsx @@ -0,0 +1,114 @@ +import { For, Show, createEffect, createMemo, createSignal, createUniqueId, on } from "solid-js" +import { ChevronRight, Search } from "lucide-solid" +import { useI18n } from "../lib/i18n" +import { filterRecents, formatRelativeTime, getDisplayPath, getProjectDisplayName } from "../lib/recent-folder-display" +import type { LaunchableRecent } from "../lib/remote-project-recents" +import { launchableRecents, openRemoteProject, openRemoteProjectTabFor } from "../stores/remote-project-open" +import { openSidecar } from "../stores/sidecar-open" +import { ensureSidecarsLoaded } from "../stores/sidecars" +import { getExistingInstanceForFolder } from "../stores/instances" +import RecentTabIcon from "./recent-tab-icon" +import EntryCount from "./entry-count" + +const [expanded, setExpanded] = createSignal(true) + +/** Search and recent choices shared by the compact launcher and a blank tab. */ +export default function RecentTabsMenu(props: { + isLoading: boolean + active: boolean + alwaysOpen?: boolean + counts?: boolean + onSelectFolder: (path: string) => void + onSelectExistingInstance: (id: string, path: string) => void + onRun?: () => void +}) { + const { t } = useI18n() + const [query, setQuery] = createSignal("") + const listId = `recent-list-${createUniqueId()}` + const optionId = (position: number) => `${listId}-option-${position}` + const [index, setIndex] = createSignal(0) + const matches = createMemo(() => filterRecents(launchableRecents(), query())) + const shown = () => props.alwaysOpen || expanded() + let root: HTMLDivElement | undefined + let list: HTMLDivElement | undefined + createEffect(on(() => props.active, (active) => { + if (!active) return + setQuery("") + setIndex(0) + void ensureSidecarsLoaded() + if (props.alwaysOpen) requestAnimationFrame(() => root?.querySelector("input")?.focus()) + })) + createEffect(on(matches, () => setIndex(0), { defer: true })) + createEffect(on([index, matches], ([value]) => { + list?.querySelector(`[data-launcher-index="${value}"]`)?.scrollIntoView({ block: "nearest" }) + })) + const existing = (recent: LaunchableRecent) => recent.sidecar ? false + : recent.remote ? Boolean(openRemoteProjectTabFor(recent)) : Boolean(getExistingInstanceForFolder(recent.path)) + function open(recent: LaunchableRecent) { + if (props.isLoading) return + props.onRun?.() + if (recent.sidecar) return void openSidecar(recent.sidecar.sidecarId) + if (recent.remote) return openRemoteProject(recent.remote.profileId, { folder: recent.path }) + const instance = getExistingInstanceForFolder(recent.path) + if (instance) props.onSelectExistingInstance(instance.id, recent.path) + else props.onSelectFolder(recent.path) + } + function searchKey(event: KeyboardEvent) { + if (event.key === "ArrowDown" || event.key === "ArrowUp") { + event.preventDefault() + if (!shown()) setExpanded(true) + else if (matches().length) setIndex((index() + (event.key === "ArrowDown" ? 1 : -1) + matches().length) % matches().length) + } else if (event.key === "Enter" && shown() && matches()[index()]) { + event.preventDefault() + open(matches()[index()]) + } + } + return ( +
+ +

{t("newInstanceLauncher.recentTitle")}

+
+ }> + +
+ +
+ {t(launchableRecents().length ? "newInstanceLauncher.noMatch" : "newInstanceLauncher.empty")}

}> + {(recent, position) => ( +
setIndex(position())} onClick={() => open(recent)}> + + {getProjectDisplayName(recent.path, recent.projectName)} + {recent.sidecar ? t("folderSelection.recent.sidecar") + : recent.remote ? `${recent.remote.serverName} · ${getDisplayPath(recent.path)}` : getDisplayPath(recent.path)} + + + + +
+ )} +
+
+
+
+ ) +} diff --git a/packages/ui/src/lib/hooks/use-app-session-capture.ts b/packages/ui/src/lib/hooks/use-app-session-capture.ts index 83bc96ea6d..16a38ef3a4 100644 --- a/packages/ui/src/lib/hooks/use-app-session-capture.ts +++ b/packages/ui/src/lib/hooks/use-app-session-capture.ts @@ -69,7 +69,7 @@ function captureRuntimeState( return { unseenIdleSince, generationRecovery, ...(Object.keys(seenInterruptions).length ? { seenInterruptions } : {}) } } function captureState(scrollAuthority: ReadonlyMap>) { - const tabs = appTabs() + const tabs = appTabs().filter((tab) => tab.kind !== "blank") const nextOccurrence = new Map() const occurrenceByInstance = new Map() for (const instance of instances().values()) { diff --git a/packages/ui/src/lib/hooks/use-remote-server-profiles.ts b/packages/ui/src/lib/hooks/use-remote-server-profiles.ts index 7a2e331263..f7238d111b 100644 --- a/packages/ui/src/lib/hooks/use-remote-server-profiles.ts +++ b/packages/ui/src/lib/hooks/use-remote-server-profiles.ts @@ -9,6 +9,7 @@ import { showAlertDialog } from "../../stores/alerts" import { useConfig } from "../../stores/preferences" import { closeRemoteProjectTabsForServer } from "../../stores/remote-project-tabs" import { openRemoteProject, opensRemoteProjectTab } from "../../stores/remote-project-open" +import { activeBlankTabId } from "../../stores/app-tabs" import type { RemoteServerProfile } from "../../../../server/src/api-types" export type RemoteServerInput = { @@ -111,9 +112,9 @@ export function useRemoteServerProfiles() { } /** A saved server opens a project tab, or its own window when it cannot (unverified certificate, no tabs here). */ - const openServer = (profile: RemoteServerProfile, entryUrl?: string) => { + const openServer = (profile: RemoteServerProfile, entryUrl?: string, blankId: string | null = activeBlankTabId() ?? null) => { if (opensRemoteProjectTab(profile)) { - openRemoteProject(profile.id, entryUrl ? { entryUrl } : {}) + openRemoteProject(profile.id, entryUrl ? { entryUrl } : {}, blankId) void markRemoteServerConnected(profile.id).catch(() => {}) } else { void connectSavedServer(profile.id) @@ -125,9 +126,10 @@ export function useRemoteServerProfiles() { * link, whose single-use code is consumed where the server opens (a tab, else its own window). */ const submitServer = async (input: RemoteServerInput, open: boolean) => { + const blankId = activeBlankTabId() ?? null if (!opensRemoteProjectTab(input)) return void await saveServer(input, open) const { profile, entryUrl } = await saveProfile(input) - if (open || entryUrl) openServer(profile, entryUrl) + if (open || entryUrl) openServer(profile, entryUrl, blankId) } // A removed server's project tabs close with it. diff --git a/packages/ui/src/lib/i18n/messages/de/folderSelection.ts b/packages/ui/src/lib/i18n/messages/de/folderSelection.ts index ad04a1fe3d..3cbd461be9 100644 --- a/packages/ui/src/lib/i18n/messages/de/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/de/folderSelection.ts @@ -112,4 +112,9 @@ export const folderSelectionMessages = { "folderSelection.recent.sidecar": "SideCar", "folderSelection.newSidecar": "Neuer SideCar", "folderSelection.remoteProject.serverMissing": "Server nicht gefunden", + "newTab.title": "Neuer Tab", + "newTab.home": "Startseite", + "newTab.items.one": "{count} Eintrag", + "newTab.items.other": "{count} Einträge", + "newTab.sponsor": "Sponsor", } as const diff --git a/packages/ui/src/lib/i18n/messages/en/folderSelection.ts b/packages/ui/src/lib/i18n/messages/en/folderSelection.ts index 654ebd6656..085d6f9164 100644 --- a/packages/ui/src/lib/i18n/messages/en/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/en/folderSelection.ts @@ -112,4 +112,9 @@ export const folderSelectionMessages = { "folderSelection.recent.sidecar": "SideCar", "folderSelection.newSidecar": "New SideCar", "folderSelection.remoteProject.serverMissing": "Server not found", + "newTab.title": "New tab", + "newTab.home": "Home", + "newTab.items.one": "{count} item", + "newTab.items.other": "{count} items", + "newTab.sponsor": "Sponsor", } as const diff --git a/packages/ui/src/lib/i18n/messages/es/folderSelection.ts b/packages/ui/src/lib/i18n/messages/es/folderSelection.ts index 6fc1bd70f9..5b26cbb8e5 100644 --- a/packages/ui/src/lib/i18n/messages/es/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/es/folderSelection.ts @@ -112,4 +112,9 @@ export const folderSelectionMessages = { "folderSelection.recent.sidecar": "SideCar", "folderSelection.newSidecar": "Nuevo SideCar", "folderSelection.remoteProject.serverMissing": "Servidor no encontrado", + "newTab.title": "Nueva pestaña", + "newTab.home": "Inicio", + "newTab.items.one": "{count} elemento", + "newTab.items.other": "{count} elementos", + "newTab.sponsor": "Patrocinar", } as const diff --git a/packages/ui/src/lib/i18n/messages/fr/folderSelection.ts b/packages/ui/src/lib/i18n/messages/fr/folderSelection.ts index 4e6a271f1a..7d49806732 100644 --- a/packages/ui/src/lib/i18n/messages/fr/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/fr/folderSelection.ts @@ -112,4 +112,9 @@ export const folderSelectionMessages = { "folderSelection.recent.sidecar": "SideCar", "folderSelection.newSidecar": "Nouveau SideCar", "folderSelection.remoteProject.serverMissing": "Serveur introuvable", + "newTab.title": "Nouvel onglet", + "newTab.home": "Accueil", + "newTab.items.one": "{count} élément", + "newTab.items.other": "{count} éléments", + "newTab.sponsor": "Sponsor", } as const diff --git a/packages/ui/src/lib/i18n/messages/he/folderSelection.ts b/packages/ui/src/lib/i18n/messages/he/folderSelection.ts index 596f434d6f..69f94a47e9 100644 --- a/packages/ui/src/lib/i18n/messages/he/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/he/folderSelection.ts @@ -112,4 +112,9 @@ export const folderSelectionMessages = { "folderSelection.recent.sidecar": "SideCar", "folderSelection.newSidecar": "SideCar חדש", "folderSelection.remoteProject.serverMissing": "השרת לא נמצא", + "newTab.title": "לשונית חדשה", + "newTab.home": "דף הבית", + "newTab.items.one": "פריט {count}", + "newTab.items.other": "{count} פריטים", + "newTab.sponsor": "תמיכה", } as const diff --git a/packages/ui/src/lib/i18n/messages/ja/folderSelection.ts b/packages/ui/src/lib/i18n/messages/ja/folderSelection.ts index 2e5a06935e..50dc5e6642 100644 --- a/packages/ui/src/lib/i18n/messages/ja/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/ja/folderSelection.ts @@ -112,4 +112,9 @@ export const folderSelectionMessages = { "folderSelection.recent.sidecar": "SideCar", "folderSelection.newSidecar": "新しい SideCar", "folderSelection.remoteProject.serverMissing": "サーバーが見つかりません", + "newTab.title": "新しいタブ", + "newTab.home": "ホーム", + "newTab.items.one": "{count} 件", + "newTab.items.other": "{count} 件", + "newTab.sponsor": "スポンサー", } as const diff --git a/packages/ui/src/lib/i18n/messages/ne/folderSelection.ts b/packages/ui/src/lib/i18n/messages/ne/folderSelection.ts index cfe1bdf665..350969ea6c 100644 --- a/packages/ui/src/lib/i18n/messages/ne/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/ne/folderSelection.ts @@ -112,4 +112,9 @@ export const folderSelectionMessages = { "folderSelection.recent.sidecar": "SideCar", "folderSelection.newSidecar": "नयाँ SideCar", "folderSelection.remoteProject.serverMissing": "सर्भर फेला परेन", + "newTab.title": "नयाँ ट्याब", + "newTab.home": "गृह पृष्ठ", + "newTab.items.one": "{count} वस्तु", + "newTab.items.other": "{count} वस्तुहरू", + "newTab.sponsor": "प्रायोजन", } as const diff --git a/packages/ui/src/lib/i18n/messages/ru/folderSelection.ts b/packages/ui/src/lib/i18n/messages/ru/folderSelection.ts index a6e53d765e..bb2cac98ea 100644 --- a/packages/ui/src/lib/i18n/messages/ru/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/ru/folderSelection.ts @@ -112,4 +112,9 @@ export const folderSelectionMessages = { "folderSelection.recent.sidecar": "SideCar", "folderSelection.newSidecar": "Новый SideCar", "folderSelection.remoteProject.serverMissing": "Сервер не найден", + "newTab.title": "Новая вкладка", + "newTab.home": "Главная", + "newTab.items.one": "{count} элемент", + "newTab.items.other": "{count} элементов", + "newTab.sponsor": "Поддержать", } as const diff --git a/packages/ui/src/lib/i18n/messages/tr/folderSelection.ts b/packages/ui/src/lib/i18n/messages/tr/folderSelection.ts index 0f3753ccf1..696c5c4400 100644 --- a/packages/ui/src/lib/i18n/messages/tr/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/tr/folderSelection.ts @@ -100,4 +100,9 @@ export const folderSelectionMessages = { "folderSelection.recent.sidecar": "SideCar", "folderSelection.newSidecar": "Yeni SideCar", "folderSelection.remoteProject.serverMissing": "Sunucu bulunamadı", + "newTab.title": "Yeni sekme", + "newTab.home": "Ana sayfa", + "newTab.items.one": "{count} öğe", + "newTab.items.other": "{count} öğe", + "newTab.sponsor": "Sponsor", } as const diff --git a/packages/ui/src/lib/i18n/messages/zh-Hans/folderSelection.ts b/packages/ui/src/lib/i18n/messages/zh-Hans/folderSelection.ts index 015a729d08..d9028339f0 100644 --- a/packages/ui/src/lib/i18n/messages/zh-Hans/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/zh-Hans/folderSelection.ts @@ -112,4 +112,9 @@ export const folderSelectionMessages = { "folderSelection.recent.sidecar": "SideCar", "folderSelection.newSidecar": "新建 SideCar", "folderSelection.remoteProject.serverMissing": "找不到服务器", + "newTab.title": "新标签页", + "newTab.home": "主页", + "newTab.items.one": "{count} 个项目", + "newTab.items.other": "{count} 个项目", + "newTab.sponsor": "赞助", } as const diff --git a/packages/ui/src/stores/app-tabs.test.ts b/packages/ui/src/stores/app-tabs.test.ts index d2cb27754a..3691ea6172 100644 --- a/packages/ui/src/stores/app-tabs.test.ts +++ b/packages/ui/src/stores/app-tabs.test.ts @@ -13,6 +13,7 @@ import { detachInstanceTab, setAppTabOrder, selectInstanceTab, + openBlankTab, closeBlankTab, replaceBlankTab, } from "./app-tabs.ts" import { createRestorableSessionPreservation, @@ -76,6 +77,32 @@ describe("renderer-local workspace tabs", () => { toast.custom = () => "test-toast" }) afterEach(() => { serverApi.deleteWorkspace = originalDelete; toast.custom = originalToast }) + it("closes empty tabs without a backend request and replaces a chosen blank slot without removing other blanks", () => { + const chosen = instance('blank-choice') + let deletes = 0 + serverApi.deleteWorkspace = async () => { deletes++ } + addInstance(chosen) + openBlankTab() + const first = activeAppTabId()! + openBlankTab() + const second = activeAppTabId()! + try { + selectInstanceTab(chosen.id) + replaceBlankTab(first, `instance:${chosen.id}`) + assert.deepEqual(appTabs().map(tab => tab.id), [`instance:${chosen.id}`, second]) + closeBlankTab(second) + assert.deepEqual(appTabs().map(tab => tab.id), [`instance:${chosen.id}`]) + openBlankTab() + const survivor = activeAppTabId()! + replaceBlankTab(second, `instance:${chosen.id}`) + assert.deepEqual(appTabs().map(tab => tab.id), [`instance:${chosen.id}`, survivor], "a closed origin cannot consume another blank") + closeBlankTab(survivor) + assert.equal(deletes, 0) + } finally { + closeBlankTab(first); closeBlankTab(second) + removeInstance(chosen.id, { authoritative: false }) + } + }) it("keeps catalog additions and updates closed until explicitly attached", () => { const first = instance("catalog-first") const second = instance("catalog-second") diff --git a/packages/ui/src/stores/app-tabs.ts b/packages/ui/src/stores/app-tabs.ts index 0eadfdc88f..f0731279fd 100644 --- a/packages/ui/src/stores/app-tabs.ts +++ b/packages/ui/src/stores/app-tabs.ts @@ -36,7 +36,39 @@ export interface RemoteProjectAppTab { remoteProjectTab: RemoteProjectTabRecord } -export type AppTabRecord = InstanceAppTab | SideCarAppTab | RemoteProjectAppTab +export interface BlankAppTab { + id: string + kind: "blank" +} + +export type AppTabRecord = InstanceAppTab | SideCarAppTab | RemoteProjectAppTab | BlankAppTab + +const [blankTabs, setBlankTabs] = createSignal([]) + +/** Empty tabs live only in this window, without a backend record or persisted state. */ +export function openBlankTab(): void { + const tab: BlankAppTab = { id: `blank:${crypto.randomUUID()}`, kind: "blank" } + setBlankTabs((tabs) => [...tabs, tab]) + selectAppTab(tab.id) +} + +export function closeBlankTab(id: string): void { + const fallback = activeAppTabId() === id ? getAdjacentAppTabId(id) : activeAppTabId() + setBlankTabs((tabs) => tabs.filter((tab) => tab.id !== id)) + setTabOrder((ids) => ids.filter((entry) => entry !== id)) + ensureActiveAppTab(fallback) +} + +/** A successful choice occupies its originating blank tab's position, even after an asynchronous opening. */ +export function replaceBlankTab(blankId: string | null | undefined, chosenId: string): void { + if (!blankId || !blankTabs().some((tab) => tab.id === blankId) || !getAppTabById(chosenId)) return + const ids = appTabs().map((tab) => tab.id).filter((id) => id !== chosenId) + setTabOrder(ids.map((id) => id === blankId ? chosenId : id)) + setBlankTabs((tabs) => tabs.filter((tab) => tab.id !== blankId)) + setAppTabOrderRevision((revision) => revision + 1) +} + +export const activeBlankTabId = () => activeAppTab()?.kind === "blank" ? activeAppTabId() ?? undefined : undefined function getInstanceAppTabId(instanceId: string): string { return `instance:${instanceId}` @@ -88,6 +120,7 @@ const appTabs = createMemo((previous = []) => { // project must not remount every shell (and restart their Git/status reads). const previousById = new Map(previous.map((tab) => [tab.id, tab])) const currentTabs = [ + ...blankTabs(), ...Array.from(instances().values()) .filter((instance) => openInstanceTabIds().has(instance.id)) .map((instance) => previousById.get(getInstanceAppTabId(instance.id)) ?? ({ @@ -157,7 +190,7 @@ function selectAppTab(tabId: string | null, options?: { source?: "restore" }) { return } setActiveRemoteProjectToken(null) - setActiveSidecarToken(tab.sidecarTab.token) + setActiveSidecarToken(tab.kind === "sidecar" ? tab.sidecarTab.token : null) } function selectRemoteProjectTab(token: string) { diff --git a/packages/ui/src/stores/remote-project-open.ts b/packages/ui/src/stores/remote-project-open.ts index c99e000add..1e3d433380 100644 --- a/packages/ui/src/stores/remote-project-open.ts +++ b/packages/ui/src/stores/remote-project-open.ts @@ -2,7 +2,7 @@ import type { RemoteServerProfile } from "../../../server/src/api-types" import { canOpenRemoteProjectTabs } from "../lib/native/remote-view" import { serverDisplayName } from "../lib/codenomad-link" import { mixRecents, type LaunchableRecent } from "../lib/remote-project-recents" -import { selectRemoteProjectTab } from "./app-tabs" +import { activeBlankTabId, replaceBlankTab, getRemoteProjectAppTabId, selectRemoteProjectTab } from "./app-tabs" import { recentFolders, remoteProjectRecents, remoteServers, sidecarRecents } from "./preferences" import { sidecars } from "./sidecars" import { openRemoteProjectTab, remoteProjectTabs, type RemoteProjectTabRecord } from "./remote-project-tabs" @@ -12,9 +12,10 @@ import { setShowFolderSelection } from "./ui" export const opensRemoteProjectTab = (profile: Pick) => !profile.skipTlsVerify && canOpenRemoteProjectTabs() -export function openRemoteProject(profileId: string, options: { folder?: string; entryUrl?: string } = {}): void { +export function openRemoteProject(profileId: string, options: { folder?: string; entryUrl?: string } = {}, blankId: string | null = activeBlankTabId() ?? null): void { const tab = openRemoteProjectTab(profileId, options) selectRemoteProjectTab(tab.token) + replaceBlankTab(blankId, getRemoteProjectAppTabId(tab.token)) setShowFolderSelection(false) } diff --git a/packages/ui/src/stores/sidecar-open.ts b/packages/ui/src/stores/sidecar-open.ts index 64c095bf13..b510c99b9e 100644 --- a/packages/ui/src/stores/sidecar-open.ts +++ b/packages/ui/src/stores/sidecar-open.ts @@ -1,7 +1,7 @@ import { tGlobal } from "../lib/i18n" import { getLogger } from "../lib/logger" import { showAlertDialog } from "./alerts" -import { selectSidecarTab } from "./app-tabs" +import { activeBlankTabId, replaceBlankTab, getSidecarAppTabId, selectSidecarTab } from "./app-tabs" import { recordSideCarRecent } from "./preferences" import { openSidecarTab } from "./sidecars" import { setShowFolderSelection } from "./ui" @@ -10,9 +10,11 @@ const log = getLogger("actions") /** Opens a SideCar in a new tab from Browse or the recent tabs, which it then joins. */ export async function openSidecar(sidecarId: string): Promise { + const blankId = activeBlankTabId() try { const tab = await openSidecarTab(sidecarId) selectSidecarTab(tab.token) + replaceBlankTab(blankId, getSidecarAppTabId(tab.token)) setShowFolderSelection(false) recordSideCarRecent(sidecarId) } catch (error) { diff --git a/packages/ui/src/styles/components/blank-tab.css b/packages/ui/src/styles/components/blank-tab.css new file mode 100644 index 0000000000..6f9099fe8a --- /dev/null +++ b/packages/ui/src/styles/components/blank-tab.css @@ -0,0 +1,35 @@ +/* Empty tabs share the home canvas and cards, with a responsive pair of choice lists. */ +.blank-tab-view { + flex: 1 1 auto; + min-width: 0; + padding: var(--space-lg); + background: var(--surface-canvas); +} + +.blank-tab-columns { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: var(--space-md); + width: min(64rem, 100%); + margin: auto; +} + +.blank-tab-section { min-width: 0; overflow: hidden; } +.blank-tab-section .browse-menu-body { background: var(--surface-canvas); } +.blank-tab-section .new-instance-launcher-recents { max-height: 60vh; } +.blank-tab-actions { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: var(--space-sm); + margin-top: var(--space-md); +} + +.recent-tabs-menu { display: flex; flex-direction: column; min-height: 0; } +.new-instance-launcher > .recent-tabs-menu { overflow: hidden; } +.native-titlebar-home { -webkit-app-region: no-drag; } +.tab-bar-home { flex: 0 0 auto; margin-inline: var(--space-xs); } + +@media (max-width: 640px) { + .blank-tab-columns { grid-template-columns: minmax(0, 1fr); } +} diff --git a/packages/ui/src/styles/controls.css b/packages/ui/src/styles/controls.css index 3856154e2a..b856d8f2e5 100644 --- a/packages/ui/src/styles/controls.css +++ b/packages/ui/src/styles/controls.css @@ -50,5 +50,6 @@ @import "./components/integration-attachment.css"; @import "./components/integration-catalog.css"; @import "./components/browse-menu.css"; +@import "./components/blank-tab.css"; @import "./components/server-add-field.css"; @import "./components/embedded-project-picker.css"; diff --git a/packages/ui/tests/browser/new-instance-launcher.test.ts b/packages/ui/tests/browser/new-instance-launcher.test.ts index ff829300c4..d758dd9a89 100644 --- a/packages/ui/tests/browser/new-instance-launcher.test.ts +++ b/packages/ui/tests/browser/new-instance-launcher.test.ts @@ -333,7 +333,7 @@ test("the home page's Recent and Browse tabs match the launcher's sections, whic // Right: two tabs, Recent tabs first, with the launcher's search. const tabList = page.getByRole("tablist") - assert.deepEqual(await tabList.getByRole("tab").allTextContents(), ["Recent", "Browse"]) + assert.deepEqual(await tabList.locator(".panel-title").allTextContents(), ["Recent", "Browse"]) const recentTab = tabList.getByRole("tab", { name: "Recent" }) assert.equal(await recentTab.getAttribute("aria-selected"), "true") const search = page.getByRole("textbox", { name: "Search recent projects" }) @@ -345,7 +345,7 @@ test("the home page's Recent and Browse tabs match the launcher's sections, whic await page.keyboard.press("ArrowRight") const browseTab = tabList.getByRole("tab", { name: "Browse" }) assert.equal(await browseTab.getAttribute("aria-selected"), "true") - assert.equal(await page.evaluate(() => document.activeElement?.textContent), "Browse") + assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Browse") const panel = page.getByRole("tabpanel", { name: "Browse" }) assert.equal(await panel.locator(".browse-menu-toggle").count(), 0) const homeRows = await panel.locator(".browse-menu-row").allTextContents() @@ -395,4 +395,4 @@ test("the launcher's Recent section folds like Browse: Escape folds it without c await page.waitForFunction(() => document.querySelectorAll(".new-instance-launcher [role=option]").length === 1) assert.deepEqual(errors, []) } finally { await page.close() } -}) \ No newline at end of file +}) diff --git a/packages/ui/tests/browser/remote-project-tabs.test.ts b/packages/ui/tests/browser/remote-project-tabs.test.ts index 0fe01481ac..96631644d2 100644 --- a/packages/ui/tests/browser/remote-project-tabs.test.ts +++ b/packages/ui/tests/browser/remote-project-tabs.test.ts @@ -27,7 +27,7 @@ const server = (id: string, extra: Record = {}) => ({ interface Scenario { context?: "local" | "remote" - host?: "electron" | "web" + host?: "electron" | "tauri" | "web" uiState?: Record /** A saved native session, restored by a local Electron window. */ restore?: unknown @@ -42,6 +42,12 @@ async function open(page: Page, path: string, scenario: Scenario) { if (host !== "web") w.__CODENOMAD_RUNTIME_HOST__ = host w.fixtureViews = { opened: [], updates: [], closed: [], listeners: [], windows: [] } w.EventSource = class extends EventTarget { close() {} } + if (host === "tauri") { + w.__TAURI__ = { core: { invoke: async () => undefined } } + w.__TAURI_INTERNALS__ = { invoke: async (command, args) => { + if (command === "open_external_url") w.externalURLs.push(args.url) + }, transformCallback: () => 1 } + } // Fixture shim: the session list's virtualizer reads defaultView from nodes the dev // server's templates create in an inert document before they are inserted. const defaultView = Object.getOwnPropertyDescriptor(Document.prototype, "defaultView") @@ -63,6 +69,7 @@ async function open(page: Page, path: string, scenario: Scenario) { } }` }) const created: string[] = [] + const workspaces: Record[] = [] const probes: string[] = [] let state = uiState await page.route(/\/(?:api|workspaces)\//, async route => { @@ -71,10 +78,12 @@ async function open(page: Page, path: string, scenario: Scenario) { if (pathname === "/api/workspaces" && request.method() === "POST") { const body = request.postDataJSON() as { path: string } created.push(body.path) - return route.fulfill({ json: { + const workspace = { id: `ws-${created.length}`, path: body.path, status: "starting", proxyPath: `/workspaces/ws-${created.length}/instance`, binaryId: "fixture", binaryLabel: "fixture", createdAt: new Date(0).toISOString(), updatedAt: new Date(0).toISOString(), - } }) + } + workspaces.push(workspace) + return route.fulfill({ json: workspace }) } if (pathname === "/api/remote-servers/probe") { const { baseUrl, skipTlsVerify } = request.postDataJSON() as { baseUrl: string; skipTlsVerify?: boolean } @@ -91,7 +100,7 @@ async function open(page: Page, path: string, scenario: Scenario) { return route.fulfill({ json: state }) } if (pathname === "/api/sidecars") return route.fulfill({ json: { sidecars } }) - const body = pathname === "/api/workspaces" ? [] + const body = pathname === "/api/workspaces" ? workspaces : pathname === "/api/storage/config/ui" ? { settings: { locale: "en" } } : pathname === "/api/storage/state/ui" ? state : {} await route.fulfill({ json: body }) @@ -224,7 +233,7 @@ test("a local window opens a saved server as a project tab whose view follows th assert.deepEqual(recents?.map(({ profileId, folder, projectName }) => ({ profileId, folder, projectName })), [{ profileId: "box", folder: "/srv/app", projectName: "App" }]) // A local overlay (the home page) hides the native view; it never covers local dialogs. - await page.locator(".new-instance-button").click() + await page.getByRole("button", { name: "Home", exact: true }).click() await page.waitForFunction((viewId) => (window as any).fixtureViews.updates.some((update: { viewId: string; visible: boolean }) => update.viewId === viewId && !update.visible), opened.viewId) // A server with an unverified certificate keeps its separate window. @@ -276,7 +285,7 @@ test("an address added in Browse opens its tab at once, named after its host; an assert.deepEqual(fixture.probes, ["https://lab.example:8443 skipTls=false"]) // The saved server opens again without a second profile or a probe. - await page.locator(".new-instance-button").click() + await page.getByRole("button", { name: "Home", exact: true }).click() await addServer(page, BOX) await page.waitForFunction(() => (window as any).fixtureViews.opened.length === 2) assert.equal((await views(page)).opened[1].profileId, "box") @@ -327,6 +336,108 @@ const sidecar = (id: string, name: string, status: "running" | "stopped") => ({ createdAt: "2026-11-01T10:00:00.000Z", updatedAt: "2026-11-01T10:00:00.000Z", }) +test("+ opens disposable blank tabs; remote and SideCar choices replace their originating blank tab in place", async () => { + const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: "en-US" }) + try { + const fixture = await open(page, "", { context: "local", host: "electron", uiState: { remoteServers: [server("box")] }, + sidecars: [sidecar("docs", "Docs", "running")] }) + await browse(page) + await page.getByRole("button", { name: "Open a project on Box" }).click() + await page.locator('.tab-pill', { hasText: 'Box' }).waitFor() + await page.locator('.new-instance-button').click() + const blank = page.locator('[data-tab-kind="blank"][data-tab-visible="true"]') + await blank.waitFor() + await page.waitForFunction(() => document.activeElement?.getAttribute('role') === 'combobox') + assert.equal(await page.locator('.tab-pill').count(), 2, await page.locator('.tab-strip-tabs').innerText()) + assert.equal(await blank.getByText('3 items', { exact: true }).count(), 1, 'Browse counts computer, server and SideCar') + assert.equal(await blank.getByText('0 items', { exact: true }).count(), 1) + assert.equal(await page.locator('.folder-home-root').count(), 0) + assert.deepEqual(fixture.created, [], 'blank tabs create no backend workspace') + assert.deepEqual(await blank.locator('.blank-tab-actions button').allTextContents(), ['Clone Git Repo', 'New temporary tab']) + const columns = await blank.locator('.blank-tab-section').evaluateAll(nodes => nodes.map(node => ({ x: node.getBoundingClientRect().x, y: node.getBoundingClientRect().y }))) + assert.equal(columns[0].y, columns[1].y) + assert.ok(columns[1].x > columns[0].x) + await page.setViewportSize({ width: 480, height: 800 }) + const narrow = await blank.locator('.blank-tab-section').evaluateAll(nodes => nodes.map(node => node.getBoundingClientRect().y)) + assert.ok(narrow[1] > narrow[0]) + await page.setViewportSize({ width: 1200, height: 800 }) + + // Open another blank, then fill the earlier one: its replacement keeps that earlier slot. + const firstBlankId = await blank.getAttribute('data-tab-id') + await page.locator('.new-instance-button').click() + await page.locator(`[data-app-tab-id="${firstBlankId}"] [role=tab]`).click() + await blank.getByRole('button', { name: 'Open a project on Box' }).click() + assert.equal(await page.locator('[data-tab-kind="blank"]').count(), 1) + assert.equal(await page.locator('.tab-pill').count(), 3) + assert.match((await page.locator('.tab-strip-tabs > *').nth(1).getAttribute('data-app-tab-id'))!, /^remote-project:/) + // Close the remaining blank: no saved record or resource is left. + await page.locator('.tab-pill', { hasText: 'New tab' }).locator('.tab-pill-close').click() + assert.equal(await page.locator('[data-tab-kind="blank"]').count(), 0) + assert.deepEqual(fixture.created, []) + assert.equal(JSON.stringify(fixture.state()).includes('blank:'), false) + + await page.locator('.new-instance-button').click() + await blank.locator('[data-sidecar="docs"]').click() + await page.locator('.tab-pill', { hasText: 'Docs' }).waitFor() + assert.equal(await page.locator('[data-tab-kind="blank"]').count(), 0) + assert.equal(await page.locator('.tab-pill').count(), 3) + } finally { await page.close() } +}) + +test("a delayed server probe fills its originating blank tab, even after another blank opens", async () => { + const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: "en-US" }) + let release!: () => void + const held = new Promise(resolve => { release = resolve }) + try { + await open(page, "", { context: "local", host: "electron", uiState: { remoteServers: [server("box")] } }) + await browse(page) + await page.getByRole("button", { name: "Open a project on Box" }).click() + await page.locator(".new-instance-button").click() + const blank = page.locator('[data-tab-kind="blank"][data-tab-visible="true"]') + const origin = await blank.getAttribute("data-tab-id") + await page.route("**/api/remote-servers/probe", async route => { await held; await route.fallback() }) + const field = blank.getByRole("textbox", { name: "Server address or link" }) + await field.fill("https://slow.example") + const pending = page.waitForRequest("**/api/remote-servers/probe") + await field.press("Enter") + await pending + await page.locator(".new-instance-button").click() + const other = await blank.getAttribute("data-tab-id") + assert.notEqual(other, origin) + release() + await page.locator(".tab-pill", { hasText: "slow.example" }).waitFor() + assert.equal(await page.locator(`[data-tab-id="${origin}"]`).count(), 0) + assert.equal(await page.locator(`[data-tab-id="${other}"]`).count(), 1) + assert.match((await page.locator(".tab-strip-tabs > *").nth(1).getAttribute("data-app-tab-id"))!, /^remote-project:/) + } finally { release(); await page.close() } +}) + +for (const host of ['web', 'electron', 'tauri'] as const) test(`${host}: the logo opens Home; Sponsor uses the existing help URL; a local choice replaces a blank tab`, async () => { + const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: 'en-US' }) + try { + const fixture = await open(page, '', { context: 'local', host, uiState: { recentFolders: [{ path: '/srv/local', projectName: 'Local', lastAccessed: 2 }] }, + sidecars: [sidecar('docs', 'Docs', 'running')] }) + const sponsor = page.getByRole('link', { name: 'Sponsor', exact: true }) + assert.equal(await sponsor.getAttribute('href'), 'https://neuralnomadsai.github.io/CodeNomad/en/sponsor.html') + await page.evaluate(() => { (window as any).externalURLs = []; window.open = ((url: string) => { (window as any).externalURLs.push(url); return null }) as any }) + await sponsor.click() + await page.waitForFunction(() => (window as any).externalURLs.length === 1) + assert.deepEqual(await page.evaluate(() => (window as any).externalURLs), ['https://neuralnomadsai.github.io/CodeNomad/en/sponsor.html']) + await page.getByRole('tab', { name: 'Browse', exact: true }).click() + await page.locator('[data-sidecar="docs"]').click() + await page.locator('.tab-pill', { hasText: 'Docs' }).waitFor() + await page.getByRole('button', { name: 'Home', exact: true }).click() + await page.locator('.folder-home-root').waitFor() + await page.getByRole('button', { name: 'Close', exact: true }).click() + await page.locator('.new-instance-button').click() + const blank = page.locator('[data-tab-kind="blank"][data-tab-visible="true"]') + await blank.getByRole('option', { name: /Local/ }).click() + await page.waitForFunction(() => !document.querySelector('[data-tab-kind="blank"]')) + assert.deepEqual(fixture.created, ['/srv/local']) + assert.equal(await page.locator('.tab-strip-tabs [role="tab"]').count(), 2) + } finally { await page.close() } +}) + test("Browse opens a running SideCar, which then joins the recent tabs of the home page and the launcher", async () => { const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: "en-US" }) try { @@ -356,7 +467,7 @@ test("Browse opens a running SideCar, which then joins the recent tabs of the ho assert.deepEqual(saved.map((entry) => Object.keys(entry).sort()), [["lastAccessed", "sidecarId"]]) assert.equal(saved[0].sidecarId, "docs") - await page.locator(".new-instance-button").click() + await page.getByRole("button", { name: "Home", exact: true }).click() const recent = page.locator('.folder-home-recent-item[data-sidecar="docs"]') await recent.waitFor() assert.match(await recent.innerText(), /Docs[\s\S]*SideCar/) From 34668caf0a23fbab9a0b42b55cdb8a2bf2209c47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Thu, 5 Nov 2026 22:38:59 +0100 Subject: [PATCH 18/34] docs(tabs): explain empty tabs and logo-based home navigation Document the ephemeral new-tab lifecycle, in-place choices, responsive Recent/Browse lists and their counts, plus the Home logo and Sponsor action. Update Projects, Desktop and Shortcuts in all ten help languages, and record the shell and asynchronous replacement contracts for contributors. Validated the full multilingual help check (31 tests) and links. Keep the generated local open_external_url permission outside these commits. --- dev-docs/PROJECTS.md | 4 +++- dev-docs/UI_SHELL.md | 2 ++ docs/help/de/desktop.md | 2 +- docs/help/de/projects.md | 4 ++-- docs/help/de/shortcuts.md | 2 +- docs/help/en/desktop.md | 2 +- docs/help/en/projects.md | 4 ++-- docs/help/en/shortcuts.md | 2 +- docs/help/es/desktop.md | 2 +- docs/help/es/projects.md | 4 ++-- docs/help/es/shortcuts.md | 2 +- docs/help/fr/desktop.md | 2 +- docs/help/fr/projects.md | 4 ++-- docs/help/fr/shortcuts.md | 2 +- docs/help/he/desktop.md | 2 +- docs/help/he/projects.md | 4 ++-- docs/help/he/shortcuts.md | 2 +- docs/help/ja/desktop.md | 2 +- docs/help/ja/projects.md | 4 ++-- docs/help/ja/shortcuts.md | 2 +- docs/help/ne/desktop.md | 2 +- docs/help/ne/projects.md | 4 ++-- docs/help/ne/shortcuts.md | 2 +- docs/help/ru/desktop.md | 2 +- docs/help/ru/projects.md | 4 ++-- docs/help/ru/shortcuts.md | 2 +- docs/help/tr/desktop.md | 2 +- docs/help/tr/projects.md | 4 ++-- docs/help/tr/shortcuts.md | 2 +- docs/help/zh-Hans/desktop.md | 2 +- docs/help/zh-Hans/projects.md | 4 ++-- docs/help/zh-Hans/shortcuts.md | 2 +- 32 files changed, 45 insertions(+), 41 deletions(-) diff --git a/dev-docs/PROJECTS.md b/dev-docs/PROJECTS.md index 99d2f39beb..6473b199d1 100644 --- a/dev-docs/PROJECTS.md +++ b/dev-docs/PROJECTS.md @@ -4,9 +4,11 @@ Closing project tabs, temporary workspaces, the new-instance launcher and the Gi ## Agent conventions +- Empty tabs (`kind: "blank"`, `stores/app-tabs.ts`) have window-local IDs and are filtered before session capture. A successful project, server or SideCar choice replaces its originating blank slot; keep that ID across asynchronous folder/clone selection, workspace creation, SideCar opens and server probes. Other empty tabs retain their positions. Closing an empty tab makes no backend call. `components/blank-tab-view.tsx` shares `RecentTabsMenu`, `BrowseMenu`, `NewTabActions` and the browse/clone dialogs with existing entry points. Recent and Browse counts include their available entries; Browse counts the computer, saved servers visible to this host and configured SideCars, with the add-server field treated as an action. + - Closing a project tab detaches it immediately and requests deletion of that occurrence's logical backend workspace record; failures notify and never retry automatically. Separate occurrences of the same folder are independent. A `workspace.stopped` deletion closes the same record in other windows and notifies only windows displaying it that did not initiate the close. CodeNomad never evicts native Locations; OpenCode sessions keep running and reopening finds them. Whole-window close, app quit, renderer reload and backend shutdown keep existing restoration behavior. Temporary discard and server stop events use local-only tab detachment, not another DELETE; Keep closes the retained project normally. - Git is a full-functionality prerequisite, with directory-only degraded conversations when the backend cannot find Git. Only the explicitly opened physical folder is session authority in that mode; never infer sibling worktrees from native project IDs. Keep ancestor/descendant mutation identities covered by the deletion fence across Git availability changes. Inform agents through the owned native `codenomad.git-availability` instruction before prompts/custom commands, remove stale context after recovery, and keep this advisory separate from fail-closed environment synchronization. Do not add a blocking Git setup UI. Validate with `scripts/test-git-degraded-native.mjs` using an isolated CLI/database and provider. - Temporary instances (`workspaces/temporary-workspaces.ts`, UI `stores/temporary-instances.ts`) are ordinary non-Git workspaces on CodeNomad-created direct children of `/temporary-workspaces`. Registry membership (`temporary-workspaces.json`), not location, makes a folder temporary; keeping only unregisters it and adds a named recent project. Discard deletes only registered children of that root, refuses running conversations and other open tabs of the folder, removes conversations deepest-first, closes the workspace before deleting the folder and keeps failed removals registered; such a folder is reachable only by browsing to it. Closing a temporary tab from the UI asks Keep/Discard/Cancel, except that an untouched one (no conversation, file or unsent draft) closes and is discarded silently (`onlyIfEmpty`: the server refuses with `temporary_has_conversations`/`temporary_not_empty`, and any failure of that quiet discard returns the choice without an error). Before the server stops it, a visible temporary tab yields to its neighbour (or closes if alone) and a refusal restores it in place; `workspace.stopped` likewise closes the tab first and clears the instance in a microtask, because clearing a visible shell's state in the same update as its tab freezes the window. Same-minute names get a `(n)` suffix. Registry changes broadcast `workspace.temporaryChanged`, which clears kept marks in every window. Open temporary tabs are saved and restored with the app state like any project tab (still marked temporary). Only the choice dialog overrides initial focus (to its last, non-destructive choice); confirms keep focus on Cancel. Refusals use stable `temporary_*` codes localized by the client. Validate with `scripts/test-temporary-workspaces-native.mjs` against an isolated CLI. -- The tab-bar new-instance button follows the last tab like a browser: the instance `TabScroll` frame only spans its tabs and the button sits after it, outside the scroller (so focusing it never scrolls the strip), ending up at the strip's end once tabs overflow. Dragged tabs stay visually within the tab list like a browser's (`KeepDraggedTabInStrip`), while the drop slot follows the pointer's unbounded position (`closestUnboundedCenter`). The button keeps its click (full home page, Cmd/Ctrl+N) while a long press, right-click, Alt+Down, Shift+F10 or Menu opens the anchored `NewInstanceLauncher` (`lib/long-press.ts`; only Escape returns focus to the button, never over another surface or the home page): titled Open a tab, it is the home page's logic in short: the search, the collapsible Recent section (unfolded by default and kept per window; chevron first, like Browse; Escape on its title folds it without closing the launcher; typing or an arrow in the search unfolds it; an open project switches to its tab), the folded Browse section, then Clone and New temporary tab only. Recents are local projects, remote projects and SideCars (`launchableRecents`, `filterRecents` for both search fields, `components/recent-tab-icon.tsx`); a SideCar joins them when it opens (`stores/sidecar-open.ts`), stored as `ui` state `sidecarRecents` with its id and time only, never an address or proxy token, and listed while still configured. The home page's right card has two tabs, Recent (with the same search; arrows move between the tabs) and Browse (the list always open); its left column holds only the creation buttons of `components/new-tab-actions.tsx`: Clone a Git repository, New temporary tab and New SideCar (`openSettingsRow("sidecars", "sidecar-add")`, the SideCar form's name field); servers are added in Browse. The launcher's `variant` keeps only the first two. Renaming and removing recent tabs stay on the home page; servers are managed in Settings → Servers, SideCars in Settings → SideCars. Browse/clone flows live once in `components/new-instance-dialogs.tsx` and recent-folder display helpers in `lib/recent-folder-display.ts`, shared with `FolderSelectionView`; styles in `styles/components/new-instance-launcher.css`. +- The tab-bar new-instance button follows the last tab like a browser: the instance `TabScroll` frame only spans its tabs and the button sits after it, outside the scroller (so focusing it never scrolls the strip), ending up at the strip's end once tabs overflow. Dragged tabs stay visually within the tab list like a browser's (`KeepDraggedTabInStrip`), while the drop slot follows the pointer's unbounded position (`closestUnboundedCenter`). Clicking it (or Cmd/Ctrl+N) opens an empty tab. A long press, right-click, Alt+Down, Shift+F10 or Menu opens the anchored `NewInstanceLauncher` (`lib/long-press.ts`; only Escape returns focus to the button, never over another surface or the home page): titled Open a tab, it is the home page's logic in short: the search, the collapsible Recent section (unfolded by default and kept per window; chevron first, like Browse; Escape on its title folds it without closing the launcher; typing or an arrow in the search unfolds it; an open project switches to its tab), the folded Browse section, then Clone and New temporary tab only. Recents are local projects, remote projects and SideCars (`launchableRecents`, `filterRecents` for search fields, `components/recent-tab-icon.tsx`); a SideCar joins them when it opens (`stores/sidecar-open.ts`), stored as `ui` state `sidecarRecents` with its id and time only, never an address or proxy token, and listed while still configured. The home page's right card has two tabs, Recent (with the same search; arrows move between the tabs) and Browse (the list always open); its left column holds only the creation buttons of `components/new-tab-actions.tsx`: Clone a Git repository, New temporary tab and New SideCar (`openSettingsRow("sidecars", "sidecar-add")`, the SideCar form's name field); servers are added in Browse. The launcher's `variant` keeps only the first two. Renaming and removing recent tabs stay on the home page; servers are managed in Settings → Servers, SideCars in Settings → SideCars. Browse/clone flows live once in `components/new-instance-dialogs.tsx` and recent-folder display helpers in `lib/recent-folder-display.ts`, shared with `FolderSelectionView`; styles in `styles/components/new-instance-launcher.css`. - Remote project tabs show one project of a saved remote CodeNomad server inside a local window. Browse (`components/browse-menu.tsx`, the home page's Browse tab with `alwaysOpen` and the launcher's folded section, its disclosure state shared per window) lists This computer (the native dialog or folder browser), then, in host windows only (`canOpenRemoteWindows()`), each saved server profile, then each configured SideCar with its state (a stopped one cannot open), then, in host windows, the inline address field last; it offers no management (no context menu). Servers are added only through that field (`components/server-add-field.tsx`), never a floating dialog: an address or a Remote Control pairing link (`lib/codenomad-link.ts`, `lib/remote-pairing-link.ts`) goes through `submitServer` (`lib/hooks/use-remote-server-profiles.ts`) and the probe, is saved under its host (`codeNomadLinkName`) and opens at once (its tab, else its window; the launcher closes then). Pasting a valid link adds it immediately; Enter or + submits typed text. An address already saved reuses its profile; an address carrying credentials or unreadable text shows a short error under the field; only a probe failing with `tls_error` on an address adds the Skip TLS verification checkbox, confirmed through the same field, which saves a window-only profile. Settings → Servers (`settings/servers-settings-section.tsx`, host windows only) is the one management surface: the same field adds a server without opening it (`open={false}`; a pairing link still opens, since that consumes its code), and each server is opened, edited through `RemoteServerDialog` (edit only: address, name, certificate check) and removed (confirmed). Saving keeps the profile id, so its storage and sign-in stay, and a rename with the same URL and TLS setting skips the probe (`saveProfile`). Opening from the native Preferences window, which has no tabs, opens the server's window. Sign-in happens on the server's own page; the view's storage keeps it across launches. Servers read as `serverDisplayName` (`lib/codenomad-link.ts`): the saved name, or the host name when that name is a raw address (pasted servers are saved under `url.host`), with the port only when another saved server shares the host name; Browse, recents, Settings → Servers and a tab whose project is not chosen yet use it. Choosing a server opens a `remote-project` app tab (`stores/remote-project-tabs.ts`, actions in `stores/remote-project-open.ts`) whose `RemoteProjectView` places a native view (Electron `WebContentsView`, `electron/main/remote-view.ts`; Tauri child webview on Windows, `src-tauri/src/remote_view.rs`) over its content area; elsewhere, and for profiles that skip TLS verification, the server keeps its separate remote window. The view uses that server's remote-window storage (Electron partition, Tauri data directory), so its session or paired device cookie is reused without signing in again, and the remote preload/capability: of native access only notifications reach the host (badges and every local command are refused). It stays on the server's origin, the public help site opening in the system browser; a navigation to the bare root (end of login or pairing) returns to the tab's entry. Under Tauri every navigation also passes the app-wide `external-link-guard` plugin after the view's own handler: `intercept_navigation` asks `RemoteViews::navigation_allowed` first for registered `remote-view-*` labels, since the window-origin rules would cancel the view's first load. The view opens the first time its tab shows, follows the placeholder's bounds and hides while its tab is hidden or a local dialog, menu or list is open (`localOverlayOpen()`, shared with browser previews); a reload or close of the owning page closes its views. The remote page runs in embedded single-project mode (`lib/embed-mode.ts`, `/?codenomadEmbed=project[&folder=…]`): no title bar, tab bar or home page, a folder picker (`components/embedded-project-picker.tsx`) until a project opens, no native badge; it records the folder in its address and the project name in `document.title`, and keeps its active session per folder in its own persistent storage (`rememberEmbeddedSession`), reselected on reopening through the restored-tab hydration (`stores/embedded-project-session.ts`). A direct-access password sign-in lasts `PASSWORD_SESSION_TTL_MS` (seven days) with a matching cookie `Max-Age`, so the view stays signed in across host restarts while the server runs; logout revokes it server-side; bootstrap-token sessions keep browser-session cookies. The host accepts a title change only from the server's origin with a folder in the address, so a server without this mode shows its full interface and the tab keeps the server's name. Tabs restore as `{kind: "remote-project", profileId, folder?}` (a removed or window-only server drops its tab); projects opened in tabs join this host's recents beside local folders (`ui` state `remoteProjectRecents`, server, folder and name only; removing a server forgets them and closes its tabs). Covered by `tests/browser/remote-project-tabs.test.ts`, `electron/main/remote-view.test.ts` and `remote_view.rs` tests (navigation, ownership, ACL of the child label). - The clone dialog (`components/new-instance-dialogs.tsx`) suggests the repository's `git clone` folder name (`lib/clone-destination.ts`) inside a parent: the folder chosen with Browse, else the server-scoped `ui` state `lastCloneParent` (the folder above the last successful clone), else the folder above the most recent project. A destination the user types is kept as entered and sent unchanged; the server creates it. diff --git a/dev-docs/UI_SHELL.md b/dev-docs/UI_SHELL.md index a5dd4ef85a..529276cfb2 100644 --- a/dev-docs/UI_SHELL.md +++ b/dev-docs/UI_SHELL.md @@ -4,6 +4,8 @@ Panel toggles, floating drawers, project/right-panel tabs, the session sidebar a ## Agent conventions +- The CodeNomad logo opens Home: `NativeTitlebar.onHome` in native title/menu bars and the tab-bar logo in web windows. The `+` button and New instance command open an ephemeral unnamed `blank` tab; its close action stays local. `BlankTabView` shares search/recents with the launcher, focuses search when activated and displays Recent/Browse side by side (stacked below 640px). Home and blank tabs use `EntryCount` with localized singular/plural labels. The home heart Sponsor action uses `helpUrl(locale, "sponsor")` through the shared external opener. Validate web, Electron and Tauri roles with `tests/browser/remote-project-tabs.test.ts` and launcher gestures with `new-instance-launcher.test.ts`. + - Docked panel resize handles follow the composer's Pointer Events design: capture the pointer on the handle and keep its `.is-resizing` highlight until pointer up/cancel, capture loss or the active handle's cleanup. Scope each handle's cleanup to its own side so resizing continues when the opposite panel closes. Keep event handlers local in `useDrawerResize.ts` and styles in `styles/panels/session-layout.css`; validate both sides, RTL and touch with `tests/browser/panel-resize.test.ts`. - Session rows keep actions inline until their measured title, badges, and controls no longer fit. Keep responsive action styles in `styles/components/session-row-actions.css`; hidden inline controls remain measurable but inert, and an open overflow menu stays mounted until dismissal. diff --git a/docs/help/de/desktop.md b/docs/help/de/desktop.md index 1d09816222..1dd29ccbf1 100644 --- a/docs/help/de/desktop.md +++ b/docs/help/de/desktop.md @@ -2,7 +2,7 @@ ## Fenster, Tabs und gemeinsamer Dienst {#windows-tabs} -1. Verwenden Sie **Neue Instanz**, um einen weiteren Projekt-/Startseiten-Tab im aktuellen Fenster zu öffnen. +1. Öffnen Sie mit **Neue Instanz** einen leeren Tab im aktuellen Fenster und wählen Sie ein Projekt. Das CodeNomad-Logo öffnet die Startseite. 2. Verwenden Sie das native **Fenster → Neues Fenster** (`Ctrl+Shift+N` oder `Cmd+Shift+N`) für ein separates Anwendungsfenster. 3. Aktivieren Sie unter **Einstellungen → Erweitert** die Option **Vorhandenes Fenster beim zweiten Start fokussieren**, wenn ein weiterer Start das zuletzt verwendete Fenster fokussieren statt ein neues öffnen soll. diff --git a/docs/help/de/projects.md b/docs/help/de/projects.md index 218df5a024..4aaf0c4262 100644 --- a/docs/help/de/projects.md +++ b/docs/help/de/projects.md @@ -4,7 +4,7 @@ Ein Projekt-Tab verbindet CodeNomad mit einem Ordner auf dem Backend-Rechner. Da ## Projekt öffnen {#open-project} -1. Klicken Sie auf **Neue Instanz** (`+`), um die Startseite zu öffnen. +1. Klicken Sie auf **Neue Instanz** (`+`), um einen leeren **Neuer Tab** mit Fokus im Suchfeld zu öffnen. **Zuletzt verwendet** und **Durchsuchen** stehen mit ihrer Eintragszahl nebeneinander, in schmalen Fenstern untereinander. Die Auswahl eines Projekts, Servers oder SideCars füllt diesen Tab an seiner Position. Ein leerer Tab schließt ohne verbleibendes Projekt und besteht bis zum Neuladen des Fensters. Das CodeNomad-Logo in der Titel- oder Tableiste öffnet die Startseite; ihre Herz-Schaltfläche **Sponsor** öffnet [CodeNomad unterstützen](sponsor.md). 2. Wählen Sie unter **Zuletzt verwendet** ein Projekt; oder öffnen Sie **Durchsuchen**, wählen Sie **Dieser Computer**, dann den Backend-Ordner, und öffnen Sie ihn. **Durchsuchen** listet auch gespeicherte CodeNomad-Server ([Remote-Projekt-Tabs](remote-access.md#remote-project-tabs)) und SideCars ([SideCars](browser-sidecars.md#register-sidecar)) auf. 3. Für eine Repository-Kopie wählen Sie **Git-Repo klonen**, geben **Repository-URL** und **Zielordner** ein und wählen **Klonen**. **Zielordner** wird mit dem Repository-Namen im Ordner, der Ihren letzten Klon enthält vorbelegt, sonst neben Ihrem zuletzt geöffneten Projekt. **Durchsuchen** wählt den Ordner, der den Klon enthält; Sie können den Pfad auch bearbeiten, einschließlich des Ordnernamens des Klons. @@ -19,7 +19,7 @@ Zuletzt verwendete Einträge sind Verknüpfungen. **Arbeitsbereich umbenennen** 1. Halten Sie `+` gedrückt oder klicken Sie mit der rechten Maustaste darauf; bei Tastaturfokus dort verwenden Sie **Alt+Down**, **Shift+F10** oder die Menütaste. 2. Durchsuchen Sie in **Tab öffnen** die Liste **Zuletzt verwendet** (Projekte, Remote-Projekte und SideCars), öffnen Sie **Durchsuchen**, oder wählen Sie **Git-Repo klonen** oder **Neuer temporärer Tab**. -Ein normaler Klick öffnet weiterhin die vollständige Startseite mit denselben Möglichkeiten. Benennen Sie zuletzt geöffnete Tabs dort um oder entfernen Sie sie; verwalten Sie Server unter **Einstellungen → Server** und SideCars unter **Einstellungen → SideCars**. Escape schließt den Starter und gibt den Fokus an `+` zurück. +Ein normaler Klick öffnet einen leeren Tab. Die Startseite über das CodeNomad-Logo bietet dieselben Möglichkeiten und Eintragszahlen in **Zuletzt verwendet** und **Durchsuchen**. Benennen Sie zuletzt geöffnete Tabs dort um oder entfernen Sie sie; verwalten Sie Server unter **Einstellungen → Server** und SideCars unter **Einstellungen → SideCars**. Escape schließt den Starter und gibt den Fokus an `+` zurück. ## Projekt-Tab schließen {#close-stop} diff --git a/docs/help/de/shortcuts.md b/docs/help/de/shortcuts.md index 97473f6b62..24e5b0e544 100644 --- a/docs/help/de/shortcuts.md +++ b/docs/help/de/shortcuts.md @@ -26,7 +26,7 @@ Schlägt Speichern fehl, behalten Sie das alte Kürzel verfügbar und prüfen Si | Aktion | Standard | | --- | --- | | Befehlspalette öffnen | `Mod+Shift+P` | -| Neue Instanz / Ordner auf der Startseite durchsuchen | `Mod+N` | +| Neue Instanz / Leeren Tab öffnen | `Mod+N` | | App-Tab schließen | `Mod+W` | | Vorheriger / nächster App-Tab | `Mod+[` / `Mod+]` | | App-Tab 1–9 | `Mod+1` bis `Mod+9` | diff --git a/docs/help/en/desktop.md b/docs/help/en/desktop.md index 4794b7a8b8..c6ec493f7c 100644 --- a/docs/help/en/desktop.md +++ b/docs/help/en/desktop.md @@ -2,7 +2,7 @@ ## Windows, tabs and the shared service {#windows-tabs} -1. Use **New instance** to open another project/home tab in the current window. +1. Use **New instance** to open an empty tab in the current window, then choose a project. The CodeNomad logo opens Home. 2. Use native **Window → New Window** (`Ctrl+Shift+N` or `Cmd+Shift+N`) for a separate application window. 3. In **Settings → Advanced**, enable **Focus existing window on second launch** if another launch should focus the most recently used window rather than open a new one. diff --git a/docs/help/en/projects.md b/docs/help/en/projects.md index f2a682f0dc..17ef96e8b1 100644 --- a/docs/help/en/projects.md +++ b/docs/help/en/projects.md @@ -4,7 +4,7 @@ A project tab connects CodeNomad to a folder on the backend computer. Opening a ## Open a project {#open-project} -1. Click **New instance** (`+`) to open the home page. +1. Click **New instance** (`+`) to open an empty **New tab**, focused on search. **Recent** and **Browse** appear side by side, stacked in a narrow window, with their item counts. Choosing a project, server or SideCar fills that tab in place. An empty tab closes without leaving a project and lasts only until the window reloads. Click the CodeNomad logo in the title bar or tab bar to open Home; its heart **Sponsor** button opens [Support CodeNomad](sponsor.md). 2. In **Recent**, choose a project; or open **Browse**, choose **This computer**, then select the backend folder and open it. **Browse** also lists saved CodeNomad servers ([remote project tabs](remote-access.md#remote-project-tabs)) and SideCars ([SideCars](browser-sidecars.md#register-sidecar)). 3. For a repository copy, choose **Clone Git Repo**, enter **Repository URL** and **Destination folder**, then **Clone**. **Destination folder** is prefilled with the repository name in the folder that holds your last clone, or next to your most recent project. **Browse** chooses the folder that contains the clone; you can also edit the path, including the clone's folder name. @@ -19,7 +19,7 @@ Recent entries are shortcuts. **Rename workspace** changes its displayed name; * 1. Long-press or right-click `+`; with keyboard focus there, use **Alt+Down**, **Shift+F10** or the Menu key. 2. In **Open a tab**, search **Recent** (projects, remote projects and SideCars), open **Browse**, or choose **Clone Git Repo** or **New temporary tab**. -A normal click still opens the full home page, which offers the same choices. Rename or remove recent tabs there; manage servers in **Settings → Servers** and SideCars in **Settings → SideCars**. Escape dismisses the launcher and returns focus to `+`. +A normal click opens an empty tab. Home, opened from the CodeNomad logo, offers the same choices and item counts in **Recent** and **Browse**. Rename or remove recent tabs there; manage servers in **Settings → Servers** and SideCars in **Settings → SideCars**. Escape dismisses the launcher and returns focus to `+`. ## Close a project tab {#close-stop} diff --git a/docs/help/en/shortcuts.md b/docs/help/en/shortcuts.md index 4321be7b88..5afddbba89 100644 --- a/docs/help/en/shortcuts.md +++ b/docs/help/en/shortcuts.md @@ -26,7 +26,7 @@ If saving fails, keep the old shortcut available and retry after checking the di | Action | Default | | --- | --- | | Open command palette | `Mod+Shift+P` | -| New instance / Browse for a folder on the home page | `Mod+N` | +| New instance / Open an empty tab | `Mod+N` | | Close app tab | `Mod+W` | | Previous / next app tab | `Mod+[` / `Mod+]` | | App tab 1–9 | `Mod+1` through `Mod+9` | diff --git a/docs/help/es/desktop.md b/docs/help/es/desktop.md index 23abd154cb..45130320c6 100644 --- a/docs/help/es/desktop.md +++ b/docs/help/es/desktop.md @@ -2,7 +2,7 @@ ## Ventanas, pestañas y servicio compartido {#windows-tabs} -1. Usa **Nueva instancia** para abrir otra pestaña de proyecto/inicio en la ventana actual. +1. Usa **Nueva instancia** para abrir una pestaña vacía en la ventana actual y elige un proyecto. El logotipo CodeNomad abre Inicio. 2. Usa **Ventana → Nueva ventana** nativo (`Ctrl+Shift+N` o `Cmd+Shift+N`) para una ventana de aplicación separada. 3. En **Configuración → Avanzado**, activa **Enfocar la ventana existente en el segundo inicio** si otro inicio debe enfocar la ventana usada más recientemente en lugar de abrir una nueva. diff --git a/docs/help/es/projects.md b/docs/help/es/projects.md index 7328029659..29866f15d2 100644 --- a/docs/help/es/projects.md +++ b/docs/help/es/projects.md @@ -4,7 +4,7 @@ Una pestaña de proyecto conecta CodeNomad a una carpeta del equipo del backend. ## Abrir un proyecto {#open-project} -1. Haz clic en **Nueva instancia** (`+`) para abrir la página de inicio. +1. Haz clic en **Nueva instancia** (`+`) para abrir una **Nueva pestaña** vacía con el foco en la búsqueda. **Recientes** y **Explorar** aparecen lado a lado, apilados en ventanas estrechas, con sus cantidades de elementos. Elegir un proyecto, servidor o SideCar llena esa pestaña en su posición. Una pestaña vacía se cierra sin dejar un proyecto y dura hasta recargar la ventana. El logotipo CodeNomad de la barra de título o de pestañas abre Inicio; su botón **Patrocinar** con un corazón abre [Apoyar CodeNomad](sponsor.md). 2. En **Recientes**, elige un proyecto; o abre **Explorar**, elige **Este equipo** y luego selecciona la carpeta del backend y ábrela. **Explorar** también lista los servidores CodeNomad guardados ([pestañas de proyectos remotos](remote-access.md#remote-project-tabs)) y los SideCars ([SideCars](browser-sidecars.md#register-sidecar)). 3. Para obtener una copia de un repositorio, elige **Clonar repo Git**, introduce la **URL del repositorio** y la **Carpeta de destino** y pulsa **Clonar**. La **Carpeta de destino** se rellena con el nombre del repositorio en la carpeta que contiene tu último clon, o junto a tu proyecto más reciente. **Buscar** elige la carpeta que contendrá el clon; también puedes editar la ruta, incluido el nombre de la carpeta del clon. @@ -19,7 +19,7 @@ Las entradas recientes son accesos directos. **Renombrar workspace** cambia su n 1. Mantén pulsado `+` o haz clic derecho; con el foco del teclado allí, usa **Alt+Down**, **Shift+F10** o la tecla Menú. 2. En **Abrir una pestaña**, busca en **Recientes** (proyectos, proyectos remotos y SideCars), abre **Explorar** o elige **Clonar repo Git** o **Nueva pestaña temporal**. -Un clic normal sigue abriendo la página de inicio completa, que ofrece las mismas opciones. Cambia el nombre o quita pestañas recientes allí; gestiona los servidores en **Configuración → Servidores** y los SideCars en **Configuración → SideCars**. Escape cierra el lanzador y devuelve el foco a `+`. +Un clic normal abre una pestaña vacía. Inicio, desde el logotipo CodeNomad, ofrece las mismas opciones y cantidades en **Recientes** y **Explorar**. Cambia el nombre o quita pestañas recientes allí; gestiona los servidores en **Configuración → Servidores** y los SideCars en **Configuración → SideCars**. Escape cierra el lanzador y devuelve el foco a `+`. ## Cerrar una pestaña de proyecto {#close-stop} diff --git a/docs/help/es/shortcuts.md b/docs/help/es/shortcuts.md index 762f020eb7..c04d349218 100644 --- a/docs/help/es/shortcuts.md +++ b/docs/help/es/shortcuts.md @@ -26,7 +26,7 @@ Si el guardado falla, conserva disponible el atajo anterior y reintenta tras com | Acción | Valor predeterminado | | --- | --- | | Abrir paleta de comandos | `Mod+Shift+P` | -| Nueva instancia / Buscar una carpeta en la página de inicio | `Mod+N` | +| Nueva instancia / Abrir una pestaña vacía | `Mod+N` | | Cerrar pestaña de la aplicación | `Mod+W` | | Pestaña anterior / siguiente de la aplicación | `Mod+[` / `Mod+]` | | Pestaña 1–9 de la aplicación | `Mod+1` a `Mod+9` | diff --git a/docs/help/fr/desktop.md b/docs/help/fr/desktop.md index cf92a46f21..e29ce1e4b5 100644 --- a/docs/help/fr/desktop.md +++ b/docs/help/fr/desktop.md @@ -2,7 +2,7 @@ ## Fenêtres, onglets et service partagé {#windows-tabs} -1. Utilisez **Nouvelle instance** pour ouvrir un autre onglet projet/accueil dans la fenêtre actuelle. +1. Utilisez **Nouvelle instance** pour ouvrir un onglet vide dans la fenêtre actuelle, puis choisissez un projet. Le logo CodeNomad ouvre l'accueil. 2. Utilisez le menu natif **Fenêtre → Nouvelle fenêtre** (`Ctrl+Shift+N` ou `Cmd+Shift+N`) pour une fenêtre d’application séparée. 3. Dans **Paramètres → Avancé**, activez **Focaliser la fenêtre existante au second lancement** si un autre lancement doit focaliser la dernière fenêtre utilisée au lieu d’en ouvrir une nouvelle. diff --git a/docs/help/fr/projects.md b/docs/help/fr/projects.md index 35609fc4bf..eccf4e8a79 100644 --- a/docs/help/fr/projects.md +++ b/docs/help/fr/projects.md @@ -4,7 +4,7 @@ Un onglet de projet relie CodeNomad à un dossier sur l’ordinateur du backend. ## Ouvrir un projet {#open-project} -1. Cliquez sur **Nouvelle instance** (`+`) pour ouvrir l’accueil. +1. Cliquez sur **Nouvelle instance** (`+`) pour ouvrir un **Nouvel onglet** vide, avec le focus dans la recherche. **Récents** et **Parcourir** apparaissent côte à côte, empilés dans une fenêtre étroite, avec leur nombre d'éléments. Choisir un projet, un serveur ou un SideCar remplit cet onglet sur place. Un onglet vide se ferme sans laisser de projet et dure jusqu'au rechargement de la fenêtre. Cliquez sur le logo CodeNomad dans la barre de titre ou d'onglets pour ouvrir l'accueil ; son bouton **Sponsor** avec un cœur ouvre [Soutenir CodeNomad](sponsor.md). 2. Dans **Récents**, choisissez un projet ; ou ouvrez **Parcourir**, choisissez **Cet ordinateur**, puis sélectionnez le dossier du backend et ouvrez-le. **Parcourir** liste aussi les serveurs CodeNomad enregistrés ([onglets de projets distants](remote-access.md#remote-project-tabs)) et les SideCars ([SideCars](browser-sidecars.md#register-sidecar)). 3. Pour une copie de dépôt, choisissez **Cloner un depot Git**, saisissez **URL du depot** et **Dossier de destination**, puis **Cloner**. **Dossier de destination** est prérempli avec le nom du dépôt, dans le dossier qui contient votre dernier clone, sinon à côté de votre projet le plus récent. **Parcourir** choisit le dossier qui contiendra le clone ; vous pouvez aussi modifier le chemin, y compris le nom du dossier du clone. @@ -19,7 +19,7 @@ Les entrées récentes sont des raccourcis. **Renommer l'espace de travail** cha 1. Appuyez longuement ou faites un clic droit sur `+` ; lorsque ce bouton a le focus clavier, utilisez **Alt+Down**, **Shift+F10** ou la touche Menu. 2. Dans **Ouvrir un onglet**, recherchez parmi les **Récents** (projets, projets distants et SideCars), ouvrez **Parcourir**, ou choisissez **Cloner un dépôt Git** ou **Nouvel onglet temporaire**. -Un clic normal ouvre toujours l’accueil complet, qui propose les mêmes choix. Renommez ou retirez-y les onglets récents ; gérez les serveurs dans **Paramètres → Serveurs** et les SideCars dans **Paramètres → SideCars**. Échap ferme le lanceur et rend le focus à `+`. +Un clic normal ouvre un onglet vide. L'accueil, ouvert depuis le logo CodeNomad, propose les mêmes choix et les compteurs dans **Récents** et **Parcourir**. Renommez ou retirez-y les onglets récents ; gérez les serveurs dans **Paramètres → Serveurs** et les SideCars dans **Paramètres → SideCars**. Échap ferme le lanceur et rend le focus à `+`. ## Fermer un onglet de projet {#close-stop} diff --git a/docs/help/fr/shortcuts.md b/docs/help/fr/shortcuts.md index 9435d160fa..65d324d117 100644 --- a/docs/help/fr/shortcuts.md +++ b/docs/help/fr/shortcuts.md @@ -26,7 +26,7 @@ Si l’enregistrement échoue, gardez l’ancien raccourci disponible et réessa | Action | Valeur par défaut | | --- | --- | | Ouvrir la palette de commandes | `Mod+Shift+P` | -| Nouvelle instance / Parcourir les dossiers sur l’accueil | `Mod+N` | +| Nouvelle instance / Ouvrir un onglet vide | `Mod+N` | | Fermer l’onglet de l’application | `Mod+W` | | Onglet d’application précédent / suivant | `Mod+[` / `Mod+]` | | Onglet d’application 1–9 | `Mod+1` à `Mod+9` | diff --git a/docs/help/he/desktop.md b/docs/help/he/desktop.md index bd36c3b119..a1085fe7d3 100644 --- a/docs/help/he/desktop.md +++ b/docs/help/he/desktop.md @@ -2,7 +2,7 @@ ## חלונות, לשוניות והשירות המשותף {#windows-tabs} -1. השתמשו ב־**מופע חדש** לפתיחת לשונית פרויקט/בית נוספת בחלון הנוכחי. +1. השתמשו ב־**מופע חדש** לפתיחת לשונית ריקה בחלון הנוכחי ובחרו פרויקט. הלוגו של CodeNomad פותח את דף הבית. 2. השתמשו בתפריט המקורי **חלון → חלון חדש** (`Ctrl+Shift+N` או `Cmd+Shift+N`) לחלון יישום נפרד. 3. ב־**הגדרות → מתקדם**, הפעילו **מיקוד חלון קיים בהפעלה שנייה** אם הפעלה נוספת אמורה למקד את החלון האחרון שהיה בשימוש במקום לפתוח חדש. diff --git a/docs/help/he/projects.md b/docs/help/he/projects.md index f19878e196..e44cf8db4d 100644 --- a/docs/help/he/projects.md +++ b/docs/help/he/projects.md @@ -4,7 +4,7 @@ ## פתיחת פרויקט {#open-project} -1. לחצו **מופע חדש** (`+`) לפתיחת דף הבית. +1. לחצו **מופע חדש** (`+`) לפתיחת **לשונית חדשה** ריקה עם מיקוד בחיפוש. **אחרונים** ו־**עיון** מוצגים זה לצד זה, ובחלון צר זה מתחת לזה, עם מספר הפריטים. בחירת פרויקט, שרת או SideCar ממלאת את הלשונית במקומה. לשונית ריקה נסגרת בלי להשאיר פרויקט וקיימת עד לטעינה מחדש של החלון. הלוגו של CodeNomad בשורת הכותרת או הלשוניות פותח את דף הבית; כפתור **חסות** עם לב פותח את [תמיכה ב־CodeNomad](sponsor.md). 2. ב־**אחרונים**, בחרו פרויקט; או פתחו את **עיון**, בחרו **המחשב הזה**, ואז בחרו את תיקיית ה־backend ופתחו אותה. **עיון** מציג גם שרתי CodeNomad שמורים ([לשוניות של פרויקטים מרוחקים](remote-access.md#remote-project-tabs)) ו־SideCars ([SideCars](browser-sidecars.md#register-sidecar)). 3. לעותק מאגר, בחרו **שכפל מאגר Git**, הזינו **כתובת המאגר** ו־**תיקיית יעד**, ואז **שכפל**. **תיקיית יעד** ממולא מראש בשם המאגר, בתיקייה שמכילה את השכפול האחרון שלך, או לצד הפרויקט האחרון שלך. **עיון** בוחר את התיקייה שתכיל את השכפול; אפשר גם לערוך את הנתיב, כולל שם התיקייה של השכפול. @@ -19,7 +19,7 @@ 1. לחצו לחיצה ארוכה או לחיצה ימנית על `+`; כשהמקלדת ממוקדת בו, השתמשו ב־**Alt+Down**, ב־**Shift+F10** או במקש Menu. 2. ב־**פתיחת לשונית**, חפשו ב־**אחרונים** (פרויקטים, פרויקטים מרוחקים ו־SideCars), פתחו את **עיון**, או בחרו **שכפל מאגר Git** או **לשונית זמנית חדשה**. -לחיצה רגילה עדיין פותחת את דף הבית המלא, שמציע את אותן אפשרויות. שנו שם של לשוניות אחרונות או הסירו אותן שם; נהלו שרתים ב־**הגדרות → שרתים** ו־SideCars ב־**הגדרות → SideCars**. Escape סוגר את המפעיל ומחזיר את המיקוד ל־`+`. +לחיצה רגילה פותחת לשונית ריקה. דף הבית דרך הלוגו של CodeNomad מציע אותן אפשרויות ואת מספר הפריטים ב־**אחרונים** וב־**עיון**. שנו שם של לשוניות אחרונות או הסירו אותן שם; נהלו שרתים ב־**הגדרות → שרתים** ו־SideCars ב־**הגדרות → SideCars**. Escape סוגר את המפעיל ומחזיר את המיקוד ל־`+`. ## סגירת לשונית פרויקט {#close-stop} diff --git a/docs/help/he/shortcuts.md b/docs/help/he/shortcuts.md index 6a1eb18291..6e9a09247a 100644 --- a/docs/help/he/shortcuts.md +++ b/docs/help/he/shortcuts.md @@ -26,7 +26,7 @@ | פעולה | ברירת מחדל | | --- | --- | | פתיחת לוח פקודות | `Mod+Shift+P` | -| מופע חדש / עיון בתיקייה בדף הבית | `Mod+N` | +| מופע חדש / פתיחת לשונית ריקה | `Mod+N` | | סגירת לשונית יישום | `Mod+W` | | לשונית יישום קודמת / הבאה | `Mod+[` / `Mod+]` | | לשונית יישום 1–9 | `Mod+1` עד `Mod+9` | diff --git a/docs/help/ja/desktop.md b/docs/help/ja/desktop.md index 8859f769f5..d6f0d3a2e6 100644 --- a/docs/help/ja/desktop.md +++ b/docs/help/ja/desktop.md @@ -2,7 +2,7 @@ ## ウィンドウ、タブ、共有サービス {#windows-tabs} -1. **新しいインスタンス** で、現在のウィンドウに別のプロジェクト/ホームタブを開きます。 +1. **新しいインスタンス** で現在のウィンドウに空のタブを開き、プロジェクトを選びます。CodeNomad ロゴはホームを開きます。 2. 独立したアプリウィンドウには、ネイティブの **ウィンドウ → 新規ウィンドウ**(`Ctrl+Shift+N` または `Cmd+Shift+N`)を使用します。 3. 再度起動したとき、新しいウィンドウを開くのではなく最後に使ったウィンドウにフォーカスしたい場合は、**設定 → 詳細設定** で **2 回目の起動で既存ウィンドウをフォーカス** を有効にします。 diff --git a/docs/help/ja/projects.md b/docs/help/ja/projects.md index 92938c820e..2ece472124 100644 --- a/docs/help/ja/projects.md +++ b/docs/help/ja/projects.md @@ -4,7 +4,7 @@ ## プロジェクトを開く {#open-project} -1. **新しいインスタンス**(`+`)をクリックしてホームページを開きます。 +1. **新しいインスタンス**(`+`)をクリックすると、検索欄にフォーカスした空の **新しいタブ** が開きます。**最近** と **参照** は件数とともに横並びで、狭いウィンドウでは縦に表示されます。プロジェクト、サーバー、SideCar を選ぶと、その位置でタブの内容が切り替わります。空のタブはプロジェクトを残さず閉じ、ウィンドウの再読み込みまで有効です。タイトルバーまたはタブバーの CodeNomad ロゴからホームを開けます。ハートの **スポンサー** ボタンは [CodeNomad を支援](sponsor.md) を開きます。 2. **最近** でプロジェクトを選ぶか、**参照** を開いて **このコンピューター** を選び、バックエンドのフォルダーを選択して開きます。**参照** には保存した CodeNomad サーバー([リモートプロジェクトのタブ](remote-access.md#remote-project-tabs))と SideCar([SideCar](browser-sidecars.md#register-sidecar))も表示されます。 3. リポジトリをコピーするには、**Git リポジトリをクローン** を選び、**リポジトリ URL** と **保存先フォルダ** を入力して **クローン** を選びます。**保存先フォルダ** には、前回のクローンがあるフォルダー(なければ最近のプロジェクトと同じ場所)にリポジトリ名のフォルダーが入力されます。**参照** ではクローンを置くフォルダーを選びます。クローンのフォルダー名を含め、パスは直接編集することもできます。 @@ -19,7 +19,7 @@ 1. `+` を長押しまたは右クリックします。キーボードフォーカスがある場合は、**Alt+Down**、**Shift+F10**、または Menu キーを使用します。 2. **タブを開く** で **最近**(プロジェクト、リモートプロジェクト、SideCar)を検索するか、**参照** を開くか、**Git リポジトリをクローン** または **新しい一時タブ** を選びます。 -通常のクリックでは引き続き完全なホームページが開き、同じ選択肢を利用できます。最近のタブの名前変更や削除はそこで行い、サーバーは **設定 → サーバー**、SideCar は **設定 → SideCar** で管理します。Escape でランチャーが閉じ、フォーカスが `+` に戻ります。 +通常のクリックでは空のタブが開きます。CodeNomad ロゴから開くホームにも、同じ選択肢と **最近**・**参照** の件数があります。最近のタブの名前変更や削除はそこで行い、サーバーは **設定 → サーバー**、SideCar は **設定 → SideCar** で管理します。Escape でランチャーが閉じ、フォーカスが `+` に戻ります。 ## タブを閉じてプロジェクトを閉じる {#close-stop} diff --git a/docs/help/ja/shortcuts.md b/docs/help/ja/shortcuts.md index e54a749588..9545a498b7 100644 --- a/docs/help/ja/shortcuts.md +++ b/docs/help/ja/shortcuts.md @@ -26,7 +26,7 @@ | 操作 | 既定値 | | --- | --- | | コマンドパレットを開く | `Mod+Shift+P` | -| 新しいインスタンス/ホームページでフォルダーを参照 | `Mod+N` | +| 新しいインスタンス/空のタブを開く | `Mod+N` | | アプリタブを閉じる | `Mod+W` | | 前/次のアプリタブ | `Mod+[` / `Mod+]` | | アプリタブ 1〜9 | `Mod+1` から `Mod+9` | diff --git a/docs/help/ne/desktop.md b/docs/help/ne/desktop.md index 50b201d50d..54b8617379 100644 --- a/docs/help/ne/desktop.md +++ b/docs/help/ne/desktop.md @@ -2,7 +2,7 @@ ## विन्डो, ट्याब र साझा सेवा {#windows-tabs} -1. हालको विन्डोमा अर्को परियोजना/गृह ट्याब खोल्न **नयाँ उदाहरण** प्रयोग गर्नुहोस्। +1. हालको विन्डोमा खाली ट्याब खोल्न **नयाँ उदाहरण** प्रयोग गरी परियोजना छान्नुहोस्। CodeNomad लोगोले गृह पृष्ठ खोल्छ। 2. छुट्टै एप विन्डोका लागि नेटिभ **सञ्झ्याल → नयाँ विन्डो** (`Ctrl+Shift+N` वा `Cmd+Shift+N`) प्रयोग गर्नुहोस्। 3. अर्को सुरुवातले नयाँ विन्डो नखोली हालै प्रयोग गरिएको विन्डोमा फोकस गर्नुपरे **सेटिङहरू → उन्नत** मा **दोस्रो सुरुवातमा विद्यमान विन्डोमा फोकस गर्नुहोस्** सक्षम गर्नुहोस्। diff --git a/docs/help/ne/projects.md b/docs/help/ne/projects.md index 7e25d88182..0645f83b3d 100644 --- a/docs/help/ne/projects.md +++ b/docs/help/ne/projects.md @@ -4,7 +4,7 @@ ## परियोजना खोल्नुहोस् {#open-project} -1. गृह पृष्ठ खोल्न **नयाँ उदाहरण** (`+`) क्लिक गर्नुहोस्। +1. खोजमा focus भएको खाली **नयाँ ट्याब** खोल्न **नयाँ उदाहरण** (`+`) क्लिक गर्नुहोस्। **हालका** र **ब्राउज गर्नुहोस्** प्रविष्टिको संख्यासहित सँगसँगै र साँघुरो झ्यालमा तलमाथि देखिन्छन्। परियोजना, सर्भर वा SideCar छान्दा यही ट्याब उही स्थानमा भरिन्छ। खाली ट्याब बन्द गर्दा परियोजना बाँकी रहँदैन र झ्याल पुनः लोड हुँदासम्म मात्र रहन्छ। शीर्षक वा ट्याब पट्टीको CodeNomad लोगोले गृह पृष्ठ खोल्छ; मुटु भएको **प्रायोजन** बटनले [CodeNomad लाई सहयोग](sponsor.md) खोल्छ। 2. **हालका** मा परियोजना छान्नुहोस्; वा **ब्राउज गर्नुहोस्** खोलेर **यो कम्प्युटर** छान्नुहोस्, अनि backend फोल्डर चयन गरी खोल्नुहोस्। **ब्राउज गर्नुहोस्** ले बचत गरिएका CodeNomad सर्भरहरू ([रिमोट परियोजना ट्याबहरू](remote-access.md#remote-project-tabs)) र SideCar हरू ([SideCars](browser-sidecars.md#register-sidecar)) पनि देखाउँछ। 3. रिपोजिटरी प्रतिलिपिका लागि **Git Repo क्लोन गर्नुहोस्** रोजी **रिपोजिटरी URL** र **गन्तव्य फोल्डर** भर्नुहोस्, अनि **क्लोन गर्नुहोस्**। **गन्तव्य फोल्डर** मा तपाईंको पछिल्लो क्लोन भएको फोल्डरभित्र (नभए सबैभन्दा हालको प्रोजेक्टको छेउमा) रिपोजिटरीको नाम पहिल्यै भरिन्छ। **ब्राउज गर्नुहोस्** ले क्लोन राख्ने फोल्डर छान्छ; क्लोनको फोल्डर नामसहित path आफैँ पनि बदल्न सकिन्छ। @@ -19,7 +19,7 @@ 1. `+` लामो थिच्नुहोस् वा right-click गर्नुहोस्; त्यहाँ keyboard focus हुँदा **Alt+Down**, **Shift+F10** वा Menu key प्रयोग गर्नुहोस्। 2. **ट्याब खोल्नुहोस्** मा **हालका** (परियोजना, रिमोट परियोजना र SideCar) खोज्नुहोस्, **ब्राउज गर्नुहोस्** खोल्नुहोस्, वा **Git Repo क्लोन गर्नुहोस्** वा **नयाँ अस्थायी ट्याब** छान्नुहोस्। -सामान्य क्लिकले अझै पूर्ण गृह पृष्ठ खोल्छ, जहाँ यिनै विकल्पहरू छन्। हालका ट्याबहरूको नाम बदल्ने वा हटाउने काम त्यहीँ गर्नुहोस्; सर्भरहरू **सेटिङहरू → सर्भरहरू** मा र SideCar हरू **सेटिङहरू → SideCars** मा व्यवस्थापन गर्नुहोस्। Escape ले लन्चर बन्द गरी focus `+` मा फर्काउँछ। +सामान्य क्लिकले खाली ट्याब खोल्छ। CodeNomad लोगोबाट खुल्ने गृह पृष्ठमा उही विकल्प र **हालका** तथा **ब्राउज गर्नुहोस्** का प्रविष्टि संख्या छन्। हालका ट्याबहरूको नाम बदल्ने वा हटाउने काम त्यहीँ गर्नुहोस्; सर्भरहरू **सेटिङहरू → सर्भरहरू** मा र SideCar हरू **सेटिङहरू → SideCars** मा व्यवस्थापन गर्नुहोस्। Escape ले लन्चर बन्द गरी focus `+` मा फर्काउँछ। ## ट्याब बन्द गरेर परियोजना बन्द गर्नुहोस् {#close-stop} diff --git a/docs/help/ne/shortcuts.md b/docs/help/ne/shortcuts.md index ee70779210..1d1ebed8cb 100644 --- a/docs/help/ne/shortcuts.md +++ b/docs/help/ne/shortcuts.md @@ -26,7 +26,7 @@ save असफल भए पुरानो shortcut उपलब्ध रा | कार्य | Default | | --- | --- | | command palette खोल्ने | `Mod+Shift+P` | -| नयाँ instance / गृह पृष्ठमा फोल्डर browse | `Mod+N` | +| नयाँ instance / खाली ट्याब खोल्नुहोस् | `Mod+N` | | app ट्याब बन्द | `Mod+W` | | अघिल्लो / अर्को app ट्याब | `Mod+[` / `Mod+]` | | app ट्याब 1–9 | `Mod+1` देखि `Mod+9` | diff --git a/docs/help/ru/desktop.md b/docs/help/ru/desktop.md index 8b69701413..8990b655df 100644 --- a/docs/help/ru/desktop.md +++ b/docs/help/ru/desktop.md @@ -2,7 +2,7 @@ ## Окна, вкладки и общая служба {#windows-tabs} -1. Используйте **Новый экземпляр** для другой вкладки проекта/главной страницы в текущем окне. +1. Используйте **Новый экземпляр**, чтобы открыть пустую вкладку в текущем окне, затем выберите проект. Логотип CodeNomad открывает главную страницу. 2. Используйте нативное **Окно → Новое окно** (`Ctrl+Shift+N` или `Cmd+Shift+N`) для отдельного окна приложения. 3. В **Настройки → Расширенные** включите **Фокусировать существующее окно при втором запуске**, если повторный запуск должен фокусировать последнее использованное окно, а не открывать новое. diff --git a/docs/help/ru/projects.md b/docs/help/ru/projects.md index c209953e0f..a81600b2df 100644 --- a/docs/help/ru/projects.md +++ b/docs/help/ru/projects.md @@ -4,7 +4,7 @@ ## Открытие проекта {#open-project} -1. Нажмите **Новый экземпляр** (`+`), чтобы открыть главную страницу. +1. Нажмите **Новый экземпляр** (`+`), чтобы открыть пустую **Новую вкладку** с фокусом в поиске. **Недавние** и **Обзор** отображаются рядом, а в узком окне — друг под другом, с числом элементов. Выбор проекта, сервера или SideCar заполняет эту вкладку на её месте. Пустая вкладка закрывается без оставшегося проекта и существует до перезагрузки окна. Логотип CodeNomad в заголовке или панели вкладок открывает главную страницу; кнопка **Спонсировать** с сердцем открывает [Поддержать CodeNomad](sponsor.md). 2. В **Недавние** выберите проект; или откройте **Обзор**, выберите **Этот компьютер**, затем укажите папку на бэкенде и откройте её. **Обзор** также показывает сохранённые серверы CodeNomad ([вкладки удалённых проектов](remote-access.md#remote-project-tabs)) и SideCar ([SideCar](browser-sidecars.md#register-sidecar)). 3. Для копирования репозитория выберите **Клонировать Git-репозиторий**, заполните **URL репозитория** и **Папка назначения**, затем нажмите **Клонировать**. **Папка назначения** заполняется заранее: папка с именем репозитория в папке, где лежит последний клон, а без него — рядом с последним проектом. **Обзор** выбирает папку, в которой будет клон; путь, включая имя папки клона, можно изменить и вручную. @@ -19,7 +19,7 @@ 1. Удерживайте `+` или щёлкните правой кнопкой; когда на ней фокус, используйте **Alt+Down**, **Shift+F10** или клавишу Menu. 2. В **Открыть вкладку** найдите нужное в **Недавние** (проекты, удалённые проекты и SideCar), откройте **Обзор** или выберите **Клонировать Git-репозиторий** или **Новая временная вкладка**. -Обычный щелчок по-прежнему открывает полную главную страницу с теми же возможностями. Переименовывайте и удаляйте недавние вкладки там; серверами управляйте в **Настройки → Серверы**, а SideCar — в **Настройки → SideCars**. Escape закрывает панель запуска и возвращает фокус на `+`. +Обычный щелчок открывает пустую вкладку. Главная страница через логотип CodeNomad предлагает те же варианты и число элементов в **Недавние** и **Обзор**. Переименовывайте и удаляйте недавние вкладки там; серверами управляйте в **Настройки → Серверы**, а SideCar — в **Настройки → SideCars**. Escape закрывает панель запуска и возвращает фокус на `+`. ## Закрытие вкладки проекта {#close-stop} diff --git a/docs/help/ru/shortcuts.md b/docs/help/ru/shortcuts.md index 2617ac523f..f0813ea5d5 100644 --- a/docs/help/ru/shortcuts.md +++ b/docs/help/ru/shortcuts.md @@ -26,7 +26,7 @@ | Действие | По умолчанию | | --- | --- | | Открыть палитру команд | `Mod+Shift+P` | -| Новый экземпляр / обзор папки на главной странице | `Mod+N` | +| Новый экземпляр / открыть пустую вкладку | `Mod+N` | | Закрыть вкладку приложения | `Mod+W` | | Предыдущая / следующая вкладка приложения | `Mod+[` / `Mod+]` | | Вкладка приложения 1–9 | От `Mod+1` до `Mod+9` | diff --git a/docs/help/tr/desktop.md b/docs/help/tr/desktop.md index cff6a53195..e0c31be06b 100644 --- a/docs/help/tr/desktop.md +++ b/docs/help/tr/desktop.md @@ -2,7 +2,7 @@ ## Pencereler, sekmeler ve paylaşılan hizmet {#windows-tabs} -1. Geçerli pencerede başka bir proje/ana sayfa sekmesi açmak için **Yeni instance** öğesini kullanın. +1. Geçerli pencerede boş bir sekme açmak için **Yeni instance** öğesini kullanıp proje seçin. CodeNomad logosu ana sayfayı açar. 2. Ayrı bir uygulama penceresi için yerel **Pencere → Yeni pencere** (`Ctrl+Shift+N` veya `Cmd+Shift+N`) kullanın. 3. **Ayarlar → Gelişmiş** bölümünde, başka bir başlatmanın yeni bir pencere açmak yerine en son kullanılan pencereye odaklanması gerekiyorsa **İkinci başlatmada mevcut pencereye odaklan** öğesini etkinleştirin. diff --git a/docs/help/tr/projects.md b/docs/help/tr/projects.md index 64d7c41511..1ecdb9cc60 100644 --- a/docs/help/tr/projects.md +++ b/docs/help/tr/projects.md @@ -4,7 +4,7 @@ Bir proje sekmesi CodeNomad'i arka uç bilgisayarındaki bir klasöre bağlar. S ## Bir proje açın {#open-project} -1. Ana sayfayı açmak için **Yeni instance** (`+`) öğesine tıklayın. +1. Arama alanına odaklanan boş bir **Yeni sekme** açmak için **Yeni instance** (`+`) öğesine tıklayın. **Son kullanılanlar** ve **Gözat**, öğe sayılarıyla yan yana, dar pencerede alt alta görünür. Proje, sunucu veya SideCar seçimi bu sekmeyi yerinde doldurur. Boş sekme proje bırakmadan kapanır ve pencere yeniden yüklenene kadar yaşar. Başlık veya sekme çubuğundaki CodeNomad logosu ana sayfayı açar; kalpli **Sponsor** düğmesi [CodeNomad'i destekleyin](sponsor.md) sayfasını açar. 2. **Son kullanılanlar** içinde bir proje seçin; ya da **Gözat** bölümünü açıp **Bu bilgisayar** seçin, ardından arka uç klasörünü seçip açın. **Gözat** kayıtlı CodeNomad sunucularını ([uzak proje sekmeleri](remote-access.md#remote-project-tabs)) ve SideCar'ları ([SideCar'lar](browser-sidecars.md#register-sidecar)) da listeler. 3. Depoyu kopyalamak için **Git Deposunu Klonla** eylemini seçin; **Depo URL'si** ve **Hedef klasör** alanlarını doldurup **Klonla** eylemini seçin. **Hedef klasör**, son klonunuzun bulunduğu klasörde (yoksa en son projenizin yanında) depo adıyla önceden doldurulur. **Göz At** klonu içerecek klasörü seçer; klon klasörünün adı dahil yolu elle de düzenleyebilirsiniz. @@ -19,7 +19,7 @@ Son kullanılan kayıtlar birer kısayoldur. **Workspace'i yeniden adlandır** g 1. `+`'ye uzun basın veya sağ tıklayın; Klavye odağı oradayken **Alt+Down**, **Shift+F10** veya Menü tuşunu kullanın. 2. **Sekme aç** içinde **Son kullanılanlar** arasında arayın (projeler, uzak projeler ve SideCar'lar), **Gözat** bölümünü açın ya da **Git Deposunu Klonla** veya **Yeni geçici sekme** seçin. -Normal bir tıklama yine aynı seçenekleri sunan tam ana sayfayı açar. Son sekmeleri orada yeniden adlandırın veya kaldırın; sunucuları **Ayarlar → Sunucular**, SideCar'ları ise **Ayarlar → SideCars** bölümünde yönetin. Escape başlatıcıyı kapatır ve odağı `+` düğmesine döndürür. +Normal tıklama boş bir sekme açar. CodeNomad logosundan açılan ana sayfa aynı seçenekleri ve **Son kullanılanlar** ile **Gözat** öğe sayılarını sunar. Son sekmeleri orada yeniden adlandırın veya kaldırın; sunucuları **Ayarlar → Sunucular**, SideCar'ları ise **Ayarlar → SideCars** bölümünde yönetin. Escape başlatıcıyı kapatır ve odağı `+` düğmesine döndürür. ## Bir projeyi kapatın {#close-stop} diff --git a/docs/help/tr/shortcuts.md b/docs/help/tr/shortcuts.md index bd4711164a..796bfa856b 100644 --- a/docs/help/tr/shortcuts.md +++ b/docs/help/tr/shortcuts.md @@ -26,7 +26,7 @@ Kaydetme başarısız olursa eski kısayolu kullanılabilir durumda tutun ve gö | Eylem | Varsayılan | | --- | --- | | Komut paletini aç | `Mod+Shift+P` | -| Yeni örnek / Ana sayfada bir klasöre göz atın | `Mod+N` | +| Yeni örnek / Boş sekme açın | `Mod+N` | | Uygulama sekmesini kapat | `Mod+W` | | Önceki / sonraki uygulama sekmesi | `Mod+[` / `Mod+]` | | Uygulama sekmesi 1-9 | `Mod+1`'den `Mod+9`'ye kadar | diff --git a/docs/help/zh-Hans/desktop.md b/docs/help/zh-Hans/desktop.md index e56c66132b..85169fc8c6 100644 --- a/docs/help/zh-Hans/desktop.md +++ b/docs/help/zh-Hans/desktop.md @@ -2,7 +2,7 @@ ## 窗口、标签页和共享服务 {#windows-tabs} -1. 使用**新建实例**在当前窗口打开另一个项目/主页标签页。 +1. 使用**新建实例**在当前窗口打开空白标签页,然后选择项目。CodeNomad 标志打开主页。 2. 使用原生 **窗口 → 新建窗口**(`Ctrl+Shift+N` 或 `Cmd+Shift+N`)打开独立应用窗口。 3. 在**设置 → 高级**中,若希望再次启动时聚焦最近使用的窗口而非新开窗口,请启用**再次启动时聚焦现有窗口**。 diff --git a/docs/help/zh-Hans/projects.md b/docs/help/zh-Hans/projects.md index 771e43170b..21b57c0fdb 100644 --- a/docs/help/zh-Hans/projects.md +++ b/docs/help/zh-Hans/projects.md @@ -4,7 +4,7 @@ ## 打开项目 {#open-project} -1. 点击**新建实例**(`+`)打开主页。 +1. 点击**新建实例**(`+`)打开空白的**新标签页**,焦点位于搜索框。**最近**和**浏览**并排显示,并附有条目数量;窄窗口中上下排列。选择项目、服务器或 SideCar 会在原位置填充此标签页。空白标签页关闭后不留下项目,仅保留到窗口重新加载。点击标题栏或标签栏中的 CodeNomad 标志打开主页;带心形图标的**赞助**按钮打开[支持 CodeNomad](sponsor.md)。 2. 在 **最近** 中选择一个项目;或打开 **浏览**,选择 **此电脑**,然后选择后端文件夹并打开。**浏览** 也列出已保存的 CodeNomad 服务器([远程项目标签页](remote-access.md#remote-project-tabs))和 SideCar([SideCar](browser-sidecars.md#register-sidecar))。 3. 若需仓库副本,选择**克隆 Git 仓库**,输入**仓库 URL** 和**目标文件夹**,然后选择**克隆**。**目标文件夹** 会预填为上次克隆所在文件夹中以仓库名命名的文件夹(没有则为最近项目旁边)。**浏览** 用于选择存放克隆的文件夹;也可以手动编辑路径,包括克隆文件夹的名称。 @@ -19,7 +19,7 @@ 1. 长按或右键点击 `+`;键盘焦点位于此处时,使用 **Alt+Down**、**Shift+F10** 或 Menu 键。 2. 在 **打开标签页** 中搜索 **最近**(项目、远程项目和 SideCar),打开 **浏览**,或选择 **克隆 Git 仓库** 或 **新建临时标签页**。 -普通点击仍会打开完整主页,提供相同的选项。在那里重命名或移除最近的标签页;在 **设置 → 服务器** 中管理服务器,在 **设置 → SideCars** 中管理 SideCar。Escape 会关闭启动器并将焦点返回 `+`。 +普通点击打开空白标签页。通过 CodeNomad 标志打开的主页提供相同的选项及**最近**和**浏览**的条目数量。在那里重命名或移除最近的标签页;在 **设置 → 服务器** 中管理服务器,在 **设置 → SideCars** 中管理 SideCar。Escape 会关闭启动器并将焦点返回 `+`。 ## 关闭标签页以关闭项目 {#close-stop} diff --git a/docs/help/zh-Hans/shortcuts.md b/docs/help/zh-Hans/shortcuts.md index fcdfc4c318..a52d15869b 100644 --- a/docs/help/zh-Hans/shortcuts.md +++ b/docs/help/zh-Hans/shortcuts.md @@ -26,7 +26,7 @@ | 操作 | 默认值 | | --- | --- | | 打开命令面板 | `Mod+Shift+P` | -| 新建实例 / 在主页浏览文件夹 | `Mod+N` | +| 新建实例 / 打开空白标签页 | `Mod+N` | | 关闭应用标签页 | `Mod+W` | | 上一个 / 下一个应用标签页 | `Mod+[` / `Mod+]` | | 应用标签页 1-9 | `Mod+1` 至 `Mod+9` | From 6364e29b16d8b7d4d7b060a8e372c2010efa6247 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 6 Nov 2026 00:25:55 +0100 Subject: [PATCH 19/34] fix(tabs): reuse Home for blank tabs and save servers without opening Render empty tabs through FolderSelectionView's blank mode so branding, background, large creation buttons, recent rows and the Recent/Browse selector match Home. Keep search beneath the selector and focus it on activation, while hiding Home-only controls and metadata. Unique view IDs and active-state guards preserve accessibility and prevent inactive tabs handling shortcuts or drops; remove the parallel blank view and stylesheet. The inline server field now saves only, focuses the saved Browse row and leaves the launcher open. Explicit row selection opens the server. Preserve TLS confirmation, credential refusal and duplicate reuse. Pairing entries wait only in renderer memory until selection, clear on removal or origin changes and never enter persisted profiles. Update Projects, Remote access and Remote Control help in all ten languages plus the shell/project/control contracts. Validated UI typecheck, 1,623 UI unit tests, 103 browser tests (one environment-dependent Electron check skipped), 31 help checks and an offline Tauri no-bundle release build. Captured and compared Home and blank layouts at desktop and narrow sizes; the built host was not launched. --- dev-docs/PROJECTS.md | 4 +- dev-docs/REMOTE_CONTROL.md | 10 +- dev-docs/UI_SHELL.md | 2 +- docs/help/de/projects.md | 2 +- docs/help/de/remote-access.md | 6 +- docs/help/de/remote-control.md | 2 +- docs/help/en/projects.md | 2 +- docs/help/en/remote-access.md | 6 +- docs/help/en/remote-control.md | 2 +- docs/help/es/projects.md | 2 +- docs/help/es/remote-access.md | 6 +- docs/help/es/remote-control.md | 2 +- docs/help/fr/projects.md | 2 +- docs/help/fr/remote-access.md | 6 +- docs/help/fr/remote-control.md | 2 +- docs/help/he/projects.md | 2 +- docs/help/he/remote-access.md | 6 +- docs/help/he/remote-control.md | 2 +- docs/help/ja/projects.md | 2 +- docs/help/ja/remote-access.md | 6 +- docs/help/ja/remote-control.md | 2 +- docs/help/ne/projects.md | 2 +- docs/help/ne/remote-access.md | 6 +- docs/help/ne/remote-control.md | 2 +- docs/help/ru/projects.md | 2 +- docs/help/ru/remote-access.md | 6 +- docs/help/ru/remote-control.md | 2 +- docs/help/tr/projects.md | 2 +- docs/help/tr/remote-access.md | 6 +- docs/help/tr/remote-control.md | 2 +- docs/help/zh-Hans/projects.md | 2 +- docs/help/zh-Hans/remote-access.md | 6 +- docs/help/zh-Hans/remote-control.md | 2 +- packages/ui/src/App.tsx | 3 +- packages/ui/src/components/blank-tab-view.tsx | 41 ----- packages/ui/src/components/browse-menu.tsx | 6 +- .../src/components/folder-selection-view.tsx | 41 +++-- .../ui/src/components/server-add-field.tsx | 12 +- .../settings/servers-settings-section.tsx | 2 +- .../lib/hooks/use-remote-server-profiles.ts | 24 +-- .../ui/src/styles/components/blank-tab.css | 35 ----- .../ui/src/styles/components/folder-home.css | 3 + .../src/styles/components/native-titlebar.css | 3 + .../components/new-instance-launcher.css | 2 + packages/ui/src/styles/controls.css | 1 - .../fixtures/remote-server-pairing.tsx | 6 +- .../tests/browser/remote-project-tabs.test.ts | 147 ++++++++++++++++-- .../browser/remote-server-pairing.test.ts | 11 +- 48 files changed, 265 insertions(+), 188 deletions(-) delete mode 100644 packages/ui/src/components/blank-tab-view.tsx delete mode 100644 packages/ui/src/styles/components/blank-tab.css diff --git a/dev-docs/PROJECTS.md b/dev-docs/PROJECTS.md index 6473b199d1..e30b2dd4a4 100644 --- a/dev-docs/PROJECTS.md +++ b/dev-docs/PROJECTS.md @@ -4,11 +4,11 @@ Closing project tabs, temporary workspaces, the new-instance launcher and the Gi ## Agent conventions -- Empty tabs (`kind: "blank"`, `stores/app-tabs.ts`) have window-local IDs and are filtered before session capture. A successful project, server or SideCar choice replaces its originating blank slot; keep that ID across asynchronous folder/clone selection, workspace creation, SideCar opens and server probes. Other empty tabs retain their positions. Closing an empty tab makes no backend call. `components/blank-tab-view.tsx` shares `RecentTabsMenu`, `BrowseMenu`, `NewTabActions` and the browse/clone dialogs with existing entry points. Recent and Browse counts include their available entries; Browse counts the computer, saved servers visible to this host and configured SideCars, with the add-server field treated as an action. +- Empty tabs (`kind: "blank"`, `stores/app-tabs.ts`) have window-local IDs and are filtered before session capture. A successful project, saved-server or SideCar choice replaces its originating blank slot; keep that ID across asynchronous folder/clone selection, workspace creation and SideCar opens. Adding a server saves its profile and preserves empty tabs; selecting its row opens it. Other empty tabs retain their positions. Closing an empty tab makes no backend call. `FolderSelectionView` owns the Home and blank layouts, with shared `BrowseMenu`, `NewTabActions`, recent rows and browse/clone dialogs; the compact launcher uses `RecentTabsMenu`. Recent and Browse counts include their available entries; Browse counts the computer, saved servers visible to this host and configured SideCars, with the add-server field treated as an action. - Closing a project tab detaches it immediately and requests deletion of that occurrence's logical backend workspace record; failures notify and never retry automatically. Separate occurrences of the same folder are independent. A `workspace.stopped` deletion closes the same record in other windows and notifies only windows displaying it that did not initiate the close. CodeNomad never evicts native Locations; OpenCode sessions keep running and reopening finds them. Whole-window close, app quit, renderer reload and backend shutdown keep existing restoration behavior. Temporary discard and server stop events use local-only tab detachment, not another DELETE; Keep closes the retained project normally. - Git is a full-functionality prerequisite, with directory-only degraded conversations when the backend cannot find Git. Only the explicitly opened physical folder is session authority in that mode; never infer sibling worktrees from native project IDs. Keep ancestor/descendant mutation identities covered by the deletion fence across Git availability changes. Inform agents through the owned native `codenomad.git-availability` instruction before prompts/custom commands, remove stale context after recovery, and keep this advisory separate from fail-closed environment synchronization. Do not add a blocking Git setup UI. Validate with `scripts/test-git-degraded-native.mjs` using an isolated CLI/database and provider. - Temporary instances (`workspaces/temporary-workspaces.ts`, UI `stores/temporary-instances.ts`) are ordinary non-Git workspaces on CodeNomad-created direct children of `/temporary-workspaces`. Registry membership (`temporary-workspaces.json`), not location, makes a folder temporary; keeping only unregisters it and adds a named recent project. Discard deletes only registered children of that root, refuses running conversations and other open tabs of the folder, removes conversations deepest-first, closes the workspace before deleting the folder and keeps failed removals registered; such a folder is reachable only by browsing to it. Closing a temporary tab from the UI asks Keep/Discard/Cancel, except that an untouched one (no conversation, file or unsent draft) closes and is discarded silently (`onlyIfEmpty`: the server refuses with `temporary_has_conversations`/`temporary_not_empty`, and any failure of that quiet discard returns the choice without an error). Before the server stops it, a visible temporary tab yields to its neighbour (or closes if alone) and a refusal restores it in place; `workspace.stopped` likewise closes the tab first and clears the instance in a microtask, because clearing a visible shell's state in the same update as its tab freezes the window. Same-minute names get a `(n)` suffix. Registry changes broadcast `workspace.temporaryChanged`, which clears kept marks in every window. Open temporary tabs are saved and restored with the app state like any project tab (still marked temporary). Only the choice dialog overrides initial focus (to its last, non-destructive choice); confirms keep focus on Cancel. Refusals use stable `temporary_*` codes localized by the client. Validate with `scripts/test-temporary-workspaces-native.mjs` against an isolated CLI. - The tab-bar new-instance button follows the last tab like a browser: the instance `TabScroll` frame only spans its tabs and the button sits after it, outside the scroller (so focusing it never scrolls the strip), ending up at the strip's end once tabs overflow. Dragged tabs stay visually within the tab list like a browser's (`KeepDraggedTabInStrip`), while the drop slot follows the pointer's unbounded position (`closestUnboundedCenter`). Clicking it (or Cmd/Ctrl+N) opens an empty tab. A long press, right-click, Alt+Down, Shift+F10 or Menu opens the anchored `NewInstanceLauncher` (`lib/long-press.ts`; only Escape returns focus to the button, never over another surface or the home page): titled Open a tab, it is the home page's logic in short: the search, the collapsible Recent section (unfolded by default and kept per window; chevron first, like Browse; Escape on its title folds it without closing the launcher; typing or an arrow in the search unfolds it; an open project switches to its tab), the folded Browse section, then Clone and New temporary tab only. Recents are local projects, remote projects and SideCars (`launchableRecents`, `filterRecents` for search fields, `components/recent-tab-icon.tsx`); a SideCar joins them when it opens (`stores/sidecar-open.ts`), stored as `ui` state `sidecarRecents` with its id and time only, never an address or proxy token, and listed while still configured. The home page's right card has two tabs, Recent (with the same search; arrows move between the tabs) and Browse (the list always open); its left column holds only the creation buttons of `components/new-tab-actions.tsx`: Clone a Git repository, New temporary tab and New SideCar (`openSettingsRow("sidecars", "sidecar-add")`, the SideCar form's name field); servers are added in Browse. The launcher's `variant` keeps only the first two. Renaming and removing recent tabs stay on the home page; servers are managed in Settings → Servers, SideCars in Settings → SideCars. Browse/clone flows live once in `components/new-instance-dialogs.tsx` and recent-folder display helpers in `lib/recent-folder-display.ts`, shared with `FolderSelectionView`; styles in `styles/components/new-instance-launcher.css`. -- Remote project tabs show one project of a saved remote CodeNomad server inside a local window. Browse (`components/browse-menu.tsx`, the home page's Browse tab with `alwaysOpen` and the launcher's folded section, its disclosure state shared per window) lists This computer (the native dialog or folder browser), then, in host windows only (`canOpenRemoteWindows()`), each saved server profile, then each configured SideCar with its state (a stopped one cannot open), then, in host windows, the inline address field last; it offers no management (no context menu). Servers are added only through that field (`components/server-add-field.tsx`), never a floating dialog: an address or a Remote Control pairing link (`lib/codenomad-link.ts`, `lib/remote-pairing-link.ts`) goes through `submitServer` (`lib/hooks/use-remote-server-profiles.ts`) and the probe, is saved under its host (`codeNomadLinkName`) and opens at once (its tab, else its window; the launcher closes then). Pasting a valid link adds it immediately; Enter or + submits typed text. An address already saved reuses its profile; an address carrying credentials or unreadable text shows a short error under the field; only a probe failing with `tls_error` on an address adds the Skip TLS verification checkbox, confirmed through the same field, which saves a window-only profile. Settings → Servers (`settings/servers-settings-section.tsx`, host windows only) is the one management surface: the same field adds a server without opening it (`open={false}`; a pairing link still opens, since that consumes its code), and each server is opened, edited through `RemoteServerDialog` (edit only: address, name, certificate check) and removed (confirmed). Saving keeps the profile id, so its storage and sign-in stay, and a rename with the same URL and TLS setting skips the probe (`saveProfile`). Opening from the native Preferences window, which has no tabs, opens the server's window. Sign-in happens on the server's own page; the view's storage keeps it across launches. Servers read as `serverDisplayName` (`lib/codenomad-link.ts`): the saved name, or the host name when that name is a raw address (pasted servers are saved under `url.host`), with the port only when another saved server shares the host name; Browse, recents, Settings → Servers and a tab whose project is not chosen yet use it. Choosing a server opens a `remote-project` app tab (`stores/remote-project-tabs.ts`, actions in `stores/remote-project-open.ts`) whose `RemoteProjectView` places a native view (Electron `WebContentsView`, `electron/main/remote-view.ts`; Tauri child webview on Windows, `src-tauri/src/remote_view.rs`) over its content area; elsewhere, and for profiles that skip TLS verification, the server keeps its separate remote window. The view uses that server's remote-window storage (Electron partition, Tauri data directory), so its session or paired device cookie is reused without signing in again, and the remote preload/capability: of native access only notifications reach the host (badges and every local command are refused). It stays on the server's origin, the public help site opening in the system browser; a navigation to the bare root (end of login or pairing) returns to the tab's entry. Under Tauri every navigation also passes the app-wide `external-link-guard` plugin after the view's own handler: `intercept_navigation` asks `RemoteViews::navigation_allowed` first for registered `remote-view-*` labels, since the window-origin rules would cancel the view's first load. The view opens the first time its tab shows, follows the placeholder's bounds and hides while its tab is hidden or a local dialog, menu or list is open (`localOverlayOpen()`, shared with browser previews); a reload or close of the owning page closes its views. The remote page runs in embedded single-project mode (`lib/embed-mode.ts`, `/?codenomadEmbed=project[&folder=…]`): no title bar, tab bar or home page, a folder picker (`components/embedded-project-picker.tsx`) until a project opens, no native badge; it records the folder in its address and the project name in `document.title`, and keeps its active session per folder in its own persistent storage (`rememberEmbeddedSession`), reselected on reopening through the restored-tab hydration (`stores/embedded-project-session.ts`). A direct-access password sign-in lasts `PASSWORD_SESSION_TTL_MS` (seven days) with a matching cookie `Max-Age`, so the view stays signed in across host restarts while the server runs; logout revokes it server-side; bootstrap-token sessions keep browser-session cookies. The host accepts a title change only from the server's origin with a folder in the address, so a server without this mode shows its full interface and the tab keeps the server's name. Tabs restore as `{kind: "remote-project", profileId, folder?}` (a removed or window-only server drops its tab); projects opened in tabs join this host's recents beside local folders (`ui` state `remoteProjectRecents`, server, folder and name only; removing a server forgets them and closes its tabs). Covered by `tests/browser/remote-project-tabs.test.ts`, `electron/main/remote-view.test.ts` and `remote_view.rs` tests (navigation, ownership, ACL of the child label). +- Remote project tabs show one project of a saved remote CodeNomad server inside a local window. Browse (`components/browse-menu.tsx`, Home/blank mode's Browse tab with `alwaysOpen` and the launcher's folded section, its disclosure state shared per window) lists This computer (the native dialog or folder browser), then, in host windows only (`canOpenRemoteWindows()`), each saved server profile, then each configured SideCar with its state (a stopped one cannot open), then, in host windows, the inline address field last; it offers no management (no context menu). Servers are added only through that field (`components/server-add-field.tsx`), never a floating dialog: an address or a Remote Control pairing link (`lib/codenomad-link.ts`, `lib/remote-pairing-link.ts`) goes through `submitServer(input, false)` (`lib/hooks/use-remote-server-profiles.ts`) and the probe, is saved under its host (`codeNomadLinkName`) and receives focus in Browse. Pasting a valid link adds it immediately; Enter or + submits typed text. The launcher stays open until a saved row is selected. Pairing entries wait in renderer memory until explicit opening (see [REMOTE_CONTROL.md](REMOTE_CONTROL.md)). An address already saved reuses its profile; an address carrying credentials or unreadable text shows a short error under the field; only a probe failing with `tls_error` on an address adds the Skip TLS verification checkbox, confirmed through the same field, which saves a window-only profile. Settings → Servers (`settings/servers-settings-section.tsx`, host windows only) is the one management surface: the same field saves a server, and each server is opened, edited through `RemoteServerDialog` (edit only: address, name, certificate check) and removed (confirmed). Saving keeps the profile id, so its storage and sign-in stay, and a rename with the same URL and TLS setting skips the probe (`saveProfile`). Opening from the native Preferences window, which has no tabs, opens the server's window. Sign-in happens on the server's own page; the view's storage keeps it across launches. Servers read as `serverDisplayName` (`lib/codenomad-link.ts`): the saved name, or the host name when that name is a raw address (pasted servers are saved under `url.host`), with the port only when another saved server shares the host name; Browse, recents, Settings → Servers and a tab whose project is not chosen yet use it. Choosing a server opens a `remote-project` app tab (`stores/remote-project-tabs.ts`, actions in `stores/remote-project-open.ts`) whose `RemoteProjectView` places a native view (Electron `WebContentsView`, `electron/main/remote-view.ts`; Tauri child webview on Windows, `src-tauri/src/remote_view.rs`) over its content area; elsewhere, and for profiles that skip TLS verification, the server keeps its separate remote window. The view uses that server's remote-window storage (Electron partition, Tauri data directory), so its session or paired device cookie is reused without signing in again, and the remote preload/capability: of native access only notifications reach the host (badges and every local command are refused). It stays on the server's origin, the public help site opening in the system browser; a navigation to the bare root (end of login or pairing) returns to the tab's entry. Under Tauri every navigation also passes the app-wide `external-link-guard` plugin after the view's own handler: `intercept_navigation` asks `RemoteViews::navigation_allowed` first for registered `remote-view-*` labels, since the window-origin rules would cancel the view's first load. The view opens the first time its tab shows, follows the placeholder's bounds and hides while its tab is hidden or a local dialog, menu or list is open (`localOverlayOpen()`, shared with browser previews); a reload or close of the owning page closes its views. The remote page runs in embedded single-project mode (`lib/embed-mode.ts`, `/?codenomadEmbed=project[&folder=…]`): no title bar, tab bar or home page, a folder picker (`components/embedded-project-picker.tsx`) until a project opens, no native badge; it records the folder in its address and the project name in `document.title`, and keeps its active session per folder in its own persistent storage (`rememberEmbeddedSession`), reselected on reopening through the restored-tab hydration (`stores/embedded-project-session.ts`). A direct-access password sign-in lasts `PASSWORD_SESSION_TTL_MS` (seven days) with a matching cookie `Max-Age`, so the view stays signed in across host restarts while the server runs; logout revokes it server-side; bootstrap-token sessions keep browser-session cookies. The host accepts a title change only from the server's origin with a folder in the address, so a server without this mode shows its full interface and the tab keeps the server's name. Tabs restore as `{kind: "remote-project", profileId, folder?}` (a removed or window-only server drops its tab); projects opened in tabs join this host's recents beside local folders (`ui` state `remoteProjectRecents`, server, folder and name only; removing a server forgets them and closes its tabs). Covered by `tests/browser/remote-project-tabs.test.ts`, `electron/main/remote-view.test.ts` and `remote_view.rs` tests (navigation, ownership, ACL of the child label). - The clone dialog (`components/new-instance-dialogs.tsx`) suggests the repository's `git clone` folder name (`lib/clone-destination.ts`) inside a parent: the folder chosen with Browse, else the server-scoped `ui` state `lastCloneParent` (the folder above the last successful clone), else the folder above the most recent project. A destination the user types is kept as entered and sent unchanged; the server creates it. diff --git a/dev-docs/REMOTE_CONTROL.md b/dev-docs/REMOTE_CONTROL.md index e8125e17a6..265a5614c6 100644 --- a/dev-docs/REMOTE_CONTROL.md +++ b/dev-docs/REMOTE_CONTROL.md @@ -83,14 +83,16 @@ browser ─TLS─▶ OpenTunnel relay (forwards ciphertext) ─▶ OpenTunnel SD - Remote devices authenticate even with `--dangerously-skip-auth`, and the local session cookie is never accepted on the ingress. - A desktop CodeNomad pairs as a device: pasting a pairing link into the inline server - field (Browse on the home page or in the launcher, or Settings → Servers) saves only the tunnel - origin and opens the server once on the link, even where adding only saves - (`lib/remote-pairing-link.ts`). The profile keeps TLS verification on, since + field (Browse on Home, an empty tab or in the launcher, or Settings → Servers) saves the tunnel + origin. The single-use entry waits in renderer memory (`pendingPairingEntries` in + `lib/hooks/use-remote-server-profiles.ts`) until the saved server is explicitly opened; + reload drops it, removal or a changed origin clears it and a successful opening consumes it. + Adding focuses the Browse row and keeps the launcher open. The profile keeps TLS verification on, since a Tauri TLS-proxy window uses an incognito store without the device cookie. The code is never stored with the server; re-pairing a saved server reuses its window storage, which keeps the device cookie across launches. Covered by `tests/browser/remote-server-pairing.test.ts`. - Where project tabs are available, the link opens a remote project tab whose view + Where project tabs are available, choosing the saved server opens a remote project tab whose view pairs on its first load with the remote window's storage ([PROJECTS.md](PROJECTS.md#agent-conventions)); the tab never relays the tunnel through the host. diff --git a/dev-docs/UI_SHELL.md b/dev-docs/UI_SHELL.md index 529276cfb2..da426731bc 100644 --- a/dev-docs/UI_SHELL.md +++ b/dev-docs/UI_SHELL.md @@ -4,7 +4,7 @@ Panel toggles, floating drawers, project/right-panel tabs, the session sidebar a ## Agent conventions -- The CodeNomad logo opens Home: `NativeTitlebar.onHome` in native title/menu bars and the tab-bar logo in web windows. The `+` button and New instance command open an ephemeral unnamed `blank` tab; its close action stays local. `BlankTabView` shares search/recents with the launcher, focuses search when activated and displays Recent/Browse side by side (stacked below 640px). Home and blank tabs use `EntryCount` with localized singular/plural labels. The home heart Sponsor action uses `helpUrl(locale, "sponsor")` through the shared external opener. Validate web, Electron and Tauri roles with `tests/browser/remote-project-tabs.test.ts` and launcher gestures with `new-instance-launcher.test.ts`. +- The CodeNomad logo opens Home: `NativeTitlebar.onHome` in native title/menu bars and the tab-bar logo in web windows. The `+` button and New instance command open an ephemeral unnamed `blank` tab; its close action stays local. `FolderSelectionView` renders both Home and its `blank` mode: the same background, centered logo/name, large Clone/Temporary/SideCar buttons and Recent/Browse selector with `EntryCount`; search sits below the selector in Recent. Blank mode hides the language, top-right actions, social links, version and OpenCode row and focuses search on activation, including an empty recent list. Each mounted view uses unique ARIA IDs and gates window hotkeys and folder drops on its active state. Adding a server focuses its saved Browse row and keeps the launcher open; selecting the row runs the ordinary open action. The home heart Sponsor action uses `helpUrl(locale, "sponsor")` through the shared external opener. Validate web, Electron and Tauri roles and compare Home/blank screenshots with `tests/browser/remote-project-tabs.test.ts`; launcher gestures use `new-instance-launcher.test.ts`. - Docked panel resize handles follow the composer's Pointer Events design: capture the pointer on the handle and keep its `.is-resizing` highlight until pointer up/cancel, capture loss or the active handle's cleanup. Scope each handle's cleanup to its own side so resizing continues when the opposite panel closes. Keep event handlers local in `useDrawerResize.ts` and styles in `styles/panels/session-layout.css`; validate both sides, RTL and touch with `tests/browser/panel-resize.test.ts`. diff --git a/docs/help/de/projects.md b/docs/help/de/projects.md index 4aaf0c4262..d95506af35 100644 --- a/docs/help/de/projects.md +++ b/docs/help/de/projects.md @@ -4,7 +4,7 @@ Ein Projekt-Tab verbindet CodeNomad mit einem Ordner auf dem Backend-Rechner. Da ## Projekt öffnen {#open-project} -1. Klicken Sie auf **Neue Instanz** (`+`), um einen leeren **Neuer Tab** mit Fokus im Suchfeld zu öffnen. **Zuletzt verwendet** und **Durchsuchen** stehen mit ihrer Eintragszahl nebeneinander, in schmalen Fenstern untereinander. Die Auswahl eines Projekts, Servers oder SideCars füllt diesen Tab an seiner Position. Ein leerer Tab schließt ohne verbleibendes Projekt und besteht bis zum Neuladen des Fensters. Das CodeNomad-Logo in der Titel- oder Tableiste öffnet die Startseite; ihre Herz-Schaltfläche **Sponsor** öffnet [CodeNomad unterstützen](sponsor.md). +1. **Neue Instanz** (`+`) öffnet einen leeren **Neuer Tab** mit Fokus in der Suche. Er nutzt Hintergrund, zentriertes CodeNomad-Logo und Namen sowie die großen Erstellungsbuttons der Startseite: **Git-Repo klonen**, **Neuer temporärer Tab**, **Neuer SideCar**. Rechts steht der Umschalter **Zuletzt verwendet | Durchsuchen** mit Eintragszahlen; die Suche liegt darunter in **Zuletzt verwendet**. Die Auswahl eines Projekts, gespeicherten Servers oder SideCars füllt diesen Tab an seiner Position. Ein leerer Tab besteht bis zum Neuladen und schließt ohne verbleibendes Projekt. Das CodeNomad-Logo in der Titel- oder Tableiste öffnet die Startseite mit Einstellungen, Sprache und der Herz-Schaltfläche **Sponsor** ([CodeNomad unterstützen](sponsor.md)). 2. Wählen Sie unter **Zuletzt verwendet** ein Projekt; oder öffnen Sie **Durchsuchen**, wählen Sie **Dieser Computer**, dann den Backend-Ordner, und öffnen Sie ihn. **Durchsuchen** listet auch gespeicherte CodeNomad-Server ([Remote-Projekt-Tabs](remote-access.md#remote-project-tabs)) und SideCars ([SideCars](browser-sidecars.md#register-sidecar)) auf. 3. Für eine Repository-Kopie wählen Sie **Git-Repo klonen**, geben **Repository-URL** und **Zielordner** ein und wählen **Klonen**. **Zielordner** wird mit dem Repository-Namen im Ordner, der Ihren letzten Klon enthält vorbelegt, sonst neben Ihrem zuletzt geöffneten Projekt. **Durchsuchen** wählt den Ordner, der den Klon enthält; Sie können den Pfad auch bearbeiten, einschließlich des Ordnernamens des Klons. diff --git a/docs/help/de/remote-access.md b/docs/help/de/remote-access.md index 858baf1a7c..00bf6c8581 100644 --- a/docs/help/de/remote-access.md +++ b/docs/help/de/remote-access.md @@ -83,8 +83,8 @@ Meldet ein Client eine Zertifikatswarnung, halten Sie an und prüfen Sie Hostnam ## Remote-Server speichern {#saved-servers} -1. Öffnen Sie auf der Desktop-Startseite oder im Starter **Tab öffnen** den Bereich **Durchsuchen**, fügen Sie die Adresse des Servers oder einen Kopplungslink in **Serveradresse oder -link** ein und drücken Sie die Eingabetaste: Der Server wird unter seinem Hostnamen gespeichert und öffnet sich. **Einstellungen → Server** bietet dasselbe Feld. -2. Verwenden Sie einen vertrauenswürdigen HTTPS-Ursprung. Besteht sein Zertifikat die Prüfung nicht, erscheint der Fehler unter dem Feld mit **TLS-Prüfung überspringen**: Aktivieren Sie dies nur für einen vertrauenswürdigen Server und drücken Sie erneut die Eingabetaste; dieser Server öffnet sich in einem eigenen Fenster. +1. Öffnen Sie auf der Startseite, einem leeren Tab oder im Starter **Tab öffnen** den Bereich **Durchsuchen**. Geben Sie Adresse oder Kopplungslink in **Serveradresse oder -link** ein: Einfügen fügt sofort hinzu, die Eingabetaste bestätigt getippten Text. Der Server wird nur unter seinem Hostnamen gespeichert und seine Zeile fokussiert; der Starter bleibt offen. Klicken Sie zum Öffnen auf diese Zeile. **Einstellungen → Server** bietet dasselbe Feld. +2. Verwenden Sie einen vertrauenswürdigen HTTPS-Ursprung. Besteht sein Zertifikat die Prüfung nicht, erscheint unter dem Feld **TLS-Prüfung überspringen**: Aktivieren Sie dies nur für einen vertrauenswürdigen Server und speichern Sie erneut mit der Eingabetaste. Die Auswahl dieses gespeicherten Servers öffnet ein eigenes Fenster. 3. Melden Sie sich auf diesem Server an. Benennen Sie ihn um oder ändern Sie seine Adresse mit **Server bearbeiten** unter **Einstellungen → Server**. Gespeicherte Server stehen unter **Durchsuchen**: Wählen Sie einen, um ihn erneut zu öffnen. In **Einstellungen → Server** öffnen, bearbeiten (**Server bearbeiten**: Name, Adresse, Zertifikatsprüfung) und entfernen (**Gespeicherten Server entfernen**) Sie sie. Lesezeichen gehören zu dieser CodeNomad-Konfiguration, nicht den Projekten des Remote-Servers. Eine URL zu speichern startet keinen Server und gewährt keinen Zugriff. **Gespeicherten Server entfernen** entfernt das Lesezeichen, nicht entfernte Unterhaltungen, Backend oder Zugangsdaten. @@ -99,7 +99,7 @@ Fügen Sie für Fernsteuerung stattdessen einen frischen Kopplungslink in **Serv In der Desktop-App (Electron oder Tauri unter Windows) kann ein gespeicherter Server eines seiner Projekte auch in einem Tab dieses Fensters öffnen, neben Ihren lokalen Projekten: -1. Öffnen Sie auf der Startseite oder im Starter **Tab öffnen** den Bereich **Durchsuchen** und wählen Sie einen Server, oder fügen Sie eine Adresse oder einen Kopplungslink in **Serveradresse oder -link** ein. +1. Öffnen Sie auf der Startseite, einem leeren Tab oder im Starter **Tab öffnen** den Bereich **Durchsuchen** und wählen Sie einen gespeicherten Server. Fügen Sie neue Server zuerst über **Serveradresse oder -link** hinzu und klicken Sie dann auf deren Zeile. 2. Wählen Sie den Ordner im Tab. Der Tab zeigt dann das Serversymbol und den Projektnamen, und das Projekt erscheint unter **Zuletzt verwendet**: Dort ausgewählt, öffnet es diesen Server und Ordner direkt wieder. Der Tab zeigt nur dieses Projekt; seine Unterhaltungen, Dateien, Git, Einstellungen und Missions laufen auf dem Remote-Server. Er nutzt den Speicher des Remote-Fensters dieses Servers, sodass eine bestehende Anmeldung oder ein gekoppeltes Gerät wiederverwendet wird, und Remote-Tabs kehren zurück, wenn CodeNomad Ihre Tabs wiederherstellt. Ein Server ohne diesen Modus zeigt im Tab seine vollständige Oberfläche. Server, die die TLS-Prüfung überspringen, sowie der Tauri-Build unter macOS und Linux öffnen weiterhin ein Remote-Fenster. Die Seite in einem Tab kann Benachrichtigungen anzeigen, hat aber sonst keinen Zugriff auf diesen Computer und bleibt auf ihrem Server. Webclients und Remote-Control-Geräte haben keine Remote-Tabs. **Gespeicherten Server entfernen** in **Einstellungen → Server** schließt auch seine Tabs. Bevor ein Projekt gewählt ist, zeigt der Tab den Namen des Servers. Melden Sie sich auf der Seite des Servers im Tab an; CodeNomad verwendet diese Anmeldung bei späteren Starts wieder. diff --git a/docs/help/de/remote-control.md b/docs/help/de/remote-control.md index cb08726def..31d56a44dd 100644 --- a/docs/help/de/remote-control.md +++ b/docs/help/de/remote-control.md @@ -11,7 +11,7 @@ Fernsteuerung ermöglicht einem gekoppelten Browser- oder Desktop-Client die Nut Der Link gilt **fünf Minuten** und funktioniert **einmal**. Behandeln Sie ihn als Zugangsdaten: Wer ihn einlöst, kann ein gekoppeltes Gerät werden. Der Code steht im URL-Fragment, nicht in der Abfragezeichenfolge. **Neuen Kopplungslink erstellen** macht den vorherigen ungenutzten Link sofort ungültig. Stop, Backend-Ende und Tunnelfehler stornieren offene Kopplungslinks. -Um einen weiteren CodeNomad-Desktop zu koppeln, öffnen Sie auf dessen Startseite **Durchsuchen** und fügen den Link in **Serveradresse oder -link** ein: Der Server öffnet sich und wird gekoppelt. Nur die Tunnel-Origin wird als Lesezeichen gespeichert; der Code bleibt nicht erhalten. TLS-Prüfung bleibt für Kopplungslinks aktiviert. +Um einen weiteren CodeNomad-Desktop zu koppeln, öffnen Sie auf der Startseite oder einem leeren Tab **Durchsuchen** und fügen den Link in **Serveradresse oder -link** ein. Das fügt nur den Server hinzu; klicken Sie zum Öffnen und Koppeln auf seine gespeicherte Zeile. Der Einmallink wartet im Speicher dieses Fensters bis zum Öffnen oder Neuladen; nutzen Sie ihn innerhalb seiner fünf Minuten Gültigkeit. Nur die Tunnel-Origin wird als Lesezeichen gespeichert. Die TLS-Prüfung bleibt für Kopplungslinks aktiviert. ## Gekoppelte Geräte verwalten {#paired-devices} diff --git a/docs/help/en/projects.md b/docs/help/en/projects.md index 17ef96e8b1..c0c0aac2ad 100644 --- a/docs/help/en/projects.md +++ b/docs/help/en/projects.md @@ -4,7 +4,7 @@ A project tab connects CodeNomad to a folder on the backend computer. Opening a ## Open a project {#open-project} -1. Click **New instance** (`+`) to open an empty **New tab**, focused on search. **Recent** and **Browse** appear side by side, stacked in a narrow window, with their item counts. Choosing a project, server or SideCar fills that tab in place. An empty tab closes without leaving a project and lasts only until the window reloads. Click the CodeNomad logo in the title bar or tab bar to open Home; its heart **Sponsor** button opens [Support CodeNomad](sponsor.md). +1. Click **New instance** (`+`) to open an empty **New tab**, focused on search. It shares Home's background, centered CodeNomad logo and name, large **Clone Git Repo**, **New temporary tab** and **New SideCar** buttons, and the **Recent | Browse** selector with item counts. Search sits below the selector in **Recent**. Choosing a project, saved server or SideCar fills that tab in place. An empty tab lasts until the window reloads and closes without leaving a project. The CodeNomad logo in the title bar or tab bar opens Home, which also offers settings, language and the heart **Sponsor** button ([Support CodeNomad](sponsor.md)). 2. In **Recent**, choose a project; or open **Browse**, choose **This computer**, then select the backend folder and open it. **Browse** also lists saved CodeNomad servers ([remote project tabs](remote-access.md#remote-project-tabs)) and SideCars ([SideCars](browser-sidecars.md#register-sidecar)). 3. For a repository copy, choose **Clone Git Repo**, enter **Repository URL** and **Destination folder**, then **Clone**. **Destination folder** is prefilled with the repository name in the folder that holds your last clone, or next to your most recent project. **Browse** chooses the folder that contains the clone; you can also edit the path, including the clone's folder name. diff --git a/docs/help/en/remote-access.md b/docs/help/en/remote-access.md index 5c8fdd64ba..a043ca6d88 100644 --- a/docs/help/en/remote-access.md +++ b/docs/help/en/remote-access.md @@ -83,8 +83,8 @@ If a client reports a certificate warning, stop and check the hostname, SANs, tr ## Save a remote server {#saved-servers} -1. On the desktop home page or in the **Open a tab** launcher, open **Browse** and paste the server's address or a pairing link into **Server address or link**, then press Enter: the server is saved under its host name and opens. **Settings → Servers** offers the same field. -2. Use a trusted HTTPS origin. If its certificate fails the check, the error shows under the field with **Skip TLS verification**: tick it only for a server you trust, then press Enter again; that server opens in its own window. +1. On Home, an empty tab or the **Open a tab** launcher, open **Browse** and enter the address or pairing link in **Server address or link**. Pasting adds it immediately; Enter adds typed text. Adding only saves the server under its host name and focuses its row; the launcher stays open. Click the saved row to open it. **Settings → Servers** offers the same field. +2. Use a trusted HTTPS origin. If its certificate fails the check, the error shows under the field with **Skip TLS verification**: tick it only for a server you trust, then press Enter again to save it. Selecting that saved server opens its own window. 3. Sign in on that server. Rename it or change its address with **Edit server** in **Settings → Servers**. Saved servers are listed under **Browse**: choose one to open it again. **Settings → Servers** is where you open, edit (**Edit server**: name, address, certificate check) and remove (**Remove saved server**) them. Bookmarks belong to this CodeNomad configuration, not the remote server's projects. Saving a URL does not start the server or grant access. **Remove saved server** removes the bookmark, not remote conversations, the backend or its credentials. @@ -99,7 +99,7 @@ For Remote Control, paste a fresh pairing link into **Server address or link** i In the desktop app (Electron, or Tauri on Windows), a saved server can also open one of its projects in a tab of this window, beside your local projects: -1. On the home page or in the **Open a tab** launcher, open **Browse** and choose a server, or paste an address or a pairing link into **Server address or link**. +1. On Home, an empty tab or the **Open a tab** launcher, open **Browse** and choose a saved server. To add one first, use **Server address or link**, then click its new row. 2. Pick the folder in the tab. The tab then shows the server icon and the project name, and the project joins **Recent**: choosing it there reopens that server and folder directly. The tab shows only that project; its conversations, files, Git, settings and Missions run on the remote server. It uses the storage of the server's remote window, so an existing sign-in or paired device is reused, and remote tabs come back when CodeNomad restores your tabs. A server without this mode shows its full interface in the tab. Servers that skip TLS verification, and the Tauri build on macOS and Linux, keep opening a remote window. The page in a tab can show notifications but has no other access to this computer and stays on its server. Web clients and Remote Control devices have no remote tabs. **Remove saved server**, in **Settings → Servers**, also closes its tabs. Before a project is chosen, the tab shows the server's name. Sign in on the server's page in the tab; CodeNomad reuses that sign-in on later launches. diff --git a/docs/help/en/remote-control.md b/docs/help/en/remote-control.md index 6f35246e8e..09a0d732bc 100644 --- a/docs/help/en/remote-control.md +++ b/docs/help/en/remote-control.md @@ -11,7 +11,7 @@ Remote Control lets a paired browser or desktop client use your running CodeNoma The link is valid for **five minutes** and succeeds **once**. Treat it as a credential: anyone who consumes it can become a paired device. The code lives in the URL fragment, not the query string. **Create new pairing link** immediately invalidates the preceding unused link. Stop, backend shutdown and tunnel failure cancel outstanding pairing links. -To pair another desktop CodeNomad, open **Browse** on its home page and paste the link into **Server address or link**: the server opens and pairs. Only the tunnel origin is saved as the bookmark; the code is not retained. TLS verification stays enabled for pairing links. +To pair another desktop CodeNomad, open **Browse** on Home or an empty tab and paste the link into **Server address or link**. This only adds the server; click its saved row to open and pair. The one-use link waits in memory in this window until you open it or reload; use it within its five-minute lifetime. Only the tunnel origin is saved as the bookmark. TLS verification stays enabled for pairing links. ## Manage paired devices {#paired-devices} diff --git a/docs/help/es/projects.md b/docs/help/es/projects.md index 29866f15d2..f570437cbb 100644 --- a/docs/help/es/projects.md +++ b/docs/help/es/projects.md @@ -4,7 +4,7 @@ Una pestaña de proyecto conecta CodeNomad a una carpeta del equipo del backend. ## Abrir un proyecto {#open-project} -1. Haz clic en **Nueva instancia** (`+`) para abrir una **Nueva pestaña** vacía con el foco en la búsqueda. **Recientes** y **Explorar** aparecen lado a lado, apilados en ventanas estrechas, con sus cantidades de elementos. Elegir un proyecto, servidor o SideCar llena esa pestaña en su posición. Una pestaña vacía se cierra sin dejar un proyecto y dura hasta recargar la ventana. El logotipo CodeNomad de la barra de título o de pestañas abre Inicio; su botón **Patrocinar** con un corazón abre [Apoyar CodeNomad](sponsor.md). +1. **Nueva instancia** (`+`) abre una **Nueva pestaña** vacía con el foco en la búsqueda. Comparte el fondo, logotipo y nombre CodeNomad centrados y los botones grandes de Inicio: **Clonar repo Git**, **Nueva pestaña temporal** y **Nuevo SideCar**. El selector **Recientes | Explorar** muestra cantidades; la búsqueda está debajo, en **Recientes**. Elegir un proyecto, servidor guardado o SideCar llena esa pestaña en su posición. La pestaña vacía dura hasta recargar y se cierra sin dejar un proyecto. El logotipo CodeNomad en la barra de título o pestañas abre Inicio, con configuración, idioma y el botón con corazón **Patrocinar** ([Apoyar CodeNomad](sponsor.md)). 2. En **Recientes**, elige un proyecto; o abre **Explorar**, elige **Este equipo** y luego selecciona la carpeta del backend y ábrela. **Explorar** también lista los servidores CodeNomad guardados ([pestañas de proyectos remotos](remote-access.md#remote-project-tabs)) y los SideCars ([SideCars](browser-sidecars.md#register-sidecar)). 3. Para obtener una copia de un repositorio, elige **Clonar repo Git**, introduce la **URL del repositorio** y la **Carpeta de destino** y pulsa **Clonar**. La **Carpeta de destino** se rellena con el nombre del repositorio en la carpeta que contiene tu último clon, o junto a tu proyecto más reciente. **Buscar** elige la carpeta que contendrá el clon; también puedes editar la ruta, incluido el nombre de la carpeta del clon. diff --git a/docs/help/es/remote-access.md b/docs/help/es/remote-access.md index 16073e3bf8..116f5db89a 100644 --- a/docs/help/es/remote-access.md +++ b/docs/help/es/remote-access.md @@ -83,8 +83,8 @@ Si un cliente muestra una advertencia de certificado, detente y comprueba el nom ## Guardar un servidor remoto {#saved-servers} -1. En la página de inicio de escritorio o en el lanzador **Abrir una pestaña**, abre **Explorar**, pega la dirección del servidor o un enlace de emparejamiento en **Dirección o enlace del servidor** y pulsa Intro: el servidor se guarda con su nombre de host y se abre. **Configuración → Servidores** ofrece el mismo campo. -2. Usa un origen HTTPS de confianza. Si su certificado no supera la verificación, el error aparece bajo el campo con **Omitir la verificación TLS**: márcala solo para un servidor de confianza y vuelve a pulsar Intro; ese servidor se abre en su propia ventana. +1. En Inicio, una pestaña vacía o el lanzador **Abrir una pestaña**, abre **Explorar** e introduce la dirección o enlace de emparejamiento en **Dirección o enlace del servidor**. Pegar lo añade al instante; Intro confirma el texto escrito. Solo se guarda el servidor con su nombre de host y se enfoca su fila; el lanzador permanece abierto. Haz clic en la fila para abrirlo. **Configuración → Servidores** ofrece el mismo campo. +2. Usa un origen HTTPS de confianza. Si su certificado no supera la verificación, aparece **Omitir la verificación TLS** bajo el campo: márcala solo para un servidor de confianza y pulsa Intro de nuevo para guardarlo. Seleccionar ese servidor guardado abre su propia ventana. 3. Inicia sesión en ese servidor. Cambia su nombre o su dirección con **Editar servidor** en **Configuración → Servidores**. Los servidores guardados aparecen en **Explorar**: elige uno para volver a abrirlo. En **Configuración → Servidores** se abren, se editan (**Editar servidor**: nombre, dirección, verificación del certificado) y se quitan (**Eliminar servidor guardado**). Los marcadores pertenecen a esta configuración de CodeNomad, no a los proyectos del servidor remoto. Guardar una URL no inicia el servidor ni concede acceso. **Eliminar servidor guardado** elimina el marcador, no las conversaciones remotas, el backend ni sus credenciales. @@ -99,7 +99,7 @@ Para Control remoto, pega en su lugar un enlace de emparejamiento nuevo en **Dir En la aplicación de escritorio (Electron, o Tauri en Windows), un servidor guardado también puede abrir uno de sus proyectos en una pestaña de esta ventana, junto a tus proyectos locales: -1. En la página de inicio o en el lanzador **Abrir una pestaña**, abre **Explorar** y elige un servidor, o pega una dirección o un enlace de emparejamiento en **Dirección o enlace del servidor**. +1. En Inicio, una pestaña vacía o el lanzador **Abrir una pestaña**, abre **Explorar** y elige un servidor guardado. Para añadirlo primero, usa **Dirección o enlace del servidor** y haz clic en su nueva fila. 2. Elige la carpeta en la pestaña. La pestaña muestra entonces el icono de servidor y el nombre del proyecto, y el proyecto se suma a **Recientes**: elegirlo allí vuelve a abrir directamente ese servidor y esa carpeta. La pestaña muestra solo ese proyecto; sus conversaciones, archivos, Git, ajustes y Missions se ejecutan en el servidor remoto. Usa el almacenamiento de la ventana remota del servidor, así que se reutiliza un inicio de sesión o un dispositivo emparejado existente, y las pestañas remotas vuelven cuando CodeNomad restaura tus pestañas. Un servidor sin este modo muestra su interfaz completa en la pestaña. Los servidores que omiten la verificación TLS, y la versión Tauri en macOS y Linux, siguen abriendo una ventana remota. La página de una pestaña puede mostrar notificaciones, pero no tiene otro acceso a este equipo y permanece en su servidor. Los clientes web y los dispositivos de Remote Control no tienen pestañas remotas. **Eliminar servidor guardado**, en **Configuración → Servidores**, también cierra sus pestañas. Antes de elegir un proyecto, la pestaña muestra el nombre del servidor. Inicia sesión en la página del servidor, dentro de la pestaña; CodeNomad reutiliza ese inicio de sesión en los siguientes arranques. diff --git a/docs/help/es/remote-control.md b/docs/help/es/remote-control.md index 35f4d7caf9..6ccf99f640 100644 --- a/docs/help/es/remote-control.md +++ b/docs/help/es/remote-control.md @@ -11,7 +11,7 @@ Control remoto permite a un navegador o cliente de escritorio emparejado usar tu El enlace es válido durante **cinco minutos** y funciona **una vez**. Trátalo como una credencial: cualquiera que lo consuma puede convertirse en un dispositivo emparejado. El código está en el fragmento de la URL, no en la cadena de consulta. **Crear nuevo enlace de emparejamiento** invalida inmediatamente el enlace anterior sin usar. Detener, apagar el backend y los fallos del túnel cancelan los enlaces de emparejamiento pendientes. -Para emparejar otro CodeNomad de escritorio, abre **Explorar** en su página de inicio y pega el enlace en **Dirección o enlace del servidor**: el servidor se abre y se empareja. Solo se guarda el origen del túnel como marcador; el código no se conserva. La verificación TLS permanece activada para enlaces de emparejamiento. +Para emparejar otro CodeNomad de escritorio, abre **Explorar** en Inicio o una pestaña vacía y pega el enlace en **Dirección o enlace del servidor**. Esto solo añade el servidor; haz clic en su fila guardada para abrir y emparejar. El enlace de un solo uso espera en la memoria de esta ventana hasta abrirlo o recargar; úsalo durante sus cinco minutos de validez. Solo se guarda el origen del túnel como marcador. La verificación TLS permanece activada para los enlaces de emparejamiento. ## Gestionar dispositivos emparejados {#paired-devices} diff --git a/docs/help/fr/projects.md b/docs/help/fr/projects.md index eccf4e8a79..2d3020356d 100644 --- a/docs/help/fr/projects.md +++ b/docs/help/fr/projects.md @@ -4,7 +4,7 @@ Un onglet de projet relie CodeNomad à un dossier sur l’ordinateur du backend. ## Ouvrir un projet {#open-project} -1. Cliquez sur **Nouvelle instance** (`+`) pour ouvrir un **Nouvel onglet** vide, avec le focus dans la recherche. **Récents** et **Parcourir** apparaissent côte à côte, empilés dans une fenêtre étroite, avec leur nombre d'éléments. Choisir un projet, un serveur ou un SideCar remplit cet onglet sur place. Un onglet vide se ferme sans laisser de projet et dure jusqu'au rechargement de la fenêtre. Cliquez sur le logo CodeNomad dans la barre de titre ou d'onglets pour ouvrir l'accueil ; son bouton **Sponsor** avec un cœur ouvre [Soutenir CodeNomad](sponsor.md). +1. Cliquez sur **Nouvelle instance** (`+`) pour ouvrir un **Nouvel onglet** vide, avec le focus dans la recherche. Il reprend le fond de l'accueil, le logo et le nom CodeNomad centrés, les grands boutons **Cloner un dépôt Git**, **Nouvel onglet temporaire** et **Nouveau SideCar**, et le sélecteur **Récents | Parcourir** avec compteurs. La recherche est sous le sélecteur dans **Récents**. Choisir un projet, un serveur enregistré ou un SideCar remplit cet onglet sur place. Un onglet vide dure jusqu'au rechargement de la fenêtre et se ferme sans laisser de projet. Le logo CodeNomad de la barre de titre ou d'onglets ouvre l'accueil, qui propose aussi les réglages, la langue et le bouton cœur **Sponsor** ([Soutenir CodeNomad](sponsor.md)). 2. Dans **Récents**, choisissez un projet ; ou ouvrez **Parcourir**, choisissez **Cet ordinateur**, puis sélectionnez le dossier du backend et ouvrez-le. **Parcourir** liste aussi les serveurs CodeNomad enregistrés ([onglets de projets distants](remote-access.md#remote-project-tabs)) et les SideCars ([SideCars](browser-sidecars.md#register-sidecar)). 3. Pour une copie de dépôt, choisissez **Cloner un depot Git**, saisissez **URL du depot** et **Dossier de destination**, puis **Cloner**. **Dossier de destination** est prérempli avec le nom du dépôt, dans le dossier qui contient votre dernier clone, sinon à côté de votre projet le plus récent. **Parcourir** choisit le dossier qui contiendra le clone ; vous pouvez aussi modifier le chemin, y compris le nom du dossier du clone. diff --git a/docs/help/fr/remote-access.md b/docs/help/fr/remote-access.md index 986e3e4c23..ef102f81f5 100644 --- a/docs/help/fr/remote-access.md +++ b/docs/help/fr/remote-access.md @@ -83,8 +83,8 @@ Si un client signale un avertissement de certificat, arrêtez-vous et vérifiez ## Enregistrer un serveur distant {#saved-servers} -1. Sur l’accueil de bureau ou dans le lanceur **Ouvrir un onglet**, ouvrez **Parcourir** et collez l’adresse du serveur ou un lien d’appairage dans **Adresse ou lien du serveur**, puis appuyez sur Entrée : le serveur est enregistré sous son nom d’hôte et s’ouvre. **Paramètres → Serveurs** propose le même champ. -2. Utilisez une origine HTTPS de confiance. Si son certificat échoue à la vérification, l’erreur s’affiche sous le champ avec **Ignorer la vérification TLS** : cochez-la seulement pour un serveur de confiance, puis appuyez de nouveau sur Entrée ; ce serveur s’ouvre dans sa propre fenêtre. +1. Sur l’accueil, un onglet vide ou le lanceur **Ouvrir un onglet**, ouvrez **Parcourir** et saisissez l’adresse ou le lien d’appairage dans **Adresse ou lien du serveur**. Le collage l’ajoute immédiatement ; Entrée ajoute le texte saisi. L’ajout enregistre seulement le serveur sous son nom d’hôte et place le focus sur sa ligne ; le lanceur reste ouvert. Cliquez sur cette ligne pour l’ouvrir. **Paramètres → Serveurs** propose le même champ. +2. Utilisez une origine HTTPS de confiance. Si son certificat échoue à la vérification, l’erreur s’affiche sous le champ avec **Ignorer la vérification TLS** : cochez-la seulement pour un serveur de confiance, puis appuyez de nouveau sur Entrée pour l’enregistrer. Sélectionner ce serveur enregistré ouvre sa propre fenêtre. 3. Connectez-vous sur ce serveur. Renommez-le ou changez son adresse avec **Modifier le serveur** dans **Paramètres → Serveurs**. Les serveurs enregistrés sont listés sous **Parcourir** : choisissez-en un pour l’ouvrir de nouveau. **Paramètres → Serveurs** permet de les ouvrir, de les modifier (**Modifier le serveur** : nom, adresse, vérification du certificat) et de les retirer (**Supprimer le serveur enregistré**). Les favoris appartiennent à cette configuration CodeNomad, pas aux projets du serveur distant. Enregistrer une URL ne démarre pas le serveur et n’accorde pas l’accès. **Supprimer le serveur enregistré** retire le favori, pas les conversations distantes, le backend ou ses identifiants. @@ -99,7 +99,7 @@ Pour le Contrôle à distance, collez plutôt un lien d’appairage récent dans Dans l'application de bureau (Electron, ou Tauri sous Windows), un serveur enregistré peut aussi ouvrir l'un de ses projets dans un onglet de cette fenêtre, à côté de vos projets locaux : -1. Sur l’accueil ou dans le lanceur **Ouvrir un onglet**, ouvrez **Parcourir** et choisissez un serveur, ou collez une adresse ou un lien d’appairage dans **Adresse ou lien du serveur**. +1. Sur l’accueil, un onglet vide ou le lanceur **Ouvrir un onglet**, ouvrez **Parcourir** et choisissez un serveur enregistré. Pour en ajouter un, utilisez **Adresse ou lien du serveur**, puis cliquez sur sa nouvelle ligne. 2. Choisissez le dossier dans l'onglet. L'onglet affiche alors l'icône serveur et le nom du projet, et le projet rejoint **Récents** : le choisir à cet endroit rouvre directement ce serveur et ce dossier. L'onglet n'affiche que ce projet ; ses conversations, fichiers, Git, paramètres et Missions s'exécutent sur le serveur distant. Il utilise le stockage de la fenêtre distante du serveur : une connexion ou un appareil appairé existant est donc réutilisé, et les onglets distants reviennent quand CodeNomad restaure vos onglets. Un serveur sans ce mode affiche son interface complète dans l'onglet. Les serveurs qui ignorent la vérification TLS, ainsi que la version Tauri sous macOS et Linux, continuent d'ouvrir une fenêtre distante. La page d'un onglet peut afficher des notifications, sans autre accès à cet ordinateur, et reste sur son serveur. Les clients web et les appareils Remote Control n'ont pas d'onglets distants. **Supprimer le serveur enregistré**, dans **Paramètres → Serveurs**, ferme aussi ses onglets. Avant le choix d’un projet, l’onglet affiche le nom du serveur. Connectez-vous sur la page du serveur, dans l’onglet ; CodeNomad réutilise cette connexion aux lancements suivants. diff --git a/docs/help/fr/remote-control.md b/docs/help/fr/remote-control.md index b8d78f38e7..8ceb60761a 100644 --- a/docs/help/fr/remote-control.md +++ b/docs/help/fr/remote-control.md @@ -11,7 +11,7 @@ Le Contrôle à distance permet à un navigateur ou client de bureau appairé d Le lien est valable **cinq minutes** et réussit **une seule fois**. Traitez-le comme un identifiant : quiconque le consomme peut devenir un appareil appairé. Le code se trouve dans le fragment d’URL, pas dans la chaîne de requête. **Créer un nouveau lien d’appairage** invalide immédiatement le lien inutilisé précédent. L’arrêt, la fermeture du backend et une panne du tunnel annulent les liens d’appairage en attente. -Pour appairer un autre CodeNomad de bureau, ouvrez **Parcourir** sur son accueil et collez le lien dans **Adresse ou lien du serveur** : le serveur s’ouvre et s’appaire. Seule l’origine du tunnel est enregistrée comme favori ; le code n’est pas conservé. La vérification TLS reste activée pour les liens d’appairage. +Pour appairer un autre CodeNomad de bureau, ouvrez **Parcourir** sur l’accueil ou un onglet vide et collez le lien dans **Adresse ou lien du serveur**. Cela ajoute seulement le serveur ; cliquez sur sa ligne enregistrée pour l’ouvrir et l’appairer. Le lien à usage unique attend en mémoire dans cette fenêtre jusqu’à son ouverture ou au rechargement ; utilisez-le pendant ses cinq minutes de validité. Seule l’origine du tunnel est enregistrée comme favori. La vérification TLS reste activée pour les liens d’appairage. ## Gérer les appareils appairés {#paired-devices} diff --git a/docs/help/he/projects.md b/docs/help/he/projects.md index e44cf8db4d..e228febd90 100644 --- a/docs/help/he/projects.md +++ b/docs/help/he/projects.md @@ -4,7 +4,7 @@ ## פתיחת פרויקט {#open-project} -1. לחצו **מופע חדש** (`+`) לפתיחת **לשונית חדשה** ריקה עם מיקוד בחיפוש. **אחרונים** ו־**עיון** מוצגים זה לצד זה, ובחלון צר זה מתחת לזה, עם מספר הפריטים. בחירת פרויקט, שרת או SideCar ממלאת את הלשונית במקומה. לשונית ריקה נסגרת בלי להשאיר פרויקט וקיימת עד לטעינה מחדש של החלון. הלוגו של CodeNomad בשורת הכותרת או הלשוניות פותח את דף הבית; כפתור **חסות** עם לב פותח את [תמיכה ב־CodeNomad](sponsor.md). +1. **מופע חדש** (`+`) פותח **לשונית חדשה** ריקה עם מיקוד בחיפוש. היא משתמשת ברקע של דף הבית, בלוגו ובשם CodeNomad במרכז ובכפתורים הגדולים **שכפל מאגר Git**, **לשונית זמנית חדשה** ו־**SideCar חדש**. הבורר **אחרונים | עיון** מציג מספר פריטים; החיפוש נמצא מתחתיו בתוך **אחרונים**. בחירת פרויקט, שרת שמור או SideCar ממלאת את הלשונית במקומה. לשונית ריקה קיימת עד לטעינה מחדש ונסגרת בלי להשאיר פרויקט. הלוגו של CodeNomad בשורת הכותרת או הלשוניות פותח את דף הבית עם הגדרות, שפה וכפתור הלב **חסות** ([תמיכה ב־CodeNomad](sponsor.md)). 2. ב־**אחרונים**, בחרו פרויקט; או פתחו את **עיון**, בחרו **המחשב הזה**, ואז בחרו את תיקיית ה־backend ופתחו אותה. **עיון** מציג גם שרתי CodeNomad שמורים ([לשוניות של פרויקטים מרוחקים](remote-access.md#remote-project-tabs)) ו־SideCars ([SideCars](browser-sidecars.md#register-sidecar)). 3. לעותק מאגר, בחרו **שכפל מאגר Git**, הזינו **כתובת המאגר** ו־**תיקיית יעד**, ואז **שכפל**. **תיקיית יעד** ממולא מראש בשם המאגר, בתיקייה שמכילה את השכפול האחרון שלך, או לצד הפרויקט האחרון שלך. **עיון** בוחר את התיקייה שתכיל את השכפול; אפשר גם לערוך את הנתיב, כולל שם התיקייה של השכפול. diff --git a/docs/help/he/remote-access.md b/docs/help/he/remote-access.md index 4789668387..5e7e285aff 100644 --- a/docs/help/he/remote-access.md +++ b/docs/help/he/remote-access.md @@ -83,8 +83,8 @@ codenomad --host 127.0.0.1 --https=false --http=true ## שמירת שרת מרוחק {#saved-servers} -1. בדף הבית בשולחן העבודה או במפעיל **פתיחת לשונית**, פתחו את **עיון**, הדביקו את כתובת השרת או קישור צימוד בשדה **כתובת או קישור של השרת** והקישו Enter: השרת נשמר בשם המארח שלו ונפתח. **הגדרות → שרתים** מציע את אותו השדה. -2. השתמשו במקור HTTPS מהימן. אם התעודה שלו נכשלת בבדיקה, השגיאה מופיעה מתחת לשדה עם **דילוג על אימות TLS**: סמנו זאת רק עבור שרת מהימן והקישו Enter שוב; השרת הזה נפתח בחלון משלו. +1. בדף הבית, בלשונית ריקה או במשגר **פתיחת לשונית**, פתחו את **עיון** והזינו כתובת או קישור צימוד ב־**כתובת או קישור של השרת**. הדבקה מוסיפה מיד; Enter מוסיף טקסט שהוקלד. ההוספה רק שומרת את השרת בשם המארח וממקדת את השורה שלו; המשגר נשאר פתוח. לחצו על השורה כדי לפתוח. **הגדרות → שרתים** מציע את אותו השדה. +2. השתמשו במקור HTTPS מהימן. אם התעודה נכשלת בבדיקה, **דילוג על אימות TLS** מופיע מתחת לשדה: סמנו רק לשרת מהימן והקישו Enter שוב כדי לשמור. בחירת השרת השמור הזה פותחת חלון משלו. 3. התחברו לשרת הזה. שנו את שמו או את כתובתו באמצעות **עריכת שרת** ב־**הגדרות → שרתים**. שרתים שמורים מופיעים תחת **עיון**: בחרו שרת כדי לפתוח אותו שוב. ב־**הגדרות → שרתים** פותחים אותם, עורכים אותם (**עריכת שרת**: שם, כתובת, בדיקת תעודה) ומסירים אותם (**הסר שרת שמור**). סימניות שייכות לתצורת CodeNomad זו, לא לפרויקטי השרת המרוחק. שמירת כתובת אינה מפעילה שרת או מעניקה גישה. **הסר שרת שמור** מסיר את הסימנייה, לא שיחות מרוחקות, את שרת הקצה או את פרטי ההתחברות שלו. @@ -99,7 +99,7 @@ codenomad --host 127.0.0.1 --https=false --http=true ביישום שולחן העבודה (Electron, או Tauri ב-Windows), שרת שמור יכול לפתוח גם אחד מהפרויקטים שלו בלשונית של החלון הזה, לצד הפרויקטים המקומיים שלך: -1. בדף הבית או במפעיל **פתיחת לשונית**, פתחו את **עיון** ובחרו שרת, או הדביקו כתובת או קישור צימוד בשדה **כתובת או קישור של השרת**. +1. בדף הבית, בלשונית ריקה או במשגר **פתיחת לשונית**, פתחו את **עיון** ובחרו שרת שמור. להוספה תחילה השתמשו ב־**כתובת או קישור של השרת**, ואז לחצו על השורה החדשה. 2. בחרו את התיקייה בלשונית. הלשונית מציגה אז את סמל השרת ואת שם הפרויקט, והפרויקט מצטרף ל-**אחרונים**: בחירה בו שם פותחת מחדש ישירות את השרת והתיקייה האלה. הלשונית מציגה רק את הפרויקט הזה; השיחות, הקבצים, Git, ההגדרות וה-Missions שלו פועלים בשרת המרוחק. היא משתמשת באחסון של החלון המרוחק של השרת, כך שהתחברות קיימת או מכשיר מצומד נעשים בהם שימוש חוזר, והלשוניות המרוחקות חוזרות כש-CodeNomad משחזר את הלשוניות שלך. שרת ללא מצב זה מציג בלשונית את הממשק המלא שלו. שרתים שמדלגים על אימות TLS, וגרסת Tauri ב-macOS וב-Linux, ממשיכים לפתוח חלון מרוחק. הדף שבלשונית יכול להציג התראות, אך אין לו גישה אחרת למחשב הזה והוא נשאר בשרת שלו. ללקוחות אינטרנט ולמכשירי Remote Control אין לשוניות מרוחקות. **הסר שרת שמור**, ב־**הגדרות → שרתים**, סוגר גם את הלשוניות שלו. לפני בחירת פרויקט, הלשונית מציגה את שם השרת. התחברו בדף של השרת בתוך הלשונית; CodeNomad משתמש שוב בהתחברות זו בהפעלות הבאות. diff --git a/docs/help/he/remote-control.md b/docs/help/he/remote-control.md index 3cbff9c281..1ad8f02a15 100644 --- a/docs/help/he/remote-control.md +++ b/docs/help/he/remote-control.md @@ -11,7 +11,7 @@ הקישור תקף ל־**חמש דקות** ומצליח **פעם אחת**. התייחסו אליו כאישור גישה: כל מי שמנצל אותו יכול להפוך למכשיר מצומד. הקוד נמצא במקטע הכתובת, לא במחרוזת השאילתה. **צור קישור צימוד חדש** מבטל מיד את הקישור הקודם שלא נוצל. עצירה, כיבוי שרת הקצה וכשל במנהרה מבטלים קישורי צימוד שטרם נוצלו. -לצימוד CodeNomad נוסף לשולחן העבודה, פתחו את **עיון** בדף הבית שלו והדביקו את הקישור בשדה **כתובת או קישור של השרת**: השרת נפתח ומצומד. רק מקור המנהרה נשמר כסימנייה; הקוד אינו נשמר. אימות TLS נשאר פעיל לקישורי צימוד. +לצימוד CodeNomad נוסף לשולחן העבודה, פתחו את **עיון** בדף הבית או בלשונית ריקה והדביקו את הקישור ב־**כתובת או קישור של השרת**. פעולה זו רק מוסיפה את השרת; לחצו על השורה השמורה לפתיחה ולצימוד. הקישור החד־פעמי ממתין בזיכרון החלון עד לפתיחה או לטעינה מחדש; השתמשו בו בחמש דקות התוקף שלו. רק מקור המנהרה נשמר כסימנייה. אימות TLS נשאר פעיל לקישורי צימוד. ## ניהול מכשירים מצומדים {#paired-devices} diff --git a/docs/help/ja/projects.md b/docs/help/ja/projects.md index 2ece472124..d600523450 100644 --- a/docs/help/ja/projects.md +++ b/docs/help/ja/projects.md @@ -4,7 +4,7 @@ ## プロジェクトを開く {#open-project} -1. **新しいインスタンス**(`+`)をクリックすると、検索欄にフォーカスした空の **新しいタブ** が開きます。**最近** と **参照** は件数とともに横並びで、狭いウィンドウでは縦に表示されます。プロジェクト、サーバー、SideCar を選ぶと、その位置でタブの内容が切り替わります。空のタブはプロジェクトを残さず閉じ、ウィンドウの再読み込みまで有効です。タイトルバーまたはタブバーの CodeNomad ロゴからホームを開けます。ハートの **スポンサー** ボタンは [CodeNomad を支援](sponsor.md) を開きます。 +1. **新しいインスタンス**(`+`)は検索欄にフォーカスした空の **新しいタブ** を開きます。ホームと同じ背景、中央の CodeNomad ロゴと名前、大きな **Git リポジトリをクローン**・**新しい一時タブ**・**新しい SideCar** ボタンを使います。**最近 | 参照** セレクターに件数が表示され、検索はその下の **最近** 内にあります。プロジェクト、保存済みサーバー、SideCar を選ぶと、その位置でタブが切り替わります。空のタブは再読み込みまで有効で、プロジェクトを残さず閉じます。タイトルバーまたはタブバーの CodeNomad ロゴは、設定・言語・ハートの **スポンサー** ボタンもあるホームを開きます([CodeNomad を支援](sponsor.md))。 2. **最近** でプロジェクトを選ぶか、**参照** を開いて **このコンピューター** を選び、バックエンドのフォルダーを選択して開きます。**参照** には保存した CodeNomad サーバー([リモートプロジェクトのタブ](remote-access.md#remote-project-tabs))と SideCar([SideCar](browser-sidecars.md#register-sidecar))も表示されます。 3. リポジトリをコピーするには、**Git リポジトリをクローン** を選び、**リポジトリ URL** と **保存先フォルダ** を入力して **クローン** を選びます。**保存先フォルダ** には、前回のクローンがあるフォルダー(なければ最近のプロジェクトと同じ場所)にリポジトリ名のフォルダーが入力されます。**参照** ではクローンを置くフォルダーを選びます。クローンのフォルダー名を含め、パスは直接編集することもできます。 diff --git a/docs/help/ja/remote-access.md b/docs/help/ja/remote-access.md index 2cf9c6b831..254ef10a78 100644 --- a/docs/help/ja/remote-access.md +++ b/docs/help/ja/remote-access.md @@ -83,8 +83,8 @@ HTTPS が有効で鍵/証明書のペアを指定していない場合、CodeN ## リモートサーバーを保存する {#saved-servers} -1. デスクトップのホームページまたは **タブを開く** ランチャーで **参照** を開き、サーバーのアドレスまたはペアリングリンクを **サーバーのアドレスまたはリンク** に貼り付けて Enter を押します。サーバーはホスト名で保存されて開きます。**設定 → サーバー** にも同じ入力欄があります。 -2. 信頼できる HTTPS オリジンを使用してください。証明書が検証に失敗した場合は、入力欄の下にエラーと **TLS 検証をスキップ** が表示されます。信頼できるサーバーの場合にのみオンにして、もう一度 Enter を押します。そのサーバーは専用のウィンドウで開きます。 +1. ホーム、空のタブ、**タブを開く** ランチャーで **参照** を開き、アドレスまたはペアリングリンクを **サーバーのアドレスまたはリンク** に入力します。貼り付けは即座に追加し、手入力は Enter で追加します。サーバーはホスト名で保存され、その行にフォーカスが移ります。ランチャーは開いたままです。行をクリックすると開きます。**設定 → サーバー** にも同じ入力欄があります。 +2. 信頼できる HTTPS オリジンを使ってください。証明書の検証に失敗した場合、入力欄の下に **TLS 検証をスキップ** が表示されます。信頼できるサーバーだけでオンにして Enter で保存します。保存したサーバーを選ぶと専用ウィンドウで開きます。 3. そのサーバーでサインインします。名前やアドレスは **設定 → サーバー** の **サーバーを編集** で変更できます。 保存したサーバーは **参照** に表示され、選ぶと再び開きます。**設定 → サーバー** では、サーバーを開く、編集する(**サーバーを編集**:名前、アドレス、証明書の検証)、削除する(**保存したサーバーを削除**)ことができます。ブックマークは、この CodeNomad 設定に属し、リモートサーバーのプロジェクトに属するわけではありません。URL の保存はサーバーの起動やアクセス許可を行いません。**保存したサーバーを削除** はブックマークを削除しますが、リモートの会話、バックエンド、認証情報は削除しません。 @@ -99,7 +99,7 @@ HTTPS が有効で鍵/証明書のペアを指定していない場合、CodeN デスクトップアプリ(Electron、または Windows の Tauri)では、保存済みサーバーのプロジェクトを、ローカルプロジェクトと並べてこのウィンドウのタブで開くこともできます。 -1. ホームページまたは **タブを開く** ランチャーで **参照** を開いてサーバーを選ぶか、アドレスまたはペアリングリンクを **サーバーのアドレスまたはリンク** に貼り付けます。 +1. ホーム、空のタブ、**タブを開く** ランチャーで **参照** を開き、保存済みサーバーを選びます。先に追加する場合は **サーバーのアドレスまたはリンク** を使い、新しい行をクリックします。 2. タブ内でフォルダーを選びます。タブにはサーバーアイコンとプロジェクト名が表示され、プロジェクトは **最近** に加わります。そこで選ぶと、そのサーバーとフォルダーが直接開き直されます。 タブにはそのプロジェクトだけが表示され、会話、ファイル、Git、設定、Missions はリモートサーバーで動作します。タブはそのサーバーのリモートウィンドウと同じストレージを使うため、既存のサインインやペアリング済みデバイスがそのまま使われ、CodeNomad がタブを復元するとリモートタブも戻ります。このモードを持たないサーバーは、タブに完全なインターフェースを表示します。TLS 検証を省略するサーバーと、macOS・Linux の Tauri ビルドでは、引き続きリモートウィンドウが開きます。タブ内のページは通知を表示できますが、このコンピューターへのその他のアクセスはなく、自分のサーバーから離れません。Web クライアントと Remote Control デバイスにはリモートタブはありません。**設定 → サーバー** の **保存したサーバーを削除** は、そのタブも閉じます。プロジェクトを選ぶ前のタブにはサーバー名が表示されます。タブ内のサーバーのページでサインインしてください。CodeNomad は次回以降の起動でもそのサインインを再利用します。 diff --git a/docs/help/ja/remote-control.md b/docs/help/ja/remote-control.md index f54f6002f5..14798f24fc 100644 --- a/docs/help/ja/remote-control.md +++ b/docs/help/ja/remote-control.md @@ -11,7 +11,7 @@ リンクの有効期間は **5 分**、成功するのは **1 回** です。利用した人はペアリング済み端末になれるため、認証情報として扱ってください。コードはクエリ文字列ではなく URL フラグメントに入ります。**新しいペアリングリンクを作成** は、直前の未使用リンクを即座に無効化します。停止、バックエンドの終了、トンネル障害は、未使用のペアリングリンクをキャンセルします。 -別のデスクトップ CodeNomad をペアリングするには、そのホームページで **参照** を開き、リンクを **サーバーのアドレスまたはリンク** に貼り付けます。サーバーが開いてペアリングされます。ブックマークにはトンネルのオリジンのみを保存し、コードは保持しません。ペアリングリンクでは TLS 検証を有効のまま維持します。 +別のデスクトップ CodeNomad をペアリングするには、ホームまたは空のタブで **参照** を開き、リンクを **サーバーのアドレスまたはリンク** に貼り付けます。これでサーバーだけが追加されます。保存した行をクリックすると開いてペアリングされます。使い捨てリンクは開くか再読み込みするまでこのウィンドウのメモリー内で待機します。有効期間の5分以内に使ってください。ブックマークにはトンネルのオリジンのみを保存します。ペアリングリンクでは TLS 検証を有効のまま維持します。 ## ペアリング済み端末を管理する {#paired-devices} diff --git a/docs/help/ne/projects.md b/docs/help/ne/projects.md index 0645f83b3d..530ae7b8a0 100644 --- a/docs/help/ne/projects.md +++ b/docs/help/ne/projects.md @@ -4,7 +4,7 @@ ## परियोजना खोल्नुहोस् {#open-project} -1. खोजमा focus भएको खाली **नयाँ ट्याब** खोल्न **नयाँ उदाहरण** (`+`) क्लिक गर्नुहोस्। **हालका** र **ब्राउज गर्नुहोस्** प्रविष्टिको संख्यासहित सँगसँगै र साँघुरो झ्यालमा तलमाथि देखिन्छन्। परियोजना, सर्भर वा SideCar छान्दा यही ट्याब उही स्थानमा भरिन्छ। खाली ट्याब बन्द गर्दा परियोजना बाँकी रहँदैन र झ्याल पुनः लोड हुँदासम्म मात्र रहन्छ। शीर्षक वा ट्याब पट्टीको CodeNomad लोगोले गृह पृष्ठ खोल्छ; मुटु भएको **प्रायोजन** बटनले [CodeNomad लाई सहयोग](sponsor.md) खोल्छ। +1. **नयाँ उदाहरण** (`+`) ले खोजमा focus भएको खाली **नयाँ ट्याब** खोल्छ। यसमा गृह पृष्ठकै पृष्ठभूमि, बीचमा CodeNomad लोगो र नाम तथा ठूला **Git Repo क्लोन गर्नुहोस्**, **नयाँ अस्थायी ट्याब** र **नयाँ SideCar** बटन हुन्छन्। **हालका | ब्राउज गर्नुहोस्** चयनकर्ताले प्रविष्टि संख्या देखाउँछ; खोज त्यसको तल **हालका** भित्र हुन्छ। परियोजना, बचत गरिएको सर्भर वा SideCar छान्दा ट्याब उही स्थानमा भरिन्छ। खाली ट्याब पुनः लोड हुँदासम्म रहन्छ र बन्द गर्दा परियोजना बाँकी रहँदैन। शीर्षक वा ट्याब पट्टीको CodeNomad लोगोले सेटिङ, भाषा र मुटु भएको **प्रायोजन** बटनसहित गृह पृष्ठ खोल्छ ([CodeNomad लाई सहयोग](sponsor.md))। 2. **हालका** मा परियोजना छान्नुहोस्; वा **ब्राउज गर्नुहोस्** खोलेर **यो कम्प्युटर** छान्नुहोस्, अनि backend फोल्डर चयन गरी खोल्नुहोस्। **ब्राउज गर्नुहोस्** ले बचत गरिएका CodeNomad सर्भरहरू ([रिमोट परियोजना ट्याबहरू](remote-access.md#remote-project-tabs)) र SideCar हरू ([SideCars](browser-sidecars.md#register-sidecar)) पनि देखाउँछ। 3. रिपोजिटरी प्रतिलिपिका लागि **Git Repo क्लोन गर्नुहोस्** रोजी **रिपोजिटरी URL** र **गन्तव्य फोल्डर** भर्नुहोस्, अनि **क्लोन गर्नुहोस्**। **गन्तव्य फोल्डर** मा तपाईंको पछिल्लो क्लोन भएको फोल्डरभित्र (नभए सबैभन्दा हालको प्रोजेक्टको छेउमा) रिपोजिटरीको नाम पहिल्यै भरिन्छ। **ब्राउज गर्नुहोस्** ले क्लोन राख्ने फोल्डर छान्छ; क्लोनको फोल्डर नामसहित path आफैँ पनि बदल्न सकिन्छ। diff --git a/docs/help/ne/remote-access.md b/docs/help/ne/remote-access.md index b347ccf796..43dadf18a9 100644 --- a/docs/help/ne/remote-access.md +++ b/docs/help/ne/remote-access.md @@ -83,8 +83,8 @@ certificate चेतावनी आए रोकिएर hostname, SAN, trust ## remote server बचत {#saved-servers} -1. desktop गृह पृष्ठमा वा **ट्याब खोल्नुहोस्** लन्चरमा **ब्राउज गर्नुहोस्** खोल्नुहोस्, सर्भरको ठेगाना वा pairing link **सर्भरको ठेगाना वा लिङ्क** मा टाँस्नुहोस् र Enter थिच्नुहोस्: सर्भर आफ्नो host name मा बचत भई खुल्छ। **सेटिङहरू → सर्भरहरू** मा पनि यही फिल्ड छ। -2. विश्वसनीय HTTPS origin प्रयोग गर्नुहोस्। यसको प्रमाणपत्र जाँचमा असफल भए फिल्डमुनि त्रुटि र **TLS प्रमाणीकरण छोड्नुहोस्** देखिन्छ: विश्वसनीय सर्भरका लागि मात्र यसलाई चिन्ह लगाएर फेरि Enter थिच्नुहोस्; त्यो सर्भर आफ्नै विन्डोमा खुल्छ। +1. गृह पृष्ठ, खाली ट्याब वा **ट्याब खोल्नुहोस्** लन्चरमा **ब्राउज गर्नुहोस्** खोली ठेगाना वा pairing link **सर्भरको ठेगाना वा लिङ्क** मा राख्नुहोस्। टाँस्दा तुरुन्त थपिन्छ; टाइप गरेको पाठ Enter ले थप्छ। सर्भर host name मा बचत मात्र हुन्छ र यसको पङ्क्तिमा focus जान्छ; लन्चर खुलै रहन्छ। खोल्न पङ्क्ति क्लिक गर्नुहोस्। **सेटिङहरू → सर्भरहरू** मा पनि यही फिल्ड छ। +2. विश्वसनीय HTTPS origin प्रयोग गर्नुहोस्। प्रमाणपत्र जाँच असफल भए फिल्डमुनि **TLS प्रमाणीकरण छोड्नुहोस्** देखिन्छ: विश्वसनीय सर्भरका लागि मात्र चिन्ह लगाई बचत गर्न फेरि Enter थिच्नुहोस्। यो बचत गरिएको सर्भर छान्दा आफ्नै विन्डोमा खुल्छ। 3. त्यो सर्भरमा sign in गर्नुहोस्। यसको नाम वा ठेगाना **सेटिङहरू → सर्भरहरू** मा **सर्भर सम्पादन गर्नुहोस्** बाट बदल्नुहोस्। बचत गरिएका सर्भरहरू **ब्राउज गर्नुहोस्** मा देखिन्छन्: फेरि खोल्न एउटा छान्नुहोस्। **सेटिङहरू → सर्भरहरू** मा तिनलाई खोल्न, सम्पादन गर्न (**सर्भर सम्पादन गर्नुहोस्**: नाम, ठेगाना, प्रमाणपत्र जाँच) र हटाउन (**बचत गरिएको सर्भर हटाउनुहोस्**) सकिन्छ। bookmark यो CodeNomad कन्फिगरेसनका हुन्, remote server का project होइनन्। URL बचतले server सुरु वा access प्रदान गर्दैन। **बचत गरिएको सर्भर हटाउनुहोस्** ले bookmark हटाउँछ, remote कुराकानी, backend वा credential होइन। @@ -99,7 +99,7 @@ Remote Control मा **सर्भरको ठेगाना वा लि डेस्कटप एपमा (Electron, वा Windows मा Tauri), बचत गरिएको सर्भरले आफ्नो कुनै परियोजना यो सञ्झ्यालको ट्याबमा, तपाईंका स्थानीय परियोजनाहरूसँगै, खोल्न पनि सक्छ: -1. गृह पृष्ठमा वा **ट्याब खोल्नुहोस्** लन्चरमा **ब्राउज गर्नुहोस्** खोलेर सर्भर छान्नुहोस्, वा ठेगाना वा pairing link **सर्भरको ठेगाना वा लिङ्क** मा टाँस्नुहोस्। +1. गृह पृष्ठ, खाली ट्याब वा **ट्याब खोल्नुहोस्** लन्चरमा **ब्राउज गर्नुहोस्** खोली बचत गरिएको सर्भर छान्नुहोस्। पहिले थप्न **सर्भरको ठेगाना वा लिङ्क** प्रयोग गरी नयाँ पङ्क्ति क्लिक गर्नुहोस्। 2. ट्याबमा फोल्डर छान्नुहोस्। त्यसपछि ट्याबले सर्भर आइकन र परियोजनाको नाम देखाउँछ, र परियोजना **हालका** मा थपिन्छ: त्यहाँ छान्दा त्यही सर्भर र फोल्डर सिधै फेरि खुल्छ। ट्याबले त्यही परियोजना मात्र देखाउँछ; यसका कुराकानी, फाइल, Git, सेटिङ र Missions रिमोट सर्भरमा चल्छन्। यसले सर्भरको रिमोट सञ्झ्यालकै भण्डारण प्रयोग गर्छ, त्यसैले भइरहेको साइन-इन वा पेयर गरिएको उपकरण फेरि प्रयोग हुन्छ, र CodeNomad ले तपाईंका ट्याब पुनर्स्थापना गर्दा रिमोट ट्याबहरू पनि फर्कन्छन्। यो मोड नभएको सर्भरले ट्याबमा आफ्नो पूर्ण इन्टरफेस देखाउँछ। TLS प्रमाणीकरण छोड्ने सर्भरहरू, र macOS तथा Linux मा Tauri बिल्डले, रिमोट सञ्झ्याल नै खोलिरहन्छन्। ट्याबको पृष्ठले सूचना देखाउन सक्छ, तर यो कम्प्युटरमा अरू पहुँच हुँदैन र यो आफ्नै सर्भरमा रहन्छ। वेब क्लाइन्ट र Remote Control उपकरणहरूमा रिमोट ट्याब हुँदैन। **सेटिङहरू → सर्भरहरू** मा रहेको **बचत गरिएको सर्भर हटाउनुहोस्** ले यसका ट्याबहरू पनि बन्द गर्छ। परियोजना छान्नुअघि ट्याबले सर्भरको नाम देखाउँछ। ट्याबभित्र सर्भरकै पृष्ठमा sign in गर्नुहोस्; CodeNomad ले पछिका सुरुवातहरूमा त्यही sign-in फेरि प्रयोग गर्छ। diff --git a/docs/help/ne/remote-control.md b/docs/help/ne/remote-control.md index e31dda2819..7af2dc1853 100644 --- a/docs/help/ne/remote-control.md +++ b/docs/help/ne/remote-control.md @@ -11,7 +11,7 @@ Remote Control ले paired browser वा desktop client लाई inbound net link **पाँच मिनेट** मान्य हुन्छ र **एकपटक** सफल हुन्छ। credential झैं लिनुहोस्: प्रयोग गर्ने जोकोही paired device बन्न सक्छ। code URL fragment मा हुन्छ, query string मा होइन। **नयाँ जोडी लिंक बनाउनुहोस्** ले अघिल्लो unused link तुरुन्त अमान्य गर्छ। Stop, backend shutdown र tunnel failure ले बाँकी pairing link रद्द गर्छन्। -अर्को desktop CodeNomad pair गर्न त्यसको गृह पृष्ठमा **ब्राउज गर्नुहोस्** खोली link **सर्भरको ठेगाना वा लिङ्क** मा टाँस्नुहोस्: सर्भर खुल्छ र pair हुन्छ। bookmark मा tunnel origin मात्र बचत हुन्छ; code रहँदैन। pairing link मा TLS verification enabled रहन्छ। +अर्को desktop CodeNomad pair गर्न गृह पृष्ठ वा खाली ट्याबमा **ब्राउज गर्नुहोस्** खोली link **सर्भरको ठेगाना वा लिङ्क** मा टाँस्नुहोस्। यसले सर्भर मात्र थप्छ; खोल्न र pair गर्न बचत गरिएको पङ्क्ति क्लिक गर्नुहोस्। एकपटक प्रयोग हुने link खोल्दासम्म वा पुनः लोड हुँदासम्म यस झ्यालको मेमोरीमा पर्खन्छ; पाँच मिनेटको वैधताभित्र प्रयोग गर्नुहोस्। bookmark मा tunnel origin मात्र बचत हुन्छ। pairing link मा TLS verification enabled रहन्छ। ## paired device व्यवस्थापन {#paired-devices} diff --git a/docs/help/ru/projects.md b/docs/help/ru/projects.md index a81600b2df..7c3a3fbb2f 100644 --- a/docs/help/ru/projects.md +++ b/docs/help/ru/projects.md @@ -4,7 +4,7 @@ ## Открытие проекта {#open-project} -1. Нажмите **Новый экземпляр** (`+`), чтобы открыть пустую **Новую вкладку** с фокусом в поиске. **Недавние** и **Обзор** отображаются рядом, а в узком окне — друг под другом, с числом элементов. Выбор проекта, сервера или SideCar заполняет эту вкладку на её месте. Пустая вкладка закрывается без оставшегося проекта и существует до перезагрузки окна. Логотип CodeNomad в заголовке или панели вкладок открывает главную страницу; кнопка **Спонсировать** с сердцем открывает [Поддержать CodeNomad](sponsor.md). +1. **Новый экземпляр** (`+`) открывает пустую **Новую вкладку** с фокусом в поиске. Она использует фон главной страницы, логотип и имя CodeNomad по центру и большие кнопки **Клонировать Git-репозиторий**, **Новая временная вкладка**, **Новый SideCar**. Переключатель **Недавние | Обзор** показывает число элементов; поиск расположен под ним в **Недавние**. Выбор проекта, сохранённого сервера или SideCar заполняет вкладку на её месте. Пустая вкладка существует до перезагрузки и закрывается без оставшегося проекта. Логотип CodeNomad в заголовке или панели вкладок открывает главную страницу с настройками, языком и кнопкой с сердцем **Спонсировать** ([Поддержать CodeNomad](sponsor.md)). 2. В **Недавние** выберите проект; или откройте **Обзор**, выберите **Этот компьютер**, затем укажите папку на бэкенде и откройте её. **Обзор** также показывает сохранённые серверы CodeNomad ([вкладки удалённых проектов](remote-access.md#remote-project-tabs)) и SideCar ([SideCar](browser-sidecars.md#register-sidecar)). 3. Для копирования репозитория выберите **Клонировать Git-репозиторий**, заполните **URL репозитория** и **Папка назначения**, затем нажмите **Клонировать**. **Папка назначения** заполняется заранее: папка с именем репозитория в папке, где лежит последний клон, а без него — рядом с последним проектом. **Обзор** выбирает папку, в которой будет клон; путь, включая имя папки клона, можно изменить и вручную. diff --git a/docs/help/ru/remote-access.md b/docs/help/ru/remote-access.md index c46405e9f3..9c22b89a6c 100644 --- a/docs/help/ru/remote-access.md +++ b/docs/help/ru/remote-access.md @@ -83,8 +83,8 @@ codenomad --host 127.0.0.1 --https=false --http=true ## Сохранение удалённого сервера {#saved-servers} -1. На главной странице настольного приложения или в панели запуска **Открыть вкладку** откройте **Обзор**, вставьте адрес сервера или ссылку сопряжения в поле **Адрес или ссылка сервера** и нажмите Enter: сервер сохранится под именем хоста и откроется. В **Настройки → Серверы** есть то же поле. -2. Используйте доверенный HTTPS-источник. Если его сертификат не прошёл проверку, под полем появится ошибка и **Пропустить проверку TLS**: включайте это только для доверенного сервера и снова нажмите Enter; такой сервер открывается в отдельном окне. +1. На главной странице, пустой вкладке или в панели **Открыть вкладку** откройте **Обзор** и введите адрес или ссылку сопряжения в **Адрес или ссылка сервера**. Вставка добавляет сразу, Enter подтверждает набранный текст. Сервер только сохраняется под именем хоста, фокус переходит на его строку; панель остаётся открытой. Нажмите на строку для открытия. В **Настройки → Серверы** есть то же поле. +2. Используйте доверенный HTTPS-источник. Если сертификат не прошёл проверку, под полем появится **Пропустить проверку TLS**: включайте это только для доверенного сервера и снова нажмите Enter для сохранения. Выбор этого сохранённого сервера открывает отдельное окно. 3. Войдите на этом сервере. Переименуйте его или измените адрес через **Изменить сервер** в **Настройки → Серверы**. Сохранённые серверы перечислены в **Обзор**: выберите сервер, чтобы снова открыть его. В **Настройки → Серверы** их можно открыть, изменить (**Изменить сервер**: имя, адрес, проверка сертификата) и удалить (**Удалить сохраненный сервер**). Закладки принадлежат этой конфигурации CodeNomad, не проектам удалённого сервера. Сохранение URL не запускает сервер и не предоставляет доступ. **Удалить сохраненный сервер** удаляет закладку, не удалённые разговоры, серверную часть или её учётные данные. @@ -99,7 +99,7 @@ codenomad --host 127.0.0.1 --https=false --http=true В настольном приложении (Electron или Tauri в Windows) сохранённый сервер может также открыть один из своих проектов во вкладке этого окна, рядом с локальными проектами: -1. На главной странице или в панели запуска **Открыть вкладку** откройте **Обзор** и выберите сервер или вставьте адрес или ссылку сопряжения в поле **Адрес или ссылка сервера**. +1. На главной странице, пустой вкладке или в панели **Открыть вкладку** откройте **Обзор** и выберите сохранённый сервер. Для добавления используйте **Адрес или ссылка сервера**, затем нажмите на новую строку. 2. Выберите папку во вкладке. Вкладка покажет значок сервера и имя проекта, а проект появится в **Недавние**: выбор там сразу снова открывает этот сервер и папку. Вкладка показывает только этот проект; его беседы, файлы, Git, настройки и Missions работают на удалённом сервере. Она использует хранилище удалённого окна сервера, поэтому существующий вход или сопряжённое устройство используются повторно, а удалённые вкладки возвращаются, когда CodeNomad восстанавливает вкладки. Сервер без этого режима показывает во вкладке свой полный интерфейс. Серверы, пропускающие проверку TLS, и сборка Tauri в macOS и Linux по-прежнему открывают удалённое окно. Страница во вкладке может показывать уведомления, но не имеет другого доступа к этому компьютеру и остаётся на своём сервере. У веб-клиентов и устройств Remote Control удалённых вкладок нет. **Удалить сохраненный сервер** в **Настройки → Серверы** также закрывает его вкладки. Пока проект не выбран, вкладка показывает имя сервера. Входите на странице сервера в самой вкладке; CodeNomad повторно использует этот вход при следующих запусках. diff --git a/docs/help/ru/remote-control.md b/docs/help/ru/remote-control.md index dba21d9e13..61dcb732bf 100644 --- a/docs/help/ru/remote-control.md +++ b/docs/help/ru/remote-control.md @@ -11,7 +11,7 @@ Ссылка действует **пять минут** и срабатывает **один раз**. Считайте её учётными данными: любой использовавший её может стать сопряжённым устройством. Код находится во фрагменте URL, не в строке запроса. **Создать новую ссылку сопряжения** немедленно делает предыдущую неиспользованную ссылку недействительной. Остановка, завершение серверной части и сбой туннеля отменяют ожидающие ссылки сопряжения. -Для сопряжения другого настольного CodeNomad откройте **Обзор** на его главной странице и вставьте ссылку в поле **Адрес или ссылка сервера**: сервер откроется и будет сопряжён. В закладке сохраняется только origin туннеля; код не хранится. Проверка TLS для ссылок сопряжения остаётся включённой. +Для сопряжения другого настольного CodeNomad откройте **Обзор** на главной странице или пустой вкладке и вставьте ссылку в **Адрес или ссылка сервера**. Это только добавляет сервер; нажмите на сохранённую строку для открытия и сопряжения. Одноразовая ссылка ждёт в памяти этого окна до открытия или перезагрузки; используйте её в течение пяти минут действия. В закладке сохраняется только origin туннеля. Проверка TLS для ссылок сопряжения остаётся включённой. ## Управление сопряжёнными устройствами {#paired-devices} diff --git a/docs/help/tr/projects.md b/docs/help/tr/projects.md index 1ecdb9cc60..7570ee3202 100644 --- a/docs/help/tr/projects.md +++ b/docs/help/tr/projects.md @@ -4,7 +4,7 @@ Bir proje sekmesi CodeNomad'i arka uç bilgisayarındaki bir klasöre bağlar. S ## Bir proje açın {#open-project} -1. Arama alanına odaklanan boş bir **Yeni sekme** açmak için **Yeni instance** (`+`) öğesine tıklayın. **Son kullanılanlar** ve **Gözat**, öğe sayılarıyla yan yana, dar pencerede alt alta görünür. Proje, sunucu veya SideCar seçimi bu sekmeyi yerinde doldurur. Boş sekme proje bırakmadan kapanır ve pencere yeniden yüklenene kadar yaşar. Başlık veya sekme çubuğundaki CodeNomad logosu ana sayfayı açar; kalpli **Sponsor** düğmesi [CodeNomad'i destekleyin](sponsor.md) sayfasını açar. +1. **Yeni instance** (`+`), aramaya odaklanan boş bir **Yeni sekme** açar. Ana sayfanın arka planını, ortalanmış CodeNomad logosu ve adını, büyük **Git Deposunu Klonla**, **Yeni geçici sekme** ve **Yeni SideCar** düğmelerini kullanır. **Son kullanılanlar | Gözat** seçicisi öğe sayılarını gösterir; arama, seçicinin altında **Son kullanılanlar** içindedir. Proje, kayıtlı sunucu veya SideCar seçimi sekmeyi yerinde doldurur. Boş sekme yeniden yüklemeye kadar yaşar ve proje bırakmadan kapanır. Başlık veya sekme çubuğundaki CodeNomad logosu ayarlar, dil ve kalpli **Sponsor** düğmesini içeren ana sayfayı açar ([CodeNomad'i destekleyin](sponsor.md)). 2. **Son kullanılanlar** içinde bir proje seçin; ya da **Gözat** bölümünü açıp **Bu bilgisayar** seçin, ardından arka uç klasörünü seçip açın. **Gözat** kayıtlı CodeNomad sunucularını ([uzak proje sekmeleri](remote-access.md#remote-project-tabs)) ve SideCar'ları ([SideCar'lar](browser-sidecars.md#register-sidecar)) da listeler. 3. Depoyu kopyalamak için **Git Deposunu Klonla** eylemini seçin; **Depo URL'si** ve **Hedef klasör** alanlarını doldurup **Klonla** eylemini seçin. **Hedef klasör**, son klonunuzun bulunduğu klasörde (yoksa en son projenizin yanında) depo adıyla önceden doldurulur. **Göz At** klonu içerecek klasörü seçer; klon klasörünün adı dahil yolu elle de düzenleyebilirsiniz. diff --git a/docs/help/tr/remote-access.md b/docs/help/tr/remote-access.md index fb61c4fc89..a1e4be5f0f 100644 --- a/docs/help/tr/remote-access.md +++ b/docs/help/tr/remote-access.md @@ -83,8 +83,8 @@ Bir istemci bir sertifika uyarısı bildirirse, durdurun ve ana bilgisayar adın ## Uzak sunucuyu kaydedin {#saved-servers} -1. Masaüstü ana sayfasında veya **Sekme aç** başlatıcısında **Gözat** bölümünü açın, sunucunun adresini veya bir eşleştirme bağlantısını **Sunucu adresi veya bağlantısı** alanına yapıştırın ve Enter'a basın: sunucu ana bilgisayar adıyla kaydedilir ve açılır. **Ayarlar → Sunucular** de aynı alanı sunar. -2. Güvenilir bir HTTPS kaynağı kullanın. Sertifikası doğrulamayı geçemezse hata, alanın altında **TLS doğrulamasını atla** ile görünür: bunu yalnızca güvendiğiniz bir sunucu için işaretleyin ve yeniden Enter'a basın; bu sunucu kendi penceresinde açılır. +1. Ana sayfada, boş sekmede veya **Sekme aç** başlatıcısında **Gözat** bölümünü açıp adresi ya da eşleştirme bağlantısını **Sunucu adresi veya bağlantısı** alanına girin. Yapıştırma hemen ekler; Enter yazılan metni ekler. Sunucu yalnızca ana bilgisayar adıyla kaydedilir ve satırına odaklanılır; başlatıcı açık kalır. Açmak için bu satıra tıklayın. **Ayarlar → Sunucular** aynı alanı sunar. +2. Güvenilir bir HTTPS kaynağı kullanın. Sertifika doğrulanamazsa alanın altında **TLS doğrulamasını atla** görünür: yalnızca güvendiğiniz sunucu için işaretleyip kaydetmek üzere yeniden Enter'a basın. Kaydedilen bu sunucuyu seçmek kendi penceresini açar. 3. O sunucuda oturum açın. Adını veya adresini **Ayarlar → Sunucular** içindeki **Sunucuyu düzenle** ile değiştirin. Kayıtlı sunucular **Gözat** altında listelenir: yeniden açmak için birini seçin. **Ayarlar → Sunucular** bölümünde sunucuları açabilir, düzenleyebilir (**Sunucuyu düzenle**: ad, adres, sertifika doğrulaması) ve kaldırabilirsiniz (**Kayıtlı sunucuyu kaldır**). Yer imleri uzak sunucunun projelerine değil, bu CodeNomad yapılandırmasına aittir. Bir URL'nin kaydedilmesi sunucuyu başlatmaz veya erişim sağlamaz. **Kayıtlı sunucuyu kaldır**, uzak konuşmaları, arka ucu veya kimlik bilgilerini değil, yer işaretini kaldırır. @@ -99,7 +99,7 @@ Uzaktan Kontrol için bunun yerine **Sunucu adresi veya bağlantısı** öğesin Masaüstü uygulamasında (Electron veya Windows'ta Tauri), kayıtlı bir sunucu projelerinden birini yerel projelerinizin yanında bu pencerenin bir sekmesinde de açabilir: -1. Ana sayfada veya **Sekme aç** başlatıcısında **Gözat** bölümünü açıp bir sunucu seçin ya da bir adresi veya eşleştirme bağlantısını **Sunucu adresi veya bağlantısı** alanına yapıştırın. +1. Ana sayfada, boş sekmede veya **Sekme aç** başlatıcısında **Gözat** bölümünü açıp kayıtlı bir sunucu seçin. Önce eklemek için **Sunucu adresi veya bağlantısı** alanını kullanıp yeni satıra tıklayın. 2. Klasörü sekmede seçin. Sekme ardından sunucu simgesini ve proje adını gösterir ve proje **Son kullanılanlar** listesine eklenir: oradan seçmek o sunucuyu ve klasörü doğrudan yeniden açar. Sekme yalnızca o projeyi gösterir; konuşmaları, dosyaları, Git'i, ayarları ve Missions uzak sunucuda çalışır. Sekme sunucunun uzak penceresiyle aynı depolamayı kullanır; böylece mevcut bir oturum veya eşleştirilmiş cihaz yeniden kullanılır ve CodeNomad sekmelerinizi geri yüklediğinde uzak sekmeler de geri gelir. Bu modu olmayan bir sunucu sekmede tam arayüzünü gösterir. TLS doğrulamasını atlayan sunucular ile macOS ve Linux'taki Tauri sürümü uzak pencere açmaya devam eder. Sekmedeki sayfa bildirim gösterebilir, ancak bu bilgisayara başka erişimi yoktur ve kendi sunucusunda kalır. Web istemcilerinde ve Remote Control cihazlarında uzak sekme yoktur. **Ayarlar → Sunucular** içindeki **Kayıtlı sunucuyu kaldır** sunucunun sekmelerini de kapatır. Proje seçilmeden önce sekme sunucunun adını gösterir. Sekmenin içinde sunucunun sayfasında oturum açın; CodeNomad bu oturumu sonraki açılışlarda yeniden kullanır. diff --git a/docs/help/tr/remote-control.md b/docs/help/tr/remote-control.md index 99996c31d1..4f3446d051 100644 --- a/docs/help/tr/remote-control.md +++ b/docs/help/tr/remote-control.md @@ -11,7 +11,7 @@ Uzaktan Kontrol, eşleştirilmiş bir tarayıcının veya masaüstü istemcisini Bağlantı **beş dakika** süreyle geçerlidir ve **bir kez** başarılı olur. Bunu bir kimlik bilgisi olarak değerlendirin: Bunu tüketen herkes eşleştirilmiş bir cihaz haline gelebilir. Kod, sorgu dizesinde değil, URL parçasında bulunur. **Yeni eşleştirme bağlantısı oluştur**, önceki kullanılmayan bağlantıyı anında geçersiz kılar. Durdurma, arka uç kapatma ve tünel arızası, bekleyen eşleştirme bağlantılarını iptal eder. -Başka masaüstü CodeNomad istemcisini eşleştirmek için onun ana sayfasında **Gözat** bölümünü açın ve bağlantıyı **Sunucu adresi veya bağlantısı** alanına yapıştırın: sunucu açılır ve eşleşir. Yer imi yalnızca tünelin origin adresini saklar; kod saklanmaz. Eşleştirme bağlantılarında TLS doğrulaması etkin kalır. +Başka masaüstü CodeNomad istemcisini eşleştirmek için ana sayfada veya boş sekmede **Gözat** bölümünü açıp bağlantıyı **Sunucu adresi veya bağlantısı** alanına yapıştırın. Bu yalnızca sunucuyu ekler; açıp eşleştirmek için kayıtlı satırına tıklayın. Tek kullanımlık bağlantı, açılana veya yeniden yüklemeye kadar bu pencerenin belleğinde bekler; beş dakikalık geçerlilik süresinde kullanın. Yer imi yalnızca tünelin origin adresini saklar. Eşleştirme bağlantılarında TLS doğrulaması etkin kalır. ## Eşleştirilmiş cihazları yönetin {#paired-devices} diff --git a/docs/help/zh-Hans/projects.md b/docs/help/zh-Hans/projects.md index 21b57c0fdb..a286a8a94e 100644 --- a/docs/help/zh-Hans/projects.md +++ b/docs/help/zh-Hans/projects.md @@ -4,7 +4,7 @@ ## 打开项目 {#open-project} -1. 点击**新建实例**(`+`)打开空白的**新标签页**,焦点位于搜索框。**最近**和**浏览**并排显示,并附有条目数量;窄窗口中上下排列。选择项目、服务器或 SideCar 会在原位置填充此标签页。空白标签页关闭后不留下项目,仅保留到窗口重新加载。点击标题栏或标签栏中的 CodeNomad 标志打开主页;带心形图标的**赞助**按钮打开[支持 CodeNomad](sponsor.md)。 +1. 点击**新建实例**(`+`)打开空白的**新标签页**,焦点位于搜索框。它使用主页的背景、居中的 CodeNomad 标志和名称,以及大号的**克隆 Git 仓库**、**新建临时标签页**和**新建 SideCar**按钮。**最近 | 浏览**选择器附有条目数量,搜索框位于选择器下方的**最近**中。选择项目、已保存的服务器或 SideCar 会在原位置填充此标签页。空白标签页仅保留到重新加载,关闭后不留下项目。标题栏或标签栏中的 CodeNomad 标志打开主页,其中还提供设置、语言和心形**赞助**按钮([支持 CodeNomad](sponsor.md))。 2. 在 **最近** 中选择一个项目;或打开 **浏览**,选择 **此电脑**,然后选择后端文件夹并打开。**浏览** 也列出已保存的 CodeNomad 服务器([远程项目标签页](remote-access.md#remote-project-tabs))和 SideCar([SideCar](browser-sidecars.md#register-sidecar))。 3. 若需仓库副本,选择**克隆 Git 仓库**,输入**仓库 URL** 和**目标文件夹**,然后选择**克隆**。**目标文件夹** 会预填为上次克隆所在文件夹中以仓库名命名的文件夹(没有则为最近项目旁边)。**浏览** 用于选择存放克隆的文件夹;也可以手动编辑路径,包括克隆文件夹的名称。 diff --git a/docs/help/zh-Hans/remote-access.md b/docs/help/zh-Hans/remote-access.md index 3197d0b99d..23a02ace50 100644 --- a/docs/help/zh-Hans/remote-access.md +++ b/docs/help/zh-Hans/remote-access.md @@ -83,8 +83,8 @@ codenomad --host 127.0.0.1 --https=false --http=true ## 保存远程服务器 {#saved-servers} -1. 在桌面主页或 **打开标签页** 启动器中打开 **浏览**,将服务器地址或配对链接粘贴到 **服务器地址或链接** 并按 Enter:服务器以其主机名保存并打开。**设置 → 服务器** 也提供相同的输入框。 -2. 请使用受信任的 HTTPS 源。如果其证书未通过检查,输入框下方会显示错误和 **跳过 TLS 验证**:仅对可信的服务器勾选,然后再次按 Enter;该服务器会在单独的窗口中打开。 +1. 在主页、空白标签页或**打开标签页**启动器中打开**浏览**,在**服务器地址或链接**中输入地址或配对链接。粘贴会立即添加,手动输入后按 Enter 添加。添加仅以主机名保存服务器并将焦点移到其行;启动器保持打开。点击该行才会打开服务器。**设置 → 服务器**也提供相同的输入框。 +2. 请使用受信任的 HTTPS 源。如果证书未通过检查,输入框下方会显示**跳过 TLS 验证**:仅对可信服务器勾选,再按 Enter 保存。选择这个已保存的服务器时,会在单独窗口打开。 3. 在该服务器上登录。可在 **设置 → 服务器** 中通过 **编辑服务器** 重命名或更改其地址。 已保存的服务器列在 **浏览** 中:选择一个即可再次打开。在 **设置 → 服务器** 中可以打开、编辑(**编辑服务器**:名称、地址、证书检查)和移除(**删除已保存服务器**)服务器。书签属于此 CodeNomad 配置,而非远程服务器项目。保存 URL 不会启动服务器或授予访问。**删除已保存服务器**移除书签,而非远程对话、后端或凭据。 @@ -99,7 +99,7 @@ codenomad --host 127.0.0.1 --https=false --http=true 在桌面应用中(Electron,或 Windows 上的 Tauri),已保存的服务器也可以在此窗口的标签页中打开其某个项目,与本地项目并列: -1. 在主页或 **打开标签页** 启动器中打开 **浏览** 并选择一个服务器,或将地址或配对链接粘贴到 **服务器地址或链接** 中。 +1. 在主页、空白标签页或**打开标签页**启动器中打开**浏览**并选择已保存的服务器。若需先添加,使用**服务器地址或链接**,然后点击新增的行。 2. 在标签页中选择文件夹。标签页随后显示服务器图标和项目名称,该项目也会加入 **最近**:在那里选择它会直接重新打开该服务器和文件夹。 标签页只显示该项目;其对话、文件、Git、设置和 Missions 都在远程服务器上运行。它使用该服务器远程窗口的存储,因此会沿用已有的登录或已配对设备;CodeNomad 恢复标签页时,远程标签页也会恢复。没有此模式的服务器会在标签页中显示其完整界面。跳过 TLS 验证的服务器,以及 macOS 和 Linux 上的 Tauri 版本,仍然打开远程窗口。标签页中的页面可以显示通知,但对这台计算机没有其他访问权限,并始终停留在其服务器上。Web 客户端和 Remote Control 设备没有远程标签页。**设置 → 服务器** 中的 **删除已保存服务器** 也会关闭它的标签页。选择项目之前,标签页显示服务器名称。请在标签页中的服务器页面登录;CodeNomad 会在之后的启动中继续使用该登录。 diff --git a/docs/help/zh-Hans/remote-control.md b/docs/help/zh-Hans/remote-control.md index 2d16c24177..20d7589c3f 100644 --- a/docs/help/zh-Hans/remote-control.md +++ b/docs/help/zh-Hans/remote-control.md @@ -11,7 +11,7 @@ 链接有效期为**五分钟**,只能成功使用**一次**。请将其视为凭据:任何消费它的人都能成为配对设备。配对码位于 URL 片段,而非查询字符串。**创建新的配对链接**会立即使上一个未使用链接失效。停止、后端关闭和隧道失败会取消未使用的配对链接。 -要配对另一个桌面 CodeNomad,在其主页打开 **浏览**,将链接粘贴到 **服务器地址或链接** 中:服务器随即打开并完成配对。书签仅保存隧道来源;不保留配对码。配对链接始终启用 TLS 验证。 +要配对另一个桌面 CodeNomad,在主页或空白标签页打开**浏览**,将链接粘贴到**服务器地址或链接**中。此操作仅添加服务器;点击保存的行才会打开并配对。一次性链接在此窗口的内存中等待,直到打开或重新加载;请在五分钟有效期内使用。书签仅保存隧道来源。配对链接始终启用 TLS 验证。 ## 管理配对设备 {#paired-devices} diff --git a/packages/ui/src/App.tsx b/packages/ui/src/App.tsx index c87fa60ba4..b59dc4755b 100644 --- a/packages/ui/src/App.tsx +++ b/packages/ui/src/App.tsx @@ -16,7 +16,6 @@ import InstanceDisconnectedModal from "./components/instance-disconnected-modal" import InstanceShell from "./components/instance/instance-shell2" import { SettingsScreen } from "./components/settings-screen" import { NativeTitlebar, hasNativeTitlebar } from "./components/native-titlebar" -import BlankTabView from "./components/blank-tab-view" import { activeBlankTabId, openBlankTab, closeBlankTab, replaceBlankTab, getInstanceAppTabId } from "./stores/app-tabs" import { SideCarView } from "./components/sidecar-view" import { RemoteProjectView } from "./components/remote-project-view" @@ -870,7 +869,7 @@ const App: Component = () => { ) : tab.kind === "blank" ? (
- void handleSelectFolder(path, tab.id)} onSelectExistingInstance={handleSelectExistingInstance} onNewTemporaryInstance={() => void handleNewTemporaryInstance(tab.id)} />
diff --git a/packages/ui/src/components/blank-tab-view.tsx b/packages/ui/src/components/blank-tab-view.tsx deleted file mode 100644 index 4221e621c5..0000000000 --- a/packages/ui/src/components/blank-tab-view.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import { useI18n } from "../lib/i18n" -import { launchableRecents } from "../stores/remote-project-open" -import { createNewInstanceDialogs } from "./new-instance-dialogs" -import BrowseMenu, { browseEntryCount } from "./browse-menu" -import RecentTabsMenu from "./recent-tabs-menu" -import NewTabActions from "./new-tab-actions" -import EntryCount from "./entry-count" - -/** A new browser-like tab: choices use the ordinary open flows and replace this empty tab on success. */ -export default function BlankTabView(props: { - active: boolean - isLoading: boolean - onSelectFolder: (path: string) => void - onSelectExistingInstance: (id: string, path: string) => void - onNewTemporaryInstance: () => void -}) { - const { t } = useI18n() - const dialogs = createNewInstanceDialogs({ - defaultPath: () => launchableRecents().find((entry) => !entry.remote && !entry.sidecar)?.path, - isLoading: () => props.isLoading, - onSelectFolder: props.onSelectFolder, - }) - return ( -
-
-
- -
-
-

{t("folderSelection.browseMenu.title")}

-
- void dialogs.browse()} /> -
-
-
- -
- ) -} diff --git a/packages/ui/src/components/browse-menu.tsx b/packages/ui/src/components/browse-menu.tsx index 887598cbeb..f3889afbcb 100644 --- a/packages/ui/src/components/browse-menu.tsx +++ b/packages/ui/src/components/browse-menu.tsx @@ -31,7 +31,7 @@ export const browseEntryCount = () => 1 + (canOpenRemoteWindows() ? savedServers * Browse, shared by the home page (a tab) and the new-instance launcher (a * folded section): this computer's folders, each saved CodeNomad server, whose * project tab picks the folder, each configured SideCar, then the field that - * adds a server and opens it. + * adds a server to the list. * Only host windows (never a web client, a Remote Control device or a remote * page) list or add servers. */ @@ -124,9 +124,9 @@ export default function BrowseMenu(props: BrowseMenuProps) { )} - {/* Adding a server opens it at once (its tab, else its window); the launcher closes then. */} - props.onRun?.()} /> + queueMicrotask(() => bodyRef?.querySelector(`[data-remote-server="${CSS.escape(id)}"]`)?.focus())} />
diff --git a/packages/ui/src/components/folder-selection-view.tsx b/packages/ui/src/components/folder-selection-view.tsx index e8c3acaaa8..c5e4357a8e 100644 --- a/packages/ui/src/components/folder-selection-view.tsx +++ b/packages/ui/src/components/folder-selection-view.tsx @@ -1,4 +1,4 @@ -import { Component, createMemo, createSignal, Show, For, onMount, onCleanup, createEffect } from "solid-js" +import { Component, createMemo, createSignal, createUniqueId, Show, For, onMount, onCleanup, createEffect, on } from "solid-js" import { Clock, Trash2, FolderPlus, Settings, ChevronRight, MonitorUp, Star, X, Pencil, Search } from "lucide-solid" import { removeRemoteProjectRecent, removeSideCarRecent, useConfig } from "../stores/preferences" import { launchableRecents, openRemoteProject } from "../stores/remote-project-open" @@ -39,11 +39,16 @@ interface FolderSelectionViewProps { onNewTemporaryInstance?: () => void isLoading?: boolean onClose?: () => void + blank?: boolean + active?: boolean } const FolderSelectionView: Component = (props) => { const { removeRecentFolder } = useConfig() const { t, locale } = useI18n() + const viewId = createUniqueId() + const tabId = (tab: string) => `folder-home-tab-${viewId}-${tab}` + const panelId = (tab: string) => `folder-home-panel-${viewId}-${tab}` onMount(() => void ensureSidecarsLoaded()) const [selectedIndex, setSelectedIndex] = createSignal(0) const [hoveredRecentActionPath, setHoveredRecentActionPath] = createSignal(null) @@ -57,6 +62,12 @@ const FolderSelectionView: Component = (props) => { let homeRootRef: HTMLDivElement | undefined let actionsColumnRef: HTMLDivElement | undefined let recentListRef: HTMLDivElement | undefined + let searchRef: HTMLInputElement | undefined + createEffect(on(() => props.blank && props.active !== false, (active) => { + if (!active) return + setHomeTab("recent") + requestAnimationFrame(() => { if (props.active !== false) searchRef?.focus() }) + })) // This computer's folders, the remote projects this window reopens and SideCars, newest first. const allRecents = () => launchableRecents() @@ -85,7 +96,7 @@ const FolderSelectionView: Component = (props) => { function handleKeyDown(e: KeyboardEvent) { - if (e.defaultPrevented || e.isComposing || isHotkeyRecording()) return + if (props.active === false || e.defaultPrevented || e.isComposing || isHotkeyRecording()) return let activeElement: HTMLElement | null = null if (typeof document !== "undefined") { activeElement = document.activeElement as HTMLElement | null @@ -214,7 +225,7 @@ const FolderSelectionView: Component = (props) => { }) function dropTargetBlocked() { - return isLoading() || dialogs.isFolderBrowserOpen() || settingsOpen() + return props.active === false || isLoading() || dialogs.isFolderBrowserOpen() || settingsOpen() } function showInvalidFolderDropAlert() { @@ -348,6 +359,7 @@ const FolderSelectionView: Component = (props) => { <>
(homeRootRef = el)} onDragEnter={folderDrop.bind.onDragEnter} onDragOver={folderDrop.bind.onDragOver} @@ -358,6 +370,7 @@ const FolderSelectionView: Component = (props) => { class="folder-home-shell w-full max-w-5xl px-4 sm:px-8 pb-2 flex flex-col" aria-busy={isLoading() ? "true" : "false"} > +
@@ -392,11 +405,13 @@ const FolderSelectionView: Component = (props) => {
+
@@ -465,10 +481,10 @@ const FolderSelectionView: Component = (props) => { type="button" role="tab" aria-label={t(tab === "recent" ? "newInstanceLauncher.recentTitle" : "folderSelection.browseMenu.title")} - id={`folder-home-tab-${tab}`} + id={tabId(tab)} data-home-tab={tab} aria-selected={homeTab() === tab} - aria-controls={`folder-home-panel-${tab}`} + aria-controls={panelId(tab)} tabIndex={homeTab() === tab ? 0 : -1} class="px-4 py-3 text-left transition-colors" classList={{ "border-r border-base": tab === "recent" }} @@ -487,18 +503,19 @@ const FolderSelectionView: Component = (props) => {
-
+
void handleBrowse()} />
-
- 0}> +
+ 0}> +
+
diff --git a/packages/ui/src/components/server-add-field.tsx b/packages/ui/src/components/server-add-field.tsx index 7139ececf9..dee364a5d8 100644 --- a/packages/ui/src/components/server-add-field.tsx +++ b/packages/ui/src/components/server-add-field.tsx @@ -6,10 +6,8 @@ import { RemoteServerProbeError, useRemoteServerProfiles } from "../lib/hooks/us interface ServerAddFieldProps { disabled?: boolean - /** Opens the server once saved (its tab, else its window); Settings only saves it. A pairing link always opens. */ - open?: boolean - /** Called once the server is saved, e.g. to dismiss the launcher. */ - onAdded?: () => void + /** Called with the saved row's ID, e.g. to focus it in Browse. */ + onAdded?: (id: string) => void /** Marks the field as a Browse row for its arrow-key navigation. */ navAttribute?: string } @@ -18,7 +16,7 @@ const carriesCredentials = (value: string) => /^[a-z][a-z\d+.-]*:\/\/[^/?#]*@/i. /** * Adds a CodeNomad server from a pasted address or Remote Control pairing link, - * inline: the server is saved under its host name and opens at once. Only a + * inline: the server is saved under its host name. Only a * certificate that fails the check offers skipping it, confirmed through the * same field. */ @@ -57,9 +55,9 @@ export default function ServerAddField(props: ServerAddFieldProps) { } setBusy(true) try { - await submitServer(input, props.open ?? true) + const profile = await submitServer(input, false) reset() - props.onAdded?.() + props.onAdded?.(profile.id) } catch (failure) { setError(failure instanceof Error && failure.message ? failure.message : t("folderSelection.servers.dialog.errorConnect")) const tls = failure instanceof RemoteServerProbeError && failure.code === "tls_error" && link.kind === "address" diff --git a/packages/ui/src/components/settings/servers-settings-section.tsx b/packages/ui/src/components/settings/servers-settings-section.tsx index 00ee77dab9..bcf175d5a8 100644 --- a/packages/ui/src/components/settings/servers-settings-section.tsx +++ b/packages/ui/src/components/settings/servers-settings-section.tsx @@ -41,7 +41,7 @@ export const ServersSettingsSection: Component = () => {
{/* Adding saves the server, like Browse's field, without opening it here. */} - + 0} fallback={
{t("folderSelection.servers.empty.title")}
}> {(server) => ( diff --git a/packages/ui/src/lib/hooks/use-remote-server-profiles.ts b/packages/ui/src/lib/hooks/use-remote-server-profiles.ts index f7238d111b..6211028012 100644 --- a/packages/ui/src/lib/hooks/use-remote-server-profiles.ts +++ b/packages/ui/src/lib/hooks/use-remote-server-profiles.ts @@ -19,6 +19,9 @@ export type RemoteServerInput = { skipTlsVerify: boolean } +// Pairing links wait in this renderer until the user opens the saved server. +const pendingPairingEntries = new Map() + /** A failed probe, with the server's reason code (`tls_error` for a certificate that failed the check). */ export class RemoteServerProbeError extends Error { constructor(message: string, readonly code?: string) { @@ -62,18 +65,19 @@ export function useRemoteServerProfiles() { baseUrl: probe.normalizedUrl, skipTlsVerify, }) + if (saved && saved.baseUrl !== profile.baseUrl) pendingPairingEntries.delete(profile.id) return { profile, entryUrl: pairing?.entryUrl } } const saveServer = async (input: RemoteServerInput, requestedWindow: boolean, windowOptions: RemoteWindowOpenOptions = {}) => { - // A Remote Control pairing code is consumed by the window that opens it, so a pairing link opens one where possible. const pairing = splitPairingLink(input.baseUrl) - const openWindow = requestedWindow || (pairing !== null && canOpenRemoteWindows()) + const openWindow = requestedWindow if (openWindow && !canOpenRemoteWindows()) { throw new Error("Remote server windows can only be opened from a local desktop window") } const { profile } = await saveProfile(input) + if (pairing) pendingPairingEntries.set(profile.id, pairing.entryUrl) if (openWindow) { const proxySession = @@ -82,7 +86,8 @@ export function useRemoteServerProfiles() { : undefined try { - await openRemoteServerWindow(profile, pairing?.entryUrl ?? proxySession?.windowUrl, proxySession?.sessionId, windowOptions) + await openRemoteServerWindow(profile, pendingPairingEntries.get(profile.id) ?? proxySession?.windowUrl, proxySession?.sessionId, windowOptions) + pendingPairingEntries.delete(profile.id) } catch (error) { if (proxySession) void serverApi.deleteRemoteProxySession(proxySession.sessionId).catch(() => {}) throw error @@ -113,27 +118,28 @@ export function useRemoteServerProfiles() { /** A saved server opens a project tab, or its own window when it cannot (unverified certificate, no tabs here). */ const openServer = (profile: RemoteServerProfile, entryUrl?: string, blankId: string | null = activeBlankTabId() ?? null) => { + entryUrl ??= pendingPairingEntries.get(profile.id) if (opensRemoteProjectTab(profile)) { openRemoteProject(profile.id, entryUrl ? { entryUrl } : {}, blankId) + pendingPairingEntries.delete(profile.id) void markRemoteServerConnected(profile.id).catch(() => {}) } else { void connectSavedServer(profile.id) } } - /** - * The server dialog's submit: saves the server, then opens it on Connect, or always for a pairing - * link, whose single-use code is consumed where the server opens (a tab, else its own window). - */ + /** Saves a server; only an explicit Connect opens it. Pairing entries stay in memory until then. */ const submitServer = async (input: RemoteServerInput, open: boolean) => { const blankId = activeBlankTabId() ?? null - if (!opensRemoteProjectTab(input)) return void await saveServer(input, open) const { profile, entryUrl } = await saveProfile(input) - if (open || entryUrl) openServer(profile, entryUrl, blankId) + if (entryUrl) pendingPairingEntries.set(profile.id, entryUrl) + if (open) openServer(profile, entryUrl, blankId) + return profile } // A removed server's project tabs close with it. const removeServer = (id: string) => { + pendingPairingEntries.delete(id) closeRemoteProjectTabsForServer(id) removeRemoteServerProfile(id) } diff --git a/packages/ui/src/styles/components/blank-tab.css b/packages/ui/src/styles/components/blank-tab.css deleted file mode 100644 index 6f9099fe8a..0000000000 --- a/packages/ui/src/styles/components/blank-tab.css +++ /dev/null @@ -1,35 +0,0 @@ -/* Empty tabs share the home canvas and cards, with a responsive pair of choice lists. */ -.blank-tab-view { - flex: 1 1 auto; - min-width: 0; - padding: var(--space-lg); - background: var(--surface-canvas); -} - -.blank-tab-columns { - display: grid; - grid-template-columns: repeat(2, minmax(0, 1fr)); - gap: var(--space-md); - width: min(64rem, 100%); - margin: auto; -} - -.blank-tab-section { min-width: 0; overflow: hidden; } -.blank-tab-section .browse-menu-body { background: var(--surface-canvas); } -.blank-tab-section .new-instance-launcher-recents { max-height: 60vh; } -.blank-tab-actions { - display: flex; - flex-wrap: wrap; - justify-content: center; - gap: var(--space-sm); - margin-top: var(--space-md); -} - -.recent-tabs-menu { display: flex; flex-direction: column; min-height: 0; } -.new-instance-launcher > .recent-tabs-menu { overflow: hidden; } -.native-titlebar-home { -webkit-app-region: no-drag; } -.tab-bar-home { flex: 0 0 auto; margin-inline: var(--space-xs); } - -@media (max-width: 640px) { - .blank-tab-columns { grid-template-columns: minmax(0, 1fr); } -} diff --git a/packages/ui/src/styles/components/folder-home.css b/packages/ui/src/styles/components/folder-home.css index 4815f33393..577f8dbeb5 100644 --- a/packages/ui/src/styles/components/folder-home.css +++ b/packages/ui/src/styles/components/folder-home.css @@ -9,10 +9,13 @@ min-height: 100%; } +.folder-home-root--blank { height: 100%; } + @media (max-width: 639px) { .folder-home-shell { padding-top: 3.5rem; } + .folder-home-root--blank .folder-home-shell { padding-top: 0; } } .folder-home-hero { diff --git a/packages/ui/src/styles/components/native-titlebar.css b/packages/ui/src/styles/components/native-titlebar.css index 37da1b775d..42d4f63f92 100644 --- a/packages/ui/src/styles/components/native-titlebar.css +++ b/packages/ui/src/styles/components/native-titlebar.css @@ -1,3 +1,6 @@ +.native-titlebar-home { -webkit-app-region: no-drag; } +.tab-bar-home { flex: 0 0 auto; margin-inline: var(--space-xs); } + .native-titlebar { display: flex; align-items: stretch; diff --git a/packages/ui/src/styles/components/new-instance-launcher.css b/packages/ui/src/styles/components/new-instance-launcher.css index 72cb362970..c2b8592ab4 100644 --- a/packages/ui/src/styles/components/new-instance-launcher.css +++ b/packages/ui/src/styles/components/new-instance-launcher.css @@ -1,4 +1,6 @@ /* Compact new-instance launcher anchored to the tab-bar button (`new-instance-launcher.tsx`). */ +.recent-tabs-menu { display: flex; flex-direction: column; min-height: 0; overflow: hidden; } + .new-instance-launcher { background-color: var(--surface-overlay); color: var(--text-secondary); diff --git a/packages/ui/src/styles/controls.css b/packages/ui/src/styles/controls.css index b856d8f2e5..3856154e2a 100644 --- a/packages/ui/src/styles/controls.css +++ b/packages/ui/src/styles/controls.css @@ -50,6 +50,5 @@ @import "./components/integration-attachment.css"; @import "./components/integration-catalog.css"; @import "./components/browse-menu.css"; -@import "./components/blank-tab.css"; @import "./components/server-add-field.css"; @import "./components/embedded-project-picker.css"; diff --git a/packages/ui/tests/browser/fixtures/remote-server-pairing.tsx b/packages/ui/tests/browser/fixtures/remote-server-pairing.tsx index 056f21ace9..70d2e5b759 100644 --- a/packages/ui/tests/browser/fixtures/remote-server-pairing.tsx +++ b/packages/ui/tests/browser/fixtures/remote-server-pairing.tsx @@ -10,11 +10,11 @@ import "../../../src/index.css" // The page's inline script declares a native Preferences window (no project tabs) that records opened remote windows. const Harness = () => { - const { remoteServers } = useRemoteServerProfiles() + const { remoteServers, openServer } = useRemoteServerProfiles() return (
-
    {(server) =>
  • {server.id} {server.baseUrl}
  • }
- +
    {(server) =>
  • }
+
) } diff --git a/packages/ui/tests/browser/remote-project-tabs.test.ts b/packages/ui/tests/browser/remote-project-tabs.test.ts index 96631644d2..322bdd01a0 100644 --- a/packages/ui/tests/browser/remote-project-tabs.test.ts +++ b/packages/ui/tests/browser/remote-project-tabs.test.ts @@ -3,6 +3,8 @@ import { after, before, test } from "node:test" import { armFixtureNavigationBudget } from "./fixture-navigation-budget" import { borrowFixture } from "./fixture-borrow" import { chromium, type Browser, type Page } from "playwright" +import { mkdir } from "node:fs/promises" +import { fileURLToPath } from "node:url" // The real application (src/main.tsx) in three roles: the page a remote server // serves inside a host tab (?codenomadEmbed=project), a web or Remote Control @@ -118,7 +120,7 @@ async function browse(page: Page) { if (await toggle.getAttribute("aria-expanded") !== "true") await toggle.click() } -// Browse's last row: the field that adds a server and opens it. Enter submits it. +// Browse's last row: the field that saves a server. Enter submits it. async function addServer(page: Page, address: string) { await browse(page) const field = page.getByRole("textbox", { name: "Server address or link" }) @@ -245,7 +247,7 @@ test("a local window opens a saved server as a project tab whose view follows th } finally { await page.close() } }) -test("Browse's field opens a pasted pairing link in its tab and refuses an address carrying credentials, without a dialog", async () => { +test("Browse saves a pairing link without opening it and refuses credentials; clicking the server pairs", async () => { const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: "en-US" }) try { const fixture = await open(page, "", { context: "local", host: "electron" }) @@ -253,7 +255,7 @@ test("Browse's field opens a pasted pairing link in its tab and refuses an addre await page.getByRole("alert").getByText("Remove the user name and password from the address.").waitFor() assert.deepEqual(fixture.probes, []) - // A pasted link is added at once; its tab opens and consumes the code. + // A pasted link is saved at once; only clicking its row consumes the code. const tunnel = "https://desk.opentunnel.test" await field.fill("") await field.evaluate((input, link) => { @@ -261,7 +263,12 @@ test("Browse's field opens a pasted pairing link in its tab and refuses an addre data.setData("text", link) input.dispatchEvent(new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true })) }, `${tunnel}/remote-pair#single-use-code`) - await page.locator(".tab-pill", { hasText: "desk.opentunnel.test" }).waitFor() + const row = page.getByRole("button", { name: "Open a project on desk.opentunnel.test" }) + await row.waitFor() + await page.waitForFunction(() => document.activeElement?.getAttribute("data-remote-server")) + assert.equal((await views(page)).opened.length, 0) + assert.equal((await views(page)).windows.length, 0) + await row.click() await page.waitForFunction(() => (window as any).fixtureViews.opened.length === 1) const [opened] = (await views(page)).opened assert.equal(opened.url, `${tunnel}/remote-pair#single-use-code`) @@ -272,11 +279,17 @@ test("Browse's field opens a pasted pairing link in its tab and refuses an addre } finally { await page.close() } }) -test("an address added in Browse opens its tab at once, named after its host; an address already saved reuses its server", async () => { +test("an address added in Browse only joins the list and receives focus; clicking it opens its tab", async () => { const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: "en-US" }) try { const fixture = await open(page, "", { context: "local", host: "electron", uiState: { remoteServers: [server("box")] } }) await addServer(page, "https://lab.example:8443") + const row = page.getByRole("button", { name: "Open a project on lab.example" }) + await row.waitFor() + await page.waitForFunction(() => document.activeElement?.textContent === "lab.example") + assert.equal((await views(page)).opened.length, 0) + assert.equal((await views(page)).windows.length, 0) + await row.click() await page.locator(".tab-pill", { hasText: "lab.example" }).waitFor() await page.waitForFunction(() => (window as any).fixtureViews.opened.length === 1) type Saved = { remoteServers: Array<{ id: string; name: string; baseUrl: string }> } @@ -287,6 +300,9 @@ test("an address added in Browse opens its tab at once, named after its host; an // The saved server opens again without a second profile or a probe. await page.getByRole("button", { name: "Home", exact: true }).click() await addServer(page, BOX) + await page.waitForFunction(() => document.activeElement?.textContent === "Box") + assert.equal((await views(page)).opened.length, 1) + await page.getByRole("button", { name: "Open a project on Box" }).click() await page.waitForFunction(() => (window as any).fixtureViews.opened.length === 2) assert.equal((await views(page)).opened[1].profileId, "box") assert.deepEqual((fixture.state() as Saved).remoteServers.map((entry) => entry.id).sort(), [added.id, "box"].sort()) @@ -322,6 +338,10 @@ test("a certificate that fails the check offers skipping it under the field; the const skip = page.getByRole("checkbox", { name: "Skip TLS verification" }) await skip.check() await field.press("Enter") + const row = page.getByRole("button", { name: "Open a project on selfsigned.example" }) + await row.waitFor() + assert.equal((await views(page)).windows.length, 0, "TLS confirmation saves only") + await row.click() await page.waitForFunction(() => (window as any).fixtureViews.windows.length === 1) assert.equal((await views(page)).opened.length, 0, "an unverified certificate never opens a tab") assert.deepEqual(fixture.probes, ["https://selfsigned.example skipTls=false", "https://selfsigned.example skipTls=true"]) @@ -347,25 +367,25 @@ test("+ opens disposable blank tabs; remote and SideCar choices replace their or await page.locator('.new-instance-button').click() const blank = page.locator('[data-tab-kind="blank"][data-tab-visible="true"]') await blank.waitFor() - await page.waitForFunction(() => document.activeElement?.getAttribute('role') === 'combobox') + await page.waitForFunction(() => document.activeElement?.getAttribute('aria-label') === 'Search recent projects') assert.equal(await page.locator('.tab-pill').count(), 2, await page.locator('.tab-strip-tabs').innerText()) assert.equal(await blank.getByText('3 items', { exact: true }).count(), 1, 'Browse counts computer, server and SideCar') assert.equal(await blank.getByText('0 items', { exact: true }).count(), 1) - assert.equal(await page.locator('.folder-home-root').count(), 0) + assert.equal(await blank.locator('.folder-home-root--blank').count(), 1) assert.deepEqual(fixture.created, [], 'blank tabs create no backend workspace') - assert.deepEqual(await blank.locator('.blank-tab-actions button').allTextContents(), ['Clone Git Repo', 'New temporary tab']) - const columns = await blank.locator('.blank-tab-section').evaluateAll(nodes => nodes.map(node => ({ x: node.getBoundingClientRect().x, y: node.getBoundingClientRect().y }))) - assert.equal(columns[0].y, columns[1].y) - assert.ok(columns[1].x > columns[0].x) + assert.deepEqual(await blank.locator('.folder-home-actions-column .button-primary').allTextContents(), ['Clone Git Repo', 'New temporary tab', 'New SideCar']) + const columns = await blank.locator('.folder-home-main > div').evaluateAll(nodes => nodes.map(node => node.getBoundingClientRect().x)) + assert.ok(columns[0] > columns[1]) await page.setViewportSize({ width: 480, height: 800 }) - const narrow = await blank.locator('.blank-tab-section').evaluateAll(nodes => nodes.map(node => node.getBoundingClientRect().y)) - assert.ok(narrow[1] > narrow[0]) + const narrow = await blank.locator('.folder-home-main > div').evaluateAll(nodes => nodes.map(node => node.getBoundingClientRect().x)) + assert.equal(narrow[0], narrow[1]) await page.setViewportSize({ width: 1200, height: 800 }) // Open another blank, then fill the earlier one: its replacement keeps that earlier slot. const firstBlankId = await blank.getAttribute('data-tab-id') await page.locator('.new-instance-button').click() await page.locator(`[data-app-tab-id="${firstBlankId}"] [role=tab]`).click() + await blank.getByRole('tab', { name: 'Browse', exact: true }).click() await blank.getByRole('button', { name: 'Open a project on Box' }).click() assert.equal(await page.locator('[data-tab-kind="blank"]').count(), 1) assert.equal(await page.locator('.tab-pill').count(), 3) @@ -377,6 +397,7 @@ test("+ opens disposable blank tabs; remote and SideCar choices replace their or assert.equal(JSON.stringify(fixture.state()).includes('blank:'), false) await page.locator('.new-instance-button').click() + await blank.getByRole('tab', { name: 'Browse', exact: true }).click() await blank.locator('[data-sidecar="docs"]').click() await page.locator('.tab-pill', { hasText: 'Docs' }).waitFor() assert.equal(await page.locator('[data-tab-kind="blank"]').count(), 0) @@ -384,7 +405,7 @@ test("+ opens disposable blank tabs; remote and SideCar choices replace their or } finally { await page.close() } }) -test("a delayed server probe fills its originating blank tab, even after another blank opens", async () => { +test("a delayed server add preserves both blank tabs; clicking its row fills the chosen blank", async () => { const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: "en-US" }) let release!: () => void const held = new Promise(resolve => { release = resolve }) @@ -395,6 +416,7 @@ test("a delayed server probe fills its originating blank tab, even after another await page.locator(".new-instance-button").click() const blank = page.locator('[data-tab-kind="blank"][data-tab-visible="true"]') const origin = await blank.getAttribute("data-tab-id") + await blank.getByRole('tab', { name: 'Browse', exact: true }).click() await page.route("**/api/remote-servers/probe", async route => { await held; await route.fallback() }) const field = blank.getByRole("textbox", { name: "Server address or link" }) await field.fill("https://slow.example") @@ -405,13 +427,104 @@ test("a delayed server probe fills its originating blank tab, even after another const other = await blank.getAttribute("data-tab-id") assert.notEqual(other, origin) release() - await page.locator(".tab-pill", { hasText: "slow.example" }).waitFor() - assert.equal(await page.locator(`[data-tab-id="${origin}"]`).count(), 0) + const originView = page.locator(`[data-tab-id="${origin}"]`) + await originView.locator('.browse-menu-row', { hasText: 'slow.example' }).waitFor({ state: "attached" }) + assert.equal(await page.locator(`[data-tab-id="${origin}"]`).count(), 1) assert.equal(await page.locator(`[data-tab-id="${other}"]`).count(), 1) + await page.locator(`[data-app-tab-id="${origin}"] [role=tab]`).click() + await originView.getByRole('tab', { name: 'Browse', exact: true }).click() + await originView.getByRole("button", { name: "Open a project on slow.example" }).click() + assert.equal(await page.locator(`[data-tab-id="${origin}"]`).count(), 0) assert.match((await page.locator(".tab-strip-tabs > *").nth(1).getAttribute("data-app-tab-id"))!, /^remote-project:/) } finally { release(); await page.close() } }) +test("blank tabs reuse Home's branding, action buttons, tab selector and recent rows, with search below the selector", async () => { + const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: "en-US" }) + const captures = fileURLToPath(new URL("../../../../.tmp/blank-polish/", import.meta.url)) + try { + await mkdir(captures, { recursive: true }) + await open(page, "", { context: "local", host: "electron", uiState: { + remoteServers: [server("box")], + recentFolders: [{ path: "/srv/local", projectName: "Local", lastAccessed: Date.now() - 60000 }], + remoteProjectRecents: [{ profileId: "box", folder: "/srv/remote", projectName: "Remote", lastAccessed: Date.now() - 120000 }], + sidecarRecents: [{ sidecarId: "docs", lastAccessed: Date.now() - 180000 }], + }, sidecars: [sidecar("docs", "Docs", "running")] }) + await page.getByRole("button", { name: "Local", exact: true }).click() + await page.locator('.tab-strip-tabs [role=tab]', { hasText: 'Local' }).waitFor() + await page.getByRole("button", { name: "Home", exact: true }).click() + const home = page.locator(".folder-home-root") + await home.getByText("3 items").first().waitFor() + const presentation = async (root: typeof home) => root.evaluate(node => { + const sizes = [] + for (const selector of ['.folder-home-logo', '.button-primary', '[role=tablist]', '.folder-home-recent-item']) { + const element = node.querySelector(selector)! + const rect = element.getBoundingClientRect(), style = getComputedStyle(element) + sizes.push({ width: rect.width, height: rect.height, background: style.backgroundColor, font: style.font, radius: style.borderRadius }) + } + return { background: getComputedStyle(node).backgroundColor, sizes } + }) + const expected = await presentation(home) + await page.screenshot({ path: `${captures}/home-desktop.png` }) + await page.getByRole("button", { name: "Close", exact: true }).click() + await page.locator(".new-instance-button").click() + const blank = page.locator('[data-tab-kind="blank"][data-tab-visible="true"]') + await page.waitForFunction(() => document.activeElement?.getAttribute("aria-label") === "Search recent projects") + const root = blank.locator(".folder-home-root") + assert.deepEqual(await presentation(root), expected) + assert.equal(await blank.getByRole("heading", { name: "CodeNomad" }).count(), 1) + assert.deepEqual(await blank.getByRole('tab').allTextContents(), ['Recent3 items', 'Browse3 items']) + const selector = await blank.getByRole('tablist').boundingBox() + const search = await blank.getByRole('textbox', { name: 'Search recent projects' }).boundingBox() + assert.ok(search!.y >= selector!.y + selector!.height, 'search stays under the selector') + assert.equal(await blank.getByRole('link').count(), 0) + assert.equal(await blank.locator('.locale-selector, .panel-section, .version-pill, .absolute.top-4').count(), 0) + assert.equal(await blank.locator('.folder-home-open-instance-button').count(), 1) + assert.equal(await blank.getByText('Box', { exact: true }).count(), 1) + assert.equal(await blank.getByText('/srv/remote', { exact: true }).count(), 1) + await page.screenshot({ path: `${captures}/blank-desktop.png` }) + await page.setViewportSize({ width: 480, height: 800 }) + await page.screenshot({ path: `${captures}/blank-narrow.png` }) + assert.equal(await root.evaluate(node => node.scrollWidth <= node.clientWidth), true) + await page.setViewportSize({ width: 1200, height: 800 }) + await blank.getByRole('tab', { name: 'Browse', exact: true }).click() + const field = blank.getByRole('textbox', { name: 'Server address or link' }) + await field.fill('https://added.example') + await field.press('Enter') + const added = blank.getByRole('button', { name: 'Open a project on added.example' }) + await added.waitFor() + await page.waitForFunction(() => document.activeElement?.textContent === 'added.example') + assert.equal(await page.locator('[data-tab-kind="blank"]').count(), 1) + await added.click() + assert.equal(await page.locator('[data-tab-kind="blank"]').count(), 0) + } finally { await page.close() } +}) + +test("adding a server in the + launcher keeps it open, focuses the saved row and opens only on selection", async () => { + const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: "en-US" }) + try { + const fixture = await open(page, "", { context: "local", host: "electron", uiState: { remoteServers: [server('box')] } }) + await browse(page) + await page.getByRole('button', { name: 'Open a project on Box' }).click() + await page.locator('.new-instance-button').click({ button: 'right' }) + const launcher = page.locator('.new-instance-launcher') + const toggle = launcher.getByRole('button', { name: 'Browse', exact: true }) + if (await toggle.getAttribute('aria-expanded') !== 'true') await toggle.click() + const field = launcher.getByRole('textbox', { name: 'Server address or link' }) + await field.fill('https://launcher.example') + await field.press('Enter') + const row = launcher.getByRole('button', { name: 'Open a project on launcher.example' }) + await row.waitFor() + await page.waitForFunction(() => document.activeElement?.textContent === 'launcher.example') + assert.equal((await views(page)).opened.length, 1) + assert.equal((await views(page)).windows.length, 0) + assert.deepEqual(fixture.created, []) + await row.click() + await launcher.waitFor({ state: 'hidden' }) + await page.waitForFunction(() => (window as any).fixtureViews.opened.length === 2) + } finally { await page.close() } +}) + for (const host of ['web', 'electron', 'tauri'] as const) test(`${host}: the logo opens Home; Sponsor uses the existing help URL; a local choice replaces a blank tab`, async () => { const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: 'en-US' }) try { @@ -431,7 +544,7 @@ for (const host of ['web', 'electron', 'tauri'] as const) test(`${host}: the log await page.getByRole('button', { name: 'Close', exact: true }).click() await page.locator('.new-instance-button').click() const blank = page.locator('[data-tab-kind="blank"][data-tab-visible="true"]') - await blank.getByRole('option', { name: /Local/ }).click() + await blank.getByRole('button', { name: 'Local', exact: true }).click() await page.waitForFunction(() => !document.querySelector('[data-tab-kind="blank"]')) assert.deepEqual(fixture.created, ['/srv/local']) assert.equal(await page.locator('.tab-strip-tabs [role="tab"]').count(), 2) diff --git a/packages/ui/tests/browser/remote-server-pairing.test.ts b/packages/ui/tests/browser/remote-server-pairing.test.ts index a75ff97af8..f6c513c9eb 100644 --- a/packages/ui/tests/browser/remote-server-pairing.test.ts +++ b/packages/ui/tests/browser/remote-server-pairing.test.ts @@ -43,13 +43,17 @@ async function add(page: Page, address: string) { const opened = (page: Page) => page.evaluate(() => (window as unknown as { opened: Array<{ id: string; baseUrl: string; entryUrl?: string }> }).opened) -test("a pairing link saves only the server and pairs in the window it opens, even where adding only saves", async () => { +test("a pairing link saves only the server; clicking it pairs in its window", async () => { const page = await browser.newPage({ viewport: { width: 900, height: 900 }, locale: "en-US" }) const errors: string[] = [] page.on("pageerror", error => errors.push(error.message)) try { await page.goto(url) await add(page, LINK) + await page.getByRole("textbox", { name: "Server address or link" }).waitFor() + await page.waitForFunction(() => (document.querySelector('[data-server-add-field]') as HTMLInputElement)?.value === "") + assert.deepEqual(await opened(page), [], "adding a pairing link never opens a window") + await page.getByTestId("servers").getByRole("button").click() await page.waitForFunction(() => (window as unknown as { opened: unknown[] }).opened.length === 1) const [payload] = await opened(page) assert.equal(payload.baseUrl, TUNNEL) @@ -71,6 +75,9 @@ test("pairing a saved server again reuses it instead of adding a duplicate", asy await page.goto(`${url}?scenario=saved`) await page.getByTestId("servers").getByText(`saved-tunnel ${TUNNEL}`).waitFor() await add(page, LINK) + await page.waitForFunction(() => (document.querySelector('[data-server-add-field]') as HTMLInputElement)?.value === "") + assert.deepEqual(await opened(page), []) + await page.getByTestId("servers").getByRole("button").click() await page.waitForFunction(() => (window as unknown as { opened: unknown[] }).opened.length === 1) assert.equal((await opened(page))[0].id, "saved-tunnel") assert.equal(await page.getByTestId("servers").locator("li").count(), 1) @@ -85,4 +92,4 @@ test("an ordinary address added in Settings is saved without opening a window", await page.getByTestId("servers").getByText("https://server.example.com").waitFor() assert.deepEqual(await opened(page), []) } finally { await page.close() } -}) \ No newline at end of file +}) From b3fb4991651c26426c8f6fd1a99f3561fcd4039e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 6 Nov 2026 02:31:43 +0100 Subject: [PATCH 20/34] feat(remote): browse server folders in place with backend-held sessions Browse now enters a saved server in place on Home, empty tabs and the plus launcher. An inline sign-in form authenticates through the local backend; recent projects, parent navigation and Select Current keep the list open until a folder is chosen. Opening that folder targets the remote project directly and replaces the originating empty tab. Native embedded views retain their independent authentication. Reuse the existing CodeNomad client, credential store, folder normalization and fake remote server without relay or event rewriting. Persist successful credentials and sessions privately beside config, retry authentication once after expiry and forget identity before removing the profile. Bind requests to backend-owned profiles, fence redirects/DNS/origins, honor certificate policy and redact connection request bodies. The new routes require loopback non-ingress access plus a trusted self Origin before any secret or network access; upstream requests never carry Origin. Remote Control backend pairing remains explicitly unavailable: its existing gate requires browser Origin while the direct listener rejects pairing. Do not spoof that header or silently weaken the gate. Imported special-address restrictions remain in place. Validated UI/server typechecks, 1623 UI unit tests, 36 targeted real-server/security tests, and 108 browser tests with one environment-dependent Electron check skipped. The full server suite reported 3688 passed, 21 skipped and four load/platform failures; all four files passed isolated reruns (16 tests). Offline Tauri no-bundle release build succeeds without launching the app. --- packages/server/src/api-types.ts | 5 + .../src/codenomad-servers/browse-manager.ts | 119 +++++++ .../src/codenomad-servers/browse.test.ts | 304 ++++++++++++++++++ .../server/src/codenomad-servers/client.ts | 135 ++++++++ .../src/codenomad-servers/credentials.ts | 67 ++++ .../server/src/codenomad-servers/folders.ts | 40 +++ .../test-support/fake-codenomad.ts | 61 ++++ .../server/src/opencode/servers/endpoint.ts | 21 ++ .../server/src/opencode/servers/origin.ts | 63 ++++ .../server/src/opencode/servers/transport.ts | 105 ++++++ .../integration-request-logging.test.ts | 7 + packages/server/src/server/http-server.ts | 5 + packages/server/src/server/request-logging.ts | 4 +- .../src/server/routes/remote-server-browse.ts | 34 ++ packages/ui/src/components/browse-menu.tsx | 27 +- .../src/components/remote-server-browser.tsx | 112 +++++++ .../ui/src/components/server-add-field.tsx | 7 + packages/ui/src/lib/api-client.ts | 10 + .../lib/hooks/use-remote-server-profiles.ts | 35 +- .../lib/i18n/messages/de/folderSelection.ts | 3 + .../lib/i18n/messages/en/folderSelection.ts | 3 + .../lib/i18n/messages/es/folderSelection.ts | 3 + .../lib/i18n/messages/fr/folderSelection.ts | 3 + .../lib/i18n/messages/he/folderSelection.ts | 3 + .../lib/i18n/messages/ja/folderSelection.ts | 3 + .../lib/i18n/messages/ne/folderSelection.ts | 3 + .../lib/i18n/messages/ru/folderSelection.ts | 3 + .../lib/i18n/messages/tr/folderSelection.ts | 3 + .../i18n/messages/zh-Hans/folderSelection.ts | 3 + .../components/remote-server-browser.css | 5 + packages/ui/src/styles/controls.css | 1 + .../fixtures/remote-server-pairing-api.ts | 1 + .../tests/browser/remote-project-tabs.test.ts | 163 +++++++++- .../browser/remote-server-pairing.test.ts | 18 +- 34 files changed, 1334 insertions(+), 45 deletions(-) create mode 100644 packages/server/src/codenomad-servers/browse-manager.ts create mode 100644 packages/server/src/codenomad-servers/browse.test.ts create mode 100644 packages/server/src/codenomad-servers/client.ts create mode 100644 packages/server/src/codenomad-servers/credentials.ts create mode 100644 packages/server/src/codenomad-servers/folders.ts create mode 100644 packages/server/src/codenomad-servers/test-support/fake-codenomad.ts create mode 100644 packages/server/src/opencode/servers/endpoint.ts create mode 100644 packages/server/src/opencode/servers/origin.ts create mode 100644 packages/server/src/opencode/servers/transport.ts create mode 100644 packages/server/src/server/routes/remote-server-browse.ts create mode 100644 packages/ui/src/components/remote-server-browser.tsx create mode 100644 packages/ui/src/styles/components/remote-server-browser.css diff --git a/packages/server/src/api-types.ts b/packages/server/src/api-types.ts index 7259e3e5e8..b019b25d76 100644 --- a/packages/server/src/api-types.ts +++ b/packages/server/src/api-types.ts @@ -767,6 +767,11 @@ export interface RemoteServerProbeRequest { skipTlsVerify?: boolean } +export interface RemoteServerBrowseResponse { + listing: FileSystemListResponse + recents: Array<{ path: string; projectName?: string; lastAccessed: number }> +} + export interface RemoteServerProbeResponse { ok: boolean reachable: boolean diff --git a/packages/server/src/codenomad-servers/browse-manager.ts b/packages/server/src/codenomad-servers/browse-manager.ts new file mode 100644 index 0000000000..17c04bd265 --- /dev/null +++ b/packages/server/src/codenomad-servers/browse-manager.ts @@ -0,0 +1,119 @@ +import path from "node:path" +import { z } from "zod" +import type { SettingsService } from "../settings/service" +import type { RemoteServerBrowseResponse } from "../api-types" +import { normalizeExplicitOrigin } from "../opencode/servers/endpoint" +import { CodeNomadServerClient, CodeNomadServerError } from "./client" +import { CodeNomadServerCredentials, type CodeNomadServerSecret } from "./credentials" +import { relayedFolderListing } from "./folders" + +const Profile = z.object({ id: z.string(), baseUrl: z.string(), skipTlsVerify: z.boolean().default(false) }) +const Recent = z.object({ path: z.string().min(1).max(8192), projectName: z.string().max(1024).optional(), lastAccessed: z.number().finite() }) +export const BrowseBody = z.object({ path: z.string().max(8192).optional() }).strict() +export const ConnectBody = z.object({ username: z.string().min(1).max(1024).optional(), password: z.string().min(1).max(8192).optional(), + pairingLink: z.string().max(8192).optional() }).strict() + +/** Only saved backend profiles can choose a network target. Owns no projects or event streams. */ +export class RemoteServerBrowseManager { + #credentials?: CodeNomadServerCredentials + #clients = new Map() + #pending = new Set() + #queues = new Map>() + #closed = false + + constructor(private readonly settings: Pick) {} + + private get credentials() { + return this.#credentials ??= new CodeNomadServerCredentials(path.join(path.dirname(this.settings.configYamlPathForAuthority()), "remote-server-credentials.json")) + } + + private profile(id: string) { + const values = this.settings.getOwner("state", "ui").remoteServers + const profile = Array.isArray(values) ? values.map(value => Profile.safeParse(value)).find(value => value.success && value.data.id === id) : undefined + if (!profile?.success) { this.remove(id); throw new CodeNomadServerError("unknown_server") } + const origin = normalizeExplicitOrigin(profile.data.baseUrl, true) + return { ...profile.data, origin, key: `${origin}|${profile.data.skipTlsVerify}` } + } + + private serial(id: string, run: () => Promise): Promise { + const pending = (this.#queues.get(id) ?? Promise.resolve()).catch(() => {}).then(() => { + if (this.#closed) throw new CodeNomadServerError("unreachable") + return run() + }) + this.#queues.set(id, pending) + void pending.finally(() => { if (this.#queues.get(id) === pending) this.#queues.delete(id) }).catch(() => {}) + return pending + } + + connect(id: string, body: z.infer) { + return this.serial(id, async () => { + const profile = this.profile(id) + if (body.pairingLink !== undefined) throw new CodeNomadServerError("pairing_unavailable") + if (Boolean(body.username) !== Boolean(body.password)) throw new CodeNomadServerError("needs_credentials") + let secret: CodeNomadServerSecret | undefined = body.password + ? { kind: "password", username: body.username!, password: body.password } + : this.credentials.read(id, profile.origin) + const client = new CodeNomadServerClient(profile.origin, secret, { skipTlsVerify: profile.skipTlsVerify, onSecretChanged: next => { secret = next } }) + this.#pending.add(client) + try { + const result = await client.json<{ authenticated?: unknown; pairingRequired?: unknown }>("/api/auth/status") + if (result.body?.pairingRequired === true) throw new CodeNomadServerError("pairing_unavailable") + if (result.status !== 200) throw new CodeNomadServerError("unreachable") + if (result.body?.authenticated !== true) throw new CodeNomadServerError("needs_credentials") + if (this.#closed || this.profile(id).key !== profile.key) throw new CodeNomadServerError("unknown_server") + // Commit only after remote authentication succeeds; failed replacements keep the working identity. + if (secret) this.credentials.set(id, profile.origin, secret) + this.#clients.get(id)?.client.close() + this.#clients.delete(id) + return { ok: true } + } finally { this.#pending.delete(client); client.close() } + }) + } + + browse(id: string, body: z.infer): Promise { + return this.serial(id, async () => { + const profile = this.profile(id) + let entry = this.#clients.get(id) + if (entry?.key !== profile.key) { entry?.client.close(); this.#clients.delete(id); entry = undefined } + if (!entry) { + const client = new CodeNomadServerClient(profile.origin, this.credentials.read(id, profile.origin), { + skipTlsVerify: profile.skipTlsVerify, + onRejected: () => { this.credentials.delete(id); this.#clients.get(id)?.client.close(); this.#clients.delete(id) }, + onSecretChanged: secret => this.credentials.set(id, profile.origin, secret), + }) + entry = { key: profile.key, client } + this.#clients.set(id, entry) + } + const suffix = body.path === undefined ? "" : `?path=${encodeURIComponent(body.path)}` + if (!this.credentials.has(id, profile.origin)) { + const status = await entry.client.json<{ pairingRequired?: unknown }>("/api/auth/status") + if (status.body?.pairingRequired === true) throw new CodeNomadServerError("pairing_unavailable") + } + const folders = await entry.client.json(`/api/filesystem${suffix}`) + if (folders.status !== 200) throw new CodeNomadServerError("unreachable") + const listing = relayedFolderListing(folders.body) + const state = await entry.client.json<{ recentFolders?: unknown }>("/api/storage/state/ui") + if (state.status !== 200 || !state.body || typeof state.body !== "object") throw new CodeNomadServerError("unreachable") + const recents = Array.isArray(state.body.recentFolders) ? state.body.recentFolders.slice(0, 2000).flatMap(value => { + const parsed = Recent.safeParse(value) + return parsed.success ? [parsed.data] : [] + }) : [] + return { listing, recents } + }) + } + + private remove(id: string) { + this.#clients.get(id)?.client.close() + this.#clients.delete(id) + this.credentials.delete(id) + } + + forget(id: string) { return this.serial(id, async () => { this.remove(id); return { ok: true } }) } + + close() { + this.#closed = true + for (const { client } of this.#clients.values()) client.close() + for (const client of this.#pending) client.close() + this.#clients.clear() + } +} diff --git a/packages/server/src/codenomad-servers/browse.test.ts b/packages/server/src/codenomad-servers/browse.test.ts new file mode 100644 index 0000000000..32a32bf476 --- /dev/null +++ b/packages/server/src/codenomad-servers/browse.test.ts @@ -0,0 +1,304 @@ +import assert from "node:assert/strict" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { request as httpRequest } from "node:http" +import { test, type TestContext } from "node:test" +import Fastify from "fastify" +import { RemoteServerBrowseManager } from "./browse-manager" +import { startFakeCodeNomad } from "./test-support/fake-codenomad" +import { registerRemoteServerBrowseRoutes } from "../server/routes/remote-server-browse" +import { registerRemoteControlRoutes } from "../server/routes/remote-control" +import { RemoteIngress } from "../remote-control/ingress" +import { gateRemoteRequest } from "../remote-control/gate" +import { normalizeExplicitOrigin } from "../opencode/servers/endpoint" +import { createExplicitTransport } from "../opencode/servers/transport" +import { resolveHttpsOptions } from "../server/tls" +import type { Logger } from "../logger" +import type { RemoteControlManager } from "../remote-control/manager" +import { redactSecrets } from "../server/request-logging" +import { relayedFolderListing } from "./folders" + +test("Windows drive roots stay navigable and cannot be selected as physical folders", () => { + const value = relayedFolderListing({ entries: [{ name: "C:", path: "C:/", type: "directory" }], + metadata: { scope: "unrestricted", pathKind: "drives", currentPath: "__windows_drives__", displayPath: "This computer", rootPath: "", homePath: "C:/Users/test" } }) + assert.equal(value.metadata.pathKind, "drives") + assert.equal(value.entries[0].path, "C:/") +}) + +function directory(t: TestContext) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "codenomad-browse-")) + t.after(() => fs.rmSync(dir, { recursive: true, force: true })) + return dir +} + +async function fixture(t: TestContext, options: Parameters[0] = {}) { + const dir = directory(t) + const remote = await startFakeCodeNomad(options) + t.after(() => remote.close()) + const profiles = [{ id: "saved", baseUrl: remote.origin, skipTlsVerify: false }] + const settings = { getOwner: () => ({ remoteServers: profiles }), configYamlPathForAuthority: () => path.join(dir, "config.yaml") } + const manager = new RemoteServerBrowseManager(settings) + const app = Fastify() + let origin = "" + registerRemoteServerBrowseRoutes(app, { manager, getSelfOrigins: () => new Set([origin]) }) + app.addHook("onClose", async () => manager.close()) + origin = await app.listen({ host: "127.0.0.1", port: 0 }) + t.after(() => app.close()) + const call = (action: string, body: unknown = {}, id = "saved", headers = { origin }) => app.inject({ + method: "POST", url: `/api/remote-servers/${id}/${action}`, headers, payload: body as object, + }) + return { dir, remote, profiles, settings, manager, app, origin, call, + connect: () => call("connect", { username: "codenomad", password: "remote-password" }) } +} + +test("Remote Control status never offers a password form or attempts login", async t => { + const f = await fixture(t) + f.remote.state.overrides.set('/api/auth/status', { status: 200, body: { authenticated: false, pairingRequired: true } }) + for (let i = 0; i < 2; i++) assert.deepEqual((await f.call('browse')).json(), { error: 'pairing_unavailable' }) + assert.equal(f.remote.state.logins, 0) + assert(f.remote.state.requests.every(request => request.path === '/api/auth/status' && request.headers.origin === undefined)) +}) + +test("saved direct authentication, sanitized folders and recents, one reauthentication after expiry", async t => { + const f = await fixture(t) + const missing = await f.call("browse") + assert.equal(missing.statusCode, 409) + assert.deepEqual(missing.json(), { error: "needs_credentials" }) + const wrong = await f.call("connect", { username: "codenomad", password: "wrong" }) + assert.equal(wrong.statusCode, 409) + assert.deepEqual(wrong.json(), { error: "auth" }) + assert.equal(fs.existsSync(path.join(f.dir, "remote-server-credentials.json")), false) + assert.deepEqual((await f.connect()).json(), { ok: true }) + const body = (await f.call("browse")).json() + assert.deepEqual(body.recents, [{ path: "/srv/projects/app", projectName: "App", lastAccessed: 42 }]) + assert.equal(body.listing.metadata.currentPath, "/srv/projects") + assert.deepEqual(body.listing.entries, [{ name: "app", path: "/srv/projects/app", absolutePath: "/srv/projects/app", type: "directory" }]) + assert.equal(JSON.stringify(body).includes("must-not-leak"), false) + const nested = (await f.call("browse", { path: "/srv/projects/folder &?#" })).json() + assert.equal(nested.listing.metadata.currentPath, "/srv/projects/folder &?#") + assert.equal(f.remote.state.logins, 2, "browse reuses the persisted successful session") + const beforeExpiry = fs.readFileSync(path.join(f.dir, "remote-server-credentials.json"), "utf8") + f.remote.restart() + assert.equal((await f.call("browse")).statusCode, 200) + assert.equal(f.remote.state.logins, 3) + assert.notEqual(fs.readFileSync(path.join(f.dir, "remote-server-credentials.json"), "utf8"), beforeExpiry, "rotated session persists after expired-session reauthentication") + assert(f.remote.state.requests.every(request => request.headers.origin === undefined), "never send Origin upstream") + assert(f.remote.state.requests.every(request => ["/api/auth/login", "/api/auth/status", "/api/filesystem", "/api/storage/state/ui"].includes(request.path.split("?")[0]!))) +}) + +test("private successful credentials and sessions survive launches; failed replacement preserves identity; forget removes it", async t => { + const f = await fixture(t) + await f.connect() + const file = path.join(f.dir, "remote-server-credentials.json") + const saved = fs.readFileSync(file, "utf8") + assert(saved.includes("remote-password")) + assert(saved.includes("codenomad_session=")) + if (process.platform !== "win32") assert.equal(fs.statSync(file).mode & 0o777, 0o600) + await f.call("connect", { username: "codenomad", password: "wrong" }) + assert.equal(fs.readFileSync(file, "utf8"), saved) + f.manager.close() + const next = new RemoteServerBrowseManager(f.settings) + t.after(() => next.close()) + assert.equal((await next.browse("saved", {})).listing.metadata.currentPath, "/srv/projects") + assert.equal(f.remote.state.logins, 2, "persisted session avoids a launch login") + await next.forget("saved") + assert.deepEqual(JSON.parse(fs.readFileSync(file, "utf8")), { servers: {} }) + await assert.rejects(next.browse("saved", {}), { code: "needs_credentials" }) +}) + +test("revoked password retries once and clears private identity; profiles are resolved by ID", async t => { + const f = await fixture(t) + await f.connect() + await f.call("browse") + f.remote.state.password = "changed" + f.remote.restart() + const refused = await f.call("browse") + assert.equal(refused.statusCode, 409) + assert.deepEqual(refused.json(), { error: "auth" }) + assert.equal(f.remote.state.logins, 2) + assert.deepEqual(JSON.parse(fs.readFileSync(path.join(f.dir, "remote-server-credentials.json"), "utf8")), { servers: {} }) + const before = f.remote.state.requests.length + assert.deepEqual((await f.call("browse", {}, "missing")).json(), { error: "unknown_server" }) + await f.call("browse", { baseUrl: f.remote.origin }) + assert.equal(f.remote.state.requests.length, before) + f.profiles[0]!.baseUrl = `${f.remote.origin}/api/auth/login` + assert.deepEqual((await f.call("browse")).json(), { error: "unreachable" }) + assert.equal(f.remote.state.requests.length, before) + assert.equal(normalizeExplicitOrigin("http://192.168.1.25:8080", true), "http://192.168.1.25:8080") +}) + +test("anonymous direct servers need no secrets; removed and changed profiles cannot reuse credentials", async t => { + const f = await fixture(t, { anonymous: true }) + assert.equal((await f.call("browse")).statusCode, 200) + assert.equal((await f.call("connect")).statusCode, 200) + assert.equal(fs.existsSync(path.join(f.dir, "remote-server-credentials.json")), false) + f.profiles.splice(0) + assert.deepEqual((await f.call("browse")).json(), { error: "unknown_server" }) +}) + +test("forget endpoint deletes credentials and client; a changed origin never receives another profile's secret", async t => { + const f = await fixture(t) + await f.connect() + await f.call("browse") + assert.deepEqual((await f.call("forget")).json(), { ok: true }) + assert.deepEqual((await f.call("browse")).json(), { error: "needs_credentials" }) + await f.connect() + const other = await startFakeCodeNomad() + t.after(() => other.close()) + f.profiles[0]!.baseUrl = other.origin + assert.deepEqual((await f.call("browse")).json(), { error: "needs_credentials" }) + assert(other.state.requests.every(request => !request.headers.cookie && !request.headers.authorization && !request.body)) + assert.equal(other.state.logins, 0) + assert.deepEqual(JSON.parse(fs.readFileSync(path.join(f.dir, "remote-server-credentials.json"), "utf8")), { servers: {} }) +}) + +test("remote data is bounded and invalid recent entries are omitted without leaking upstream payloads", async t => { + const f = await fixture(t) + await f.connect() + f.remote.state.recents[0]!.projectName = "x".repeat(1025) + assert.deepEqual((await f.call("browse")).json().recents, []) + f.remote.state.recents[0]!.projectName = "x".repeat(8 * 1024 * 1024) + assert.deepEqual((await f.call("browse")).json(), { error: "unreachable" }) +}) + +test("malformed remote metadata and entries always return stable sanitized errors", async t => { + const f = await fixture(t) + await f.connect() + const listing = (await f.call("browse")).json().listing + for (const body of [null, { ...listing, metadata: null }, { ...listing, metadata: { ...listing.metadata, rootPath: { password: "private" } } }, + { ...listing, entries: [{ type: "directory", name: "app", path: { cookie: "private" } }] }, { ...listing, entries: "private" }]) { + f.remote.state.overrides.set("/api/filesystem", { status: 200, body }) + const response = await f.call("browse") + assert.equal(response.statusCode, 502) + assert.deepEqual(response.json(), { error: "unreachable" }) + } +}) + +test("unsuccessful login or redirected reads cannot replace persisted credentials or forward cookies", async t => { + const f = await fixture(t) + await f.connect() + await f.call("browse") + const file = path.join(f.dir, "remote-server-credentials.json") + const saved = fs.readFileSync(file, "utf8") + f.remote.state.overrides.set("/api/auth/login", { status: 401, body: { password: "must-not-leak" }, headers: { "set-cookie": "codenomad_session=failed-login; Path=/" } }) + const failed = await f.call("connect", { username: "codenomad", password: "wrong" }) + assert.equal(failed.statusCode, 409) + assert.deepEqual(failed.json(), { error: "auth" }) + assert.equal(fs.readFileSync(file, "utf8"), saved) + f.remote.state.overrides.delete("/api/auth/login") + const other = await startFakeCodeNomad() + t.after(() => other.close()) + f.remote.state.overrides.set("/api/filesystem", { status: 302, body: { cookie: "must-not-leak" }, headers: { + location: `${other.origin}/api/filesystem`, "set-cookie": "codenomad_session=redirect-secret; Domain=foreign.test; Path=/", + } }) + assert.deepEqual((await f.call("browse")).json(), { error: "unreachable" }) + assert.equal(fs.readFileSync(file, "utf8"), saved) + assert.equal(other.state.requests.length, 0) + f.remote.state.overrides.delete("/api/filesystem") + assert.equal((await f.call("browse")).statusCode, 200) + await f.call("forget") + f.profiles.splice(0) + assert.deepEqual((await f.call("browse")).json(), { error: "unknown_server" }) + assert.deepEqual(JSON.parse(fs.readFileSync(file, "utf8")), { servers: {} }) +}) + +test("transport strips Origin, caller cookies and response cookies, and fences every dispatch to its bound origin", async t => { + const remote = await startFakeCodeNomad() + const other = await startFakeCodeNomad() + t.after(() => remote.close()) + t.after(() => other.close()) + const captured: string[] = [] + remote.state.overrides.set("/api/auth/status", { status: 200, body: { authenticated: true }, headers: { "set-cookie": "private-session=value; Domain=foreign.test; Path=/" } }) + const transport = createExplicitTransport({ origin: remote.origin, allowHttp: true, + headers: () => ({ Origin: remote.origin, cookie: "private-cookie=value" }), onSetCookie: values => captured.push(...values) }) + const response = await transport.fetch(`${remote.origin}/api/auth/status`, { headers: { origin: "http://foreign.test", cookie: "caller-cookie=value" } }) + assert.equal(response.headers.get("set-cookie"), null) + await response.body?.cancel() + assert.equal(captured.length, 1) + assert.equal(remote.state.requests[0]!.headers.origin, undefined) + assert.equal(remote.state.requests[0]!.headers.cookie, "private-cookie=value") + await assert.rejects(transport.fetch(`${other.origin}/api/auth/status`), { code: "invalid_origin" }) + assert.equal(other.state.requests.length, 0) + remote.state.overrides.set("/api/auth/status", { status: 302, body: {}, headers: { location: "/api/filesystem", "set-cookie": "private-session=redirected" } }) + await assert.rejects(transport.fetch(`${remote.origin}/api/auth/status`), { code: "redirect" }) + assert.equal(captured.length, 1, "even same-origin redirects do not rotate stored cookies") + assert.equal(remote.state.requests.length, 2, "redirect is never followed") +}) + +test("host guard requires loopback AND exact self Origin even with no general authentication", async t => { + const f = await fixture(t) + for (const action of ["browse", "connect", "forget"]) { + for (const origin of [undefined, "null", "http://foreign.test", "http://localhost:3000", "http://127.0.0.1:1"]) { + const headers = origin ? { origin } : {} + const response = await f.app.inject({ method: "POST", url: `/api/remote-servers/saved/${action}`, headers, payload: {} }) + assert.equal(response.statusCode, 403) + assert.deepEqual(response.json(), { error: "auth" }) + } + const lan = await f.app.inject({ method: "POST", url: `/api/remote-servers/saved/${action}`, remoteAddress: "192.168.1.8", headers: { origin: f.origin }, payload: {} }) + assert.equal(lan.statusCode, 403) + } + const ingress = new RemoteIngress((req, res) => f.app.server.emit("request", req, res)) + const target = await ingress.start() + t.after(() => ingress.stop()) + for (const action of ["browse", "connect", "forget"]) { + const response = await fetch(`http://${target}/api/remote-servers/saved/${action}`, { + method: "POST", headers: { origin: f.origin, "content-type": "application/json", "x-forwarded-for": "127.0.0.1" }, body: "{}", + }) + assert.equal(response.status, 403) + assert.deepEqual(await response.json(), { error: "auth" }) + } + assert.equal(f.remote.state.requests.length, 0, "refused before reading credentials or contacting the saved target") + assert.equal(fs.existsSync(path.join(f.dir, "remote-server-credentials.json")), false) +}) + +test("pairing unavailable preserves the actual Remote Control Origin and direct-listener policy", async t => { + const f = await fixture(t) + assert.deepEqual((await f.call("connect", { pairingLink: "https://remote.test/remote-pair#secret" })).json(), { error: "pairing_unavailable" }) + assert.equal(f.remote.state.requests.length, 0) + assert.deepEqual(redactSecrets({ pairingLink: "https://remote.test/remote-pair#secret", password: "secret" }), { pairingLink: "", password: "" }) + const app = Fastify() + let exchanges = 0 + registerRemoteControlRoutes(app, { manager: { exchangePairing() { exchanges++; return null } } as unknown as RemoteControlManager }) + app.addHook("onRequest", (request, reply, done) => { + if (!gateRemoteRequest(request, reply, { publicHost: () => "remote.test", authenticate: () => null, assignDevice() {}, servesPreview: () => false })) done() + }) + await app.listen({ port: 0, host: "127.0.0.1" }) + t.after(() => app.close()) + const direct = await app.inject({ method: "POST", url: "/api/remote-control/pair", payload: { code: "secret" } }) + assert.equal(direct.statusCode, 404) + const ingress = new RemoteIngress((req, res) => app.server.emit("request", req, res)) + const target = await ingress.start() + t.after(() => ingress.stop()) + const status = await new Promise((resolve, reject) => { + const request = httpRequest(`http://${target}/api/remote-control/pair`, { + method: "POST", headers: { host: "remote.test", "content-type": "application/json" }, + }, response => { response.resume(); response.on("end", () => resolve(response.statusCode)) }) + request.on("error", reject) + request.end(JSON.stringify({ code: "secret" })) + }) + assert.equal(status, 403, "real gate refuses server-to-server pairing without Origin") + assert.equal(exchanges, 0) +}) + +test("real HTTPS honors the saved certificate policy; TLS errors never expose details", async t => { + const dir = directory(t) + const logger = { info() {}, warn() {}, error() {}, child() { return logger } } as unknown as Logger + const tls = resolveHttpsOptions({ enabled: true, configDir: dir, host: "localhost", logger })! + const f = await fixture(t, { tls: tls.httpsOptions }) + assert.deepEqual((await f.connect()).json(), { error: "tls_error" }) + assert.equal(fs.existsSync(path.join(f.dir, "remote-server-credentials.json")), false) + f.profiles[0]!.skipTlsVerify = true + assert.deepEqual((await f.connect()).json(), { ok: true }) + assert.equal((await f.call("browse")).statusCode, 200) + f.profiles[0]!.skipTlsVerify = false + assert.deepEqual((await f.call("browse")).json(), { error: "tls_error" }) +}) + +test("unreachable targets return a stable error, and manager shutdown cancels further work", async t => { + const f = await fixture(t) + await f.remote.close() + assert.deepEqual((await f.connect()).json(), { error: "unreachable" }) + f.manager.close() + assert.deepEqual((await f.call("browse")).json(), { error: "unreachable" }) +}) diff --git a/packages/server/src/codenomad-servers/client.ts b/packages/server/src/codenomad-servers/client.ts new file mode 100644 index 0000000000..0825266607 --- /dev/null +++ b/packages/server/src/codenomad-servers/client.ts @@ -0,0 +1,135 @@ +import { createExplicitTransport } from "../opencode/servers/transport" +import { ExplicitEndpointError, type ResolveAddresses } from "../opencode/servers/endpoint" +import type { CodeNomadServerSecret } from "./credentials" + +export type CodeNomadServerErrorCode = "unreachable" | "tls_error" | "auth" | "pairing_unavailable" | "needs_credentials" | "unknown_server" + +/** Stable codes only; never a URL, credential or upstream message. */ +export class CodeNomadServerError extends Error { + constructor(readonly code: CodeNomadServerErrorCode) { + super(code) + this.name = "CodeNomadServerError" + } +} + +const READ_LIMIT_BYTES = 8 * 1024 * 1024 +const CALL_TIMEOUT_MS = 10_000 + +export function endpointErrorCode(error: unknown): CodeNomadServerErrorCode { + if (error instanceof CodeNomadServerError) return error.code + if (error instanceof ExplicitEndpointError && error.code === "tls") return "tls_error" + return "unreachable" +} + +/** Name=value pairs of Set-Cookie values; attributes are dropped. */ +function cookiePairs(values: string[]): Map { + const pairs = new Map() + for (const value of values) { + const pair = value.split(";", 1)[0]!.trim() + const index = pair.indexOf("=") + if (index > 0) pairs.set(pair.slice(0, index), pair.slice(index + 1)) + } + return pairs +} + +/** One authenticated, read-only client per saved CodeNomad profile. */ +export class CodeNomadServerClient { + #cookies = new Map() + #login?: Promise + #controller = new AbortController() + readonly #transport: ReturnType + + constructor(readonly origin: string, private secret: CodeNomadServerSecret | undefined, private readonly options: { + /** A refused credential (bad password, revoked device). */ + onRejected?: () => void + /** A successful session/device cookie rotation to persist. */ + onSecretChanged?: (secret: CodeNomadServerSecret) => void + resolve?: ResolveAddresses + skipTlsVerify?: boolean + } = {}) { + if (secret?.cookie) for (const [name, value] of cookiePairs([secret.cookie])) this.#cookies.set(name, value) + this.#transport = createExplicitTransport({ + origin, signal: this.#controller.signal, + allowHttp: true, skipTlsVerify: options.skipTlsVerify, + headers: (): Record => (this.#cookies.size ? { cookie: [...this.#cookies].map(([name, value]) => `${name}=${value}`).join("; ") } : {}), + onSetCookie: values => this.capture(values), + }, options.resolve) + } + + private capture(values: string[]) { + for (const [name, value] of cookiePairs(values)) { + if (value) this.#cookies.set(name, value) + else this.#cookies.delete(name) + } + if (this.secret) { + const cookie = [...this.#cookies].map(([name, value]) => `${name}=${value}`).join("; ") + if (cookie && cookie !== this.secret.cookie) { + this.secret = { ...this.secret, cookie } + this.options.onSecretChanged?.(this.secret) + } + } + } + + close() { this.#controller.abort() } + get closed() { return this.#controller.signal.aborted } + + /** Password login; cookies and passwords stay in the backend's private store. */ + login(signal?: AbortSignal): Promise { + if (this.secret?.kind !== "password") return Promise.reject(new CodeNomadServerError("needs_credentials")) + const secret = this.secret + return this.#login ??= (async () => { + const response = await this.#transport.fetch(new URL("/api/auth/login", this.origin), { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ username: secret.username, password: secret.password }), + signal: AbortSignal.any([AbortSignal.timeout(CALL_TIMEOUT_MS), ...(signal ? [signal] : [])]), + }) + await response.body?.cancel().catch(() => {}) + if (response.status === 401 || response.status === 400) { this.options.onRejected?.(); throw new CodeNomadServerError("auth") } + if (!response.ok) throw new CodeNomadServerError("unreachable") + })().finally(() => { this.#login = undefined }) + } + + /** Authenticated call. A 401 means the remote did not process the request: log in again and retry once. */ + async fetch(path: string, init: RequestInit = {}): Promise { + const url = new URL(path, this.origin) + if (url.origin !== this.origin) throw new CodeNomadServerError("unreachable") + if (this.secret?.kind === "password" && !this.#cookies.size) await this.login(init.signal ?? undefined) + let response = await this.#transport.fetch(url, init) + if (response.status === 401 && this.secret?.kind === "password") { + await response.body?.cancel().catch(() => {}) + this.#cookies.clear() + await this.login(init.signal ?? undefined) + response = await this.#transport.fetch(url, init) + } + if (response.status === 401) { + await response.body?.cancel().catch(() => {}) + this.options.onRejected?.() + throw new CodeNomadServerError(this.secret ? "auth" : "needs_credentials") + } + return response + } + + /** Bounded JSON read of a fixed backend route. */ + async json(path: string, init: RequestInit = {}): Promise<{ status: number; body: T | undefined }> { + const signal = AbortSignal.any([AbortSignal.timeout(CALL_TIMEOUT_MS), ...(init.signal ? [init.signal] : [])]) + const response = await this.fetch(path, { ...init, signal }) + const reader = response.body?.getReader() + const chunks: Uint8Array[] = [] + let length = 0 + if (reader) { + try { + while (true) { + const chunk = await reader.read() + if (chunk.done) break + length += chunk.value.byteLength + if (length > READ_LIMIT_BYTES) throw new CodeNomadServerError("unreachable") + chunks.push(chunk.value) + } + } catch (error) { await reader.cancel().catch(() => {}); throw error } + } + let body: T | undefined + try { body = length ? JSON.parse(Buffer.concat(chunks, length).toString("utf8")) as T : undefined } catch { body = undefined } + return { status: response.status, body } + } + +} diff --git a/packages/server/src/codenomad-servers/credentials.ts b/packages/server/src/codenomad-servers/credentials.ts new file mode 100644 index 0000000000..84610853d6 --- /dev/null +++ b/packages/server/src/codenomad-servers/credentials.ts @@ -0,0 +1,67 @@ +import fs from "node:fs" +import path from "node:path" + +/** How this backend authenticates to a relayed CodeNomad server. */ +export type CodeNomadServerSecret = + | { kind: "password"; username: string; password: string; cookie?: string } + | { kind: "device"; cookie: string } + | { kind: "session"; cookie: string } + +type Entry = { origin: string; secret: CodeNomadServerSecret } + +function validEntry(value: unknown): value is Entry { + if (!value || typeof value !== "object") return false + const entry = value as { origin?: unknown; secret?: Record } + if (typeof entry.origin !== "string" || !entry.secret || typeof entry.secret !== "object") return false + const secret = entry.secret + if (secret.kind === "password") return typeof secret.username === "string" && typeof secret.password === "string" && (secret.cookie === undefined || typeof secret.cookie === "string") + return (secret.kind === "device" || secret.kind === "session") && typeof secret.cookie === "string" +} + +/** Backend-only, mode 0600, beside the profile's config and never inside it. Kept across + * launches (password or Remote Control device cookie) until removal or a refused credential. + * Never logged, never returned to a browser or a paired device. */ +export class CodeNomadServerCredentials { + #entries = new Map() + + constructor(private readonly filePath: string) { + try { + const value = JSON.parse(fs.readFileSync(filePath, "utf8")) as { servers?: Record } + for (const [id, entry] of Object.entries(value.servers ?? {})) if (validEntry(entry)) this.#entries.set(id, entry) + } catch { /* No server yet, or an unreadable file: adding the server again replaces it. */ } + } + + /** The secret, only for the exact origin it was obtained from. */ + read(serverId: string, origin: string): CodeNomadServerSecret | undefined { + const entry = this.#entries.get(serverId) + if (!entry) return undefined + if (entry.origin !== origin) { this.delete(serverId); return undefined } + return { ...entry.secret } + } + + has(serverId: string, origin: string): boolean { + return this.#entries.get(serverId)?.origin === origin + } + + set(serverId: string, origin: string, secret: CodeNomadServerSecret): void { + const next = new Map(this.#entries).set(serverId, { origin, secret: { ...secret } }) + this.persist(next) + this.#entries = next + } + + delete(serverId: string): void { + if (!this.#entries.has(serverId)) return + const next = new Map(this.#entries) + next.delete(serverId) + this.persist(next) + this.#entries = next + } + + private persist(entries: Map): void { + fs.mkdirSync(path.dirname(this.filePath), { recursive: true }) + const temporary = `${this.filePath}.${process.pid}.tmp` + fs.writeFileSync(temporary, `${JSON.stringify({ servers: Object.fromEntries(entries) })}\n`, { mode: 0o600 }) + fs.chmodSync(temporary, 0o600) + fs.renameSync(temporary, this.filePath) + } +} diff --git a/packages/server/src/codenomad-servers/folders.ts b/packages/server/src/codenomad-servers/folders.ts new file mode 100644 index 0000000000..db30b6bdb9 --- /dev/null +++ b/packages/server/src/codenomad-servers/folders.ts @@ -0,0 +1,40 @@ +import type { FileSystemEntry, FileSystemListResponse } from "../api-types" +import { z } from "zod" + +const MAX_ENTRIES = 2_000 +const RemotePath = z.string().max(8192) +const Listing = z.object({ + entries: z.array(z.object({ name: z.string().max(1024), path: RemotePath, absolutePath: RemotePath.optional(), type: z.enum(["directory", "file"]) })).max(MAX_ENTRIES), + metadata: z.object({ scope: z.enum(["restricted", "unrestricted"]), currentPath: RemotePath, parentPath: RemotePath.optional(), + rootPath: RemotePath, homePath: RemotePath, displayPath: RemotePath, pathKind: z.enum(["relative", "absolute", "drives"]) }), +}) + +function joinRemote(root: string, relative: string): string { + if (relative === "." || relative === "") return root + const separator = /^[A-Za-z]:\\/.test(root) && !root.includes("/") ? "\\" : "/" + const base = root.replace(/[\\/]+$/, "") + return `${base}${separator}${relative.split("/").join(separator)}` +} + +/** The remote's folder listing with absolute paths only (a restricted root answers relative ones), + * folders only, in the shape the folder browser reads. */ +export function relayedFolderListing(input: unknown): FileSystemListResponse { + const value = Listing.parse(input) + const metadata = value?.metadata + if (!metadata || typeof metadata.currentPath !== "string" || !Array.isArray(value.entries)) throw new Error("Invalid remote folder listing") + const relative = metadata.pathKind === "relative" + const currentPath = relative ? (typeof metadata.displayPath === "string" ? metadata.displayPath : joinRemote(metadata.rootPath, metadata.currentPath)) : metadata.currentPath + const parentPath = metadata.parentPath === undefined ? undefined : relative ? joinRemote(metadata.rootPath, metadata.parentPath) : metadata.parentPath + const entries: FileSystemEntry[] = [] + for (const entry of value.entries) { + if (entries.length >= MAX_ENTRIES) break + if (entry?.type !== "directory" || typeof entry.name !== "string") continue + const absolute = typeof entry.absolutePath === "string" ? entry.absolutePath : relative ? joinRemote(metadata.rootPath, entry.path) : entry.path + if (typeof absolute !== "string") continue + entries.push({ name: entry.name, path: absolute, absolutePath: absolute, type: "directory" }) + } + return { + entries, + metadata: { ...metadata, currentPath, ...(parentPath === undefined ? { parentPath: undefined } : { parentPath }), displayPath: currentPath, pathKind: metadata.pathKind === "drives" ? "drives" : "absolute" }, + } +} diff --git a/packages/server/src/codenomad-servers/test-support/fake-codenomad.ts b/packages/server/src/codenomad-servers/test-support/fake-codenomad.ts new file mode 100644 index 0000000000..988aac57dd --- /dev/null +++ b/packages/server/src/codenomad-servers/test-support/fake-codenomad.ts @@ -0,0 +1,61 @@ +import { randomUUID } from "node:crypto" +import { once } from "node:events" +import { createServer, type IncomingHttpHeaders, type RequestListener } from "node:http" +import { createServer as createHttpsServer, type ServerOptions } from "node:https" + +export type RecordedRequest = { method: string; path: string; headers: IncomingHttpHeaders; body: string } + +/** A real direct-listener HTTP(S) remote, with expirable authentication and bounded browsing routes. */ +export async function startFakeCodeNomad(options: { password?: string; root?: string; tls?: ServerOptions; anonymous?: boolean } = {}) { + const state = { + password: options.password ?? "remote-password", sessions: new Set(), logins: 0, + requests: [] as RecordedRequest[], + overrides: new Map }>(), + recents: [{ path: "/srv/projects/app", projectName: "App", lastAccessed: 42, password: "must-not-leak" }], + } + const root = options.root ?? "/srv/projects" + const listener: RequestListener = async (request, response) => { + const url = new URL(request.url ?? "/", "http://fake") + let body = "" + for await (const chunk of request) body += chunk + state.requests.push({ method: request.method!, path: `${url.pathname}${url.search}`, headers: request.headers, body }) + const json = (status: number, value: unknown, headers: Record = {}) => { + response.writeHead(status, { "content-type": "application/json", ...headers }); response.end(JSON.stringify(value)) + } + const override = state.overrides.get(url.pathname) + if (override) return json(override.status, override.body, override.headers) + if (url.pathname === "/api/auth/login" && request.method === "POST") { + state.logins++ + const { username, password } = JSON.parse(body || "{}") + if (username !== "codenomad" || password !== state.password) return json(401, { error: "Invalid credentials" }) + const session = randomUUID() + state.sessions.add(session) + return json(200, { ok: true }, { "set-cookie": `codenomad_session=${session}; HttpOnly; Path=/; SameSite=Lax` }) + } + const cookies = Object.fromEntries((request.headers.cookie ?? "").split(/;\s*/).filter(Boolean).map(pair => pair.split("=", 2) as [string, string])) + const authenticated = options.anonymous || state.sessions.has(cookies.codenomad_session ?? "") + if (url.pathname === "/api/auth/status") return json(200, { authenticated }) + if (!authenticated) return json(401, { error: "Unauthorized" }) + if (url.pathname === "/api/storage/state/ui") return json(200, { recentFolders: state.recents, password: "must-not-leak" }) + if (url.pathname === "/api/filesystem") { + const relative = url.searchParams.get("path") ?? "." + const current = relative.startsWith(root) ? relative.slice(root.length).replace(/^\//, "") || "." : relative + return json(200, { + entries: [{ name: "app", path: current === "." ? "app" : `${current}/app`, absolutePath: `${root}/${current === "." ? "" : `${current}/`}app`, type: "directory", password: "must-not-leak" }, + { name: "README.md", path: "README.md", type: "file" }], + metadata: { scope: "restricted", currentPath: current, ...(current === "." ? {} : { parentPath: "." }), rootPath: root, homePath: root, + displayPath: current === "." ? root : `${root}/${current}`, pathKind: "relative", password: "must-not-leak" }, + }) + } + json(404, { error: "Not found" }) + } + const server = options.tls ? createHttpsServer(options.tls, listener) : createServer(listener) + server.listen(0, "127.0.0.1") + await once(server, "listening") + const origin = `${options.tls ? "https" : "http"}://127.0.0.1:${(server.address() as { port: number }).port}` + return { + origin, state, + restart() { state.sessions.clear() }, + async close() { server.closeAllConnections(); await new Promise(resolve => server.close(() => resolve())) }, + } +} diff --git a/packages/server/src/opencode/servers/endpoint.ts b/packages/server/src/opencode/servers/endpoint.ts new file mode 100644 index 0000000000..e4d8940f95 --- /dev/null +++ b/packages/server/src/opencode/servers/endpoint.ts @@ -0,0 +1,21 @@ +import { lookup } from "node:dns/promises" +import { isIP } from "node:net" + +import { admitAddress, ExplicitEndpointError, normalizeExplicitOrigin } from "./origin" +export { admitAddress, ExplicitEndpointError, normalizeExplicitOrigin, type EndpointErrorCode } from "./origin" + +export type ResolveAddresses = (hostname: string) => Promise +export const resolveAddresses: ResolveAddresses = hostname => lookup(hostname, { all: true, verbatim: true }) + +/** Validate every answer and return the exact address the dialer must use. */ +export async function resolveExplicitAddress(origin: string, resolve: ResolveAddresses = resolveAddresses, allowHttp = false) { + const url = new URL(normalizeExplicitOrigin(origin, allowHttp)) + const hostname = url.hostname.replace(/^\[|\]$/g, "") + let answers: readonly { address: string; family: number }[] + try { answers = isIP(hostname) ? [{ address: hostname, family: isIP(hostname) }] : await resolve(hostname) } + catch { throw new ExplicitEndpointError("dns") } + if (!answers.length) throw new ExplicitEndpointError("dns") + const admitted = answers.map(answer => admitAddress(answer.address)) + if (!allowHttp && url.protocol === "http:" && admitted.some(answer => !answer.loopback)) throw new ExplicitEndpointError("https_required") + return admitted[0]! +} diff --git a/packages/server/src/opencode/servers/origin.ts b/packages/server/src/opencode/servers/origin.ts new file mode 100644 index 0000000000..f60b5aec00 --- /dev/null +++ b/packages/server/src/opencode/servers/origin.ts @@ -0,0 +1,63 @@ +import { isIP } from "node:net" + +export type EndpointErrorCode = "invalid_origin" | "forbidden_address" | "https_required" | "dns" | "network" | "tls" | "redirect" | "timeout" | "response_limit" | "probe_path" | "custom_ca_unsupported" + +/** Diagnostics contain only a stable code, never a URL, credential or upstream error. */ +export class ExplicitEndpointError extends Error { + constructor(readonly code: EndpointErrorCode) { super(code); this.name = "ExplicitEndpointError" } +} + +function ipv4(address: string): number[] | undefined { + if (isIP(address) === 4) return address.split(".").map(Number) + if (isIP(address) !== 6) return + const parts = address.split("::") + const left = parts[0] ? parts[0].split(":") : [] + const right = parts[1] ? parts[1].split(":") : [] + const words = [...left, ...Array(8 - left.length - right.length).fill("0"), ...right].map(word => parseInt(word, 16)) + if (words.slice(0, 5).every(word => word === 0) && words[5] === 0xffff) { + return [words[6]! >> 8, words[6]! & 255, words[7]! >> 8, words[7]! & 255] + } +} + +export function admitAddress(input: string): { address: string; family: 4 | 6; loopback: boolean } { + if (!isIP(input)) throw new ExplicitEndpointError("forbidden_address") + const address = isIP(input) === 6 ? new URL(`http://[${input}]/`).hostname.slice(1, -1) : input + const v4 = ipv4(address) + let loopback = false + if (v4) { + const [a, b, c, d] = v4 as [number, number, number, number] + loopback = a === 127 + if (a === 0 || a >= 224 || (a === 169 && b === 254) + || (a === 100 && b >= 64 && b <= 127) + || (a === 168 && b === 63 && c === 129 && d === 16)) throw new ExplicitEndpointError("forbidden_address") + } else { + loopback = address === "::1" + // Global unicast and private ULA only; transition/link-local/site-local ranges fail closed. + const first = parseInt(address.split(":")[0]!, 16) + if (!loopback && !((first >= 0x2000 && first <= 0x3fff) || (first >= 0xfc00 && first <= 0xfdff))) { + throw new ExplicitEndpointError("forbidden_address") + } + if (address === "fd00:ec2::254" || address.startsWith("2002:") || address.startsWith("2001:0:") || address.startsWith("2001::")) throw new ExplicitEndpointError("forbidden_address") + } + return { address, family: isIP(address) as 4 | 6, loopback } +} + +/** Synchronous origin validation shared by registry metadata and network admission. */ +export function normalizeExplicitOrigin(value: string, allowHttp = false): string { + let url: URL + try { + // Inspect the supplied syntax before WHATWG normalization can erase dot paths or empty delimiters. + if (!/^https?:\/\/[^/?#\\\s]+\/?$/i.test(value)) throw new Error() + url = new URL(value) + if (url.username || url.password || value.includes("@") || url.pathname !== "/" || url.search || url.hash) throw new Error() + } catch { throw new ExplicitEndpointError("invalid_origin") } + const hostname = url.hostname.replace(/^\[|\]$/g, "") + if (isIP(hostname)) { + const admitted = admitAddress(hostname) + if (!allowHttp && url.protocol === "http:" && !admitted.loopback) throw new ExplicitEndpointError("https_required") + } else { + if (hostname === "*" || hostname.includes("*") || !hostname) throw new ExplicitEndpointError("invalid_origin") + if (!allowHttp && url.protocol === "http:" && hostname !== "localhost") throw new ExplicitEndpointError("https_required") + } + return url.origin +} diff --git a/packages/server/src/opencode/servers/transport.ts b/packages/server/src/opencode/servers/transport.ts new file mode 100644 index 0000000000..f938e3a54c --- /dev/null +++ b/packages/server/src/opencode/servers/transport.ts @@ -0,0 +1,105 @@ +import { Agent, fetch as undiciFetch } from "undici" +import { ExplicitEndpointError, normalizeExplicitOrigin, resolveExplicitAddress, type ResolveAddresses } from "./endpoint" + +const requestDenied = /^(origin|authorization|proxy-authorization|cookie|cookie2|host|forwarded|x-forwarded-.*|x-real-ip|connection|keep-alive|proxy-connection|te|trailer|transfer-encoding|upgrade)$/i +const responseDenied = /^(authorization|proxy-authorization|cookie|set-cookie2?|www-authenticate|proxy-authenticate|authentication-info|proxy-authentication-info|server|x-powered-by|connection|keep-alive|proxy-connection|te|trailer|transfer-encoding|upgrade)$/i + +function filterHeaders(input: Headers, denied: RegExp): Headers { + const headers = new Headers(input) + for (const name of (input.get("connection") ?? "").split(",")) if (name.trim()) headers.delete(name.trim()) + for (const name of [...headers.keys()]) if (denied.test(name)) headers.delete(name) + return headers +} + +function diagnostic(error: unknown, signal: AbortSignal): ExplicitEndpointError { + if (error instanceof ExplicitEndpointError) return error + if (signal.aborted) return new ExplicitEndpointError("timeout") + const code = (error as { cause?: { code?: string }; code?: string })?.cause?.code ?? (error as { code?: string })?.code ?? "" + return new ExplicitEndpointError(/CERT|TLS|SSL|SELF_SIGNED|UNABLE_TO_VERIFY/.test(code) ? "tls" : "network") +} + +function abortable(promise: Promise, signal: AbortSignal): Promise { + return new Promise((resolve, reject) => { + const abort = () => reject(new ExplicitEndpointError("timeout")) + if (signal.aborted) { abort(); return } + signal.addEventListener("abort", abort, { once: true }) + promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort)) + }) +} + +/** Internal backend seam. All explicit HTTP dispatches, including probes, use this fetch. */ +export function createExplicitTransport(options: { + origin: string + credentials?: { username: string; password: string } + signal?: AbortSignal + ca?: string + /** Saved CodeNomad profiles explicitly permit direct HTTP and optional private TLS. */ + allowHttp?: boolean + skipTlsVerify?: boolean + /** Backend-held cookies, set after filtering. */ + headers?: () => Record + /** Receives Set-Cookie values; they never reach the returned response. */ + onSetCookie?: (values: string[]) => void +}, resolve?: ResolveAddresses) { + const origin = normalizeExplicitOrigin(options.origin, options.allowHttp) + if (options.ca !== undefined) throw new ExplicitEndpointError("custom_ca_unsupported") + // Copy secret inputs; subsequent caller mutation cannot retarget credentials. + const credentials = options.credentials ? { ...options.credentials } : undefined + if (credentials?.username.includes(":")) throw new ExplicitEndpointError("invalid_origin") + const lifetime = options.signal ?? new AbortController().signal + const fetch: typeof globalThis.fetch = async (input, init) => { + let agent: Agent | undefined + let signal = lifetime + try { + const request = new Request(input, init) + const url = new URL(request.url) + if (url.origin !== origin || url.username || url.password || url.hash) throw new ExplicitEndpointError("invalid_origin") + signal = AbortSignal.any([lifetime, request.signal]) + signal.throwIfAborted() + const address = await abortable(resolveExplicitAddress(origin, resolve, options.allowHttp), signal) + signal.throwIfAborted() + agent = new Agent({ connect: { + rejectUnauthorized: !options.skipTlsVerify, + // No second DNS query: TLS still verifies the original hostname and sends its SNI. + lookup: (_hostname, options, callback) => { + if (options.all) callback(null, [{ address: address.address, family: address.family }] as never) + else callback(null, address.address, address.family) + }, + } }) + const headers = filterHeaders(request.headers, requestDenied) + if (credentials) headers.set("authorization", `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString("base64")}`) + for (const [name, value] of Object.entries(options.headers?.() ?? {})) if (name.toLowerCase() !== "origin") headers.set(name, value) + const response = await undiciFetch(url, { + method: request.method, headers: Object.fromEntries(headers), + body: request.body as never, duplex: "half", signal, redirect: "manual", dispatcher: agent, + }) + signal.throwIfAborted() + if (response.status >= 300 && response.status < 400 && response.status !== 304) { + void response.body?.cancel().catch(() => {}) + throw new ExplicitEndpointError("redirect") + } + const cookies = response.headers.getSetCookie() + if (response.ok && cookies.length) options.onSetCookie?.(cookies) + const responseHeaders = filterHeaders(new Headers([...response.headers]), responseDenied) + const owner = agent + if (!response.body) { void owner.destroy().catch(() => {}); return new Response(null, { status: response.status, headers: responseHeaders }) } + const reader = response.body.getReader() + let cleaned = false + const cleanup = () => { if (cleaned) return; cleaned = true; reader.releaseLock(); void owner.destroy().catch(() => {}) } + const body = new ReadableStream({ + async pull(controller) { + try { + const chunk = await reader.read() + signal.throwIfAborted() + if (chunk.done) { controller.close(); cleanup() } + else controller.enqueue(chunk.value) + } catch (error) { controller.error(diagnostic(error, signal)); cleanup() } + }, + cancel() { void reader.cancel().catch(() => {}); cleanup() }, + }) + return new Response(body, { status: response.status, headers: responseHeaders }) + } catch (error) { void agent?.destroy().catch(() => {}); throw diagnostic(error, signal) } + } + + return { origin, fetch } +} diff --git a/packages/server/src/server/__tests__/integration-request-logging.test.ts b/packages/server/src/server/__tests__/integration-request-logging.test.ts index 51fb22fbc8..dad3b190c9 100644 --- a/packages/server/src/server/__tests__/integration-request-logging.test.ts +++ b/packages/server/src/server/__tests__/integration-request-logging.test.ts @@ -39,6 +39,13 @@ function harness(level: "debug" | "trace") { } for (const level of ["debug", "trace"] as const) { + test(`${level}: remote server connection credentials never enter request logs`, async t => { + const f = harness(level) + t.after(() => f.app.close()) + f.app.post('/api/remote-servers/:id/connect', () => ({ ok: true })) + await f.app.inject({ method: 'POST', url: '/api/remote-servers/saved/connect', payload: { username: secret, password: secret, pairingLink: secret } }) + f.check() + }) test(`${level}: plugin source configuration and error diagnostics remain private`, async t => { const f = harness(level) t.after(() => f.app.close()) diff --git a/packages/server/src/server/http-server.ts b/packages/server/src/server/http-server.ts index 15f21fbf6f..bcab4a2dc1 100644 --- a/packages/server/src/server/http-server.ts +++ b/packages/server/src/server/http-server.ts @@ -38,6 +38,8 @@ import { registerSpeechRoutes } from "./routes/speech" import { registerOpenCodeUpdateRoutes } from "./routes/opencode-update" import { registerRemoteControlRoutes } from "./routes/remote-control" import { registerRemoteServerRoutes } from "./routes/remote-servers" +import { registerRemoteServerBrowseRoutes } from "./routes/remote-server-browse" +import { RemoteServerBrowseManager } from "../codenomad-servers/browse-manager" import { registerRemoteProxyRoutes } from "./routes/remote-proxy" import { registerSideCarRoutes } from "./routes/sidecars" import { registerPreviewRoutes } from "./routes/previews" @@ -397,6 +399,9 @@ export function createHttpServer(deps: HttpServerDeps) { workspaceManager: deps.workspaceManager, }) registerRemoteServerRoutes(app, { logger: apiLogger }) + const remoteServerBrowse = new RemoteServerBrowseManager(deps.settings) + registerRemoteServerBrowseRoutes(app, { manager: remoteServerBrowse, getSelfOrigins }) + app.addHook("onClose", async () => remoteServerBrowse.close()) registerRemoteProxyRoutes(app, { logger: proxyLogger, sessionManager: deps.remoteProxySessionManager }) registerRemoteControlRoutes(app, { manager: deps.remoteControlManager }) registerSpeechRoutes(app, { speechService: deps.speechService }) diff --git a/packages/server/src/server/request-logging.ts b/packages/server/src/server/request-logging.ts index 901845b5c0..bab8d16f8a 100644 --- a/packages/server/src/server/request-logging.ts +++ b/packages/server/src/server/request-logging.ts @@ -37,7 +37,7 @@ export function registerRequestLogging(app: FastifyInstance, apiLogger: Logger) ...base, params: redactSecrets(request.params), query: redactSecrets(request.query), - body: typeof request.body === "string" || request.url.startsWith("/api/panel-extensions") ? "" : redactSecrets(request.body), + body: typeof request.body === "string" || request.url.startsWith("/api/panel-extensions") || request.url.startsWith("/api/remote-servers/") ? "" : redactSecrets(request.body), }, "HTTP request payload") } done() @@ -54,6 +54,6 @@ export function redactSecrets(value: unknown): unknown { || isHumanAnswerProofPayload(value as Record)) return "" return Object.fromEntries(Object.entries(value).map(([key, entry]) => [ key, - /(authorization|cookie|key|code|token|password|secret|principal)/i.test(key) ? "" : redactSecrets(entry), + /(authorization|cookie|key|code|token|password|secret|principal|pairingLink)/i.test(key) ? "" : redactSecrets(entry), ])) } diff --git a/packages/server/src/server/routes/remote-server-browse.ts b/packages/server/src/server/routes/remote-server-browse.ts new file mode 100644 index 0000000000..717c1b6d16 --- /dev/null +++ b/packages/server/src/server/routes/remote-server-browse.ts @@ -0,0 +1,34 @@ +import type { FastifyInstance } from "fastify" +import { isLocalRequest } from "../../remote-control/request-origin" +import { BrowseBody, ConnectBody, type RemoteServerBrowseManager } from "../../codenomad-servers/browse-manager" +import { endpointErrorCode } from "../../codenomad-servers/client" + +export function registerRemoteServerBrowseRoutes(app: FastifyInstance, deps: { + manager: RemoteServerBrowseManager + getSelfOrigins(): Set +}) { + // This guard is deliberately stricter than CORS and runs before body parsing or secret/network access. + for (const action of ["browse", "connect", "forget"] as const) { + app.post<{ Params: { id: string } }>(`/api/remote-servers/:id/${action}`, { + bodyLimit: 24 * 1024, + onRequest: async (request, reply) => { + const origin = request.headers.origin + if (!isLocalRequest(request) || !origin || origin === "null" || !deps.getSelfOrigins().has(origin)) { + return reply.code(403).send({ error: "auth" }) + } + reply.header("Cache-Control", "no-store") + }, + }, async (request, reply) => { + try { + const id = request.params.id + if (!id || id.length > 256) return reply.code(404).send({ error: "unknown_server" }) + if (action === "forget") return await deps.manager.forget(id) + if (action === "connect") return await deps.manager.connect(id, ConnectBody.parse(request.body ?? {})) + return await deps.manager.browse(id, BrowseBody.parse(request.body ?? {})) + } catch (error) { + const code = endpointErrorCode(error) + return reply.code(code === "unknown_server" ? 404 : code === "needs_credentials" || code === "auth" || code === "pairing_unavailable" ? 409 : 502).send({ error: code }) + } + }) + } +} diff --git a/packages/ui/src/components/browse-menu.tsx b/packages/ui/src/components/browse-menu.tsx index f3889afbcb..dbb0c3f0a2 100644 --- a/packages/ui/src/components/browse-menu.tsx +++ b/packages/ui/src/components/browse-menu.tsx @@ -1,4 +1,4 @@ -import { For, Show, createMemo, createSignal, createUniqueId, onMount } from "solid-js" +import { For, Show, createEffect, createMemo, createSignal, createUniqueId, onMount } from "solid-js" import { ChevronRight, Globe, Laptop, Server } from "lucide-solid" import type { RemoteServerProfile, SideCar } from "../../../server/src/api-types" import { useI18n } from "../lib/i18n" @@ -8,6 +8,9 @@ import { useRemoteServerProfiles } from "../lib/hooks/use-remote-server-profiles import { canOpenRemoteWindows } from "../lib/runtime-env" import { openSidecar } from "../stores/sidecar-open" import ServerAddField from "./server-add-field" +import RemoteServerBrowser from "./remote-server-browser" +import { openRemoteProject, opensRemoteProjectTab } from "../stores/remote-project-open" +import { embeddedProjectUrl } from "../lib/embed-mode" import { remoteServers as savedServers } from "../stores/preferences" import { ensureSidecarsLoaded, sidecars } from "../stores/sidecars" @@ -38,6 +41,8 @@ export const browseEntryCount = () => 1 + (canOpenRemoteWindows() ? savedServers export default function BrowseMenu(props: BrowseMenuProps) { const { t } = useI18n() const { remoteServers, openServer } = useRemoteServerProfiles() + const [selectedServer, setSelectedServer] = createSignal() + createEffect(() => { if (selectedServer() && !remoteServers().some(profile => profile.id === selectedServer()!.id)) setSelectedServer(undefined) }) const bodyId = createUniqueId() let toggleRef: HTMLButtonElement | undefined let bodyRef: HTMLDivElement | undefined @@ -75,13 +80,22 @@ export default function BrowseMenu(props: BrowseMenuProps) { else if (event.key === "ArrowUp") move(index - 1) else if (event.key === "Home" && !inField) move(0) else if (event.key === "End" && !inField) move(items.length - 1) - else if (event.key === "Escape" && !props.alwaysOpen) { + else if (event.key === "Escape" && selectedServer()) { + event.preventDefault() + backToRoot() + } else if (event.key === "Escape" && !props.alwaysOpen) { event.preventDefault() setExpanded(false) toggleRef?.focus() } } + function backToRoot() { + const id = selectedServer()?.id + setSelectedServer(undefined) + queueMicrotask(() => bodyRef?.querySelector(`[data-remote-server="${CSS.escape(id ?? "")}"]`)?.focus()) + } + const sidecarRunning = (sidecar: SideCar) => sidecar.status === "running" return ( @@ -97,6 +111,12 @@ export default function BrowseMenu(props: BrowseMenuProps) {
+ {(profile) => run(() => { + if (opensRemoteProjectTab(profile())) openRemoteProject(profile().id, { folder }) + else openServer(profile(), embeddedProjectUrl(profile().baseUrl, folder)) + })} />} +
diff --git a/packages/ui/src/components/remote-server-browser.tsx b/packages/ui/src/components/remote-server-browser.tsx new file mode 100644 index 0000000000..e61e1304df --- /dev/null +++ b/packages/ui/src/components/remote-server-browser.tsx @@ -0,0 +1,112 @@ +import { For, Show, createSignal, onCleanup, onMount } from "solid-js" +import { ArrowLeft, ArrowUp, Folder, Loader2 } from "lucide-solid" +import type { RemoteServerBrowseResponse, RemoteServerProfile } from "../../../server/src/api-types" +import { serverApi } from "../lib/api-client" +import { useI18n } from "../lib/i18n" +import { getProjectDisplayName } from "../lib/recent-folder-display" + +/** Remote metadata is read by the local backend; only this component's password input holds entered text. */ +export default function RemoteServerBrowser(props: { + profile: RemoteServerProfile + onBack: () => void + onSelect: (folder: string) => void +}) { + const { t } = useI18n() + const [result, setResult] = createSignal() + const [busy, setBusy] = createSignal(false) + const [error, setError] = createSignal("") + const [username, setUsername] = createSignal("codenomad") + let password: HTMLInputElement | undefined + let root: HTMLDivElement | undefined + let controller: AbortController | undefined + let generation = 0 + const needsCredentials = () => error() === "needs_credentials" || error() === "auth" + function failure(value: unknown) { + const code = value instanceof Error ? value.message : "unreachable" + setError(["needs_credentials", "auth", "pairing_unavailable", "tls_error"].includes(code) ? code : "unreachable") + if (needsCredentials()) queueMicrotask(() => password?.focus()) + } + async function browse(path?: string) { + controller?.abort() + controller = new AbortController() + const current = ++generation + setBusy(true) + setError("") + try { + const value = await serverApi.browseRemoteServer(props.profile.id, path, controller.signal) + if (current !== generation) return + setResult(value) + queueMicrotask(() => root?.querySelector("[data-remote-folder]")?.focus()) + } catch (error) { if (current === generation) failure(error) } + finally { if (current === generation) setBusy(false) } + } + async function connect(event: SubmitEvent) { + event.preventDefault() + if (busy() || !password?.value) return + setBusy(true) + const current = generation + const entered = password.value + password.value = "" + try { + await serverApi.connectRemoteServer(props.profile.id, { username: username(), password: entered }) + if (current === generation) await browse(result()?.listing.metadata.currentPath) + } catch (error) { if (current === generation) failure(error) } + finally { if (current === generation) setBusy(false) } + } + onMount(() => void browse()) + onCleanup(() => { ++generation; controller?.abort(); if (password) password.value = "" }) + return ( +
+ + + + + + + + + + + + + {(value) => { + const listing = () => value().listing + return <> +
{listing().metadata.displayPath}
+ + + + + + + {(recent) => + + } + {(entry) => + + } + + }} +
+
+ ) +} diff --git a/packages/ui/src/components/server-add-field.tsx b/packages/ui/src/components/server-add-field.tsx index dee364a5d8..384a7e39e4 100644 --- a/packages/ui/src/components/server-add-field.tsx +++ b/packages/ui/src/components/server-add-field.tsx @@ -59,6 +59,13 @@ export default function ServerAddField(props: ServerAddFieldProps) { reset() props.onAdded?.(profile.id) } catch (failure) { + if (failure instanceof Error && failure.message === "pairing_unavailable") { + reset() + setError(t("remoteBrowse.pairingUnavailable")) + const saved = remoteServers().find(server => server.baseUrl === link.baseUrl) + if (saved) props.onAdded?.(saved.id) + return + } setError(failure instanceof Error && failure.message ? failure.message : t("folderSelection.servers.dialog.errorConnect")) const tls = failure instanceof RemoteServerProbeError && failure.code === "tls_error" && link.kind === "address" setTlsFailedFor(tls ? link.baseUrl : undefined) diff --git a/packages/ui/src/lib/api-client.ts b/packages/ui/src/lib/api-client.ts index acf16d3d44..c8a9276238 100644 --- a/packages/ui/src/lib/api-client.ts +++ b/packages/ui/src/lib/api-client.ts @@ -45,6 +45,7 @@ import type { RemoteProxySessionCreateResponse, RemoteServerProbeRequest, RemoteServerProbeResponse, + RemoteServerBrowseResponse, RemoteControlDevice, RemoteControlPairing, RemoteControlStartResponse, @@ -245,6 +246,15 @@ async function requestRaw(path: string, init?: RequestInit): Promise { export const serverApi = { + browseRemoteServer(id: string, path?: string, signal?: AbortSignal): Promise { + return request(`/api/remote-servers/${encodeURIComponent(id)}/browse`, { method: "POST", body: JSON.stringify({ path }), signal }) + }, + connectRemoteServer(id: string, credentials: { username?: string; password?: string; pairingLink?: string }): Promise<{ ok: boolean }> { + return request(`/api/remote-servers/${encodeURIComponent(id)}/connect`, { method: "POST", body: JSON.stringify(credentials) }) + }, + forgetRemoteServer(id: string): Promise<{ ok: boolean }> { + return request(`/api/remote-servers/${encodeURIComponent(id)}/forget`, { method: "POST", body: "{}" }) + }, fetchPermissionReceipts(instanceId: string, sessionId: string, scope: { messageId: string } | { unanchored: true }, cursor?: string, signal?: AbortSignal): Promise { const params = new URLSearchParams("messageId" in scope ? { messageId: scope.messageId } : { unanchored: "true" }) if (cursor) params.set("cursor", cursor) diff --git a/packages/ui/src/lib/hooks/use-remote-server-profiles.ts b/packages/ui/src/lib/hooks/use-remote-server-profiles.ts index 6211028012..0a8b791a85 100644 --- a/packages/ui/src/lib/hooks/use-remote-server-profiles.ts +++ b/packages/ui/src/lib/hooks/use-remote-server-profiles.ts @@ -19,9 +19,6 @@ export type RemoteServerInput = { skipTlsVerify: boolean } -// Pairing links wait in this renderer until the user opens the saved server. -const pendingPairingEntries = new Map() - /** A failed probe, with the server's reason code (`tls_error` for a certificate that failed the check). */ export class RemoteServerProbeError extends Error { constructor(message: string, readonly code?: string) { @@ -65,11 +62,10 @@ export function useRemoteServerProfiles() { baseUrl: probe.normalizedUrl, skipTlsVerify, }) - if (saved && saved.baseUrl !== profile.baseUrl) pendingPairingEntries.delete(profile.id) return { profile, entryUrl: pairing?.entryUrl } } - const saveServer = async (input: RemoteServerInput, requestedWindow: boolean, windowOptions: RemoteWindowOpenOptions = {}) => { + const saveServer = async (input: RemoteServerInput, requestedWindow: boolean, windowOptions: RemoteWindowOpenOptions = {}, entryUrl?: string) => { const pairing = splitPairingLink(input.baseUrl) const openWindow = requestedWindow if (openWindow && !canOpenRemoteWindows()) { @@ -77,7 +73,6 @@ export function useRemoteServerProfiles() { } const { profile } = await saveProfile(input) - if (pairing) pendingPairingEntries.set(profile.id, pairing.entryUrl) if (openWindow) { const proxySession = @@ -86,8 +81,13 @@ export function useRemoteServerProfiles() { : undefined try { - await openRemoteServerWindow(profile, pendingPairingEntries.get(profile.id) ?? proxySession?.windowUrl, proxySession?.sessionId, windowOptions) - pendingPairingEntries.delete(profile.id) + let target = pairing?.entryUrl ?? entryUrl ?? proxySession?.windowUrl + if (proxySession && entryUrl) { + const bootstrap = new URL(proxySession.windowUrl), entry = new URL(entryUrl) + bootstrap.searchParams.set("returnTo", `${entry.pathname}${entry.search}`) + target = bootstrap.toString() + } + await openRemoteServerWindow(profile, target, proxySession?.sessionId, windowOptions) } catch (error) { if (proxySession) void serverApi.deleteRemoteProxySession(proxySession.sessionId).catch(() => {}) throw error @@ -98,14 +98,14 @@ export function useRemoteServerProfiles() { return profile } - const connectSavedServer = async (id: string) => { + const connectSavedServer = async (id: string, entryUrl?: string) => { if (!canOpenRemoteWindows() || connectingServerId()) return const target = remoteServers().find((server) => server.id === id) if (!target) return setConnectingServerId(id) try { - await saveServer(target, true) + await saveServer(target, true, {}, entryUrl) } catch (error) { showAlertDialog(error instanceof Error ? error.message : String(error), { title: t("folderSelection.servers.errorTitle"), @@ -118,28 +118,29 @@ export function useRemoteServerProfiles() { /** A saved server opens a project tab, or its own window when it cannot (unverified certificate, no tabs here). */ const openServer = (profile: RemoteServerProfile, entryUrl?: string, blankId: string | null = activeBlankTabId() ?? null) => { - entryUrl ??= pendingPairingEntries.get(profile.id) if (opensRemoteProjectTab(profile)) { openRemoteProject(profile.id, entryUrl ? { entryUrl } : {}, blankId) - pendingPairingEntries.delete(profile.id) void markRemoteServerConnected(profile.id).catch(() => {}) } else { - void connectSavedServer(profile.id) + void connectSavedServer(profile.id, entryUrl) } } - /** Saves a server; only an explicit Connect opens it. Pairing entries stay in memory until then. */ + /** Saves a server; backend browsing credentials stay with the local server. */ const submitServer = async (input: RemoteServerInput, open: boolean) => { const blankId = activeBlankTabId() ?? null const { profile, entryUrl } = await saveProfile(input) - if (entryUrl) pendingPairingEntries.set(profile.id, entryUrl) + if (entryUrl) await serverApi.connectRemoteServer(profile.id, { pairingLink: entryUrl }) if (open) openServer(profile, entryUrl, blankId) return profile } // A removed server's project tabs close with it. - const removeServer = (id: string) => { - pendingPairingEntries.delete(id) + const removeServer = async (id: string) => { + try { await serverApi.forgetRemoteServer(id) } catch { + showAlertDialog(t("folderSelection.servers.dialog.errorConnect"), { variant: "warning" }) + return + } closeRemoteProjectTabsForServer(id) removeRemoteServerProfile(id) } diff --git a/packages/ui/src/lib/i18n/messages/de/folderSelection.ts b/packages/ui/src/lib/i18n/messages/de/folderSelection.ts index 3cbd461be9..fb95a49972 100644 --- a/packages/ui/src/lib/i18n/messages/de/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/de/folderSelection.ts @@ -1,4 +1,7 @@ export const folderSelectionMessages = { + "remoteBrowse.back": "Zurück zu Durchsuchen", + "remoteBrowse.pairingUnavailable": "Serverseitige Remote-Control-Kopplung nicht verfügbar.", + "remoteBrowse.tlsError": "Zertifikatsprüfung fehlgeschlagen.", "folderSelection.language.ariaLabel": "Sprache", "folderSelection.logoAlt": "CodeNomad Logo", diff --git a/packages/ui/src/lib/i18n/messages/en/folderSelection.ts b/packages/ui/src/lib/i18n/messages/en/folderSelection.ts index 085d6f9164..33d732cce2 100644 --- a/packages/ui/src/lib/i18n/messages/en/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/en/folderSelection.ts @@ -1,4 +1,7 @@ export const folderSelectionMessages = { + "remoteBrowse.back": "Back to Browse", + "remoteBrowse.pairingUnavailable": "Server-side Remote Control pairing unavailable.", + "remoteBrowse.tlsError": "Certificate check failed.", "folderSelection.language.ariaLabel": "Language", "folderSelection.logoAlt": "CodeNomad logo", diff --git a/packages/ui/src/lib/i18n/messages/es/folderSelection.ts b/packages/ui/src/lib/i18n/messages/es/folderSelection.ts index 5b26cbb8e5..cea776c431 100644 --- a/packages/ui/src/lib/i18n/messages/es/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/es/folderSelection.ts @@ -1,4 +1,7 @@ export const folderSelectionMessages = { + "remoteBrowse.back": "Volver a Explorar", + "remoteBrowse.pairingUnavailable": "Emparejamiento de Control remoto en el servidor no disponible.", + "remoteBrowse.tlsError": "Error al verificar el certificado.", "folderSelection.language.ariaLabel": "Idioma", "folderSelection.logoAlt": "Logo de CodeNomad", diff --git a/packages/ui/src/lib/i18n/messages/fr/folderSelection.ts b/packages/ui/src/lib/i18n/messages/fr/folderSelection.ts index 7d49806732..403432533a 100644 --- a/packages/ui/src/lib/i18n/messages/fr/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/fr/folderSelection.ts @@ -1,4 +1,7 @@ export const folderSelectionMessages = { + "remoteBrowse.back": "Retour à Parcourir", + "remoteBrowse.pairingUnavailable": "Appairage Remote Control côté serveur indisponible.", + "remoteBrowse.tlsError": "Échec de la vérification du certificat.", "folderSelection.language.ariaLabel": "Langue", "folderSelection.logoAlt": "Logo CodeNomad", diff --git a/packages/ui/src/lib/i18n/messages/he/folderSelection.ts b/packages/ui/src/lib/i18n/messages/he/folderSelection.ts index 69f94a47e9..c1a4015b5c 100644 --- a/packages/ui/src/lib/i18n/messages/he/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/he/folderSelection.ts @@ -1,4 +1,7 @@ export const folderSelectionMessages = { + "remoteBrowse.back": "חזרה לעיון", + "remoteBrowse.pairingUnavailable": "צימוד שליטה מרחוק בצד השרת אינו זמין.", + "remoteBrowse.tlsError": "בדיקת התעודה נכשלה.", "folderSelection.language.ariaLabel": "שפה", "folderSelection.logoAlt": "לוגו CodeNomad", diff --git a/packages/ui/src/lib/i18n/messages/ja/folderSelection.ts b/packages/ui/src/lib/i18n/messages/ja/folderSelection.ts index 50dc5e6642..03c7d421ce 100644 --- a/packages/ui/src/lib/i18n/messages/ja/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/ja/folderSelection.ts @@ -1,4 +1,7 @@ export const folderSelectionMessages = { + "remoteBrowse.back": "参照に戻る", + "remoteBrowse.pairingUnavailable": "サーバー側のリモートコントロールのペアリングは利用できません。", + "remoteBrowse.tlsError": "証明書の検証に失敗しました。", "folderSelection.language.ariaLabel": "言語", "folderSelection.logoAlt": "CodeNomad ロゴ", diff --git a/packages/ui/src/lib/i18n/messages/ne/folderSelection.ts b/packages/ui/src/lib/i18n/messages/ne/folderSelection.ts index 350969ea6c..7d226fd33f 100644 --- a/packages/ui/src/lib/i18n/messages/ne/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/ne/folderSelection.ts @@ -1,4 +1,7 @@ export const folderSelectionMessages = { + "remoteBrowse.back": "ब्राउजमा फर्कनुहोस्", + "remoteBrowse.pairingUnavailable": "सर्भरबाट Remote Control pairing उपलब्ध छैन।", + "remoteBrowse.tlsError": "प्रमाणपत्र जाँच असफल भयो।", "folderSelection.language.ariaLabel": "भाषा", "folderSelection.logoAlt": "CodeNomad लोगो", diff --git a/packages/ui/src/lib/i18n/messages/ru/folderSelection.ts b/packages/ui/src/lib/i18n/messages/ru/folderSelection.ts index bb2cac98ea..d119275889 100644 --- a/packages/ui/src/lib/i18n/messages/ru/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/ru/folderSelection.ts @@ -1,4 +1,7 @@ export const folderSelectionMessages = { + "remoteBrowse.back": "Назад к обзору", + "remoteBrowse.pairingUnavailable": "Сопряжение удалённого управления на стороне сервера недоступно.", + "remoteBrowse.tlsError": "Проверка сертификата не пройдена.", "folderSelection.language.ariaLabel": "Язык", "folderSelection.logoAlt": "Логотип CodeNomad", diff --git a/packages/ui/src/lib/i18n/messages/tr/folderSelection.ts b/packages/ui/src/lib/i18n/messages/tr/folderSelection.ts index 696c5c4400..6538f1c2fc 100644 --- a/packages/ui/src/lib/i18n/messages/tr/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/tr/folderSelection.ts @@ -1,4 +1,7 @@ export const folderSelectionMessages = { + "remoteBrowse.back": "Gözat'a dön", + "remoteBrowse.pairingUnavailable": "Sunucu tarafında Uzaktan Kontrol eşleştirmesi kullanılamıyor.", + "remoteBrowse.tlsError": "Sertifika doğrulaması başarısız.", "folderSelection.language.ariaLabel": "Dil", "folderSelection.logoAlt": "CodeNomad logosu", "folderSelection.tagline": "AI ile kod yazmaya başlamak için bir klasör seçin", diff --git a/packages/ui/src/lib/i18n/messages/zh-Hans/folderSelection.ts b/packages/ui/src/lib/i18n/messages/zh-Hans/folderSelection.ts index d9028339f0..4063a1ecec 100644 --- a/packages/ui/src/lib/i18n/messages/zh-Hans/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/zh-Hans/folderSelection.ts @@ -1,4 +1,7 @@ export const folderSelectionMessages = { + "remoteBrowse.back": "返回浏览", + "remoteBrowse.pairingUnavailable": "服务器端远程控制配对不可用。", + "remoteBrowse.tlsError": "证书验证失败。", "folderSelection.language.ariaLabel": "语言", "folderSelection.logoAlt": "CodeNomad 徽标", diff --git a/packages/ui/src/styles/components/remote-server-browser.css b/packages/ui/src/styles/components/remote-server-browser.css new file mode 100644 index 0000000000..67a582c9fc --- /dev/null +++ b/packages/ui/src/styles/components/remote-server-browser.css @@ -0,0 +1,5 @@ +.remote-server-browser { min-width: 0; max-height: 55dvh; overflow: auto; } +.remote-server-browser .browse-menu-meta { max-width: 45%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +.remote-server-signin { display: grid; gap: var(--space-sm); padding: var(--space-sm); } +.remote-server-signin input { background: var(--surface-field); } +.remote-server-path { padding: var(--space-sm); overflow-wrap: anywhere; color: var(--text-muted); font-size: var(--font-size-sm); } diff --git a/packages/ui/src/styles/controls.css b/packages/ui/src/styles/controls.css index 3856154e2a..db975d8c0e 100644 --- a/packages/ui/src/styles/controls.css +++ b/packages/ui/src/styles/controls.css @@ -52,3 +52,4 @@ @import "./components/browse-menu.css"; @import "./components/server-add-field.css"; @import "./components/embedded-project-picker.css"; +@import "./components/remote-server-browser.css"; diff --git a/packages/ui/tests/browser/fixtures/remote-server-pairing-api.ts b/packages/ui/tests/browser/fixtures/remote-server-pairing-api.ts index 7d997f0fa2..f71472d853 100644 --- a/packages/ui/tests/browser/fixtures/remote-server-pairing-api.ts +++ b/packages/ui/tests/browser/fixtures/remote-server-pairing-api.ts @@ -21,3 +21,4 @@ serverApi.probeRemoteServer = async ({ baseUrl, skipTlsVerify }) => { fixture.probes.push(`${baseUrl} skipTls=${Boolean(skipTlsVerify)}`) return { ok: true, reachable: true, normalizedUrl: baseUrl.replace(/\/$/, ""), skipTlsVerify: Boolean(skipTlsVerify), requiresAuth: true, authenticated: false } } +serverApi.connectRemoteServer = async () => { throw Object.assign(new Error("pairing_unavailable"), { status: 409 }) } diff --git a/packages/ui/tests/browser/remote-project-tabs.test.ts b/packages/ui/tests/browser/remote-project-tabs.test.ts index 322bdd01a0..1d9135dadf 100644 --- a/packages/ui/tests/browser/remote-project-tabs.test.ts +++ b/packages/ui/tests/browser/remote-project-tabs.test.ts @@ -34,6 +34,7 @@ interface Scenario { /** A saved native session, restored by a local Electron window. */ restore?: unknown sidecars?: unknown[] + remoteNeedsPassword?: boolean } async function open(page: Page, path: string, scenario: Scenario) { @@ -74,9 +75,28 @@ async function open(page: Page, path: string, scenario: Scenario) { const workspaces: Record[] = [] const probes: string[] = [] let state = uiState + let remoteAuthenticated = !scenario.remoteNeedsPassword + const remoteReads: string[] = [] await page.route(/\/(?:api|workspaces)\//, async route => { const request = route.request() const pathname = new URL(request.url()).pathname + const remote = pathname.match(/^\/api\/remote-servers\/([^/]+)\/(browse|connect|forget)$/) + if (remote) { + const body = request.postDataJSON() ?? {} + if (remote[2] === 'forget') return route.fulfill({ json: { ok: true } }) + if (remote[2] === 'connect') { + if (body.pairingLink) return route.fulfill({ status: 409, json: { error: 'pairing_unavailable' } }) + if (body.password !== 'fixture-password') return route.fulfill({ status: 409, json: { error: 'auth' } }) + remoteAuthenticated = true + return route.fulfill({ json: { ok: true } }) + } + if (!remoteAuthenticated) return route.fulfill({ status: 409, json: { error: 'needs_credentials' } }) + const current = body.path ?? '/' + remoteReads.push(current) + return route.fulfill({ json: { listing: { metadata: { currentPath: current, displayPath: current, rootPath: '/', homePath: '/', scope: 'unrestricted', pathKind: 'absolute', ...(current === '/' ? {} : { parentPath: '/' }) }, + entries: current === '/' ? [{ name: 'app', path: '/srv/app', absolutePath: '/srv/app', type: 'directory' }] : [] }, + recents: [{ path: '/srv/recent', projectName: 'Remote recent', lastAccessed: 1 }] } }) + } if (pathname === "/api/workspaces" && request.method() === "POST") { const body = request.postDataJSON() as { path: string } created.push(body.path) @@ -108,7 +128,7 @@ async function open(page: Page, path: string, scenario: Scenario) { await route.fulfill({ json: body }) }) await page.goto(`${url}${path}`) - return { created, probes, state: () => state } + return { created, probes, remoteReads, state: () => state } } // Shows Browse: the home page's tab, else the launcher's section, which stays unfolded once opened. @@ -131,7 +151,113 @@ async function addServer(page: Page, address: string) { const views = (page: Page) => page.evaluate(() => (window as any).fixtureViews as { opened: Array<{ viewId: string; profileId: string; baseUrl: string; url: string; bounds: { width: number; height: number } }> - updates: Array<{ viewId: string; visible: boolean }>; closed: string[]; windows: Array<{ id: string }> + updates: Array<{ viewId: string; visible: boolean }>; closed: string[]; windows: Array<{ id: string; entryUrl?: string }> +}) + +async function chooseRemoteRoot(page: Page) { + await page.getByRole('button', { name: 'Select Current', exact: true }).click() +} + +for (const surface of ['Home', 'blank', 'launcher'] as const) test(`${surface}: remote browsing signs in inline and opens only the chosen folder`, async () => { + const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: 'en-US' }) + try { + const fixture = await open(page, '', { context: 'local', host: 'electron', remoteNeedsPassword: true, + uiState: { remoteServers: [server('box')] }, sidecars: [sidecar('docs', 'Docs', 'running')] }) + await browse(page) + if (surface !== 'Home') { + await page.locator('[data-sidecar="docs"]').click() + await page.locator('.tab-pill', { hasText: 'Docs' }).waitFor() + await page.locator('.new-instance-button').click(surface === 'launcher' ? { button: 'right' } : {}) + await browse(page) + } + const root = surface === 'launcher' ? page.locator('.new-instance-launcher') + : surface === 'blank' ? page.locator('[data-tab-kind="blank"][data-tab-visible="true"]') : page.locator('.folder-home-root') + const beforeTabs = await page.locator('.tab-pill').count() + const blankId = surface === 'blank' ? await root.getAttribute('data-tab-id') : null + await root.getByRole('button', { name: 'Open a project on Box' }).click() + const password = root.getByRole('textbox', { name: 'Password', exact: true }).or(root.locator('input[type="password"]')) + await password.waitFor() + assert.equal(await root.getByRole('textbox', { name: 'Username', exact: true }).inputValue(), 'codenomad') + assert.equal(await page.getByRole('dialog').count(), surface === 'launcher' ? 1 : 0, 'sign-in creates no floating dialog') + assert.equal(await page.locator('.tab-pill').count(), beforeTabs) + assert.deepEqual((await views(page)).opened, []) + assert.deepEqual((await views(page)).windows, []) + await password.fill('wrong-password') + await root.getByRole('button', { name: 'Sign in', exact: true }).click() + await root.getByRole('alert').getByText('The username or password is incorrect.').waitFor() + assert.equal(await password.inputValue(), '') + assert.equal(await page.getByRole('dialog').count(), surface === 'launcher' ? 1 : 0, 'failed sign-in stays inline') + await password.fill('fixture-password') + await root.getByRole('button', { name: 'Sign in', exact: true }).click() + await root.locator('[data-remote-folder]').waitFor() + assert.equal(await root.locator('input[type="password"]').count(), 0) + assert.equal(JSON.stringify(fixture.state()).includes('fixture-password'), false) + await page.waitForFunction(() => document.activeElement?.hasAttribute('data-remote-folder')) + await page.keyboard.press('Home') + await page.waitForFunction(() => document.activeElement?.textContent === 'Back to Browse') + await page.keyboard.press('End') + await page.waitForFunction(() => document.activeElement?.hasAttribute('data-remote-folder')) + await page.keyboard.press('Enter') + await root.locator('.remote-server-path').getByText('/srv/app', { exact: true }).waitFor() + assert.deepEqual((await views(page)).opened, []) + await root.getByRole('button', { name: 'Parent folder', exact: true }).click() + await root.locator('[data-remote-folder]').waitFor() + await root.getByRole('button', { name: 'Back to Browse', exact: true }).click() + await page.waitForFunction(() => document.activeElement?.getAttribute('data-remote-server') === 'box') + await page.keyboard.press('Enter') + await root.locator('[data-remote-folder]').waitFor() + await page.keyboard.press('Escape') + await root.getByRole('button', { name: 'This computer', exact: true }).waitFor() + await page.waitForFunction(() => document.activeElement?.getAttribute('data-remote-server') === 'box') + assert.equal(await page.locator('.tab-pill').count(), beforeTabs) + await page.keyboard.press('Enter') + await root.getByRole('button', { name: 'app', exact: true }).click() + await root.locator('.remote-server-path').getByText('/srv/app', { exact: true }).waitFor() + await root.getByRole('button', { name: 'Select Current', exact: true }).click() + await page.waitForFunction(() => (window as any).fixtureViews.opened.length === 1) + assert.equal((await views(page)).opened[0].url, `${BOX}/?codenomadEmbed=project&folder=%2Fsrv%2Fapp`) + assert.equal(await page.locator('.tab-pill').count(), beforeTabs + (surface === 'blank' ? 0 : 1)) + if (blankId) assert.equal(await page.locator(`[data-tab-id="${blankId}"]`).count(), 0) + assert.equal(await page.locator('.new-instance-launcher').count(), 0) + assert.deepEqual(fixture.created, []) + assert.deepEqual(fixture.remoteReads, ['/', '/srv/app', '/', '/', '/', '/srv/app']) + } finally { await page.close() } +}) + +for (const pending of ['browse', 'connect'] as const) test(`returning to Browse fences a delayed remote ${pending} response and its focus`, async () => { + const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: 'en-US' }) + let release!: () => void + const held = new Promise(resolve => { release = resolve }) + let settled!: () => void + const finished = new Promise(resolve => { settled = resolve }) + try { + await open(page, '', { context: 'local', host: 'electron', remoteNeedsPassword: pending === 'connect', uiState: { remoteServers: [server('box')] } }) + await browse(page) + await page.route(`**/api/remote-servers/box/${pending}`, async route => { + await held + try { await route.fulfill({ json: pending === 'connect' ? { ok: true } : { + listing: { metadata: { currentPath: '/late', displayPath: '/late', pathKind: 'absolute' }, entries: [{ name: 'late', path: '/late', type: 'directory' }] }, recents: [], + } }) } finally { settled() } + }) + const request = page.waitForRequest(`**/api/remote-servers/box/${pending}`) + await page.getByRole('button', { name: 'Open a project on Box' }).click() + if (pending === 'connect') { + await page.getByRole('textbox', { name: 'Username', exact: true }).waitFor() + await page.locator('input[type="password"]').fill('fixture-password') + await page.getByRole('button', { name: 'Sign in', exact: true }).click() + assert.equal(await page.locator('input[type="password"]').inputValue(), '', 'cleared while connect is pending') + } + await request + await page.getByRole('button', { name: 'Back to Browse', exact: true }).click() + await page.waitForFunction(() => document.activeElement?.getAttribute('data-remote-server') === 'box') + release() + await finished + await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())))) + assert.equal(await page.locator('.remote-server-browser').count(), 0) + assert.equal(await page.evaluate(() => document.activeElement?.getAttribute('data-remote-server')), 'box') + assert.deepEqual((await views(page)).opened, []) + assert.deepEqual((await views(page)).windows, []) + } finally { release(); await page.close() } }) test("the embedded page shows no tab bar or home, only a folder picker that opens one project", async () => { @@ -210,13 +336,14 @@ test("a local window opens a saved server as a project tab whose view follows th const fixture = await open(page, "", { context: "local", host: "electron", uiState: { remoteServers: [server("box"), server("lab", { skipTlsVerify: true })] } }) await browse(page) await page.getByRole("button", { name: "Open a project on Box" }).click() + await chooseRemoteRoot(page) const tab = page.locator(".tab-pill", { hasText: "Box" }) await tab.waitFor() await page.waitForFunction(() => (window as any).fixtureViews.opened.length === 1) const [opened] = (await views(page)).opened assert.equal(opened.profileId, "box") assert.equal(opened.baseUrl, BOX) - assert.equal(opened.url, `${BOX}/?codenomadEmbed=project`) + assert.equal(opened.url, `${BOX}/?codenomadEmbed=project&folder=%2F`) assert.ok(opened.bounds.width > 100 && opened.bounds.height > 100) // The embedded page reports its project: the tab takes its name and the host remembers it. @@ -241,13 +368,15 @@ test("a local window opens a saved server as a project tab whose view follows th // A server with an unverified certificate keeps its separate window. await browse(page) await page.getByRole("button", { name: "Open a project on lab" }).click() + await chooseRemoteRoot(page) await page.waitForFunction(() => (window as any).fixtureViews.windows.length === 1) assert.equal((await views(page)).windows[0].id, "lab") + assert.equal((await views(page)).windows[0].entryUrl, 'https://lab.example/?codenomadEmbed=project&folder=%2F') assert.equal((await views(page)).opened.length, 1) } finally { await page.close() } }) -test("Browse saves a pairing link without opening it and refuses credentials; clicking the server pairs", async () => { +test("Browse refuses address credentials and saves a pairing server while reporting unavailable pairing", async () => { const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: "en-US" }) try { const fixture = await open(page, "", { context: "local", host: "electron" }) @@ -255,7 +384,7 @@ test("Browse saves a pairing link without opening it and refuses credentials; cl await page.getByRole("alert").getByText("Remove the user name and password from the address.").waitFor() assert.deepEqual(fixture.probes, []) - // A pasted link is saved at once; only clicking its row consumes the code. + // A pasted link saves its origin and attempts backend pairing without opening a native view. const tunnel = "https://desk.opentunnel.test" await field.fill("") await field.evaluate((input, link) => { @@ -268,18 +397,15 @@ test("Browse saves a pairing link without opening it and refuses credentials; cl await page.waitForFunction(() => document.activeElement?.getAttribute("data-remote-server")) assert.equal((await views(page)).opened.length, 0) assert.equal((await views(page)).windows.length, 0) - await row.click() - await page.waitForFunction(() => (window as any).fixtureViews.opened.length === 1) - const [opened] = (await views(page)).opened - assert.equal(opened.url, `${tunnel}/remote-pair#single-use-code`) - assert.equal(opened.baseUrl, tunnel) + await page.getByRole('alert').getByText('Server-side Remote Control pairing unavailable.').waitFor() + assert.equal((await views(page)).opened.length, 0) assert.equal(JSON.stringify(fixture.state()).includes("single-use-code"), false) assert.deepEqual((fixture.state() as { remoteServers: Array<{ baseUrl: string }> }).remoteServers.map((entry) => entry.baseUrl), [tunnel]) assert.equal(await page.getByRole("dialog").count(), 0) } finally { await page.close() } }) -test("an address added in Browse only joins the list and receives focus; clicking it opens its tab", async () => { +test("an address added in Browse receives focus; choosing a folder opens its tab", async () => { const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: "en-US" }) try { const fixture = await open(page, "", { context: "local", host: "electron", uiState: { remoteServers: [server("box")] } }) @@ -290,6 +416,7 @@ test("an address added in Browse only joins the list and receives focus; clickin assert.equal((await views(page)).opened.length, 0) assert.equal((await views(page)).windows.length, 0) await row.click() + await chooseRemoteRoot(page) await page.locator(".tab-pill", { hasText: "lab.example" }).waitFor() await page.waitForFunction(() => (window as any).fixtureViews.opened.length === 1) type Saved = { remoteServers: Array<{ id: string; name: string; baseUrl: string }> } @@ -303,6 +430,7 @@ test("an address added in Browse only joins the list and receives focus; clickin await page.waitForFunction(() => document.activeElement?.textContent === "Box") assert.equal((await views(page)).opened.length, 1) await page.getByRole("button", { name: "Open a project on Box" }).click() + await chooseRemoteRoot(page) await page.waitForFunction(() => (window as any).fixtureViews.opened.length === 2) assert.equal((await views(page)).opened[1].profileId, "box") assert.deepEqual((fixture.state() as Saved).remoteServers.map((entry) => entry.id).sort(), [added.id, "box"].sort()) @@ -311,7 +439,7 @@ test("an address added in Browse only joins the list and receives focus; clickin } finally { await page.close() } }) -test("Browse lists saved servers by name and a server's tab shows that name before a project is chosen", async () => { +test("Browse lists saved servers by name and the selected root tab shows its server name", async () => { const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: "en-US" }) try { // An existing user's profiles, one saved under its pasted address. @@ -324,6 +452,7 @@ test("Browse lists saved servers by name and a server's tab shows that name befo await page.getByRole("button", { name: "Open a project on Box" }).click({ button: "right" }) assert.equal(await page.getByRole("menuitem").count(), 0) await page.getByRole("button", { name: "Open a project on 127.0.0.1" }).click() + await chooseRemoteRoot(page) await page.locator(".tab-pill", { hasText: "127.0.0.1" }).waitFor() assert.equal(await page.locator(".tab-pill", { hasText: "127.0.0.1:9911" }).count(), 0) } finally { await page.close() } @@ -342,6 +471,7 @@ test("a certificate that fails the check offers skipping it under the field; the await row.waitFor() assert.equal((await views(page)).windows.length, 0, "TLS confirmation saves only") await row.click() + await chooseRemoteRoot(page) await page.waitForFunction(() => (window as any).fixtureViews.windows.length === 1) assert.equal((await views(page)).opened.length, 0, "an unverified certificate never opens a tab") assert.deepEqual(fixture.probes, ["https://selfsigned.example skipTls=false", "https://selfsigned.example skipTls=true"]) @@ -363,6 +493,7 @@ test("+ opens disposable blank tabs; remote and SideCar choices replace their or sidecars: [sidecar("docs", "Docs", "running")] }) await browse(page) await page.getByRole("button", { name: "Open a project on Box" }).click() + await chooseRemoteRoot(page) await page.locator('.tab-pill', { hasText: 'Box' }).waitFor() await page.locator('.new-instance-button').click() const blank = page.locator('[data-tab-kind="blank"][data-tab-visible="true"]') @@ -387,6 +518,8 @@ test("+ opens disposable blank tabs; remote and SideCar choices replace their or await page.locator(`[data-app-tab-id="${firstBlankId}"] [role=tab]`).click() await blank.getByRole('tab', { name: 'Browse', exact: true }).click() await blank.getByRole('button', { name: 'Open a project on Box' }).click() + assert.equal(await page.locator('[data-tab-kind="blank"]').count(), 2, 'browsing preserves both blanks') + await blank.getByRole('button', { name: 'Remote recent /srv/recent', exact: true }).click() assert.equal(await page.locator('[data-tab-kind="blank"]').count(), 1) assert.equal(await page.locator('.tab-pill').count(), 3) assert.match((await page.locator('.tab-strip-tabs > *').nth(1).getAttribute('data-app-tab-id'))!, /^remote-project:/) @@ -413,6 +546,7 @@ test("a delayed server add preserves both blank tabs; clicking its row fills the await open(page, "", { context: "local", host: "electron", uiState: { remoteServers: [server("box")] } }) await browse(page) await page.getByRole("button", { name: "Open a project on Box" }).click() + await chooseRemoteRoot(page) await page.locator(".new-instance-button").click() const blank = page.locator('[data-tab-kind="blank"][data-tab-visible="true"]') const origin = await blank.getAttribute("data-tab-id") @@ -434,6 +568,7 @@ test("a delayed server add preserves both blank tabs; clicking its row fills the await page.locator(`[data-app-tab-id="${origin}"] [role=tab]`).click() await originView.getByRole('tab', { name: 'Browse', exact: true }).click() await originView.getByRole("button", { name: "Open a project on slow.example" }).click() + await chooseRemoteRoot(page) assert.equal(await page.locator(`[data-tab-id="${origin}"]`).count(), 0) assert.match((await page.locator(".tab-strip-tabs > *").nth(1).getAttribute("data-app-tab-id"))!, /^remote-project:/) } finally { release(); await page.close() } @@ -496,6 +631,8 @@ test("blank tabs reuse Home's branding, action buttons, tab selector and recent await page.waitForFunction(() => document.activeElement?.textContent === 'added.example') assert.equal(await page.locator('[data-tab-kind="blank"]').count(), 1) await added.click() + assert.equal(await page.locator('[data-tab-kind="blank"]').count(), 1) + await chooseRemoteRoot(page) assert.equal(await page.locator('[data-tab-kind="blank"]').count(), 0) } finally { await page.close() } }) @@ -506,6 +643,7 @@ test("adding a server in the + launcher keeps it open, focuses the saved row and const fixture = await open(page, "", { context: "local", host: "electron", uiState: { remoteServers: [server('box')] } }) await browse(page) await page.getByRole('button', { name: 'Open a project on Box' }).click() + await chooseRemoteRoot(page) await page.locator('.new-instance-button').click({ button: 'right' }) const launcher = page.locator('.new-instance-launcher') const toggle = launcher.getByRole('button', { name: 'Browse', exact: true }) @@ -520,6 +658,7 @@ test("adding a server in the + launcher keeps it open, focuses the saved row and assert.equal((await views(page)).windows.length, 0) assert.deepEqual(fixture.created, []) await row.click() + await launcher.getByRole('button', { name: 'Select Current', exact: true }).click() await launcher.waitFor({ state: 'hidden' }) await page.waitForFunction(() => (window as any).fixtureViews.opened.length === 2) } finally { await page.close() } diff --git a/packages/ui/tests/browser/remote-server-pairing.test.ts b/packages/ui/tests/browser/remote-server-pairing.test.ts index f6c513c9eb..03cfcaef92 100644 --- a/packages/ui/tests/browser/remote-server-pairing.test.ts +++ b/packages/ui/tests/browser/remote-server-pairing.test.ts @@ -43,7 +43,7 @@ async function add(page: Page, address: string) { const opened = (page: Page) => page.evaluate(() => (window as unknown as { opened: Array<{ id: string; baseUrl: string; entryUrl?: string }> }).opened) -test("a pairing link saves only the server; clicking it pairs in its window", async () => { +test("a pairing link saves only the server and reports unavailable backend pairing", async () => { const page = await browser.newPage({ viewport: { width: 900, height: 900 }, locale: "en-US" }) const errors: string[] = [] page.on("pageerror", error => errors.push(error.message)) @@ -53,13 +53,8 @@ test("a pairing link saves only the server; clicking it pairs in its window", as await page.getByRole("textbox", { name: "Server address or link" }).waitFor() await page.waitForFunction(() => (document.querySelector('[data-server-add-field]') as HTMLInputElement)?.value === "") assert.deepEqual(await opened(page), [], "adding a pairing link never opens a window") - await page.getByTestId("servers").getByRole("button").click() - await page.waitForFunction(() => (window as unknown as { opened: unknown[] }).opened.length === 1) - const [payload] = await opened(page) - assert.equal(payload.baseUrl, TUNNEL) - assert.equal(payload.entryUrl, LINK) - // Skipping TLS checks would later route Tauri through the incognito proxy store and lose the pairing. - assert.equal((payload as { skipTlsVerify?: boolean }).skipTlsVerify, false) + await page.getByRole("alert").getByText("Server-side Remote Control pairing unavailable.").waitFor() + assert.equal((await page.locator("body").innerText()).includes("single-use-code"), false) assert.deepEqual(await page.evaluate(() => (window as unknown as { probes: string[] }).probes), [`${TUNNEL} skipTls=false`]) const state = JSON.parse(await page.evaluate(() => (window as unknown as { uiState: () => string }).uiState())) assert.equal(JSON.stringify(state).includes("single-use-code"), false) @@ -77,9 +72,10 @@ test("pairing a saved server again reuses it instead of adding a duplicate", asy await add(page, LINK) await page.waitForFunction(() => (document.querySelector('[data-server-add-field]') as HTMLInputElement)?.value === "") assert.deepEqual(await opened(page), []) - await page.getByTestId("servers").getByRole("button").click() - await page.waitForFunction(() => (window as unknown as { opened: unknown[] }).opened.length === 1) - assert.equal((await opened(page))[0].id, "saved-tunnel") + await page.getByRole("alert").getByText("Server-side Remote Control pairing unavailable.").waitFor() + const state = await page.evaluate(() => (window as unknown as { uiState: () => string }).uiState()) + assert.equal(state.includes("single-use-code"), false) + assert.equal(JSON.parse(state).remoteServers[0].id, "saved-tunnel") assert.equal(await page.getByTestId("servers").locator("li").count(), 1) } finally { await page.close() } }) From fef67f916eb3b694fa9cefd630ebd19e49ee6c7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 6 Nov 2026 02:31:45 +0100 Subject: [PATCH 21/34] docs(remote): describe inline browsing and private backend connections Update Projects, Remote access and Remote Control in all ten languages for in-place browsing, separate native-view sign-in, private persistent credentials, removal and address/TLS safeguards. Document the unavailable server-side Remote Control pairing path without implying that browser pairing grants the backend a session. Keep CLI native-window sign-in distinct from Browse. Record the API admission and credential ownership contracts in Projects, Remote Control and architecture. The complete multilingual help validation passes 31 tests. --- dev-docs/PROJECTS.md | 8 ++++++-- dev-docs/REMOTE_CONTROL.md | 25 ++++++++++--------------- dev-docs/architecture.md | 5 ++++- docs/help/de/projects.md | 4 +++- docs/help/de/remote-access.md | 19 +++++++++++-------- docs/help/de/remote-control.md | 4 ++-- docs/help/en/projects.md | 4 +++- docs/help/en/remote-access.md | 19 +++++++++++-------- docs/help/en/remote-control.md | 4 ++-- docs/help/es/projects.md | 4 +++- docs/help/es/remote-access.md | 19 +++++++++++-------- docs/help/es/remote-control.md | 4 ++-- docs/help/fr/projects.md | 4 +++- docs/help/fr/remote-access.md | 19 +++++++++++-------- docs/help/fr/remote-control.md | 4 ++-- docs/help/he/projects.md | 4 +++- docs/help/he/remote-access.md | 19 +++++++++++-------- docs/help/he/remote-control.md | 4 ++-- docs/help/ja/projects.md | 4 +++- docs/help/ja/remote-access.md | 19 +++++++++++-------- docs/help/ja/remote-control.md | 4 ++-- docs/help/ne/projects.md | 4 +++- docs/help/ne/remote-access.md | 19 +++++++++++-------- docs/help/ne/remote-control.md | 4 ++-- docs/help/ru/projects.md | 4 +++- docs/help/ru/remote-access.md | 19 +++++++++++-------- docs/help/ru/remote-control.md | 4 ++-- docs/help/tr/projects.md | 4 +++- docs/help/tr/remote-access.md | 19 +++++++++++-------- docs/help/tr/remote-control.md | 4 ++-- docs/help/zh-Hans/projects.md | 4 +++- docs/help/zh-Hans/remote-access.md | 19 +++++++++++-------- docs/help/zh-Hans/remote-control.md | 4 ++-- 33 files changed, 180 insertions(+), 128 deletions(-) diff --git a/dev-docs/PROJECTS.md b/dev-docs/PROJECTS.md index e30b2dd4a4..11aeea21b1 100644 --- a/dev-docs/PROJECTS.md +++ b/dev-docs/PROJECTS.md @@ -4,11 +4,15 @@ Closing project tabs, temporary workspaces, the new-instance launcher and the Gi ## Agent conventions -- Empty tabs (`kind: "blank"`, `stores/app-tabs.ts`) have window-local IDs and are filtered before session capture. A successful project, saved-server or SideCar choice replaces its originating blank slot; keep that ID across asynchronous folder/clone selection, workspace creation and SideCar opens. Adding a server saves its profile and preserves empty tabs; selecting its row opens it. Other empty tabs retain their positions. Closing an empty tab makes no backend call. `FolderSelectionView` owns the Home and blank layouts, with shared `BrowseMenu`, `NewTabActions`, recent rows and browse/clone dialogs; the compact launcher uses `RecentTabsMenu`. Recent and Browse counts include their available entries; Browse counts the computer, saved servers visible to this host and configured SideCars, with the add-server field treated as an action. +- Empty tabs (`kind: "blank"`, `stores/app-tabs.ts`) have window-local IDs and are filtered before session capture. A successful local/remote project or SideCar choice replaces its originating blank slot; keep that ID across asynchronous folder/clone selection, remote browsing, workspace creation and SideCar opens. Adding a server saves its profile and preserves empty tabs; selecting its Browse row shows its recent projects and folders in place until a folder is chosen. Other empty tabs retain their positions. Closing an empty tab makes no backend call. `FolderSelectionView` owns the Home and blank layouts, with shared `BrowseMenu`, `NewTabActions`, recent rows and browse/clone dialogs; the compact launcher uses `RecentTabsMenu`. Recent and Browse counts include their available entries; Browse counts the computer, saved servers visible to this host and configured SideCars, with the add-server field treated as an action. - Closing a project tab detaches it immediately and requests deletion of that occurrence's logical backend workspace record; failures notify and never retry automatically. Separate occurrences of the same folder are independent. A `workspace.stopped` deletion closes the same record in other windows and notifies only windows displaying it that did not initiate the close. CodeNomad never evicts native Locations; OpenCode sessions keep running and reopening finds them. Whole-window close, app quit, renderer reload and backend shutdown keep existing restoration behavior. Temporary discard and server stop events use local-only tab detachment, not another DELETE; Keep closes the retained project normally. - Git is a full-functionality prerequisite, with directory-only degraded conversations when the backend cannot find Git. Only the explicitly opened physical folder is session authority in that mode; never infer sibling worktrees from native project IDs. Keep ancestor/descendant mutation identities covered by the deletion fence across Git availability changes. Inform agents through the owned native `codenomad.git-availability` instruction before prompts/custom commands, remove stale context after recovery, and keep this advisory separate from fail-closed environment synchronization. Do not add a blocking Git setup UI. Validate with `scripts/test-git-degraded-native.mjs` using an isolated CLI/database and provider. - Temporary instances (`workspaces/temporary-workspaces.ts`, UI `stores/temporary-instances.ts`) are ordinary non-Git workspaces on CodeNomad-created direct children of `/temporary-workspaces`. Registry membership (`temporary-workspaces.json`), not location, makes a folder temporary; keeping only unregisters it and adds a named recent project. Discard deletes only registered children of that root, refuses running conversations and other open tabs of the folder, removes conversations deepest-first, closes the workspace before deleting the folder and keeps failed removals registered; such a folder is reachable only by browsing to it. Closing a temporary tab from the UI asks Keep/Discard/Cancel, except that an untouched one (no conversation, file or unsent draft) closes and is discarded silently (`onlyIfEmpty`: the server refuses with `temporary_has_conversations`/`temporary_not_empty`, and any failure of that quiet discard returns the choice without an error). Before the server stops it, a visible temporary tab yields to its neighbour (or closes if alone) and a refusal restores it in place; `workspace.stopped` likewise closes the tab first and clears the instance in a microtask, because clearing a visible shell's state in the same update as its tab freezes the window. Same-minute names get a `(n)` suffix. Registry changes broadcast `workspace.temporaryChanged`, which clears kept marks in every window. Open temporary tabs are saved and restored with the app state like any project tab (still marked temporary). Only the choice dialog overrides initial focus (to its last, non-destructive choice); confirms keep focus on Cancel. Refusals use stable `temporary_*` codes localized by the client. Validate with `scripts/test-temporary-workspaces-native.mjs` against an isolated CLI. - The tab-bar new-instance button follows the last tab like a browser: the instance `TabScroll` frame only spans its tabs and the button sits after it, outside the scroller (so focusing it never scrolls the strip), ending up at the strip's end once tabs overflow. Dragged tabs stay visually within the tab list like a browser's (`KeepDraggedTabInStrip`), while the drop slot follows the pointer's unbounded position (`closestUnboundedCenter`). Clicking it (or Cmd/Ctrl+N) opens an empty tab. A long press, right-click, Alt+Down, Shift+F10 or Menu opens the anchored `NewInstanceLauncher` (`lib/long-press.ts`; only Escape returns focus to the button, never over another surface or the home page): titled Open a tab, it is the home page's logic in short: the search, the collapsible Recent section (unfolded by default and kept per window; chevron first, like Browse; Escape on its title folds it without closing the launcher; typing or an arrow in the search unfolds it; an open project switches to its tab), the folded Browse section, then Clone and New temporary tab only. Recents are local projects, remote projects and SideCars (`launchableRecents`, `filterRecents` for search fields, `components/recent-tab-icon.tsx`); a SideCar joins them when it opens (`stores/sidecar-open.ts`), stored as `ui` state `sidecarRecents` with its id and time only, never an address or proxy token, and listed while still configured. The home page's right card has two tabs, Recent (with the same search; arrows move between the tabs) and Browse (the list always open); its left column holds only the creation buttons of `components/new-tab-actions.tsx`: Clone a Git repository, New temporary tab and New SideCar (`openSettingsRow("sidecars", "sidecar-add")`, the SideCar form's name field); servers are added in Browse. The launcher's `variant` keeps only the first two. Renaming and removing recent tabs stay on the home page; servers are managed in Settings → Servers, SideCars in Settings → SideCars. Browse/clone flows live once in `components/new-instance-dialogs.tsx` and recent-folder display helpers in `lib/recent-folder-display.ts`, shared with `FolderSelectionView`; styles in `styles/components/new-instance-launcher.css`. -- Remote project tabs show one project of a saved remote CodeNomad server inside a local window. Browse (`components/browse-menu.tsx`, Home/blank mode's Browse tab with `alwaysOpen` and the launcher's folded section, its disclosure state shared per window) lists This computer (the native dialog or folder browser), then, in host windows only (`canOpenRemoteWindows()`), each saved server profile, then each configured SideCar with its state (a stopped one cannot open), then, in host windows, the inline address field last; it offers no management (no context menu). Servers are added only through that field (`components/server-add-field.tsx`), never a floating dialog: an address or a Remote Control pairing link (`lib/codenomad-link.ts`, `lib/remote-pairing-link.ts`) goes through `submitServer(input, false)` (`lib/hooks/use-remote-server-profiles.ts`) and the probe, is saved under its host (`codeNomadLinkName`) and receives focus in Browse. Pasting a valid link adds it immediately; Enter or + submits typed text. The launcher stays open until a saved row is selected. Pairing entries wait in renderer memory until explicit opening (see [REMOTE_CONTROL.md](REMOTE_CONTROL.md)). An address already saved reuses its profile; an address carrying credentials or unreadable text shows a short error under the field; only a probe failing with `tls_error` on an address adds the Skip TLS verification checkbox, confirmed through the same field, which saves a window-only profile. Settings → Servers (`settings/servers-settings-section.tsx`, host windows only) is the one management surface: the same field saves a server, and each server is opened, edited through `RemoteServerDialog` (edit only: address, name, certificate check) and removed (confirmed). Saving keeps the profile id, so its storage and sign-in stay, and a rename with the same URL and TLS setting skips the probe (`saveProfile`). Opening from the native Preferences window, which has no tabs, opens the server's window. Sign-in happens on the server's own page; the view's storage keeps it across launches. Servers read as `serverDisplayName` (`lib/codenomad-link.ts`): the saved name, or the host name when that name is a raw address (pasted servers are saved under `url.host`), with the port only when another saved server shares the host name; Browse, recents, Settings → Servers and a tab whose project is not chosen yet use it. Choosing a server opens a `remote-project` app tab (`stores/remote-project-tabs.ts`, actions in `stores/remote-project-open.ts`) whose `RemoteProjectView` places a native view (Electron `WebContentsView`, `electron/main/remote-view.ts`; Tauri child webview on Windows, `src-tauri/src/remote_view.rs`) over its content area; elsewhere, and for profiles that skip TLS verification, the server keeps its separate remote window. The view uses that server's remote-window storage (Electron partition, Tauri data directory), so its session or paired device cookie is reused without signing in again, and the remote preload/capability: of native access only notifications reach the host (badges and every local command are refused). It stays on the server's origin, the public help site opening in the system browser; a navigation to the bare root (end of login or pairing) returns to the tab's entry. Under Tauri every navigation also passes the app-wide `external-link-guard` plugin after the view's own handler: `intercept_navigation` asks `RemoteViews::navigation_allowed` first for registered `remote-view-*` labels, since the window-origin rules would cancel the view's first load. The view opens the first time its tab shows, follows the placeholder's bounds and hides while its tab is hidden or a local dialog, menu or list is open (`localOverlayOpen()`, shared with browser previews); a reload or close of the owning page closes its views. The remote page runs in embedded single-project mode (`lib/embed-mode.ts`, `/?codenomadEmbed=project[&folder=…]`): no title bar, tab bar or home page, a folder picker (`components/embedded-project-picker.tsx`) until a project opens, no native badge; it records the folder in its address and the project name in `document.title`, and keeps its active session per folder in its own persistent storage (`rememberEmbeddedSession`), reselected on reopening through the restored-tab hydration (`stores/embedded-project-session.ts`). A direct-access password sign-in lasts `PASSWORD_SESSION_TTL_MS` (seven days) with a matching cookie `Max-Age`, so the view stays signed in across host restarts while the server runs; logout revokes it server-side; bootstrap-token sessions keep browser-session cookies. The host accepts a title change only from the server's origin with a folder in the address, so a server without this mode shows its full interface and the tab keeps the server's name. Tabs restore as `{kind: "remote-project", profileId, folder?}` (a removed or window-only server drops its tab); projects opened in tabs join this host's recents beside local folders (`ui` state `remoteProjectRecents`, server, folder and name only; removing a server forgets them and closes its tabs). Covered by `tests/browser/remote-project-tabs.test.ts`, `electron/main/remote-view.test.ts` and `remote_view.rs` tests (navigation, ownership, ACL of the child label). +- Browse (`components/browse-menu.tsx`) lists This computer, host-visible saved servers, configured SideCars and the inline server-add field. `components/server-add-field.tsx` saves a profile only; pasting adds immediately and Enter or + submits typed text. An existing address reuses its profile. Credentials in an address are rejected. A `tls_error` offers Skip TLS verification with explicit confirmation and a window-only profile. A Remote Control pairing link saves its origin but reports localized server-side pairing unavailable and discards the code ([REMOTE_CONTROL.md](REMOTE_CONTROL.md)). Never persist a pairing code or retain it for native opening. +- Choosing a saved Browse row switches the list in place to that server's recent projects and folder list, with Back to Browse. An inline username/password form obtains a backend-held direct-access session when needed. Folder navigation stays in that list; Select Current or choosing a recent project opens its folder in a remote tab, replacing the originating blank slot. The `+` launcher stays open until a folder is chosen. Keep this flow shared between Home, blank tabs and the compact launcher. Backend browsing and native embedded views own independent authentication. +- Settings → Servers (`settings/servers-settings-section.tsx`, host windows only) manages profiles through the same add field, the edit-only `RemoteServerDialog` (address, name, certificate check) and confirmed removal. Removal must call the backend forget endpoint before removing the profile, then clear its recents and close its tabs. Saving keeps the profile id; a rename with unchanged URL/TLS skips the probe (`saveProfile`). Opening from the tabless native Preferences window opens the server's window. `serverDisplayName` (`lib/codenomad-link.ts`) uses the saved name or hostname, showing a port when another saved server shares that hostname. +- A selected remote folder opens a `remote-project` app tab (`stores/remote-project-tabs.ts`, `stores/remote-project-open.ts`). `RemoteProjectView` places a native view over its content area: Electron `WebContentsView` (`electron/main/remote-view.ts`) or a Windows Tauri child webview (`src-tauri/src/remote_view.rs`). Other platforms and profiles that skip TLS verification open a separate remote window. Embedded views share the server's remote-window storage (Electron partition or Tauri data directory) and keep their own sign-in/device cookie; backend browsing uses its private credential store. Native access permits notifications only. Views stay on the server origin, open public help externally and return bare-root navigation after authentication to their tab entry. Tauri's `external-link-guard` checks registered `remote-view-*` labels through `RemoteViews::navigation_allowed` before window-origin rules. Views open lazily, track placeholder bounds, hide for inactive tabs and local overlays (`localOverlayOpen()`), and close with their owning page. +- Embedded single-project mode (`lib/embed-mode.ts`, `/?codenomadEmbed=project[&folder=…]`) shows one project without the title/tab bars, Home or native badge; its folder picker handles entries without a folder. It records the folder in the URL and project name in `document.title`, and restores the active session per folder (`rememberEmbeddedSession`, `stores/embedded-project-session.ts`). The host accepts title updates only from the server origin with a folder in the address. Servers without this mode show their full interface and retain the server title. Password sessions last seven days (`PASSWORD_SESSION_TTL_MS`) with matching cookie `Max-Age`; logout revokes them and bootstrap sessions use browser-session cookies. Tabs restore as `{kind: "remote-project", profileId, folder?}`; missing/window-only profiles drop their tabs. Remote recents (`ui.remoteProjectRecents`) contain server, folder and name only. Covered by `tests/browser/remote-project-tabs.test.ts`, `electron/main/remote-view.test.ts` and `remote_view.rs` tests. - The clone dialog (`components/new-instance-dialogs.tsx`) suggests the repository's `git clone` folder name (`lib/clone-destination.ts`) inside a parent: the folder chosen with Browse, else the server-scoped `ui` state `lastCloneParent` (the folder above the last successful clone), else the folder above the most recent project. A destination the user types is kept as entered and sent unchanged; the server creates it. diff --git a/dev-docs/REMOTE_CONTROL.md b/dev-docs/REMOTE_CONTROL.md index 265a5614c6..727b47639a 100644 --- a/dev-docs/REMOTE_CONTROL.md +++ b/dev-docs/REMOTE_CONTROL.md @@ -82,24 +82,19 @@ browser ─TLS─▶ OpenTunnel relay (forwards ciphertext) ─▶ OpenTunnel SD only once Remote Control is used. - Remote devices authenticate even with `--dangerously-skip-auth`, and the local session cookie is never accepted on the ingress. -- A desktop CodeNomad pairs as a device: pasting a pairing link into the inline server - field (Browse on Home, an empty tab or in the launcher, or Settings → Servers) saves the tunnel - origin. The single-use entry waits in renderer memory (`pendingPairingEntries` in - `lib/hooks/use-remote-server-profiles.ts`) until the saved server is explicitly opened; - reload drops it, removal or a changed origin clears it and a successful opening consumes it. - Adding focuses the Browse row and keeps the launcher open. The profile keeps TLS verification on, since - a Tauri TLS-proxy window uses an incognito store without the device cookie. - The code is never stored with the server; - re-pairing a saved server reuses its window storage, which keeps the device - cookie across launches. Covered by `tests/browser/remote-server-pairing.test.ts`. - Where project tabs are available, choosing the saved server opens a remote project tab whose view - pairs on its first load with the remote window's storage - ([PROJECTS.md](PROJECTS.md#agent-conventions)); the tab never relays the - tunnel through the host. +- Browser pairing consumes the link in the intended browser/profile. The remote + gate requires its exact public browser `Origin` on mutations, while the direct + listener refuses the pair route. Backend remote-server requests omit `Origin`, + so `connect` with a pairing link returns `pairing_unavailable`. The desktop + saves only the tunnel-origin profile, reports localized server-side pairing + unavailable and discards the code. Never keep it in persisted state or a native + pending-entry map. Embedded views retain their own remote-window authentication; + the backend Browse session is independent of a view's paired-device cookie + ([PROJECTS.md](PROJECTS.md#agent-conventions)). - `--connect-server` opens a saved server or URL at launch through that same connect flow ([architecture.md](architecture.md#native-profiles-windows-and-client-state)). It refuses URLs with user info or a fragment, so a pairing code or password - never travels on a command line; pair from Browse instead. + never travels on a command line; open pairing links in the intended browser. ## Validation diff --git a/dev-docs/architecture.md b/dev-docs/architecture.md index 1fe6198527..97a05a60fb 100644 --- a/dev-docs/architecture.md +++ b/dev-docs/architecture.md @@ -53,6 +53,7 @@ CodeNomad control APIs live under `/api/*`. Important routes include: - `/api/storage`, `/api/settings`, `/api/filesystem`, `/api/speech` - `/api/opencode-plugin/automation`, authenticated by a per-process loopback token and restricted to CodeNomad-owned locations - `/api/remote-control/*`, managed from the host only; `POST /api/remote-control/pair` and `/remote-pair` answer only through Remote Control ([REMOTE_CONTROL.md](REMOTE_CONTROL.md)) +- `POST /api/remote-servers/:id/browse`, `/connect` and `/forget`, for saved-profile direct-access browsing. Access requires both loopback non-Remote-Control ingress and an explicit trusted self `Origin`. The backend resolves the profile id from its authoritative UI state; never accept caller-supplied remote URLs as profile authority. Authentication and Remote Control admission judge `routedPath()` (`server/routed-path.ts`), the path Fastify's router matches (`/%61pi/x` routes as `/api/x`), and refuse targets it would reinterpret. Never base an access decision on the raw request target. @@ -62,6 +63,8 @@ Yolo state endpoints live at `/workspaces/:id/yolo/sessions/:sessionId`; Yolo no ## Client And Events +Remote Browse obtains remote recent projects and folders through a backend-held direct CodeNomad session. The UI switches its Browse list in place, requests username/password inline when needed, and opens a remote tab only after a folder is selected. An expired session is reauthenticated once. All upstream remote-server requests omit `Origin`; target validation rejects CGNAT/Tailscale IP literals and special-use address ranges. TLS verification follows the saved profile and its existing explicit opt-out confirmation. Embedded native views retain their own authentication and remote-window storage independently of backend browsing. Remote Control pairing through backend connect returns `pairing_unavailable`; the profile retains only the tunnel origin and the code is discarded ([REMOTE_CONTROL.md](REMOTE_CONTROL.md)). + `packages/ui/src/lib/sdk-manager.ts` uses `OpenCode.make()` and caches generated Promise clients by instance proxy path. `packages/ui/src/stores/opencode-client.ts` is the root-client authority; native directory/location fields select the worktree. The server holds one `client.event.subscribe()` stream. `InstanceEventBridge` maps native location events to CodeNomad `instance.event` records, and `/api/events` multiplexes them with workspace and Yolo events for the browser; heartbeats use `POST /api/client-connections/pong`. The stream is volatile and has no replay guarantee: reconnect must reconcile sessions and pending requests and reread authoritative file/config state. Pending recovery uses the loaded-only broker, never worktree-wide ordinary lists; see [compatibility](OPENCODE_COMPATIBILITY.md), whose Agent conventions also specify relay ordering and ownership fences. @@ -88,7 +91,7 @@ Session Shell and conversation instructions are native features. Session Shell i ## Persistence -CodeNomad configuration resolves through `packages/server/src/config/location.ts`: `config.yaml`, `state.yaml`, `remote-control-devices.json`, and `instances/` under `~/.config/codenomad/`. `config.json` is read only as migration input. +CodeNomad configuration resolves through `packages/server/src/config/location.ts`: `config.yaml`, `state.yaml`, `remote-control-devices.json`, `remote-server-credentials.json`, and `instances/` under `~/.config/codenomad/`. `config.json` is read only as migration input. The private `remote-server-credentials.json` beside the backend configuration stores remote browsing passwords and sessions with mode `0600`. Never include those secrets in API responses, UI state or logs. Removing a saved profile calls `/api/remote-servers/:id/forget` before deleting its UI-state entry. ## Implementation Map diff --git a/docs/help/de/projects.md b/docs/help/de/projects.md index d95506af35..42a06fb4a0 100644 --- a/docs/help/de/projects.md +++ b/docs/help/de/projects.md @@ -4,12 +4,14 @@ Ein Projekt-Tab verbindet CodeNomad mit einem Ordner auf dem Backend-Rechner. Da ## Projekt öffnen {#open-project} -1. **Neue Instanz** (`+`) öffnet einen leeren **Neuer Tab** mit Fokus in der Suche. Er nutzt Hintergrund, zentriertes CodeNomad-Logo und Namen sowie die großen Erstellungsbuttons der Startseite: **Git-Repo klonen**, **Neuer temporärer Tab**, **Neuer SideCar**. Rechts steht der Umschalter **Zuletzt verwendet | Durchsuchen** mit Eintragszahlen; die Suche liegt darunter in **Zuletzt verwendet**. Die Auswahl eines Projekts, gespeicherten Servers oder SideCars füllt diesen Tab an seiner Position. Ein leerer Tab besteht bis zum Neuladen und schließt ohne verbleibendes Projekt. Das CodeNomad-Logo in der Titel- oder Tableiste öffnet die Startseite mit Einstellungen, Sprache und der Herz-Schaltfläche **Sponsor** ([CodeNomad unterstützen](sponsor.md)). +1. **Neue Instanz** (`+`) öffnet einen leeren **Neuer Tab** mit Fokus in der Suche. Er nutzt Hintergrund, zentriertes CodeNomad-Logo und Namen sowie die großen Erstellungsbuttons der Startseite: **Git-Repo klonen**, **Neuer temporärer Tab**, **Neuer SideCar**. Rechts steht der Umschalter **Zuletzt verwendet | Durchsuchen** mit Eintragszahlen; die Suche liegt darunter in **Zuletzt verwendet**. Die Auswahl eines lokalen oder entfernten Projekts oder SideCars füllt diesen Tab an seiner Position. Ein leerer Tab besteht bis zum Neuladen und schließt ohne verbleibendes Projekt. Das CodeNomad-Logo in der Titel- oder Tableiste öffnet die Startseite mit Einstellungen, Sprache und der Herz-Schaltfläche **Sponsor** ([CodeNomad unterstützen](sponsor.md)). 2. Wählen Sie unter **Zuletzt verwendet** ein Projekt; oder öffnen Sie **Durchsuchen**, wählen Sie **Dieser Computer**, dann den Backend-Ordner, und öffnen Sie ihn. **Durchsuchen** listet auch gespeicherte CodeNomad-Server ([Remote-Projekt-Tabs](remote-access.md#remote-project-tabs)) und SideCars ([SideCars](browser-sidecars.md#register-sidecar)) auf. 3. Für eine Repository-Kopie wählen Sie **Git-Repo klonen**, geben **Repository-URL** und **Zielordner** ein und wählen **Klonen**. **Zielordner** wird mit dem Repository-Namen im Ordner, der Ihren letzten Klon enthält vorbelegt, sonst neben Ihrem zuletzt geöffneten Projekt. **Durchsuchen** wählt den Ordner, der den Klon enthält; Sie können den Pfad auch bearbeiten, einschließlich des Ordnernamens des Klons. Einen Remote-Server zu durchsuchen bedeutet, dessen Dateisystem zu durchsuchen, nicht Ihr Telefon oder Notebook. Das Öffnen eines Projekts erzeugt keinen separaten OpenCode-Daemon pro Tab. Unterhaltungen sind native OpenCode-Sitzungen; ihre Lebensdauer entspricht nicht der des Tabs. +Die Auswahl eines Servers in **Durchsuchen** ersetzt die Liste durch dessen letzte Projekte und Ordner. Melden Sie sich bei Bedarf im eingeblendeten Formular an und wählen Sie ein Projekt oder einen Ordner mit **Aktuellen auswählen**. Die Rückkehr zu Durchsuchen zeigt die Server. Erst die Projektwahl füllt den leeren Tab und schließt den `+`-Starter. Der Remote-Tab kann eine eigene Anmeldung unabhängig von der Suche verlangen. + Klonen schreibt ein Repository ins Zielverzeichnis. **Zielordner zuerst entfernen, falls er bereits existiert.** ist destruktiv: Aktivieren Sie dies nur, wenn alles dort Vorhandene gelöscht werden darf. Verwenden Sie im Zweifel ein neues Ziel. Ein fehlgeschlagener Klon ist kein Grund, ein vorhandenes Projekt zu löschen; prüfen Sie vor dem Wiederholen das gemeldete Ziel und den Fehler. Zuletzt verwendete Einträge sind Verknüpfungen. **Arbeitsbereich umbenennen** ändert den Anzeigenamen; **Aus Liste entfernen** entfernt die Verknüpfung, nicht die Dateien oder Unterhaltungen. Ein Klick auf ein bereits geöffnetes zuletzt verwendetes Projekt öffnet einen neuen Tab; seine Schaltfläche **Offen** (**Zum offenen Projekt wechseln**) wählt stattdessen den vorhandenen Tab. diff --git a/docs/help/de/remote-access.md b/docs/help/de/remote-access.md index 00bf6c8581..6b7c64e892 100644 --- a/docs/help/de/remote-access.md +++ b/docs/help/de/remote-access.md @@ -83,23 +83,26 @@ Meldet ein Client eine Zertifikatswarnung, halten Sie an und prüfen Sie Hostnam ## Remote-Server speichern {#saved-servers} -1. Öffnen Sie auf der Startseite, einem leeren Tab oder im Starter **Tab öffnen** den Bereich **Durchsuchen**. Geben Sie Adresse oder Kopplungslink in **Serveradresse oder -link** ein: Einfügen fügt sofort hinzu, die Eingabetaste bestätigt getippten Text. Der Server wird nur unter seinem Hostnamen gespeichert und seine Zeile fokussiert; der Starter bleibt offen. Klicken Sie zum Öffnen auf diese Zeile. **Einstellungen → Server** bietet dasselbe Feld. -2. Verwenden Sie einen vertrauenswürdigen HTTPS-Ursprung. Besteht sein Zertifikat die Prüfung nicht, erscheint unter dem Feld **TLS-Prüfung überspringen**: Aktivieren Sie dies nur für einen vertrauenswürdigen Server und speichern Sie erneut mit der Eingabetaste. Die Auswahl dieses gespeicherten Servers öffnet ein eigenes Fenster. -3. Melden Sie sich auf diesem Server an. Benennen Sie ihn um oder ändern Sie seine Adresse mit **Server bearbeiten** unter **Einstellungen → Server**. +1. Öffnen Sie auf der Startseite, einem leeren Tab oder im Starter **Tab öffnen** den Bereich **Durchsuchen**. Geben Sie Adresse oder Kopplungslink in **Serveradresse oder -link** ein: Einfügen fügt sofort hinzu, die Eingabetaste bestätigt getippten Text. Der Server wird nur unter seinem Hostnamen gespeichert und seine Zeile fokussiert; der Starter bleibt offen. Klicken Sie auf diese Zeile, um Projekte an Ort und Stelle zu durchsuchen. **Einstellungen → Server** bietet dasselbe Feld. +2. Verwenden Sie einen vertrauenswürdigen HTTPS-Ursprung. Besteht sein Zertifikat die Prüfung nicht, erscheint unter dem Feld **TLS-Prüfung überspringen**: Aktivieren Sie dies nur für einen vertrauenswürdigen Server und speichern Sie erneut mit der Eingabetaste. Die Auswahl eines Ordners oder Projekts dieses Profils öffnet ein eigenes Fenster. +3. Wählen Sie seine Zeile unter **Durchsuchen**, um Projekte an Ort und Stelle zu durchsuchen. Geben Sie bei Bedarf Benutzername und Passwort im eingeblendeten Formular ein. Name und Adresse ändern Sie mit **Server bearbeiten** unter **Einstellungen → Server**. -Gespeicherte Server stehen unter **Durchsuchen**: Wählen Sie einen, um ihn erneut zu öffnen. In **Einstellungen → Server** öffnen, bearbeiten (**Server bearbeiten**: Name, Adresse, Zertifikatsprüfung) und entfernen (**Gespeicherten Server entfernen**) Sie sie. Lesezeichen gehören zu dieser CodeNomad-Konfiguration, nicht den Projekten des Remote-Servers. Eine URL zu speichern startet keinen Server und gewährt keinen Zugriff. **Gespeicherten Server entfernen** entfernt das Lesezeichen, nicht entfernte Unterhaltungen, Backend oder Zugangsdaten. +**Einstellungen → Server** verwaltet Profile (**Server bearbeiten**, **Gespeicherten Server entfernen**). Beim Entfernen werden zuerst die Zugangsdaten und die Suchsitzung im Backend vergessen, dann das Lesezeichen entfernt und seine Tabs geschlossen. Entfernte Projekte und Unterhaltungen bleiben auf ihrem Server. Das lokale Backend speichert Suchzugangsdaten privat in `remote-server-credentials.json` neben seiner Konfiguration; schützen Sie diese Datei wie ein Passwort. Eingebettete Ansichten behalten eine separate Authentifizierung. -Um einen gespeicherten Server direkt von der Befehlszeile zu öffnen, starten Sie die Desktop-App mit `--connect-server ` (oder `--connect-server=`) und dem gespeicherten Namen des Servers oder seiner `https://`-URL. CodeNomad öffnet nur das Remote-Fenster, mit denselben Prüfungen und derselben Anmeldung wie **Durchsuchen**; läuft CodeNomad bereits, öffnet sein aktuelles Fenster den Server statt eines neuen Fensters. Eine URL, die zu keinem gespeicherten Server passt, wird unter ihrem Hostnamen gespeichert. Startwerte enthalten nie Zugangsdaten: Eine URL mit Benutzername, Passwort oder Kopplungscode wird abgelehnt. Ist der Name unbekannt, die URL ungültig oder schlägt die Verbindung fehl, startet CodeNomad normal und zeigt den Fehler an. Braucht die Verbindung eine Bestätigung, etwa die Installation des lokalen Zertifikats für einen selbstsignierten Server, startet CodeNomad ebenfalls normal und fragt dort nach. Unter Windows startet der Tauri-Build nicht, wenn ein Startargument `|` enthält; verwenden Sie stattdessen die URL des Servers oder benennen Sie den Server um. +Um einen gespeicherten Server direkt von der Befehlszeile zu öffnen, starten Sie die Desktop-App mit `--connect-server ` (oder `--connect-server=`) und dem gespeicherten Namen des Servers oder seiner `https://`-URL. CodeNomad öffnet nur das Remote-Fenster, mit den TLS-Prüfungen des Profils und der eigenen Anmeldung des nativen Remote-Fensters; läuft CodeNomad bereits, öffnet sein aktuelles Fenster den Server statt eines neuen Fensters. Eine URL, die zu keinem gespeicherten Server passt, wird unter ihrem Hostnamen gespeichert. Startwerte enthalten nie Zugangsdaten: Eine URL mit Benutzername, Passwort oder Kopplungscode wird abgelehnt. Ist der Name unbekannt, die URL ungültig oder schlägt die Verbindung fehl, startet CodeNomad normal und zeigt den Fehler an. Braucht die Verbindung eine Bestätigung, etwa die Installation des lokalen Zertifikats für einen selbstsignierten Server, startet CodeNomad ebenfalls normal und fragt dort nach. Unter Windows startet der Tauri-Build nicht, wenn ein Startargument `|` enthält; verwenden Sie stattdessen die URL des Servers oder benennen Sie den Server um. Ein Remote-Fenster lässt immer einen Weg zurück zu diesem Computer. Wenn Sie das letzte lokale Fenster schließen, während Remote-Fenster geöffnet bleiben, behält es seine Tabs: **Fenster → Neues Fenster** in einem Remote-Fenster oder ein erneuter Start von CodeNomad öffnet es wieder. Kann ein Server nicht geladen werden, zeigt sein Fenster das an und bietet **Erneut versuchen**, **Lokales Fenster öffnen** und **Fenster schließen**; in der Tauri-Version verwenden Sie die Schaltfläche zum Neuladen der Seite und **Fenster → Neues Fenster**. -Fügen Sie für Fernsteuerung stattdessen einen frischen Kopplungslink in **Serveradresse oder -link** ein. Das Lesezeichen behält nur die Tunnel-Origin, nie den Einmal-Kopplungscode; siehe [Fernsteuerung](remote-control.md) zur erneuten Kopplung nach Verlust des Geräte-Cookies. +Das Einfügen eines Fernsteuerungslinks speichert nur den Tunnel-Ursprung und meldet, dass serverseitige Kopplung nicht verfügbar ist; der Code wird verworfen. Öffnen Sie den Link zum Koppeln im gewünschten Browser. Siehe [Fernsteuerung](remote-control.md). ## Ein Remote-Projekt in einem Tab öffnen {#remote-project-tabs} In der Desktop-App (Electron oder Tauri unter Windows) kann ein gespeicherter Server eines seiner Projekte auch in einem Tab dieses Fensters öffnen, neben Ihren lokalen Projekten: 1. Öffnen Sie auf der Startseite, einem leeren Tab oder im Starter **Tab öffnen** den Bereich **Durchsuchen** und wählen Sie einen gespeicherten Server. Fügen Sie neue Server zuerst über **Serveradresse oder -link** hinzu und klicken Sie dann auf deren Zeile. -2. Wählen Sie den Ordner im Tab. Der Tab zeigt dann das Serversymbol und den Projektnamen, und das Projekt erscheint unter **Zuletzt verwendet**: Dort ausgewählt, öffnet es diesen Server und Ordner direkt wieder. +2. Die Liste zeigt dort die zuletzt verwendeten Projekte und Ordner dieses Servers. Melden Sie sich bei Bedarf im eingeblendeten Formular an. Wählen Sie ein Projekt oder navigieren Sie zu einem Ordner und wählen Sie **Aktuellen auswählen**. **Zurück zu Durchsuchen** führt zur Serverliste. +3. Die Ordnerwahl öffnet den Remote-Projekttab und ersetzt den ursprünglichen leeren Tab. Der `+`-Starter bleibt bis zu dieser Wahl offen. Das Projekt erscheint zum direkten Wiederöffnen unter **Zuletzt verwendet**. -Der Tab zeigt nur dieses Projekt; seine Unterhaltungen, Dateien, Git, Einstellungen und Missions laufen auf dem Remote-Server. Er nutzt den Speicher des Remote-Fensters dieses Servers, sodass eine bestehende Anmeldung oder ein gekoppeltes Gerät wiederverwendet wird, und Remote-Tabs kehren zurück, wenn CodeNomad Ihre Tabs wiederherstellt. Ein Server ohne diesen Modus zeigt im Tab seine vollständige Oberfläche. Server, die die TLS-Prüfung überspringen, sowie der Tauri-Build unter macOS und Linux öffnen weiterhin ein Remote-Fenster. Die Seite in einem Tab kann Benachrichtigungen anzeigen, hat aber sonst keinen Zugriff auf diesen Computer und bleibt auf ihrem Server. Webclients und Remote-Control-Geräte haben keine Remote-Tabs. **Gespeicherten Server entfernen** in **Einstellungen → Server** schließt auch seine Tabs. Bevor ein Projekt gewählt ist, zeigt der Tab den Namen des Servers. Melden Sie sich auf der Seite des Servers im Tab an; CodeNomad verwendet diese Anmeldung bei späteren Starts wieder. +Unterhaltungen, Dateien, Git, Einstellungen und Missions des Tabs laufen auf dem Remote-Server. Seine eingebettete Ansicht teilt den Speicher des Remote-Fensters und kann eine eigene Anmeldung unabhängig von Durchsuchen verlangen. Remote-Tabs werden beim Start wiederhergestellt. Server ohne eingebetteten Modus zeigen ihre vollständige Oberfläche; Profile ohne TLS-Prüfung und Tauri unter macOS/Linux öffnen ein separates Fenster. Die eingebettete Seite bleibt auf ihrem Server und hat nur Benachrichtigungszugriff auf den Host. Webclients und Fernsteuerungsgeräte haben keine Remote-Tabs. + +Die Backend-Suche nutzt direkten CodeNomad-Zugriff mit Adressschutz: CGNAT-/Tailscale-IP-Literale und spezielle Adressbereiche werden abgelehnt. Prüfen Sie Ihr konkretes Ziel, statt jede VPN-Adresse als unterstützt anzusehen. Die Zertifikatsprüfung folgt dem gespeicherten Profil und seiner ausdrücklichen TLS-Bestätigung. diff --git a/docs/help/de/remote-control.md b/docs/help/de/remote-control.md index 31d56a44dd..d59f965101 100644 --- a/docs/help/de/remote-control.md +++ b/docs/help/de/remote-control.md @@ -11,7 +11,7 @@ Fernsteuerung ermöglicht einem gekoppelten Browser- oder Desktop-Client die Nut Der Link gilt **fünf Minuten** und funktioniert **einmal**. Behandeln Sie ihn als Zugangsdaten: Wer ihn einlöst, kann ein gekoppeltes Gerät werden. Der Code steht im URL-Fragment, nicht in der Abfragezeichenfolge. **Neuen Kopplungslink erstellen** macht den vorherigen ungenutzten Link sofort ungültig. Stop, Backend-Ende und Tunnelfehler stornieren offene Kopplungslinks. -Um einen weiteren CodeNomad-Desktop zu koppeln, öffnen Sie auf der Startseite oder einem leeren Tab **Durchsuchen** und fügen den Link in **Serveradresse oder -link** ein. Das fügt nur den Server hinzu; klicken Sie zum Öffnen und Koppeln auf seine gespeicherte Zeile. Der Einmallink wartet im Speicher dieses Fensters bis zum Öffnen oder Neuladen; nutzen Sie ihn innerhalb seiner fünf Minuten Gültigkeit. Nur die Tunnel-Origin wird als Lesezeichen gespeichert. Die TLS-Prüfung bleibt für Kopplungslinks aktiviert. +Öffnen Sie Kopplungslinks im gewünschten Browser. Das Einfügen in **Serveradresse oder -link** auf dem Desktop speichert nur den Tunnel-Ursprung und meldet, dass serverseitige Kopplung nicht verfügbar ist. Der Code wird verworfen. Die Ordnersuche des Backends verwendet eine eigene Direktzugriffssitzung; die eingebettete Ansicht behält unabhängig davon ihre Anmeldung oder ihr Geräte-Cookie. ## Gekoppelte Geräte verwalten {#paired-devices} @@ -28,7 +28,7 @@ Eine Änderung des Direktzugriffspassworts widerruft Geräte **nicht**. **Fernst ### Ohne Positionsverlust erneut koppeln {#re-pair} 1. Zeigt der Client **Dieses Gerät erneut koppeln**, lassen Sie diese Seite offen. -2. Wählen Sie auf dem Host **Neuen Kopplungslink erstellen** und öffnen Sie ihn im **selben Client-Browser/-Profil**. Verbinden Sie bei gespeichertem Desktop-Server mit dem frischen Link neu, damit der vorhandene Remote-Fensterspeicher wiederverwendet wird. +2. Wählen Sie auf dem Host **Neuen Kopplungslink erstellen** und öffnen Sie ihn im **selben Client-Browser/-Profil**. 3. Kehren Sie zur wartenden Seite zurück und wählen Sie **Verbindung prüfen**; sie prüft auch erneut, wenn die Seite wieder den Fokus erhält. Die Wiederherstellung bewahrt die geöffnete Seite und Entwürfe; sie wiederholt keine fehlgeschlagene Aktion. Prüfen Sie vor Wiederholung, ob Senden, Antworten oder Löschen wirksam war. Ein Direktzugriffspasswort kann die Fernsteuerungskopplung nicht wiederherstellen. diff --git a/docs/help/en/projects.md b/docs/help/en/projects.md index c0c0aac2ad..1fcad2467f 100644 --- a/docs/help/en/projects.md +++ b/docs/help/en/projects.md @@ -4,12 +4,14 @@ A project tab connects CodeNomad to a folder on the backend computer. Opening a ## Open a project {#open-project} -1. Click **New instance** (`+`) to open an empty **New tab**, focused on search. It shares Home's background, centered CodeNomad logo and name, large **Clone Git Repo**, **New temporary tab** and **New SideCar** buttons, and the **Recent | Browse** selector with item counts. Search sits below the selector in **Recent**. Choosing a project, saved server or SideCar fills that tab in place. An empty tab lasts until the window reloads and closes without leaving a project. The CodeNomad logo in the title bar or tab bar opens Home, which also offers settings, language and the heart **Sponsor** button ([Support CodeNomad](sponsor.md)). +1. Click **New instance** (`+`) to open an empty **New tab**, focused on search. It shares Home's background, centered CodeNomad logo and name, large **Clone Git Repo**, **New temporary tab** and **New SideCar** buttons, and the **Recent | Browse** selector with item counts. Search sits below the selector in **Recent**. Choosing a local or remote project or a SideCar fills that tab in place. An empty tab lasts until the window reloads and closes without leaving a project. The CodeNomad logo in the title bar or tab bar opens Home, which also offers settings, language and the heart **Sponsor** button ([Support CodeNomad](sponsor.md)). 2. In **Recent**, choose a project; or open **Browse**, choose **This computer**, then select the backend folder and open it. **Browse** also lists saved CodeNomad servers ([remote project tabs](remote-access.md#remote-project-tabs)) and SideCars ([SideCars](browser-sidecars.md#register-sidecar)). 3. For a repository copy, choose **Clone Git Repo**, enter **Repository URL** and **Destination folder**, then **Clone**. **Destination folder** is prefilled with the repository name in the folder that holds your last clone, or next to your most recent project. **Browse** chooses the folder that contains the clone; you can also edit the path, including the clone's folder name. Browsing a remote server means browsing that server's filesystem, not your phone or laptop. Opening a project does not create a separate OpenCode daemon for each tab. Conversations are native OpenCode sessions; their lifetime is not the tab's lifetime. +Choosing a saved server in **Browse** replaces the list with its recent projects and folders. Sign in inline if requested, then choose a recent project or navigate to a folder and use **Select Current**. **Back to Browse** returns to the servers. Only choosing a project fills the empty tab and dismisses the `+` launcher. The remote tab may request its own sign-in separately from browsing. + Cloning writes a repository to the destination. **Remove the destination folder first if it already exists.** is destructive: enable it only when everything already there can be deleted. Use a fresh destination if unsure. A failed clone is not a reason to delete an existing project; inspect the reported destination and error before retrying. Recent entries are shortcuts. **Rename workspace** changes its displayed name; **Remove from recent** removes the shortcut, not its files or conversations. Clicking an already-open recent project opens a new tab; its **Open** button (**Switch to open project**) selects the existing tab instead. diff --git a/docs/help/en/remote-access.md b/docs/help/en/remote-access.md index a043ca6d88..d60632fa09 100644 --- a/docs/help/en/remote-access.md +++ b/docs/help/en/remote-access.md @@ -83,23 +83,26 @@ If a client reports a certificate warning, stop and check the hostname, SANs, tr ## Save a remote server {#saved-servers} -1. On Home, an empty tab or the **Open a tab** launcher, open **Browse** and enter the address or pairing link in **Server address or link**. Pasting adds it immediately; Enter adds typed text. Adding only saves the server under its host name and focuses its row; the launcher stays open. Click the saved row to open it. **Settings → Servers** offers the same field. -2. Use a trusted HTTPS origin. If its certificate fails the check, the error shows under the field with **Skip TLS verification**: tick it only for a server you trust, then press Enter again to save it. Selecting that saved server opens its own window. -3. Sign in on that server. Rename it or change its address with **Edit server** in **Settings → Servers**. +1. On Home, an empty tab or the **Open a tab** launcher, open **Browse** and enter the address or pairing link in **Server address or link**. Pasting adds it immediately; Enter adds typed text. Adding only saves the server under its host name and focuses its row; the launcher stays open. Click the saved row to browse projects in place. **Settings → Servers** offers the same field. +2. Use a trusted HTTPS origin. If its certificate fails the check, the error shows under the field with **Skip TLS verification**: tick it only for a server you trust, then press Enter again to save it. Choosing a folder or project on that profile opens its own window. +3. Choose its saved **Browse** row to browse projects in place. If prompted, enter the server username and password in the inline form. Rename it or change its address with **Edit server** in **Settings → Servers**. -Saved servers are listed under **Browse**: choose one to open it again. **Settings → Servers** is where you open, edit (**Edit server**: name, address, certificate check) and remove (**Remove saved server**) them. Bookmarks belong to this CodeNomad configuration, not the remote server's projects. Saving a URL does not start the server or grant access. **Remove saved server** removes the bookmark, not remote conversations, the backend or its credentials. +**Settings → Servers** manages saved profiles (**Edit server**, **Remove saved server**). Removing a profile first forgets its backend-held browsing credentials and session, then removes the bookmark and closes its tabs. Remote projects and conversations stay on their server. The local backend stores browsing secrets privately in `remote-server-credentials.json` beside its configuration; protect that file as a password. Embedded views keep their own authentication separately. -To open a saved server straight from the command line, start the desktop app with `--connect-server ` (or `--connect-server=`), using the server's saved name, or with its `https://` URL. CodeNomad opens only the remote window, with the same checks and sign-in as **Browse**; when CodeNomad is already running, its current window opens it instead of a new one. A URL that matches no saved server is saved under its host name. Launch values never carry credentials: a URL with a user name, password or pairing code is refused. If the name is unknown, the URL is invalid or the connection fails, CodeNomad starts normally and shows the error. When the connection needs a confirmation, such as installing the local certificate for a self-signed server, CodeNomad also starts normally and asks there. On Windows, the Tauri build refuses to start when a launch argument contains `|`; use the server's URL instead, or rename the server. +To open a saved server straight from the command line, start the desktop app with `--connect-server ` (or `--connect-server=`), using the server's saved name, or with its `https://` URL. CodeNomad opens only the remote window, using the profile's TLS checks and the native remote window's own sign-in; when CodeNomad is already running, its current window opens it instead of a new one. A URL that matches no saved server is saved under its host name. Launch values never carry credentials: a URL with a user name, password or pairing code is refused. If the name is unknown, the URL is invalid or the connection fails, CodeNomad starts normally and shows the error. When the connection needs a confirmation, such as installing the local certificate for a self-signed server, CodeNomad also starts normally and asks there. On Windows, the Tauri build refuses to start when a launch argument contains `|`; use the server's URL instead, or rename the server. A remote window always leaves a way back to this computer. Closing the last local window while remote windows stay open keeps its tabs: **Window → New Window** in a remote window, or starting CodeNomad again, reopens it. If a server cannot be loaded, its window says so and offers **Try again**, **Open a local window** and **Close window**; in the Tauri build, use the page's reload button and **Window → New Window**. -For Remote Control, paste a fresh pairing link into **Server address or link** instead. The bookmark retains only the tunnel origin, never the one-use pairing code; see [Remote Control](remote-control.md) for re-pairing after device-cookie loss. +Pasting a Remote Control pairing link saves only its tunnel origin and reports that server-side pairing is unavailable; the code is discarded. Open the link in the intended browser to pair there. See [Remote Control](remote-control.md). ## Open a remote project in a tab {#remote-project-tabs} In the desktop app (Electron, or Tauri on Windows), a saved server can also open one of its projects in a tab of this window, beside your local projects: 1. On Home, an empty tab or the **Open a tab** launcher, open **Browse** and choose a saved server. To add one first, use **Server address or link**, then click its new row. -2. Pick the folder in the tab. The tab then shows the server icon and the project name, and the project joins **Recent**: choosing it there reopens that server and folder directly. +2. The list switches in place to that server's recent projects and folders. Sign in with the inline username/password form if needed. Choose a recent project, or navigate folders and choose **Select Current**. **Back to Browse** returns to the server list. +3. Choosing the folder opens its remote project tab, replacing the originating empty tab. The `+` launcher stays open until this choice. The project joins **Recent** for reopening directly. -The tab shows only that project; its conversations, files, Git, settings and Missions run on the remote server. It uses the storage of the server's remote window, so an existing sign-in or paired device is reused, and remote tabs come back when CodeNomad restores your tabs. A server without this mode shows its full interface in the tab. Servers that skip TLS verification, and the Tauri build on macOS and Linux, keep opening a remote window. The page in a tab can show notifications but has no other access to this computer and stays on its server. Web clients and Remote Control devices have no remote tabs. **Remove saved server**, in **Settings → Servers**, also closes its tabs. Before a project is chosen, the tab shows the server's name. Sign in on the server's page in the tab; CodeNomad reuses that sign-in on later launches. +The tab's conversations, files, Git, settings and Missions run on the remote server. Its embedded view shares that server's remote-window storage and may ask you to sign in separately from Browse. Remote tabs participate in startup restoration. Servers without embedded mode show their full interface; profiles that skip TLS verification and Tauri on macOS/Linux open a separate remote window. The embedded page stays on its server and has only notification access to the host. Web clients and Remote Control devices have no remote tabs. + +Backend browsing supports direct CodeNomad access subject to address safeguards: CGNAT/Tailscale IP literals and special-use address ranges are rejected. Check your actual destination rather than assuming every VPN address works. Certificate verification follows the saved profile and its explicit TLS confirmation. diff --git a/docs/help/en/remote-control.md b/docs/help/en/remote-control.md index 09a0d732bc..af66ffbf60 100644 --- a/docs/help/en/remote-control.md +++ b/docs/help/en/remote-control.md @@ -11,7 +11,7 @@ Remote Control lets a paired browser or desktop client use your running CodeNoma The link is valid for **five minutes** and succeeds **once**. Treat it as a credential: anyone who consumes it can become a paired device. The code lives in the URL fragment, not the query string. **Create new pairing link** immediately invalidates the preceding unused link. Stop, backend shutdown and tunnel failure cancel outstanding pairing links. -To pair another desktop CodeNomad, open **Browse** on Home or an empty tab and paste the link into **Server address or link**. This only adds the server; click its saved row to open and pair. The one-use link waits in memory in this window until you open it or reload; use it within its five-minute lifetime. Only the tunnel origin is saved as the bookmark. TLS verification stays enabled for pairing links. +Open pairing links in the intended browser. Pasting one into desktop **Server address or link** saves only the tunnel origin and reports that server-side pairing is unavailable. The code is discarded. Backend folder browsing uses its own direct-access session; an embedded view keeps its own sign-in or paired-device cookie independently. ## Manage paired devices {#paired-devices} @@ -28,7 +28,7 @@ Changing the direct-access password does **not** revoke devices. **Stop Remote C ### Re-pair without losing your place {#re-pair} 1. If the client shows **Pair this device again**, leave that page open. -2. On the host, choose **Create new pairing link** and open it in the **same client browser/profile**. For a saved desktop server, reconnect using the fresh pairing link so its existing remote-window storage is reused. +2. On the host, choose **Create new pairing link** and open it in the **same client browser/profile**. 3. Return to the waiting page and choose **Check connection**; it also checks again when the page regains focus. Recovery preserves the open page and drafts; it does not replay a failed action. Check whether a send, answer or delete took effect before retrying it. A direct-access password cannot recover Remote Control pairing. diff --git a/docs/help/es/projects.md b/docs/help/es/projects.md index f570437cbb..50b02a6ef2 100644 --- a/docs/help/es/projects.md +++ b/docs/help/es/projects.md @@ -4,12 +4,14 @@ Una pestaña de proyecto conecta CodeNomad a una carpeta del equipo del backend. ## Abrir un proyecto {#open-project} -1. **Nueva instancia** (`+`) abre una **Nueva pestaña** vacía con el foco en la búsqueda. Comparte el fondo, logotipo y nombre CodeNomad centrados y los botones grandes de Inicio: **Clonar repo Git**, **Nueva pestaña temporal** y **Nuevo SideCar**. El selector **Recientes | Explorar** muestra cantidades; la búsqueda está debajo, en **Recientes**. Elegir un proyecto, servidor guardado o SideCar llena esa pestaña en su posición. La pestaña vacía dura hasta recargar y se cierra sin dejar un proyecto. El logotipo CodeNomad en la barra de título o pestañas abre Inicio, con configuración, idioma y el botón con corazón **Patrocinar** ([Apoyar CodeNomad](sponsor.md)). +1. **Nueva instancia** (`+`) abre una **Nueva pestaña** vacía con el foco en la búsqueda. Comparte el fondo, logotipo y nombre CodeNomad centrados y los botones grandes de Inicio: **Clonar repo Git**, **Nueva pestaña temporal** y **Nuevo SideCar**. El selector **Recientes | Explorar** muestra cantidades; la búsqueda está debajo, en **Recientes**. Elegir un proyecto local o remoto o un SideCar llena esa pestaña en su posición. La pestaña vacía dura hasta recargar y se cierra sin dejar un proyecto. El logotipo CodeNomad en la barra de título o pestañas abre Inicio, con configuración, idioma y el botón con corazón **Patrocinar** ([Apoyar CodeNomad](sponsor.md)). 2. En **Recientes**, elige un proyecto; o abre **Explorar**, elige **Este equipo** y luego selecciona la carpeta del backend y ábrela. **Explorar** también lista los servidores CodeNomad guardados ([pestañas de proyectos remotos](remote-access.md#remote-project-tabs)) y los SideCars ([SideCars](browser-sidecars.md#register-sidecar)). 3. Para obtener una copia de un repositorio, elige **Clonar repo Git**, introduce la **URL del repositorio** y la **Carpeta de destino** y pulsa **Clonar**. La **Carpeta de destino** se rellena con el nombre del repositorio en la carpeta que contiene tu último clon, o junto a tu proyecto más reciente. **Buscar** elige la carpeta que contendrá el clon; también puedes editar la ruta, incluido el nombre de la carpeta del clon. Explorar un servidor remoto significa explorar el sistema de archivos de ese servidor, no el de tu teléfono o portátil. Abrir un proyecto no crea un daemon de OpenCode distinto para cada pestaña. Las conversaciones son sesiones nativas de OpenCode; su duración no es la de la pestaña. +Elegir un servidor en **Explorar** sustituye la lista por sus proyectos recientes y carpetas. Inicia sesión en el formulario integrado si se solicita y elige un proyecto o navega a una carpeta y pulsa **Seleccionar actual**. Volver a Explorar muestra los servidores. Solo elegir un proyecto rellena la pestaña vacía y cierra el lanzador `+`. La pestaña remota puede pedir su propio inicio de sesión, separado de la exploración. + La clonación escribe un repositorio en el destino. **Eliminar primero la carpeta de destino si ya existe.** es destructivo: actívalo solo si se puede borrar todo lo que ya haya allí. Usa un destino nuevo si tienes dudas. Una clonación fallida no es motivo para eliminar un proyecto existente; inspecciona el destino y el error indicados antes de reintentar. Las entradas recientes son accesos directos. **Renombrar workspace** cambia su nombre visible; **Eliminar de recientes** elimina el acceso directo, no sus archivos ni conversaciones. Hacer clic en un proyecto reciente que ya esté abierto abre una pestaña nueva; su botón **Abierta** (**Cambiar al proyecto abierto**) selecciona en cambio la pestaña existente. diff --git a/docs/help/es/remote-access.md b/docs/help/es/remote-access.md index 116f5db89a..c864042773 100644 --- a/docs/help/es/remote-access.md +++ b/docs/help/es/remote-access.md @@ -83,23 +83,26 @@ Si un cliente muestra una advertencia de certificado, detente y comprueba el nom ## Guardar un servidor remoto {#saved-servers} -1. En Inicio, una pestaña vacía o el lanzador **Abrir una pestaña**, abre **Explorar** e introduce la dirección o enlace de emparejamiento en **Dirección o enlace del servidor**. Pegar lo añade al instante; Intro confirma el texto escrito. Solo se guarda el servidor con su nombre de host y se enfoca su fila; el lanzador permanece abierto. Haz clic en la fila para abrirlo. **Configuración → Servidores** ofrece el mismo campo. -2. Usa un origen HTTPS de confianza. Si su certificado no supera la verificación, aparece **Omitir la verificación TLS** bajo el campo: márcala solo para un servidor de confianza y pulsa Intro de nuevo para guardarlo. Seleccionar ese servidor guardado abre su propia ventana. -3. Inicia sesión en ese servidor. Cambia su nombre o su dirección con **Editar servidor** en **Configuración → Servidores**. +1. En Inicio, una pestaña vacía o el lanzador **Abrir una pestaña**, abre **Explorar** e introduce la dirección o enlace de emparejamiento en **Dirección o enlace del servidor**. Pegar lo añade al instante; Intro confirma el texto escrito. Solo se guarda el servidor con su nombre de host y se enfoca su fila; el lanzador permanece abierto. Haz clic en la fila para explorar sus proyectos en la misma lista. **Configuración → Servidores** ofrece el mismo campo. +2. Usa un origen HTTPS de confianza. Si su certificado no supera la verificación, aparece **Omitir la verificación TLS** bajo el campo: márcala solo para un servidor de confianza y pulsa Intro de nuevo para guardarlo. Elegir una carpeta o proyecto de ese perfil abre su propia ventana. +3. Elige su fila en **Explorar** para ver los proyectos en la misma lista. Si se solicita, introduce usuario y contraseña del servidor en el formulario integrado. Cambia su nombre o dirección con **Editar servidor** en **Configuración → Servidores**. -Los servidores guardados aparecen en **Explorar**: elige uno para volver a abrirlo. En **Configuración → Servidores** se abren, se editan (**Editar servidor**: nombre, dirección, verificación del certificado) y se quitan (**Eliminar servidor guardado**). Los marcadores pertenecen a esta configuración de CodeNomad, no a los proyectos del servidor remoto. Guardar una URL no inicia el servidor ni concede acceso. **Eliminar servidor guardado** elimina el marcador, no las conversaciones remotas, el backend ni sus credenciales. +**Configuración → Servidores** gestiona los perfiles (**Editar servidor**, **Eliminar servidor guardado**). Al eliminar uno, primero se olvidan sus credenciales y sesión de exploración del backend, después se quita el marcador y se cierran sus pestañas. Los proyectos y conversaciones remotos permanecen en su servidor. El backend local guarda los secretos de exploración en `remote-server-credentials.json`, junto a su configuración; protege ese archivo como una contraseña. Las vistas integradas mantienen una autenticación separada. -Para abrir un servidor guardado directamente desde la línea de comandos, inicia la aplicación de escritorio con `--connect-server ` (o `--connect-server=`), usando el nombre guardado del servidor o su URL `https://`. CodeNomad abre solo la ventana remota, con las mismas comprobaciones e inicio de sesión que **Explorar**; si CodeNomad ya se está ejecutando, su ventana actual lo abre en lugar de una nueva. Una URL que no coincide con ningún servidor guardado se guarda con su nombre de host. Los valores de inicio nunca llevan credenciales: se rechaza una URL con nombre de usuario, contraseña o código de emparejamiento. Si el nombre es desconocido, la URL no es válida o la conexión falla, CodeNomad se inicia con normalidad y muestra el error. Cuando la conexión necesita una confirmación, como instalar el certificado local para un servidor autofirmado, CodeNomad también se inicia con normalidad y la pide allí. En Windows, la compilación Tauri no se inicia si un argumento de inicio contiene `|`; usa en su lugar la URL del servidor o cambia el nombre del servidor. +Para abrir un servidor guardado directamente desde la línea de comandos, inicia la aplicación de escritorio con `--connect-server ` (o `--connect-server=`), usando el nombre guardado del servidor o su URL `https://`. CodeNomad abre solo la ventana remota, con las comprobaciones TLS del perfil y el inicio de sesión propio de la ventana remota nativa; si CodeNomad ya se está ejecutando, su ventana actual lo abre en lugar de una nueva. Una URL que no coincide con ningún servidor guardado se guarda con su nombre de host. Los valores de inicio nunca llevan credenciales: se rechaza una URL con nombre de usuario, contraseña o código de emparejamiento. Si el nombre es desconocido, la URL no es válida o la conexión falla, CodeNomad se inicia con normalidad y muestra el error. Cuando la conexión necesita una confirmación, como instalar el certificado local para un servidor autofirmado, CodeNomad también se inicia con normalidad y la pide allí. En Windows, la compilación Tauri no se inicia si un argumento de inicio contiene `|`; usa en su lugar la URL del servidor o cambia el nombre del servidor. Una ventana remota siempre deja una forma de volver a este equipo. Cerrar la última ventana local mientras siguen abiertas ventanas remotas conserva sus pestañas: **Ventana → Nueva ventana** en una ventana remota, o iniciar CodeNomad de nuevo, la vuelve a abrir. Si un servidor no se puede cargar, su ventana lo indica y ofrece **Reintentar**, **Abrir una ventana local** y **Cerrar ventana**; en la versión Tauri, usa el botón de recarga de la página y **Ventana → Nueva ventana**. -Para Control remoto, pega en su lugar un enlace de emparejamiento nuevo en **Dirección o enlace del servidor**. El marcador conserva solo el origen del túnel, nunca el código de un solo uso; consulta [Control remoto](remote-control.md) para volver a emparejar tras perder la cookie del dispositivo. +Pegar un enlace de Control remoto solo guarda el origen del túnel e informa de que el emparejamiento del lado del servidor no está disponible; el código se descarta. Abre el enlace en el navegador deseado para emparejarlo. Consulta [Control remoto](remote-control.md). ## Abrir un proyecto remoto en una pestaña {#remote-project-tabs} En la aplicación de escritorio (Electron, o Tauri en Windows), un servidor guardado también puede abrir uno de sus proyectos en una pestaña de esta ventana, junto a tus proyectos locales: 1. En Inicio, una pestaña vacía o el lanzador **Abrir una pestaña**, abre **Explorar** y elige un servidor guardado. Para añadirlo primero, usa **Dirección o enlace del servidor** y haz clic en su nueva fila. -2. Elige la carpeta en la pestaña. La pestaña muestra entonces el icono de servidor y el nombre del proyecto, y el proyecto se suma a **Recientes**: elegirlo allí vuelve a abrir directamente ese servidor y esa carpeta. +2. La lista pasa a mostrar los proyectos recientes y carpetas de ese servidor. Inicia sesión en el formulario integrado si hace falta. Elige un proyecto reciente o navega por las carpetas y pulsa **Seleccionar actual**. **Volver a Explorar** regresa a la lista de servidores. +3. Elegir la carpeta abre su pestaña remota y sustituye la pestaña vacía de origen. El lanzador `+` permanece abierto hasta esa elección. El proyecto se añade a **Recientes** para abrirlo directamente. -La pestaña muestra solo ese proyecto; sus conversaciones, archivos, Git, ajustes y Missions se ejecutan en el servidor remoto. Usa el almacenamiento de la ventana remota del servidor, así que se reutiliza un inicio de sesión o un dispositivo emparejado existente, y las pestañas remotas vuelven cuando CodeNomad restaura tus pestañas. Un servidor sin este modo muestra su interfaz completa en la pestaña. Los servidores que omiten la verificación TLS, y la versión Tauri en macOS y Linux, siguen abriendo una ventana remota. La página de una pestaña puede mostrar notificaciones, pero no tiene otro acceso a este equipo y permanece en su servidor. Los clientes web y los dispositivos de Remote Control no tienen pestañas remotas. **Eliminar servidor guardado**, en **Configuración → Servidores**, también cierra sus pestañas. Antes de elegir un proyecto, la pestaña muestra el nombre del servidor. Inicia sesión en la página del servidor, dentro de la pestaña; CodeNomad reutiliza ese inicio de sesión en los siguientes arranques. +Las conversaciones, archivos, Git, ajustes y Missions de la pestaña se ejecutan en el servidor remoto. Su vista integrada comparte el almacenamiento de la ventana remota y puede pedir otro inicio de sesión independiente de Explorar. Las pestañas remotas participan en la restauración al iniciar. Los servidores sin modo integrado muestran su interfaz completa; los perfiles que omiten TLS y Tauri en macOS/Linux abren otra ventana. La página integrada permanece en su servidor y solo dispone de notificaciones en el anfitrión. Los clientes web y dispositivos de Control remoto carecen de pestañas remotas. + +La exploración del backend utiliza acceso directo a CodeNomad con protecciones de direcciones: rechaza IP literales CGNAT/Tailscale y rangos especiales. Comprueba el destino real sin asumir que cualquier dirección VPN funciona. La verificación del certificado sigue el perfil guardado y su confirmación TLS explícita. diff --git a/docs/help/es/remote-control.md b/docs/help/es/remote-control.md index 6ccf99f640..6f46ce8fa8 100644 --- a/docs/help/es/remote-control.md +++ b/docs/help/es/remote-control.md @@ -11,7 +11,7 @@ Control remoto permite a un navegador o cliente de escritorio emparejado usar tu El enlace es válido durante **cinco minutos** y funciona **una vez**. Trátalo como una credencial: cualquiera que lo consuma puede convertirse en un dispositivo emparejado. El código está en el fragmento de la URL, no en la cadena de consulta. **Crear nuevo enlace de emparejamiento** invalida inmediatamente el enlace anterior sin usar. Detener, apagar el backend y los fallos del túnel cancelan los enlaces de emparejamiento pendientes. -Para emparejar otro CodeNomad de escritorio, abre **Explorar** en Inicio o una pestaña vacía y pega el enlace en **Dirección o enlace del servidor**. Esto solo añade el servidor; haz clic en su fila guardada para abrir y emparejar. El enlace de un solo uso espera en la memoria de esta ventana hasta abrirlo o recargar; úsalo durante sus cinco minutos de validez. Solo se guarda el origen del túnel como marcador. La verificación TLS permanece activada para los enlaces de emparejamiento. +Abre los enlaces de emparejamiento en el navegador deseado. Pegarlos en **Dirección o enlace del servidor** del escritorio solo guarda el origen del túnel e informa de que el emparejamiento del lado del servidor no está disponible. El código se descarta. La exploración de carpetas del backend utiliza su propia sesión de acceso directo; la vista integrada conserva su inicio de sesión o cookie de dispositivo de forma independiente. ## Gestionar dispositivos emparejados {#paired-devices} @@ -28,7 +28,7 @@ Cambiar la contraseña de acceso directo **no** revoca dispositivos. **Detener c ### Volver a emparejar sin perder tu lugar {#re-pair} 1. Si el cliente muestra **Vincular de nuevo este dispositivo**, deja abierta esa página. -2. En el anfitrión, elige **Crear nuevo enlace de emparejamiento** y ábrelo en el **mismo navegador/perfil del cliente**. Para un servidor de escritorio guardado, reconecta usando el enlace nuevo para reutilizar el almacenamiento de su ventana remota existente. +2. En el anfitrión, elige **Crear nuevo enlace de emparejamiento** y ábrelo en el **mismo navegador/perfil del cliente**. 3. Vuelve a la página en espera y elige **Comprobar conexión**; también vuelve a comprobarla cuando la página recupera el foco. La recuperación conserva la página abierta y los borradores; no repite una acción fallida. Comprueba si un envío, respuesta o eliminación surtió efecto antes de reintentarlo. Una contraseña de acceso directo no puede recuperar el emparejamiento de Control remoto. diff --git a/docs/help/fr/projects.md b/docs/help/fr/projects.md index 2d3020356d..c080a2ad35 100644 --- a/docs/help/fr/projects.md +++ b/docs/help/fr/projects.md @@ -4,12 +4,14 @@ Un onglet de projet relie CodeNomad à un dossier sur l’ordinateur du backend. ## Ouvrir un projet {#open-project} -1. Cliquez sur **Nouvelle instance** (`+`) pour ouvrir un **Nouvel onglet** vide, avec le focus dans la recherche. Il reprend le fond de l'accueil, le logo et le nom CodeNomad centrés, les grands boutons **Cloner un dépôt Git**, **Nouvel onglet temporaire** et **Nouveau SideCar**, et le sélecteur **Récents | Parcourir** avec compteurs. La recherche est sous le sélecteur dans **Récents**. Choisir un projet, un serveur enregistré ou un SideCar remplit cet onglet sur place. Un onglet vide dure jusqu'au rechargement de la fenêtre et se ferme sans laisser de projet. Le logo CodeNomad de la barre de titre ou d'onglets ouvre l'accueil, qui propose aussi les réglages, la langue et le bouton cœur **Sponsor** ([Soutenir CodeNomad](sponsor.md)). +1. Cliquez sur **Nouvelle instance** (`+`) pour ouvrir un **Nouvel onglet** vide, avec le focus dans la recherche. Il reprend le fond de l'accueil, le logo et le nom CodeNomad centrés, les grands boutons **Cloner un dépôt Git**, **Nouvel onglet temporaire** et **Nouveau SideCar**, et le sélecteur **Récents | Parcourir** avec compteurs. La recherche est sous le sélecteur dans **Récents**. Choisir un projet local ou distant ou un SideCar remplit cet onglet sur place. Un onglet vide dure jusqu'au rechargement de la fenêtre et se ferme sans laisser de projet. Le logo CodeNomad de la barre de titre ou d'onglets ouvre l'accueil, qui propose aussi les réglages, la langue et le bouton cœur **Sponsor** ([Soutenir CodeNomad](sponsor.md)). 2. Dans **Récents**, choisissez un projet ; ou ouvrez **Parcourir**, choisissez **Cet ordinateur**, puis sélectionnez le dossier du backend et ouvrez-le. **Parcourir** liste aussi les serveurs CodeNomad enregistrés ([onglets de projets distants](remote-access.md#remote-project-tabs)) et les SideCars ([SideCars](browser-sidecars.md#register-sidecar)). 3. Pour une copie de dépôt, choisissez **Cloner un depot Git**, saisissez **URL du depot** et **Dossier de destination**, puis **Cloner**. **Dossier de destination** est prérempli avec le nom du dépôt, dans le dossier qui contient votre dernier clone, sinon à côté de votre projet le plus récent. **Parcourir** choisit le dossier qui contiendra le clone ; vous pouvez aussi modifier le chemin, y compris le nom du dossier du clone. Parcourir un serveur distant signifie parcourir son système de fichiers, pas votre téléphone ou ordinateur portable. Ouvrir un projet ne crée pas un démon OpenCode distinct par onglet. Les conversations sont des sessions natives OpenCode ; leur durée de vie n’est pas celle de l’onglet. +Choisir un serveur dans **Parcourir** remplace la liste par ses projets récents et ses dossiers. Connectez-vous dans le formulaire intégré si demandé, puis choisissez un projet récent ou un dossier avec **Sélectionner le dossier actuel**. Le retour à Parcourir affiche les serveurs. Seul le choix d’un projet remplit l’onglet vide et ferme le lanceur `+`. L’onglet distant peut demander sa propre connexion, séparément du parcours. + Le clonage écrit un dépôt dans la destination. **Supprimer d'abord le dossier de destination s'il existe deja.** est destructeur : n’activez cette option que si tout ce qui s’y trouve peut être supprimé. Dans le doute, utilisez une nouvelle destination. Un échec de clonage n’est pas une raison de supprimer un projet existant ; vérifiez la destination et l’erreur signalées avant de réessayer. Les entrées récentes sont des raccourcis. **Renommer l'espace de travail** change son nom affiché ; **Retirer des récents** retire le raccourci, pas ses fichiers ni ses conversations. Cliquer sur un projet récent déjà ouvert ouvre un nouvel onglet ; son bouton **Ouvert** (**Basculer vers le projet ouvert**) sélectionne plutôt l’onglet existant. diff --git a/docs/help/fr/remote-access.md b/docs/help/fr/remote-access.md index ef102f81f5..5a9328dbc4 100644 --- a/docs/help/fr/remote-access.md +++ b/docs/help/fr/remote-access.md @@ -83,23 +83,26 @@ Si un client signale un avertissement de certificat, arrêtez-vous et vérifiez ## Enregistrer un serveur distant {#saved-servers} -1. Sur l’accueil, un onglet vide ou le lanceur **Ouvrir un onglet**, ouvrez **Parcourir** et saisissez l’adresse ou le lien d’appairage dans **Adresse ou lien du serveur**. Le collage l’ajoute immédiatement ; Entrée ajoute le texte saisi. L’ajout enregistre seulement le serveur sous son nom d’hôte et place le focus sur sa ligne ; le lanceur reste ouvert. Cliquez sur cette ligne pour l’ouvrir. **Paramètres → Serveurs** propose le même champ. -2. Utilisez une origine HTTPS de confiance. Si son certificat échoue à la vérification, l’erreur s’affiche sous le champ avec **Ignorer la vérification TLS** : cochez-la seulement pour un serveur de confiance, puis appuyez de nouveau sur Entrée pour l’enregistrer. Sélectionner ce serveur enregistré ouvre sa propre fenêtre. -3. Connectez-vous sur ce serveur. Renommez-le ou changez son adresse avec **Modifier le serveur** dans **Paramètres → Serveurs**. +1. Sur l’accueil, un onglet vide ou le lanceur **Ouvrir un onglet**, ouvrez **Parcourir** et saisissez l’adresse ou le lien d’appairage dans **Adresse ou lien du serveur**. Le collage l’ajoute immédiatement ; Entrée ajoute le texte saisi. L’ajout enregistre seulement le serveur sous son nom d’hôte et place le focus sur sa ligne ; le lanceur reste ouvert. Cliquez sur cette ligne pour parcourir ses projets sur place. **Paramètres → Serveurs** propose le même champ. +2. Utilisez une origine HTTPS de confiance. Si son certificat échoue à la vérification, l’erreur s’affiche sous le champ avec **Ignorer la vérification TLS** : cochez-la seulement pour un serveur de confiance, puis appuyez de nouveau sur Entrée pour l’enregistrer. Choisir un dossier ou un projet de ce profil ouvre sa propre fenêtre. +3. Choisissez sa ligne dans **Parcourir** pour explorer ses projets sur place. Si demandé, saisissez le nom d’utilisateur et le mot de passe du serveur dans le formulaire intégré. Modifiez son nom ou son adresse avec **Modifier le serveur** dans **Paramètres → Serveurs**. -Les serveurs enregistrés sont listés sous **Parcourir** : choisissez-en un pour l’ouvrir de nouveau. **Paramètres → Serveurs** permet de les ouvrir, de les modifier (**Modifier le serveur** : nom, adresse, vérification du certificat) et de les retirer (**Supprimer le serveur enregistré**). Les favoris appartiennent à cette configuration CodeNomad, pas aux projets du serveur distant. Enregistrer une URL ne démarre pas le serveur et n’accorde pas l’accès. **Supprimer le serveur enregistré** retire le favori, pas les conversations distantes, le backend ou ses identifiants. +**Paramètres → Serveurs** gère les profils (**Modifier le serveur**, **Supprimer le serveur enregistré**). La suppression oublie d’abord les identifiants et la session de parcours conservés par le backend, puis retire le favori et ferme ses onglets. Les projets et conversations distants restent sur leur serveur. Le backend local conserve les secrets de parcours dans `remote-server-credentials.json`, à côté de sa configuration ; protégez ce fichier comme un mot de passe. Les vues intégrées gardent leur authentification séparément. -Pour ouvrir un serveur enregistré directement depuis la ligne de commande, lancez l’application de bureau avec `--connect-server ` (ou `--connect-server=`), en indiquant le nom enregistré du serveur ou son URL `https://`. CodeNomad n’ouvre que la fenêtre distante, avec les mêmes vérifications et la même connexion que **Parcourir** ; si CodeNomad est déjà lancé, sa fenêtre actuelle l’ouvre au lieu d’une nouvelle fenêtre. Une URL qui ne correspond à aucun serveur enregistré est enregistrée sous son nom d’hôte. Les valeurs de lancement ne portent jamais d’identifiants : une URL avec un nom d’utilisateur, un mot de passe ou un code d’appairage est refusée. Si le nom est inconnu, l’URL invalide ou la connexion échoue, CodeNomad démarre normalement et affiche l’erreur. Quand la connexion demande une confirmation, comme l’installation du certificat local pour un serveur auto-signé, CodeNomad démarre aussi normalement et la demande là. Sous Windows, la version Tauri refuse de démarrer quand un argument de lancement contient `|` ; utilisez plutôt l’URL du serveur, ou renommez le serveur. +Pour ouvrir un serveur enregistré directement depuis la ligne de commande, lancez l’application de bureau avec `--connect-server ` (ou `--connect-server=`), en indiquant le nom enregistré du serveur ou son URL `https://`. CodeNomad n’ouvre que la fenêtre distante, avec les vérifications TLS du profil et la connexion propre à la fenêtre distante native ; si CodeNomad est déjà lancé, sa fenêtre actuelle l’ouvre au lieu d’une nouvelle fenêtre. Une URL qui ne correspond à aucun serveur enregistré est enregistrée sous son nom d’hôte. Les valeurs de lancement ne portent jamais d’identifiants : une URL avec un nom d’utilisateur, un mot de passe ou un code d’appairage est refusée. Si le nom est inconnu, l’URL invalide ou la connexion échoue, CodeNomad démarre normalement et affiche l’erreur. Quand la connexion demande une confirmation, comme l’installation du certificat local pour un serveur auto-signé, CodeNomad démarre aussi normalement et la demande là. Sous Windows, la version Tauri refuse de démarrer quand un argument de lancement contient `|` ; utilisez plutôt l’URL du serveur, ou renommez le serveur. Une fenêtre distante laisse toujours un moyen de revenir sur cet ordinateur. Fermer la dernière fenêtre locale alors que des fenêtres distantes restent ouvertes conserve ses onglets : **Fenêtre → Nouvelle fenêtre** dans une fenêtre distante, ou un nouveau lancement de CodeNomad, la rouvre. Si un serveur ne peut pas être chargé, sa fenêtre l’indique et propose **Réessayer**, **Ouvrir une fenêtre locale** et **Fermer la fenêtre** ; dans la version Tauri, utilisez le bouton d’actualisation de la page et **Fenêtre → Nouvelle fenêtre**. -Pour le Contrôle à distance, collez plutôt un lien d’appairage récent dans **Adresse ou lien du serveur**. Le favori ne conserve que l’origine du tunnel, jamais le code d’appairage à usage unique ; voir [Contrôle à distance](remote-control.md) pour le réappairage après perte du cookie de l’appareil. +Coller un lien du Contrôle à distance enregistre seulement l’origine du tunnel et signale que l’appairage côté serveur est indisponible ; le code est supprimé. Ouvrez le lien dans le navigateur voulu pour l’appairer. Voir [Contrôle à distance](remote-control.md). ## Ouvrir un projet distant dans un onglet {#remote-project-tabs} Dans l'application de bureau (Electron, ou Tauri sous Windows), un serveur enregistré peut aussi ouvrir l'un de ses projets dans un onglet de cette fenêtre, à côté de vos projets locaux : 1. Sur l’accueil, un onglet vide ou le lanceur **Ouvrir un onglet**, ouvrez **Parcourir** et choisissez un serveur enregistré. Pour en ajouter un, utilisez **Adresse ou lien du serveur**, puis cliquez sur sa nouvelle ligne. -2. Choisissez le dossier dans l'onglet. L'onglet affiche alors l'icône serveur et le nom du projet, et le projet rejoint **Récents** : le choisir à cet endroit rouvre directement ce serveur et ce dossier. +2. La liste affiche sur place les projets récents et les dossiers de ce serveur. Connectez-vous avec le formulaire intégré si nécessaire. Choisissez un projet récent, ou parcourez les dossiers puis choisissez **Sélectionner le dossier actuel**. **Retour à Parcourir** revient à la liste des serveurs. +3. Le choix du dossier ouvre son onglet distant et remplace l’onglet vide d’origine. Le lanceur `+` reste ouvert jusqu’à ce choix. Le projet rejoint **Récents** pour être rouvert directement. -L'onglet n'affiche que ce projet ; ses conversations, fichiers, Git, paramètres et Missions s'exécutent sur le serveur distant. Il utilise le stockage de la fenêtre distante du serveur : une connexion ou un appareil appairé existant est donc réutilisé, et les onglets distants reviennent quand CodeNomad restaure vos onglets. Un serveur sans ce mode affiche son interface complète dans l'onglet. Les serveurs qui ignorent la vérification TLS, ainsi que la version Tauri sous macOS et Linux, continuent d'ouvrir une fenêtre distante. La page d'un onglet peut afficher des notifications, sans autre accès à cet ordinateur, et reste sur son serveur. Les clients web et les appareils Remote Control n'ont pas d'onglets distants. **Supprimer le serveur enregistré**, dans **Paramètres → Serveurs**, ferme aussi ses onglets. Avant le choix d’un projet, l’onglet affiche le nom du serveur. Connectez-vous sur la page du serveur, dans l’onglet ; CodeNomad réutilise cette connexion aux lancements suivants. +Les conversations, fichiers, Git, paramètres et Missions de l’onglet s’exécutent sur le serveur distant. Sa vue intégrée partage le stockage de la fenêtre distante de ce serveur et peut demander une connexion distincte de Parcourir. Les onglets distants participent à la restauration au démarrage. Les serveurs sans mode intégré affichent leur interface complète ; les profils ignorant TLS et Tauri sous macOS/Linux ouvrent une fenêtre distincte. La page intégrée reste sur son serveur et dispose seulement des notifications sur l’hôte. Les clients web et appareils du Contrôle à distance n’ont pas d’onglets distants. + +Le parcours par le backend utilise l’accès direct CodeNomad avec des protections d’adresse : les IP littérales CGNAT/Tailscale et les plages spéciales sont refusées. Vérifiez votre destination sans supposer que toute adresse VPN fonctionne. La vérification des certificats suit le profil enregistré et sa confirmation TLS explicite. diff --git a/docs/help/fr/remote-control.md b/docs/help/fr/remote-control.md index 8ceb60761a..85f1a462a6 100644 --- a/docs/help/fr/remote-control.md +++ b/docs/help/fr/remote-control.md @@ -11,7 +11,7 @@ Le Contrôle à distance permet à un navigateur ou client de bureau appairé d Le lien est valable **cinq minutes** et réussit **une seule fois**. Traitez-le comme un identifiant : quiconque le consomme peut devenir un appareil appairé. Le code se trouve dans le fragment d’URL, pas dans la chaîne de requête. **Créer un nouveau lien d’appairage** invalide immédiatement le lien inutilisé précédent. L’arrêt, la fermeture du backend et une panne du tunnel annulent les liens d’appairage en attente. -Pour appairer un autre CodeNomad de bureau, ouvrez **Parcourir** sur l’accueil ou un onglet vide et collez le lien dans **Adresse ou lien du serveur**. Cela ajoute seulement le serveur ; cliquez sur sa ligne enregistrée pour l’ouvrir et l’appairer. Le lien à usage unique attend en mémoire dans cette fenêtre jusqu’à son ouverture ou au rechargement ; utilisez-le pendant ses cinq minutes de validité. Seule l’origine du tunnel est enregistrée comme favori. La vérification TLS reste activée pour les liens d’appairage. +Ouvrez les liens d’appairage dans le navigateur voulu. En coller un dans **Adresse ou lien du serveur** sur le bureau enregistre seulement l’origine du tunnel et signale que l’appairage côté serveur est indisponible. Le code est supprimé. Le parcours des dossiers par le backend utilise sa propre session d’accès direct ; la vue intégrée conserve indépendamment sa connexion ou son cookie d’appareil appairé. ## Gérer les appareils appairés {#paired-devices} @@ -28,7 +28,7 @@ Changer le mot de passe d’accès direct ne révoque **pas** les appareils. **A ### Réappairer sans perdre sa place {#re-pair} 1. Si le client affiche **Appairer à nouveau cet appareil**, laissez cette page ouverte. -2. Sur l’hôte, choisissez **Créer un nouveau lien d’appairage** et ouvrez-le dans le **même navigateur/profil client**. Pour un serveur de bureau enregistré, reconnectez-vous avec le lien récent afin de réutiliser le stockage existant de sa fenêtre distante. +2. Sur l’hôte, choisissez **Créer un nouveau lien d’appairage** et ouvrez-le dans le **même navigateur/profil client**. 3. Revenez à la page en attente et choisissez **Vérifier la connexion** ; la vérification se refait aussi quand la page reprend le focus. La récupération préserve la page ouverte et les brouillons ; elle ne rejoue pas une action échouée. Vérifiez si un envoi, une réponse ou une suppression a pris effet avant de réessayer. Un mot de passe d’accès direct ne peut pas récupérer un appairage de Contrôle à distance. diff --git a/docs/help/he/projects.md b/docs/help/he/projects.md index e228febd90..9d38dd15ad 100644 --- a/docs/help/he/projects.md +++ b/docs/help/he/projects.md @@ -4,12 +4,14 @@ ## פתיחת פרויקט {#open-project} -1. **מופע חדש** (`+`) פותח **לשונית חדשה** ריקה עם מיקוד בחיפוש. היא משתמשת ברקע של דף הבית, בלוגו ובשם CodeNomad במרכז ובכפתורים הגדולים **שכפל מאגר Git**, **לשונית זמנית חדשה** ו־**SideCar חדש**. הבורר **אחרונים | עיון** מציג מספר פריטים; החיפוש נמצא מתחתיו בתוך **אחרונים**. בחירת פרויקט, שרת שמור או SideCar ממלאת את הלשונית במקומה. לשונית ריקה קיימת עד לטעינה מחדש ונסגרת בלי להשאיר פרויקט. הלוגו של CodeNomad בשורת הכותרת או הלשוניות פותח את דף הבית עם הגדרות, שפה וכפתור הלב **חסות** ([תמיכה ב־CodeNomad](sponsor.md)). +1. **מופע חדש** (`+`) פותח **לשונית חדשה** ריקה עם מיקוד בחיפוש. היא משתמשת ברקע של דף הבית, בלוגו ובשם CodeNomad במרכז ובכפתורים הגדולים **שכפל מאגר Git**, **לשונית זמנית חדשה** ו־**SideCar חדש**. הבורר **אחרונים | עיון** מציג מספר פריטים; החיפוש נמצא מתחתיו בתוך **אחרונים**. בחירת פרויקט מקומי או מרוחק או SideCar ממלאת את הלשונית במקומה. לשונית ריקה קיימת עד לטעינה מחדש ונסגרת בלי להשאיר פרויקט. הלוגו של CodeNomad בשורת הכותרת או הלשוניות פותח את דף הבית עם הגדרות, שפה וכפתור הלב **חסות** ([תמיכה ב־CodeNomad](sponsor.md)). 2. ב־**אחרונים**, בחרו פרויקט; או פתחו את **עיון**, בחרו **המחשב הזה**, ואז בחרו את תיקיית ה־backend ופתחו אותה. **עיון** מציג גם שרתי CodeNomad שמורים ([לשוניות של פרויקטים מרוחקים](remote-access.md#remote-project-tabs)) ו־SideCars ([SideCars](browser-sidecars.md#register-sidecar)). 3. לעותק מאגר, בחרו **שכפל מאגר Git**, הזינו **כתובת המאגר** ו־**תיקיית יעד**, ואז **שכפל**. **תיקיית יעד** ממולא מראש בשם המאגר, בתיקייה שמכילה את השכפול האחרון שלך, או לצד הפרויקט האחרון שלך. **עיון** בוחר את התיקייה שתכיל את השכפול; אפשר גם לערוך את הנתיב, כולל שם התיקייה של השכפול. עיון בשרת מרוחק הוא עיון במערכת הקבצים שלו, לא בטלפון או במחשב הנייד שלכם. פתיחת פרויקט אינה יוצרת דמון OpenCode נפרד לכל לשונית. שיחות הן סשנים מקוריים של OpenCode; משך חייהן אינו משך חיי הלשונית. +בחירת שרת ב־**עיון** מחליפה את הרשימה בפרויקטים האחרונים ובתיקיות שלו. התחברו בטופס המשולב אם תתבקשו, ואז בחרו פרויקט או נווטו לתיקייה ובחרו **בחר נוכחית**. חזרה לעיון מציגה את השרתים. רק בחירת פרויקט ממלאת את הלשונית הריקה וסוגרת את משגר `+`. הלשונית המרוחקת עשויה לדרוש התחברות משלה, בנפרד מהעיון. + שכפול כותב מאגר ליעד. **מחק תחילה את תיקיית היעד אם היא כבר קיימת.** היא אפשרות הרסנית: הפעילו אותה רק כשמותר למחוק את כל מה שכבר נמצא שם. השתמשו ביעד חדש אם אינכם בטוחים. שכפול שנכשל אינו סיבה למחוק פרויקט קיים; בדקו את היעד והשגיאה שדווחו לפני ניסיון חוזר. רשומות אחרונות הן קיצורי דרך. **שנה שם סביבת עבודה** משנה את שמה המוצג; **הסר מהרשימה האחרונה** מסיר את קיצור הדרך, לא את קבציו או שיחותיו. לחיצה על פרויקט אחרון שכבר פתוח פותחת לשונית חדשה; הכפתור **פתוח** שלו (**עבור לפרויקט הפתוח**) בוחר במקום זאת את הלשונית הקיימת. diff --git a/docs/help/he/remote-access.md b/docs/help/he/remote-access.md index 5e7e285aff..2555f1e4ea 100644 --- a/docs/help/he/remote-access.md +++ b/docs/help/he/remote-access.md @@ -83,23 +83,26 @@ codenomad --host 127.0.0.1 --https=false --http=true ## שמירת שרת מרוחק {#saved-servers} -1. בדף הבית, בלשונית ריקה או במשגר **פתיחת לשונית**, פתחו את **עיון** והזינו כתובת או קישור צימוד ב־**כתובת או קישור של השרת**. הדבקה מוסיפה מיד; Enter מוסיף טקסט שהוקלד. ההוספה רק שומרת את השרת בשם המארח וממקדת את השורה שלו; המשגר נשאר פתוח. לחצו על השורה כדי לפתוח. **הגדרות → שרתים** מציע את אותו השדה. -2. השתמשו במקור HTTPS מהימן. אם התעודה נכשלת בבדיקה, **דילוג על אימות TLS** מופיע מתחת לשדה: סמנו רק לשרת מהימן והקישו Enter שוב כדי לשמור. בחירת השרת השמור הזה פותחת חלון משלו. -3. התחברו לשרת הזה. שנו את שמו או את כתובתו באמצעות **עריכת שרת** ב־**הגדרות → שרתים**. +1. בדף הבית, בלשונית ריקה או במשגר **פתיחת לשונית**, פתחו את **עיון** והזינו כתובת או קישור צימוד ב־**כתובת או קישור של השרת**. הדבקה מוסיפה מיד; Enter מוסיף טקסט שהוקלד. ההוספה רק שומרת את השרת בשם המארח וממקדת את השורה שלו; המשגר נשאר פתוח. לחצו על השורה כדי לעיין בפרויקטים באותה רשימה. **הגדרות → שרתים** מציע את אותו השדה. +2. השתמשו במקור HTTPS מהימן. אם התעודה נכשלת בבדיקה, **דילוג על אימות TLS** מופיע מתחת לשדה: סמנו רק לשרת מהימן והקישו Enter שוב כדי לשמור. בחירת תיקייה או פרויקט בפרופיל הזה פותחת חלון משלו. +3. בחרו בשורת השרת ב־**עיון** כדי לעיין בפרויקטים באותה רשימה. אם תתבקשו, הזינו שם משתמש וסיסמה בטופס המשולב. שנו את שמו או כתובתו באמצעות **עריכת שרת** ב־**הגדרות → שרתים**. -שרתים שמורים מופיעים תחת **עיון**: בחרו שרת כדי לפתוח אותו שוב. ב־**הגדרות → שרתים** פותחים אותם, עורכים אותם (**עריכת שרת**: שם, כתובת, בדיקת תעודה) ומסירים אותם (**הסר שרת שמור**). סימניות שייכות לתצורת CodeNomad זו, לא לפרויקטי השרת המרוחק. שמירת כתובת אינה מפעילה שרת או מעניקה גישה. **הסר שרת שמור** מסיר את הסימנייה, לא שיחות מרוחקות, את שרת הקצה או את פרטי ההתחברות שלו. +**הגדרות → שרתים** מנהל פרופילים (**עריכת שרת**, **הסר שרת שמור**). הסרה שוכחת תחילה את פרטי ההתחברות וסשן העיון שבשרת הקצה, ואז מסירה את הסימנייה וסוגרת את לשוניותיה. פרויקטים ושיחות מרוחקים נשארים בשרת שלהם. שרת הקצה המקומי שומר את סודות העיון ב־`remote-server-credentials.json` לצד התצורה שלו; הגנו על קובץ זה כמו על סיסמה. תצוגות מוטמעות שומרות אימות נפרד. -כדי לפתוח שרת שמור ישירות משורת הפקודה, הפעילו את אפליקציית שולחן העבודה עם `--connect-server ` (או `--connect-server=`), עם השם השמור של השרת או עם כתובת ה־`https://` שלו. CodeNomad פותח רק את החלון המרוחק, עם אותן בדיקות ואותה התחברות כמו **עיון**; כש־CodeNomad כבר פועל, החלון הנוכחי שלו פותח אותו במקום חלון חדש. כתובת שאינה תואמת אף שרת שמור נשמרת בשם המארח שלה. ערכי הפעלה לעולם אינם נושאים פרטי התחברות: כתובת עם שם משתמש, סיסמה או קוד צימוד נדחית. אם השם אינו מוכר, הכתובת אינה תקינה או שהחיבור נכשל, CodeNomad מופעל כרגיל ומציג את השגיאה. כשהחיבור דורש אישור, כמו התקנת התעודה המקומית לשרת בחתימה עצמית, CodeNomad גם מופעל כרגיל ומבקש אותו שם. ב־Windows, גרסת Tauri מסרבת לעלות כשארגומנט הפעלה מכיל `|`; השתמשו במקום זאת בכתובת השרת, או שנו את שם השרת. +כדי לפתוח שרת שמור ישירות משורת הפקודה, הפעילו את אפליקציית שולחן העבודה עם `--connect-server ` (או `--connect-server=`), עם השם השמור של השרת או עם כתובת ה־`https://` שלו. CodeNomad פותח רק את החלון המרוחק, עם בדיקות ה־TLS של הפרופיל וההתחברות העצמאית של החלון המרוחק המקורי; כש־CodeNomad כבר פועל, החלון הנוכחי שלו פותח אותו במקום חלון חדש. כתובת שאינה תואמת אף שרת שמור נשמרת בשם המארח שלה. ערכי הפעלה לעולם אינם נושאים פרטי התחברות: כתובת עם שם משתמש, סיסמה או קוד צימוד נדחית. אם השם אינו מוכר, הכתובת אינה תקינה או שהחיבור נכשל, CodeNomad מופעל כרגיל ומציג את השגיאה. כשהחיבור דורש אישור, כמו התקנת התעודה המקומית לשרת בחתימה עצמית, CodeNomad גם מופעל כרגיל ומבקש אותו שם. ב־Windows, גרסת Tauri מסרבת לעלות כשארגומנט הפעלה מכיל `|`; השתמשו במקום זאת בכתובת השרת, או שנו את שם השרת. חלון מרוחק תמיד משאיר דרך לחזור למחשב הזה. סגירת החלון המקומי האחרון בזמן שחלונות מרוחקים נשארים פתוחים שומרת את הלשוניות שלו: **חלון → חלון חדש** בחלון מרוחק, או הפעלה מחדש של CodeNomad, פותחים אותו שוב. אם לא ניתן לטעון שרת, החלון שלו מציין זאת ומציע **נסו שוב**, **פתיחת חלון מקומי** ו**סגירת החלון**; בגרסת Tauri, השתמשו בכפתור הרענון של הדף וב־**חלון → חלון חדש**. -לשליטה מרחוק, הדביקו במקום זאת קישור צימוד חדש ב־**כתובת או קישור של השרת**. הסימנייה שומרת רק את מקור המנהרה, לעולם לא את קוד הצימוד החד־פעמי; ראו [שליטה מרחוק](remote-control.md) לצימוד מחדש לאחר אובדן עוגיית המכשיר. +הדבקת קישור של שליטה מרחוק שומרת רק את מקור המנהרה ומדווחת שצימוד בצד השרת אינו זמין; הקוד נמחק. פתחו את הקישור בדפדפן הרצוי לצימוד שם. ראו [שליטה מרחוק](remote-control.md). ## פתיחת פרויקט מרוחק בלשונית {#remote-project-tabs} ביישום שולחן העבודה (Electron, או Tauri ב-Windows), שרת שמור יכול לפתוח גם אחד מהפרויקטים שלו בלשונית של החלון הזה, לצד הפרויקטים המקומיים שלך: 1. בדף הבית, בלשונית ריקה או במשגר **פתיחת לשונית**, פתחו את **עיון** ובחרו שרת שמור. להוספה תחילה השתמשו ב־**כתובת או קישור של השרת**, ואז לחצו על השורה החדשה. -2. בחרו את התיקייה בלשונית. הלשונית מציגה אז את סמל השרת ואת שם הפרויקט, והפרויקט מצטרף ל-**אחרונים**: בחירה בו שם פותחת מחדש ישירות את השרת והתיקייה האלה. +2. הרשימה מתחלפת באותו מקום לפרויקטים אחרונים ולתיקיות של השרת. התחברו בטופס המשולב לפי הצורך. בחרו פרויקט אחרון, או נווטו לתיקייה ובחרו **בחר נוכחית**. **חזרה לעיון** מחזירה לרשימת השרתים. +3. בחירת תיקייה פותחת לשונית פרויקט מרוחק ומחליפה את הלשונית הריקה המקורית. משגר `+` נשאר פתוח עד הבחירה. הפרויקט נוסף ל־**אחרונים** לפתיחה ישירה. -הלשונית מציגה רק את הפרויקט הזה; השיחות, הקבצים, Git, ההגדרות וה-Missions שלו פועלים בשרת המרוחק. היא משתמשת באחסון של החלון המרוחק של השרת, כך שהתחברות קיימת או מכשיר מצומד נעשים בהם שימוש חוזר, והלשוניות המרוחקות חוזרות כש-CodeNomad משחזר את הלשוניות שלך. שרת ללא מצב זה מציג בלשונית את הממשק המלא שלו. שרתים שמדלגים על אימות TLS, וגרסת Tauri ב-macOS וב-Linux, ממשיכים לפתוח חלון מרוחק. הדף שבלשונית יכול להציג התראות, אך אין לו גישה אחרת למחשב הזה והוא נשאר בשרת שלו. ללקוחות אינטרנט ולמכשירי Remote Control אין לשוניות מרוחקות. **הסר שרת שמור**, ב־**הגדרות → שרתים**, סוגר גם את הלשוניות שלו. לפני בחירת פרויקט, הלשונית מציגה את שם השרת. התחברו בדף של השרת בתוך הלשונית; CodeNomad משתמש שוב בהתחברות זו בהפעלות הבאות. +השיחות, הקבצים, Git, ההגדרות ו־Missions בלשונית פועלים בשרת המרוחק. התצוגה המוטמעת חולקת את אחסון החלון המרוחק שלו ועשויה לדרוש התחברות נפרדת מעיון. לשוניות מרוחקות משתתפות בשחזור בהפעלה. שרתים ללא מצב מוטמע מציגים את הממשק המלא; פרופילים שמדלגים על TLS ו־Tauri ב־macOS/Linux פותחים חלון נפרד. הדף המוטמע נשאר בשרת שלו ויכול רק לשלוח התראות למארח. ללקוחות דפדפן ולמכשירי שליטה מרחוק אין לשוניות מרוחקות. + +העיון דרך שרת הקצה משתמש בגישה ישירה ל־CodeNomad עם הגנות כתובת: כתובות IP מילוליות של CGNAT/Tailscale וטווחים מיוחדים נדחים. בדקו את היעד בפועל במקום להניח שכל כתובת VPN נתמכת. בדיקת התעודה פועלת לפי הפרופיל השמור ואישור ה־TLS המפורש שלו. diff --git a/docs/help/he/remote-control.md b/docs/help/he/remote-control.md index 1ad8f02a15..dd6ebfc541 100644 --- a/docs/help/he/remote-control.md +++ b/docs/help/he/remote-control.md @@ -11,7 +11,7 @@ הקישור תקף ל־**חמש דקות** ומצליח **פעם אחת**. התייחסו אליו כאישור גישה: כל מי שמנצל אותו יכול להפוך למכשיר מצומד. הקוד נמצא במקטע הכתובת, לא במחרוזת השאילתה. **צור קישור צימוד חדש** מבטל מיד את הקישור הקודם שלא נוצל. עצירה, כיבוי שרת הקצה וכשל במנהרה מבטלים קישורי צימוד שטרם נוצלו. -לצימוד CodeNomad נוסף לשולחן העבודה, פתחו את **עיון** בדף הבית או בלשונית ריקה והדביקו את הקישור ב־**כתובת או קישור של השרת**. פעולה זו רק מוסיפה את השרת; לחצו על השורה השמורה לפתיחה ולצימוד. הקישור החד־פעמי ממתין בזיכרון החלון עד לפתיחה או לטעינה מחדש; השתמשו בו בחמש דקות התוקף שלו. רק מקור המנהרה נשמר כסימנייה. אימות TLS נשאר פעיל לקישורי צימוד. +פתחו קישורי צימוד בדפדפן הרצוי. הדבקה ב־**כתובת או קישור של השרת** בשולחן העבודה שומרת רק את מקור המנהרה ומציגה שצימוד בצד השרת אינו זמין. הקוד נמחק. עיון בתיקיות דרך שרת הקצה משתמש בסשן גישה ישירה משלו; התצוגה המוטמעת שומרת בנפרד את ההתחברות או עוגיית המכשיר שלה. ## ניהול מכשירים מצומדים {#paired-devices} @@ -28,7 +28,7 @@ ### צימוד מחדש בלי לאבד את המקום {#re-pair} 1. אם הלקוח מציג **יש לצמד מחדש את המכשיר הזה**, השאירו את הדף פתוח. -2. במארח, בחרו **צור קישור צימוד חדש** ופתחו אותו ב־**אותו דפדפן/פרופיל לקוח**. לשרת שמור בשולחן העבודה, התחברו מחדש בקישור הצימוד החדש כדי להשתמש שוב באחסון החלון המרוחק הקיים שלו. +2. במארח, בחרו **צור קישור צימוד חדש** ופתחו אותו ב־**אותו דפדפן/פרופיל לקוח**. 3. חזרו לדף הממתין ובחרו **בדיקת חיבור**; הבדיקה מתבצעת שוב גם כשהדף חוזר למיקוד. ההתאוששות משמרת את הדף הפתוח והטיוטות; היא אינה חוזרת על פעולה שנכשלה. בדקו אם שליחה, תשובה או מחיקה נכנסו לתוקף לפני ניסיון חוזר. סיסמת גישה ישירה אינה יכולה לשחזר צימוד לשליטה מרחוק. diff --git a/docs/help/ja/projects.md b/docs/help/ja/projects.md index d600523450..51072120a0 100644 --- a/docs/help/ja/projects.md +++ b/docs/help/ja/projects.md @@ -4,12 +4,14 @@ ## プロジェクトを開く {#open-project} -1. **新しいインスタンス**(`+`)は検索欄にフォーカスした空の **新しいタブ** を開きます。ホームと同じ背景、中央の CodeNomad ロゴと名前、大きな **Git リポジトリをクローン**・**新しい一時タブ**・**新しい SideCar** ボタンを使います。**最近 | 参照** セレクターに件数が表示され、検索はその下の **最近** 内にあります。プロジェクト、保存済みサーバー、SideCar を選ぶと、その位置でタブが切り替わります。空のタブは再読み込みまで有効で、プロジェクトを残さず閉じます。タイトルバーまたはタブバーの CodeNomad ロゴは、設定・言語・ハートの **スポンサー** ボタンもあるホームを開きます([CodeNomad を支援](sponsor.md))。 +1. **新しいインスタンス**(`+`)は検索欄にフォーカスした空の **新しいタブ** を開きます。ホームと同じ背景、中央の CodeNomad ロゴと名前、大きな **Git リポジトリをクローン**・**新しい一時タブ**・**新しい SideCar** ボタンを使います。**最近 | 参照** セレクターに件数が表示され、検索はその下の **最近** 内にあります。ローカルまたはリモートのプロジェクトや SideCar を選ぶと、その位置でタブが切り替わります。空のタブは再読み込みまで有効で、プロジェクトを残さず閉じます。タイトルバーまたはタブバーの CodeNomad ロゴは、設定・言語・ハートの **スポンサー** ボタンもあるホームを開きます([CodeNomad を支援](sponsor.md))。 2. **最近** でプロジェクトを選ぶか、**参照** を開いて **このコンピューター** を選び、バックエンドのフォルダーを選択して開きます。**参照** には保存した CodeNomad サーバー([リモートプロジェクトのタブ](remote-access.md#remote-project-tabs))と SideCar([SideCar](browser-sidecars.md#register-sidecar))も表示されます。 3. リポジトリをコピーするには、**Git リポジトリをクローン** を選び、**リポジトリ URL** と **保存先フォルダ** を入力して **クローン** を選びます。**保存先フォルダ** には、前回のクローンがあるフォルダー(なければ最近のプロジェクトと同じ場所)にリポジトリ名のフォルダーが入力されます。**参照** ではクローンを置くフォルダーを選びます。クローンのフォルダー名を含め、パスは直接編集することもできます。 リモートサーバーの参照とは、そのサーバーのファイルシステムの参照であり、スマートフォンやノートパソコンの参照ではありません。プロジェクトを開いても、タブごとに別の OpenCode デーモンは作成されません。会話は OpenCode ネイティブのセッションであり、その寿命はタブの寿命と同じではありません。 +**参照** でサーバーを選ぶと、一覧がその最近のプロジェクトとフォルダーに切り替わります。必要ならインラインフォームでサインインし、最近のプロジェクトを選ぶか、フォルダーを移動して **現在のフォルダを選択** を押します。参照に戻るとサーバー一覧が表示されます。プロジェクトの選択後に空タブが埋まり、`+` ランチャーが閉じます。リモートタブは参照とは別のサインインを求める場合があります。 + クローンは保存先にリポジトリを書き込みます。**保存先フォルダが既に存在する場合は先に削除します。** は破壊的な操作です。そこに既にあるすべての内容を削除してよい場合にのみ有効にしてください。不確かな場合は、新しい保存先を使用します。クローンの失敗を理由に既存のプロジェクトを削除しないでください。再試行する前に、表示された保存先とエラーを確認します。 最近使った項目はショートカットです。**ワークスペース名を変更** は表示名を変更し、**履歴から削除** はショートカットを削除しますが、ファイルや会話は削除しません。既に開いている最近のプロジェクトをクリックすると新しいタブで開きます。その **開いています** ボタン(**開いているプロジェクトに切り替え**)は、代わりに既存のタブを選択します。 diff --git a/docs/help/ja/remote-access.md b/docs/help/ja/remote-access.md index 254ef10a78..f1c64a9bf4 100644 --- a/docs/help/ja/remote-access.md +++ b/docs/help/ja/remote-access.md @@ -83,23 +83,26 @@ HTTPS が有効で鍵/証明書のペアを指定していない場合、CodeN ## リモートサーバーを保存する {#saved-servers} -1. ホーム、空のタブ、**タブを開く** ランチャーで **参照** を開き、アドレスまたはペアリングリンクを **サーバーのアドレスまたはリンク** に入力します。貼り付けは即座に追加し、手入力は Enter で追加します。サーバーはホスト名で保存され、その行にフォーカスが移ります。ランチャーは開いたままです。行をクリックすると開きます。**設定 → サーバー** にも同じ入力欄があります。 -2. 信頼できる HTTPS オリジンを使ってください。証明書の検証に失敗した場合、入力欄の下に **TLS 検証をスキップ** が表示されます。信頼できるサーバーだけでオンにして Enter で保存します。保存したサーバーを選ぶと専用ウィンドウで開きます。 -3. そのサーバーでサインインします。名前やアドレスは **設定 → サーバー** の **サーバーを編集** で変更できます。 +1. ホーム、空のタブ、**タブを開く** ランチャーで **参照** を開き、アドレスまたはペアリングリンクを **サーバーのアドレスまたはリンク** に入力します。貼り付けは即座に追加し、手入力は Enter で追加します。サーバーはホスト名で保存され、その行にフォーカスが移ります。ランチャーは開いたままです。行をクリックすると、その場でプロジェクトを参照できます。**設定 → サーバー** にも同じ入力欄があります。 +2. 信頼できる HTTPS オリジンを使ってください。証明書の検証に失敗した場合、入力欄の下に **TLS 検証をスキップ** が表示されます。信頼できるサーバーだけでオンにして Enter で保存します。このプロファイルのフォルダーやプロジェクトを選ぶと専用ウィンドウで開きます。 +3. **参照** の保存済みサーバー行を選ぶと、その場でプロジェクトを参照できます。求められたらインラインフォームにユーザー名とパスワードを入力します。名前やアドレスは **設定 → サーバー** の **サーバーを編集** で変更できます。 -保存したサーバーは **参照** に表示され、選ぶと再び開きます。**設定 → サーバー** では、サーバーを開く、編集する(**サーバーを編集**:名前、アドレス、証明書の検証)、削除する(**保存したサーバーを削除**)ことができます。ブックマークは、この CodeNomad 設定に属し、リモートサーバーのプロジェクトに属するわけではありません。URL の保存はサーバーの起動やアクセス許可を行いません。**保存したサーバーを削除** はブックマークを削除しますが、リモートの会話、バックエンド、認証情報は削除しません。 +**設定 → サーバー** でプロファイルを管理します(**サーバーを編集**、**保存したサーバーを削除**)。削除時は、まずバックエンドの参照用認証情報とセッションを消去し、ブックマークを削除して関連タブを閉じます。リモートのプロジェクトと会話はサーバーに残ります。ローカルバックエンドは参照用の秘密情報を設定の隣の `remote-server-credentials.json` に保存します。このファイルはパスワードと同様に保護してください。埋め込みビューの認証は独立しています。 -保存したサーバーをコマンドラインから直接開くには、サーバーの保存名か `https://` URL を指定して、デスクトップアプリを `--connect-server `(または `--connect-server=`)付きで起動します。CodeNomad はリモートウィンドウだけを開き、**参照** と同じ確認とログインを行います。CodeNomad がすでに起動している場合は、新しいウィンドウではなく現在のウィンドウから開きます。どの保存済みサーバーにも一致しない URL は、ホスト名で保存されます。起動時の値に認証情報は含められません。ユーザー名、パスワード、ペアリングコードを含む URL は拒否されます。名前が不明な場合、URL が無効な場合、または接続に失敗した場合、CodeNomad は通常どおり起動してエラーを表示します。 自己署名サーバー用のローカル証明書のインストールなど、接続に確認が必要な場合も、CodeNomad は通常どおり起動してそこで確認します。 Windows では、起動引数に `|` が含まれると Tauri 版は起動しません。代わりにサーバーの URL を使うか、サーバー名を変更してください。 +保存したサーバーをコマンドラインから直接開くには、サーバーの保存名か `https://` URL を指定して、デスクトップアプリを `--connect-server `(または `--connect-server=`)付きで起動します。CodeNomad はリモートウィンドウだけを開き、プロファイルの TLS 検証とネイティブリモートウィンドウ独自のサインインを使います。CodeNomad がすでに起動している場合は、新しいウィンドウではなく現在のウィンドウから開きます。どの保存済みサーバーにも一致しない URL は、ホスト名で保存されます。起動時の値に認証情報は含められません。ユーザー名、パスワード、ペアリングコードを含む URL は拒否されます。名前が不明な場合、URL が無効な場合、または接続に失敗した場合、CodeNomad は通常どおり起動してエラーを表示します。 自己署名サーバー用のローカル証明書のインストールなど、接続に確認が必要な場合も、CodeNomad は通常どおり起動してそこで確認します。 Windows では、起動引数に `|` が含まれると Tauri 版は起動しません。代わりにサーバーの URL を使うか、サーバー名を変更してください。 リモートウィンドウからは、いつでもこのコンピューターに戻れます。リモートウィンドウを開いたまま最後のローカルウィンドウを閉じても、そのタブは保持されます。リモートウィンドウの **ウィンドウ → 新規ウィンドウ**、または CodeNomad の再起動で再び開きます。サーバーを読み込めない場合は、そのウィンドウにその旨が表示され、**再試行**、**ローカルウィンドウを開く**、**ウィンドウを閉じる** を選べます。Tauri 版では、ページの再読み込みボタンと **ウィンドウ → 新規ウィンドウ** を使用します。 -リモートコントロールでは、代わりに新しいペアリングリンクを **サーバーのアドレスまたはリンク** に貼り付けます。ブックマークはトンネルのオリジンだけを保持し、使い捨てのペアリングコードは保持しません。端末 Cookie 消失後の再ペアリングは、[リモートコントロール](remote-control.md)を参照してください。 +リモートコントロールのリンクを貼り付けるとトンネルのオリジンのみが保存され、サーバー側のペアリングが利用できない旨が表示されます。コードは破棄されます。ペアリングするブラウザーでリンクを開いてください。[リモートコントロール](remote-control.md)を参照してください。 ## リモートプロジェクトをタブで開く {#remote-project-tabs} デスクトップアプリ(Electron、または Windows の Tauri)では、保存済みサーバーのプロジェクトを、ローカルプロジェクトと並べてこのウィンドウのタブで開くこともできます。 1. ホーム、空のタブ、**タブを開く** ランチャーで **参照** を開き、保存済みサーバーを選びます。先に追加する場合は **サーバーのアドレスまたはリンク** を使い、新しい行をクリックします。 -2. タブ内でフォルダーを選びます。タブにはサーバーアイコンとプロジェクト名が表示され、プロジェクトは **最近** に加わります。そこで選ぶと、そのサーバーとフォルダーが直接開き直されます。 +2. 一覧がその場でサーバーの最近のプロジェクトとフォルダーに切り替わります。必要ならインラインフォームでサインインします。最近のプロジェクトを選ぶか、フォルダーを移動して **現在のフォルダを選択** を押します。**参照に戻る** でサーバー一覧に戻れます。 +3. フォルダーを選ぶとリモートプロジェクトのタブが開き、元の空タブを置き換えます。`+` ランチャーは選択まで開いたままです。プロジェクトは直接開き直せるよう **最近** に追加されます。 -タブにはそのプロジェクトだけが表示され、会話、ファイル、Git、設定、Missions はリモートサーバーで動作します。タブはそのサーバーのリモートウィンドウと同じストレージを使うため、既存のサインインやペアリング済みデバイスがそのまま使われ、CodeNomad がタブを復元するとリモートタブも戻ります。このモードを持たないサーバーは、タブに完全なインターフェースを表示します。TLS 検証を省略するサーバーと、macOS・Linux の Tauri ビルドでは、引き続きリモートウィンドウが開きます。タブ内のページは通知を表示できますが、このコンピューターへのその他のアクセスはなく、自分のサーバーから離れません。Web クライアントと Remote Control デバイスにはリモートタブはありません。**設定 → サーバー** の **保存したサーバーを削除** は、そのタブも閉じます。プロジェクトを選ぶ前のタブにはサーバー名が表示されます。タブ内のサーバーのページでサインインしてください。CodeNomad は次回以降の起動でもそのサインインを再利用します。 +タブの会話、ファイル、Git、設定、Missions はリモートサーバーで動作します。埋め込みビューはそのサーバーのリモートウィンドウのストレージを共有し、参照とは別にサインインを求める場合があります。リモートタブは起動時に復元されます。埋め込みモードのないサーバーは完全な UI を表示し、TLS 検証を省略するプロファイルと macOS/Linux の Tauri は別ウィンドウを開きます。埋め込みページはサーバー内に留まり、ホストへは通知のみ送れます。Web クライアントとリモートコントロール端末にはリモートタブはありません。 + +バックエンド参照はアドレス保護付きの CodeNomad 直接アクセスを使い、CGNAT/Tailscale の IP リテラルと特殊用途の範囲を拒否します。すべての VPN アドレスが使えると考えず、実際の接続先を確認してください。証明書検証は保存したプロファイルと明示的な TLS 確認に従います。 diff --git a/docs/help/ja/remote-control.md b/docs/help/ja/remote-control.md index 14798f24fc..bf0d15076b 100644 --- a/docs/help/ja/remote-control.md +++ b/docs/help/ja/remote-control.md @@ -11,7 +11,7 @@ リンクの有効期間は **5 分**、成功するのは **1 回** です。利用した人はペアリング済み端末になれるため、認証情報として扱ってください。コードはクエリ文字列ではなく URL フラグメントに入ります。**新しいペアリングリンクを作成** は、直前の未使用リンクを即座に無効化します。停止、バックエンドの終了、トンネル障害は、未使用のペアリングリンクをキャンセルします。 -別のデスクトップ CodeNomad をペアリングするには、ホームまたは空のタブで **参照** を開き、リンクを **サーバーのアドレスまたはリンク** に貼り付けます。これでサーバーだけが追加されます。保存した行をクリックすると開いてペアリングされます。使い捨てリンクは開くか再読み込みするまでこのウィンドウのメモリー内で待機します。有効期間の5分以内に使ってください。ブックマークにはトンネルのオリジンのみを保存します。ペアリングリンクでは TLS 検証を有効のまま維持します。 +ペアリングリンクは使用するブラウザーで開いてください。デスクトップの **サーバーのアドレスまたはリンク** に貼り付けると、トンネルのオリジンのみが保存され、サーバー側のペアリングが利用できない旨が表示されます。コードは破棄されます。バックエンドのフォルダー参照は専用の直接アクセスセッションを使い、埋め込みビューは独立したサインインやデバイス Cookie を保持します。 ## ペアリング済み端末を管理する {#paired-devices} @@ -28,7 +28,7 @@ ### 現在の表示を失わず再ペアリングする {#re-pair} 1. クライアントに **このデバイスを再ペアリング** が表示されたら、そのページを開いたままにします。 -2. ホストで **新しいペアリングリンクを作成** を選び、**同じクライアントのブラウザー/プロファイル** で開きます。保存済みデスクトップサーバーでは、新しいペアリングリンクで接続し直して、既存のリモートウィンドウのストレージを再利用します。 +2. ホストで **新しいペアリングリンクを作成** を選び、**同じクライアントのブラウザー/プロファイル** で開きます。 3. 待機しているページに戻り、**接続を確認** を選びます。ページにフォーカスが戻ったときにも再確認されます。 復旧は開いているページと下書きを保持しますが、失敗した操作は再実行しません。再試行の前に、送信、回答、削除が実際に反映されたか確認してください。直接アクセスのパスワードでは、リモートコントロールのペアリングを復旧できません。 diff --git a/docs/help/ne/projects.md b/docs/help/ne/projects.md index 530ae7b8a0..6d99852759 100644 --- a/docs/help/ne/projects.md +++ b/docs/help/ne/projects.md @@ -4,12 +4,14 @@ ## परियोजना खोल्नुहोस् {#open-project} -1. **नयाँ उदाहरण** (`+`) ले खोजमा focus भएको खाली **नयाँ ट्याब** खोल्छ। यसमा गृह पृष्ठकै पृष्ठभूमि, बीचमा CodeNomad लोगो र नाम तथा ठूला **Git Repo क्लोन गर्नुहोस्**, **नयाँ अस्थायी ट्याब** र **नयाँ SideCar** बटन हुन्छन्। **हालका | ब्राउज गर्नुहोस्** चयनकर्ताले प्रविष्टि संख्या देखाउँछ; खोज त्यसको तल **हालका** भित्र हुन्छ। परियोजना, बचत गरिएको सर्भर वा SideCar छान्दा ट्याब उही स्थानमा भरिन्छ। खाली ट्याब पुनः लोड हुँदासम्म रहन्छ र बन्द गर्दा परियोजना बाँकी रहँदैन। शीर्षक वा ट्याब पट्टीको CodeNomad लोगोले सेटिङ, भाषा र मुटु भएको **प्रायोजन** बटनसहित गृह पृष्ठ खोल्छ ([CodeNomad लाई सहयोग](sponsor.md))। +1. **नयाँ उदाहरण** (`+`) ले खोजमा focus भएको खाली **नयाँ ट्याब** खोल्छ। यसमा गृह पृष्ठकै पृष्ठभूमि, बीचमा CodeNomad लोगो र नाम तथा ठूला **Git Repo क्लोन गर्नुहोस्**, **नयाँ अस्थायी ट्याब** र **नयाँ SideCar** बटन हुन्छन्। **हालका | ब्राउज गर्नुहोस्** चयनकर्ताले प्रविष्टि संख्या देखाउँछ; खोज त्यसको तल **हालका** भित्र हुन्छ। स्थानीय वा remote परियोजना वा SideCar छान्दा ट्याब उही स्थानमा भरिन्छ। खाली ट्याब पुनः लोड हुँदासम्म रहन्छ र बन्द गर्दा परियोजना बाँकी रहँदैन। शीर्षक वा ट्याब पट्टीको CodeNomad लोगोले सेटिङ, भाषा र मुटु भएको **प्रायोजन** बटनसहित गृह पृष्ठ खोल्छ ([CodeNomad लाई सहयोग](sponsor.md))। 2. **हालका** मा परियोजना छान्नुहोस्; वा **ब्राउज गर्नुहोस्** खोलेर **यो कम्प्युटर** छान्नुहोस्, अनि backend फोल्डर चयन गरी खोल्नुहोस्। **ब्राउज गर्नुहोस्** ले बचत गरिएका CodeNomad सर्भरहरू ([रिमोट परियोजना ट्याबहरू](remote-access.md#remote-project-tabs)) र SideCar हरू ([SideCars](browser-sidecars.md#register-sidecar)) पनि देखाउँछ। 3. रिपोजिटरी प्रतिलिपिका लागि **Git Repo क्लोन गर्नुहोस्** रोजी **रिपोजिटरी URL** र **गन्तव्य फोल्डर** भर्नुहोस्, अनि **क्लोन गर्नुहोस्**। **गन्तव्य फोल्डर** मा तपाईंको पछिल्लो क्लोन भएको फोल्डरभित्र (नभए सबैभन्दा हालको प्रोजेक्टको छेउमा) रिपोजिटरीको नाम पहिल्यै भरिन्छ। **ब्राउज गर्नुहोस्** ले क्लोन राख्ने फोल्डर छान्छ; क्लोनको फोल्डर नामसहित path आफैँ पनि बदल्न सकिन्छ। रिमोट सर्भर ब्राउज गर्नु त्यस सर्भरको फाइल प्रणाली ब्राउज गर्नु हो, आफ्नो फोन वा ल्यापटपको होइन। परियोजना खोल्दा प्रत्येक ट्याबको छुट्टै OpenCode daemon बन्दैन। कुराकानी नेटिभ OpenCode सत्र हुन्; तिनको आयु ट्याबको आयु होइन। +**ब्राउज गर्नुहोस्** मा सर्भर छान्दा सूची त्यसका हालका परियोजना र folder ले बदलिन्छ। मागिएमा inline form बाट sign in गरी परियोजना छान्नुहोस्, वा folder मा गई **हालको चयन गर्नुहोस्** थिच्नुहोस्। ब्राउजमा फर्कँदा सर्भर सूची देखिन्छ। परियोजना छानेपछि मात्र खाली ट्याब भरिन्छ र `+` लन्चर बन्द हुन्छ। Remote ट्याबले browsing भन्दा छुट्टै sign-in माग्न सक्छ। + क्लोनले गन्तव्यमा रिपोजिटरी लेख्छ। **यदि पहिले नै अवस्थित छ भने पहिले गन्तव्य फोल्डर हटाउनुहोस्।** विनाशकारी छ: त्यहाँका सबै सामग्री मेट्न मिल्दा मात्र सक्षम गर्नुहोस्। अनिश्चित भए नयाँ गन्तव्य प्रयोग गर्नुहोस्। क्लोन असफल भयो भन्दै विद्यमान परियोजना नमेट्नुहोस्; फेरि प्रयासअघि देखाइएको गन्तव्य र त्रुटि जाँच्नुहोस्। भर्खरका प्रविष्टि shortcut हुन्। **कार्यस्थान पुन: नामकरण गर्नुहोस्** ले देखिने नाम बदल्छ; **भर्खरको सूचीबाट हटाउनुहोस्** ले shortcut हटाउँछ, फाइल वा कुराकानी होइन। पहिले नै खुला recent परियोजना क्लिक गर्दा नयाँ ट्याब खुल्छ; त्यसको सट्टा विद्यमान ट्याब चयन गर्न त्यसको **खोल्नुहोस्** बटन (**खुला परियोजनामा जानुहोस्**) प्रयोग गर्नुहोस्। diff --git a/docs/help/ne/remote-access.md b/docs/help/ne/remote-access.md index 43dadf18a9..7778952619 100644 --- a/docs/help/ne/remote-access.md +++ b/docs/help/ne/remote-access.md @@ -83,23 +83,26 @@ certificate चेतावनी आए रोकिएर hostname, SAN, trust ## remote server बचत {#saved-servers} -1. गृह पृष्ठ, खाली ट्याब वा **ट्याब खोल्नुहोस्** लन्चरमा **ब्राउज गर्नुहोस्** खोली ठेगाना वा pairing link **सर्भरको ठेगाना वा लिङ्क** मा राख्नुहोस्। टाँस्दा तुरुन्त थपिन्छ; टाइप गरेको पाठ Enter ले थप्छ। सर्भर host name मा बचत मात्र हुन्छ र यसको पङ्क्तिमा focus जान्छ; लन्चर खुलै रहन्छ। खोल्न पङ्क्ति क्लिक गर्नुहोस्। **सेटिङहरू → सर्भरहरू** मा पनि यही फिल्ड छ। -2. विश्वसनीय HTTPS origin प्रयोग गर्नुहोस्। प्रमाणपत्र जाँच असफल भए फिल्डमुनि **TLS प्रमाणीकरण छोड्नुहोस्** देखिन्छ: विश्वसनीय सर्भरका लागि मात्र चिन्ह लगाई बचत गर्न फेरि Enter थिच्नुहोस्। यो बचत गरिएको सर्भर छान्दा आफ्नै विन्डोमा खुल्छ। -3. त्यो सर्भरमा sign in गर्नुहोस्। यसको नाम वा ठेगाना **सेटिङहरू → सर्भरहरू** मा **सर्भर सम्पादन गर्नुहोस्** बाट बदल्नुहोस्। +1. गृह पृष्ठ, खाली ट्याब वा **ट्याब खोल्नुहोस्** लन्चरमा **ब्राउज गर्नुहोस्** खोली ठेगाना वा pairing link **सर्भरको ठेगाना वा लिङ्क** मा राख्नुहोस्। टाँस्दा तुरुन्त थपिन्छ; टाइप गरेको पाठ Enter ले थप्छ। सर्भर host name मा बचत मात्र हुन्छ र यसको पङ्क्तिमा focus जान्छ; लन्चर खुलै रहन्छ। त्यही सूचीमा परियोजना हेर्न पङ्क्ति क्लिक गर्नुहोस्। **सेटिङहरू → सर्भरहरू** मा पनि यही फिल्ड छ। +2. विश्वसनीय HTTPS origin प्रयोग गर्नुहोस्। प्रमाणपत्र जाँच असफल भए फिल्डमुनि **TLS प्रमाणीकरण छोड्नुहोस्** देखिन्छ: विश्वसनीय सर्भरका लागि मात्र चिन्ह लगाई बचत गर्न फेरि Enter थिच्नुहोस्। यो profile को folder वा परियोजना छान्दा आफ्नै विन्डोमा खुल्छ। +3. **ब्राउज गर्नुहोस्** मा सर्भरको पङ्क्ति छानेर त्यही सूचीमा परियोजना हेर्नुहोस्। मागिएमा inline form मा username र password दिनुहोस्। नाम वा ठेगाना **सेटिङहरू → सर्भरहरू** को **सर्भर सम्पादन गर्नुहोस्** बाट बदल्नुहोस्। -बचत गरिएका सर्भरहरू **ब्राउज गर्नुहोस्** मा देखिन्छन्: फेरि खोल्न एउटा छान्नुहोस्। **सेटिङहरू → सर्भरहरू** मा तिनलाई खोल्न, सम्पादन गर्न (**सर्भर सम्पादन गर्नुहोस्**: नाम, ठेगाना, प्रमाणपत्र जाँच) र हटाउन (**बचत गरिएको सर्भर हटाउनुहोस्**) सकिन्छ। bookmark यो CodeNomad कन्फिगरेसनका हुन्, remote server का project होइनन्। URL बचतले server सुरु वा access प्रदान गर्दैन। **बचत गरिएको सर्भर हटाउनुहोस्** ले bookmark हटाउँछ, remote कुराकानी, backend वा credential होइन। +**सेटिङहरू → सर्भरहरू** मा profile व्यवस्थापन हुन्छ (**सर्भर सम्पादन गर्नुहोस्**, **बचत गरिएको सर्भर हटाउनुहोस्**)। हटाउँदा पहिले backend मा भएका browsing credential र session बिर्सिन्छ, अनि bookmark हट्छ र सम्बन्धित ट्याब बन्द हुन्छन्। Remote परियोजना र कुराकानी सर्भरमै रहन्छन्। स्थानीय backend ले browsing secret आफ्नो configuration सँगै `remote-server-credentials.json` मा राख्छ; यो फाइललाई password जस्तै सुरक्षित राख्नुहोस्। Embedded view को authentication छुट्टै हुन्छ। -सुरक्षित सर्भर command line बाट सिधै खोल्न, सर्भरको सुरक्षित नाम वा यसको `https://` URL सहित desktop app लाई `--connect-server ` (वा `--connect-server=`) सँग सुरु गर्नुहोस्। CodeNomad ले remote window मात्र खोल्छ, **ब्राउज गर्नुहोस्** जस्तै उही जाँच र sign in सहित; CodeNomad पहिले नै चलिरहेको छ भने, नयाँ window को सट्टा यसको हालको window ले त्यसलाई खोल्छ। कुनै सुरक्षित सर्भरसँग नमिल्ने URL यसको host नाममा बचत हुन्छ। सुरु गर्दा दिइने मानमा credential कहिल्यै हुँदैन: user नाम, password वा pairing code भएको URL अस्वीकार हुन्छ। नाम अज्ञात भए, URL अमान्य भए वा जडान असफल भए, CodeNomad सामान्य रूपमा सुरु हुन्छ र त्रुटि देखाउँछ। स्व-हस्ताक्षरित सर्भरका लागि स्थानीय प्रमाणपत्र स्थापना जस्ता पुष्टि जडानलाई चाहिँदा पनि, CodeNomad सामान्य रूपमा सुरु हुन्छ र त्यहीँ सोध्छ। Windows मा, सुरु गर्ने argument मा `|` भए Tauri build सुरु हुँदैन; बरु सर्भरको URL प्रयोग गर्नुहोस्, वा सर्भरको नाम बदल्नुहोस्। +सुरक्षित सर्भर command line बाट सिधै खोल्न, सर्भरको सुरक्षित नाम वा यसको `https://` URL सहित desktop app लाई `--connect-server ` (वा `--connect-server=`) सँग सुरु गर्नुहोस्। CodeNomad ले remote window मात्र खोल्छ, profile को TLS जाँच र native remote window को आफ्नै sign-in सहित; CodeNomad पहिले नै चलिरहेको छ भने, नयाँ window को सट्टा यसको हालको window ले त्यसलाई खोल्छ। कुनै सुरक्षित सर्भरसँग नमिल्ने URL यसको host नाममा बचत हुन्छ। सुरु गर्दा दिइने मानमा credential कहिल्यै हुँदैन: user नाम, password वा pairing code भएको URL अस्वीकार हुन्छ। नाम अज्ञात भए, URL अमान्य भए वा जडान असफल भए, CodeNomad सामान्य रूपमा सुरु हुन्छ र त्रुटि देखाउँछ। स्व-हस्ताक्षरित सर्भरका लागि स्थानीय प्रमाणपत्र स्थापना जस्ता पुष्टि जडानलाई चाहिँदा पनि, CodeNomad सामान्य रूपमा सुरु हुन्छ र त्यहीँ सोध्छ। Windows मा, सुरु गर्ने argument मा `|` भए Tauri build सुरु हुँदैन; बरु सर्भरको URL प्रयोग गर्नुहोस्, वा सर्भरको नाम बदल्नुहोस्। रिमोट विन्डोले यो कम्प्युटरमा फर्कने बाटो सधैँ छोड्छ। रिमोट विन्डोहरू खुला रहँदा अन्तिम स्थानीय विन्डो बन्द गर्दा त्यसका ट्याबहरू रहन्छन्: रिमोट विन्डोमा **सञ्झ्याल → नयाँ विन्डो**, वा CodeNomad फेरि सुरु गर्दा त्यो फेरि खुल्छ। सर्भर लोड गर्न नसकिँदा त्यसको विन्डोले त्यो देखाउँछ र **फेरि प्रयास गर्नुहोस्**, **स्थानीय विन्डो खोल्नुहोस्** र **विन्डो बन्द गर्नुहोस्** दिन्छ; Tauri संस्करणमा पृष्ठको रिलोड बटन र **सञ्झ्याल → नयाँ विन्डो** प्रयोग गर्नुहोस्। -Remote Control मा **सर्भरको ठेगाना वा लिङ्क** मा नयाँ pairing link paste गर्नुहोस्। bookmark ले tunnel origin मात्र राख्छ, one-use code कहिल्यै होइन; device-cookie हराएपछि पुनःpair गर्न [Remote Control](remote-control.md) हेर्नुहोस्। +Remote Control link टाँस्दा tunnel origin मात्र बचत हुन्छ र server-side pairing उपलब्ध नभएको त्रुटि देखिन्छ; code हटाइन्छ। Pair गर्न इच्छित browser मा link खोल्नुहोस्। [Remote Control](remote-control.md) हेर्नुहोस्। ## रिमोट परियोजना ट्याबमा खोल्नुहोस् {#remote-project-tabs} डेस्कटप एपमा (Electron, वा Windows मा Tauri), बचत गरिएको सर्भरले आफ्नो कुनै परियोजना यो सञ्झ्यालको ट्याबमा, तपाईंका स्थानीय परियोजनाहरूसँगै, खोल्न पनि सक्छ: 1. गृह पृष्ठ, खाली ट्याब वा **ट्याब खोल्नुहोस्** लन्चरमा **ब्राउज गर्नुहोस्** खोली बचत गरिएको सर्भर छान्नुहोस्। पहिले थप्न **सर्भरको ठेगाना वा लिङ्क** प्रयोग गरी नयाँ पङ्क्ति क्लिक गर्नुहोस्। -2. ट्याबमा फोल्डर छान्नुहोस्। त्यसपछि ट्याबले सर्भर आइकन र परियोजनाको नाम देखाउँछ, र परियोजना **हालका** मा थपिन्छ: त्यहाँ छान्दा त्यही सर्भर र फोल्डर सिधै फेरि खुल्छ। +2. त्यही सूचीमा सर्भरका हालका परियोजना र folder देखिन्छन्। आवश्यक भए inline form बाट sign in गर्नुहोस्। हालको परियोजना छान्नुहोस् वा folder मा गई **हालको चयन गर्नुहोस्** थिच्नुहोस्। **ब्राउजमा फर्कनुहोस्** ले सर्भर सूची देखाउँछ। +3. Folder छान्दा remote project ट्याब खुल्छ र सुरुको खाली ट्याबलाई बदल्छ। `+` लन्चर यो छनोटसम्म खुलै रहन्छ। परियोजना सिधै फेरि खोल्न **हालका** मा थपिन्छ। -ट्याबले त्यही परियोजना मात्र देखाउँछ; यसका कुराकानी, फाइल, Git, सेटिङ र Missions रिमोट सर्भरमा चल्छन्। यसले सर्भरको रिमोट सञ्झ्यालकै भण्डारण प्रयोग गर्छ, त्यसैले भइरहेको साइन-इन वा पेयर गरिएको उपकरण फेरि प्रयोग हुन्छ, र CodeNomad ले तपाईंका ट्याब पुनर्स्थापना गर्दा रिमोट ट्याबहरू पनि फर्कन्छन्। यो मोड नभएको सर्भरले ट्याबमा आफ्नो पूर्ण इन्टरफेस देखाउँछ। TLS प्रमाणीकरण छोड्ने सर्भरहरू, र macOS तथा Linux मा Tauri बिल्डले, रिमोट सञ्झ्याल नै खोलिरहन्छन्। ट्याबको पृष्ठले सूचना देखाउन सक्छ, तर यो कम्प्युटरमा अरू पहुँच हुँदैन र यो आफ्नै सर्भरमा रहन्छ। वेब क्लाइन्ट र Remote Control उपकरणहरूमा रिमोट ट्याब हुँदैन। **सेटिङहरू → सर्भरहरू** मा रहेको **बचत गरिएको सर्भर हटाउनुहोस्** ले यसका ट्याबहरू पनि बन्द गर्छ। परियोजना छान्नुअघि ट्याबले सर्भरको नाम देखाउँछ। ट्याबभित्र सर्भरकै पृष्ठमा sign in गर्नुहोस्; CodeNomad ले पछिका सुरुवातहरूमा त्यही sign-in फेरि प्रयोग गर्छ। +ट्याबका कुराकानी, फाइल, Git, सेटिङ र Missions remote server मा चल्छन्। Embedded view ले सर्भरको remote-window storage साझा गर्छ र Browse भन्दा छुट्टै sign-in माग्न सक्छ। Remote ट्याब startup restoration मा फर्कन्छन्। Embedded mode नभएका सर्भरले पूर्ण UI देखाउँछन्; TLS verification छोड्ने profile र macOS/Linux को Tauri ले छुट्टै window खोल्छन्। Embedded page सर्भरमै रहन्छ र host मा notification मात्र दिन सक्छ। Web client र Remote Control device मा remote ट्याब हुँदैनन्। + +Backend browsing ले address सुरक्षा सहित direct CodeNomad access प्रयोग गर्छ: CGNAT/Tailscale IP literal र विशेष address range अस्वीकार हुन्छन्। सबै VPN address चल्छन् भन्ने नमान्नुहोस्; वास्तविक destination जाँच्नुहोस्। Certificate verification बचत गरिएको profile र स्पष्ट TLS confirmation अनुसार हुन्छ। diff --git a/docs/help/ne/remote-control.md b/docs/help/ne/remote-control.md index 7af2dc1853..a576bf41be 100644 --- a/docs/help/ne/remote-control.md +++ b/docs/help/ne/remote-control.md @@ -11,7 +11,7 @@ Remote Control ले paired browser वा desktop client लाई inbound net link **पाँच मिनेट** मान्य हुन्छ र **एकपटक** सफल हुन्छ। credential झैं लिनुहोस्: प्रयोग गर्ने जोकोही paired device बन्न सक्छ। code URL fragment मा हुन्छ, query string मा होइन। **नयाँ जोडी लिंक बनाउनुहोस्** ले अघिल्लो unused link तुरुन्त अमान्य गर्छ। Stop, backend shutdown र tunnel failure ले बाँकी pairing link रद्द गर्छन्। -अर्को desktop CodeNomad pair गर्न गृह पृष्ठ वा खाली ट्याबमा **ब्राउज गर्नुहोस्** खोली link **सर्भरको ठेगाना वा लिङ्क** मा टाँस्नुहोस्। यसले सर्भर मात्र थप्छ; खोल्न र pair गर्न बचत गरिएको पङ्क्ति क्लिक गर्नुहोस्। एकपटक प्रयोग हुने link खोल्दासम्म वा पुनः लोड हुँदासम्म यस झ्यालको मेमोरीमा पर्खन्छ; पाँच मिनेटको वैधताभित्र प्रयोग गर्नुहोस्। bookmark मा tunnel origin मात्र बचत हुन्छ। pairing link मा TLS verification enabled रहन्छ। +Pairing link इच्छित browser मा खोल्नुहोस्। Desktop को **सर्भरको ठेगाना वा लिङ्क** मा टाँस्दा tunnel origin मात्र बचत हुन्छ र server-side pairing उपलब्ध नभएको त्रुटि देखिन्छ। Code हटाइन्छ। Backend को folder browsing ले आफ्नै direct-access session प्रयोग गर्छ; embedded view ले आफ्नो sign-in वा device cookie स्वतन्त्र रूपमा राख्छ। ## paired device व्यवस्थापन {#paired-devices} @@ -28,7 +28,7 @@ direct-access password बदल्दा device revoke **हुँदैनन ### आफ्नो ठाउँ नगुमाई पुनःpair {#re-pair} 1. client ले **यो उपकरण फेरि जोड्नुहोस्** देखाए त्यो पृष्ठ खुलै राख्नुहोस्। -2. host मा **नयाँ जोडी लिंक बनाउनुहोस्** रोजी **उही client browser/profile** मा खोल्नुहोस्। saved desktop server मा विद्यमान remote-window storage पुनःप्रयोग गर्न नयाँ pairing link बाट reconnect गर्नुहोस्। +2. host मा **नयाँ जोडी लिंक बनाउनुहोस्** रोजी **उही client browser/profile** मा खोल्नुहोस्। 3. पर्खिरहेको पृष्ठमा फर्केर **जडान जाँच्नुहोस्** रोज्नुहोस्; पृष्ठमा फेरि focus आउँदा पनि यसले फेरि जाँच्छ। recovery ले खुला पृष्ठ र मस्यौदा जोगाउँछ; असफल कार्य replay गर्दैन। retry अघि send, answer वा delete लागू भयो कि जाँच्नुहोस्। direct-access password ले Remote Control pairing पुनःप्राप्त गर्न सक्दैन। diff --git a/docs/help/ru/projects.md b/docs/help/ru/projects.md index 7c3a3fbb2f..f5e51b306d 100644 --- a/docs/help/ru/projects.md +++ b/docs/help/ru/projects.md @@ -4,12 +4,14 @@ ## Открытие проекта {#open-project} -1. **Новый экземпляр** (`+`) открывает пустую **Новую вкладку** с фокусом в поиске. Она использует фон главной страницы, логотип и имя CodeNomad по центру и большие кнопки **Клонировать Git-репозиторий**, **Новая временная вкладка**, **Новый SideCar**. Переключатель **Недавние | Обзор** показывает число элементов; поиск расположен под ним в **Недавние**. Выбор проекта, сохранённого сервера или SideCar заполняет вкладку на её месте. Пустая вкладка существует до перезагрузки и закрывается без оставшегося проекта. Логотип CodeNomad в заголовке или панели вкладок открывает главную страницу с настройками, языком и кнопкой с сердцем **Спонсировать** ([Поддержать CodeNomad](sponsor.md)). +1. **Новый экземпляр** (`+`) открывает пустую **Новую вкладку** с фокусом в поиске. Она использует фон главной страницы, логотип и имя CodeNomad по центру и большие кнопки **Клонировать Git-репозиторий**, **Новая временная вкладка**, **Новый SideCar**. Переключатель **Недавние | Обзор** показывает число элементов; поиск расположен под ним в **Недавние**. Выбор локального или удалённого проекта либо SideCar заполняет вкладку на её месте. Пустая вкладка существует до перезагрузки и закрывается без оставшегося проекта. Логотип CodeNomad в заголовке или панели вкладок открывает главную страницу с настройками, языком и кнопкой с сердцем **Спонсировать** ([Поддержать CodeNomad](sponsor.md)). 2. В **Недавние** выберите проект; или откройте **Обзор**, выберите **Этот компьютер**, затем укажите папку на бэкенде и откройте её. **Обзор** также показывает сохранённые серверы CodeNomad ([вкладки удалённых проектов](remote-access.md#remote-project-tabs)) и SideCar ([SideCar](browser-sidecars.md#register-sidecar)). 3. Для копирования репозитория выберите **Клонировать Git-репозиторий**, заполните **URL репозитория** и **Папка назначения**, затем нажмите **Клонировать**. **Папка назначения** заполняется заранее: папка с именем репозитория в папке, где лежит последний клон, а без него — рядом с последним проектом. **Обзор** выбирает папку, в которой будет клон; путь, включая имя папки клона, можно изменить и вручную. Просмотр удалённого сервера означает просмотр его файловой системы, а не телефона или ноутбука. Открытие проекта не создаёт отдельный демон OpenCode для каждой вкладки. Разговоры — нативные сессии OpenCode; их время жизни не совпадает со временем жизни вкладки. +Выбор сервера в **Обзор** заменяет список его недавними проектами и папками. При запросе войдите во встроенной форме, затем выберите проект или перейдите в папку и нажмите **Выбрать текущую**. Возврат к обзору показывает серверы. Только выбор проекта заполняет пустую вкладку и закрывает панель `+`. Удалённая вкладка может запросить отдельный вход независимо от просмотра. + Клонирование записывает репозиторий в папку назначения. Параметр **Сначала удалить папку назначения, если она уже существует.** разрушителен: включайте его, только если всё уже находящееся там можно удалить. Если не уверены, используйте новую папку. Неудачное клонирование не повод удалять существующий проект; перед повтором проверьте указанные папку назначения и ошибку. Недавние записи — это ярлыки. **Переименовать рабочее пространство** меняет отображаемое имя; **Убрать из недавних** удаляет ярлык, но не файлы и разговоры. Щелчок по уже открытому недавнему проекту открывает новую вкладку; его кнопка **Открыта** (**Перейти к открытому проекту**) вместо этого выбирает существующую вкладку. diff --git a/docs/help/ru/remote-access.md b/docs/help/ru/remote-access.md index 9c22b89a6c..c3b6a40071 100644 --- a/docs/help/ru/remote-access.md +++ b/docs/help/ru/remote-access.md @@ -83,23 +83,26 @@ codenomad --host 127.0.0.1 --https=false --http=true ## Сохранение удалённого сервера {#saved-servers} -1. На главной странице, пустой вкладке или в панели **Открыть вкладку** откройте **Обзор** и введите адрес или ссылку сопряжения в **Адрес или ссылка сервера**. Вставка добавляет сразу, Enter подтверждает набранный текст. Сервер только сохраняется под именем хоста, фокус переходит на его строку; панель остаётся открытой. Нажмите на строку для открытия. В **Настройки → Серверы** есть то же поле. -2. Используйте доверенный HTTPS-источник. Если сертификат не прошёл проверку, под полем появится **Пропустить проверку TLS**: включайте это только для доверенного сервера и снова нажмите Enter для сохранения. Выбор этого сохранённого сервера открывает отдельное окно. -3. Войдите на этом сервере. Переименуйте его или измените адрес через **Изменить сервер** в **Настройки → Серверы**. +1. На главной странице, пустой вкладке или в панели **Открыть вкладку** откройте **Обзор** и введите адрес или ссылку сопряжения в **Адрес или ссылка сервера**. Вставка добавляет сразу, Enter подтверждает набранный текст. Сервер только сохраняется под именем хоста, фокус переходит на его строку; панель остаётся открытой. Нажмите на строку для просмотра проектов на месте. В **Настройки → Серверы** есть то же поле. +2. Используйте доверенный HTTPS-источник. Если сертификат не прошёл проверку, под полем появится **Пропустить проверку TLS**: включайте это только для доверенного сервера и снова нажмите Enter для сохранения. Выбор папки или проекта этого профиля открывает отдельное окно. +3. Выберите строку сервера в **Обзор**, чтобы просматривать проекты на месте. При запросе введите имя пользователя и пароль во встроенной форме. Имя и адрес меняются через **Изменить сервер** в **Настройки → Серверы**. -Сохранённые серверы перечислены в **Обзор**: выберите сервер, чтобы снова открыть его. В **Настройки → Серверы** их можно открыть, изменить (**Изменить сервер**: имя, адрес, проверка сертификата) и удалить (**Удалить сохраненный сервер**). Закладки принадлежат этой конфигурации CodeNomad, не проектам удалённого сервера. Сохранение URL не запускает сервер и не предоставляет доступ. **Удалить сохраненный сервер** удаляет закладку, не удалённые разговоры, серверную часть или её учётные данные. +**Настройки → Серверы** управляет профилями (**Изменить сервер**, **Удалить сохраненный сервер**). При удалении сначала забываются учётные данные и сеанс просмотра в серверной части, затем удаляется закладка и закрываются её вкладки. Удалённые проекты и разговоры остаются на своём сервере. Локальная серверная часть хранит секреты просмотра в `remote-server-credentials.json` рядом с конфигурацией; защищайте файл как пароль. Встроенные представления сохраняют отдельную аутентификацию. -Чтобы открыть сохранённый сервер прямо из командной строки, запустите настольное приложение с `--connect-server ` (или `--connect-server=`), указав сохранённое имя сервера или его URL `https://`. CodeNomad открывает только удалённое окно, с теми же проверками и входом, что и **Обзор**; если CodeNomad уже запущен, сервер открывает его текущее окно, а не новое. URL, не совпадающий ни с одним сохранённым сервером, сохраняется под именем своего хоста. Значения запуска никогда не содержат учётных данных: URL с именем пользователя, паролем или кодом сопряжения отклоняется. Если имя неизвестно, URL недействителен или подключение не удалось, CodeNomad запускается как обычно и показывает ошибку. Если подключению нужно подтверждение, например установка локального сертификата для самоподписанного сервера, CodeNomad тоже запускается как обычно и запрашивает его там. В Windows сборка Tauri не запускается, если аргумент запуска содержит `|`; используйте URL сервера или переименуйте сервер. +Чтобы открыть сохранённый сервер прямо из командной строки, запустите настольное приложение с `--connect-server ` (или `--connect-server=`), указав сохранённое имя сервера или его URL `https://`. CodeNomad открывает только удалённое окно, с проверками TLS профиля и собственным входом нативного удалённого окна; если CodeNomad уже запущен, сервер открывает его текущее окно, а не новое. URL, не совпадающий ни с одним сохранённым сервером, сохраняется под именем своего хоста. Значения запуска никогда не содержат учётных данных: URL с именем пользователя, паролем или кодом сопряжения отклоняется. Если имя неизвестно, URL недействителен или подключение не удалось, CodeNomad запускается как обычно и показывает ошибку. Если подключению нужно подтверждение, например установка локального сертификата для самоподписанного сервера, CodeNomad тоже запускается как обычно и запрашивает его там. В Windows сборка Tauri не запускается, если аргумент запуска содержит `|`; используйте URL сервера или переименуйте сервер. Из удалённого окна всегда можно вернуться на этот компьютер. Если закрыть последнее локальное окно, пока удалённые окна остаются открытыми, его вкладки сохраняются: **Окно → Новое окно** в удалённом окне или повторный запуск CodeNomad открывает его снова. Если сервер не удаётся загрузить, его окно сообщает об этом и предлагает **Повторить**, **Открыть локальное окно** и **Закрыть окно**; в версии Tauri используйте кнопку перезагрузки страницы и **Окно → Новое окно**. -Для удалённого управления вместо этого вставьте свежую ссылку сопряжения в **Адрес или ссылка сервера**. Закладка хранит только origin туннеля, никогда одноразовый код; повторное сопряжение после потери cookie устройства описано в [удалённом управлении](remote-control.md). +Вставка ссылки удалённого управления сохраняет только origin туннеля и сообщает о недоступности сопряжения на стороне сервера; код удаляется. Для сопряжения откройте ссылку в нужном браузере. См. [удалённое управление](remote-control.md). ## Открыть удалённый проект во вкладке {#remote-project-tabs} В настольном приложении (Electron или Tauri в Windows) сохранённый сервер может также открыть один из своих проектов во вкладке этого окна, рядом с локальными проектами: 1. На главной странице, пустой вкладке или в панели **Открыть вкладку** откройте **Обзор** и выберите сохранённый сервер. Для добавления используйте **Адрес или ссылка сервера**, затем нажмите на новую строку. -2. Выберите папку во вкладке. Вкладка покажет значок сервера и имя проекта, а проект появится в **Недавние**: выбор там сразу снова открывает этот сервер и папку. +2. Список на месте переключится на недавние проекты и папки сервера. При необходимости войдите во встроенной форме. Выберите недавний проект или перейдите в папку и нажмите **Выбрать текущую**. **Назад к обзору** открывает список серверов. +3. Выбор папки открывает вкладку удалённого проекта вместо исходной пустой вкладки. Панель `+` остаётся открытой до выбора. Проект добавляется в **Недавние** для прямого открытия. -Вкладка показывает только этот проект; его беседы, файлы, Git, настройки и Missions работают на удалённом сервере. Она использует хранилище удалённого окна сервера, поэтому существующий вход или сопряжённое устройство используются повторно, а удалённые вкладки возвращаются, когда CodeNomad восстанавливает вкладки. Сервер без этого режима показывает во вкладке свой полный интерфейс. Серверы, пропускающие проверку TLS, и сборка Tauri в macOS и Linux по-прежнему открывают удалённое окно. Страница во вкладке может показывать уведомления, но не имеет другого доступа к этому компьютеру и остаётся на своём сервере. У веб-клиентов и устройств Remote Control удалённых вкладок нет. **Удалить сохраненный сервер** в **Настройки → Серверы** также закрывает его вкладки. Пока проект не выбран, вкладка показывает имя сервера. Входите на странице сервера в самой вкладке; CodeNomad повторно использует этот вход при следующих запусках. +Беседы, файлы, Git, настройки и Missions вкладки работают на удалённом сервере. Встроенное представление использует хранилище удалённого окна и может запросить отдельный вход независимо от Обзора. Удалённые вкладки восстанавливаются при запуске. Серверы без встроенного режима показывают полный интерфейс; профили без проверки TLS и Tauri в macOS/Linux открывают отдельное окно. Встроенная страница остаётся на своём сервере и имеет только доступ к уведомлениям хоста. У веб-клиентов и устройств удалённого управления нет удалённых вкладок. + +Просмотр через серверную часть использует прямой доступ CodeNomad с защитой адресов: IP-литералы CGNAT/Tailscale и специальные диапазоны отклоняются. Проверяйте конкретный адрес, не предполагая поддержку любого VPN. Проверка сертификата следует сохранённому профилю и его явному подтверждению TLS. diff --git a/docs/help/ru/remote-control.md b/docs/help/ru/remote-control.md index 61dcb732bf..dcc1f09571 100644 --- a/docs/help/ru/remote-control.md +++ b/docs/help/ru/remote-control.md @@ -11,7 +11,7 @@ Ссылка действует **пять минут** и срабатывает **один раз**. Считайте её учётными данными: любой использовавший её может стать сопряжённым устройством. Код находится во фрагменте URL, не в строке запроса. **Создать новую ссылку сопряжения** немедленно делает предыдущую неиспользованную ссылку недействительной. Остановка, завершение серверной части и сбой туннеля отменяют ожидающие ссылки сопряжения. -Для сопряжения другого настольного CodeNomad откройте **Обзор** на главной странице или пустой вкладке и вставьте ссылку в **Адрес или ссылка сервера**. Это только добавляет сервер; нажмите на сохранённую строку для открытия и сопряжения. Одноразовая ссылка ждёт в памяти этого окна до открытия или перезагрузки; используйте её в течение пяти минут действия. В закладке сохраняется только origin туннеля. Проверка TLS для ссылок сопряжения остаётся включённой. +Открывайте ссылки сопряжения в нужном браузере. Вставка в **Адрес или ссылка сервера** настольного приложения сохраняет только origin туннеля и сообщает, что сопряжение на стороне сервера недоступно. Код удаляется. Просмотр папок через серверную часть использует собственный сеанс прямого доступа; встроенное представление независимо хранит свой вход или cookie устройства. ## Управление сопряжёнными устройствами {#paired-devices} @@ -28,7 +28,7 @@ ### Повторное сопряжение без потери места {#re-pair} 1. Если клиент показывает **Повторно сопрягите это устройство**, оставьте эту страницу открытой. -2. На хосте выберите **Создать новую ссылку сопряжения** и откройте в **том же браузере/профиле клиента**. Для сохранённого настольного сервера переподключитесь по свежей ссылке, чтобы использовать существующее хранилище удалённого окна. +2. На хосте выберите **Создать новую ссылку сопряжения** и откройте в **том же браузере/профиле клиента**. 3. Вернитесь на ожидающую страницу и нажмите **Проверить соединение**; проверка также повторяется, когда страница снова получает фокус. Восстановление сохраняет открытую страницу и черновики; не повторяет неудачное действие. Перед повтором проверьте, сработала ли отправка, ответ или удаление. Пароль прямого доступа не восстанавливает сопряжение удалённого управления. diff --git a/docs/help/tr/projects.md b/docs/help/tr/projects.md index 7570ee3202..726d8cbcf5 100644 --- a/docs/help/tr/projects.md +++ b/docs/help/tr/projects.md @@ -4,12 +4,14 @@ Bir proje sekmesi CodeNomad'i arka uç bilgisayarındaki bir klasöre bağlar. S ## Bir proje açın {#open-project} -1. **Yeni instance** (`+`), aramaya odaklanan boş bir **Yeni sekme** açar. Ana sayfanın arka planını, ortalanmış CodeNomad logosu ve adını, büyük **Git Deposunu Klonla**, **Yeni geçici sekme** ve **Yeni SideCar** düğmelerini kullanır. **Son kullanılanlar | Gözat** seçicisi öğe sayılarını gösterir; arama, seçicinin altında **Son kullanılanlar** içindedir. Proje, kayıtlı sunucu veya SideCar seçimi sekmeyi yerinde doldurur. Boş sekme yeniden yüklemeye kadar yaşar ve proje bırakmadan kapanır. Başlık veya sekme çubuğundaki CodeNomad logosu ayarlar, dil ve kalpli **Sponsor** düğmesini içeren ana sayfayı açar ([CodeNomad'i destekleyin](sponsor.md)). +1. **Yeni instance** (`+`), aramaya odaklanan boş bir **Yeni sekme** açar. Ana sayfanın arka planını, ortalanmış CodeNomad logosu ve adını, büyük **Git Deposunu Klonla**, **Yeni geçici sekme** ve **Yeni SideCar** düğmelerini kullanır. **Son kullanılanlar | Gözat** seçicisi öğe sayılarını gösterir; arama, seçicinin altında **Son kullanılanlar** içindedir. Yerel veya uzak proje ya da SideCar seçimi sekmeyi yerinde doldurur. Boş sekme yeniden yüklemeye kadar yaşar ve proje bırakmadan kapanır. Başlık veya sekme çubuğundaki CodeNomad logosu ayarlar, dil ve kalpli **Sponsor** düğmesini içeren ana sayfayı açar ([CodeNomad'i destekleyin](sponsor.md)). 2. **Son kullanılanlar** içinde bir proje seçin; ya da **Gözat** bölümünü açıp **Bu bilgisayar** seçin, ardından arka uç klasörünü seçip açın. **Gözat** kayıtlı CodeNomad sunucularını ([uzak proje sekmeleri](remote-access.md#remote-project-tabs)) ve SideCar'ları ([SideCar'lar](browser-sidecars.md#register-sidecar)) da listeler. 3. Depoyu kopyalamak için **Git Deposunu Klonla** eylemini seçin; **Depo URL'si** ve **Hedef klasör** alanlarını doldurup **Klonla** eylemini seçin. **Hedef klasör**, son klonunuzun bulunduğu klasörde (yoksa en son projenizin yanında) depo adıyla önceden doldurulur. **Göz At** klonu içerecek klasörü seçer; klon klasörünün adı dahil yolu elle de düzenleyebilirsiniz. Uzak bir sunucuya göz atmak, telefonunuzun veya dizüstü bilgisayarınızın değil, o sunucunun dosya sistemine göz atmak anlamına gelir. Bir projeyi açmak, her sekme için ayrı bir OpenCode arka plan programı oluşturmaz. Konuşmalar yerel OpenCode oturumlarıdır; bunların ömrü sekmenin ömrü değildir. +**Gözat** içinde sunucu seçmek listeyi onun son projeleri ve klasörleriyle değiştirir. İstenirse satır içi formdan oturum açın, sonra proje seçin veya klasöre gidip **Geçerli Olanı Seç** öğesini kullanın. Gözat'a dönüş sunucuları gösterir. Yalnızca proje seçimi boş sekmeyi doldurur ve `+` başlatıcısını kapatır. Uzak sekme taramadan bağımsız oturum açmanızı isteyebilir. + Klonlama hedefe bir depo yazar. **Hedef klasör zaten varsa önce onu kaldırın.** yıkıcıdır: yalnızca zaten orada olan her şeyin silinebildiği durumlarda etkinleştirin. Emin değilseniz yeni bir hedef kullanın. Başarısız bir klon, mevcut bir projeyi silmek için bir neden değildir; yeniden denemeden önce bildirilen hedefi ve hatayı inceleyin. Son kullanılan kayıtlar birer kısayoldur. **Workspace'i yeniden adlandır** görünen adı değiştirir; **Son kullanılanlardan kaldır** dosyaları veya konuşmaları değil, kısayolu kaldırır. Zaten açık olan bir son kullanılan projeye tıklamak yeni bir sekme açar; mevcut sekmeyi seçmek için bunun yerine projenin **Aç** düğmesini (**Açık projeye geç**) kullanın. diff --git a/docs/help/tr/remote-access.md b/docs/help/tr/remote-access.md index a1e4be5f0f..a60197c85c 100644 --- a/docs/help/tr/remote-access.md +++ b/docs/help/tr/remote-access.md @@ -83,23 +83,26 @@ Bir istemci bir sertifika uyarısı bildirirse, durdurun ve ana bilgisayar adın ## Uzak sunucuyu kaydedin {#saved-servers} -1. Ana sayfada, boş sekmede veya **Sekme aç** başlatıcısında **Gözat** bölümünü açıp adresi ya da eşleştirme bağlantısını **Sunucu adresi veya bağlantısı** alanına girin. Yapıştırma hemen ekler; Enter yazılan metni ekler. Sunucu yalnızca ana bilgisayar adıyla kaydedilir ve satırına odaklanılır; başlatıcı açık kalır. Açmak için bu satıra tıklayın. **Ayarlar → Sunucular** aynı alanı sunar. -2. Güvenilir bir HTTPS kaynağı kullanın. Sertifika doğrulanamazsa alanın altında **TLS doğrulamasını atla** görünür: yalnızca güvendiğiniz sunucu için işaretleyip kaydetmek üzere yeniden Enter'a basın. Kaydedilen bu sunucuyu seçmek kendi penceresini açar. -3. O sunucuda oturum açın. Adını veya adresini **Ayarlar → Sunucular** içindeki **Sunucuyu düzenle** ile değiştirin. +1. Ana sayfada, boş sekmede veya **Sekme aç** başlatıcısında **Gözat** bölümünü açıp adresi ya da eşleştirme bağlantısını **Sunucu adresi veya bağlantısı** alanına girin. Yapıştırma hemen ekler; Enter yazılan metni ekler. Sunucu yalnızca ana bilgisayar adıyla kaydedilir ve satırına odaklanılır; başlatıcı açık kalır. Projeleri aynı yerde taramak için bu satıra tıklayın. **Ayarlar → Sunucular** aynı alanı sunar. +2. Güvenilir bir HTTPS kaynağı kullanın. Sertifika doğrulanamazsa alanın altında **TLS doğrulamasını atla** görünür: yalnızca güvendiğiniz sunucu için işaretleyip kaydetmek üzere yeniden Enter'a basın. Bu profilde klasör veya proje seçmek kendi penceresini açar. +3. Projeleri aynı yerde taramak için **Gözat** içindeki kayıtlı satırını seçin. İstenirse satır içi forma sunucu kullanıcı adını ve parolasını girin. Adı veya adresi **Ayarlar → Sunucular** içindeki **Sunucuyu düzenle** ile değiştirin. -Kayıtlı sunucular **Gözat** altında listelenir: yeniden açmak için birini seçin. **Ayarlar → Sunucular** bölümünde sunucuları açabilir, düzenleyebilir (**Sunucuyu düzenle**: ad, adres, sertifika doğrulaması) ve kaldırabilirsiniz (**Kayıtlı sunucuyu kaldır**). Yer imleri uzak sunucunun projelerine değil, bu CodeNomad yapılandırmasına aittir. Bir URL'nin kaydedilmesi sunucuyu başlatmaz veya erişim sağlamaz. **Kayıtlı sunucuyu kaldır**, uzak konuşmaları, arka ucu veya kimlik bilgilerini değil, yer işaretini kaldırır. +**Ayarlar → Sunucular** profilleri yönetir (**Sunucuyu düzenle**, **Kayıtlı sunucuyu kaldır**). Kaldırma önce arka uçtaki tarama kimlik bilgilerini ve oturumunu unutur, ardından yer imini kaldırıp sekmelerini kapatır. Uzak projeler ve konuşmalar sunucuda kalır. Yerel arka uç tarama sırlarını yapılandırmasının yanında `remote-server-credentials.json` içinde saklar; bu dosyayı parola gibi koruyun. Gömülü görünümlerin kimlik doğrulaması ayrıdır. -Kayıtlı bir sunucuyu doğrudan komut satırından açmak için masaüstü uygulamasını sunucunun kayıtlı adıyla veya `https://` URL'siyle `--connect-server ` (ya da `--connect-server=`) seçeneğiyle başlatın. CodeNomad yalnızca uzak pencereyi açar; denetimler ve oturum açma **Gözat** ile aynıdır. CodeNomad zaten çalışıyorsa sunucuyu yeni bir pencere yerine geçerli penceresi açar. Hiçbir kayıtlı sunucuyla eşleşmeyen bir URL, ana bilgisayar adıyla kaydedilir. Başlatma değerleri hiçbir zaman kimlik bilgisi taşımaz: kullanıcı adı, parola veya eşleştirme kodu içeren bir URL reddedilir. Ad bilinmiyorsa, URL geçersizse veya bağlantı başarısız olursa CodeNomad normal şekilde başlar ve hatayı gösterir. Bağlantı, kendinden imzalı bir sunucu için yerel sertifikanın yüklenmesi gibi bir onay gerektirdiğinde de CodeNomad normal şekilde başlar ve onayı orada ister. Windows'ta bir başlatma bağımsız değişkeni `|` içerdiğinde Tauri derlemesi başlamaz; bunun yerine sunucunun URL'sini kullanın veya sunucuyu yeniden adlandırın. +Kayıtlı bir sunucuyu doğrudan komut satırından açmak için masaüstü uygulamasını sunucunun kayıtlı adıyla veya `https://` URL'siyle `--connect-server ` (ya da `--connect-server=`) seçeneğiyle başlatın. CodeNomad yalnızca uzak pencereyi açar; profilin TLS denetimlerini ve yerel uzak pencerenin kendi oturum açma işlemini kullanır. CodeNomad zaten çalışıyorsa sunucuyu yeni bir pencere yerine geçerli penceresi açar. Hiçbir kayıtlı sunucuyla eşleşmeyen bir URL, ana bilgisayar adıyla kaydedilir. Başlatma değerleri hiçbir zaman kimlik bilgisi taşımaz: kullanıcı adı, parola veya eşleştirme kodu içeren bir URL reddedilir. Ad bilinmiyorsa, URL geçersizse veya bağlantı başarısız olursa CodeNomad normal şekilde başlar ve hatayı gösterir. Bağlantı, kendinden imzalı bir sunucu için yerel sertifikanın yüklenmesi gibi bir onay gerektirdiğinde de CodeNomad normal şekilde başlar ve onayı orada ister. Windows'ta bir başlatma bağımsız değişkeni `|` içerdiğinde Tauri derlemesi başlamaz; bunun yerine sunucunun URL'sini kullanın veya sunucuyu yeniden adlandırın. Uzak pencere bu bilgisayara dönmenin bir yolunu her zaman bırakır. Uzak pencereler açık kalırken son yerel pencereyi kapatmak sekmelerini korur: uzak penceredeki **Pencere → Yeni pencere** ya da CodeNomad'ı yeniden başlatmak onu yeniden açar. Bir sunucu yüklenemezse penceresi bunu bildirir ve **Yeniden dene**, **Yerel pencere aç** ve **Pencereyi kapat** seçeneklerini sunar; Tauri sürümünde sayfanın yeniden yükleme düğmesini ve **Pencere → Yeni pencere** öğesini kullanın. -Uzaktan Kontrol için bunun yerine **Sunucu adresi veya bağlantısı** öğesine yeni bir eşleştirme bağlantısı yapıştırın. Yer imi yalnızca tünelin kökenini korur, asla tek kullanımlık eşleştirme kodunu içermez; Cihaz çerezi kaybından sonra yeniden eşleştirme için bkz. [Uzaktan Kontrol](remote-control.md). +Uzaktan Kontrol bağlantısı yapıştırmak yalnızca tünel kökenini kaydeder ve sunucu tarafında eşleştirmenin kullanılamadığını bildirir; kod silinir. Eşleştirmek için bağlantıyı istediğiniz tarayıcıda açın. Bkz. [Uzaktan Kontrol](remote-control.md). ## Uzak bir projeyi sekmede açın {#remote-project-tabs} Masaüstü uygulamasında (Electron veya Windows'ta Tauri), kayıtlı bir sunucu projelerinden birini yerel projelerinizin yanında bu pencerenin bir sekmesinde de açabilir: 1. Ana sayfada, boş sekmede veya **Sekme aç** başlatıcısında **Gözat** bölümünü açıp kayıtlı bir sunucu seçin. Önce eklemek için **Sunucu adresi veya bağlantısı** alanını kullanıp yeni satıra tıklayın. -2. Klasörü sekmede seçin. Sekme ardından sunucu simgesini ve proje adını gösterir ve proje **Son kullanılanlar** listesine eklenir: oradan seçmek o sunucuyu ve klasörü doğrudan yeniden açar. +2. Liste aynı yerde sunucunun son projelerine ve klasörlerine geçer. Gerekirse satır içi formdan oturum açın. Son projelerden birini seçin veya klasörlere gidip **Geçerli Olanı Seç** öğesini kullanın. **Gözat'a dön** sunucu listesini açar. +3. Klasör seçimi uzak proje sekmesini açar ve başlangıçtaki boş sekmenin yerini alır. `+` başlatıcısı seçime kadar açık kalır. Proje doğrudan yeniden açılmak üzere **Son kullanılanlar** listesine eklenir. -Sekme yalnızca o projeyi gösterir; konuşmaları, dosyaları, Git'i, ayarları ve Missions uzak sunucuda çalışır. Sekme sunucunun uzak penceresiyle aynı depolamayı kullanır; böylece mevcut bir oturum veya eşleştirilmiş cihaz yeniden kullanılır ve CodeNomad sekmelerinizi geri yüklediğinde uzak sekmeler de geri gelir. Bu modu olmayan bir sunucu sekmede tam arayüzünü gösterir. TLS doğrulamasını atlayan sunucular ile macOS ve Linux'taki Tauri sürümü uzak pencere açmaya devam eder. Sekmedeki sayfa bildirim gösterebilir, ancak bu bilgisayara başka erişimi yoktur ve kendi sunucusunda kalır. Web istemcilerinde ve Remote Control cihazlarında uzak sekme yoktur. **Ayarlar → Sunucular** içindeki **Kayıtlı sunucuyu kaldır** sunucunun sekmelerini de kapatır. Proje seçilmeden önce sekme sunucunun adını gösterir. Sekmenin içinde sunucunun sayfasında oturum açın; CodeNomad bu oturumu sonraki açılışlarda yeniden kullanır. +Sekmenin konuşmaları, dosyaları, Git'i, ayarları ve Missions uzak sunucuda çalışır. Gömülü görünüm sunucunun uzak pencere depolamasını paylaşır ve Gözat'tan bağımsız oturum açmanızı isteyebilir. Uzak sekmeler başlangıçta geri yüklenir. Gömülü modu olmayan sunucular tam arayüzü gösterir; TLS doğrulamasını atlayan profiller ve macOS/Linux'ta Tauri ayrı pencere açar. Gömülü sayfa kendi sunucusunda kalır ve ana bilgisayarda yalnızca bildirim erişimine sahiptir. Web istemcilerinde ve Uzaktan Kontrol cihazlarında uzak sekme yoktur. + +Arka uç taraması adres korumalı doğrudan CodeNomad erişimini kullanır: CGNAT/Tailscale IP sabitleri ve özel adres aralıkları reddedilir. Her VPN adresinin çalışacağını varsaymak yerine gerçek hedefi denetleyin. Sertifika doğrulaması kayıtlı profili ve açık TLS onayını izler. diff --git a/docs/help/tr/remote-control.md b/docs/help/tr/remote-control.md index 4f3446d051..8ea0a1ba66 100644 --- a/docs/help/tr/remote-control.md +++ b/docs/help/tr/remote-control.md @@ -11,7 +11,7 @@ Uzaktan Kontrol, eşleştirilmiş bir tarayıcının veya masaüstü istemcisini Bağlantı **beş dakika** süreyle geçerlidir ve **bir kez** başarılı olur. Bunu bir kimlik bilgisi olarak değerlendirin: Bunu tüketen herkes eşleştirilmiş bir cihaz haline gelebilir. Kod, sorgu dizesinde değil, URL parçasında bulunur. **Yeni eşleştirme bağlantısı oluştur**, önceki kullanılmayan bağlantıyı anında geçersiz kılar. Durdurma, arka uç kapatma ve tünel arızası, bekleyen eşleştirme bağlantılarını iptal eder. -Başka masaüstü CodeNomad istemcisini eşleştirmek için ana sayfada veya boş sekmede **Gözat** bölümünü açıp bağlantıyı **Sunucu adresi veya bağlantısı** alanına yapıştırın. Bu yalnızca sunucuyu ekler; açıp eşleştirmek için kayıtlı satırına tıklayın. Tek kullanımlık bağlantı, açılana veya yeniden yüklemeye kadar bu pencerenin belleğinde bekler; beş dakikalık geçerlilik süresinde kullanın. Yer imi yalnızca tünelin origin adresini saklar. Eşleştirme bağlantılarında TLS doğrulaması etkin kalır. +Eşleştirme bağlantılarını istediğiniz tarayıcıda açın. Masaüstündeki **Sunucu adresi veya bağlantısı** alanına yapıştırmak yalnızca tünel kökenini kaydeder ve sunucu tarafında eşleştirmenin kullanılamadığını bildirir. Kod silinir. Arka uç klasör taraması kendi doğrudan erişim oturumunu kullanır; gömülü görünüm kendi oturumunu veya cihaz çerezini bağımsız olarak saklar. ## Eşleştirilmiş cihazları yönetin {#paired-devices} @@ -28,7 +28,7 @@ Doğrudan erişim parolasını değiştirmek cihazları **iptal etmez**. **Uzakt ### Yerinizi kaybetmeden yeniden eşleştirin {#re-pair} 1. İstemci **Bu cihazı yeniden eşleştirin** gösterirse bu sayfayı açık bırakın. -2. Ana bilgisayarda **Yeni eşleştirme bağlantısı oluştur** öğesini seçin ve **aynı istemci tarayıcısında/profilinde** açın. Kaydedilmiş bir masaüstü sunucusu için, yeni eşleştirme bağlantısını kullanarak yeniden bağlanın, böylece mevcut uzak pencere depolama alanı yeniden kullanılabilir. +2. Ana bilgisayarda **Yeni eşleştirme bağlantısı oluştur** öğesini seçin ve **aynı istemci tarayıcısında/profilinde** açın. 3. Bekleme sayfasına dönün ve **Bağlantıyı kontrol et** öğesini seçin; sayfa yeniden odak kazandığında da kontrol tekrarlanır. Kurtarma, açık sayfayı ve taslakları korur; başarısız bir eylemi tekrarlamaz. Yeniden denemeden önce bir gönderme, yanıtlama veya silme işleminin etkili olup olmadığını kontrol edin. Doğrudan erişim parolası Uzaktan Kontrol eşleştirmesini kurtaramaz. diff --git a/docs/help/zh-Hans/projects.md b/docs/help/zh-Hans/projects.md index a286a8a94e..4800f8f95d 100644 --- a/docs/help/zh-Hans/projects.md +++ b/docs/help/zh-Hans/projects.md @@ -4,12 +4,14 @@ ## 打开项目 {#open-project} -1. 点击**新建实例**(`+`)打开空白的**新标签页**,焦点位于搜索框。它使用主页的背景、居中的 CodeNomad 标志和名称,以及大号的**克隆 Git 仓库**、**新建临时标签页**和**新建 SideCar**按钮。**最近 | 浏览**选择器附有条目数量,搜索框位于选择器下方的**最近**中。选择项目、已保存的服务器或 SideCar 会在原位置填充此标签页。空白标签页仅保留到重新加载,关闭后不留下项目。标题栏或标签栏中的 CodeNomad 标志打开主页,其中还提供设置、语言和心形**赞助**按钮([支持 CodeNomad](sponsor.md))。 +1. 点击**新建实例**(`+`)打开空白的**新标签页**,焦点位于搜索框。它使用主页的背景、居中的 CodeNomad 标志和名称,以及大号的**克隆 Git 仓库**、**新建临时标签页**和**新建 SideCar**按钮。**最近 | 浏览**选择器附有条目数量,搜索框位于选择器下方的**最近**中。选择本地或远程项目或 SideCar 会在原位置填充此标签页。空白标签页仅保留到重新加载,关闭后不留下项目。标题栏或标签栏中的 CodeNomad 标志打开主页,其中还提供设置、语言和心形**赞助**按钮([支持 CodeNomad](sponsor.md))。 2. 在 **最近** 中选择一个项目;或打开 **浏览**,选择 **此电脑**,然后选择后端文件夹并打开。**浏览** 也列出已保存的 CodeNomad 服务器([远程项目标签页](remote-access.md#remote-project-tabs))和 SideCar([SideCar](browser-sidecars.md#register-sidecar))。 3. 若需仓库副本,选择**克隆 Git 仓库**,输入**仓库 URL** 和**目标文件夹**,然后选择**克隆**。**目标文件夹** 会预填为上次克隆所在文件夹中以仓库名命名的文件夹(没有则为最近项目旁边)。**浏览** 用于选择存放克隆的文件夹;也可以手动编辑路径,包括克隆文件夹的名称。 浏览远程服务器意味着浏览该服务器的文件系统,而非你的手机或笔记本电脑。打开项目不会为每个标签页创建独立的 OpenCode 守护进程。对话是原生 OpenCode 会话;其生命周期不等于标签页的生命周期。 +在**浏览**中选择服务器后,列表会切换为该服务器的最近项目和文件夹。出现提示时通过内嵌表单登录,然后选择项目,或进入文件夹并点击**选择当前**。返回浏览会显示服务器列表。只有选择项目后才会填充空白标签页并关闭 `+` 启动器。远程标签页可能要求独立于浏览流程再次登录。 + 克隆会将仓库写入目标位置。**如果目标文件夹已存在,先将其删除。**具有破坏性:仅在其中所有现有内容都可以删除时启用。不确定时请使用新目标位置。克隆失败不是删除现有项目的理由;重试之前先检查报告的目标位置和错误。 最近条目只是快捷方式。**重命名工作区**更改显示名称;**从最近列表移除**仅移除快捷方式,不会删除文件或对话。点击已打开的最近项目会打开新标签页;其**已打开**按钮(**切换到已打开的项目**)则会选择现有标签页。 diff --git a/docs/help/zh-Hans/remote-access.md b/docs/help/zh-Hans/remote-access.md index 23a02ace50..c665123c91 100644 --- a/docs/help/zh-Hans/remote-access.md +++ b/docs/help/zh-Hans/remote-access.md @@ -83,23 +83,26 @@ codenomad --host 127.0.0.1 --https=false --http=true ## 保存远程服务器 {#saved-servers} -1. 在主页、空白标签页或**打开标签页**启动器中打开**浏览**,在**服务器地址或链接**中输入地址或配对链接。粘贴会立即添加,手动输入后按 Enter 添加。添加仅以主机名保存服务器并将焦点移到其行;启动器保持打开。点击该行才会打开服务器。**设置 → 服务器**也提供相同的输入框。 -2. 请使用受信任的 HTTPS 源。如果证书未通过检查,输入框下方会显示**跳过 TLS 验证**:仅对可信服务器勾选,再按 Enter 保存。选择这个已保存的服务器时,会在单独窗口打开。 -3. 在该服务器上登录。可在 **设置 → 服务器** 中通过 **编辑服务器** 重命名或更改其地址。 +1. 在主页、空白标签页或**打开标签页**启动器中打开**浏览**,在**服务器地址或链接**中输入地址或配对链接。粘贴会立即添加,手动输入后按 Enter 添加。添加仅以主机名保存服务器并将焦点移到其行;启动器保持打开。点击该行可在原位浏览项目。**设置 → 服务器**也提供相同的输入框。 +2. 请使用受信任的 HTTPS 源。如果证书未通过检查,输入框下方会显示**跳过 TLS 验证**:仅对可信服务器勾选,再按 Enter 保存。选择此配置的文件夹或项目后,会在单独窗口打开。 +3. 选择**浏览**中的已保存服务器行,即可在原位浏览项目。出现提示时,在内嵌表单中输入服务器用户名和密码。可在 **设置 → 服务器** 中通过 **编辑服务器** 更改名称或地址。 -已保存的服务器列在 **浏览** 中:选择一个即可再次打开。在 **设置 → 服务器** 中可以打开、编辑(**编辑服务器**:名称、地址、证书检查)和移除(**删除已保存服务器**)服务器。书签属于此 CodeNomad 配置,而非远程服务器项目。保存 URL 不会启动服务器或授予访问。**删除已保存服务器**移除书签,而非远程对话、后端或凭据。 +**设置 → 服务器**管理配置(**编辑服务器**、**删除已保存服务器**)。删除时先清除后端保存的浏览凭据和会话,再移除书签并关闭其标签页。远程项目和对话保留在服务器上。本地后端将浏览密钥保存在配置旁的 `remote-server-credentials.json` 中;请像保护密码一样保护此文件。嵌入视图的身份验证独立保存。 -要直接从命令行打开已保存的服务器,请使用服务器的保存名称或其 `https://` URL,以 `--connect-server `(或 `--connect-server=`)启动桌面应用。CodeNomad 只打开远程窗口,检查和登录与**浏览**相同;如果 CodeNomad 已在运行,则由其当前窗口打开,而不是新建窗口。未匹配任何已保存服务器的 URL 会以其主机名保存。启动值绝不携带凭据:包含用户名、密码或配对码的 URL 会被拒绝。如果名称未知、URL 无效或连接失败,CodeNomad 会正常启动并显示错误。 当连接需要确认(例如为自签名服务器安装本地证书)时,CodeNomad 同样会正常启动并在其中询问。 在 Windows 上,如果启动参数包含 `|`,Tauri 版本会拒绝启动;请改用服务器的 URL,或重命名该服务器。 +要直接从命令行打开已保存的服务器,请使用服务器的保存名称或其 `https://` URL,以 `--connect-server `(或 `--connect-server=`)启动桌面应用。CodeNomad 只打开远程窗口,使用配置的 TLS 检查和原生远程窗口自身的登录;如果 CodeNomad 已在运行,则由其当前窗口打开,而不是新建窗口。未匹配任何已保存服务器的 URL 会以其主机名保存。启动值绝不携带凭据:包含用户名、密码或配对码的 URL 会被拒绝。如果名称未知、URL 无效或连接失败,CodeNomad 会正常启动并显示错误。 当连接需要确认(例如为自签名服务器安装本地证书)时,CodeNomad 同样会正常启动并在其中询问。 在 Windows 上,如果启动参数包含 `|`,Tauri 版本会拒绝启动;请改用服务器的 URL,或重命名该服务器。 远程窗口始终保留返回本机的途径。在远程窗口仍打开时关闭最后一个本地窗口,会保留其标签页:在远程窗口中使用 **窗口 → 新建窗口**,或再次启动 CodeNomad,即可重新打开它。如果无法加载某个服务器,其窗口会说明情况,并提供 **重试**、**打开本地窗口** 和 **关闭窗口**;在 Tauri 版本中,请使用页面的重新加载按钮和 **窗口 → 新建窗口**。 -使用远程控制时,改为将新配对链接粘贴到**服务器地址或链接**。书签仅保留隧道来源,绝不保留一次性配对码;设备 cookie 丢失后的重新配对请参阅[远程控制](remote-control.md)。 +粘贴远程控制配对链接只会保存隧道来源,并提示服务器端配对不可用;配对码会被丢弃。请在目标浏览器中打开链接进行配对。参阅[远程控制](remote-control.md)。 ## 在标签页中打开远程项目 {#remote-project-tabs} 在桌面应用中(Electron,或 Windows 上的 Tauri),已保存的服务器也可以在此窗口的标签页中打开其某个项目,与本地项目并列: 1. 在主页、空白标签页或**打开标签页**启动器中打开**浏览**并选择已保存的服务器。若需先添加,使用**服务器地址或链接**,然后点击新增的行。 -2. 在标签页中选择文件夹。标签页随后显示服务器图标和项目名称,该项目也会加入 **最近**:在那里选择它会直接重新打开该服务器和文件夹。 +2. 列表在原位切换为该服务器的最近项目和文件夹。必要时通过内嵌表单登录。选择最近项目,或进入文件夹后点击**选择当前**。**返回浏览**会回到服务器列表。 +3. 选择文件夹后打开远程项目标签页,并替换原来的空白标签页。`+` 启动器在选择之前保持打开。项目会加入**最近**,便于直接重新打开。 -标签页只显示该项目;其对话、文件、Git、设置和 Missions 都在远程服务器上运行。它使用该服务器远程窗口的存储,因此会沿用已有的登录或已配对设备;CodeNomad 恢复标签页时,远程标签页也会恢复。没有此模式的服务器会在标签页中显示其完整界面。跳过 TLS 验证的服务器,以及 macOS 和 Linux 上的 Tauri 版本,仍然打开远程窗口。标签页中的页面可以显示通知,但对这台计算机没有其他访问权限,并始终停留在其服务器上。Web 客户端和 Remote Control 设备没有远程标签页。**设置 → 服务器** 中的 **删除已保存服务器** 也会关闭它的标签页。选择项目之前,标签页显示服务器名称。请在标签页中的服务器页面登录;CodeNomad 会在之后的启动中继续使用该登录。 +标签页的对话、文件、Git、设置和 Missions 在远程服务器上运行。嵌入视图共享该服务器远程窗口的存储,可能要求独立于浏览流程再次登录。远程标签页参与启动恢复。没有嵌入模式的服务器显示完整界面;跳过 TLS 验证的配置及 macOS/Linux 上的 Tauri 会打开单独窗口。嵌入页面始终停留在其服务器上,对本机仅有通知权限。Web 客户端和远程控制设备没有远程标签页。 + +后端浏览使用带有地址保护的 CodeNomad 直接访问:CGNAT/Tailscale IP 字面量及特殊用途地址范围会被拒绝。请检查实际目标,不要假定所有 VPN 地址均可使用。证书验证遵循已保存配置及其明确的 TLS 确认。 diff --git a/docs/help/zh-Hans/remote-control.md b/docs/help/zh-Hans/remote-control.md index 20d7589c3f..8c201a9fce 100644 --- a/docs/help/zh-Hans/remote-control.md +++ b/docs/help/zh-Hans/remote-control.md @@ -11,7 +11,7 @@ 链接有效期为**五分钟**,只能成功使用**一次**。请将其视为凭据:任何消费它的人都能成为配对设备。配对码位于 URL 片段,而非查询字符串。**创建新的配对链接**会立即使上一个未使用链接失效。停止、后端关闭和隧道失败会取消未使用的配对链接。 -要配对另一个桌面 CodeNomad,在主页或空白标签页打开**浏览**,将链接粘贴到**服务器地址或链接**中。此操作仅添加服务器;点击保存的行才会打开并配对。一次性链接在此窗口的内存中等待,直到打开或重新加载;请在五分钟有效期内使用。书签仅保存隧道来源。配对链接始终启用 TLS 验证。 +请在目标浏览器中打开配对链接。在桌面端的**服务器地址或链接**中粘贴链接只会保存隧道来源,并提示服务器端配对不可用。配对码会被丢弃。后端文件夹浏览使用独立的直接访问会话;嵌入视图独立保留其登录或设备 cookie。 ## 管理配对设备 {#paired-devices} @@ -28,7 +28,7 @@ ### 不丢失当前位置地重新配对 {#re-pair} 1. 如果客户端显示**重新配对此设备**,请保持该页面打开。 -2. 在主机选择**创建新的配对链接**,在**同一客户端浏览器/配置文件**中打开。对于已保存的桌面服务器,使用新配对链接重新连接,以复用其现有远程窗口存储。 +2. 在主机选择**创建新的配对链接**,在**同一客户端浏览器/配置文件**中打开。 3. 返回等待页面并选择**检查连接**;页面重新获得焦点时也会再次检查。 恢复会保留打开页面和草稿;不会重放失败操作。重试发送、回答或删除之前,请检查是否已生效。直接访问密码无法恢复远程控制配对。 From 68fb38ea812a059e332da6ab9d83b8ce3d65dc6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 6 Nov 2026 03:35:24 +0100 Subject: [PATCH 22/34] fix(remote): permit every saved server destination address A saved server is an explicit destination chosen by this computer's user. Remove special-address range filters that prevented Tailscale/CGNAT, LAN, container, VM and IPv6 link-local connections. Preserve IP syntax checking and DNS pinning, the local caller guard, profile certificate policy, origin-bound private credentials, and refusal to follow redirects. No upstream Origin is synthesized. Test former excluded ranges, MagicDNS answers, ULA and scoped link-local answers, and authenticated fake-server requests through a pinned MagicDNS resolver. Update the address-policy documentation in all ten help languages. Server typecheck and 38 targeted tests pass; the complete serial server suite without forced exit passes 3695 tests with 21 platform skips. Baseline 6364e29b1 reproduces all four previous failure signatures: three Windows libuv shutdown assertions with forced exit, and the Git observation deadline under concurrent load. No introduced shared state or fixed-port contention found. Help passes 31 tests and the offline Tauri no-bundle build succeeds. --- dev-docs/architecture.md | 2 +- docs/help/de/remote-access.md | 2 +- docs/help/en/remote-access.md | 2 +- docs/help/es/remote-access.md | 2 +- docs/help/fr/remote-access.md | 2 +- docs/help/he/remote-access.md | 2 +- docs/help/ja/remote-access.md | 2 +- docs/help/ne/remote-access.md | 2 +- docs/help/ru/remote-access.md | 2 +- docs/help/tr/remote-access.md | 2 +- docs/help/zh-Hans/remote-access.md | 2 +- .../src/codenomad-servers/browse-manager.ts | 2 +- .../src/codenomad-servers/browse.test.ts | 4 +- .../server/src/codenomad-servers/client.ts | 2 +- .../codenomad-servers/saved-addresses.test.ts | 57 +++++++++++++++++++ .../server/src/opencode/servers/endpoint.ts | 5 +- .../server/src/opencode/servers/origin.ts | 50 +++------------- .../server/src/opencode/servers/transport.ts | 6 +- 18 files changed, 84 insertions(+), 64 deletions(-) create mode 100644 packages/server/src/codenomad-servers/saved-addresses.test.ts diff --git a/dev-docs/architecture.md b/dev-docs/architecture.md index 97a05a60fb..26df389e5c 100644 --- a/dev-docs/architecture.md +++ b/dev-docs/architecture.md @@ -63,7 +63,7 @@ Yolo state endpoints live at `/workspaces/:id/yolo/sessions/:sessionId`; Yolo no ## Client And Events -Remote Browse obtains remote recent projects and folders through a backend-held direct CodeNomad session. The UI switches its Browse list in place, requests username/password inline when needed, and opens a remote tab only after a folder is selected. An expired session is reauthenticated once. All upstream remote-server requests omit `Origin`; target validation rejects CGNAT/Tailscale IP literals and special-use address ranges. TLS verification follows the saved profile and its existing explicit opt-out confirmation. Embedded native views retain their own authentication and remote-window storage independently of backend browsing. Remote Control pairing through backend connect returns `pairing_unavailable`; the profile retains only the tunnel origin and the code is discarded ([REMOTE_CONTROL.md](REMOTE_CONTROL.md)). +Remote Browse obtains remote recent projects and folders through a backend-held direct CodeNomad session. The UI switches its Browse list in place, requests username/password inline when needed, and opens a remote tab only after a folder is selected. An expired session is reauthenticated once. Saving a profile authorizes its destination address: eligible targets include loopback, RFC1918 LAN, Docker, Hyper-V, CGNAT/Tailscale (`100.64.0.0/10`), MagicDNS and `*.ts.net`, IPv6 ULA/link-local, and names resolving to these addresses. Connections require working network routes and TLS; verification follows the saved profile and its existing explicit opt-out confirmation. Browsing credentials remain private to the backend. All upstream remote-server requests omit `Origin`; never forge it or forward credentials through redirects or to a foreign origin. Embedded native views retain their own authentication and remote-window storage independently of backend browsing. Remote Control pairing through backend connect returns `pairing_unavailable`; the profile retains only the tunnel origin and the code is discarded ([REMOTE_CONTROL.md](REMOTE_CONTROL.md)). `packages/ui/src/lib/sdk-manager.ts` uses `OpenCode.make()` and caches generated Promise clients by instance proxy path. `packages/ui/src/stores/opencode-client.ts` is the root-client authority; native directory/location fields select the worktree. diff --git a/docs/help/de/remote-access.md b/docs/help/de/remote-access.md index 6b7c64e892..6391551b03 100644 --- a/docs/help/de/remote-access.md +++ b/docs/help/de/remote-access.md @@ -105,4 +105,4 @@ In der Desktop-App (Electron oder Tauri unter Windows) kann ein gespeicherter Se Unterhaltungen, Dateien, Git, Einstellungen und Missions des Tabs laufen auf dem Remote-Server. Seine eingebettete Ansicht teilt den Speicher des Remote-Fensters und kann eine eigene Anmeldung unabhängig von Durchsuchen verlangen. Remote-Tabs werden beim Start wiederhergestellt. Server ohne eingebetteten Modus zeigen ihre vollständige Oberfläche; Profile ohne TLS-Prüfung und Tauri unter macOS/Linux öffnen ein separates Fenster. Die eingebettete Seite bleibt auf ihrem Server und hat nur Benachrichtigungszugriff auf den Host. Webclients und Fernsteuerungsgeräte haben keine Remote-Tabs. -Die Backend-Suche nutzt direkten CodeNomad-Zugriff mit Adressschutz: CGNAT-/Tailscale-IP-Literale und spezielle Adressbereiche werden abgelehnt. Prüfen Sie Ihr konkretes Ziel, statt jede VPN-Adresse als unterstützt anzusehen. Die Zertifikatsprüfung folgt dem gespeicherten Profil und seiner ausdrücklichen TLS-Bestätigung. +Die Backend-Suche akzeptiert die Zieladresse jedes gespeicherten Profils, einschließlich Loopback, RFC1918-LAN, Docker, Hyper-V, CGNAT/Tailscale (`100.64.0.0/10`), MagicDNS und `*.ts.net`, IPv6-ULA/Link-Local sowie Namen, die zu diesen Adressen aufgelöst werden. Ihre Netzwerkrouten und TLS-Konfiguration müssen die Verbindung ermöglichen. Die Zertifikatsprüfung folgt dem gespeicherten Profil und seiner ausdrücklichen TLS-Bestätigung. diff --git a/docs/help/en/remote-access.md b/docs/help/en/remote-access.md index d60632fa09..9c6cd69c96 100644 --- a/docs/help/en/remote-access.md +++ b/docs/help/en/remote-access.md @@ -105,4 +105,4 @@ In the desktop app (Electron, or Tauri on Windows), a saved server can also open The tab's conversations, files, Git, settings and Missions run on the remote server. Its embedded view shares that server's remote-window storage and may ask you to sign in separately from Browse. Remote tabs participate in startup restoration. Servers without embedded mode show their full interface; profiles that skip TLS verification and Tauri on macOS/Linux open a separate remote window. The embedded page stays on its server and has only notification access to the host. Web clients and Remote Control devices have no remote tabs. -Backend browsing supports direct CodeNomad access subject to address safeguards: CGNAT/Tailscale IP literals and special-use address ranges are rejected. Check your actual destination rather than assuming every VPN address works. Certificate verification follows the saved profile and its explicit TLS confirmation. +Backend browsing accepts every saved profile's destination address, including loopback, RFC1918 LAN, Docker, Hyper-V, CGNAT/Tailscale (`100.64.0.0/10`), MagicDNS and `*.ts.net`, IPv6 ULA/link-local, and names resolving to these addresses. Your network routes and TLS setup must allow the connection. Certificate verification follows the saved profile and its explicit TLS confirmation. diff --git a/docs/help/es/remote-access.md b/docs/help/es/remote-access.md index c864042773..394ffdf9f9 100644 --- a/docs/help/es/remote-access.md +++ b/docs/help/es/remote-access.md @@ -105,4 +105,4 @@ En la aplicación de escritorio (Electron, o Tauri en Windows), un servidor guar Las conversaciones, archivos, Git, ajustes y Missions de la pestaña se ejecutan en el servidor remoto. Su vista integrada comparte el almacenamiento de la ventana remota y puede pedir otro inicio de sesión independiente de Explorar. Las pestañas remotas participan en la restauración al iniciar. Los servidores sin modo integrado muestran su interfaz completa; los perfiles que omiten TLS y Tauri en macOS/Linux abren otra ventana. La página integrada permanece en su servidor y solo dispone de notificaciones en el anfitrión. Los clientes web y dispositivos de Control remoto carecen de pestañas remotas. -La exploración del backend utiliza acceso directo a CodeNomad con protecciones de direcciones: rechaza IP literales CGNAT/Tailscale y rangos especiales. Comprueba el destino real sin asumir que cualquier dirección VPN funciona. La verificación del certificado sigue el perfil guardado y su confirmación TLS explícita. +La exploración del backend acepta la dirección de destino de cada perfil guardado, incluidas las de bucle local, LAN RFC1918, Docker, Hyper-V, CGNAT/Tailscale (`100.64.0.0/10`), MagicDNS y `*.ts.net`, IPv6 ULA/link-local y los nombres que se resuelvan a estas direcciones. Las rutas de red y la configuración TLS deben permitir la conexión. La verificación del certificado sigue el perfil guardado y su confirmación TLS explícita. diff --git a/docs/help/fr/remote-access.md b/docs/help/fr/remote-access.md index 5a9328dbc4..9c365fecd5 100644 --- a/docs/help/fr/remote-access.md +++ b/docs/help/fr/remote-access.md @@ -105,4 +105,4 @@ Dans l'application de bureau (Electron, ou Tauri sous Windows), un serveur enreg Les conversations, fichiers, Git, paramètres et Missions de l’onglet s’exécutent sur le serveur distant. Sa vue intégrée partage le stockage de la fenêtre distante de ce serveur et peut demander une connexion distincte de Parcourir. Les onglets distants participent à la restauration au démarrage. Les serveurs sans mode intégré affichent leur interface complète ; les profils ignorant TLS et Tauri sous macOS/Linux ouvrent une fenêtre distincte. La page intégrée reste sur son serveur et dispose seulement des notifications sur l’hôte. Les clients web et appareils du Contrôle à distance n’ont pas d’onglets distants. -Le parcours par le backend utilise l’accès direct CodeNomad avec des protections d’adresse : les IP littérales CGNAT/Tailscale et les plages spéciales sont refusées. Vérifiez votre destination sans supposer que toute adresse VPN fonctionne. La vérification des certificats suit le profil enregistré et sa confirmation TLS explicite. +Le parcours par le backend accepte l’adresse de destination de chaque profil enregistré, y compris le bouclage, les réseaux locaux RFC1918, Docker, Hyper-V, CGNAT/Tailscale (`100.64.0.0/10`), MagicDNS et `*.ts.net`, les adresses IPv6 ULA/link-local et les noms résolus vers ces adresses. Vos routes réseau et votre configuration TLS doivent permettre la connexion. La vérification des certificats suit le profil enregistré et sa confirmation TLS explicite. diff --git a/docs/help/he/remote-access.md b/docs/help/he/remote-access.md index 2555f1e4ea..22a144fc0e 100644 --- a/docs/help/he/remote-access.md +++ b/docs/help/he/remote-access.md @@ -105,4 +105,4 @@ codenomad --host 127.0.0.1 --https=false --http=true השיחות, הקבצים, Git, ההגדרות ו־Missions בלשונית פועלים בשרת המרוחק. התצוגה המוטמעת חולקת את אחסון החלון המרוחק שלו ועשויה לדרוש התחברות נפרדת מעיון. לשוניות מרוחקות משתתפות בשחזור בהפעלה. שרתים ללא מצב מוטמע מציגים את הממשק המלא; פרופילים שמדלגים על TLS ו־Tauri ב־macOS/Linux פותחים חלון נפרד. הדף המוטמע נשאר בשרת שלו ויכול רק לשלוח התראות למארח. ללקוחות דפדפן ולמכשירי שליטה מרחוק אין לשוניות מרוחקות. -העיון דרך שרת הקצה משתמש בגישה ישירה ל־CodeNomad עם הגנות כתובת: כתובות IP מילוליות של CGNAT/Tailscale וטווחים מיוחדים נדחים. בדקו את היעד בפועל במקום להניח שכל כתובת VPN נתמכת. בדיקת התעודה פועלת לפי הפרופיל השמור ואישור ה־TLS המפורש שלו. +העיון דרך שרת הקצה מקבל את כתובת היעד של כל פרופיל שמור, כולל loopback, רשתות LAN מסוג RFC1918, Docker, Hyper-V, CGNAT/Tailscale (`100.64.0.0/10`), MagicDNS ו־`*.ts.net`, כתובות IPv6 ULA/link-local ושמות שמתורגמים לכתובות אלה. נתיבי הרשת והגדרות ה־TLS שלכם חייבים לאפשר את החיבור. בדיקת התעודה פועלת לפי הפרופיל השמור ואישור ה־TLS המפורש שלו. diff --git a/docs/help/ja/remote-access.md b/docs/help/ja/remote-access.md index f1c64a9bf4..a17bce8f47 100644 --- a/docs/help/ja/remote-access.md +++ b/docs/help/ja/remote-access.md @@ -105,4 +105,4 @@ HTTPS が有効で鍵/証明書のペアを指定していない場合、CodeN タブの会話、ファイル、Git、設定、Missions はリモートサーバーで動作します。埋め込みビューはそのサーバーのリモートウィンドウのストレージを共有し、参照とは別にサインインを求める場合があります。リモートタブは起動時に復元されます。埋め込みモードのないサーバーは完全な UI を表示し、TLS 検証を省略するプロファイルと macOS/Linux の Tauri は別ウィンドウを開きます。埋め込みページはサーバー内に留まり、ホストへは通知のみ送れます。Web クライアントとリモートコントロール端末にはリモートタブはありません。 -バックエンド参照はアドレス保護付きの CodeNomad 直接アクセスを使い、CGNAT/Tailscale の IP リテラルと特殊用途の範囲を拒否します。すべての VPN アドレスが使えると考えず、実際の接続先を確認してください。証明書検証は保存したプロファイルと明示的な TLS 確認に従います。 +バックエンド参照は、保存したすべてのプロファイルの接続先アドレスを受け付けます。対象にはループバック、RFC1918 LAN、Docker、Hyper-V、CGNAT/Tailscale(`100.64.0.0/10`)、MagicDNS と `*.ts.net`、IPv6 ULA/リンクローカル、およびこれらのアドレスに解決される名前が含まれます。接続には、ネットワーク経路と TLS 設定が適切に機能する必要があります。証明書検証は保存したプロファイルと明示的な TLS 確認に従います。 diff --git a/docs/help/ne/remote-access.md b/docs/help/ne/remote-access.md index 7778952619..c63c244896 100644 --- a/docs/help/ne/remote-access.md +++ b/docs/help/ne/remote-access.md @@ -105,4 +105,4 @@ Remote Control link टाँस्दा tunnel origin मात्र बच ट्याबका कुराकानी, फाइल, Git, सेटिङ र Missions remote server मा चल्छन्। Embedded view ले सर्भरको remote-window storage साझा गर्छ र Browse भन्दा छुट्टै sign-in माग्न सक्छ। Remote ट्याब startup restoration मा फर्कन्छन्। Embedded mode नभएका सर्भरले पूर्ण UI देखाउँछन्; TLS verification छोड्ने profile र macOS/Linux को Tauri ले छुट्टै window खोल्छन्। Embedded page सर्भरमै रहन्छ र host मा notification मात्र दिन सक्छ। Web client र Remote Control device मा remote ट्याब हुँदैनन्। -Backend browsing ले address सुरक्षा सहित direct CodeNomad access प्रयोग गर्छ: CGNAT/Tailscale IP literal र विशेष address range अस्वीकार हुन्छन्। सबै VPN address चल्छन् भन्ने नमान्नुहोस्; वास्तविक destination जाँच्नुहोस्। Certificate verification बचत गरिएको profile र स्पष्ट TLS confirmation अनुसार हुन्छ। +Backend browsing ले प्रत्येक बचत गरिएको profile को destination address स्वीकार गर्छ, जसमा loopback, RFC1918 LAN, Docker, Hyper-V, CGNAT/Tailscale (`100.64.0.0/10`), MagicDNS र `*.ts.net`, IPv6 ULA/link-local र यी address मा resolve हुने नामहरू पर्छन्। तपाईंको network route र TLS setup ले connection सम्भव बनाउनुपर्छ। Certificate verification बचत गरिएको profile र स्पष्ट TLS confirmation अनुसार हुन्छ। diff --git a/docs/help/ru/remote-access.md b/docs/help/ru/remote-access.md index c3b6a40071..868e7a9406 100644 --- a/docs/help/ru/remote-access.md +++ b/docs/help/ru/remote-access.md @@ -105,4 +105,4 @@ codenomad --host 127.0.0.1 --https=false --http=true Беседы, файлы, Git, настройки и Missions вкладки работают на удалённом сервере. Встроенное представление использует хранилище удалённого окна и может запросить отдельный вход независимо от Обзора. Удалённые вкладки восстанавливаются при запуске. Серверы без встроенного режима показывают полный интерфейс; профили без проверки TLS и Tauri в macOS/Linux открывают отдельное окно. Встроенная страница остаётся на своём сервере и имеет только доступ к уведомлениям хоста. У веб-клиентов и устройств удалённого управления нет удалённых вкладок. -Просмотр через серверную часть использует прямой доступ CodeNomad с защитой адресов: IP-литералы CGNAT/Tailscale и специальные диапазоны отклоняются. Проверяйте конкретный адрес, не предполагая поддержку любого VPN. Проверка сертификата следует сохранённому профилю и его явному подтверждению TLS. +Просмотр через серверную часть принимает адрес назначения каждого сохранённого профиля, включая loopback, локальные сети RFC1918, Docker, Hyper-V, CGNAT/Tailscale (`100.64.0.0/10`), MagicDNS и `*.ts.net`, IPv6 ULA/link-local и имена, разрешающиеся в эти адреса. Сетевые маршруты и настройки TLS должны обеспечивать подключение. Проверка сертификата следует сохранённому профилю и его явному подтверждению TLS. diff --git a/docs/help/tr/remote-access.md b/docs/help/tr/remote-access.md index a60197c85c..65b0f10ae2 100644 --- a/docs/help/tr/remote-access.md +++ b/docs/help/tr/remote-access.md @@ -105,4 +105,4 @@ Masaüstü uygulamasında (Electron veya Windows'ta Tauri), kayıtlı bir sunucu Sekmenin konuşmaları, dosyaları, Git'i, ayarları ve Missions uzak sunucuda çalışır. Gömülü görünüm sunucunun uzak pencere depolamasını paylaşır ve Gözat'tan bağımsız oturum açmanızı isteyebilir. Uzak sekmeler başlangıçta geri yüklenir. Gömülü modu olmayan sunucular tam arayüzü gösterir; TLS doğrulamasını atlayan profiller ve macOS/Linux'ta Tauri ayrı pencere açar. Gömülü sayfa kendi sunucusunda kalır ve ana bilgisayarda yalnızca bildirim erişimine sahiptir. Web istemcilerinde ve Uzaktan Kontrol cihazlarında uzak sekme yoktur. -Arka uç taraması adres korumalı doğrudan CodeNomad erişimini kullanır: CGNAT/Tailscale IP sabitleri ve özel adres aralıkları reddedilir. Her VPN adresinin çalışacağını varsaymak yerine gerçek hedefi denetleyin. Sertifika doğrulaması kayıtlı profili ve açık TLS onayını izler. +Arka uç taraması, geri döngü, RFC1918 LAN, Docker, Hyper-V, CGNAT/Tailscale (`100.64.0.0/10`), MagicDNS ve `*.ts.net`, IPv6 ULA/link-local ve bu adreslere çözümlenen adlar dahil her kayıtlı profilin hedef adresini kabul eder. Ağ rotalarınız ve TLS yapılandırmanız bağlantıya izin vermelidir. Sertifika doğrulaması kayıtlı profili ve açık TLS onayını izler. diff --git a/docs/help/zh-Hans/remote-access.md b/docs/help/zh-Hans/remote-access.md index c665123c91..7d8f2d6e71 100644 --- a/docs/help/zh-Hans/remote-access.md +++ b/docs/help/zh-Hans/remote-access.md @@ -105,4 +105,4 @@ codenomad --host 127.0.0.1 --https=false --http=true 标签页的对话、文件、Git、设置和 Missions 在远程服务器上运行。嵌入视图共享该服务器远程窗口的存储,可能要求独立于浏览流程再次登录。远程标签页参与启动恢复。没有嵌入模式的服务器显示完整界面;跳过 TLS 验证的配置及 macOS/Linux 上的 Tauri 会打开单独窗口。嵌入页面始终停留在其服务器上,对本机仅有通知权限。Web 客户端和远程控制设备没有远程标签页。 -后端浏览使用带有地址保护的 CodeNomad 直接访问:CGNAT/Tailscale IP 字面量及特殊用途地址范围会被拒绝。请检查实际目标,不要假定所有 VPN 地址均可使用。证书验证遵循已保存配置及其明确的 TLS 确认。 +后端浏览接受每个已保存配置的目标地址,包括环回地址、RFC1918 局域网、Docker、Hyper-V、CGNAT/Tailscale(`100.64.0.0/10`)、MagicDNS 和 `*.ts.net`、IPv6 ULA/链路本地地址,以及解析到这些地址的名称。网络路由和 TLS 配置必须能够支持连接。证书验证遵循已保存配置及其明确的 TLS 确认。 diff --git a/packages/server/src/codenomad-servers/browse-manager.ts b/packages/server/src/codenomad-servers/browse-manager.ts index 17c04bd265..3201a3d585 100644 --- a/packages/server/src/codenomad-servers/browse-manager.ts +++ b/packages/server/src/codenomad-servers/browse-manager.ts @@ -31,7 +31,7 @@ export class RemoteServerBrowseManager { const values = this.settings.getOwner("state", "ui").remoteServers const profile = Array.isArray(values) ? values.map(value => Profile.safeParse(value)).find(value => value.success && value.data.id === id) : undefined if (!profile?.success) { this.remove(id); throw new CodeNomadServerError("unknown_server") } - const origin = normalizeExplicitOrigin(profile.data.baseUrl, true) + const origin = normalizeExplicitOrigin(profile.data.baseUrl) return { ...profile.data, origin, key: `${origin}|${profile.data.skipTlsVerify}` } } diff --git a/packages/server/src/codenomad-servers/browse.test.ts b/packages/server/src/codenomad-servers/browse.test.ts index 32a32bf476..6cf7805137 100644 --- a/packages/server/src/codenomad-servers/browse.test.ts +++ b/packages/server/src/codenomad-servers/browse.test.ts @@ -125,7 +125,7 @@ test("revoked password retries once and clears private identity; profiles are re f.profiles[0]!.baseUrl = `${f.remote.origin}/api/auth/login` assert.deepEqual((await f.call("browse")).json(), { error: "unreachable" }) assert.equal(f.remote.state.requests.length, before) - assert.equal(normalizeExplicitOrigin("http://192.168.1.25:8080", true), "http://192.168.1.25:8080") + assert.equal(normalizeExplicitOrigin("http://192.168.1.25:8080"), "http://192.168.1.25:8080") }) test("anonymous direct servers need no secrets; removed and changed profiles cannot reuse credentials", async t => { @@ -210,7 +210,7 @@ test("transport strips Origin, caller cookies and response cookies, and fences e t.after(() => other.close()) const captured: string[] = [] remote.state.overrides.set("/api/auth/status", { status: 200, body: { authenticated: true }, headers: { "set-cookie": "private-session=value; Domain=foreign.test; Path=/" } }) - const transport = createExplicitTransport({ origin: remote.origin, allowHttp: true, + const transport = createExplicitTransport({ origin: remote.origin, headers: () => ({ Origin: remote.origin, cookie: "private-cookie=value" }), onSetCookie: values => captured.push(...values) }) const response = await transport.fetch(`${remote.origin}/api/auth/status`, { headers: { origin: "http://foreign.test", cookie: "caller-cookie=value" } }) assert.equal(response.headers.get("set-cookie"), null) diff --git a/packages/server/src/codenomad-servers/client.ts b/packages/server/src/codenomad-servers/client.ts index 0825266607..fd4474be5a 100644 --- a/packages/server/src/codenomad-servers/client.ts +++ b/packages/server/src/codenomad-servers/client.ts @@ -50,7 +50,7 @@ export class CodeNomadServerClient { if (secret?.cookie) for (const [name, value] of cookiePairs([secret.cookie])) this.#cookies.set(name, value) this.#transport = createExplicitTransport({ origin, signal: this.#controller.signal, - allowHttp: true, skipTlsVerify: options.skipTlsVerify, + skipTlsVerify: options.skipTlsVerify, headers: (): Record => (this.#cookies.size ? { cookie: [...this.#cookies].map(([name, value]) => `${name}=${value}`).join("; ") } : {}), onSetCookie: values => this.capture(values), }, options.resolve) diff --git a/packages/server/src/codenomad-servers/saved-addresses.test.ts b/packages/server/src/codenomad-servers/saved-addresses.test.ts new file mode 100644 index 0000000000..e41f36163b --- /dev/null +++ b/packages/server/src/codenomad-servers/saved-addresses.test.ts @@ -0,0 +1,57 @@ +import assert from "node:assert/strict" +import { isIP } from "node:net" +import { test } from "node:test" +import { normalizeExplicitOrigin, resolveExplicitAddress } from "../opencode/servers/endpoint" +import { CodeNomadServerClient } from "./client" +import { startFakeCodeNomad } from "./test-support/fake-codenomad" + +const addresses = [ + "127.0.0.1", "10.0.0.1", "172.17.0.2", "192.168.1.2", + "100.64.0.1", "100.127.255.254", "169.254.10.20", "168.63.129.16", + "0.1.2.3", "224.0.0.1", "240.0.0.1", + "::1", "fd7a:115c:a1e0::1", "fc00::1", "fe80::1234", "fec0::1", + "fd00:ec2::254", "2002:a00:1::1", "2001::1", "ff02::1", "::", + "::ffff:100.64.0.1", "::ffff:169.254.1.2", +] + +test("saved profile literals and MagicDNS answers accept every IP range", async () => { + for (const address of addresses) { + const literal = `http://${isIP(address) === 6 ? `[${address}]` : address}:8080` + assert.equal(normalizeExplicitOrigin(literal), new URL(literal).origin, address) + const resolved = await resolveExplicitAddress(literal) + assert.equal(resolved.address, new URL(literal).hostname.replace(/^\[|\]$/g, ""), address) + const dns = await resolveExplicitAddress("http://vm.example.ts.net:8080", async hostname => { + assert.equal(hostname, "vm.example.ts.net") + return [{ address, family: isIP(address) }] + }) + assert.equal(dns.address, address) + assert.equal(dns.family, isIP(address)) + } + const scoped = await resolveExplicitAddress("http://link-local.example:8080", async () => [{ address: "fe80::1%12", family: 6 }]) + assert.equal(scoped.address, "fe80::1%12", "the resolver's link-local interface scope is preserved") + await assert.rejects(resolveExplicitAddress("http://vm.example.ts.net", async () => [{ address: "not-an-ip", family: 4 }]), { code: "dns" }) +}) + +test("a MagicDNS saved origin authenticates and lists the real fake server through its pinned resolver", async t => { + const remote = await startFakeCodeNomad() + t.after(() => remote.close()) + const origin = `http://vm.example.ts.net:${new URL(remote.origin).port}` + let lookups = 0 + const client = new CodeNomadServerClient(origin, { kind: "password", username: "codenomad", password: "remote-password" }, { + resolve: async hostname => { + assert.equal(hostname, "vm.example.ts.net") + lookups++ + return [{ address: "127.0.0.1", family: 4 }] + }, + }) + t.after(() => client.close()) + const response = await client.json<{ entries: unknown[] }>("/api/filesystem") + assert.equal(response.status, 200) + assert.ok(response.body!.entries.length > 0) + assert.equal(remote.state.logins, 1) + assert.equal(lookups, remote.state.requests.length) + for (const request of remote.state.requests) { + assert.equal(request.headers.host, new URL(origin).host) + assert.equal(request.headers.origin, undefined) + } +}) diff --git a/packages/server/src/opencode/servers/endpoint.ts b/packages/server/src/opencode/servers/endpoint.ts index e4d8940f95..1cee68a274 100644 --- a/packages/server/src/opencode/servers/endpoint.ts +++ b/packages/server/src/opencode/servers/endpoint.ts @@ -8,14 +8,13 @@ export type ResolveAddresses = (hostname: string) => Promise lookup(hostname, { all: true, verbatim: true }) /** Validate every answer and return the exact address the dialer must use. */ -export async function resolveExplicitAddress(origin: string, resolve: ResolveAddresses = resolveAddresses, allowHttp = false) { - const url = new URL(normalizeExplicitOrigin(origin, allowHttp)) +export async function resolveExplicitAddress(origin: string, resolve: ResolveAddresses = resolveAddresses) { + const url = new URL(normalizeExplicitOrigin(origin)) const hostname = url.hostname.replace(/^\[|\]$/g, "") let answers: readonly { address: string; family: number }[] try { answers = isIP(hostname) ? [{ address: hostname, family: isIP(hostname) }] : await resolve(hostname) } catch { throw new ExplicitEndpointError("dns") } if (!answers.length) throw new ExplicitEndpointError("dns") const admitted = answers.map(answer => admitAddress(answer.address)) - if (!allowHttp && url.protocol === "http:" && admitted.some(answer => !answer.loopback)) throw new ExplicitEndpointError("https_required") return admitted[0]! } diff --git a/packages/server/src/opencode/servers/origin.ts b/packages/server/src/opencode/servers/origin.ts index f60b5aec00..391345a84e 100644 --- a/packages/server/src/opencode/servers/origin.ts +++ b/packages/server/src/opencode/servers/origin.ts @@ -1,49 +1,21 @@ import { isIP } from "node:net" -export type EndpointErrorCode = "invalid_origin" | "forbidden_address" | "https_required" | "dns" | "network" | "tls" | "redirect" | "timeout" | "response_limit" | "probe_path" | "custom_ca_unsupported" +export type EndpointErrorCode = "invalid_origin" | "dns" | "network" | "tls" | "redirect" | "timeout" | "response_limit" | "probe_path" | "custom_ca_unsupported" /** Diagnostics contain only a stable code, never a URL, credential or upstream error. */ export class ExplicitEndpointError extends Error { constructor(readonly code: EndpointErrorCode) { super(code); this.name = "ExplicitEndpointError" } } -function ipv4(address: string): number[] | undefined { - if (isIP(address) === 4) return address.split(".").map(Number) - if (isIP(address) !== 6) return - const parts = address.split("::") - const left = parts[0] ? parts[0].split(":") : [] - const right = parts[1] ? parts[1].split(":") : [] - const words = [...left, ...Array(8 - left.length - right.length).fill("0"), ...right].map(word => parseInt(word, 16)) - if (words.slice(0, 5).every(word => word === 0) && words[5] === 0xffff) { - return [words[6]! >> 8, words[6]! & 255, words[7]! >> 8, words[7]! & 255] - } -} - -export function admitAddress(input: string): { address: string; family: 4 | 6; loopback: boolean } { - if (!isIP(input)) throw new ExplicitEndpointError("forbidden_address") - const address = isIP(input) === 6 ? new URL(`http://[${input}]/`).hostname.slice(1, -1) : input - const v4 = ipv4(address) - let loopback = false - if (v4) { - const [a, b, c, d] = v4 as [number, number, number, number] - loopback = a === 127 - if (a === 0 || a >= 224 || (a === 169 && b === 254) - || (a === 100 && b >= 64 && b <= 127) - || (a === 168 && b === 63 && c === 129 && d === 16)) throw new ExplicitEndpointError("forbidden_address") - } else { - loopback = address === "::1" - // Global unicast and private ULA only; transition/link-local/site-local ranges fail closed. - const first = parseInt(address.split(":")[0]!, 16) - if (!loopback && !((first >= 0x2000 && first <= 0x3fff) || (first >= 0xfc00 && first <= 0xfdff))) { - throw new ExplicitEndpointError("forbidden_address") - } - if (address === "fd00:ec2::254" || address.startsWith("2002:") || address.startsWith("2001:0:") || address.startsWith("2001::")) throw new ExplicitEndpointError("forbidden_address") - } - return { address, family: isIP(address) as 4 | 6, loopback } +/** A saved profile chooses its destination; only the resolver's IP syntax is checked here. */ +export function admitAddress(address: string): { address: string; family: 4 | 6 } { + const family = isIP(address) + if (!family) throw new ExplicitEndpointError("dns") + return { address, family: family as 4 | 6 } } /** Synchronous origin validation shared by registry metadata and network admission. */ -export function normalizeExplicitOrigin(value: string, allowHttp = false): string { +export function normalizeExplicitOrigin(value: string): string { let url: URL try { // Inspect the supplied syntax before WHATWG normalization can erase dot paths or empty delimiters. @@ -52,12 +24,6 @@ export function normalizeExplicitOrigin(value: string, allowHttp = false): strin if (url.username || url.password || value.includes("@") || url.pathname !== "/" || url.search || url.hash) throw new Error() } catch { throw new ExplicitEndpointError("invalid_origin") } const hostname = url.hostname.replace(/^\[|\]$/g, "") - if (isIP(hostname)) { - const admitted = admitAddress(hostname) - if (!allowHttp && url.protocol === "http:" && !admitted.loopback) throw new ExplicitEndpointError("https_required") - } else { - if (hostname === "*" || hostname.includes("*") || !hostname) throw new ExplicitEndpointError("invalid_origin") - if (!allowHttp && url.protocol === "http:" && hostname !== "localhost") throw new ExplicitEndpointError("https_required") - } + if (hostname.includes("*") || !hostname) throw new ExplicitEndpointError("invalid_origin") return url.origin } diff --git a/packages/server/src/opencode/servers/transport.ts b/packages/server/src/opencode/servers/transport.ts index f938e3a54c..7d4c0b9737 100644 --- a/packages/server/src/opencode/servers/transport.ts +++ b/packages/server/src/opencode/servers/transport.ts @@ -33,15 +33,13 @@ export function createExplicitTransport(options: { credentials?: { username: string; password: string } signal?: AbortSignal ca?: string - /** Saved CodeNomad profiles explicitly permit direct HTTP and optional private TLS. */ - allowHttp?: boolean skipTlsVerify?: boolean /** Backend-held cookies, set after filtering. */ headers?: () => Record /** Receives Set-Cookie values; they never reach the returned response. */ onSetCookie?: (values: string[]) => void }, resolve?: ResolveAddresses) { - const origin = normalizeExplicitOrigin(options.origin, options.allowHttp) + const origin = normalizeExplicitOrigin(options.origin) if (options.ca !== undefined) throw new ExplicitEndpointError("custom_ca_unsupported") // Copy secret inputs; subsequent caller mutation cannot retarget credentials. const credentials = options.credentials ? { ...options.credentials } : undefined @@ -56,7 +54,7 @@ export function createExplicitTransport(options: { if (url.origin !== origin || url.username || url.password || url.hash) throw new ExplicitEndpointError("invalid_origin") signal = AbortSignal.any([lifetime, request.signal]) signal.throwIfAborted() - const address = await abortable(resolveExplicitAddress(origin, resolve, options.allowHttp), signal) + const address = await abortable(resolveExplicitAddress(origin, resolve), signal) signal.throwIfAborted() agent = new Agent({ connect: { rejectUnauthorized: !options.skipTlsVerify, From aba4ecaf31db6e42e9d85652506e6a238520fb4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 6 Nov 2026 04:57:53 +0100 Subject: [PATCH 23/34] feat(remote): redeem pairing links through a dedicated server protocol Add POST /api/remote-control/server-pair on the Remote Control ingress. Its explicit JSON/header protocol uses only the short-lived single-use code and shares device issuance, revocation, expiry and eviction with browser pairing. Device labels identify the requesting CodeNomad hostname without attesting it. Browser pairing and its Origin checks retain their existing behavior. Reject browser, ambient-auth and preflight metadata before CORS; emit no CORS or Set-Cookie headers. Limit the dedicated route to ten attempts per minute and bounded bodies. The local backend validates the exact HTTPS saved origin, performs a fresh cookie-free exchange without Origin or Fetch metadata, verifies the resulting device and persists only its private device credential. Fixed endpoints, TLS policy, redirect refusal and request-log confidentiality prevent credential escape. Pairing-link profiles can browse in place immediately. Revoked credentials and unsupported older endpoints recover through the inline sign-in flow; refused link attempts clear the field and show localized expired/rate-limit errors. Native embedded views keep their separate authentication. UI/server typechecks, 44 targeted server tests, 46 browser tests, 1623 UI unit tests and 31 help checks pass. The complete serial server suite reports 3702 passed, 21 skipped and the previously baseline-reproduced Git observation deadline; its file passes 10 tests on isolated rerun. Offline Tauri no-bundle release build succeeds without launching the app. --- .../src/codenomad-servers/browse-manager.ts | 25 ++- .../src/codenomad-servers/browse.test.ts | 8 +- .../server/src/codenomad-servers/client.ts | 72 ++++++--- .../src/codenomad-servers/pairing.test.ts | 148 ++++++++++++++++++ .../server/src/opencode/servers/transport.ts | 11 +- packages/server/src/remote-control/gate.ts | 7 + packages/server/src/remote-control/manager.ts | 4 +- .../src/remote-control/server-pairing.test.ts | 98 ++++++++++++ .../src/remote-control/server-pairing.ts | 25 +++ .../remote-control/test-support/surface.ts | 9 +- .../integration-request-logging.test.ts | 7 + packages/server/src/server/http-server.ts | 13 +- packages/server/src/server/request-logging.ts | 5 +- .../src/server/routes/remote-control.ts | 19 +++ .../src/server/routes/remote-server-browse.ts | 2 +- .../src/components/remote-server-browser.tsx | 2 +- .../ui/src/components/server-add-field.tsx | 7 +- .../lib/i18n/messages/de/folderSelection.ts | 2 + .../lib/i18n/messages/en/folderSelection.ts | 2 + .../lib/i18n/messages/es/folderSelection.ts | 2 + .../lib/i18n/messages/fr/folderSelection.ts | 2 + .../lib/i18n/messages/he/folderSelection.ts | 2 + .../lib/i18n/messages/ja/folderSelection.ts | 2 + .../lib/i18n/messages/ne/folderSelection.ts | 2 + .../lib/i18n/messages/ru/folderSelection.ts | 2 + .../lib/i18n/messages/tr/folderSelection.ts | 2 + .../i18n/messages/zh-Hans/folderSelection.ts | 2 + packages/ui/src/lib/remote-pairing-link.ts | 4 +- .../tests/browser/remote-project-tabs.test.ts | 57 ++++++- 29 files changed, 498 insertions(+), 45 deletions(-) create mode 100644 packages/server/src/codenomad-servers/pairing.test.ts create mode 100644 packages/server/src/remote-control/server-pairing.test.ts create mode 100644 packages/server/src/remote-control/server-pairing.ts diff --git a/packages/server/src/codenomad-servers/browse-manager.ts b/packages/server/src/codenomad-servers/browse-manager.ts index 3201a3d585..0f95299df0 100644 --- a/packages/server/src/codenomad-servers/browse-manager.ts +++ b/packages/server/src/codenomad-servers/browse-manager.ts @@ -9,6 +9,15 @@ import { relayedFolderListing } from "./folders" const Profile = z.object({ id: z.string(), baseUrl: z.string(), skipTlsVerify: z.boolean().default(false) }) const Recent = z.object({ path: z.string().min(1).max(8192), projectName: z.string().max(1024).optional(), lastAccessed: z.number().finite() }) +function pairingCode(link: string, origin: string): string { + try { + const url = new URL(link) + if (url.protocol === "https:" && url.origin === origin && !url.username && !url.password && !url.search + && url.pathname === "/remote-pair" && /^#[A-Za-z0-9_-]{32}$/.test(url.hash) + && link === `${url.origin}/remote-pair${url.hash}`) return url.hash.slice(1) + } catch { /* Return a stable error without the caller's link. */ } + throw new CodeNomadServerError("pairing_expired") +} export const BrowseBody = z.object({ path: z.string().max(8192).optional() }).strict() export const ConnectBody = z.object({ username: z.string().min(1).max(1024).optional(), password: z.string().min(1).max(8192).optional(), pairingLink: z.string().max(8192).optional() }).strict() @@ -48,16 +57,22 @@ export class RemoteServerBrowseManager { connect(id: string, body: z.infer) { return this.serial(id, async () => { const profile = this.profile(id) - if (body.pairingLink !== undefined) throw new CodeNomadServerError("pairing_unavailable") + // Validate the exact saved origin and link syntax before constructing any transport or resolving DNS. + const code = body.pairingLink === undefined ? undefined : pairingCode(body.pairingLink, profile.origin) if (Boolean(body.username) !== Boolean(body.password)) throw new CodeNomadServerError("needs_credentials") - let secret: CodeNomadServerSecret | undefined = body.password + let secret: CodeNomadServerSecret | undefined = code ? undefined : body.password ? { kind: "password", username: body.username!, password: body.password } : this.credentials.read(id, profile.origin) - const client = new CodeNomadServerClient(profile.origin, secret, { skipTlsVerify: profile.skipTlsVerify, onSecretChanged: next => { secret = next } }) + const client = new CodeNomadServerClient(profile.origin, secret, { + skipTlsVerify: profile.skipTlsVerify, + onSecretChanged: next => { secret = next }, + onRejected: () => { if (!code && !body.password) this.remove(id) }, + }) this.#pending.add(client) try { + if (code) secret = await client.pair(code) const result = await client.json<{ authenticated?: unknown; pairingRequired?: unknown }>("/api/auth/status") - if (result.body?.pairingRequired === true) throw new CodeNomadServerError("pairing_unavailable") + if (result.body?.pairingRequired === true) throw new CodeNomadServerError("needs_credentials") if (result.status !== 200) throw new CodeNomadServerError("unreachable") if (result.body?.authenticated !== true) throw new CodeNomadServerError("needs_credentials") if (this.#closed || this.profile(id).key !== profile.key) throw new CodeNomadServerError("unknown_server") @@ -87,7 +102,7 @@ export class RemoteServerBrowseManager { const suffix = body.path === undefined ? "" : `?path=${encodeURIComponent(body.path)}` if (!this.credentials.has(id, profile.origin)) { const status = await entry.client.json<{ pairingRequired?: unknown }>("/api/auth/status") - if (status.body?.pairingRequired === true) throw new CodeNomadServerError("pairing_unavailable") + if (status.body?.pairingRequired === true) throw new CodeNomadServerError("needs_credentials") } const folders = await entry.client.json(`/api/filesystem${suffix}`) if (folders.status !== 200) throw new CodeNomadServerError("unreachable") diff --git a/packages/server/src/codenomad-servers/browse.test.ts b/packages/server/src/codenomad-servers/browse.test.ts index 6cf7805137..b3b3576c23 100644 --- a/packages/server/src/codenomad-servers/browse.test.ts +++ b/packages/server/src/codenomad-servers/browse.test.ts @@ -52,10 +52,10 @@ async function fixture(t: TestContext, options: Parameters call("connect", { username: "codenomad", password: "remote-password" }) } } -test("Remote Control status never offers a password form or attempts login", async t => { +test("unpaired Remote Control status requests credentials without attempting password login", async t => { const f = await fixture(t) f.remote.state.overrides.set('/api/auth/status', { status: 200, body: { authenticated: false, pairingRequired: true } }) - for (let i = 0; i < 2; i++) assert.deepEqual((await f.call('browse')).json(), { error: 'pairing_unavailable' }) + for (let i = 0; i < 2; i++) assert.deepEqual((await f.call('browse')).json(), { error: 'needs_credentials' }) assert.equal(f.remote.state.logins, 0) assert(f.remote.state.requests.every(request => request.path === '/api/auth/status' && request.headers.origin === undefined)) }) @@ -252,9 +252,9 @@ test("host guard requires loopback AND exact self Origin even with no general au assert.equal(fs.existsSync(path.join(f.dir, "remote-server-credentials.json")), false) }) -test("pairing unavailable preserves the actual Remote Control Origin and direct-listener policy", async t => { +test("invalid pairing links never dispatch; browser pairing preserves its Origin and direct-listener policy", async t => { const f = await fixture(t) - assert.deepEqual((await f.call("connect", { pairingLink: "https://remote.test/remote-pair#secret" })).json(), { error: "pairing_unavailable" }) + assert.deepEqual((await f.call("connect", { pairingLink: "https://remote.test/remote-pair#secret" })).json(), { error: "pairing_expired" }) assert.equal(f.remote.state.requests.length, 0) assert.deepEqual(redactSecrets({ pairingLink: "https://remote.test/remote-pair#secret", password: "secret" }), { pairingLink: "", password: "" }) const app = Fastify() diff --git a/packages/server/src/codenomad-servers/client.ts b/packages/server/src/codenomad-servers/client.ts index fd4474be5a..1c2e89c779 100644 --- a/packages/server/src/codenomad-servers/client.ts +++ b/packages/server/src/codenomad-servers/client.ts @@ -1,8 +1,12 @@ +import { hostname } from "node:os" +import { z } from "zod" import { createExplicitTransport } from "../opencode/servers/transport" import { ExplicitEndpointError, type ResolveAddresses } from "../opencode/servers/endpoint" import type { CodeNomadServerSecret } from "./credentials" +import { SERVER_PAIR_PATH } from "../remote-control/server-pairing" +import { DEVICE_COOKIE_NAME } from "../remote-control/gate" -export type CodeNomadServerErrorCode = "unreachable" | "tls_error" | "auth" | "pairing_unavailable" | "needs_credentials" | "unknown_server" +export type CodeNomadServerErrorCode = "unreachable" | "tls_error" | "auth" | "pairing_unavailable" | "pairing_expired" | "pairing_rate_limited" | "needs_credentials" | "unknown_server" /** Stable codes only; never a URL, credential or upstream message. */ export class CodeNomadServerError extends Error { @@ -14,6 +18,10 @@ export class CodeNomadServerError extends Error { const READ_LIMIT_BYTES = 8 * 1024 * 1024 const CALL_TIMEOUT_MS = 10_000 +const PairResponse = z.object({ + device: z.object({ id: z.string().uuid(), name: z.string().min(1).max(80), createdAt: z.string().datetime(), lastSeenAt: z.string().datetime() }).strict(), + credential: z.string().regex(/^[A-Za-z0-9_-]{43}$/), +}).strict() export function endpointErrorCode(error: unknown): CodeNomadServerErrorCode { if (error instanceof CodeNomadServerError) return error.code @@ -57,6 +65,7 @@ export class CodeNomadServerClient { } private capture(values: string[]) { + if (this.secret?.kind === "device") return for (const [name, value] of cookiePairs(values)) { if (value) this.#cookies.set(name, value) else this.#cookies.delete(name) @@ -73,6 +82,31 @@ export class CodeNomadServerClient { close() { this.#controller.abort() } get closed() { return this.#controller.signal.aborted } + /** A fresh, cookie-free exchange; the code is never retained by the client. */ + async pair(code: string): Promise { + const transport = createExplicitTransport({ origin: this.origin, signal: this.#controller.signal, + skipTlsVerify: this.options.skipTlsVerify, omitFetchMetadata: true }, this.options.resolve) + const response = await transport.fetch(new URL(SERVER_PAIR_PATH, this.origin), { + method: "POST", headers: { "content-type": "application/json", "x-codenomad-server-pairing": "1" }, + body: JSON.stringify({ code, hostName: hostname().slice(0, 255) }), signal: AbortSignal.timeout(CALL_TIMEOUT_MS), + }) + if (response.status !== 200) { + await response.body?.cancel().catch(() => {}) + throw new CodeNomadServerError([403, 404, 405].includes(response.status) ? "pairing_unavailable" + : [400, 401, 410].includes(response.status) ? "pairing_expired" : response.status === 429 ? "pairing_rate_limited" : "unreachable") + } + if (!/^application\/json(?:;|$)/i.test(response.headers.get("content-type") ?? "")) { + await response.body?.cancel().catch(() => {}) + throw new CodeNomadServerError("unreachable") + } + const parsed = PairResponse.safeParse(await readJson(response, 4096)) + if (!parsed.success) throw new CodeNomadServerError("unreachable") + const cookie = `${DEVICE_COOKIE_NAME}=${parsed.data.credential}` + this.#cookies.clear() + this.#cookies.set(DEVICE_COOKIE_NAME, parsed.data.credential) + return this.secret = { kind: "device", cookie } + } + /** Password login; cookies and passwords stay in the backend's private store. */ login(signal?: AbortSignal): Promise { if (this.secret?.kind !== "password") return Promise.reject(new CodeNomadServerError("needs_credentials")) @@ -113,23 +147,25 @@ export class CodeNomadServerClient { async json(path: string, init: RequestInit = {}): Promise<{ status: number; body: T | undefined }> { const signal = AbortSignal.any([AbortSignal.timeout(CALL_TIMEOUT_MS), ...(init.signal ? [init.signal] : [])]) const response = await this.fetch(path, { ...init, signal }) - const reader = response.body?.getReader() - const chunks: Uint8Array[] = [] - let length = 0 - if (reader) { - try { - while (true) { - const chunk = await reader.read() - if (chunk.done) break - length += chunk.value.byteLength - if (length > READ_LIMIT_BYTES) throw new CodeNomadServerError("unreachable") - chunks.push(chunk.value) - } - } catch (error) { await reader.cancel().catch(() => {}); throw error } - } - let body: T | undefined - try { body = length ? JSON.parse(Buffer.concat(chunks, length).toString("utf8")) as T : undefined } catch { body = undefined } - return { status: response.status, body } + return { status: response.status, body: await readJson(response, READ_LIMIT_BYTES) as T | undefined } } } + +async function readJson(response: Response, limit: number): Promise { + const reader = response.body?.getReader() + const chunks: Uint8Array[] = [] + let length = 0 + if (reader) { + try { + while (true) { + const chunk = await reader.read() + if (chunk.done) break + length += chunk.value.byteLength + if (length > limit) throw new CodeNomadServerError("unreachable") + chunks.push(chunk.value) + } + } catch (error) { await reader.cancel().catch(() => {}); throw error } + } + try { return length ? JSON.parse(Buffer.concat(chunks, length).toString("utf8")) : undefined } catch { return undefined } +} diff --git a/packages/server/src/codenomad-servers/pairing.test.ts b/packages/server/src/codenomad-servers/pairing.test.ts new file mode 100644 index 0000000000..ea8b2300f1 --- /dev/null +++ b/packages/server/src/codenomad-servers/pairing.test.ts @@ -0,0 +1,148 @@ +import assert from "node:assert/strict" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import http from "node:http" +import https from "node:https" +import { once } from "node:events" +import test, { type TestContext } from "node:test" +import type { RemoteTunnel } from "@codenomad/remote-tunnel" +import { RemoteServerBrowseManager } from "./browse-manager" +import { CodeNomadServerClient } from "./client" +import { startFakeCodeNomad } from "./test-support/fake-codenomad" +import { startRemoteSurface } from "../remote-control/test-support/surface" +import { resolveHttpsOptions } from "../server/tls" +import { SERVER_PAIR_PATH } from "../remote-control/server-pairing" +import { createLogger } from "../logger" +import { redactSecrets } from "../server/request-logging" + +const logger = createLogger({ level: "silent" } as never) +function directory(t: TestContext) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "codenomad-server-pair-")) + t.after(() => fs.rmSync(dir, { recursive: true, force: true })) + return dir +} +function tls(t: TestContext) { + return resolveHttpsOptions({ enabled: true, configDir: directory(t), host: "localhost", logger })!.httpsOptions +} + +test("real TLS tunnel exchange verifies status, persists only the device, browses after restart and clears revocation", async t => { + const tlsOptions = tls(t) + const requests: { path: string; headers: http.IncomingHttpHeaders }[] = [] + const f = await startRemoteSurface(t, { browse: true, openTunnel: async options => { + const [hostname, port] = options.target.split(":") + const server = https.createServer(tlsOptions, (request, response) => { + requests.push({ path: request.url!, headers: { ...request.headers } }) + const proxy = http.request({ hostname, port, path: request.url, method: request.method, headers: request.headers }, upstream => { + response.writeHead(upstream.statusCode!, upstream.headers) + upstream.pipe(response) + }) + proxy.on("error", () => response.destroy()) + request.pipe(proxy) + }) + server.listen(0, "127.0.0.1") + await once(server, "listening") + const host = `127.0.0.1:${(server.address() as { port: number }).port}` + let resolveClosed!: (error: string | undefined) => void + const closed = new Promise(resolve => { resolveClosed = resolve }) + return { url: `https://${host}`, hostname: host, status: () => ({ state: "connected", connections: 0 }), closed, + close: async () => { server.closeAllConnections(); await new Promise(resolve => server.close(() => resolve())); resolveClosed(undefined) } } satisfies RemoteTunnel + } }) + const dir = directory(t) + const origin = new URL(f.pairing.url).origin + const profiles = [{ id: "saved", baseUrl: origin, skipTlsVerify: false }] + const settings = { getOwner: () => ({ remoteServers: profiles }), configYamlPathForAuthority: () => path.join(dir, "config.yaml") } + const manager = new RemoteServerBrowseManager(settings) + t.after(() => manager.close()) + await assert.rejects(manager.connect("saved", { pairingLink: f.pairing.url }), { code: "tls" }) + assert.equal(requests.length, 0) + profiles[0]!.skipTlsVerify = true + assert.deepEqual(await manager.connect("saved", { pairingLink: f.pairing.url }), { ok: true }) + assert.deepEqual(requests.map(request => request.path), [SERVER_PAIR_PATH, "/api/auth/status"]) + const exchange = requests[0]!.headers + for (const name of ["origin", "cookie", "authorization", "proxy-authorization", "referer", "sec-fetch-mode", "sec-fetch-site"]) assert.equal(exchange[name], undefined, name) + assert.equal(exchange["x-codenomad-server-pairing"], "1") + const device = f.manager.devices()[0]! + assert.equal(device.name, `CodeNomad · ${os.hostname()}`.slice(0, 80)) + const file = path.join(dir, "remote-server-credentials.json") + const stored = JSON.parse(fs.readFileSync(file, "utf8")) + assert.deepEqual(Object.keys(stored.servers.saved.secret).sort(), ["cookie", "kind"]) + assert.equal(stored.servers.saved.origin, origin) + assert.equal(stored.servers.saved.secret.kind, "device") + assert.match(stored.servers.saved.secret.cookie, /^__Host-codenomad_device=[A-Za-z0-9_-]{43}$/) + assert(!fs.readFileSync(file, "utf8").includes(f.code)) + if (process.platform !== "win32") assert.equal(fs.statSync(file).mode & 0o777, 0o600) + const browse = await manager.browse("saved", {}) + assert.equal(browse.listing.metadata.currentPath, "/srv") + assert(!JSON.stringify(browse).includes(stored.servers.saved.secret.cookie)) + manager.close() + const next = new RemoteServerBrowseManager(settings) + t.after(() => next.close()) + assert.equal((await next.browse("saved", {})).listing.metadata.currentPath, "/srv") + assert(requests.every(request => request.headers.origin === undefined)) + assert.equal(requests.filter(request => request.path === SERVER_PAIR_PATH).length, 1) + assert(f.manager.revokeDevice(device.id)) + await assert.rejects(next.browse("saved", {}), { code: "auth" }) + assert.deepEqual(JSON.parse(fs.readFileSync(file, "utf8")), { servers: {} }) + await assert.rejects(next.browse("saved", {}), { code: "needs_credentials" }) + assert.deepEqual(await next.connect("saved", { pairingLink: f.manager.createPairing().url }), { ok: true }) + await next.forget("saved") + assert.deepEqual(JSON.parse(fs.readFileSync(file, "utf8")), { servers: {} }) + assert.deepEqual(redactSecrets({ credential: "private", pairingLink: f.pairing.url }), { credential: "", pairingLink: "" }) +}) + +test("link syntax and saved-origin fences reject before DNS or dispatch", async t => { + const dir = directory(t) + const origin = "https://does-not-resolve.invalid" + const manager = new RemoteServerBrowseManager({ getOwner: () => ({ remoteServers: [{ id: "saved", baseUrl: origin }] }), configYamlPathForAuthority: () => path.join(dir, "config.yaml") }) + t.after(() => manager.close()) + const code = "a".repeat(32) + for (const link of [ + `http://does-not-resolve.invalid/remote-pair#${code}`, `https://foreign.invalid/remote-pair#${code}`, + `${origin}/remote-pair?query=1#${code}`, `${origin}/remote-pair?#${code}`, `${origin}/other#${code}`, + `https://user@does-not-resolve.invalid/remote-pair#${code}`, `${origin}/x/../remote-pair#${code}`, + `${origin}/remote-pair#short`, `${origin}/remote-pair#${code}%00`, `${origin}/remote-pair#${code}/`, + ]) await assert.rejects(manager.connect("saved", { pairingLink: link }), { code: "pairing_expired" }) + assert.equal(fs.existsSync(path.join(dir, "remote-server-credentials.json")), false) +}) + +test("older endpoints and refused/malformed exchanges yield stable errors without credentials or ambient cookies", async t => { + const remote = await startFakeCodeNomad({ tls: tls(t) }) + t.after(() => remote.close()) + const dir = directory(t) + const manager = new RemoteServerBrowseManager({ getOwner: () => ({ remoteServers: [{ id: "saved", baseUrl: remote.origin, skipTlsVerify: true }] }), configYamlPathForAuthority: () => path.join(dir, "config.yaml") }) + t.after(() => manager.close()) + const link = `${remote.origin}/remote-pair#${"a".repeat(32)}` + for (const [status, code] of [[403, "pairing_unavailable"], [404, "pairing_unavailable"], [405, "pairing_unavailable"], [400, "pairing_expired"], [401, "pairing_expired"], [410, "pairing_expired"], [429, "pairing_rate_limited"], [500, "unreachable"]] as const) { + remote.state.overrides.set(SERVER_PAIR_PATH, { status, body: { credential: "must-not-leak" }, headers: { "set-cookie": "guest=ambient; Path=/" } }) + await assert.rejects(manager.connect("saved", { pairingLink: link }), { code }) + } + for (const body of [null, { credential: "injected; cookie=x" }, { device: {}, credential: "x".repeat(43) }, { payload: "x".repeat(4096) }]) { + remote.state.overrides.set(SERVER_PAIR_PATH, { status: 200, body, headers: { "set-cookie": "guest=ambient; Path=/" } }) + await assert.rejects(manager.connect("saved", { pairingLink: link }), { code: "unreachable" }) + } + assert.equal(fs.existsSync(path.join(dir, "remote-server-credentials.json")), false) + assert(remote.state.requests.every(request => request.path === SERVER_PAIR_PATH && !request.headers.origin && !request.headers.cookie && !request.headers["sec-fetch-mode"])) + assert(remote.state.requests.every(request => JSON.parse(request.body).hostName === os.hostname())) + const credential = "a".repeat(43) + const device = { id: "12345678-1234-4123-8123-123456789012", name: "CodeNomad · test", createdAt: new Date().toISOString(), lastSeenAt: new Date().toISOString() } + remote.state.overrides.set(SERVER_PAIR_PATH, { status: 200, body: { credential, device }, headers: { "set-cookie": "guest=ambient; Path=/" } }) + remote.state.overrides.set("/api/auth/status", { status: 200, body: { authenticated: false }, headers: { "set-cookie": "guest=ambient; Path=/" } }) + await assert.rejects(manager.connect("saved", { pairingLink: link }), { code: "needs_credentials" }) + assert.equal(fs.existsSync(path.join(dir, "remote-server-credentials.json")), false, "even a well-formed exchange must authenticate before persistence") + assert.equal(remote.state.requests.at(-1)!.headers.cookie, `__Host-codenomad_device=${credential}`) + remote.state.overrides.set("/api/auth/status", { status: 200, body: { authenticated: true } }) + assert.deepEqual(await manager.connect("saved", { pairingLink: link }), { ok: true }) + remote.state.overrides.set("/api/auth/status", { status: 401, body: { error: "revoked" } }) + await assert.rejects(manager.connect("saved", {}), { code: "auth" }) + assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir, "remote-server-credentials.json"), "utf8")), { servers: {} }, "a refused saved identity is cleared by connect as well as browse") + // Pairing remains independent even when a client was constructed with an ambient session. + const client = new CodeNomadServerClient(remote.origin, { kind: "session", cookie: "guest=existing" }, { skipTlsVerify: true }) + t.after(() => client.close()) + assert.deepEqual(await client.pair("a".repeat(32)), { kind: "device", cookie: `__Host-codenomad_device=${credential}` }) + assert.equal(remote.state.requests.at(-1)!.headers.cookie, undefined) + remote.state.overrides.set(SERVER_PAIR_PATH, { status: 302, body: {}, headers: { location: "/api/auth/status" } }) + const beforeRedirect = remote.state.requests.length + await assert.rejects(client.pair("a".repeat(32)), { code: "redirect" }) + assert.equal(remote.state.requests.length, beforeRedirect + 1) +}) diff --git a/packages/server/src/opencode/servers/transport.ts b/packages/server/src/opencode/servers/transport.ts index 7d4c0b9737..a62d2efb5d 100644 --- a/packages/server/src/opencode/servers/transport.ts +++ b/packages/server/src/opencode/servers/transport.ts @@ -38,6 +38,8 @@ export function createExplicitTransport(options: { headers?: () => Record /** Receives Set-Cookie values; they never reach the returned response. */ onSetCookie?: (values: string[]) => void + /** Explicit server protocols must not carry Fetch's automatically generated browser metadata. */ + omitFetchMetadata?: boolean }, resolve?: ResolveAddresses) { const origin = normalizeExplicitOrigin(options.origin) if (options.ca !== undefined) throw new ExplicitEndpointError("custom_ca_unsupported") @@ -64,12 +66,19 @@ export function createExplicitTransport(options: { else callback(null, address.address, address.family) }, } }) + const dispatcher = options.omitFetchMetadata ? agent.compose(dispatch => (options, handler) => { + const input = options.headers + // Fetch supplies an object; also accept the dispatch API's flat pair form. + const entries = Array.isArray(input) ? input.flatMap((name, i) => i % 2 ? [] : [[name, input[i + 1]]]) : Object.entries(input ?? {}) + const headers = Object.fromEntries(entries.filter(([name]) => !/^sec-fetch-/i.test(name!))) + return dispatch({ ...options, headers }, handler) + }) : agent const headers = filterHeaders(request.headers, requestDenied) if (credentials) headers.set("authorization", `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString("base64")}`) for (const [name, value] of Object.entries(options.headers?.() ?? {})) if (name.toLowerCase() !== "origin") headers.set(name, value) const response = await undiciFetch(url, { method: request.method, headers: Object.fromEntries(headers), - body: request.body as never, duplex: "half", signal, redirect: "manual", dispatcher: agent, + body: request.body as never, duplex: "half", signal, redirect: "manual", dispatcher, }) signal.throwIfAborted() if (response.status >= 300 && response.status < 400 && response.status !== 304) { diff --git a/packages/server/src/remote-control/gate.ts b/packages/server/src/remote-control/gate.ts index b7453f77d6..2faf715011 100644 --- a/packages/server/src/remote-control/gate.ts +++ b/packages/server/src/remote-control/gate.ts @@ -6,6 +6,7 @@ import type { RemoteControlDevice } from "../api-types" import { parsePreviewUpgradePath } from "../previews/upgrade-path" import { routedPath } from "../server/routed-path" import { attachRemoteDevice, isRemoteRequest } from "./request-origin" +import { SERVER_PAIR_PATH, validServerPairRequest } from "./server-pairing" export const DEVICE_COOKIE_NAME = "__Host-codenomad_device" export const PAIR_PAGE_PATH = "/remote-pair" @@ -53,6 +54,12 @@ export function gateRemoteRequest(request: FastifyRequest, reply: FastifyReply, reject(reply, 400, "Invalid request path") return true } + // Only this explicit non-browser exchange can omit the mutation Origin. + if (pathname === SERVER_PAIR_PATH) { + if (validServerPairRequest(request)) return false + reject(reply, 403, "Server pairing request rejected") + return true + } // A preview's sandboxed document sends no device cookie and `Origin: null`; its // capability token admits it, as on local listeners, while the host allows previews. const previewToken = pathname.match(/^\/previews\/([^/]+)(?:\/|$)/)?.[1] diff --git a/packages/server/src/remote-control/manager.ts b/packages/server/src/remote-control/manager.ts index e83acb4135..bd3012f55d 100644 --- a/packages/server/src/remote-control/manager.ts +++ b/packages/server/src/remote-control/manager.ts @@ -111,9 +111,9 @@ export class RemoteControlManager { return this.pairingFor(this.tunnel) } - exchangePairing(code: string, userAgent: string | undefined): { device: RemoteControlDevice; token: string } | null { + exchangePairing(code: string, userAgent: string | undefined, serverHostName?: string): { device: RemoteControlDevice; token: string } | null { if (!this.enabled || !this.tunnel) return null - const paired = this.options.registry.exchange(code, deviceNameFromUserAgent(userAgent)) + const paired = this.options.registry.exchange(code, serverHostName === undefined ? deviceNameFromUserAgent(userAgent) : `CodeNomad · ${serverHostName}`) if (!paired) return null // A device replaced at the limit loses its live connections, as on revocation. if (paired.evictedId) this.ingress.disconnectDevice(paired.evictedId) diff --git a/packages/server/src/remote-control/server-pairing.test.ts b/packages/server/src/remote-control/server-pairing.test.ts new file mode 100644 index 0000000000..bbeaf1adce --- /dev/null +++ b/packages/server/src/remote-control/server-pairing.test.ts @@ -0,0 +1,98 @@ +import assert from "node:assert/strict" +import http from "node:http" +import test from "node:test" +import { startRemoteSurface, FAKE_TUNNEL_HOST } from "./test-support/surface" +import { SERVER_PAIR_PATH } from "./server-pairing" +import { PAIRING_TTL_MS } from "./devices" + +function send(target: string, code: string, options: { method?: string; headers?: Record; path?: string; body?: string } = {}) { + const [hostname, port] = target.split(":") + const body = options.body ?? (options.method === "GET" || options.method === "HEAD" ? undefined : JSON.stringify({ code, hostName: "test-host" })) + return new Promise<{ status: number; headers: http.IncomingHttpHeaders; body: string }>((resolve, reject) => { + const request = http.request({ hostname, port, agent: false, path: options.path ?? SERVER_PAIR_PATH, method: options.method ?? "POST", + headers: { host: FAKE_TUNNEL_HOST, "content-length": String(Buffer.byteLength(body ?? "")), "content-type": "application/json", "x-codenomad-server-pairing": "1", ...options.headers } }, response => { + let body = "" + response.setEncoding("utf8").on("data", chunk => { body += chunk }).on("end", () => resolve({ status: response.statusCode!, headers: response.headers, body })) + }) + request.on("error", error => reject(new Error(`${options.method ?? "POST"} ${target}${options.path ?? SERVER_PAIR_PATH}: ${error.message}`))) + request.end(body) + }) +} + +function privateResponse(response: Awaited>) { + assert.equal(response.headers["set-cookie"], undefined) + assert(!Object.keys(response.headers).some(name => name.startsWith("access-control-"))) +} + +test("dedicated exchange is ingress-only, consumes the shared code and creates a listed revocable device", async t => { + const f = await startRemoteSurface(t) + const direct = await send(f.local, f.code) + assert.equal(direct.status, 404) + privateResponse(direct) + const wrongHost = await send(f.target(), f.code, { headers: { host: "foreign.test", "x-forwarded-host": FAKE_TUNNEL_HOST } }) + assert.equal(wrongHost.status, 421) + privateResponse(wrongHost) + const response = await send(f.target(), f.code, { headers: { "x-forwarded-for": "127.0.0.1", "x-forwarded-proto": "https", "x-codenomad-remote-control": "0" } }) + assert.equal(response.status, 200, response.body) + assert.equal(response.headers["cache-control"], "no-store") + privateResponse(response) + const { credential, device } = JSON.parse(response.body) + assert.match(credential, /^[A-Za-z0-9_-]{43}$/) + assert.equal(device.name, "CodeNomad · test-host") + assert.deepEqual(f.manager.devices(), [device]) + const cookie = `__Host-codenomad_device=${credential}` + const auth = await send(f.target(), "", { method: "GET", path: "/api/test/echo", headers: { cookie } }) + assert.equal(auth.status, 200) + assert.equal(JSON.parse(auth.body).loopbackPrivileges, false) + assert.equal((await send(f.target(), f.code)).status, 401) + assert.equal((await send(f.target(), f.code, { path: "/api/remote-control/pair", headers: { origin: `https://${FAKE_TUNNEL_HOST}` } })).status, 401) + assert(f.manager.revokeDevice(device.id)) + assert.equal((await send(f.target(), "", { method: "GET", path: "/api/test/echo", headers: { cookie } })).status, 401) + const next = new URL(f.manager.createPairing().url).hash.slice(1) + assert.equal((await send(f.target(), next, { path: "/api/remote-control/pair", headers: { origin: `https://${FAKE_TUNNEL_HOST}` } })).status, 200) + assert.equal((await send(f.target(), next)).status, 401, "browser consumption also forbids server replay") +}) + +test("browser/ambient auth headers and every non-POST fail before CORS without consuming the code", async t => { + const f = await startRemoteSurface(t) + for (const [name, value] of [ + ["origin", "null"], ["origin", `https://${FAKE_TUNNEL_HOST}`], ["origin", "https://foreign.test"], ["origin", ""], + ["cookie", "guest=1"], ["cookie", "__Host-codenomad_device=guest"], ["authorization", "Bearer guest"], ["proxy-authorization", "Basic guest"], + ["referer", `https://${FAKE_TUNNEL_HOST}/`], ["sec-fetch-site", "same-origin"], ["sec-fetch-mode", "cors"], ["sec-fetch-dest", "empty"], + ["access-control-request-method", "POST"], ["access-control-request-headers", "x-codenomad-server-pairing"], + ["x-codenomad-server-pairing", ""], ["content-type", "text/plain"], + ]) { + const response = await send(f.target(), f.code, { headers: { [name!]: value! } }) + assert.equal(response.status, 403, name) + privateResponse(response) + } + for (const target of [f.target(), f.local]) { + for (const method of ["GET", "HEAD", "PUT", "PATCH", "DELETE", "OPTIONS"]) { + const response = await send(target, f.code, { method, headers: { origin: "http://localhost:3000", "access-control-request-method": "POST" } }) + assert.equal(response.status, target === f.local ? 404 : 403, method) + privateResponse(response) + } + } + assert.equal((await send(f.target(), f.code)).status, 200) +}) + +test("strict bodies, expiry and wrong codes are refused; only the server route has a bounded limiter", async t => { + let now = Date.now() + const f = await startRemoteSurface(t, { now: () => now }) + for (const body of [JSON.stringify({ code: f.code, hostName: "" }), JSON.stringify({ code: f.code, hostName: "x", extra: true }), JSON.stringify({ code: "short", hostName: "x" })]) { + assert.equal((await send(f.target(), f.code, { body })).status, 400) + } + const oversized = await send(f.target(), f.code, { body: JSON.stringify({ code: f.code, hostName: "x".repeat(4096) }) }) + assert.equal(oversized.status, 413) + privateResponse(oversized) + assert.equal((await send(f.target(), "x".repeat(32))).status, 401) + now += PAIRING_TTL_MS + 1 + assert.equal((await send(f.target(), f.code)).status, 401) + for (let i = 0; i < 5; i++) assert.equal((await send(f.target(), "x".repeat(32))).status, 401) + const next = new URL(f.manager.createPairing().url).hash.slice(1) + const limited = await send(f.target(), next) + assert.equal(limited.status, 429) + assert.match(String(limited.headers["retry-after"]), /^[1-6]?[0-9]$/) + privateResponse(limited) + assert.equal((await send(f.target(), next, { path: "/api/remote-control/pair", headers: { origin: `https://${FAKE_TUNNEL_HOST}` } })).status, 200, "browser flow stays independent") +}) diff --git a/packages/server/src/remote-control/server-pairing.ts b/packages/server/src/remote-control/server-pairing.ts new file mode 100644 index 0000000000..00dd810ce8 --- /dev/null +++ b/packages/server/src/remote-control/server-pairing.ts @@ -0,0 +1,25 @@ +import type { FastifyReply, FastifyRequest } from "fastify" +import { routedPath } from "../server/routed-path" +import { isRemoteRequest } from "./request-origin" + +export const SERVER_PAIR_PATH = "/api/remote-control/server-pair" +const forbidden = /^(origin|cookie2?|authorization|proxy-authorization|referer|sec-fetch-.*|access-control-request-.*)$/i + +/** Dedicated non-browser protocol. Presence, including empty headers, is a refusal. */ +export function validServerPairRequest(request: FastifyRequest): boolean { + return request.method === "POST" + && request.headers["x-codenomad-server-pairing"] === "1" + && request.headers["content-type"] === "application/json" + && !Object.keys(request.headers).some(name => forbidden.test(name)) +} + +/** Runs globally before CORS, including its wildcard OPTIONS route and direct listeners. */ +export function guardServerPairRequest(request: FastifyRequest, reply: FastifyReply): boolean { + if (routedPath(request.raw.url ?? request.url) !== SERVER_PAIR_PATH) return false + reply.header("Cache-Control", "no-store") + if (!isRemoteRequest(request) || !validServerPairRequest(request)) { + reply.header("connection", "close").code(!isRemoteRequest(request) ? 404 : 403).send(request.method === "HEAD" ? "" : { error: "Server pairing request rejected" }) + return true + } + return false +} diff --git a/packages/server/src/remote-control/test-support/surface.ts b/packages/server/src/remote-control/test-support/surface.ts index a1e28a31c6..ca2add3f7a 100644 --- a/packages/server/src/remote-control/test-support/surface.ts +++ b/packages/server/src/remote-control/test-support/surface.ts @@ -22,6 +22,8 @@ const logger = createLogger({ level: "silent" } as never) */ export async function startRemoteSurface(t: TestContext, options: { skipAuth?: boolean + now?: () => number + browse?: boolean openTunnel?: (options: OpenRemoteTunnelOptions) => Promise /** Real panel extension routes over this store, with `workspaceManager` in place of the stub. */ panelExtensions?: { store: PanelExtensionStore; workspaceManager: unknown } @@ -46,7 +48,7 @@ export async function startRemoteSurface(t: TestContext, options: { let previewUpgrade: ReturnType["previewUpgrade"] | null = null const previewManager = new PreviewManager() const manager = new RemoteControlManager({ - registry: new RemoteDeviceRegistry(path.join(directory, "remote-control-devices.json")), + registry: new RemoteDeviceRegistry(path.join(directory, "remote-control-devices.json"), options.now), router: () => (app ? (request, response) => app!.routing(request, response) : null), previewUpgrade: () => previewUpgrade, hasPreview: (token) => previewManager.get(token) !== undefined, @@ -75,8 +77,9 @@ export async function startRemoteSurface(t: TestContext, options: { protocol: "http", workspaceManager: (options.panelExtensions?.workspaceManager ?? stub) as never, panelExtensions: options.panelExtensions?.store, - settings: stub, - fileSystemBrowser: stub, + settings: options.browse ? { getOwner: () => ({ recentFolders: [] }) } as never : stub, + fileSystemBrowser: options.browse ? { browse: () => ({ entries: [{ name: "app", path: "/srv/app", type: "directory" }], + metadata: { scope: "unrestricted", pathKind: "absolute", currentPath: "/srv", rootPath: "/", homePath: "/srv", displayPath: "/srv" } }) } as never : stub, eventBus: stub, serverMeta: { localUrl: "http://localhost:0", eventsUrl: "/api/events", host: "127.0.0.1", listeningMode: "local", localPort: 0, hostLabel: "test", workspaceRoot: directory, addresses: [] } as never, instanceStore: stub, diff --git a/packages/server/src/server/__tests__/integration-request-logging.test.ts b/packages/server/src/server/__tests__/integration-request-logging.test.ts index dad3b190c9..418b2cfbe1 100644 --- a/packages/server/src/server/__tests__/integration-request-logging.test.ts +++ b/packages/server/src/server/__tests__/integration-request-logging.test.ts @@ -39,6 +39,13 @@ function harness(level: "debug" | "trace") { } for (const level of ["debug", "trace"] as const) { + test(`${level}: server pairing logs exclude raw URLs, codes and credentials`, async t => { + const f = harness(level) + t.after(() => f.app.close()) + f.app.post('/api/remote-control/server-pair', () => ({ credential: secret })) + await f.app.inject({ method: 'POST', url: `/api/remote-control/server-pair?code=${secret}`, payload: { code: secret, credential: secret } }) + f.check() + }) test(`${level}: remote server connection credentials never enter request logs`, async t => { const f = harness(level) t.after(() => f.app.close()) diff --git a/packages/server/src/server/http-server.ts b/packages/server/src/server/http-server.ts index bcab4a2dc1..9b451240fa 100644 --- a/packages/server/src/server/http-server.ts +++ b/packages/server/src/server/http-server.ts @@ -1,5 +1,5 @@ import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify" -import cors from "@fastify/cors" +import cors, { type FastifyCorsOptions } from "@fastify/cors" import fastifyStatic from "@fastify/static" import replyFrom from "@fastify/reply-from" import fs from "fs" @@ -93,6 +93,7 @@ import { proxyWebSocket } from "./proxy-websocket" import type { PreviewManager } from "../previews/manager" import type { RemoteControlManager } from "../remote-control/manager" import { gateRemoteRequest, PAIR_EXCHANGE_PATH, PAIR_PAGE_PATH } from "../remote-control/gate" +import { guardServerPairRequest, SERVER_PAIR_PATH } from "../remote-control/server-pairing" import { isRemoteRequest } from "../remote-control/request-origin" import { routedPath } from "./routed-path" import { redactSecrets, registerRequestLogging } from "./request-logging" @@ -196,6 +197,7 @@ export function createHttpServer(deps: HttpServerDeps) { // Remote Control admission runs before CORS, authentication and routing. const remoteGate = deps.remoteControlManager.gate() app.addHook("onRequest", (request, reply, done) => { + if (guardServerPairRequest(request, reply)) return if (!gateRemoteRequest(request, reply, remoteGate)) done() }) @@ -221,7 +223,7 @@ export function createHttpServer(deps: HttpServerDeps) { return origins } - app.register(cors, { + const corsOptions: FastifyCorsOptions = { origin: (origin, cb) => { if (!origin) { cb(null, true) @@ -254,7 +256,10 @@ export function createHttpServer(deps: HttpServerDeps) { cb(null, false) }, credentials: true, - }) + } + // This CORS version uses a per-request delegator for route-level opt-out. + app.register(cors, { delegator: (request, callback) => callback(null, + routedPath(request.raw.url ?? request.url) === SERVER_PAIR_PATH ? { origin: false } : corsOptions) }) app.register(replyFrom, { contentTypesToEncode: [], @@ -277,7 +282,7 @@ export function createHttpServer(deps: HttpServerDeps) { } // Pairing routes answer only through the Remote Control ingress. - const publicApiPaths = new Set(["/api/auth/login", "/api/auth/token", "/api/auth/status", "/api/auth/logout", PAIR_EXCHANGE_PATH]) + const publicApiPaths = new Set(["/api/auth/login", "/api/auth/token", "/api/auth/status", "/api/auth/logout", PAIR_EXCHANGE_PATH, SERVER_PAIR_PATH]) const publicPagePaths = new Set(["/login", PAIR_PAGE_PATH]) if (deps.authManager.isTokenBootstrapEnabled()) { publicPagePaths.add("/auth/token") diff --git a/packages/server/src/server/request-logging.ts b/packages/server/src/server/request-logging.ts index bab8d16f8a..d560a10d28 100644 --- a/packages/server/src/server/request-logging.ts +++ b/packages/server/src/server/request-logging.ts @@ -2,11 +2,14 @@ import type { FastifyInstance, FastifyRequest } from "fastify" import type { Logger } from "../logger" import { isHumanAnswerProofPayload } from "../missions/human-answer" import { isRecurrenceProofPayload } from "../missions/recurrence-control-proof" +import { SERVER_PAIR_PATH } from "../remote-control/server-pairing" +import { routedPath } from "./routed-path" const integrationRoute = "/api/workspaces/:id/integrations" const integrationRoutes = new Set([integrationRoute, "/api/workspaces/:id/plugin-sources", ...["hosts", "binding", "attach", "detach", "install", "install-host"].map(action => `${integrationRoute}/:integrationId/${action}`)]) function integrationLogRoute(request: FastifyRequest): string | undefined { + if (routedPath(request.raw.url ?? request.url) === SERVER_PAIR_PATH) return SERVER_PAIR_PATH const route = request.routeOptions.url if (route && integrationRoutes.has(route)) return route // Rejects and malformed parameters may have no matched route. Decode segments independently so @@ -54,6 +57,6 @@ export function redactSecrets(value: unknown): unknown { || isHumanAnswerProofPayload(value as Record)) return "" return Object.fromEntries(Object.entries(value).map(([key, entry]) => [ key, - /(authorization|cookie|key|code|token|password|secret|principal|pairingLink)/i.test(key) ? "" : redactSecrets(entry), + /(authorization|cookie|credential|key|code|token|password|secret|principal|pairingLink)/i.test(key) ? "" : redactSecrets(entry), ])) } diff --git a/packages/server/src/server/routes/remote-control.ts b/packages/server/src/server/routes/remote-control.ts index 922d87ec90..09199449ea 100644 --- a/packages/server/src/server/routes/remote-control.ts +++ b/packages/server/src/server/routes/remote-control.ts @@ -4,6 +4,7 @@ import { z } from "zod" import type { RemoteControlManager } from "../../remote-control/manager" import { deviceCookie, PAIR_EXCHANGE_PATH, PAIR_PAGE_PATH } from "../../remote-control/gate" import { isRemoteRequest } from "../../remote-control/request-origin" +import { SERVER_PAIR_PATH, validServerPairRequest } from "../../remote-control/server-pairing" interface RouteDeps { manager: RemoteControlManager @@ -11,11 +12,29 @@ interface RouteDeps { const DeviceParams = z.object({ id: z.string().uuid() }) const PairBody = z.object({ code: z.string().min(1).max(256) }) +const ServerPairBody = z.object({ code: z.string().regex(/^[A-Za-z0-9_-]{32}$/), hostName: z.string().trim().min(1).max(255) }).strict() const PreviewsBody = z.object({ enabled: z.boolean() }) const PAIR_TEMPLATE_URL = new URL("./auth-pages/remote-pair.html", import.meta.url) let pairTemplate: string | null = null export function registerRemoteControlRoutes(app: FastifyInstance, deps: RouteDeps) { + // One bounded global bucket per backend, independent of untrusted peer/forwarded metadata. + let attempts = 0 + let resetsAt = 0 + app.post(SERVER_PAIR_PATH, { bodyLimit: 4096, config: { cors: false } }, async (request, reply) => { + reply.header("Cache-Control", "no-store") + if (!isRemoteRequest(request)) return reply.code(404).send({ error: "Not found" }) + if (!validServerPairRequest(request)) return reply.code(403).send({ error: "Server pairing request rejected" }) + const now = Date.now() + if (now >= resetsAt) { attempts = 0; resetsAt = now + 60_000 } + if (++attempts > 10) return reply.header("Retry-After", String(Math.max(1, Math.ceil((resetsAt - now) / 1000)))).code(429).send({ error: "Pairing rate limited" }) + const parsed = ServerPairBody.safeParse(request.body) + if (!parsed.success) return reply.code(400).send({ error: "Invalid server pairing body" }) + const paired = deps.manager.exchangePairing(parsed.data.code, undefined, parsed.data.hostName) + if (!paired) return reply.code(401).send({ error: "This pairing link is invalid, already used or expired" }) + return { device: paired.device, credential: paired.token } + }) + app.get("/api/remote-control/status", async (request) => { const status = deps.manager.status() return isRemoteRequest(request) ? { ...status, manageable: false } : status diff --git a/packages/server/src/server/routes/remote-server-browse.ts b/packages/server/src/server/routes/remote-server-browse.ts index 717c1b6d16..497afb7212 100644 --- a/packages/server/src/server/routes/remote-server-browse.ts +++ b/packages/server/src/server/routes/remote-server-browse.ts @@ -27,7 +27,7 @@ export function registerRemoteServerBrowseRoutes(app: FastifyInstance, deps: { return await deps.manager.browse(id, BrowseBody.parse(request.body ?? {})) } catch (error) { const code = endpointErrorCode(error) - return reply.code(code === "unknown_server" ? 404 : code === "needs_credentials" || code === "auth" || code === "pairing_unavailable" ? 409 : 502).send({ error: code }) + return reply.code(code === "unknown_server" ? 404 : ["needs_credentials", "auth", "pairing_unavailable", "pairing_expired", "pairing_rate_limited"].includes(code) ? 409 : 502).send({ error: code }) } }) } diff --git a/packages/ui/src/components/remote-server-browser.tsx b/packages/ui/src/components/remote-server-browser.tsx index e61e1304df..72ff3a9930 100644 --- a/packages/ui/src/components/remote-server-browser.tsx +++ b/packages/ui/src/components/remote-server-browser.tsx @@ -20,7 +20,7 @@ export default function RemoteServerBrowser(props: { let root: HTMLDivElement | undefined let controller: AbortController | undefined let generation = 0 - const needsCredentials = () => error() === "needs_credentials" || error() === "auth" + const needsCredentials = () => error() === "needs_credentials" || error() === "auth" || error() === "pairing_unavailable" function failure(value: unknown) { const code = value instanceof Error ? value.message : "unreachable" setError(["needs_credentials", "auth", "pairing_unavailable", "tls_error"].includes(code) ? code : "unreachable") diff --git a/packages/ui/src/components/server-add-field.tsx b/packages/ui/src/components/server-add-field.tsx index 384a7e39e4..c8ff7add1a 100644 --- a/packages/ui/src/components/server-add-field.tsx +++ b/packages/ui/src/components/server-add-field.tsx @@ -59,9 +59,12 @@ export default function ServerAddField(props: ServerAddFieldProps) { reset() props.onAdded?.(profile.id) } catch (failure) { - if (failure instanceof Error && failure.message === "pairing_unavailable") { + if (link.kind === "pairing") { + const code = failure instanceof Error ? failure.message : "unreachable" reset() - setError(t("remoteBrowse.pairingUnavailable")) + setError(t(code === "pairing_unavailable" ? "remoteBrowse.pairingUnavailable" + : code === "pairing_expired" ? "remoteBrowse.pairingExpired" + : code === "pairing_rate_limited" ? "remoteBrowse.pairingRateLimited" : "folderSelection.servers.dialog.errorConnect")) const saved = remoteServers().find(server => server.baseUrl === link.baseUrl) if (saved) props.onAdded?.(saved.id) return diff --git a/packages/ui/src/lib/i18n/messages/de/folderSelection.ts b/packages/ui/src/lib/i18n/messages/de/folderSelection.ts index fb95a49972..12b36bce83 100644 --- a/packages/ui/src/lib/i18n/messages/de/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/de/folderSelection.ts @@ -1,4 +1,6 @@ export const folderSelectionMessages = { + "remoteBrowse.pairingExpired": "Kopplungslink ungültig oder abgelaufen.", + "remoteBrowse.pairingRateLimited": "Zu viele Kopplungsversuche. Versuchen Sie es später erneut.", "remoteBrowse.back": "Zurück zu Durchsuchen", "remoteBrowse.pairingUnavailable": "Serverseitige Remote-Control-Kopplung nicht verfügbar.", "remoteBrowse.tlsError": "Zertifikatsprüfung fehlgeschlagen.", diff --git a/packages/ui/src/lib/i18n/messages/en/folderSelection.ts b/packages/ui/src/lib/i18n/messages/en/folderSelection.ts index 33d732cce2..8d8d045294 100644 --- a/packages/ui/src/lib/i18n/messages/en/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/en/folderSelection.ts @@ -1,4 +1,6 @@ export const folderSelectionMessages = { + "remoteBrowse.pairingExpired": "Pairing link invalid or expired.", + "remoteBrowse.pairingRateLimited": "Too many pairing attempts. Try again later.", "remoteBrowse.back": "Back to Browse", "remoteBrowse.pairingUnavailable": "Server-side Remote Control pairing unavailable.", "remoteBrowse.tlsError": "Certificate check failed.", diff --git a/packages/ui/src/lib/i18n/messages/es/folderSelection.ts b/packages/ui/src/lib/i18n/messages/es/folderSelection.ts index cea776c431..db78cbb3d7 100644 --- a/packages/ui/src/lib/i18n/messages/es/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/es/folderSelection.ts @@ -1,4 +1,6 @@ export const folderSelectionMessages = { + "remoteBrowse.pairingExpired": "Enlace de emparejamiento inválido o caducado.", + "remoteBrowse.pairingRateLimited": "Demasiados intentos de emparejamiento. Inténtalo más tarde.", "remoteBrowse.back": "Volver a Explorar", "remoteBrowse.pairingUnavailable": "Emparejamiento de Control remoto en el servidor no disponible.", "remoteBrowse.tlsError": "Error al verificar el certificado.", diff --git a/packages/ui/src/lib/i18n/messages/fr/folderSelection.ts b/packages/ui/src/lib/i18n/messages/fr/folderSelection.ts index 403432533a..cc8d3e0aae 100644 --- a/packages/ui/src/lib/i18n/messages/fr/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/fr/folderSelection.ts @@ -1,4 +1,6 @@ export const folderSelectionMessages = { + "remoteBrowse.pairingExpired": "Lien d’appairage invalide ou expiré.", + "remoteBrowse.pairingRateLimited": "Trop de tentatives d’appairage. Réessayez plus tard.", "remoteBrowse.back": "Retour à Parcourir", "remoteBrowse.pairingUnavailable": "Appairage Remote Control côté serveur indisponible.", "remoteBrowse.tlsError": "Échec de la vérification du certificat.", diff --git a/packages/ui/src/lib/i18n/messages/he/folderSelection.ts b/packages/ui/src/lib/i18n/messages/he/folderSelection.ts index c1a4015b5c..bf804b7ed6 100644 --- a/packages/ui/src/lib/i18n/messages/he/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/he/folderSelection.ts @@ -1,4 +1,6 @@ export const folderSelectionMessages = { + "remoteBrowse.pairingExpired": "קישור הצימוד אינו תקין או שפג תוקפו.", + "remoteBrowse.pairingRateLimited": "יותר מדי ניסיונות צימוד. נסו שוב מאוחר יותר.", "remoteBrowse.back": "חזרה לעיון", "remoteBrowse.pairingUnavailable": "צימוד שליטה מרחוק בצד השרת אינו זמין.", "remoteBrowse.tlsError": "בדיקת התעודה נכשלה.", diff --git a/packages/ui/src/lib/i18n/messages/ja/folderSelection.ts b/packages/ui/src/lib/i18n/messages/ja/folderSelection.ts index 03c7d421ce..90ab760793 100644 --- a/packages/ui/src/lib/i18n/messages/ja/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/ja/folderSelection.ts @@ -1,4 +1,6 @@ export const folderSelectionMessages = { + "remoteBrowse.pairingExpired": "ペアリングリンクが無効か期限切れです。", + "remoteBrowse.pairingRateLimited": "ペアリングの試行が多すぎます。後でもう一度試してください。", "remoteBrowse.back": "参照に戻る", "remoteBrowse.pairingUnavailable": "サーバー側のリモートコントロールのペアリングは利用できません。", "remoteBrowse.tlsError": "証明書の検証に失敗しました。", diff --git a/packages/ui/src/lib/i18n/messages/ne/folderSelection.ts b/packages/ui/src/lib/i18n/messages/ne/folderSelection.ts index 7d226fd33f..80fd6ff62b 100644 --- a/packages/ui/src/lib/i18n/messages/ne/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/ne/folderSelection.ts @@ -1,4 +1,6 @@ export const folderSelectionMessages = { + "remoteBrowse.pairingExpired": "Pairing लिङ्क अमान्य वा म्याद सकिएको छ।", + "remoteBrowse.pairingRateLimited": "धेरै pairing प्रयास भए। पछि फेरि प्रयास गर्नुहोस्।", "remoteBrowse.back": "ब्राउजमा फर्कनुहोस्", "remoteBrowse.pairingUnavailable": "सर्भरबाट Remote Control pairing उपलब्ध छैन।", "remoteBrowse.tlsError": "प्रमाणपत्र जाँच असफल भयो।", diff --git a/packages/ui/src/lib/i18n/messages/ru/folderSelection.ts b/packages/ui/src/lib/i18n/messages/ru/folderSelection.ts index d119275889..4ac5152789 100644 --- a/packages/ui/src/lib/i18n/messages/ru/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/ru/folderSelection.ts @@ -1,4 +1,6 @@ export const folderSelectionMessages = { + "remoteBrowse.pairingExpired": "Ссылка сопряжения недействительна или истекла.", + "remoteBrowse.pairingRateLimited": "Слишком много попыток сопряжения. Повторите позже.", "remoteBrowse.back": "Назад к обзору", "remoteBrowse.pairingUnavailable": "Сопряжение удалённого управления на стороне сервера недоступно.", "remoteBrowse.tlsError": "Проверка сертификата не пройдена.", diff --git a/packages/ui/src/lib/i18n/messages/tr/folderSelection.ts b/packages/ui/src/lib/i18n/messages/tr/folderSelection.ts index 6538f1c2fc..f963e413df 100644 --- a/packages/ui/src/lib/i18n/messages/tr/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/tr/folderSelection.ts @@ -1,4 +1,6 @@ export const folderSelectionMessages = { + "remoteBrowse.pairingExpired": "Eşleştirme bağlantısı geçersiz veya süresi dolmuş.", + "remoteBrowse.pairingRateLimited": "Çok fazla eşleştirme denemesi. Daha sonra tekrar deneyin.", "remoteBrowse.back": "Gözat'a dön", "remoteBrowse.pairingUnavailable": "Sunucu tarafında Uzaktan Kontrol eşleştirmesi kullanılamıyor.", "remoteBrowse.tlsError": "Sertifika doğrulaması başarısız.", diff --git a/packages/ui/src/lib/i18n/messages/zh-Hans/folderSelection.ts b/packages/ui/src/lib/i18n/messages/zh-Hans/folderSelection.ts index 4063a1ecec..5009bfd0e6 100644 --- a/packages/ui/src/lib/i18n/messages/zh-Hans/folderSelection.ts +++ b/packages/ui/src/lib/i18n/messages/zh-Hans/folderSelection.ts @@ -1,4 +1,6 @@ export const folderSelectionMessages = { + "remoteBrowse.pairingExpired": "配对链接无效或已过期。", + "remoteBrowse.pairingRateLimited": "配对尝试过多。请稍后重试。", "remoteBrowse.back": "返回浏览", "remoteBrowse.pairingUnavailable": "服务器端远程控制配对不可用。", "remoteBrowse.tlsError": "证书验证失败。", diff --git a/packages/ui/src/lib/remote-pairing-link.ts b/packages/ui/src/lib/remote-pairing-link.ts index e7f025935b..f7bc088fec 100644 --- a/packages/ui/src/lib/remote-pairing-link.ts +++ b/packages/ui/src/lib/remote-pairing-link.ts @@ -3,8 +3,8 @@ const PAIR_PAGE_PATH = "/remote-pair" /** * Splits a Remote Control pairing link into the server address to save and the - * single-use link that only the first window opens. The code lives in the - * fragment and is never stored with the server. + * single-use link redeemed by the local backend. The code lives in the + * fragment and is never stored with the profile. */ export function splitPairingLink(input: string): { baseUrl: string; entryUrl: string } | null { let url: URL diff --git a/packages/ui/tests/browser/remote-project-tabs.test.ts b/packages/ui/tests/browser/remote-project-tabs.test.ts index 1d9135dadf..dd4feaa122 100644 --- a/packages/ui/tests/browser/remote-project-tabs.test.ts +++ b/packages/ui/tests/browser/remote-project-tabs.test.ts @@ -35,6 +35,8 @@ interface Scenario { restore?: unknown sidecars?: unknown[] remoteNeedsPassword?: boolean + pairingWorks?: boolean + pairingError?: string } async function open(page: Page, path: string, scenario: Scenario) { @@ -85,7 +87,8 @@ async function open(page: Page, path: string, scenario: Scenario) { const body = request.postDataJSON() ?? {} if (remote[2] === 'forget') return route.fulfill({ json: { ok: true } }) if (remote[2] === 'connect') { - if (body.pairingLink) return route.fulfill({ status: 409, json: { error: 'pairing_unavailable' } }) + if (body.pairingLink && !scenario.pairingWorks) return route.fulfill({ status: 409, json: { error: scenario.pairingError ?? 'pairing_unavailable' } }) + if (body.pairingLink) { remoteAuthenticated = true; return route.fulfill({ json: { ok: true } }) } if (body.password !== 'fixture-password') return route.fulfill({ status: 409, json: { error: 'auth' } }) remoteAuthenticated = true return route.fulfill({ json: { ok: true } }) @@ -376,6 +379,58 @@ test("a local window opens a saved server as a project tab whose view follows th } finally { await page.close() } }) +test("a pairing-link profile browses with the backend's device and fills its blank tab only on project selection", async () => { + const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: 'en-US' }) + try { + const f = await open(page, '', { context: 'local', host: 'electron', remoteNeedsPassword: true, pairingWorks: true, + sidecars: [sidecar('docs', 'Docs', 'running')] }) + await browse(page) + await page.locator('[data-sidecar="docs"]').click() + await page.locator('.new-instance-button').click() + const blank = page.locator('[data-tab-kind="blank"][data-tab-visible="true"]') + await blank.getByRole('tab', { name: 'Browse', exact: true }).click() + const code = 'p'.repeat(32) + const field = blank.getByRole('textbox', { name: 'Server address or link' }) + await field.fill(`https://paired.example.test/remote-pair#${code}`) + await field.press('Enter') + const row = blank.getByRole('button', { name: 'Open a project on paired.example.test' }) + await row.waitFor() + await page.waitForFunction(() => document.activeElement?.textContent === 'paired.example.test') + assert.equal(await field.inputValue(), '') + assert.equal((await views(page)).opened.length, 0) + assert.equal(JSON.stringify(f.state()).includes(code), false) + await row.click() + const recent = blank.getByRole('button', { name: /Remote recent/ }) + await recent.waitFor() + assert.equal(await blank.getByRole('textbox', { name: 'Password', exact: true }).count(), 0) + assert.equal((await views(page)).opened.length, 0) + await recent.click() + await page.waitForFunction(() => (window as any).fixtureViews.opened.length === 1) + assert.equal(await page.locator('[data-tab-kind="blank"]').count(), 0) + assert.equal((await views(page)).opened[0].url, 'https://paired.example.test/?codenomadEmbed=project&folder=%2Fsrv%2Frecent') + assert.equal(JSON.stringify(f.state()).includes(code), false) + } finally { await page.close() } +}) + +for (const [code, message] of [ + ['pairing_unavailable', 'Server-side Remote Control pairing unavailable.'], + ['pairing_expired', 'Pairing link invalid or expired.'], + ['pairing_rate_limited', 'Too many pairing attempts. Try again later.'], +] as const) test(`${code}: a refused exchange clears its link and permits inline password recovery`, async () => { + const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: 'en-US' }) + try { + const f = await open(page, '', { context: 'local', host: 'electron', remoteNeedsPassword: true, pairingError: code }) + const field = await addServer(page, `https://older.example.test/remote-pair#${'x'.repeat(32)}`) + await page.getByRole('alert').getByText(message, { exact: true }).waitFor() + assert.equal(await field.inputValue(), '') + assert.equal(JSON.stringify(f.state()).includes('x'.repeat(32)), false) + await page.getByRole('button', { name: 'Open a project on older.example.test' }).click() + await page.getByRole('textbox', { name: 'Password', exact: true }).waitFor() + assert.equal(await page.getByRole('dialog').count(), 0) + assert.equal((await views(page)).opened.length, 0) + } finally { await page.close() } +}) + test("Browse refuses address credentials and saves a pairing server while reporting unavailable pairing", async () => { const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, locale: "en-US" }) try { From 54116d175c9552a8a681b42476616fd997c65a05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 6 Nov 2026 04:57:57 +0100 Subject: [PATCH 24/34] docs(remote): specify server pairing security and recovery Document the dedicated tunnel protocol, code-only authorization, browser and ambient-auth rejection, no-CORS responses, shared one-use semantics, global rate-limit tradeoff, device scope and private local storage. Explain supported tunnel exchange, older-server recovery and separate native-view authentication in all ten help languages. The full multilingual help validation passes 31 tests; the documentation records current behavior and the hostname label's trust boundary. --- dev-docs/PROJECTS.md | 4 +- dev-docs/REMOTE_CONTROL.md | 74 ++++++++++++++++++++++++----- dev-docs/architecture.md | 6 +-- docs/help/de/remote-access.md | 4 +- docs/help/de/remote-control.md | 8 +++- docs/help/en/remote-access.md | 4 +- docs/help/en/remote-control.md | 8 +++- docs/help/es/remote-access.md | 4 +- docs/help/es/remote-control.md | 8 +++- docs/help/fr/remote-access.md | 4 +- docs/help/fr/remote-control.md | 8 +++- docs/help/he/remote-access.md | 4 +- docs/help/he/remote-control.md | 8 +++- docs/help/ja/remote-access.md | 4 +- docs/help/ja/remote-control.md | 8 +++- docs/help/ne/remote-access.md | 4 +- docs/help/ne/remote-control.md | 8 +++- docs/help/ru/remote-access.md | 4 +- docs/help/ru/remote-control.md | 8 +++- docs/help/tr/remote-access.md | 4 +- docs/help/tr/remote-control.md | 8 +++- docs/help/zh-Hans/remote-access.md | 4 +- docs/help/zh-Hans/remote-control.md | 8 +++- 23 files changed, 147 insertions(+), 57 deletions(-) diff --git a/dev-docs/PROJECTS.md b/dev-docs/PROJECTS.md index 11aeea21b1..9b3cb8549c 100644 --- a/dev-docs/PROJECTS.md +++ b/dev-docs/PROJECTS.md @@ -10,8 +10,8 @@ Closing project tabs, temporary workspaces, the new-instance launcher and the Gi - Git is a full-functionality prerequisite, with directory-only degraded conversations when the backend cannot find Git. Only the explicitly opened physical folder is session authority in that mode; never infer sibling worktrees from native project IDs. Keep ancestor/descendant mutation identities covered by the deletion fence across Git availability changes. Inform agents through the owned native `codenomad.git-availability` instruction before prompts/custom commands, remove stale context after recovery, and keep this advisory separate from fail-closed environment synchronization. Do not add a blocking Git setup UI. Validate with `scripts/test-git-degraded-native.mjs` using an isolated CLI/database and provider. - Temporary instances (`workspaces/temporary-workspaces.ts`, UI `stores/temporary-instances.ts`) are ordinary non-Git workspaces on CodeNomad-created direct children of `/temporary-workspaces`. Registry membership (`temporary-workspaces.json`), not location, makes a folder temporary; keeping only unregisters it and adds a named recent project. Discard deletes only registered children of that root, refuses running conversations and other open tabs of the folder, removes conversations deepest-first, closes the workspace before deleting the folder and keeps failed removals registered; such a folder is reachable only by browsing to it. Closing a temporary tab from the UI asks Keep/Discard/Cancel, except that an untouched one (no conversation, file or unsent draft) closes and is discarded silently (`onlyIfEmpty`: the server refuses with `temporary_has_conversations`/`temporary_not_empty`, and any failure of that quiet discard returns the choice without an error). Before the server stops it, a visible temporary tab yields to its neighbour (or closes if alone) and a refusal restores it in place; `workspace.stopped` likewise closes the tab first and clears the instance in a microtask, because clearing a visible shell's state in the same update as its tab freezes the window. Same-minute names get a `(n)` suffix. Registry changes broadcast `workspace.temporaryChanged`, which clears kept marks in every window. Open temporary tabs are saved and restored with the app state like any project tab (still marked temporary). Only the choice dialog overrides initial focus (to its last, non-destructive choice); confirms keep focus on Cancel. Refusals use stable `temporary_*` codes localized by the client. Validate with `scripts/test-temporary-workspaces-native.mjs` against an isolated CLI. - The tab-bar new-instance button follows the last tab like a browser: the instance `TabScroll` frame only spans its tabs and the button sits after it, outside the scroller (so focusing it never scrolls the strip), ending up at the strip's end once tabs overflow. Dragged tabs stay visually within the tab list like a browser's (`KeepDraggedTabInStrip`), while the drop slot follows the pointer's unbounded position (`closestUnboundedCenter`). Clicking it (or Cmd/Ctrl+N) opens an empty tab. A long press, right-click, Alt+Down, Shift+F10 or Menu opens the anchored `NewInstanceLauncher` (`lib/long-press.ts`; only Escape returns focus to the button, never over another surface or the home page): titled Open a tab, it is the home page's logic in short: the search, the collapsible Recent section (unfolded by default and kept per window; chevron first, like Browse; Escape on its title folds it without closing the launcher; typing or an arrow in the search unfolds it; an open project switches to its tab), the folded Browse section, then Clone and New temporary tab only. Recents are local projects, remote projects and SideCars (`launchableRecents`, `filterRecents` for search fields, `components/recent-tab-icon.tsx`); a SideCar joins them when it opens (`stores/sidecar-open.ts`), stored as `ui` state `sidecarRecents` with its id and time only, never an address or proxy token, and listed while still configured. The home page's right card has two tabs, Recent (with the same search; arrows move between the tabs) and Browse (the list always open); its left column holds only the creation buttons of `components/new-tab-actions.tsx`: Clone a Git repository, New temporary tab and New SideCar (`openSettingsRow("sidecars", "sidecar-add")`, the SideCar form's name field); servers are added in Browse. The launcher's `variant` keeps only the first two. Renaming and removing recent tabs stay on the home page; servers are managed in Settings → Servers, SideCars in Settings → SideCars. Browse/clone flows live once in `components/new-instance-dialogs.tsx` and recent-folder display helpers in `lib/recent-folder-display.ts`, shared with `FolderSelectionView`; styles in `styles/components/new-instance-launcher.css`. -- Browse (`components/browse-menu.tsx`) lists This computer, host-visible saved servers, configured SideCars and the inline server-add field. `components/server-add-field.tsx` saves a profile only; pasting adds immediately and Enter or + submits typed text. An existing address reuses its profile. Credentials in an address are rejected. A `tls_error` offers Skip TLS verification with explicit confirmation and a window-only profile. A Remote Control pairing link saves its origin but reports localized server-side pairing unavailable and discards the code ([REMOTE_CONTROL.md](REMOTE_CONTROL.md)). Never persist a pairing code or retain it for native opening. -- Choosing a saved Browse row switches the list in place to that server's recent projects and folder list, with Back to Browse. An inline username/password form obtains a backend-held direct-access session when needed. Folder navigation stays in that list; Select Current or choosing a recent project opens its folder in a remote tab, replacing the originating blank slot. The `+` launcher stays open until a folder is chosen. Keep this flow shared between Home, blank tabs and the compact launcher. Backend browsing and native embedded views own independent authentication. +- Browse (`components/browse-menu.tsx`) lists This computer, host-visible saved servers, configured SideCars and the inline server-add field. `components/server-add-field.tsx` saves a profile; pasting adds immediately and Enter or + submits typed text. An existing address reuses its profile. Credentials in an address are rejected. A `tls_error` offers Skip TLS verification with explicit confirmation and a window-only profile. A Remote Control pairing link also asks the local backend to redeem its one-use code over the dedicated HTTPS tunnel protocol and persist a private device credential for browsing ([REMOTE_CONTROL.md](REMOTE_CONTROL.md#backend-to-backend-pairing)). The UI receives success only and scrubs the field after the attempt. Never persist a pairing code or retain it for native opening. Expired/replayed codes and rate limits have localized errors; unsupported remote pairing offers inline password recovery, which requires a direct-listener URL or a remote update for tunnel pairing. +- Choosing a saved Browse row switches the list in place to that server's recent projects and folder list, with Back to Browse. An inline username/password form obtains a backend-held direct-access session when needed. Backend pairing survives launches; revocation clears its rejected credential and shows the inline form again. Repair tunnel browsing with Back to Browse and a fresh pairing link in the add field. Folder navigation stays in that list; Select Current or choosing a recent project opens its folder in a remote tab, replacing the originating blank slot. The `+` launcher stays open until a folder is chosen. Keep this flow shared between Home, blank tabs and the compact launcher. Backend browsing and native embedded views own independent authentication. - Settings → Servers (`settings/servers-settings-section.tsx`, host windows only) manages profiles through the same add field, the edit-only `RemoteServerDialog` (address, name, certificate check) and confirmed removal. Removal must call the backend forget endpoint before removing the profile, then clear its recents and close its tabs. Saving keeps the profile id; a rename with unchanged URL/TLS skips the probe (`saveProfile`). Opening from the tabless native Preferences window opens the server's window. `serverDisplayName` (`lib/codenomad-link.ts`) uses the saved name or hostname, showing a port when another saved server shares that hostname. - A selected remote folder opens a `remote-project` app tab (`stores/remote-project-tabs.ts`, `stores/remote-project-open.ts`). `RemoteProjectView` places a native view over its content area: Electron `WebContentsView` (`electron/main/remote-view.ts`) or a Windows Tauri child webview (`src-tauri/src/remote_view.rs`). Other platforms and profiles that skip TLS verification open a separate remote window. Embedded views share the server's remote-window storage (Electron partition or Tauri data directory) and keep their own sign-in/device cookie; backend browsing uses its private credential store. Native access permits notifications only. Views stay on the server origin, open public help externally and return bare-root navigation after authentication to their tab entry. Tauri's `external-link-guard` checks registered `remote-view-*` labels through `RemoteViews::navigation_allowed` before window-origin rules. Views open lazily, track placeholder bounds, hide for inactive tabs and local overlays (`localOverlayOpen()`), and close with their owning page. - Embedded single-project mode (`lib/embed-mode.ts`, `/?codenomadEmbed=project[&folder=…]`) shows one project without the title/tab bars, Home or native badge; its folder picker handles entries without a folder. It records the folder in the URL and project name in `document.title`, and restores the active session per folder (`rememberEmbeddedSession`, `stores/embedded-project-session.ts`). The host accepts title updates only from the server origin with a folder in the address. Servers without this mode show their full interface and retain the server title. Password sessions last seven days (`PASSWORD_SESSION_TTL_MS`) with matching cookie `Max-Age`; logout revokes them and bootstrap sessions use browser-session cookies. Tabs restore as `{kind: "remote-project", profileId, folder?}`; missing/window-only profiles drop their tabs. Remote recents (`ui.remoteProjectRecents`) contain server, folder and name only. Covered by `tests/browser/remote-project-tabs.test.ts`, `electron/main/remote-view.test.ts` and `remote_view.rs` tests. diff --git a/dev-docs/REMOTE_CONTROL.md b/dev-docs/REMOTE_CONTROL.md index 727b47639a..85bdc9d06d 100644 --- a/dev-docs/REMOTE_CONTROL.md +++ b/dev-docs/REMOTE_CONTROL.md @@ -53,7 +53,7 @@ browser ─TLS─▶ OpenTunnel relay (forwards ciphertext) ─▶ OpenTunnel SD - `request-origin.ts` is the only authority for local privileges: `isLocalRequest()` requires a loopback peer **and** a non-ingress socket. - `gate.ts` runs before CORS, authentication and routing. It requires the exact - tunnel `Host` and the public `Origin` on mutations, and strips forwarding + tunnel `Host` and the public `Origin` on browser mutations, and strips forwarding headers. It accepts origin-form targets only (no absolute-form, leading `//` or fragment, which the router would reinterpret) and judges the path the router routes (`server/routed-path.ts`). It denies host-only paths: login and token @@ -73,7 +73,8 @@ browser ─TLS─▶ OpenTunnel relay (forwards ciphertext) ─▶ OpenTunnel SD `pairingRequired`. The recovery dialog then explains how to pair again instead of offering password login, keeping the page and its drafts. Pairing from another tab restores it on the next check. -- `devices.ts` issues one five-minute, single-use pairing code. The link carries +- `devices.ts` issues one 192-bit, five-minute, single-use pairing code shared by + browser and server pairing. Consuming it through either route exhausts it for both. The link carries it in the fragment, never in the query or a log. It stores SHA-256 hashes of device credentials and expires devices after 30 days without use. `__Host-codenomad_device` is `Secure; HttpOnly; SameSite=Lax`. Revocation, @@ -82,19 +83,68 @@ browser ─TLS─▶ OpenTunnel relay (forwards ciphertext) ─▶ OpenTunnel SD only once Remote Control is used. - Remote devices authenticate even with `--dangerously-skip-auth`, and the local session cookie is never accepted on the ingress. -- Browser pairing consumes the link in the intended browser/profile. The remote - gate requires its exact public browser `Origin` on mutations, while the direct - listener refuses the pair route. Backend remote-server requests omit `Origin`, - so `connect` with a pairing link returns `pairing_unavailable`. The desktop - saves only the tunnel-origin profile, reports localized server-side pairing - unavailable and discards the code. Never keep it in persisted state or a native - pending-entry map. Embedded views retain their own remote-window authentication; - the backend Browse session is independent of a view's paired-device cookie - ([PROJECTS.md](PROJECTS.md#agent-conventions)). +- Browser pairing consumes the link in the intended browser/profile through + `/api/remote-control/pair`. Its exact public `Origin` checks remain mandatory. + Direct listeners refuse both pairing routes. Pasting a pairing link into the + desktop server-add field saves the tunnel-origin profile and asks the local + backend to redeem the code through the server protocol below. Embedded views + retain their own remote-window authentication, independently of backend Browse + pairing ([PROJECTS.md](PROJECTS.md#agent-conventions)). Never persist a pairing + code or retain it for native opening. - `--connect-server` opens a saved server or URL at launch through that same connect flow ([architecture.md](architecture.md#native-profiles-windows-and-client-state)). It refuses URLs with user info or a fragment, so a pairing code or password - never travels on a command line; open pairing links in the intended browser. + never travels on a command line; use the server-add field or the intended browser for pairing links. + +## Backend-to-backend pairing + +`POST /api/remote-control/server-pair` is a dedicated HTTPS tunnel-ingress +protocol. `server-pairing.ts` guards its exact routed path before CORS, authentication +and routing; the remote gate exempts only that path from browser mutation `Origin` +requirements. The direct listener returns 404. Never forge an `Origin` to pair. + +- Require `X-CodeNomad-Server-Pairing: 1`, exact `Content-Type: application/json`, + and a body of at most 4096 bytes: `{code, hostName}`, with a 32-character base64url + code and a hostname of at most 255 characters. +- Refuse every non-POST and any presence of `Origin` (including `null`), `Cookie`, + `Cookie2`, `Authorization`, `Proxy-Authorization`, `Referer`, `sec-fetch-*` or + `access-control-request-*` headers before CORS. Responses carry `Cache-Control: + no-store`, omit CORS and `Set-Cookie`, and return `{device, credential}` only to + the calling backend on success. Code possession is the authorization; excluding + ambient authentication and browser/preflight metadata confines this exchange + to the explicit protocol while browser pairing keeps its own admission checks. +- A global bucket per remote backend allows ten attempts per minute on this + route and returns 429 with `Retry-After` when exhausted. This bounds redemption + work and guessing; competing clients can exhaust the shared bucket and delay + legitimate server pairing. Browser pairing retains its existing behavior. +- The device uses the shared registry's 30-day idle expiry, revocation and + least-recently-seen eviction. Its display name is `CodeNomad · `: + a self-reported label, with identity assurance supplied by code possession and + the TLS endpoint rather than hostname attestation. + +The local backend validates an HTTPS pairing link against the exact saved origin +before DNS resolution. A fresh, cookie-free, bounded exchange strips Undici Fetch +metadata, follows the saved TLS policy and endpoint-identity checks, and refuses +redirects and foreign origins. It verifies `/api/auth/status` reports device +authentication before persisting the device cookie in private +`remote-server-credentials.json` (mode `0600`). Protect the configuration directory +and its platform permissions as credential storage. The local UI receives only +success; secrets stay out of UI state and logs, and the add field is scrubbed after +the attempt. Never retain codes for retries. + +The credential survives local launches. Forgetting the saved server deletes it; +revocation clears the rejected credential and returns Browse to its inline +password form. To repair tunnel browsing, use Back to Browse and paste a fresh +pairing link into the add field. Native embedded views pair separately. + +Compatibility is capability-based: an endpoint returning 403 (including an older +browser-Origin rejection), 404 or 405 maps to `pairing_unavailable` and offers +inline password recovery. Password login on tunnel ingress remains host-only: +update the remote server for backend pairing, or save its direct-listener URL for +password access. Invalid, expired or replayed codes map to `pairing_expired` +(`pairingExpired` in UI translations); 429 maps to `pairing_rate_limited` +(`pairingRateLimited`). Obtain a fresh link for expired codes and wait before +retrying a rate-limited attempt. ## Validation diff --git a/dev-docs/architecture.md b/dev-docs/architecture.md index 26df389e5c..f28bf086f0 100644 --- a/dev-docs/architecture.md +++ b/dev-docs/architecture.md @@ -52,7 +52,7 @@ CodeNomad control APIs live under `/api/*`. Important routes include: - `/api/events` and `/api/client-connections/pong` - `/api/storage`, `/api/settings`, `/api/filesystem`, `/api/speech` - `/api/opencode-plugin/automation`, authenticated by a per-process loopback token and restricted to CodeNomad-owned locations -- `/api/remote-control/*`, managed from the host only; `POST /api/remote-control/pair` and `/remote-pair` answer only through Remote Control ([REMOTE_CONTROL.md](REMOTE_CONTROL.md)) +- `/api/remote-control/*`, managed from the host only; browser `POST /api/remote-control/pair`, `/remote-pair` and the dedicated backend `POST /api/remote-control/server-pair` answer only through Remote Control. The backend protocol requires explicit headers and code possession, rejects ambient authentication and browser metadata before CORS, and returns its credential only to the calling backend ([REMOTE_CONTROL.md](REMOTE_CONTROL.md#backend-to-backend-pairing)). - `POST /api/remote-servers/:id/browse`, `/connect` and `/forget`, for saved-profile direct-access browsing. Access requires both loopback non-Remote-Control ingress and an explicit trusted self `Origin`. The backend resolves the profile id from its authoritative UI state; never accept caller-supplied remote URLs as profile authority. Authentication and Remote Control admission judge `routedPath()` (`server/routed-path.ts`), the path Fastify's router matches (`/%61pi/x` routes as `/api/x`), and refuse targets it would reinterpret. Never base an access decision on the raw request target. @@ -63,7 +63,7 @@ Yolo state endpoints live at `/workspaces/:id/yolo/sessions/:sessionId`; Yolo no ## Client And Events -Remote Browse obtains remote recent projects and folders through a backend-held direct CodeNomad session. The UI switches its Browse list in place, requests username/password inline when needed, and opens a remote tab only after a folder is selected. An expired session is reauthenticated once. Saving a profile authorizes its destination address: eligible targets include loopback, RFC1918 LAN, Docker, Hyper-V, CGNAT/Tailscale (`100.64.0.0/10`), MagicDNS and `*.ts.net`, IPv6 ULA/link-local, and names resolving to these addresses. Connections require working network routes and TLS; verification follows the saved profile and its existing explicit opt-out confirmation. Browsing credentials remain private to the backend. All upstream remote-server requests omit `Origin`; never forge it or forward credentials through redirects or to a foreign origin. Embedded native views retain their own authentication and remote-window storage independently of backend browsing. Remote Control pairing through backend connect returns `pairing_unavailable`; the profile retains only the tunnel origin and the code is discarded ([REMOTE_CONTROL.md](REMOTE_CONTROL.md)). +Remote Browse obtains remote recent projects and folders through a backend-held password session or Remote Control device credential. The UI switches its Browse list in place, requests username/password inline when needed, and opens a remote tab only after a folder is selected. An expired password session is reauthenticated once. Saving a profile authorizes its destination address: eligible targets include loopback, RFC1918 LAN, Docker, Hyper-V, CGNAT/Tailscale (`100.64.0.0/10`), MagicDNS and `*.ts.net`, IPv6 ULA/link-local, and names resolving to these addresses. Connections require working network routes and TLS; verification follows the saved profile and its existing explicit opt-out confirmation. Browsing credentials remain private to the backend. All upstream remote-server requests omit `Origin`; never forge it or forward credentials through redirects or to a foreign origin. Adding a Remote Control pairing link saves its origin and redeems its one-use code via a fresh cookie-free HTTPS tunnel exchange, after exact saved-origin validation before DNS. The backend checks device authentication before persisting the credential; the UI receives success only and scrubs the field. Revocation clears rejected credentials; Back to Browse and a fresh link repair tunnel browsing. Unsupported pairing endpoints offer inline password recovery, with a remote update required for tunnel pairing or a direct-listener URL for password access. Embedded native views retain their own authentication and remote-window storage independently of backend browsing ([REMOTE_CONTROL.md](REMOTE_CONTROL.md#backend-to-backend-pairing)). `packages/ui/src/lib/sdk-manager.ts` uses `OpenCode.make()` and caches generated Promise clients by instance proxy path. `packages/ui/src/stores/opencode-client.ts` is the root-client authority; native directory/location fields select the worktree. @@ -91,7 +91,7 @@ Session Shell and conversation instructions are native features. Session Shell i ## Persistence -CodeNomad configuration resolves through `packages/server/src/config/location.ts`: `config.yaml`, `state.yaml`, `remote-control-devices.json`, `remote-server-credentials.json`, and `instances/` under `~/.config/codenomad/`. `config.json` is read only as migration input. The private `remote-server-credentials.json` beside the backend configuration stores remote browsing passwords and sessions with mode `0600`. Never include those secrets in API responses, UI state or logs. Removing a saved profile calls `/api/remote-servers/:id/forget` before deleting its UI-state entry. +CodeNomad configuration resolves through `packages/server/src/config/location.ts`: `config.yaml`, `state.yaml`, `remote-control-devices.json`, `remote-server-credentials.json`, and `instances/` under `~/.config/codenomad/`. `config.json` is read only as migration input. The private `remote-server-credentials.json` beside the backend configuration stores remote browsing passwords, sessions and paired-device cookies across launches with mode `0600`; protect its directory and platform permissions. Never include those secrets in local UI API responses, UI state or logs, or persist pairing codes. The remote server's device registry stores credential hashes. Removing a saved profile calls `/api/remote-servers/:id/forget` before deleting its UI-state entry. ## Implementation Map diff --git a/docs/help/de/remote-access.md b/docs/help/de/remote-access.md index 6391551b03..705b5d6538 100644 --- a/docs/help/de/remote-access.md +++ b/docs/help/de/remote-access.md @@ -83,7 +83,7 @@ Meldet ein Client eine Zertifikatswarnung, halten Sie an und prüfen Sie Hostnam ## Remote-Server speichern {#saved-servers} -1. Öffnen Sie auf der Startseite, einem leeren Tab oder im Starter **Tab öffnen** den Bereich **Durchsuchen**. Geben Sie Adresse oder Kopplungslink in **Serveradresse oder -link** ein: Einfügen fügt sofort hinzu, die Eingabetaste bestätigt getippten Text. Der Server wird nur unter seinem Hostnamen gespeichert und seine Zeile fokussiert; der Starter bleibt offen. Klicken Sie auf diese Zeile, um Projekte an Ort und Stelle zu durchsuchen. **Einstellungen → Server** bietet dasselbe Feld. +1. Öffnen Sie auf der Startseite, einem leeren Tab oder im Starter **Tab öffnen** den Bereich **Durchsuchen**. Geben Sie Adresse oder Kopplungslink in **Serveradresse oder -link** ein: Einfügen fügt sofort hinzu, die Eingabetaste bestätigt getippten Text. Der Server wird unter seinem Hostnamen gespeichert und seine Zeile fokussiert; ein Kopplungslink koppelt außerdem das lokale Backend für die Ordnersuche. Der Starter bleibt offen. Klicken Sie auf diese Zeile, um Projekte an Ort und Stelle zu durchsuchen. **Einstellungen → Server** bietet dasselbe Feld. 2. Verwenden Sie einen vertrauenswürdigen HTTPS-Ursprung. Besteht sein Zertifikat die Prüfung nicht, erscheint unter dem Feld **TLS-Prüfung überspringen**: Aktivieren Sie dies nur für einen vertrauenswürdigen Server und speichern Sie erneut mit der Eingabetaste. Die Auswahl eines Ordners oder Projekts dieses Profils öffnet ein eigenes Fenster. 3. Wählen Sie seine Zeile unter **Durchsuchen**, um Projekte an Ort und Stelle zu durchsuchen. Geben Sie bei Bedarf Benutzername und Passwort im eingeblendeten Formular ein. Name und Adresse ändern Sie mit **Server bearbeiten** unter **Einstellungen → Server**. @@ -93,7 +93,7 @@ Um einen gespeicherten Server direkt von der Befehlszeile zu öffnen, starten Si Ein Remote-Fenster lässt immer einen Weg zurück zu diesem Computer. Wenn Sie das letzte lokale Fenster schließen, während Remote-Fenster geöffnet bleiben, behält es seine Tabs: **Fenster → Neues Fenster** in einem Remote-Fenster oder ein erneuter Start von CodeNomad öffnet es wieder. Kann ein Server nicht geladen werden, zeigt sein Fenster das an und bietet **Erneut versuchen**, **Lokales Fenster öffnen** und **Fenster schließen**; in der Tauri-Version verwenden Sie die Schaltfläche zum Neuladen der Seite und **Fenster → Neues Fenster**. -Das Einfügen eines Fernsteuerungslinks speichert nur den Tunnel-Ursprung und meldet, dass serverseitige Kopplung nicht verfügbar ist; der Code wird verworfen. Öffnen Sie den Link zum Koppeln im gewünschten Browser. Siehe [Fernsteuerung](remote-control.md). +Das Einfügen eines frischen Fernsteuerungslinks speichert den Tunnel-Ursprung und koppelt das lokale Backend für die Ordnersuche. Seine Gerätezugangsdaten bleiben privat über Neustarts hinweg gespeichert; der Code wird nach dem Versuch verworfen. Wählen Sie nach einem Widerruf **Zurück zu Durchsuchen** und fügen Sie einen frischen Link in **Serveradresse oder -link** ein. Eingebettete Ansichten werden separat gekoppelt. Ist serverseitige Kopplung nicht verfügbar, aktualisieren Sie den entfernten Server oder nutzen Sie seine direkte Listener-URL zur Passwortanmeldung; Tunneladressen erfordern Kopplung. Siehe [Fernsteuerung](remote-control.md). ## Ein Remote-Projekt in einem Tab öffnen {#remote-project-tabs} diff --git a/docs/help/de/remote-control.md b/docs/help/de/remote-control.md index d59f965101..d554d1942a 100644 --- a/docs/help/de/remote-control.md +++ b/docs/help/de/remote-control.md @@ -11,12 +11,16 @@ Fernsteuerung ermöglicht einem gekoppelten Browser- oder Desktop-Client die Nut Der Link gilt **fünf Minuten** und funktioniert **einmal**. Behandeln Sie ihn als Zugangsdaten: Wer ihn einlöst, kann ein gekoppeltes Gerät werden. Der Code steht im URL-Fragment, nicht in der Abfragezeichenfolge. **Neuen Kopplungslink erstellen** macht den vorherigen ungenutzten Link sofort ungültig. Stop, Backend-Ende und Tunnelfehler stornieren offene Kopplungslinks. -Öffnen Sie Kopplungslinks im gewünschten Browser. Das Einfügen in **Serveradresse oder -link** auf dem Desktop speichert nur den Tunnel-Ursprung und meldet, dass serverseitige Kopplung nicht verfügbar ist. Der Code wird verworfen. Die Ordnersuche des Backends verwendet eine eigene Direktzugriffssitzung; die eingebettete Ansicht behält unabhängig davon ihre Anmeldung oder ihr Geräte-Cookie. +Öffnen Sie einen Kopplungslink im gewünschten Browser oder fügen Sie einen frischen Link auf dem Desktop in **Serveradresse oder -link** ein. Dadurch wird der Server gespeichert und das lokale Backend für die Ordnersuche über die Fernsteuerung gekoppelt. Jeder Link funktioniert über beide Methoden hinweg genau einmal. Das Backend bewahrt seine Gerätezugangsdaten privat über Neustarts hinweg auf; der Code wird nach dem Versuch verworfen. Eingebettete Ansichten und entfernte Fenster verwenden ihre eigene Authentifizierung und benötigen gegebenenfalls einen eigenen Kopplungslink. + +Backend-Kopplungen erscheinen als `CodeNomad · `. Der Hostname ist eine selbst angegebene Bezeichnung; prüfen Sie Ziel und TLS-Zertifikat, bevor Sie einen Link teilen. Das Entfernen des gespeicherten Servers löscht seine lokalen Zugangsdaten zur Ordnersuche; das Widerrufen seines Geräts beendet den Zugriff. Wählen Sie zur Wiederherstellung **Zurück zu Durchsuchen** und fügen Sie einen frischen Link in **Serveradresse oder -link** ein. Erstellen Sie bei abgelaufenen oder bereits verwendeten Codes einen neuen Link; warten Sie bei einer Ratenbegrenzung vor dem nächsten Versuch. Die Backend-Kopplung erlaubt insgesamt zehn Versuche pro Minute für alle Clients des entfernten Backends. + +Meldet der entfernte Server, dass serverseitige Kopplung nicht verfügbar ist, aktualisieren Sie ihn oder speichern Sie seine direkte Listener-URL für das integrierte Passwortformular. Die Passwortanmeldung erfolgt über den Direktzugriff; eine Tunneladresse erfordert Kopplung. ## Gekoppelte Geräte verwalten {#paired-devices} 1. Kehren Sie auf dem Host zu **Einstellungen → Remote-Zugriff → Fernsteuerung** zurück. -2. Prüfen Sie **Gekoppelte Geräte** und deren **Zuletzt gesehen:**-Zeit. Jedes Gerät ist nach der Plattform und dem Browser benannt, die es gekoppelt haben, etwa `iPhone · Safari`. +2. Prüfen Sie **Gekoppelte Geräte** und deren **Zuletzt gesehen:**-Zeit. Browser-Kopplungen sind nach ihrer Plattform und ihrem Browser benannt, etwa `iPhone · Safari`. 3. Wählen Sie **Widerrufen** für ein Gerät, das nicht länger zugreifen soll. Widerruf beendet aktuelle HTTP-/SSE-Verbindungen des Geräts sowie zukünftigen Zugriff. Koppeln Sie zum Wiederherstellen mit einem neuen Link. Ein Gerät verfällt nach **30 Tagen ohne Nutzung**. Bei der **Grenze von 32 Geräten** ersetzt eine neue Kopplung das am längsten nicht gesehene Gerät und schließt dessen Verbindungen. diff --git a/docs/help/en/remote-access.md b/docs/help/en/remote-access.md index 9c6cd69c96..68959f2498 100644 --- a/docs/help/en/remote-access.md +++ b/docs/help/en/remote-access.md @@ -83,7 +83,7 @@ If a client reports a certificate warning, stop and check the hostname, SANs, tr ## Save a remote server {#saved-servers} -1. On Home, an empty tab or the **Open a tab** launcher, open **Browse** and enter the address or pairing link in **Server address or link**. Pasting adds it immediately; Enter adds typed text. Adding only saves the server under its host name and focuses its row; the launcher stays open. Click the saved row to browse projects in place. **Settings → Servers** offers the same field. +1. On Home, an empty tab or the **Open a tab** launcher, open **Browse** and enter the address or pairing link in **Server address or link**. Pasting adds it immediately; Enter adds typed text. Adding saves the server under its host name and focuses its row; a pairing link also pairs the local backend for browsing. The launcher stays open. Click the saved row to browse projects in place. **Settings → Servers** offers the same field. 2. Use a trusted HTTPS origin. If its certificate fails the check, the error shows under the field with **Skip TLS verification**: tick it only for a server you trust, then press Enter again to save it. Choosing a folder or project on that profile opens its own window. 3. Choose its saved **Browse** row to browse projects in place. If prompted, enter the server username and password in the inline form. Rename it or change its address with **Edit server** in **Settings → Servers**. @@ -93,7 +93,7 @@ To open a saved server straight from the command line, start the desktop app wit A remote window always leaves a way back to this computer. Closing the last local window while remote windows stay open keeps its tabs: **Window → New Window** in a remote window, or starting CodeNomad again, reopens it. If a server cannot be loaded, its window says so and offers **Try again**, **Open a local window** and **Close window**; in the Tauri build, use the page's reload button and **Window → New Window**. -Pasting a Remote Control pairing link saves only its tunnel origin and reports that server-side pairing is unavailable; the code is discarded. Open the link in the intended browser to pair there. See [Remote Control](remote-control.md). +Pasting a fresh Remote Control pairing link saves its tunnel origin and pairs the local backend for browsing, with its device credential kept privately across launches. The code is discarded after the attempt. After revocation, choose **Back to Browse** and paste a fresh link into **Server address or link**. Embedded views pair independently. If server-side pairing is unavailable, update the remote server or use its direct-listener URL for password login; tunnel addresses require pairing. See [Remote Control](remote-control.md). ## Open a remote project in a tab {#remote-project-tabs} diff --git a/docs/help/en/remote-control.md b/docs/help/en/remote-control.md index af66ffbf60..efb18e3aa6 100644 --- a/docs/help/en/remote-control.md +++ b/docs/help/en/remote-control.md @@ -11,12 +11,16 @@ Remote Control lets a paired browser or desktop client use your running CodeNoma The link is valid for **five minutes** and succeeds **once**. Treat it as a credential: anyone who consumes it can become a paired device. The code lives in the URL fragment, not the query string. **Create new pairing link** immediately invalidates the preceding unused link. Stop, backend shutdown and tunnel failure cancel outstanding pairing links. -Open pairing links in the intended browser. Pasting one into desktop **Server address or link** saves only the tunnel origin and reports that server-side pairing is unavailable. The code is discarded. Backend folder browsing uses its own direct-access session; an embedded view keeps its own sign-in or paired-device cookie independently. +Open a pairing link in the intended browser, or paste a fresh link into desktop **Server address or link** to save the server and pair the local backend for folder browsing through Remote Control. Each link works once across both methods. The backend keeps its device credential privately across launches; the code is discarded after the attempt. Embedded views and remote windows keep their own authentication and may need a separate pairing link. + +Backend pairings appear as `CodeNomad · ` in the device list. The hostname is a self-reported label; verify the destination and its TLS certificate before sharing a link. Removing the saved server deletes its local browsing credential; revoking its device ends access. To restore browsing, choose **Back to Browse** and paste a fresh link into **Server address or link**. For an expired or already-used code, create a new link; for a rate-limit error, wait before retrying. Backend pairing allows ten attempts per minute across all clients of the remote backend. + +If the remote server reports server-side pairing unavailable, update that server or save its direct-listener URL to use the inline password form. Password login is available through direct access; a tunnel address requires pairing. ## Manage paired devices {#paired-devices} 1. On the host, return to **Settings → Remote Access → Remote Control**. -2. Review **Paired devices** and their **Last seen** time. Each device is named after the platform and browser that paired it, such as `iPhone · Safari`. +2. Review **Paired devices** and their **Last seen** time. Browser pairings are named after their platform and browser, such as `iPhone · Safari`. 3. Choose **Revoke** for a device that should no longer connect. Revocation ends that device's current HTTP/SSE connections as well as future access. Pair again with a new link to restore access. A device expires after **30 days without use**. At the **32-device limit**, a new pairing replaces the least recently seen device and closes its connections. diff --git a/docs/help/es/remote-access.md b/docs/help/es/remote-access.md index 394ffdf9f9..7445cbf470 100644 --- a/docs/help/es/remote-access.md +++ b/docs/help/es/remote-access.md @@ -83,7 +83,7 @@ Si un cliente muestra una advertencia de certificado, detente y comprueba el nom ## Guardar un servidor remoto {#saved-servers} -1. En Inicio, una pestaña vacía o el lanzador **Abrir una pestaña**, abre **Explorar** e introduce la dirección o enlace de emparejamiento en **Dirección o enlace del servidor**. Pegar lo añade al instante; Intro confirma el texto escrito. Solo se guarda el servidor con su nombre de host y se enfoca su fila; el lanzador permanece abierto. Haz clic en la fila para explorar sus proyectos en la misma lista. **Configuración → Servidores** ofrece el mismo campo. +1. En Inicio, una pestaña vacía o el lanzador **Abrir una pestaña**, abre **Explorar** e introduce la dirección o enlace de emparejamiento en **Dirección o enlace del servidor**. Pegar lo añade al instante; Intro confirma el texto escrito. Se guarda el servidor con su nombre de host y se enfoca su fila; un enlace de emparejamiento también empareja el backend local para explorar. El lanzador permanece abierto. Haz clic en la fila para explorar sus proyectos en la misma lista. **Configuración → Servidores** ofrece el mismo campo. 2. Usa un origen HTTPS de confianza. Si su certificado no supera la verificación, aparece **Omitir la verificación TLS** bajo el campo: márcala solo para un servidor de confianza y pulsa Intro de nuevo para guardarlo. Elegir una carpeta o proyecto de ese perfil abre su propia ventana. 3. Elige su fila en **Explorar** para ver los proyectos en la misma lista. Si se solicita, introduce usuario y contraseña del servidor en el formulario integrado. Cambia su nombre o dirección con **Editar servidor** en **Configuración → Servidores**. @@ -93,7 +93,7 @@ Para abrir un servidor guardado directamente desde la línea de comandos, inicia Una ventana remota siempre deja una forma de volver a este equipo. Cerrar la última ventana local mientras siguen abiertas ventanas remotas conserva sus pestañas: **Ventana → Nueva ventana** en una ventana remota, o iniciar CodeNomad de nuevo, la vuelve a abrir. Si un servidor no se puede cargar, su ventana lo indica y ofrece **Reintentar**, **Abrir una ventana local** y **Cerrar ventana**; en la versión Tauri, usa el botón de recarga de la página y **Ventana → Nueva ventana**. -Pegar un enlace de Control remoto solo guarda el origen del túnel e informa de que el emparejamiento del lado del servidor no está disponible; el código se descarta. Abre el enlace en el navegador deseado para emparejarlo. Consulta [Control remoto](remote-control.md). +Pegar un enlace nuevo de Control remoto guarda el origen del túnel y empareja el backend local para explorar; su credencial de dispositivo se conserva de forma privada entre inicios. El código se descarta tras el intento. Tras una revocación, elige **Volver a Explorar** y pega un enlace nuevo en **Dirección o enlace del servidor**. Las vistas integradas se emparejan por separado. Si el emparejamiento del lado del servidor no está disponible, actualiza el servidor remoto o usa su URL de escucha directa para iniciar sesión con contraseña; las direcciones de túnel requieren emparejamiento. Consulta [Control remoto](remote-control.md). ## Abrir un proyecto remoto en una pestaña {#remote-project-tabs} diff --git a/docs/help/es/remote-control.md b/docs/help/es/remote-control.md index 6f46ce8fa8..806429991e 100644 --- a/docs/help/es/remote-control.md +++ b/docs/help/es/remote-control.md @@ -11,12 +11,16 @@ Control remoto permite a un navegador o cliente de escritorio emparejado usar tu El enlace es válido durante **cinco minutos** y funciona **una vez**. Trátalo como una credencial: cualquiera que lo consuma puede convertirse en un dispositivo emparejado. El código está en el fragmento de la URL, no en la cadena de consulta. **Crear nuevo enlace de emparejamiento** invalida inmediatamente el enlace anterior sin usar. Detener, apagar el backend y los fallos del túnel cancelan los enlaces de emparejamiento pendientes. -Abre los enlaces de emparejamiento en el navegador deseado. Pegarlos en **Dirección o enlace del servidor** del escritorio solo guarda el origen del túnel e informa de que el emparejamiento del lado del servidor no está disponible. El código se descarta. La exploración de carpetas del backend utiliza su propia sesión de acceso directo; la vista integrada conserva su inicio de sesión o cookie de dispositivo de forma independiente. +Abre un enlace de emparejamiento en el navegador deseado o pega uno nuevo en **Dirección o enlace del servidor** del escritorio para guardar el servidor y emparejar el backend local para explorar carpetas mediante Control remoto. Cada enlace funciona una sola vez entre ambos métodos. El backend conserva su credencial de dispositivo de forma privada entre inicios; el código se descarta tras el intento. Las vistas integradas y ventanas remotas conservan su propia autenticación y pueden necesitar otro enlace. + +Los emparejamientos del backend aparecen como `CodeNomad · `. El nombre de host es una etiqueta declarada por el cliente; comprueba el destino y su certificado TLS antes de compartir un enlace. Eliminar el servidor guardado borra su credencial local de exploración; revocar su dispositivo termina el acceso. Para restaurarlo, elige **Volver a Explorar** y pega un enlace nuevo en **Dirección o enlace del servidor**. Si el código ha caducado o ya se ha usado, crea otro enlace; si aparece un límite de intentos, espera antes de reintentar. El emparejamiento del backend permite diez intentos por minuto entre todos los clientes del backend remoto. + +Si el servidor remoto indica que el emparejamiento del lado del servidor no está disponible, actualízalo o guarda su URL de escucha directa para usar el formulario de contraseña integrado. El inicio de sesión con contraseña usa el acceso directo; una dirección de túnel requiere emparejamiento. ## Gestionar dispositivos emparejados {#paired-devices} 1. En el equipo anfitrión, vuelve a **Configuración → Acceso remoto → Control remoto**. -2. Revisa **Dispositivos emparejados** y su hora de **Última actividad**. Cada dispositivo recibe el nombre de la plataforma y el navegador que lo emparejaron, como `iPhone · Safari`. +2. Revisa **Dispositivos emparejados** y su hora de **Última actividad**. Los emparejamientos de navegador reciben el nombre de su plataforma y navegador, como `iPhone · Safari`. 3. Elige **Revocar** para un dispositivo que ya no deba conectarse. La revocación finaliza las conexiones HTTP/SSE actuales del dispositivo y su acceso futuro. Vuelve a emparejarlo con un enlace nuevo para restaurar el acceso. Un dispositivo caduca tras **30 días sin uso**. Al alcanzar el **límite de 32 dispositivos**, un emparejamiento nuevo reemplaza el dispositivo con actividad más antigua y cierra sus conexiones. diff --git a/docs/help/fr/remote-access.md b/docs/help/fr/remote-access.md index 9c365fecd5..a701d86b15 100644 --- a/docs/help/fr/remote-access.md +++ b/docs/help/fr/remote-access.md @@ -83,7 +83,7 @@ Si un client signale un avertissement de certificat, arrêtez-vous et vérifiez ## Enregistrer un serveur distant {#saved-servers} -1. Sur l’accueil, un onglet vide ou le lanceur **Ouvrir un onglet**, ouvrez **Parcourir** et saisissez l’adresse ou le lien d’appairage dans **Adresse ou lien du serveur**. Le collage l’ajoute immédiatement ; Entrée ajoute le texte saisi. L’ajout enregistre seulement le serveur sous son nom d’hôte et place le focus sur sa ligne ; le lanceur reste ouvert. Cliquez sur cette ligne pour parcourir ses projets sur place. **Paramètres → Serveurs** propose le même champ. +1. Sur l’accueil, un onglet vide ou le lanceur **Ouvrir un onglet**, ouvrez **Parcourir** et saisissez l’adresse ou le lien d’appairage dans **Adresse ou lien du serveur**. Le collage l’ajoute immédiatement ; Entrée ajoute le texte saisi. L’ajout enregistre le serveur sous son nom d’hôte et place le focus sur sa ligne ; un lien d’appairage appaire aussi le backend local pour le parcours. Le lanceur reste ouvert. Cliquez sur cette ligne pour parcourir ses projets sur place. **Paramètres → Serveurs** propose le même champ. 2. Utilisez une origine HTTPS de confiance. Si son certificat échoue à la vérification, l’erreur s’affiche sous le champ avec **Ignorer la vérification TLS** : cochez-la seulement pour un serveur de confiance, puis appuyez de nouveau sur Entrée pour l’enregistrer. Choisir un dossier ou un projet de ce profil ouvre sa propre fenêtre. 3. Choisissez sa ligne dans **Parcourir** pour explorer ses projets sur place. Si demandé, saisissez le nom d’utilisateur et le mot de passe du serveur dans le formulaire intégré. Modifiez son nom ou son adresse avec **Modifier le serveur** dans **Paramètres → Serveurs**. @@ -93,7 +93,7 @@ Pour ouvrir un serveur enregistré directement depuis la ligne de commande, lanc Une fenêtre distante laisse toujours un moyen de revenir sur cet ordinateur. Fermer la dernière fenêtre locale alors que des fenêtres distantes restent ouvertes conserve ses onglets : **Fenêtre → Nouvelle fenêtre** dans une fenêtre distante, ou un nouveau lancement de CodeNomad, la rouvre. Si un serveur ne peut pas être chargé, sa fenêtre l’indique et propose **Réessayer**, **Ouvrir une fenêtre locale** et **Fermer la fenêtre** ; dans la version Tauri, utilisez le bouton d’actualisation de la page et **Fenêtre → Nouvelle fenêtre**. -Coller un lien du Contrôle à distance enregistre seulement l’origine du tunnel et signale que l’appairage côté serveur est indisponible ; le code est supprimé. Ouvrez le lien dans le navigateur voulu pour l’appairer. Voir [Contrôle à distance](remote-control.md). +Coller un lien neuf du Contrôle à distance enregistre l’origine du tunnel et appaire le backend local pour le parcours ; son identifiant d’appareil reste privé et persiste entre les lancements. Le code est supprimé après la tentative. Après révocation, choisissez **Retour à Parcourir** et collez un lien neuf dans **Adresse ou lien du serveur**. Les vues intégrées s’appairent séparément. Si l’appairage côté serveur est indisponible, mettez le serveur distant à jour ou utilisez son URL d’écoute directe pour la connexion par mot de passe ; les adresses de tunnel exigent un appairage. Voir [Contrôle à distance](remote-control.md). ## Ouvrir un projet distant dans un onglet {#remote-project-tabs} diff --git a/docs/help/fr/remote-control.md b/docs/help/fr/remote-control.md index 85f1a462a6..a9212cd7eb 100644 --- a/docs/help/fr/remote-control.md +++ b/docs/help/fr/remote-control.md @@ -11,12 +11,16 @@ Le Contrôle à distance permet à un navigateur ou client de bureau appairé d Le lien est valable **cinq minutes** et réussit **une seule fois**. Traitez-le comme un identifiant : quiconque le consomme peut devenir un appareil appairé. Le code se trouve dans le fragment d’URL, pas dans la chaîne de requête. **Créer un nouveau lien d’appairage** invalide immédiatement le lien inutilisé précédent. L’arrêt, la fermeture du backend et une panne du tunnel annulent les liens d’appairage en attente. -Ouvrez les liens d’appairage dans le navigateur voulu. En coller un dans **Adresse ou lien du serveur** sur le bureau enregistre seulement l’origine du tunnel et signale que l’appairage côté serveur est indisponible. Le code est supprimé. Le parcours des dossiers par le backend utilise sa propre session d’accès direct ; la vue intégrée conserve indépendamment sa connexion ou son cookie d’appareil appairé. +Ouvrez un lien d’appairage dans le navigateur voulu, ou collez un lien neuf dans **Adresse ou lien du serveur** sur le bureau pour enregistrer le serveur et appairer le backend local afin de parcourir les dossiers via le Contrôle à distance. Chaque lien fonctionne une seule fois, toutes méthodes confondues. Le backend conserve son identifiant d’appareil en privé entre les lancements ; le code est supprimé après la tentative. Les vues intégrées et fenêtres distantes conservent leur propre authentification et peuvent nécessiter un lien distinct. + +Les appairages du backend apparaissent sous `CodeNomad · `. Le nom d’hôte est une étiquette déclarée par le client ; vérifiez la destination et son certificat TLS avant de partager un lien. Supprimer le serveur enregistré efface son identifiant local de parcours ; révoquer son appareil termine l’accès. Pour rétablir le parcours, choisissez **Retour à Parcourir** et collez un lien neuf dans **Adresse ou lien du serveur**. Pour un code expiré ou déjà utilisé, créez un nouveau lien ; en cas de limitation, attendez avant de réessayer. L’appairage du backend autorise dix tentatives par minute pour l’ensemble des clients du backend distant. + +Si le serveur distant signale que l’appairage côté serveur est indisponible, mettez-le à jour ou enregistrez son URL d’écoute directe pour utiliser le formulaire de mot de passe intégré. La connexion par mot de passe passe par l’accès direct ; une adresse de tunnel exige un appairage. ## Gérer les appareils appairés {#paired-devices} 1. Sur l’hôte, revenez à **Paramètres → Accès distant → Contrôle à distance**. -2. Vérifiez **Appareils appairés** et leur heure **Dernière activité**. Chaque appareil porte le nom de la plateforme et du navigateur qui l’ont appairé, par exemple `iPhone · Safari`. +2. Vérifiez **Appareils appairés** et leur heure **Dernière activité**. Les appairages de navigateur portent le nom de leur plateforme et de leur navigateur, par exemple `iPhone · Safari`. 3. Choisissez **Révoquer** pour un appareil qui ne doit plus se connecter. La révocation termine les connexions HTTP/SSE actuelles de cet appareil ainsi que son accès futur. Appairez-le à nouveau avec un nouveau lien pour rétablir l’accès. Un appareil expire après **30 jours sans utilisation**. À la **limite de 32 appareils**, un nouvel appairage remplace l’appareil vu le moins récemment et ferme ses connexions. diff --git a/docs/help/he/remote-access.md b/docs/help/he/remote-access.md index 22a144fc0e..32ac5c7e69 100644 --- a/docs/help/he/remote-access.md +++ b/docs/help/he/remote-access.md @@ -83,7 +83,7 @@ codenomad --host 127.0.0.1 --https=false --http=true ## שמירת שרת מרוחק {#saved-servers} -1. בדף הבית, בלשונית ריקה או במשגר **פתיחת לשונית**, פתחו את **עיון** והזינו כתובת או קישור צימוד ב־**כתובת או קישור של השרת**. הדבקה מוסיפה מיד; Enter מוסיף טקסט שהוקלד. ההוספה רק שומרת את השרת בשם המארח וממקדת את השורה שלו; המשגר נשאר פתוח. לחצו על השורה כדי לעיין בפרויקטים באותה רשימה. **הגדרות → שרתים** מציע את אותו השדה. +1. בדף הבית, בלשונית ריקה או במשגר **פתיחת לשונית**, פתחו את **עיון** והזינו כתובת או קישור צימוד ב־**כתובת או קישור של השרת**. הדבקה מוסיפה מיד; Enter מוסיף טקסט שהוקלד. ההוספה שומרת את השרת בשם המארח וממקדת את השורה שלו; קישור צימוד גם מצמד את שרת הקצה המקומי לעיון. המשגר נשאר פתוח. לחצו על השורה כדי לעיין בפרויקטים באותה רשימה. **הגדרות → שרתים** מציע את אותו השדה. 2. השתמשו במקור HTTPS מהימן. אם התעודה נכשלת בבדיקה, **דילוג על אימות TLS** מופיע מתחת לשדה: סמנו רק לשרת מהימן והקישו Enter שוב כדי לשמור. בחירת תיקייה או פרויקט בפרופיל הזה פותחת חלון משלו. 3. בחרו בשורת השרת ב־**עיון** כדי לעיין בפרויקטים באותה רשימה. אם תתבקשו, הזינו שם משתמש וסיסמה בטופס המשולב. שנו את שמו או כתובתו באמצעות **עריכת שרת** ב־**הגדרות → שרתים**. @@ -93,7 +93,7 @@ codenomad --host 127.0.0.1 --https=false --http=true חלון מרוחק תמיד משאיר דרך לחזור למחשב הזה. סגירת החלון המקומי האחרון בזמן שחלונות מרוחקים נשארים פתוחים שומרת את הלשוניות שלו: **חלון → חלון חדש** בחלון מרוחק, או הפעלה מחדש של CodeNomad, פותחים אותו שוב. אם לא ניתן לטעון שרת, החלון שלו מציין זאת ומציע **נסו שוב**, **פתיחת חלון מקומי** ו**סגירת החלון**; בגרסת Tauri, השתמשו בכפתור הרענון של הדף וב־**חלון → חלון חדש**. -הדבקת קישור של שליטה מרחוק שומרת רק את מקור המנהרה ומדווחת שצימוד בצד השרת אינו זמין; הקוד נמחק. פתחו את הקישור בדפדפן הרצוי לצימוד שם. ראו [שליטה מרחוק](remote-control.md). +הדבקת קישור חדש של שליטה מרחוק שומרת את מקור המנהרה ומצמדת את שרת הקצה המקומי לעיון; אישור המכשיר נשמר בפרטיות גם בין הפעלות. הקוד נמחק לאחר הניסיון. לאחר ביטול בחרו **חזרה לעיון** והדביקו קישור חדש ב־**כתובת או קישור של השרת**. תצוגות מוטמעות מצומדות בנפרד. אם צימוד בצד השרת אינו זמין, עדכנו את השרת המרוחק או השתמשו בכתובת ההאזנה הישירה שלו להתחברות בסיסמה; כתובות מנהרה דורשות צימוד. ראו [שליטה מרחוק](remote-control.md). ## פתיחת פרויקט מרוחק בלשונית {#remote-project-tabs} diff --git a/docs/help/he/remote-control.md b/docs/help/he/remote-control.md index dd6ebfc541..aca35a4d82 100644 --- a/docs/help/he/remote-control.md +++ b/docs/help/he/remote-control.md @@ -11,12 +11,16 @@ הקישור תקף ל־**חמש דקות** ומצליח **פעם אחת**. התייחסו אליו כאישור גישה: כל מי שמנצל אותו יכול להפוך למכשיר מצומד. הקוד נמצא במקטע הכתובת, לא במחרוזת השאילתה. **צור קישור צימוד חדש** מבטל מיד את הקישור הקודם שלא נוצל. עצירה, כיבוי שרת הקצה וכשל במנהרה מבטלים קישורי צימוד שטרם נוצלו. -פתחו קישורי צימוד בדפדפן הרצוי. הדבקה ב־**כתובת או קישור של השרת** בשולחן העבודה שומרת רק את מקור המנהרה ומציגה שצימוד בצד השרת אינו זמין. הקוד נמחק. עיון בתיקיות דרך שרת הקצה משתמש בסשן גישה ישירה משלו; התצוגה המוטמעת שומרת בנפרד את ההתחברות או עוגיית המכשיר שלה. +פתחו קישור צימוד בדפדפן הרצוי, או הדביקו קישור חדש ב־**כתובת או קישור של השרת** בשולחן העבודה כדי לשמור את השרת ולצמד את שרת הקצה המקומי לעיון בתיקיות דרך שליטה מרחוק. כל קישור פועל פעם אחת בלבד בשתי השיטות יחד. שרת הקצה שומר את אישור המכשיר באופן פרטי גם בין הפעלות; הקוד נמחק לאחר הניסיון. תצוגות מוטמעות וחלונות מרוחקים שומרים אימות משלהם ועשויים לדרוש קישור צימוד נפרד. + +צימודי שרת הקצה מופיעים כ־`CodeNomad · <שם המארח של שרת הקצה>`. שם המארח הוא תווית שהלקוח מדווח בעצמו; בדקו את היעד ואת תעודת ה־TLS שלו לפני שיתוף קישור. הסרת השרת השמור מוחקת את אישור העיון המקומי שלו; ביטול המכשיר מסיים את הגישה. לשחזור העיון בחרו **חזרה לעיון** והדביקו קישור חדש ב־**כתובת או קישור של השרת**. לקוד שפג תוקפו או שכבר נוצל צרו קישור חדש; בשגיאת הגבלת קצב המתינו לפני ניסיון נוסף. צימוד שרת הקצה מאפשר עשרה ניסיונות בדקה לכל לקוחות שרת הקצה המרוחק יחד. + +אם השרת המרוחק מדווח שצימוד בצד השרת אינו זמין, עדכנו אותו או שמרו את כתובת ההאזנה הישירה שלו כדי להשתמש בטופס הסיסמה המובנה. התחברות בסיסמה זמינה בגישה ישירה; כתובת מנהרה דורשת צימוד. ## ניהול מכשירים מצומדים {#paired-devices} 1. במארח, חזרו אל **הגדרות → גישה מרוחקת → שליטה מרחוק**. -2. בדקו **מכשירים מצומדים** ואת זמן **נראה לאחרונה** שלהם. כל מכשיר נקרא על שם הפלטפורמה והדפדפן שצימדו אותו, כגון `iPhone · Safari`. +2. בדקו **מכשירים מצומדים** ואת זמן **נראה לאחרונה** שלהם. צימודי דפדפן נקראים על שם הפלטפורמה והדפדפן שלהם, כגון `iPhone · Safari`. 3. בחרו **בטל גישה** למכשיר שכבר לא אמור להתחבר. ביטול גישה מסיים את חיבורי HTTP/SSE הנוכחיים של המכשיר וגם גישה עתידית. בצעו צימוד מחדש בקישור חדש לשחזור הגישה. מכשיר פג לאחר **30 ימים ללא שימוש**. ב־**מגבלת 32 מכשירים**, צימוד חדש מחליף את המכשיר שנראה לפני הזמן הרב ביותר וסוגר את חיבוריו. diff --git a/docs/help/ja/remote-access.md b/docs/help/ja/remote-access.md index a17bce8f47..9851a32cbc 100644 --- a/docs/help/ja/remote-access.md +++ b/docs/help/ja/remote-access.md @@ -83,7 +83,7 @@ HTTPS が有効で鍵/証明書のペアを指定していない場合、CodeN ## リモートサーバーを保存する {#saved-servers} -1. ホーム、空のタブ、**タブを開く** ランチャーで **参照** を開き、アドレスまたはペアリングリンクを **サーバーのアドレスまたはリンク** に入力します。貼り付けは即座に追加し、手入力は Enter で追加します。サーバーはホスト名で保存され、その行にフォーカスが移ります。ランチャーは開いたままです。行をクリックすると、その場でプロジェクトを参照できます。**設定 → サーバー** にも同じ入力欄があります。 +1. ホーム、空のタブ、**タブを開く** ランチャーで **参照** を開き、アドレスまたはペアリングリンクを **サーバーのアドレスまたはリンク** に入力します。貼り付けは即座に追加し、手入力は Enter で追加します。サーバーはホスト名で保存され、その行にフォーカスが移ります。ペアリングリンクでは参照用のローカルバックエンドもペアリングします。ランチャーは開いたままです。行をクリックすると、その場でプロジェクトを参照できます。**設定 → サーバー** にも同じ入力欄があります。 2. 信頼できる HTTPS オリジンを使ってください。証明書の検証に失敗した場合、入力欄の下に **TLS 検証をスキップ** が表示されます。信頼できるサーバーだけでオンにして Enter で保存します。このプロファイルのフォルダーやプロジェクトを選ぶと専用ウィンドウで開きます。 3. **参照** の保存済みサーバー行を選ぶと、その場でプロジェクトを参照できます。求められたらインラインフォームにユーザー名とパスワードを入力します。名前やアドレスは **設定 → サーバー** の **サーバーを編集** で変更できます。 @@ -93,7 +93,7 @@ HTTPS が有効で鍵/証明書のペアを指定していない場合、CodeN リモートウィンドウからは、いつでもこのコンピューターに戻れます。リモートウィンドウを開いたまま最後のローカルウィンドウを閉じても、そのタブは保持されます。リモートウィンドウの **ウィンドウ → 新規ウィンドウ**、または CodeNomad の再起動で再び開きます。サーバーを読み込めない場合は、そのウィンドウにその旨が表示され、**再試行**、**ローカルウィンドウを開く**、**ウィンドウを閉じる** を選べます。Tauri 版では、ページの再読み込みボタンと **ウィンドウ → 新規ウィンドウ** を使用します。 -リモートコントロールのリンクを貼り付けるとトンネルのオリジンのみが保存され、サーバー側のペアリングが利用できない旨が表示されます。コードは破棄されます。ペアリングするブラウザーでリンクを開いてください。[リモートコントロール](remote-control.md)を参照してください。 +新しいリモートコントロールのリンクを貼り付けると、トンネルのオリジンを保存し、参照用のローカルバックエンドをペアリングします。デバイス認証情報は非公開で再起動後も保持され、コードは試行後に破棄されます。取り消し後は **参照に戻る** を選び、新しいリンクを **サーバーのアドレスまたはリンク** に貼り付けてください。埋め込みビューは別途ペアリングします。サーバー側のペアリングが利用できない場合は、リモートサーバーを更新するか、パスワードログインに直接アクセス用リスナーの URL を使ってください。トンネルアドレスにはペアリングが必要です。[リモートコントロール](remote-control.md)を参照してください。 ## リモートプロジェクトをタブで開く {#remote-project-tabs} diff --git a/docs/help/ja/remote-control.md b/docs/help/ja/remote-control.md index bf0d15076b..0e2010a8aa 100644 --- a/docs/help/ja/remote-control.md +++ b/docs/help/ja/remote-control.md @@ -11,12 +11,16 @@ リンクの有効期間は **5 分**、成功するのは **1 回** です。利用した人はペアリング済み端末になれるため、認証情報として扱ってください。コードはクエリ文字列ではなく URL フラグメントに入ります。**新しいペアリングリンクを作成** は、直前の未使用リンクを即座に無効化します。停止、バックエンドの終了、トンネル障害は、未使用のペアリングリンクをキャンセルします。 -ペアリングリンクは使用するブラウザーで開いてください。デスクトップの **サーバーのアドレスまたはリンク** に貼り付けると、トンネルのオリジンのみが保存され、サーバー側のペアリングが利用できない旨が表示されます。コードは破棄されます。バックエンドのフォルダー参照は専用の直接アクセスセッションを使い、埋め込みビューは独立したサインインやデバイス Cookie を保持します。 +ペアリングリンクを使用するブラウザーで開くか、新しいリンクをデスクトップの **サーバーのアドレスまたはリンク** に貼り付けてください。後者はサーバーを保存し、リモートコントロール経由でフォルダーを参照できるようローカルバックエンドをペアリングします。各リンクは両方の方法を通じて1回だけ使用できます。バックエンドはデバイス認証情報を非公開で保持し、再起動後も使用します。コードは試行後に破棄されます。埋め込みビューとリモートウィンドウは独立した認証を使用し、別のリンクが必要になる場合があります。 + +バックエンドのペアリングは `CodeNomad · <バックエンドのホスト名>` と表示されます。ホスト名はクライアントの自己申告によるラベルです。リンクを共有する前に接続先と TLS 証明書を確認してください。保存済みサーバーを削除するとローカルの参照用認証情報が削除され、デバイスを取り消すとアクセスが終了します。参照を復旧するには **参照に戻る** を選び、新しいリンクを **サーバーのアドレスまたはリンク** に貼り付けます。期限切れや使用済みのコードには新しいリンクを作成し、試行回数の制限では待ってから再試行してください。バックエンドのペアリングは、リモートバックエンドの全クライアント合計で毎分10回までです。 + +サーバー側のペアリングが利用できない場合は、リモートサーバーを更新するか、直接アクセス用リスナーの URL を保存してインラインのパスワードフォームを使ってください。パスワードログインは直接アクセスで利用でき、トンネルアドレスにはペアリングが必要です。 ## ペアリング済み端末を管理する {#paired-devices} 1. ホストで **設定 → リモートアクセス → リモートコントロール** に戻ります。 -2. **ペアリング済み端末** と **最終アクセス** の時刻を確認します。各端末には、`iPhone · Safari` のように、ペアリングしたプラットフォームとブラウザーにちなんだ名前が付きます。 +2. **ペアリング済み端末** と **最終アクセス** の時刻を確認します。ブラウザーでのペアリングには、`iPhone · Safari` のように、そのプラットフォームとブラウザーにちなんだ名前が付きます。 3. 接続を許可しなくなった端末には **取り消す** を選びます。 取り消しは、その端末の現在の HTTP/SSE 接続と将来のアクセスを終了します。復旧するには新しいリンクで再ペアリングします。端末は **30 日間未使用** で期限切れになります。**上限の 32 台** に達すると、新しいペアリングは最も長く見られていない端末を置き換え、その接続を閉じます。 diff --git a/docs/help/ne/remote-access.md b/docs/help/ne/remote-access.md index c63c244896..ef9aa1d9cf 100644 --- a/docs/help/ne/remote-access.md +++ b/docs/help/ne/remote-access.md @@ -83,7 +83,7 @@ certificate चेतावनी आए रोकिएर hostname, SAN, trust ## remote server बचत {#saved-servers} -1. गृह पृष्ठ, खाली ट्याब वा **ट्याब खोल्नुहोस्** लन्चरमा **ब्राउज गर्नुहोस्** खोली ठेगाना वा pairing link **सर्भरको ठेगाना वा लिङ्क** मा राख्नुहोस्। टाँस्दा तुरुन्त थपिन्छ; टाइप गरेको पाठ Enter ले थप्छ। सर्भर host name मा बचत मात्र हुन्छ र यसको पङ्क्तिमा focus जान्छ; लन्चर खुलै रहन्छ। त्यही सूचीमा परियोजना हेर्न पङ्क्ति क्लिक गर्नुहोस्। **सेटिङहरू → सर्भरहरू** मा पनि यही फिल्ड छ। +1. गृह पृष्ठ, खाली ट्याब वा **ट्याब खोल्नुहोस्** लन्चरमा **ब्राउज गर्नुहोस्** खोली ठेगाना वा pairing link **सर्भरको ठेगाना वा लिङ्क** मा राख्नुहोस्। टाँस्दा तुरुन्त थपिन्छ; टाइप गरेको पाठ Enter ले थप्छ। सर्भर host name मा बचत हुन्छ र यसको पङ्क्तिमा focus जान्छ; pairing link ले browsing का लागि local backend पनि pair गर्छ। लन्चर खुलै रहन्छ। त्यही सूचीमा परियोजना हेर्न पङ्क्ति क्लिक गर्नुहोस्। **सेटिङहरू → सर्भरहरू** मा पनि यही फिल्ड छ। 2. विश्वसनीय HTTPS origin प्रयोग गर्नुहोस्। प्रमाणपत्र जाँच असफल भए फिल्डमुनि **TLS प्रमाणीकरण छोड्नुहोस्** देखिन्छ: विश्वसनीय सर्भरका लागि मात्र चिन्ह लगाई बचत गर्न फेरि Enter थिच्नुहोस्। यो profile को folder वा परियोजना छान्दा आफ्नै विन्डोमा खुल्छ। 3. **ब्राउज गर्नुहोस्** मा सर्भरको पङ्क्ति छानेर त्यही सूचीमा परियोजना हेर्नुहोस्। मागिएमा inline form मा username र password दिनुहोस्। नाम वा ठेगाना **सेटिङहरू → सर्भरहरू** को **सर्भर सम्पादन गर्नुहोस्** बाट बदल्नुहोस्। @@ -93,7 +93,7 @@ certificate चेतावनी आए रोकिएर hostname, SAN, trust रिमोट विन्डोले यो कम्प्युटरमा फर्कने बाटो सधैँ छोड्छ। रिमोट विन्डोहरू खुला रहँदा अन्तिम स्थानीय विन्डो बन्द गर्दा त्यसका ट्याबहरू रहन्छन्: रिमोट विन्डोमा **सञ्झ्याल → नयाँ विन्डो**, वा CodeNomad फेरि सुरु गर्दा त्यो फेरि खुल्छ। सर्भर लोड गर्न नसकिँदा त्यसको विन्डोले त्यो देखाउँछ र **फेरि प्रयास गर्नुहोस्**, **स्थानीय विन्डो खोल्नुहोस्** र **विन्डो बन्द गर्नुहोस्** दिन्छ; Tauri संस्करणमा पृष्ठको रिलोड बटन र **सञ्झ्याल → नयाँ विन्डो** प्रयोग गर्नुहोस्। -Remote Control link टाँस्दा tunnel origin मात्र बचत हुन्छ र server-side pairing उपलब्ध नभएको त्रुटि देखिन्छ; code हटाइन्छ। Pair गर्न इच्छित browser मा link खोल्नुहोस्। [Remote Control](remote-control.md) हेर्नुहोस्। +नयाँ Remote Control link टाँस्दा tunnel origin बचत हुन्छ र browsing का लागि local backend pair हुन्छ। यसको device credential निजी रूपमा अर्को launch सम्म पनि रहन्छ; प्रयासपछि code हटाइन्छ। Revocation पछि **ब्राउजमा फर्कनुहोस्** छानी नयाँ link **सर्भरको ठेगाना वा लिङ्क** मा टाँस्नुहोस्। Embedded view छुट्टै pair हुन्छ। Server-side pairing उपलब्ध नभए remote server update गर्नुहोस् वा password login का लागि यसको direct-listener URL प्रयोग गर्नुहोस्; tunnel address लाई pairing चाहिन्छ। [Remote Control](remote-control.md) हेर्नुहोस्। ## रिमोट परियोजना ट्याबमा खोल्नुहोस् {#remote-project-tabs} diff --git a/docs/help/ne/remote-control.md b/docs/help/ne/remote-control.md index a576bf41be..4673e94562 100644 --- a/docs/help/ne/remote-control.md +++ b/docs/help/ne/remote-control.md @@ -11,12 +11,16 @@ Remote Control ले paired browser वा desktop client लाई inbound net link **पाँच मिनेट** मान्य हुन्छ र **एकपटक** सफल हुन्छ। credential झैं लिनुहोस्: प्रयोग गर्ने जोकोही paired device बन्न सक्छ। code URL fragment मा हुन्छ, query string मा होइन। **नयाँ जोडी लिंक बनाउनुहोस्** ले अघिल्लो unused link तुरुन्त अमान्य गर्छ। Stop, backend shutdown र tunnel failure ले बाँकी pairing link रद्द गर्छन्। -Pairing link इच्छित browser मा खोल्नुहोस्। Desktop को **सर्भरको ठेगाना वा लिङ्क** मा टाँस्दा tunnel origin मात्र बचत हुन्छ र server-side pairing उपलब्ध नभएको त्रुटि देखिन्छ। Code हटाइन्छ। Backend को folder browsing ले आफ्नै direct-access session प्रयोग गर्छ; embedded view ले आफ्नो sign-in वा device cookie स्वतन्त्र रूपमा राख्छ। +Pairing link इच्छित browser मा खोल्नुहोस्, वा नयाँ link desktop को **सर्भरको ठेगाना वा लिङ्क** मा टाँस्नुहोस्। यसले सर्भर बचत गरी Remote Control बाट folder browsing गर्न local backend pair गर्छ। दुवै विधि मिलाएर प्रत्येक link एक पटक मात्र चल्छ। Backend ले आफ्नो device credential निजी रूपमा राख्छ र अर्को launch मा पनि प्रयोग गर्छ; प्रयासपछि code हटाइन्छ। Embedded view र remote window का आफ्नै authentication हुन्छन् र छुट्टै pairing link चाहिन सक्छ। + +Backend pairing device सूचीमा `CodeNomad · ` देखिन्छ। Hostname client ले आफैँ दिएको label हो; link बाँड्नुअघि destination र TLS certificate जाँच्नुहोस्। बचत गरिएको सर्भर हटाउँदा यसको local browsing credential मेटिन्छ; device revoke गर्दा पहुँच बन्द हुन्छ। Browsing फर्काउन **ब्राउजमा फर्कनुहोस्** छानी नयाँ link **सर्भरको ठेगाना वा लिङ्क** मा टाँस्नुहोस्। Expired वा प्रयोग भइसकेको code भए नयाँ link बनाउनुहोस्; rate-limit त्रुटि भए फेरि प्रयास गर्नुअघि पर्खनुहोस्। Backend pairing मा remote backend का सबै client मिलाएर प्रति मिनेट दस प्रयासको सीमा छ। + +Remote server ले server-side pairing उपलब्ध नभएको देखाएमा त्यसलाई update गर्नुहोस् वा inline password form प्रयोग गर्न यसको direct-listener URL बचत गर्नुहोस्। Password login direct access बाट उपलब्ध हुन्छ; tunnel address लाई pairing चाहिन्छ। ## paired device व्यवस्थापन {#paired-devices} 1. host मा **सेटिङहरू → रिमोट पहुँच → रिमोट कन्ट्रोल** फर्कनुहोस्। -2. **जोडिएका उपकरणहरू** र तिनको **अन्तिम पटक:** समय समीक्षा गर्नुहोस्। हरेक device लाई त्यसलाई pair गर्ने platform र browser अनुसार नाम दिइन्छ, जस्तै `iPhone · Safari`। +2. **जोडिएका उपकरणहरू** र तिनको **अन्तिम पटक:** समय समीक्षा गर्नुहोस्। Browser pairing लाई त्यसको platform र browser अनुसार नाम दिइन्छ, जस्तै `iPhone · Safari`। 3. अब जोडिन नहुने device का लागि **हटाउनुहोस्** रोज्नुहोस्। revocation ले हालका HTTP/SSE जडान र भावी पहुँच दुवै अन्त्य गर्छ। पहुँच फर्काउन नयाँ link बाट pair गर्नुहोस्। device **30 दिन प्रयोग नभएपछि** expire हुन्छ। **32-device सीमा** मा नयाँ pairing ले सबैभन्दा पुरानो last-seen device बदल्छ र त्यसका जडान बन्द गर्छ। diff --git a/docs/help/ru/remote-access.md b/docs/help/ru/remote-access.md index 868e7a9406..fd47d8edea 100644 --- a/docs/help/ru/remote-access.md +++ b/docs/help/ru/remote-access.md @@ -83,7 +83,7 @@ codenomad --host 127.0.0.1 --https=false --http=true ## Сохранение удалённого сервера {#saved-servers} -1. На главной странице, пустой вкладке или в панели **Открыть вкладку** откройте **Обзор** и введите адрес или ссылку сопряжения в **Адрес или ссылка сервера**. Вставка добавляет сразу, Enter подтверждает набранный текст. Сервер только сохраняется под именем хоста, фокус переходит на его строку; панель остаётся открытой. Нажмите на строку для просмотра проектов на месте. В **Настройки → Серверы** есть то же поле. +1. На главной странице, пустой вкладке или в панели **Открыть вкладку** откройте **Обзор** и введите адрес или ссылку сопряжения в **Адрес или ссылка сервера**. Вставка добавляет сразу, Enter подтверждает набранный текст. Сервер сохраняется под именем хоста, фокус переходит на его строку; ссылка сопряжения также сопрягает локальную серверную часть для просмотра. Панель остаётся открытой. Нажмите на строку для просмотра проектов на месте. В **Настройки → Серверы** есть то же поле. 2. Используйте доверенный HTTPS-источник. Если сертификат не прошёл проверку, под полем появится **Пропустить проверку TLS**: включайте это только для доверенного сервера и снова нажмите Enter для сохранения. Выбор папки или проекта этого профиля открывает отдельное окно. 3. Выберите строку сервера в **Обзор**, чтобы просматривать проекты на месте. При запросе введите имя пользователя и пароль во встроенной форме. Имя и адрес меняются через **Изменить сервер** в **Настройки → Серверы**. @@ -93,7 +93,7 @@ codenomad --host 127.0.0.1 --https=false --http=true Из удалённого окна всегда можно вернуться на этот компьютер. Если закрыть последнее локальное окно, пока удалённые окна остаются открытыми, его вкладки сохраняются: **Окно → Новое окно** в удалённом окне или повторный запуск CodeNomad открывает его снова. Если сервер не удаётся загрузить, его окно сообщает об этом и предлагает **Повторить**, **Открыть локальное окно** и **Закрыть окно**; в версии Tauri используйте кнопку перезагрузки страницы и **Окно → Новое окно**. -Вставка ссылки удалённого управления сохраняет только origin туннеля и сообщает о недоступности сопряжения на стороне сервера; код удаляется. Для сопряжения откройте ссылку в нужном браузере. См. [удалённое управление](remote-control.md). +Вставка свежей ссылки удалённого управления сохраняет origin туннеля и сопрягает локальную серверную часть для просмотра. Учётные данные устройства хранятся приватно между запусками; код удаляется после попытки. После отзыва выберите **Назад к обзору** и вставьте свежую ссылку в **Адрес или ссылка сервера**. Встроенные представления сопрягаются отдельно. Если сопряжение на стороне сервера недоступно, обновите удалённый сервер или используйте URL его прямого слушателя для входа по паролю; адреса туннеля требуют сопряжения. См. [удалённое управление](remote-control.md). ## Открыть удалённый проект во вкладке {#remote-project-tabs} diff --git a/docs/help/ru/remote-control.md b/docs/help/ru/remote-control.md index dcc1f09571..51c005d3f2 100644 --- a/docs/help/ru/remote-control.md +++ b/docs/help/ru/remote-control.md @@ -11,12 +11,16 @@ Ссылка действует **пять минут** и срабатывает **один раз**. Считайте её учётными данными: любой использовавший её может стать сопряжённым устройством. Код находится во фрагменте URL, не в строке запроса. **Создать новую ссылку сопряжения** немедленно делает предыдущую неиспользованную ссылку недействительной. Остановка, завершение серверной части и сбой туннеля отменяют ожидающие ссылки сопряжения. -Открывайте ссылки сопряжения в нужном браузере. Вставка в **Адрес или ссылка сервера** настольного приложения сохраняет только origin туннеля и сообщает, что сопряжение на стороне сервера недоступно. Код удаляется. Просмотр папок через серверную часть использует собственный сеанс прямого доступа; встроенное представление независимо хранит свой вход или cookie устройства. +Откройте ссылку сопряжения в нужном браузере или вставьте свежую ссылку в **Адрес или ссылка сервера** настольного приложения. Это сохраняет сервер и сопрягает локальную серверную часть для просмотра папок через удалённое управление. Каждая ссылка действует один раз на оба способа вместе. Серверная часть хранит учётные данные устройства в закрытом хранилище между запусками; код удаляется после попытки. Встроенные представления и удалённые окна используют собственную аутентификацию и могут потребовать отдельную ссылку. + +Сопряжения серверной части отображаются как `CodeNomad · <имя хоста серверной части>`. Имя хоста — метка, сообщённая самим клиентом; перед передачей ссылки проверьте адрес назначения и его сертификат TLS. Удаление сохранённого сервера стирает его локальные учётные данные просмотра; отзыв устройства прекращает доступ. Для восстановления выберите **Назад к обзору** и вставьте свежую ссылку в **Адрес или ссылка сервера**. Для просроченного или использованного кода создайте новую ссылку; при ограничении частоты подождите перед повторной попыткой. Сопряжение серверной части допускает десять попыток в минуту суммарно для всех клиентов удалённой серверной части. + +Если удалённый сервер сообщает о недоступности сопряжения на стороне сервера, обновите его или сохраните URL его прямого слушателя для встроенной формы пароля. Вход по паролю доступен через прямое подключение; адрес туннеля требует сопряжения. ## Управление сопряжёнными устройствами {#paired-devices} 1. На хосте вернитесь в **Настройки → Удалённый доступ → Удалённое управление**. -2. Проверьте **Сопряжённые устройства** и время **Последняя активность**. Каждое устройство названо по платформе и браузеру, с которых выполнено сопряжение, например `iPhone · Safari`. +2. Проверьте **Сопряжённые устройства** и время **Последняя активность**. Сопряжения браузеров названы по их платформе и браузеру, например `iPhone · Safari`. 3. Нажмите **Отозвать** для устройства, которому больше нельзя подключаться. Отзыв завершает текущие HTTP/SSE-подключения устройства и будущий доступ. Для восстановления выполните сопряжение по новой ссылке. Устройство истекает после **30 дней без использования**. При **лимите 32 устройства** новое сопряжение заменяет устройство с самой давней активностью и закрывает его подключения. diff --git a/docs/help/tr/remote-access.md b/docs/help/tr/remote-access.md index 65b0f10ae2..99191d6818 100644 --- a/docs/help/tr/remote-access.md +++ b/docs/help/tr/remote-access.md @@ -83,7 +83,7 @@ Bir istemci bir sertifika uyarısı bildirirse, durdurun ve ana bilgisayar adın ## Uzak sunucuyu kaydedin {#saved-servers} -1. Ana sayfada, boş sekmede veya **Sekme aç** başlatıcısında **Gözat** bölümünü açıp adresi ya da eşleştirme bağlantısını **Sunucu adresi veya bağlantısı** alanına girin. Yapıştırma hemen ekler; Enter yazılan metni ekler. Sunucu yalnızca ana bilgisayar adıyla kaydedilir ve satırına odaklanılır; başlatıcı açık kalır. Projeleri aynı yerde taramak için bu satıra tıklayın. **Ayarlar → Sunucular** aynı alanı sunar. +1. Ana sayfada, boş sekmede veya **Sekme aç** başlatıcısında **Gözat** bölümünü açıp adresi ya da eşleştirme bağlantısını **Sunucu adresi veya bağlantısı** alanına girin. Yapıştırma hemen ekler; Enter yazılan metni ekler. Sunucu ana bilgisayar adıyla kaydedilir ve satırına odaklanılır; eşleştirme bağlantısı tarama için yerel arka ucu da eşleştirir. Başlatıcı açık kalır. Projeleri aynı yerde taramak için bu satıra tıklayın. **Ayarlar → Sunucular** aynı alanı sunar. 2. Güvenilir bir HTTPS kaynağı kullanın. Sertifika doğrulanamazsa alanın altında **TLS doğrulamasını atla** görünür: yalnızca güvendiğiniz sunucu için işaretleyip kaydetmek üzere yeniden Enter'a basın. Bu profilde klasör veya proje seçmek kendi penceresini açar. 3. Projeleri aynı yerde taramak için **Gözat** içindeki kayıtlı satırını seçin. İstenirse satır içi forma sunucu kullanıcı adını ve parolasını girin. Adı veya adresi **Ayarlar → Sunucular** içindeki **Sunucuyu düzenle** ile değiştirin. @@ -93,7 +93,7 @@ Kayıtlı bir sunucuyu doğrudan komut satırından açmak için masaüstü uygu Uzak pencere bu bilgisayara dönmenin bir yolunu her zaman bırakır. Uzak pencereler açık kalırken son yerel pencereyi kapatmak sekmelerini korur: uzak penceredeki **Pencere → Yeni pencere** ya da CodeNomad'ı yeniden başlatmak onu yeniden açar. Bir sunucu yüklenemezse penceresi bunu bildirir ve **Yeniden dene**, **Yerel pencere aç** ve **Pencereyi kapat** seçeneklerini sunar; Tauri sürümünde sayfanın yeniden yükleme düğmesini ve **Pencere → Yeni pencere** öğesini kullanın. -Uzaktan Kontrol bağlantısı yapıştırmak yalnızca tünel kökenini kaydeder ve sunucu tarafında eşleştirmenin kullanılamadığını bildirir; kod silinir. Eşleştirmek için bağlantıyı istediğiniz tarayıcıda açın. Bkz. [Uzaktan Kontrol](remote-control.md). +Yeni bir Uzaktan Kontrol bağlantısı yapıştırmak tünel kökenini kaydeder ve yerel arka ucu tarama için eşleştirir. Cihaz kimlik bilgisi başlatmalar arasında özel olarak saklanır; kod denemeden sonra silinir. İptal sonrasında **Gözat'a dön** seçeneğini kullanıp **Sunucu adresi veya bağlantısı** alanına yeni bağlantı yapıştırın. Gömülü görünümler ayrı eşleştirilir. Sunucu tarafında eşleştirme kullanılamıyorsa uzak sunucuyu güncelleyin veya parolayla giriş için doğrudan dinleyici URL'sini kullanın; tünel adresleri eşleştirme gerektirir. Bkz. [Uzaktan Kontrol](remote-control.md). ## Uzak bir projeyi sekmede açın {#remote-project-tabs} diff --git a/docs/help/tr/remote-control.md b/docs/help/tr/remote-control.md index 8ea0a1ba66..318562bcd7 100644 --- a/docs/help/tr/remote-control.md +++ b/docs/help/tr/remote-control.md @@ -11,12 +11,16 @@ Uzaktan Kontrol, eşleştirilmiş bir tarayıcının veya masaüstü istemcisini Bağlantı **beş dakika** süreyle geçerlidir ve **bir kez** başarılı olur. Bunu bir kimlik bilgisi olarak değerlendirin: Bunu tüketen herkes eşleştirilmiş bir cihaz haline gelebilir. Kod, sorgu dizesinde değil, URL parçasında bulunur. **Yeni eşleştirme bağlantısı oluştur**, önceki kullanılmayan bağlantıyı anında geçersiz kılar. Durdurma, arka uç kapatma ve tünel arızası, bekleyen eşleştirme bağlantılarını iptal eder. -Eşleştirme bağlantılarını istediğiniz tarayıcıda açın. Masaüstündeki **Sunucu adresi veya bağlantısı** alanına yapıştırmak yalnızca tünel kökenini kaydeder ve sunucu tarafında eşleştirmenin kullanılamadığını bildirir. Kod silinir. Arka uç klasör taraması kendi doğrudan erişim oturumunu kullanır; gömülü görünüm kendi oturumunu veya cihaz çerezini bağımsız olarak saklar. +Eşleştirme bağlantısını istediğiniz tarayıcıda açın veya yeni bir bağlantıyı masaüstündeki **Sunucu adresi veya bağlantısı** alanına yapıştırın. Bu, sunucuyu kaydeder ve Uzaktan Kontrol üzerinden klasör taraması için yerel arka ucu eşleştirir. Her bağlantı, iki yöntem arasında toplam bir kez çalışır. Arka uç cihaz kimlik bilgisini başlatmalar arasında özel olarak saklar; kod denemeden sonra silinir. Gömülü görünümler ve uzak pencereler kendi kimlik doğrulamalarını kullanır ve ayrı bir eşleştirme bağlantısı isteyebilir. + +Arka uç eşleştirmeleri `CodeNomad · ` olarak görünür. Ana bilgisayar adı istemcinin bildirdiği bir etikettir; bağlantıyı paylaşmadan önce hedefi ve TLS sertifikasını doğrulayın. Kayıtlı sunucuyu kaldırmak yerel tarama kimlik bilgisini siler; cihazı iptal etmek erişimi sonlandırır. Taramayı geri getirmek için **Gözat'a dön** seçeneğini kullanıp **Sunucu adresi veya bağlantısı** alanına yeni bağlantı yapıştırın. Süresi dolmuş veya kullanılmış kod için yeni bağlantı oluşturun; hız sınırı hatasında yeniden denemeden önce bekleyin. Arka uç eşleştirmesi, uzak arka ucun tüm istemcileri için toplam dakikada on denemeye izin verir. + +Uzak sunucu, sunucu tarafında eşleştirmenin kullanılamadığını bildirirse sunucuyu güncelleyin veya satır içi parola formunu kullanmak için doğrudan dinleyici URL'sini kaydedin. Parolayla giriş doğrudan erişimde kullanılabilir; tünel adresi eşleştirme gerektirir. ## Eşleştirilmiş cihazları yönetin {#paired-devices} 1. Ana bilgisayarda **Ayarlar → Uzak Erişim → Uzaktan Kontrol** öğesine dönün. -2. **Eşleştirilmiş cihazlar** ve **Son görülme** zamanlarını inceleyin. Her cihaz, onu eşleştiren platform ve tarayıcıya göre adlandırılır; örneğin `iPhone · Safari`. +2. **Eşleştirilmiş cihazlar** ve **Son görülme** zamanlarını inceleyin. Tarayıcı eşleştirmeleri platform ve tarayıcılarına göre adlandırılır; örneğin `iPhone · Safari`. 3. Artık bağlanmaması gereken cihaz için **İptal et** eylemini seçin. İptal, cihazın mevcut HTTP/SSE bağlantılarını ve gelecekteki erişimini sonlandırır. Yeniden erişim için yeni bağlantıyla eşleştirin. Cihazın süresi **30 gün kullanılmadığında** dolar. **32 cihaz sınırında**, yeni eşleştirme en uzun süredir görülmeyen cihazın yerini alır ve bağlantılarını kapatır. diff --git a/docs/help/zh-Hans/remote-access.md b/docs/help/zh-Hans/remote-access.md index 7d8f2d6e71..499c2423a6 100644 --- a/docs/help/zh-Hans/remote-access.md +++ b/docs/help/zh-Hans/remote-access.md @@ -83,7 +83,7 @@ codenomad --host 127.0.0.1 --https=false --http=true ## 保存远程服务器 {#saved-servers} -1. 在主页、空白标签页或**打开标签页**启动器中打开**浏览**,在**服务器地址或链接**中输入地址或配对链接。粘贴会立即添加,手动输入后按 Enter 添加。添加仅以主机名保存服务器并将焦点移到其行;启动器保持打开。点击该行可在原位浏览项目。**设置 → 服务器**也提供相同的输入框。 +1. 在主页、空白标签页或**打开标签页**启动器中打开**浏览**,在**服务器地址或链接**中输入地址或配对链接。粘贴会立即添加,手动输入后按 Enter 添加。添加会以主机名保存服务器并将焦点移到其行;配对链接还会为本地后端配对以供浏览。启动器保持打开。点击该行可在原位浏览项目。**设置 → 服务器**也提供相同的输入框。 2. 请使用受信任的 HTTPS 源。如果证书未通过检查,输入框下方会显示**跳过 TLS 验证**:仅对可信服务器勾选,再按 Enter 保存。选择此配置的文件夹或项目后,会在单独窗口打开。 3. 选择**浏览**中的已保存服务器行,即可在原位浏览项目。出现提示时,在内嵌表单中输入服务器用户名和密码。可在 **设置 → 服务器** 中通过 **编辑服务器** 更改名称或地址。 @@ -93,7 +93,7 @@ codenomad --host 127.0.0.1 --https=false --http=true 远程窗口始终保留返回本机的途径。在远程窗口仍打开时关闭最后一个本地窗口,会保留其标签页:在远程窗口中使用 **窗口 → 新建窗口**,或再次启动 CodeNomad,即可重新打开它。如果无法加载某个服务器,其窗口会说明情况,并提供 **重试**、**打开本地窗口** 和 **关闭窗口**;在 Tauri 版本中,请使用页面的重新加载按钮和 **窗口 → 新建窗口**。 -粘贴远程控制配对链接只会保存隧道来源,并提示服务器端配对不可用;配对码会被丢弃。请在目标浏览器中打开链接进行配对。参阅[远程控制](remote-control.md)。 +粘贴新的远程控制配对链接会保存隧道来源,并为本地后端配对以供浏览。设备凭据会私密保存并跨启动保留;配对码在尝试后丢弃。撤销后,请选择**返回浏览**,并将新链接粘贴到**服务器地址或链接**中。嵌入视图需单独配对。如果服务器端配对不可用,请更新远程服务器,或使用其直接监听地址进行密码登录;隧道地址需要配对。参阅[远程控制](remote-control.md)。 ## 在标签页中打开远程项目 {#remote-project-tabs} diff --git a/docs/help/zh-Hans/remote-control.md b/docs/help/zh-Hans/remote-control.md index 8c201a9fce..900d7ad662 100644 --- a/docs/help/zh-Hans/remote-control.md +++ b/docs/help/zh-Hans/remote-control.md @@ -11,12 +11,16 @@ 链接有效期为**五分钟**,只能成功使用**一次**。请将其视为凭据:任何消费它的人都能成为配对设备。配对码位于 URL 片段,而非查询字符串。**创建新的配对链接**会立即使上一个未使用链接失效。停止、后端关闭和隧道失败会取消未使用的配对链接。 -请在目标浏览器中打开配对链接。在桌面端的**服务器地址或链接**中粘贴链接只会保存隧道来源,并提示服务器端配对不可用。配对码会被丢弃。后端文件夹浏览使用独立的直接访问会话;嵌入视图独立保留其登录或设备 cookie。 +在目标浏览器中打开配对链接,或将新链接粘贴到桌面端的**服务器地址或链接**中,以保存服务器并为本地后端配对,通过远程控制浏览文件夹。每个链接在这两种方式中合计只能使用一次。后端会私密保存设备凭据,并在下次启动时继续使用;配对码在尝试后丢弃。嵌入视图和远程窗口使用独立的身份验证,可能需要另一个配对链接。 + +后端配对在设备列表中显示为 `CodeNomad · <后端主机名>`。主机名是客户端自行报告的标签;分享链接前,请确认目标地址及其 TLS 证书。移除已保存的服务器会删除本地浏览凭据;撤销其设备会终止访问。要恢复浏览,请选择**返回浏览**,并将新链接粘贴到**服务器地址或链接**中。配对码过期或已使用时,请创建新链接;遇到速率限制时,请等待后再试。后端配对对远程后端的所有客户端合计限制为每分钟十次尝试。 + +如果远程服务器提示服务器端配对不可用,请更新该服务器,或保存其直接监听地址以使用内嵌密码表单。密码登录适用于直接访问;隧道地址需要配对。 ## 管理配对设备 {#paired-devices} 1. 在主机返回**设置 → 远程访问 → 远程控制**。 -2. 检查**已配对设备**及其**上次活动**时间。每台设备以配对时所用的平台和浏览器命名,例如 `iPhone · Safari`。 +2. 检查**已配对设备**及其**上次活动**时间。浏览器配对以所用的平台和浏览器命名,例如 `iPhone · Safari`。 3. 对不应继续连接的设备选择**撤销**。 撤销会终止该设备当前的 HTTP/SSE 连接及未来访问。使用新链接重新配对即可恢复访问。设备**连续 30 天未使用**后过期。达到 **32 台设备上限**时,新配对会替换最久未见的设备并关闭其连接。 From 0720f8d59fe2f56c940f62b16b6352b26575de21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 6 Nov 2026 05:54:51 +0100 Subject: [PATCH 25/34] fix(remote): redeem valid pairing codes before throttling failures A global attempt quota allowed anonymous guesses to block every valid server pairing link. Check and atomically consume a valid code through the existing manager exchange before applying the failure bucket. Successful exchanges never count toward the quota; invalid bodies, guesses and replays retain the existing bounded failure responses and Retry-After behavior. Browser pairing, Origin checks and the device registry remain unchanged. The code contains 192 cryptographically random bits and lasts five minutes, making online guessing infeasible even when validity is checked before throttling. Document that entropy supplies guessing resistance while the failure quota must not deny legitimate holders, and update the ten help translations. Replayed the reviewer's original three probes, then converted the lockout proof into a regression that fails before the fix with 429 instead of 200. Keep the exact ten-wrong-then-valid case in the server unit tests and preserve the broader replayable review probes separately from that suite's browser-free runtime. Server typecheck, 69 targeted/review tests, the complete serial server suite (21 skips, no failures), 31 help tests and diff checks pass. No UI/native code changed and no running host was stopped. --- dev-docs/REMOTE_CONTROL.md | 14 ++- docs/help/de/remote-control.md | 2 +- docs/help/en/remote-control.md | 2 +- docs/help/es/remote-control.md | 2 +- docs/help/fr/remote-control.md | 2 +- docs/help/he/remote-control.md | 2 +- docs/help/ja/remote-control.md | 2 +- docs/help/ne/remote-control.md | 2 +- docs/help/ru/remote-control.md | 2 +- docs/help/tr/remote-control.md | 2 +- docs/help/zh-Hans/remote-control.md | 2 +- .../src/remote-control/server-pairing.test.ts | 17 ++- .../src/server/routes/remote-control.ts | 18 +-- .../p2-pairing-security-review.test.mts | 106 ++++++++++++++++++ 14 files changed, 152 insertions(+), 23 deletions(-) create mode 100644 scripts/fixtures/p2-pairing-security-review.test.mts diff --git a/dev-docs/REMOTE_CONTROL.md b/dev-docs/REMOTE_CONTROL.md index 85bdc9d06d..f74166d3c5 100644 --- a/dev-docs/REMOTE_CONTROL.md +++ b/dev-docs/REMOTE_CONTROL.md @@ -113,10 +113,16 @@ requirements. The direct listener returns 404. Never forge an `Origin` to pair. the calling backend on success. Code possession is the authorization; excluding ambient authentication and browser/preflight metadata confines this exchange to the explicit protocol while browser pairing keeps its own admission checks. -- A global bucket per remote backend allows ten attempts per minute on this - route and returns 429 with `Retry-After` when exhausted. This bounds redemption - work and guessing; competing clients can exhaust the shared bucket and delay - legitimate server pairing. Browser pairing retains its existing behavior. +- Valid codes are checked and atomically consumed through the manager exchange + before the global failure bucket: successful pairings always proceed, even + after an anonymous failure flood, and never count toward the quota. The bucket + allows ten failure responses per minute per remote backend, then returns 429 + with `Retry-After`. Replayed codes remain invalid and receive 401 or 429 according + to the failure budget. The cryptographically random 192-bit code expires after + 300 seconds; even at one million guesses per second, the chance of guessing it + is below 4.8 × 10^-50. Code entropy supplies the guessing resistance; the quota + throttles failure responses while keeping valid links redeemable. Browser + pairing has no failure quota and keeps its exact public `Origin` checks. - The device uses the shared registry's 30-day idle expiry, revocation and least-recently-seen eviction. Its display name is `CodeNomad · `: a self-reported label, with identity assurance supplied by code possession and diff --git a/docs/help/de/remote-control.md b/docs/help/de/remote-control.md index d554d1942a..7a3a47d092 100644 --- a/docs/help/de/remote-control.md +++ b/docs/help/de/remote-control.md @@ -13,7 +13,7 @@ Der Link gilt **fünf Minuten** und funktioniert **einmal**. Behandeln Sie ihn a Öffnen Sie einen Kopplungslink im gewünschten Browser oder fügen Sie einen frischen Link auf dem Desktop in **Serveradresse oder -link** ein. Dadurch wird der Server gespeichert und das lokale Backend für die Ordnersuche über die Fernsteuerung gekoppelt. Jeder Link funktioniert über beide Methoden hinweg genau einmal. Das Backend bewahrt seine Gerätezugangsdaten privat über Neustarts hinweg auf; der Code wird nach dem Versuch verworfen. Eingebettete Ansichten und entfernte Fenster verwenden ihre eigene Authentifizierung und benötigen gegebenenfalls einen eigenen Kopplungslink. -Backend-Kopplungen erscheinen als `CodeNomad · `. Der Hostname ist eine selbst angegebene Bezeichnung; prüfen Sie Ziel und TLS-Zertifikat, bevor Sie einen Link teilen. Das Entfernen des gespeicherten Servers löscht seine lokalen Zugangsdaten zur Ordnersuche; das Widerrufen seines Geräts beendet den Zugriff. Wählen Sie zur Wiederherstellung **Zurück zu Durchsuchen** und fügen Sie einen frischen Link in **Serveradresse oder -link** ein. Erstellen Sie bei abgelaufenen oder bereits verwendeten Codes einen neuen Link; warten Sie bei einer Ratenbegrenzung vor dem nächsten Versuch. Die Backend-Kopplung erlaubt insgesamt zehn Versuche pro Minute für alle Clients des entfernten Backends. +Backend-Kopplungen erscheinen als `CodeNomad · `. Der Hostname ist eine selbst angegebene Bezeichnung; prüfen Sie Ziel und TLS-Zertifikat, bevor Sie einen Link teilen. Das Entfernen des gespeicherten Servers löscht seine lokalen Zugangsdaten zur Ordnersuche; das Widerrufen seines Geräts beendet den Zugriff. Wählen Sie zur Wiederherstellung **Zurück zu Durchsuchen** und fügen Sie einen frischen Link in **Serveradresse oder -link** ein. Erstellen Sie bei abgelaufenen oder bereits verwendeten Codes einen neuen Link; warten Sie bei einer Ratenbegrenzung vor dem nächsten Versuch. Die Backend-Kopplung erlaubt insgesamt zehn Fehlerantworten pro Minute für alle Clients des entfernten Backends; gültige Links bleiben auch bei ausgeschöpftem Kontingent einlösbar. Meldet der entfernte Server, dass serverseitige Kopplung nicht verfügbar ist, aktualisieren Sie ihn oder speichern Sie seine direkte Listener-URL für das integrierte Passwortformular. Die Passwortanmeldung erfolgt über den Direktzugriff; eine Tunneladresse erfordert Kopplung. diff --git a/docs/help/en/remote-control.md b/docs/help/en/remote-control.md index efb18e3aa6..3b277df5a3 100644 --- a/docs/help/en/remote-control.md +++ b/docs/help/en/remote-control.md @@ -13,7 +13,7 @@ The link is valid for **five minutes** and succeeds **once**. Treat it as a cred Open a pairing link in the intended browser, or paste a fresh link into desktop **Server address or link** to save the server and pair the local backend for folder browsing through Remote Control. Each link works once across both methods. The backend keeps its device credential privately across launches; the code is discarded after the attempt. Embedded views and remote windows keep their own authentication and may need a separate pairing link. -Backend pairings appear as `CodeNomad · ` in the device list. The hostname is a self-reported label; verify the destination and its TLS certificate before sharing a link. Removing the saved server deletes its local browsing credential; revoking its device ends access. To restore browsing, choose **Back to Browse** and paste a fresh link into **Server address or link**. For an expired or already-used code, create a new link; for a rate-limit error, wait before retrying. Backend pairing allows ten attempts per minute across all clients of the remote backend. +Backend pairings appear as `CodeNomad · ` in the device list. The hostname is a self-reported label; verify the destination and its TLS certificate before sharing a link. Removing the saved server deletes its local browsing credential; revoking its device ends access. To restore browsing, choose **Back to Browse** and paste a fresh link into **Server address or link**. For an expired or already-used code, create a new link; for a rate-limit error, wait before retrying. Backend pairing allows ten failure responses per minute across all clients of the remote backend; valid links remain redeemable even when this quota is exhausted. If the remote server reports server-side pairing unavailable, update that server or save its direct-listener URL to use the inline password form. Password login is available through direct access; a tunnel address requires pairing. diff --git a/docs/help/es/remote-control.md b/docs/help/es/remote-control.md index 806429991e..6e93fe28b3 100644 --- a/docs/help/es/remote-control.md +++ b/docs/help/es/remote-control.md @@ -13,7 +13,7 @@ El enlace es válido durante **cinco minutos** y funciona **una vez**. Trátalo Abre un enlace de emparejamiento en el navegador deseado o pega uno nuevo en **Dirección o enlace del servidor** del escritorio para guardar el servidor y emparejar el backend local para explorar carpetas mediante Control remoto. Cada enlace funciona una sola vez entre ambos métodos. El backend conserva su credencial de dispositivo de forma privada entre inicios; el código se descarta tras el intento. Las vistas integradas y ventanas remotas conservan su propia autenticación y pueden necesitar otro enlace. -Los emparejamientos del backend aparecen como `CodeNomad · `. El nombre de host es una etiqueta declarada por el cliente; comprueba el destino y su certificado TLS antes de compartir un enlace. Eliminar el servidor guardado borra su credencial local de exploración; revocar su dispositivo termina el acceso. Para restaurarlo, elige **Volver a Explorar** y pega un enlace nuevo en **Dirección o enlace del servidor**. Si el código ha caducado o ya se ha usado, crea otro enlace; si aparece un límite de intentos, espera antes de reintentar. El emparejamiento del backend permite diez intentos por minuto entre todos los clientes del backend remoto. +Los emparejamientos del backend aparecen como `CodeNomad · `. El nombre de host es una etiqueta declarada por el cliente; comprueba el destino y su certificado TLS antes de compartir un enlace. Eliminar el servidor guardado borra su credencial local de exploración; revocar su dispositivo termina el acceso. Para restaurarlo, elige **Volver a Explorar** y pega un enlace nuevo en **Dirección o enlace del servidor**. Si el código ha caducado o ya se ha usado, crea otro enlace; si aparece un límite de intentos, espera antes de reintentar. El emparejamiento del backend permite diez respuestas de error por minuto entre todos los clientes del backend remoto; los enlaces válidos siguen siendo canjeables incluso cuando se agota esta cuota. Si el servidor remoto indica que el emparejamiento del lado del servidor no está disponible, actualízalo o guarda su URL de escucha directa para usar el formulario de contraseña integrado. El inicio de sesión con contraseña usa el acceso directo; una dirección de túnel requiere emparejamiento. diff --git a/docs/help/fr/remote-control.md b/docs/help/fr/remote-control.md index a9212cd7eb..c8e97e8d7e 100644 --- a/docs/help/fr/remote-control.md +++ b/docs/help/fr/remote-control.md @@ -13,7 +13,7 @@ Le lien est valable **cinq minutes** et réussit **une seule fois**. Traitez-le Ouvrez un lien d’appairage dans le navigateur voulu, ou collez un lien neuf dans **Adresse ou lien du serveur** sur le bureau pour enregistrer le serveur et appairer le backend local afin de parcourir les dossiers via le Contrôle à distance. Chaque lien fonctionne une seule fois, toutes méthodes confondues. Le backend conserve son identifiant d’appareil en privé entre les lancements ; le code est supprimé après la tentative. Les vues intégrées et fenêtres distantes conservent leur propre authentification et peuvent nécessiter un lien distinct. -Les appairages du backend apparaissent sous `CodeNomad · `. Le nom d’hôte est une étiquette déclarée par le client ; vérifiez la destination et son certificat TLS avant de partager un lien. Supprimer le serveur enregistré efface son identifiant local de parcours ; révoquer son appareil termine l’accès. Pour rétablir le parcours, choisissez **Retour à Parcourir** et collez un lien neuf dans **Adresse ou lien du serveur**. Pour un code expiré ou déjà utilisé, créez un nouveau lien ; en cas de limitation, attendez avant de réessayer. L’appairage du backend autorise dix tentatives par minute pour l’ensemble des clients du backend distant. +Les appairages du backend apparaissent sous `CodeNomad · `. Le nom d’hôte est une étiquette déclarée par le client ; vérifiez la destination et son certificat TLS avant de partager un lien. Supprimer le serveur enregistré efface son identifiant local de parcours ; révoquer son appareil termine l’accès. Pour rétablir le parcours, choisissez **Retour à Parcourir** et collez un lien neuf dans **Adresse ou lien du serveur**. Pour un code expiré ou déjà utilisé, créez un nouveau lien ; en cas de limitation, attendez avant de réessayer. L’appairage du backend autorise dix réponses d’échec par minute pour l’ensemble des clients du backend distant ; les liens valides restent utilisables même lorsque ce quota est épuisé. Si le serveur distant signale que l’appairage côté serveur est indisponible, mettez-le à jour ou enregistrez son URL d’écoute directe pour utiliser le formulaire de mot de passe intégré. La connexion par mot de passe passe par l’accès direct ; une adresse de tunnel exige un appairage. diff --git a/docs/help/he/remote-control.md b/docs/help/he/remote-control.md index aca35a4d82..b18af6d9e9 100644 --- a/docs/help/he/remote-control.md +++ b/docs/help/he/remote-control.md @@ -13,7 +13,7 @@ פתחו קישור צימוד בדפדפן הרצוי, או הדביקו קישור חדש ב־**כתובת או קישור של השרת** בשולחן העבודה כדי לשמור את השרת ולצמד את שרת הקצה המקומי לעיון בתיקיות דרך שליטה מרחוק. כל קישור פועל פעם אחת בלבד בשתי השיטות יחד. שרת הקצה שומר את אישור המכשיר באופן פרטי גם בין הפעלות; הקוד נמחק לאחר הניסיון. תצוגות מוטמעות וחלונות מרוחקים שומרים אימות משלהם ועשויים לדרוש קישור צימוד נפרד. -צימודי שרת הקצה מופיעים כ־`CodeNomad · <שם המארח של שרת הקצה>`. שם המארח הוא תווית שהלקוח מדווח בעצמו; בדקו את היעד ואת תעודת ה־TLS שלו לפני שיתוף קישור. הסרת השרת השמור מוחקת את אישור העיון המקומי שלו; ביטול המכשיר מסיים את הגישה. לשחזור העיון בחרו **חזרה לעיון** והדביקו קישור חדש ב־**כתובת או קישור של השרת**. לקוד שפג תוקפו או שכבר נוצל צרו קישור חדש; בשגיאת הגבלת קצב המתינו לפני ניסיון נוסף. צימוד שרת הקצה מאפשר עשרה ניסיונות בדקה לכל לקוחות שרת הקצה המרוחק יחד. +צימודי שרת הקצה מופיעים כ־`CodeNomad · <שם המארח של שרת הקצה>`. שם המארח הוא תווית שהלקוח מדווח בעצמו; בדקו את היעד ואת תעודת ה־TLS שלו לפני שיתוף קישור. הסרת השרת השמור מוחקת את אישור העיון המקומי שלו; ביטול המכשיר מסיים את הגישה. לשחזור העיון בחרו **חזרה לעיון** והדביקו קישור חדש ב־**כתובת או קישור של השרת**. לקוד שפג תוקפו או שכבר נוצל צרו קישור חדש; בשגיאת הגבלת קצב המתינו לפני ניסיון נוסף. צימוד שרת הקצה מאפשר עשר תגובות כשל בדקה לכל לקוחות שרת הקצה המרוחק יחד; קישורים תקפים נשארים ניתנים למימוש גם כשהמכסה מוצתה. אם השרת המרוחק מדווח שצימוד בצד השרת אינו זמין, עדכנו אותו או שמרו את כתובת ההאזנה הישירה שלו כדי להשתמש בטופס הסיסמה המובנה. התחברות בסיסמה זמינה בגישה ישירה; כתובת מנהרה דורשת צימוד. diff --git a/docs/help/ja/remote-control.md b/docs/help/ja/remote-control.md index 0e2010a8aa..b274e8ae59 100644 --- a/docs/help/ja/remote-control.md +++ b/docs/help/ja/remote-control.md @@ -13,7 +13,7 @@ ペアリングリンクを使用するブラウザーで開くか、新しいリンクをデスクトップの **サーバーのアドレスまたはリンク** に貼り付けてください。後者はサーバーを保存し、リモートコントロール経由でフォルダーを参照できるようローカルバックエンドをペアリングします。各リンクは両方の方法を通じて1回だけ使用できます。バックエンドはデバイス認証情報を非公開で保持し、再起動後も使用します。コードは試行後に破棄されます。埋め込みビューとリモートウィンドウは独立した認証を使用し、別のリンクが必要になる場合があります。 -バックエンドのペアリングは `CodeNomad · <バックエンドのホスト名>` と表示されます。ホスト名はクライアントの自己申告によるラベルです。リンクを共有する前に接続先と TLS 証明書を確認してください。保存済みサーバーを削除するとローカルの参照用認証情報が削除され、デバイスを取り消すとアクセスが終了します。参照を復旧するには **参照に戻る** を選び、新しいリンクを **サーバーのアドレスまたはリンク** に貼り付けます。期限切れや使用済みのコードには新しいリンクを作成し、試行回数の制限では待ってから再試行してください。バックエンドのペアリングは、リモートバックエンドの全クライアント合計で毎分10回までです。 +バックエンドのペアリングは `CodeNomad · <バックエンドのホスト名>` と表示されます。ホスト名はクライアントの自己申告によるラベルです。リンクを共有する前に接続先と TLS 証明書を確認してください。保存済みサーバーを削除するとローカルの参照用認証情報が削除され、デバイスを取り消すとアクセスが終了します。参照を復旧するには **参照に戻る** を選び、新しいリンクを **サーバーのアドレスまたはリンク** に貼り付けます。期限切れや使用済みのコードには新しいリンクを作成し、試行回数の制限では待ってから再試行してください。バックエンドのペアリングの失敗応答は、リモートバックエンドの全クライアント合計で毎分10回までです。この上限に達しても、有効なリンクは引き続き使用できます。 サーバー側のペアリングが利用できない場合は、リモートサーバーを更新するか、直接アクセス用リスナーの URL を保存してインラインのパスワードフォームを使ってください。パスワードログインは直接アクセスで利用でき、トンネルアドレスにはペアリングが必要です。 diff --git a/docs/help/ne/remote-control.md b/docs/help/ne/remote-control.md index 4673e94562..2c2ff26bca 100644 --- a/docs/help/ne/remote-control.md +++ b/docs/help/ne/remote-control.md @@ -13,7 +13,7 @@ link **पाँच मिनेट** मान्य हुन्छ र **ए Pairing link इच्छित browser मा खोल्नुहोस्, वा नयाँ link desktop को **सर्भरको ठेगाना वा लिङ्क** मा टाँस्नुहोस्। यसले सर्भर बचत गरी Remote Control बाट folder browsing गर्न local backend pair गर्छ। दुवै विधि मिलाएर प्रत्येक link एक पटक मात्र चल्छ। Backend ले आफ्नो device credential निजी रूपमा राख्छ र अर्को launch मा पनि प्रयोग गर्छ; प्रयासपछि code हटाइन्छ। Embedded view र remote window का आफ्नै authentication हुन्छन् र छुट्टै pairing link चाहिन सक्छ। -Backend pairing device सूचीमा `CodeNomad · ` देखिन्छ। Hostname client ले आफैँ दिएको label हो; link बाँड्नुअघि destination र TLS certificate जाँच्नुहोस्। बचत गरिएको सर्भर हटाउँदा यसको local browsing credential मेटिन्छ; device revoke गर्दा पहुँच बन्द हुन्छ। Browsing फर्काउन **ब्राउजमा फर्कनुहोस्** छानी नयाँ link **सर्भरको ठेगाना वा लिङ्क** मा टाँस्नुहोस्। Expired वा प्रयोग भइसकेको code भए नयाँ link बनाउनुहोस्; rate-limit त्रुटि भए फेरि प्रयास गर्नुअघि पर्खनुहोस्। Backend pairing मा remote backend का सबै client मिलाएर प्रति मिनेट दस प्रयासको सीमा छ। +Backend pairing device सूचीमा `CodeNomad · ` देखिन्छ। Hostname client ले आफैँ दिएको label हो; link बाँड्नुअघि destination र TLS certificate जाँच्नुहोस्। बचत गरिएको सर्भर हटाउँदा यसको local browsing credential मेटिन्छ; device revoke गर्दा पहुँच बन्द हुन्छ। Browsing फर्काउन **ब्राउजमा फर्कनुहोस्** छानी नयाँ link **सर्भरको ठेगाना वा लिङ्क** मा टाँस्नुहोस्। Expired वा प्रयोग भइसकेको code भए नयाँ link बनाउनुहोस्; rate-limit त्रुटि भए फेरि प्रयास गर्नुअघि पर्खनुहोस्। Backend pairing मा remote backend का सबै client मिलाएर प्रति मिनेट दस असफलता प्रतिक्रियाको सीमा छ; यो सीमा पुगे पनि मान्य link प्रयोग गर्न सकिन्छ। Remote server ले server-side pairing उपलब्ध नभएको देखाएमा त्यसलाई update गर्नुहोस् वा inline password form प्रयोग गर्न यसको direct-listener URL बचत गर्नुहोस्। Password login direct access बाट उपलब्ध हुन्छ; tunnel address लाई pairing चाहिन्छ। diff --git a/docs/help/ru/remote-control.md b/docs/help/ru/remote-control.md index 51c005d3f2..8d56164059 100644 --- a/docs/help/ru/remote-control.md +++ b/docs/help/ru/remote-control.md @@ -13,7 +13,7 @@ Откройте ссылку сопряжения в нужном браузере или вставьте свежую ссылку в **Адрес или ссылка сервера** настольного приложения. Это сохраняет сервер и сопрягает локальную серверную часть для просмотра папок через удалённое управление. Каждая ссылка действует один раз на оба способа вместе. Серверная часть хранит учётные данные устройства в закрытом хранилище между запусками; код удаляется после попытки. Встроенные представления и удалённые окна используют собственную аутентификацию и могут потребовать отдельную ссылку. -Сопряжения серверной части отображаются как `CodeNomad · <имя хоста серверной части>`. Имя хоста — метка, сообщённая самим клиентом; перед передачей ссылки проверьте адрес назначения и его сертификат TLS. Удаление сохранённого сервера стирает его локальные учётные данные просмотра; отзыв устройства прекращает доступ. Для восстановления выберите **Назад к обзору** и вставьте свежую ссылку в **Адрес или ссылка сервера**. Для просроченного или использованного кода создайте новую ссылку; при ограничении частоты подождите перед повторной попыткой. Сопряжение серверной части допускает десять попыток в минуту суммарно для всех клиентов удалённой серверной части. +Сопряжения серверной части отображаются как `CodeNomad · <имя хоста серверной части>`. Имя хоста — метка, сообщённая самим клиентом; перед передачей ссылки проверьте адрес назначения и его сертификат TLS. Удаление сохранённого сервера стирает его локальные учётные данные просмотра; отзыв устройства прекращает доступ. Для восстановления выберите **Назад к обзору** и вставьте свежую ссылку в **Адрес или ссылка сервера**. Для просроченного или использованного кода создайте новую ссылку; при ограничении частоты подождите перед повторной попыткой. Сопряжение серверной части допускает десять ответов об ошибке в минуту суммарно для всех клиентов удалённой серверной части; действующие ссылки можно использовать даже после исчерпания этой квоты. Если удалённый сервер сообщает о недоступности сопряжения на стороне сервера, обновите его или сохраните URL его прямого слушателя для встроенной формы пароля. Вход по паролю доступен через прямое подключение; адрес туннеля требует сопряжения. diff --git a/docs/help/tr/remote-control.md b/docs/help/tr/remote-control.md index 318562bcd7..349b45b3eb 100644 --- a/docs/help/tr/remote-control.md +++ b/docs/help/tr/remote-control.md @@ -13,7 +13,7 @@ Bağlantı **beş dakika** süreyle geçerlidir ve **bir kez** başarılı olur. Eşleştirme bağlantısını istediğiniz tarayıcıda açın veya yeni bir bağlantıyı masaüstündeki **Sunucu adresi veya bağlantısı** alanına yapıştırın. Bu, sunucuyu kaydeder ve Uzaktan Kontrol üzerinden klasör taraması için yerel arka ucu eşleştirir. Her bağlantı, iki yöntem arasında toplam bir kez çalışır. Arka uç cihaz kimlik bilgisini başlatmalar arasında özel olarak saklar; kod denemeden sonra silinir. Gömülü görünümler ve uzak pencereler kendi kimlik doğrulamalarını kullanır ve ayrı bir eşleştirme bağlantısı isteyebilir. -Arka uç eşleştirmeleri `CodeNomad · ` olarak görünür. Ana bilgisayar adı istemcinin bildirdiği bir etikettir; bağlantıyı paylaşmadan önce hedefi ve TLS sertifikasını doğrulayın. Kayıtlı sunucuyu kaldırmak yerel tarama kimlik bilgisini siler; cihazı iptal etmek erişimi sonlandırır. Taramayı geri getirmek için **Gözat'a dön** seçeneğini kullanıp **Sunucu adresi veya bağlantısı** alanına yeni bağlantı yapıştırın. Süresi dolmuş veya kullanılmış kod için yeni bağlantı oluşturun; hız sınırı hatasında yeniden denemeden önce bekleyin. Arka uç eşleştirmesi, uzak arka ucun tüm istemcileri için toplam dakikada on denemeye izin verir. +Arka uç eşleştirmeleri `CodeNomad · ` olarak görünür. Ana bilgisayar adı istemcinin bildirdiği bir etikettir; bağlantıyı paylaşmadan önce hedefi ve TLS sertifikasını doğrulayın. Kayıtlı sunucuyu kaldırmak yerel tarama kimlik bilgisini siler; cihazı iptal etmek erişimi sonlandırır. Taramayı geri getirmek için **Gözat'a dön** seçeneğini kullanıp **Sunucu adresi veya bağlantısı** alanına yeni bağlantı yapıştırın. Süresi dolmuş veya kullanılmış kod için yeni bağlantı oluşturun; hız sınırı hatasında yeniden denemeden önce bekleyin. Arka uç eşleştirmesi, uzak arka ucun tüm istemcileri için toplam dakikada on başarısızlık yanıtına izin verir; bu kota dolduğunda bile geçerli bağlantılar kullanılabilir. Uzak sunucu, sunucu tarafında eşleştirmenin kullanılamadığını bildirirse sunucuyu güncelleyin veya satır içi parola formunu kullanmak için doğrudan dinleyici URL'sini kaydedin. Parolayla giriş doğrudan erişimde kullanılabilir; tünel adresi eşleştirme gerektirir. diff --git a/docs/help/zh-Hans/remote-control.md b/docs/help/zh-Hans/remote-control.md index 900d7ad662..5ec0888c24 100644 --- a/docs/help/zh-Hans/remote-control.md +++ b/docs/help/zh-Hans/remote-control.md @@ -13,7 +13,7 @@ 在目标浏览器中打开配对链接,或将新链接粘贴到桌面端的**服务器地址或链接**中,以保存服务器并为本地后端配对,通过远程控制浏览文件夹。每个链接在这两种方式中合计只能使用一次。后端会私密保存设备凭据,并在下次启动时继续使用;配对码在尝试后丢弃。嵌入视图和远程窗口使用独立的身份验证,可能需要另一个配对链接。 -后端配对在设备列表中显示为 `CodeNomad · <后端主机名>`。主机名是客户端自行报告的标签;分享链接前,请确认目标地址及其 TLS 证书。移除已保存的服务器会删除本地浏览凭据;撤销其设备会终止访问。要恢复浏览,请选择**返回浏览**,并将新链接粘贴到**服务器地址或链接**中。配对码过期或已使用时,请创建新链接;遇到速率限制时,请等待后再试。后端配对对远程后端的所有客户端合计限制为每分钟十次尝试。 +后端配对在设备列表中显示为 `CodeNomad · <后端主机名>`。主机名是客户端自行报告的标签;分享链接前,请确认目标地址及其 TLS 证书。移除已保存的服务器会删除本地浏览凭据;撤销其设备会终止访问。要恢复浏览,请选择**返回浏览**,并将新链接粘贴到**服务器地址或链接**中。配对码过期或已使用时,请创建新链接;遇到速率限制时,请等待后再试。后端配对对远程后端的所有客户端合计限制为每分钟十次失败响应;即使配额耗尽,有效链接仍可使用。 如果远程服务器提示服务器端配对不可用,请更新该服务器,或保存其直接监听地址以使用内嵌密码表单。密码登录适用于直接访问;隧道地址需要配对。 diff --git a/packages/server/src/remote-control/server-pairing.test.ts b/packages/server/src/remote-control/server-pairing.test.ts index bbeaf1adce..b76d433dc7 100644 --- a/packages/server/src/remote-control/server-pairing.test.ts +++ b/packages/server/src/remote-control/server-pairing.test.ts @@ -76,6 +76,17 @@ test("browser/ambient auth headers and every non-POST fail before CORS without c assert.equal((await send(f.target(), f.code)).status, 200) }) +test("ten wrong codes cannot lock out a fresh valid code or permit its replay", async t => { + const f = await startRemoteSurface(t) + for (let i = 0; i < 10; i++) assert.equal((await send(f.target(), "x".repeat(32))).status, 401) + const valid = new URL(f.manager.createPairing().url).hash.slice(1) + assert.equal((await send(f.target(), valid)).status, 200) + assert.equal(f.manager.devices().length, 1) + assert.notEqual((await send(f.target(), valid)).status, 200) + assert.equal((await send(f.target(), valid, { path: "/api/remote-control/pair", headers: { origin: `https://${FAKE_TUNNEL_HOST}` } })).status, 401) + assert.equal(f.manager.devices().length, 1) +}) + test("strict bodies, expiry and wrong codes are refused; only the server route has a bounded limiter", async t => { let now = Date.now() const f = await startRemoteSurface(t, { now: () => now }) @@ -90,9 +101,13 @@ test("strict bodies, expiry and wrong codes are refused; only the server route h assert.equal((await send(f.target(), f.code)).status, 401) for (let i = 0; i < 5; i++) assert.equal((await send(f.target(), "x".repeat(32))).status, 401) const next = new URL(f.manager.createPairing().url).hash.slice(1) + assert.equal((await send(f.target(), next)).status, 200, "a valid code bypasses the failure quota") + assert.equal(f.manager.devices().length, 1) const limited = await send(f.target(), next) assert.equal(limited.status, 429) assert.match(String(limited.headers["retry-after"]), /^[1-6]?[0-9]$/) privateResponse(limited) - assert.equal((await send(f.target(), next, { path: "/api/remote-control/pair", headers: { origin: `https://${FAKE_TUNNEL_HOST}` } })).status, 200, "browser flow stays independent") + assert.equal((await send(f.target(), next, { path: "/api/remote-control/pair", headers: { origin: `https://${FAKE_TUNNEL_HOST}` } })).status, 401, "redemption consumes the shared browser code") + const browserCode = new URL(f.manager.createPairing().url).hash.slice(1) + assert.equal((await send(f.target(), browserCode, { path: "/api/remote-control/pair", headers: { origin: `https://${FAKE_TUNNEL_HOST}` } })).status, 200, "browser flow stays independent") }) diff --git a/packages/server/src/server/routes/remote-control.ts b/packages/server/src/server/routes/remote-control.ts index 09199449ea..cfae608f47 100644 --- a/packages/server/src/server/routes/remote-control.ts +++ b/packages/server/src/server/routes/remote-control.ts @@ -18,21 +18,23 @@ const PAIR_TEMPLATE_URL = new URL("./auth-pages/remote-pair.html", import.meta.u let pairTemplate: string | null = null export function registerRemoteControlRoutes(app: FastifyInstance, deps: RouteDeps) { - // One bounded global bucket per backend, independent of untrusted peer/forwarded metadata. - let attempts = 0 + // One failure bucket per backend, independent of untrusted peer/forwarded metadata. + let failedAttempts = 0 let resetsAt = 0 app.post(SERVER_PAIR_PATH, { bodyLimit: 4096, config: { cors: false } }, async (request, reply) => { reply.header("Cache-Control", "no-store") if (!isRemoteRequest(request)) return reply.code(404).send({ error: "Not found" }) if (!validServerPairRequest(request)) return reply.code(403).send({ error: "Server pairing request rejected" }) - const now = Date.now() - if (now >= resetsAt) { attempts = 0; resetsAt = now + 60_000 } - if (++attempts > 10) return reply.header("Retry-After", String(Math.max(1, Math.ceil((resetsAt - now) / 1000)))).code(429).send({ error: "Pairing rate limited" }) const parsed = ServerPairBody.safeParse(request.body) + // The 192-bit code is checked and consumed atomically before throttling failures; + // unauthenticated guesses must never lock out a holder of the valid code. + const paired = parsed.success ? deps.manager.exchangePairing(parsed.data.code, undefined, parsed.data.hostName) : null + if (paired) return { device: paired.device, credential: paired.token } + const now = Date.now() + if (now >= resetsAt) { failedAttempts = 0; resetsAt = now + 60_000 } + if (++failedAttempts > 10) return reply.header("Retry-After", String(Math.max(1, Math.ceil((resetsAt - now) / 1000)))).code(429).send({ error: "Pairing rate limited" }) if (!parsed.success) return reply.code(400).send({ error: "Invalid server pairing body" }) - const paired = deps.manager.exchangePairing(parsed.data.code, undefined, parsed.data.hostName) - if (!paired) return reply.code(401).send({ error: "This pairing link is invalid, already used or expired" }) - return { device: paired.device, credential: paired.token } + return reply.code(401).send({ error: "This pairing link is invalid, already used or expired" }) }) app.get("/api/remote-control/status", async (request) => { diff --git a/scripts/fixtures/p2-pairing-security-review.test.mts b/scripts/fixtures/p2-pairing-security-review.test.mts new file mode 100644 index 0000000000..22ec5f57a0 --- /dev/null +++ b/scripts/fixtures/p2-pairing-security-review.test.mts @@ -0,0 +1,106 @@ +// Reviewer probes, including real Chromium; kept separate from the browser-free server unit suite. +// node --import tsx --test scripts/fixtures/p2-pairing-security-review.test.mts +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import os from 'node:os' +import test from 'node:test' +import http from 'node:http' +import Fastify from 'fastify' +import { chromium } from 'playwright' +import { RemoteServerBrowseManager } from '../../packages/server/src/codenomad-servers/browse-manager' +import { CodeNomadServerCredentials } from '../../packages/server/src/codenomad-servers/credentials' +import { startFakeCodeNomad } from '../../packages/server/src/codenomad-servers/test-support/fake-codenomad' +import { registerRemoteServerBrowseRoutes } from '../../packages/server/src/server/routes/remote-server-browse' +import { getBrowserFramePolicy } from '../../packages/ui/src/components/browser-frame-security' +import { startRemoteSurface, FAKE_TUNNEL_HOST } from '../../packages/server/src/remote-control/test-support/surface' + +test('ten unauthenticated guesses cannot deny a valid server code, permit replay or lock out browser pairing', async t => { + const f = await startRemoteSurface(t) + const send = (code: string, browser = false) => new Promise((resolve, reject) => { + const body = JSON.stringify(browser ? { code } : { code, hostName: 'proof' }) + const request = http.request(`http://${f.target()}${browser ? '/api/remote-control/pair' : '/api/remote-control/server-pair'}`, { + method: 'POST', headers: { host: FAKE_TUNNEL_HOST, 'content-type': 'application/json', 'content-length': Buffer.byteLength(body), + ...(browser ? { origin: `https://${FAKE_TUNNEL_HOST}` } : { 'x-codenomad-server-pairing': '1' }) }, + }, response => { response.resume(); response.on('end', () => resolve(response.statusCode!)) }) + request.on('error', reject) + request.end(body) + }) + for (let i = 0; i < 10; i++) assert.equal(await send('x'.repeat(32)), 401) + const valid = new URL(f.manager.createPairing().url).hash.slice(1) + assert.equal(await send(valid), 200, 'invalid guesses cannot block the holder of a valid code') + assert.equal(f.manager.devices().length, 1) + assert.notEqual(await send(valid), 200, 'server replay cannot issue another device') + assert.equal(await send(valid, true), 401, 'server redemption also consumes the browser code') + assert.equal(f.manager.devices().length, 1) + for (let i = 0; i < 10; i++) assert.equal(await send('x'.repeat(32), true), 401) + const browserCode = new URL(f.manager.createPairing().url).hash.slice(1) + assert.equal(await send(browserCode, true), 200, 'browser pairing has no lockout from server failures') + assert.equal(f.manager.devices().length, 2) +}) + +test('real browser: foreign, opaque extension and DNS-rebinding origins fail; trusted same-origin SideCar retains documented application authority', async t => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'p2-browser-guard-')) + t.after(() => fs.rmSync(dir, { recursive: true, force: true })) + const remote = await startFakeCodeNomad() + t.after(() => remote.close()) + const manager = new RemoteServerBrowseManager({ getOwner: () => ({ remoteServers: [{ id: 'saved', baseUrl: remote.origin }] }), configYamlPathForAuthority: () => path.join(dir, 'config.yaml') }) + t.after(() => manager.close()) + await manager.connect('saved', { username: 'codenomad', password: 'remote-password' }) + const app = Fastify() + let origin = '' + registerRemoteServerBrowseRoutes(app, { manager, getSelfOrigins: () => new Set([origin]) }) + app.get('/', (_, reply) => reply.type('text/html').send('Host')) + app.get('/sidecars/proof/', (_, reply) => reply.type('text/html').send(``)) + origin = await app.listen({ host: '127.0.0.1', port: 0 }) + t.after(() => app.close()) + const browser = await chromium.launch() + t.after(() => browser.close()) + const page = await browser.newPage() + await page.goto(origin) + const before = remote.state.requests.length + const opaque = await page.evaluate(() => new Promise(resolve => { + window.addEventListener('message', event => resolve(event.data), { once: true }) + const frame = document.createElement('iframe') + frame.sandbox.add('allow-scripts') + frame.src = '/sidecars/proof/' + document.body.append(frame) + })) + assert.equal(opaque.blocked, true) + assert.equal(remote.state.requests.length, before) + // A rebinding hostname still presents the attacker's Origin, not the saved self origin. + for (const source of ['http://rebind.attacker.invalid', 'https://remote-page.invalid', 'null']) { + const response = await app.inject({ method: 'POST', url: '/api/remote-servers/saved/browse', headers: { origin: source }, payload: {} }) + assert.equal(response.statusCode, 403) + } + assert.equal(remote.state.requests.length, before) + const policy = getBrowserFramePolicy({ host: 'web', windowContext: 'local' }, { trustedSameOrigin: true }) + const trusted = await page.evaluate(sandbox => new Promise(resolve => { + window.addEventListener('message', event => resolve(event.data), { once: true }) + const frame = document.createElement('iframe') + frame.setAttribute('sandbox', sandbox) + frame.src = '/sidecars/proof/' + document.body.append(frame) + }), policy.sandbox) + assert.equal(trusted.status, 200) + assert.equal(trusted.body.listing.metadata.currentPath, '/srv/projects') + assert(remote.state.requests.length > before) + assert(!JSON.stringify(trusted).includes('remote-password')) +}) + +test('corrupt credential file fails closed without exposing stored data', t => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'p2-corrupt-')) + t.after(() => fs.rmSync(dir, { recursive: true, force: true })) + const file = path.join(dir, 'remote-server-credentials.json') + for (const value of ['{broken', 'null', '{"servers":{"saved":{"origin":"http://example.test","secret":{"kind":"device","cookie":null}}}}']) { + fs.writeFileSync(file, value) + const credentials = new CodeNomadServerCredentials(file) + assert.equal(credentials.read('saved', 'http://example.test'), undefined) + credentials.set('replacement', 'https://example.test', { kind: 'device', cookie: 'dummy-review-value' }) + assert.deepEqual(Object.keys(JSON.parse(fs.readFileSync(file, 'utf8')).servers), ['replacement']) + } +}) From 03c4059b0d7dd0adf32fa9e66fba4266b3a326b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Sat, 7 Nov 2026 14:46:58 +0100 Subject: [PATCH 26/34] feat(projects): consolidate project opening around one selector Use the same Recent/Browse selector on Home and compact blank tabs, with shared secondary creation actions. Keep the alternative plus-button launcher limited to recent projects and an action opening a blank tab. Main project actions create independent local, remote and SideCar occurrences; separate Open actions join existing tabs, including Browse entries. Retain server identity through authentication and folder navigation, label credentials, separate remote recents from folders, localize short connection failures and expose details on demand. Identify pairing failures on their server, keep repair inline, disclose separate-window fallback at selection and fence late autofocus when the user moves elsewhere. Preserve the existing backend/native authentication boundary. Update all ten UI locales and help pages, plus project/shell/remote-control conventions. Validate with UI typecheck, 1,623 CI UI unit tests, 16 focused units, the server's same-path occurrence test, 59 real-component browser tests, 31 help checks and an offline Tauri --no-bundle build. Compare screenshots with concept A; native cross-platform qualification remains separate. --- dev-docs/PROJECTS.md | 8 +- dev-docs/REMOTE_CONTROL.md | 14 +- dev-docs/UI_SHELL.md | 2 +- docs/help/de/browser-sidecars.md | 2 +- docs/help/de/projects.md | 12 +- docs/help/de/remote-access.md | 12 +- docs/help/en/browser-sidecars.md | 2 +- docs/help/en/projects.md | 12 +- docs/help/en/remote-access.md | 16 +- docs/help/es/browser-sidecars.md | 2 +- docs/help/es/projects.md | 12 +- docs/help/es/remote-access.md | 12 +- docs/help/fr/browser-sidecars.md | 2 +- docs/help/fr/projects.md | 12 +- docs/help/fr/remote-access.md | 12 +- docs/help/he/browser-sidecars.md | 2 +- docs/help/he/projects.md | 12 +- docs/help/he/remote-access.md | 12 +- docs/help/ja/browser-sidecars.md | 2 +- docs/help/ja/projects.md | 12 +- docs/help/ja/remote-access.md | 12 +- docs/help/ne/browser-sidecars.md | 2 +- docs/help/ne/projects.md | 12 +- docs/help/ne/remote-access.md | 12 +- docs/help/ru/browser-sidecars.md | 2 +- docs/help/ru/projects.md | 12 +- docs/help/ru/remote-access.md | 12 +- docs/help/tr/browser-sidecars.md | 2 +- docs/help/tr/projects.md | 12 +- docs/help/tr/remote-access.md | 12 +- docs/help/zh-Hans/browser-sidecars.md | 2 +- docs/help/zh-Hans/projects.md | 12 +- docs/help/zh-Hans/remote-access.md | 12 +- packages/ui/src/App.tsx | 2 +- packages/ui/src/components/browse-menu.tsx | 73 ++--- .../src/components/folder-selection-view.tsx | 213 +++++---------- .../src/components/new-instance-launcher.tsx | 30 +- .../ui/src/components/new-tab-actions.tsx | 38 +-- .../ui/src/components/recent-tabs-menu.tsx | 112 ++++---- .../src/components/remote-server-browser.tsx | 107 ++++++-- .../src/components/remote-server-dialog.tsx | 40 ++- .../ui/src/components/server-add-field.tsx | 55 +++- .../lib/i18n/messages/de/folderSelection.ts | 33 ++- .../lib/i18n/messages/en/folderSelection.ts | 33 ++- .../lib/i18n/messages/es/folderSelection.ts | 33 ++- .../lib/i18n/messages/fr/folderSelection.ts | 33 ++- .../lib/i18n/messages/he/folderSelection.ts | 33 ++- .../lib/i18n/messages/ja/folderSelection.ts | 33 ++- .../lib/i18n/messages/ne/folderSelection.ts | 33 ++- .../lib/i18n/messages/ru/folderSelection.ts | 33 ++- .../lib/i18n/messages/tr/folderSelection.ts | 33 ++- .../i18n/messages/zh-Hans/folderSelection.ts | 33 ++- packages/ui/src/lib/recent-open-target.ts | 42 +++ packages/ui/src/lib/request-focus.ts | 10 + .../ui/src/stores/remote-project-tabs.test.ts | 6 +- packages/ui/src/stores/remote-project-tabs.ts | 4 - .../ui/src/styles/components/browse-menu.css | 49 +--- .../ui/src/styles/components/folder-home.css | 166 +++-------- .../components/new-instance-launcher.css | 139 ++-------- .../components/remote-server-browser.css | 10 +- .../fixtures/new-instance-launcher.tsx | 5 +- .../browser/fixtures/remote-server-ux.tsx | 23 ++ .../browser/new-instance-launcher.test.ts | 151 ++++------ .../tests/browser/remote-project-tabs.test.ts | 258 ++++++++++++++---- .../ui/tests/browser/remote-server-ux.test.ts | 202 ++++++++++++++ 65 files changed, 1245 insertions(+), 1108 deletions(-) create mode 100644 packages/ui/src/lib/recent-open-target.ts create mode 100644 packages/ui/src/lib/request-focus.ts create mode 100644 packages/ui/tests/browser/fixtures/remote-server-ux.tsx create mode 100644 packages/ui/tests/browser/remote-server-ux.test.ts diff --git a/dev-docs/PROJECTS.md b/dev-docs/PROJECTS.md index 9b3cb8549c..b6e6b31fac 100644 --- a/dev-docs/PROJECTS.md +++ b/dev-docs/PROJECTS.md @@ -9,9 +9,13 @@ Closing project tabs, temporary workspaces, the new-instance launcher and the Gi - Closing a project tab detaches it immediately and requests deletion of that occurrence's logical backend workspace record; failures notify and never retry automatically. Separate occurrences of the same folder are independent. A `workspace.stopped` deletion closes the same record in other windows and notifies only windows displaying it that did not initiate the close. CodeNomad never evicts native Locations; OpenCode sessions keep running and reopening finds them. Whole-window close, app quit, renderer reload and backend shutdown keep existing restoration behavior. Temporary discard and server stop events use local-only tab detachment, not another DELETE; Keep closes the retained project normally. - Git is a full-functionality prerequisite, with directory-only degraded conversations when the backend cannot find Git. Only the explicitly opened physical folder is session authority in that mode; never infer sibling worktrees from native project IDs. Keep ancestor/descendant mutation identities covered by the deletion fence across Git availability changes. Inform agents through the owned native `codenomad.git-availability` instruction before prompts/custom commands, remove stale context after recovery, and keep this advisory separate from fail-closed environment synchronization. Do not add a blocking Git setup UI. Validate with `scripts/test-git-degraded-native.mjs` using an isolated CLI/database and provider. - Temporary instances (`workspaces/temporary-workspaces.ts`, UI `stores/temporary-instances.ts`) are ordinary non-Git workspaces on CodeNomad-created direct children of `/temporary-workspaces`. Registry membership (`temporary-workspaces.json`), not location, makes a folder temporary; keeping only unregisters it and adds a named recent project. Discard deletes only registered children of that root, refuses running conversations and other open tabs of the folder, removes conversations deepest-first, closes the workspace before deleting the folder and keeps failed removals registered; such a folder is reachable only by browsing to it. Closing a temporary tab from the UI asks Keep/Discard/Cancel, except that an untouched one (no conversation, file or unsent draft) closes and is discarded silently (`onlyIfEmpty`: the server refuses with `temporary_has_conversations`/`temporary_not_empty`, and any failure of that quiet discard returns the choice without an error). Before the server stops it, a visible temporary tab yields to its neighbour (or closes if alone) and a refusal restores it in place; `workspace.stopped` likewise closes the tab first and clears the instance in a microtask, because clearing a visible shell's state in the same update as its tab freezes the window. Same-minute names get a `(n)` suffix. Registry changes broadcast `workspace.temporaryChanged`, which clears kept marks in every window. Open temporary tabs are saved and restored with the app state like any project tab (still marked temporary). Only the choice dialog overrides initial focus (to its last, non-destructive choice); confirms keep focus on Cancel. Refusals use stable `temporary_*` codes localized by the client. Validate with `scripts/test-temporary-workspaces-native.mjs` against an isolated CLI. -- The tab-bar new-instance button follows the last tab like a browser: the instance `TabScroll` frame only spans its tabs and the button sits after it, outside the scroller (so focusing it never scrolls the strip), ending up at the strip's end once tabs overflow. Dragged tabs stay visually within the tab list like a browser's (`KeepDraggedTabInStrip`), while the drop slot follows the pointer's unbounded position (`closestUnboundedCenter`). Clicking it (or Cmd/Ctrl+N) opens an empty tab. A long press, right-click, Alt+Down, Shift+F10 or Menu opens the anchored `NewInstanceLauncher` (`lib/long-press.ts`; only Escape returns focus to the button, never over another surface or the home page): titled Open a tab, it is the home page's logic in short: the search, the collapsible Recent section (unfolded by default and kept per window; chevron first, like Browse; Escape on its title folds it without closing the launcher; typing or an arrow in the search unfolds it; an open project switches to its tab), the folded Browse section, then Clone and New temporary tab only. Recents are local projects, remote projects and SideCars (`launchableRecents`, `filterRecents` for search fields, `components/recent-tab-icon.tsx`); a SideCar joins them when it opens (`stores/sidecar-open.ts`), stored as `ui` state `sidecarRecents` with its id and time only, never an address or proxy token, and listed while still configured. The home page's right card has two tabs, Recent (with the same search; arrows move between the tabs) and Browse (the list always open); its left column holds only the creation buttons of `components/new-tab-actions.tsx`: Clone a Git repository, New temporary tab and New SideCar (`openSettingsRow("sidecars", "sidecar-add")`, the SideCar form's name field); servers are added in Browse. The launcher's `variant` keeps only the first two. Renaming and removing recent tabs stay on the home page; servers are managed in Settings → Servers, SideCars in Settings → SideCars. Browse/clone flows live once in `components/new-instance-dialogs.tsx` and recent-folder display helpers in `lib/recent-folder-display.ts`, shared with `FolderSelectionView`; styles in `styles/components/new-instance-launcher.css`. +- The tab-bar new-instance button follows the last tab: the instance `TabScroll` frame spans its tabs and the button sits after it, outside the scroller, reaching the strip's end on overflow. Dragged tabs stay within the list (`KeepDraggedTabInStrip`), while the drop slot follows the unbounded pointer (`closestUnboundedCenter`). Clicking `+` or Cmd/Ctrl+N opens an empty tab. A long press, right-click, Alt+Down, Shift+F10 or Menu opens `NewInstanceLauncher` (`lib/long-press.ts`), titled Recent projects: search and recents only, followed by Open another project… which opens a blank tab. Keep browsing, authentication, server addition and creation in the canonical selector. Escape dismisses the launcher and returns focus to `+`, without stealing focus from another surface or Home. +- Home preserves CodeNomad identity, language, settings, Sponsor and links. Blank tabs show the compact Open a project title. Both use the same `FolderSelectionView` Recent | Browse selector, counts, row actions, search and states. Creation sits in one secondary bar below the list (`NewTabActions`): Clone Git Repo, New temporary tab and New SideCar (`openSettingsRow("sidecars", "sidecar-add")`). Clone and temporary folders target the local backend explicitly, independently of the server being browsed. Rename/remove actions live in the same recent-row menu on both surfaces. Servers are managed in Settings → Servers, SideCars in Settings → SideCars. Browse/clone dialogs live in `components/new-instance-dialogs.tsx`; display helpers in `lib/recent-folder-display.ts`. +- Recents share `launchableRecents`, `filterRecents` and `components/recent-tab-icon.tsx`: local projects, remote projects and configured SideCars. SideCars enter `ui.sidecarRecents` when opened (`stores/sidecar-open.ts`), storing only id and time. Across Home, blank tabs, quick launcher and Browse, selecting an entry creates a new occurrence for local projects, remote projects and SideCars even if already open. The separate Open action joins an existing occurrence; keep its click and keyboard activation distinct from the row's open-new action. Resolve remote identity by profile/server and folder, SideCars by configured id, and local projects by folder. - Browse (`components/browse-menu.tsx`) lists This computer, host-visible saved servers, configured SideCars and the inline server-add field. `components/server-add-field.tsx` saves a profile; pasting adds immediately and Enter or + submits typed text. An existing address reuses its profile. Credentials in an address are rejected. A `tls_error` offers Skip TLS verification with explicit confirmation and a window-only profile. A Remote Control pairing link also asks the local backend to redeem its one-use code over the dedicated HTTPS tunnel protocol and persist a private device credential for browsing ([REMOTE_CONTROL.md](REMOTE_CONTROL.md#backend-to-backend-pairing)). The UI receives success only and scrubs the field after the attempt. Never persist a pairing code or retain it for native opening. Expired/replayed codes and rate limits have localized errors; unsupported remote pairing offers inline password recovery, which requires a direct-listener URL or a remote update for tunnel pairing. -- Choosing a saved Browse row switches the list in place to that server's recent projects and folder list, with Back to Browse. An inline username/password form obtains a backend-held direct-access session when needed. Backend pairing survives launches; revocation clears its rejected credential and shows the inline form again. Repair tunnel browsing with Back to Browse and a fresh pairing link in the add field. Folder navigation stays in that list; Select Current or choosing a recent project opens its folder in a remote tab, replacing the originating blank slot. The `+` launcher stays open until a folder is chosen. Keep this flow shared between Home, blank tabs and the compact launcher. Backend browsing and native embedded views own independent authentication. +- Choosing a saved Browse row shows that server's name through authentication and navigation. Visible username/password labels identify the inline direct-access form. Recent and Folders sections distinguish immediate project opening from folder traversal; Open this folder opens the current folder, replacing the originating blank slot. Back to Browse returns to the server list. Keep this flow shared by Home and blank tabs. Backend pairing survives launches; repair tunnel browsing with a fresh pairing link after revocation. Pairing errors name the affected server. TLS and unreachable-server failures use short localized messages with technical diagnostics available on demand. The edit dialog's URL/TLS help uses keyboard-accessible information controls. +- Known authentication limitation: backend browsing and native embedded views own independent authentication. Backend credentials persist privately; native views keep their own cookies and can require another sign-in or pairing. Unifying those authorities requires a separate backend/native authentication change; preserve the single-use pairing-code boundary. +- Separate-window fallback is explicit at project selection: opening actions identify the separate window for profiles skipping TLS verification and platforms without embedded-view support. Preserve that disclosure across canonical selectors and recent-entry opening paths. - Settings → Servers (`settings/servers-settings-section.tsx`, host windows only) manages profiles through the same add field, the edit-only `RemoteServerDialog` (address, name, certificate check) and confirmed removal. Removal must call the backend forget endpoint before removing the profile, then clear its recents and close its tabs. Saving keeps the profile id; a rename with unchanged URL/TLS skips the probe (`saveProfile`). Opening from the tabless native Preferences window opens the server's window. `serverDisplayName` (`lib/codenomad-link.ts`) uses the saved name or hostname, showing a port when another saved server shares that hostname. - A selected remote folder opens a `remote-project` app tab (`stores/remote-project-tabs.ts`, `stores/remote-project-open.ts`). `RemoteProjectView` places a native view over its content area: Electron `WebContentsView` (`electron/main/remote-view.ts`) or a Windows Tauri child webview (`src-tauri/src/remote_view.rs`). Other platforms and profiles that skip TLS verification open a separate remote window. Embedded views share the server's remote-window storage (Electron partition or Tauri data directory) and keep their own sign-in/device cookie; backend browsing uses its private credential store. Native access permits notifications only. Views stay on the server origin, open public help externally and return bare-root navigation after authentication to their tab entry. Tauri's `external-link-guard` checks registered `remote-view-*` labels through `RemoteViews::navigation_allowed` before window-origin rules. Views open lazily, track placeholder bounds, hide for inactive tabs and local overlays (`localOverlayOpen()`), and close with their owning page. - Embedded single-project mode (`lib/embed-mode.ts`, `/?codenomadEmbed=project[&folder=…]`) shows one project without the title/tab bars, Home or native badge; its folder picker handles entries without a folder. It records the folder in the URL and project name in `document.title`, and restores the active session per folder (`rememberEmbeddedSession`, `stores/embedded-project-session.ts`). The host accepts title updates only from the server origin with a folder in the address. Servers without this mode show their full interface and retain the server title. Password sessions last seven days (`PASSWORD_SESSION_TTL_MS`) with matching cookie `Max-Age`; logout revokes them and bootstrap sessions use browser-session cookies. Tabs restore as `{kind: "remote-project", profileId, folder?}`; missing/window-only profiles drop their tabs. Remote recents (`ui.remoteProjectRecents`) contain server, folder and name only. Covered by `tests/browser/remote-project-tabs.test.ts`, `electron/main/remote-view.test.ts` and `remote_view.rs` tests. diff --git a/dev-docs/REMOTE_CONTROL.md b/dev-docs/REMOTE_CONTROL.md index f74166d3c5..48aefa7420 100644 --- a/dev-docs/REMOTE_CONTROL.md +++ b/dev-docs/REMOTE_CONTROL.md @@ -139,9 +139,17 @@ success; secrets stay out of UI state and logs, and the add field is scrubbed af the attempt. Never retain codes for retries. The credential survives local launches. Forgetting the saved server deletes it; -revocation clears the rejected credential and returns Browse to its inline -password form. To repair tunnel browsing, use Back to Browse and paste a fresh -pairing link into the add field. Native embedded views pair separately. +revocation clears the rejected credential. To repair tunnel browsing, use Back to +Browse and paste a fresh pairing link into the add field. Pairing errors name the +saved server. Home and blank tabs own this named-server browsing flow; the quick +launcher reaches it through Open another project…. + +Known authentication limitation: native embedded views and backend browsing use +independent authentication authorities. A native view can require another sign-in +or pairing link even after backend browsing succeeds. A separate backend/native +authentication change is required to unify that flow; keep single-use codes +scrubbed after redemption. Project selection explicitly labels the separate-window +fallback for profiles skipping TLS verification and hosts without embedded views. Compatibility is capability-based: an endpoint returning 403 (including an older browser-Origin rejection), 404 or 405 maps to `pairing_unavailable` and offers diff --git a/dev-docs/UI_SHELL.md b/dev-docs/UI_SHELL.md index da426731bc..c1f9ab4853 100644 --- a/dev-docs/UI_SHELL.md +++ b/dev-docs/UI_SHELL.md @@ -4,7 +4,7 @@ Panel toggles, floating drawers, project/right-panel tabs, the session sidebar a ## Agent conventions -- The CodeNomad logo opens Home: `NativeTitlebar.onHome` in native title/menu bars and the tab-bar logo in web windows. The `+` button and New instance command open an ephemeral unnamed `blank` tab; its close action stays local. `FolderSelectionView` renders both Home and its `blank` mode: the same background, centered logo/name, large Clone/Temporary/SideCar buttons and Recent/Browse selector with `EntryCount`; search sits below the selector in Recent. Blank mode hides the language, top-right actions, social links, version and OpenCode row and focuses search on activation, including an empty recent list. Each mounted view uses unique ARIA IDs and gates window hotkeys and folder drops on its active state. Adding a server focuses its saved Browse row and keeps the launcher open; selecting the row runs the ordinary open action. The home heart Sponsor action uses `helpUrl(locale, "sponsor")` through the shared external opener. Validate web, Electron and Tauri roles and compare Home/blank screenshots with `tests/browser/remote-project-tabs.test.ts`; launcher gestures use `new-instance-launcher.test.ts`. +- The CodeNomad logo opens Home: `NativeTitlebar.onHome` in native title/menu bars and the tab-bar logo in web windows. `+` and New instance (Cmd/Ctrl+N) open an ephemeral unnamed `blank` tab; closing it stays local. `FolderSelectionView` shares one Recent | Browse selector, counts, search, row actions and secondary creation bar below the list between Home and blank tabs. Home carries CodeNomad's logo/name, language, settings, Sponsor and links; blank mode uses the compact Open a project title and focuses search on activation. Each mounted view uses unique ARIA IDs and gates window hotkeys and folder drops on its active state. Adding a server focuses its saved Browse row and preserves the selector; choosing its row browses in place, with a named server header through labelled sign-in and Recent/Folders navigation. Only choosing a project fills the originating blank slot. The alternate `+` gestures open a recents-only quick launcher with search and Open another project… toward a blank tab. Entry activation creates a new local/remote/SideCar occurrence; a separate Open action joins an existing one. Escape returns launcher focus to `+`; back navigation restores the originating server row, and late responses respect the active surface. The home heart Sponsor action uses `helpUrl(locale, "sponsor")` through the shared external opener. Validate Home/blank and native roles with `tests/browser/remote-project-tabs.test.ts`; launcher gestures use `new-instance-launcher.test.ts`. - Docked panel resize handles follow the composer's Pointer Events design: capture the pointer on the handle and keep its `.is-resizing` highlight until pointer up/cancel, capture loss or the active handle's cleanup. Scope each handle's cleanup to its own side so resizing continues when the opposite panel closes. Keep event handlers local in `useDrawerResize.ts` and styles in `styles/panels/session-layout.css`; validate both sides, RTL and touch with `tests/browser/panel-resize.test.ts`. diff --git a/docs/help/de/browser-sidecars.md b/docs/help/de/browser-sidecars.md index ed8f79a965..bee23c7e52 100644 --- a/docs/help/de/browser-sidecars.md +++ b/docs/help/de/browser-sidecars.md @@ -47,7 +47,7 @@ Native Mobilvorlagen setzen Android-/Chromium-Identität, Ausrichtung, Touch und 1. Starten Sie das Webwerkzeug separat auf dem CodeNomad-Backend-Host, lauschend auf `127.0.0.1:`. 2. Öffnen Sie **Einstellungen → SideCars**. Geben Sie **Name** und **Port** ein; prüfen Sie den abgeleiteten **Basispfad** (`/sidecars/`). 3. Setzen Sie **Protokoll** passend zum Upstream-Dienst und wählen Sie **Präfix-Modus**. -4. Wählen Sie **SideCar hinzufügen** und öffnen Sie den SideCar dann über **Durchsuchen** auf der Startseite oder im Starter; danach erscheint er unter **Zuletzt verwendet**. **Neuer SideCar** öffnet dieses Formular. +4. Wählen Sie **SideCar hinzufügen** und öffnen Sie ihn über **Durchsuchen** auf Startseite oder leerem Tab; danach erscheint er unter **Zuletzt verwendet** und in der Schnellstartersuche. **Neuer SideCar** unter der Auswahlliste öffnet dieses Formular. Die SideCar-Auswahl erzeugt ein neues Vorkommen; die separate Aktion **Offen** wählt ein bestehendes ([Projekt-Tabs](projects.md#open-project)). | Auswahl | Exakte Wirkung | | --- | --- | diff --git a/docs/help/de/projects.md b/docs/help/de/projects.md index 42a06fb4a0..04f740344e 100644 --- a/docs/help/de/projects.md +++ b/docs/help/de/projects.md @@ -4,24 +4,24 @@ Ein Projekt-Tab verbindet CodeNomad mit einem Ordner auf dem Backend-Rechner. Da ## Projekt öffnen {#open-project} -1. **Neue Instanz** (`+`) öffnet einen leeren **Neuer Tab** mit Fokus in der Suche. Er nutzt Hintergrund, zentriertes CodeNomad-Logo und Namen sowie die großen Erstellungsbuttons der Startseite: **Git-Repo klonen**, **Neuer temporärer Tab**, **Neuer SideCar**. Rechts steht der Umschalter **Zuletzt verwendet | Durchsuchen** mit Eintragszahlen; die Suche liegt darunter in **Zuletzt verwendet**. Die Auswahl eines lokalen oder entfernten Projekts oder SideCars füllt diesen Tab an seiner Position. Ein leerer Tab besteht bis zum Neuladen und schließt ohne verbleibendes Projekt. Das CodeNomad-Logo in der Titel- oder Tableiste öffnet die Startseite mit Einstellungen, Sprache und der Herz-Schaltfläche **Sponsor** ([CodeNomad unterstützen](sponsor.md)). +1. **Neue Instanz** (`+`) oder `Ctrl/Cmd+N` öffnet einen leeren Tab mit dem kompakten Titel **Projekt öffnen**. Die Startseite nutzt denselben Umschalter **Zuletzt verwendet | Durchsuchen**, Zähler, Suche und Projektaktionen. **Git-Repo klonen**, **Neuer temporärer Tab** und **Neuer SideCar** stehen in einer sekundären Leiste unter der Liste; Klonen und temporäre Ordner verwenden das lokale Backend. Die Projekt- oder SideCar-Auswahl füllt den leeren Tab an seiner Position. Leere Tabs bestehen bis zum Neuladen und schließen ohne Projekt. Das Logo öffnet die Startseite mit CodeNomad-Identität, Einstellungen, Sprache, Links und **Sponsor** ([CodeNomad unterstützen](sponsor.md)). 2. Wählen Sie unter **Zuletzt verwendet** ein Projekt; oder öffnen Sie **Durchsuchen**, wählen Sie **Dieser Computer**, dann den Backend-Ordner, und öffnen Sie ihn. **Durchsuchen** listet auch gespeicherte CodeNomad-Server ([Remote-Projekt-Tabs](remote-access.md#remote-project-tabs)) und SideCars ([SideCars](browser-sidecars.md#register-sidecar)) auf. 3. Für eine Repository-Kopie wählen Sie **Git-Repo klonen**, geben **Repository-URL** und **Zielordner** ein und wählen **Klonen**. **Zielordner** wird mit dem Repository-Namen im Ordner, der Ihren letzten Klon enthält vorbelegt, sonst neben Ihrem zuletzt geöffneten Projekt. **Durchsuchen** wählt den Ordner, der den Klon enthält; Sie können den Pfad auch bearbeiten, einschließlich des Ordnernamens des Klons. Einen Remote-Server zu durchsuchen bedeutet, dessen Dateisystem zu durchsuchen, nicht Ihr Telefon oder Notebook. Das Öffnen eines Projekts erzeugt keinen separaten OpenCode-Daemon pro Tab. Unterhaltungen sind native OpenCode-Sitzungen; ihre Lebensdauer entspricht nicht der des Tabs. -Die Auswahl eines Servers in **Durchsuchen** ersetzt die Liste durch dessen letzte Projekte und Ordner. Melden Sie sich bei Bedarf im eingeblendeten Formular an und wählen Sie ein Projekt oder einen Ordner mit **Aktuellen auswählen**. Die Rückkehr zu Durchsuchen zeigt die Server. Erst die Projektwahl füllt den leeren Tab und schließt den `+`-Starter. Der Remote-Tab kann eine eigene Anmeldung unabhängig von der Suche verlangen. +Der in **Durchsuchen** gewählte Server bleibt bei Anmeldung und Navigation namentlich sichtbar. Die Anmeldefelder sind beschriftet; **Zuletzt verwendet** öffnet Projekte, **Ordner** navigiert. **Diesen Ordner öffnen** öffnet den aktuellen Ordner; Zurück zu Durchsuchen zeigt die Server. Erst die Projektwahl füllt den leeren Tab. Bekannte Einschränkung: Backend-Ordnersuche und native Ansicht authentifizieren sich unabhängig; der Remote-Tab kann eine eigene Anmeldung verlangen. Klonen schreibt ein Repository ins Zielverzeichnis. **Zielordner zuerst entfernen, falls er bereits existiert.** ist destruktiv: Aktivieren Sie dies nur, wenn alles dort Vorhandene gelöscht werden darf. Verwenden Sie im Zweifel ein neues Ziel. Ein fehlgeschlagener Klon ist kein Grund, ein vorhandenes Projekt zu löschen; prüfen Sie vor dem Wiederholen das gemeldete Ziel und den Fehler. -Zuletzt verwendete Einträge sind Verknüpfungen. **Arbeitsbereich umbenennen** ändert den Anzeigenamen; **Aus Liste entfernen** entfernt die Verknüpfung, nicht die Dateien oder Unterhaltungen. Ein Klick auf ein bereits geöffnetes zuletzt verwendetes Projekt öffnet einen neuen Tab; seine Schaltfläche **Offen** (**Zum offenen Projekt wechseln**) wählt stattdessen den vorhandenen Tab. +Zuletzt verwendete Einträge sind Verknüpfungen. Ihr Aktionsmenü auf Startseite und leeren Tabs bietet je nach Eintrag **Arbeitsbereich umbenennen** und **Aus Liste entfernen**; Dateien und Unterhaltungen bleiben erhalten. Auf Startseite, leeren Tabs und im Schnellstarter erzeugt ein Klick auf lokale/entfernte Projekte oder SideCars ein neues Vorkommen, auch wenn sie geöffnet sind. Die separate Aktion **Offen** (**Zum offenen Projekt wechseln**) wählt das vorhandene Vorkommen. ## Schnellstarter für neue Instanzen verwenden {#new-instance-launcher} 1. Halten Sie `+` gedrückt oder klicken Sie mit der rechten Maustaste darauf; bei Tastaturfokus dort verwenden Sie **Alt+Down**, **Shift+F10** oder die Menütaste. -2. Durchsuchen Sie in **Tab öffnen** die Liste **Zuletzt verwendet** (Projekte, Remote-Projekte und SideCars), öffnen Sie **Durchsuchen**, oder wählen Sie **Git-Repo klonen** oder **Neuer temporärer Tab**. +2. **Zuletzt verwendete Projekte** durchsucht nur zuletzt verwendete lokale Projekte, Remote-Projekte und SideCars. Eine Zeile öffnet ein neues Vorkommen, ihre separate Aktion **Offen** wechselt zum vorhandenen. **Anderes Projekt öffnen…** öffnet einen leeren Tab zum Durchsuchen, Hinzufügen von Servern und Erstellen von Projekten. -Ein normaler Klick öffnet einen leeren Tab. Die Startseite über das CodeNomad-Logo bietet dieselben Möglichkeiten und Eintragszahlen in **Zuletzt verwendet** und **Durchsuchen**. Benennen Sie zuletzt geöffnete Tabs dort um oder entfernen Sie sie; verwalten Sie Server unter **Einstellungen → Server** und SideCars unter **Einstellungen → SideCars**. Escape schließt den Starter und gibt den Fokus an `+` zurück. +Ein normaler Klick öffnet einen leeren Tab. Der Schnellstarter enthält zuletzt verwendete Projekte, deren Suche und **Anderes Projekt öffnen…**. Verwalten Sie letzte Einträge auf Startseite oder leeren Tabs, Server unter **Einstellungen → Server** und SideCars unter **Einstellungen → SideCars**. Escape schließt den Starter und gibt den Fokus an `+` zurück. ## Projekt-Tab schließen {#close-stop} @@ -40,7 +40,7 @@ Das Schließen eines ganzen Fensters, Beenden oder Neuladen schließt dessen Pro ## Temporäre Arbeitsbereiche {#temporary-workspaces} -1. Wählen Sie **Neuer temporärer Tab** auf der Startseite oder im Starter. +1. Wählen Sie **Neuer temporärer Tab** unter der Liste auf der Startseite oder einem leeren Tab. 2. Arbeiten Sie im leeren, von CodeNomad verwalteten Ordner; Git wird nicht automatisch initialisiert. 3. Wählen Sie beim Schließen des Tabs **Behalten**, **Verwerfen** oder **Abbrechen**. Das Tab-Menü bietet auch **Als Projekt behalten**. diff --git a/docs/help/de/remote-access.md b/docs/help/de/remote-access.md index 705b5d6538..080b2a3a34 100644 --- a/docs/help/de/remote-access.md +++ b/docs/help/de/remote-access.md @@ -83,9 +83,9 @@ Meldet ein Client eine Zertifikatswarnung, halten Sie an und prüfen Sie Hostnam ## Remote-Server speichern {#saved-servers} -1. Öffnen Sie auf der Startseite, einem leeren Tab oder im Starter **Tab öffnen** den Bereich **Durchsuchen**. Geben Sie Adresse oder Kopplungslink in **Serveradresse oder -link** ein: Einfügen fügt sofort hinzu, die Eingabetaste bestätigt getippten Text. Der Server wird unter seinem Hostnamen gespeichert und seine Zeile fokussiert; ein Kopplungslink koppelt außerdem das lokale Backend für die Ordnersuche. Der Starter bleibt offen. Klicken Sie auf diese Zeile, um Projekte an Ort und Stelle zu durchsuchen. **Einstellungen → Server** bietet dasselbe Feld. -2. Verwenden Sie einen vertrauenswürdigen HTTPS-Ursprung. Besteht sein Zertifikat die Prüfung nicht, erscheint unter dem Feld **TLS-Prüfung überspringen**: Aktivieren Sie dies nur für einen vertrauenswürdigen Server und speichern Sie erneut mit der Eingabetaste. Die Auswahl eines Ordners oder Projekts dieses Profils öffnet ein eigenes Fenster. -3. Wählen Sie seine Zeile unter **Durchsuchen**, um Projekte an Ort und Stelle zu durchsuchen. Geben Sie bei Bedarf Benutzername und Passwort im eingeblendeten Formular ein. Name und Adresse ändern Sie mit **Server bearbeiten** unter **Einstellungen → Server**. +1. Öffnen Sie auf der Startseite oder einem leeren **Projekt öffnen**-Tab **Durchsuchen** und geben Sie Adresse oder Kopplungslink in **Serveradresse oder -link** ein. Im Schnellstarter wählen Sie zuerst **Anderes Projekt öffnen…**. Einfügen fügt sofort hinzu, Enter bestätigt getippten Text. Der Server wird gespeichert, seine Zeile fokussiert und der Selektor bleibt offen; ein Link koppelt auch das lokale Backend für die Ordnersuche. Klicken Sie zum Durchsuchen auf die Zeile. **Einstellungen → Server** bietet dasselbe Feld. +2. Verwenden Sie einen vertrauenswürdigen HTTPS-Ursprung. Zertifikatsfehler und unerreichbare Server erhalten übersetzte Meldungen; technische Details öffnen Sie über die Informationsschaltfläche. **TLS-Prüfung überspringen** erfordert Ihre ausdrückliche Wahl: nur für vertrauenswürdige Server aktivieren und erneut bestätigen. Die Öffnen-Aktion kündigt bei der Projektwahl das separate Fenster für dieses Profil an. +3. Der Servername bleibt bei Anmeldung und Navigation sichtbar, mit beschrifteten Feldern und den Bereichen **Zuletzt verwendet** und **Ordner**. Kopplungsfehler nennen den betroffenen Server. **Server bearbeiten** unter **Einstellungen → Server** ändert URL und Namen; `i`-Schaltflächen zeigen URL/TLS-Hilfe auf Abruf. **Einstellungen → Server** verwaltet Profile (**Server bearbeiten**, **Gespeicherten Server entfernen**). Beim Entfernen werden zuerst die Zugangsdaten und die Suchsitzung im Backend vergessen, dann das Lesezeichen entfernt und seine Tabs geschlossen. Entfernte Projekte und Unterhaltungen bleiben auf ihrem Server. Das lokale Backend speichert Suchzugangsdaten privat in `remote-server-credentials.json` neben seiner Konfiguration; schützen Sie diese Datei wie ein Passwort. Eingebettete Ansichten behalten eine separate Authentifizierung. @@ -99,9 +99,9 @@ Das Einfügen eines frischen Fernsteuerungslinks speichert den Tunnel-Ursprung u In der Desktop-App (Electron oder Tauri unter Windows) kann ein gespeicherter Server eines seiner Projekte auch in einem Tab dieses Fensters öffnen, neben Ihren lokalen Projekten: -1. Öffnen Sie auf der Startseite, einem leeren Tab oder im Starter **Tab öffnen** den Bereich **Durchsuchen** und wählen Sie einen gespeicherten Server. Fügen Sie neue Server zuerst über **Serveradresse oder -link** hinzu und klicken Sie dann auf deren Zeile. -2. Die Liste zeigt dort die zuletzt verwendeten Projekte und Ordner dieses Servers. Melden Sie sich bei Bedarf im eingeblendeten Formular an. Wählen Sie ein Projekt oder navigieren Sie zu einem Ordner und wählen Sie **Aktuellen auswählen**. **Zurück zu Durchsuchen** führt zur Serverliste. -3. Die Ordnerwahl öffnet den Remote-Projekttab und ersetzt den ursprünglichen leeren Tab. Der `+`-Starter bleibt bis zu dieser Wahl offen. Das Projekt erscheint zum direkten Wiederöffnen unter **Zuletzt verwendet**. +1. Öffnen Sie auf Startseite oder leerem Tab **Durchsuchen** und wählen Sie einen Server. Im Schnellstarter zuerst **Anderes Projekt öffnen…** wählen. Neue Server über **Serveradresse oder -link** hinzufügen, dann auf ihre Zeile klicken. +2. Der benannte Server zeigt **Zuletzt verwendet** und **Ordner** an Ort und Stelle. Bei Bedarf im beschrifteten Formular anmelden. Wählen Sie ein Projekt oder einen Ordner mit **Diesen Ordner öffnen**. **Zurück zu Durchsuchen** führt zur Serverliste. +3. Die Ordnerwahl erzeugt ein neues Remote-Vorkommen anstelle des leeren Tabs und ergänzt **Zuletzt verwendet**. Die separate Aktion **Offen** wählt ein bestehendes Vorkommen. Die Öffnen-Aktion kündigt bei der Auswahl separate Fenster an, insbesondere beim TLS-Fallback und Tauri macOS/Linux. Bekannte Einschränkung: Backend-Ordnersuche und native Ansicht authentifizieren sich unabhängig. Unterhaltungen, Dateien, Git, Einstellungen und Missions des Tabs laufen auf dem Remote-Server. Seine eingebettete Ansicht teilt den Speicher des Remote-Fensters und kann eine eigene Anmeldung unabhängig von Durchsuchen verlangen. Remote-Tabs werden beim Start wiederhergestellt. Server ohne eingebetteten Modus zeigen ihre vollständige Oberfläche; Profile ohne TLS-Prüfung und Tauri unter macOS/Linux öffnen ein separates Fenster. Die eingebettete Seite bleibt auf ihrem Server und hat nur Benachrichtigungszugriff auf den Host. Webclients und Fernsteuerungsgeräte haben keine Remote-Tabs. diff --git a/docs/help/en/browser-sidecars.md b/docs/help/en/browser-sidecars.md index 114040e8af..357126ea36 100644 --- a/docs/help/en/browser-sidecars.md +++ b/docs/help/en/browser-sidecars.md @@ -47,7 +47,7 @@ Native mobile templates set Android/Chromium identity, orientation, touch and DP 1. Start the web tool separately on the CodeNomad backend host, listening on `127.0.0.1:`. 2. Open **Settings → SideCars**. Enter **Name** and **Port**; check the derived **Base path** (`/sidecars/`). 3. Set **Protocol** to match the upstream service, and choose **Prefix mode**. -4. Choose **Add SideCar**, then open the SideCar from **Browse** on the home page or in the launcher; it then joins **Recent**. **New SideCar** opens this form. +4. Choose **Add SideCar**, then open it from **Browse** on Home or an empty tab; it then joins **Recent** and the quick launcher's search. **New SideCar**, below the selector's list, opens this form. Selecting a SideCar creates a new occurrence; its separate **Open** action joins an existing one ([project tabs](projects.md#open-project)). | Choice | Exact effect | | --- | --- | diff --git a/docs/help/en/projects.md b/docs/help/en/projects.md index 1fcad2467f..62b7fa2736 100644 --- a/docs/help/en/projects.md +++ b/docs/help/en/projects.md @@ -4,24 +4,24 @@ A project tab connects CodeNomad to a folder on the backend computer. Opening a ## Open a project {#open-project} -1. Click **New instance** (`+`) to open an empty **New tab**, focused on search. It shares Home's background, centered CodeNomad logo and name, large **Clone Git Repo**, **New temporary tab** and **New SideCar** buttons, and the **Recent | Browse** selector with item counts. Search sits below the selector in **Recent**. Choosing a local or remote project or a SideCar fills that tab in place. An empty tab lasts until the window reloads and closes without leaving a project. The CodeNomad logo in the title bar or tab bar opens Home, which also offers settings, language and the heart **Sponsor** button ([Support CodeNomad](sponsor.md)). +1. Click **New instance** (`+`) or press `Ctrl/Cmd+N` to open an empty **New tab** with the compact **Open a project** selector. Home uses the same **Recent | Browse** selector, counts, search and project actions. **Clone Git Repo**, **New temporary tab** and **New SideCar** sit in a secondary bar below the list; cloning and temporary folders target the local backend. Choosing a local or remote project or a SideCar fills the empty tab in place. Empty tabs last until reload and close without leaving a project. The CodeNomad logo opens Home, with CodeNomad's identity, settings, language, links and the heart **Sponsor** button ([Support CodeNomad](sponsor.md)). 2. In **Recent**, choose a project; or open **Browse**, choose **This computer**, then select the backend folder and open it. **Browse** also lists saved CodeNomad servers ([remote project tabs](remote-access.md#remote-project-tabs)) and SideCars ([SideCars](browser-sidecars.md#register-sidecar)). 3. For a repository copy, choose **Clone Git Repo**, enter **Repository URL** and **Destination folder**, then **Clone**. **Destination folder** is prefilled with the repository name in the folder that holds your last clone, or next to your most recent project. **Browse** chooses the folder that contains the clone; you can also edit the path, including the clone's folder name. Browsing a remote server means browsing that server's filesystem, not your phone or laptop. Opening a project does not create a separate OpenCode daemon for each tab. Conversations are native OpenCode sessions; their lifetime is not the tab's lifetime. -Choosing a saved server in **Browse** replaces the list with its recent projects and folders. Sign in inline if requested, then choose a recent project or navigate to a folder and use **Select Current**. **Back to Browse** returns to the servers. Only choosing a project fills the empty tab and dismisses the `+` launcher. The remote tab may request its own sign-in separately from browsing. +Choosing a saved server in **Browse** shows its name throughout sign-in and folder navigation. The sign-in fields have visible labels; **Recent** opens a project, while **Folders** navigates. Choose **Open this folder** to open the current folder, or **Back to Browse** to return to the servers. Only a project choice fills the empty tab. Known limitation: backend browsing and the native view authenticate independently, so the remote tab may request its own sign-in. Cloning writes a repository to the destination. **Remove the destination folder first if it already exists.** is destructive: enable it only when everything already there can be deleted. Use a fresh destination if unsure. A failed clone is not a reason to delete an existing project; inspect the reported destination and error before retrying. -Recent entries are shortcuts. **Rename workspace** changes its displayed name; **Remove from recent** removes the shortcut, not its files or conversations. Clicking an already-open recent project opens a new tab; its **Open** button (**Switch to open project**) selects the existing tab instead. +Recent entries are shortcuts. Their project-actions menu on Home and empty tabs offers **Rename workspace** and **Remove from recent** where available; removal keeps files and conversations. Across Home, empty tabs and the quick launcher, clicking a local project, remote project or SideCar creates a new occurrence, even when already open. Its separate **Open** action (**Switch to open project**) selects the existing occurrence instead. ## Use the new-instance launcher {#new-instance-launcher} 1. Long-press or right-click `+`; with keyboard focus there, use **Alt+Down**, **Shift+F10** or the Menu key. -2. In **Open a tab**, search **Recent** (projects, remote projects and SideCars), open **Browse**, or choose **Clone Git Repo** or **New temporary tab**. +2. **Recent projects** searches only recent local projects, remote projects and SideCars. Choose a row for a new occurrence, or its separate **Open** action to switch to the existing one. **Open another project…** opens an empty tab for browsing, adding servers or creating projects. -A normal click opens an empty tab. Home, opened from the CodeNomad logo, offers the same choices and item counts in **Recent** and **Browse**. Rename or remove recent tabs there; manage servers in **Settings → Servers** and SideCars in **Settings → SideCars**. Escape dismisses the launcher and returns focus to `+`. +A normal click opens an empty tab. The quick launcher contains recents and search only, plus **Open another project…**. Manage recent entries on Home or an empty tab, servers in **Settings → Servers** and SideCars in **Settings → SideCars**. Escape dismisses the launcher and returns focus to `+`. ## Close a project tab {#close-stop} @@ -40,7 +40,7 @@ Closing a whole window, quitting or reloading does not close its project connect ## Temporary workspaces {#temporary-workspaces} -1. Choose **New temporary tab** on the home page or in the launcher. +1. Choose **New temporary tab** below the list on Home or an empty tab. 2. Work in the empty CodeNomad-managed folder; Git is not initialized automatically. 3. On closing the tab, choose **Keep**, **Discard** or **Cancel**. The tab menu also offers **Keep as project**. diff --git a/docs/help/en/remote-access.md b/docs/help/en/remote-access.md index 68959f2498..de03e4d79f 100644 --- a/docs/help/en/remote-access.md +++ b/docs/help/en/remote-access.md @@ -83,9 +83,9 @@ If a client reports a certificate warning, stop and check the hostname, SANs, tr ## Save a remote server {#saved-servers} -1. On Home, an empty tab or the **Open a tab** launcher, open **Browse** and enter the address or pairing link in **Server address or link**. Pasting adds it immediately; Enter adds typed text. Adding saves the server under its host name and focuses its row; a pairing link also pairs the local backend for browsing. The launcher stays open. Click the saved row to browse projects in place. **Settings → Servers** offers the same field. -2. Use a trusted HTTPS origin. If its certificate fails the check, the error shows under the field with **Skip TLS verification**: tick it only for a server you trust, then press Enter again to save it. Choosing a folder or project on that profile opens its own window. -3. Choose its saved **Browse** row to browse projects in place. If prompted, enter the server username and password in the inline form. Rename it or change its address with **Edit server** in **Settings → Servers**. +1. On Home or an empty **Open a project** tab, open **Browse** and enter the address or pairing link in **Server address or link**. From the quick launcher, use **Open another project…** first. Pasting adds immediately; Enter adds typed text. Adding saves the server, focuses its row and keeps the selector in place; a pairing link also pairs the local backend for browsing. Click the row to browse. **Settings → Servers** offers the same field. +2. Use a trusted HTTPS origin. Certificate and unreachable-server errors are localized; request details with the information control for the technical diagnostic. **Skip TLS verification** requires your explicit choice: use it only for a trusted server, then submit again. Opening a project on this profile uses a separate window; the opening action announces this at selection time. +3. Choose the saved **Browse** row. The server name stays visible during sign-in and navigation, with labelled sign-in fields and distinct **Recent** and **Folders** sections. **Edit server** in **Settings → Servers** changes its URL or name; its `i` controls reveal address and TLS help on demand. **Settings → Servers** manages saved profiles (**Edit server**, **Remove saved server**). Removing a profile first forgets its backend-held browsing credentials and session, then removes the bookmark and closes its tabs. Remote projects and conversations stay on their server. The local backend stores browsing secrets privately in `remote-server-credentials.json` beside its configuration; protect that file as a password. Embedded views keep their own authentication separately. @@ -93,16 +93,16 @@ To open a saved server straight from the command line, start the desktop app wit A remote window always leaves a way back to this computer. Closing the last local window while remote windows stay open keeps its tabs: **Window → New Window** in a remote window, or starting CodeNomad again, reopens it. If a server cannot be loaded, its window says so and offers **Try again**, **Open a local window** and **Close window**; in the Tauri build, use the page's reload button and **Window → New Window**. -Pasting a fresh Remote Control pairing link saves its tunnel origin and pairs the local backend for browsing, with its device credential kept privately across launches. The code is discarded after the attempt. After revocation, choose **Back to Browse** and paste a fresh link into **Server address or link**. Embedded views pair independently. If server-side pairing is unavailable, update the remote server or use its direct-listener URL for password login; tunnel addresses require pairing. See [Remote Control](remote-control.md). +Pasting a fresh Remote Control pairing link saves its tunnel origin and pairs the local backend for browsing, with its device credential kept privately across launches. The code is discarded after the attempt. Pairing errors name the affected server. After revocation, choose **Back to Browse** and paste a fresh link into **Server address or link**. Known limitation: embedded views authenticate independently and may require their own pairing. If server-side pairing is unavailable, update the remote server or use its direct-listener URL for password login; tunnel addresses require pairing. See [Remote Control](remote-control.md). ## Open a remote project in a tab {#remote-project-tabs} In the desktop app (Electron, or Tauri on Windows), a saved server can also open one of its projects in a tab of this window, beside your local projects: -1. On Home, an empty tab or the **Open a tab** launcher, open **Browse** and choose a saved server. To add one first, use **Server address or link**, then click its new row. -2. The list switches in place to that server's recent projects and folders. Sign in with the inline username/password form if needed. Choose a recent project, or navigate folders and choose **Select Current**. **Back to Browse** returns to the server list. -3. Choosing the folder opens its remote project tab, replacing the originating empty tab. The `+` launcher stays open until this choice. The project joins **Recent** for reopening directly. +1. On Home or an empty tab, open **Browse** and choose a saved server. From the quick launcher, use **Open another project…** first. To add a server, use **Server address or link**, then click its new row. +2. The named server's **Recent** and **Folders** sections appear in place. Sign in using the labelled inline form if needed. Choose a recent project, or navigate folders and choose **Open this folder**. **Back to Browse** returns to the server list. +3. Choosing the folder creates a new remote project occurrence, replacing the originating empty tab. The project joins **Recent**. To join an existing occurrence instead, use its separate **Open** action. -The tab's conversations, files, Git, settings and Missions run on the remote server. Its embedded view shares that server's remote-window storage and may ask you to sign in separately from Browse. Remote tabs participate in startup restoration. Servers without embedded mode show their full interface; profiles that skip TLS verification and Tauri on macOS/Linux open a separate remote window. The embedded page stays on its server and has only notification access to the host. Web clients and Remote Control devices have no remote tabs. +The tab's conversations, files, Git, settings and Missions run on the remote server. Its embedded view shares that server's remote-window storage and may ask you to sign in separately from Browse. Remote tabs participate in startup restoration. Servers without embedded mode show their full interface; profiles that skip TLS verification and Tauri on macOS/Linux open a separate remote window, explicitly indicated by the opening action when choosing the project. The embedded page stays on its server and has only notification access to the host. Web clients and Remote Control devices have no remote tabs. Backend browsing accepts every saved profile's destination address, including loopback, RFC1918 LAN, Docker, Hyper-V, CGNAT/Tailscale (`100.64.0.0/10`), MagicDNS and `*.ts.net`, IPv6 ULA/link-local, and names resolving to these addresses. Your network routes and TLS setup must allow the connection. Certificate verification follows the saved profile and its explicit TLS confirmation. diff --git a/docs/help/es/browser-sidecars.md b/docs/help/es/browser-sidecars.md index e6544844ca..18817333fe 100644 --- a/docs/help/es/browser-sidecars.md +++ b/docs/help/es/browser-sidecars.md @@ -47,7 +47,7 @@ Las plantillas móviles nativas establecen identidad Android/Chromium, orientaci 1. Inicia la herramienta web por separado en el equipo del backend de CodeNomad, escuchando en `127.0.0.1:`. 2. Abre **Configuración → SideCars**. Introduce **Nombre** y **Puerto**; comprueba la **Ruta base** derivada (`/sidecars/`). 3. Establece **Protocolo** para que coincida con el servicio de destino y elige **Modo de prefijo**. -4. Elige **Añadir SideCar** y luego abre el SideCar desde **Explorar** en la página de inicio o en el lanzador; después aparece en **Recientes**. **Nuevo SideCar** abre este formulario. +4. Elige **Añadir SideCar** y ábrelo desde **Explorar** en Inicio o una pestaña vacía; aparecerá en **Recientes** y en la búsqueda del lanzador rápido. **Nuevo SideCar**, bajo la lista del selector, abre este formulario. Elegir un SideCar crea una nueva instancia; su acción separada **Abierta** selecciona la existente ([pestañas de proyecto](projects.md#open-project)). | Opción | Efecto exacto | | --- | --- | diff --git a/docs/help/es/projects.md b/docs/help/es/projects.md index 50b02a6ef2..c3ad486d35 100644 --- a/docs/help/es/projects.md +++ b/docs/help/es/projects.md @@ -4,24 +4,24 @@ Una pestaña de proyecto conecta CodeNomad a una carpeta del equipo del backend. ## Abrir un proyecto {#open-project} -1. **Nueva instancia** (`+`) abre una **Nueva pestaña** vacía con el foco en la búsqueda. Comparte el fondo, logotipo y nombre CodeNomad centrados y los botones grandes de Inicio: **Clonar repo Git**, **Nueva pestaña temporal** y **Nuevo SideCar**. El selector **Recientes | Explorar** muestra cantidades; la búsqueda está debajo, en **Recientes**. Elegir un proyecto local o remoto o un SideCar llena esa pestaña en su posición. La pestaña vacía dura hasta recargar y se cierra sin dejar un proyecto. El logotipo CodeNomad en la barra de título o pestañas abre Inicio, con configuración, idioma y el botón con corazón **Patrocinar** ([Apoyar CodeNomad](sponsor.md)). +1. **Nueva instancia** (`+`) o `Ctrl/Cmd+N` abre una pestaña vacía con el título compacto **Abrir un proyecto**. Inicio comparte el selector **Recientes | Explorar**, cantidades, búsqueda y acciones. **Clonar repo Git**, **Nueva pestaña temporal** y **Nuevo SideCar** están en una barra secundaria bajo la lista; los clones y carpetas temporales usan el backend local. Elegir un proyecto local, remoto o SideCar llena la pestaña en su posición. Las pestañas vacías duran hasta recargar y se cierran sin dejar proyecto. El logotipo abre Inicio con la identidad de CodeNomad, configuración, idioma, enlaces y **Patrocinar** ([Apoyar CodeNomad](sponsor.md)). 2. En **Recientes**, elige un proyecto; o abre **Explorar**, elige **Este equipo** y luego selecciona la carpeta del backend y ábrela. **Explorar** también lista los servidores CodeNomad guardados ([pestañas de proyectos remotos](remote-access.md#remote-project-tabs)) y los SideCars ([SideCars](browser-sidecars.md#register-sidecar)). 3. Para obtener una copia de un repositorio, elige **Clonar repo Git**, introduce la **URL del repositorio** y la **Carpeta de destino** y pulsa **Clonar**. La **Carpeta de destino** se rellena con el nombre del repositorio en la carpeta que contiene tu último clon, o junto a tu proyecto más reciente. **Buscar** elige la carpeta que contendrá el clon; también puedes editar la ruta, incluido el nombre de la carpeta del clon. Explorar un servidor remoto significa explorar el sistema de archivos de ese servidor, no el de tu teléfono o portátil. Abrir un proyecto no crea un daemon de OpenCode distinto para cada pestaña. Las conversaciones son sesiones nativas de OpenCode; su duración no es la de la pestaña. -Elegir un servidor en **Explorar** sustituye la lista por sus proyectos recientes y carpetas. Inicia sesión en el formulario integrado si se solicita y elige un proyecto o navega a una carpeta y pulsa **Seleccionar actual**. Volver a Explorar muestra los servidores. Solo elegir un proyecto rellena la pestaña vacía y cierra el lanzador `+`. La pestaña remota puede pedir su propio inicio de sesión, separado de la exploración. +El servidor elegido en **Explorar** conserva su nombre visible durante el acceso y la navegación. Los campos tienen etiquetas; **Recientes** abre proyectos y **Carpetas** permite navegar. **Abrir esta carpeta** abre la carpeta actual; volver a Explorar muestra los servidores. Solo elegir proyecto llena la pestaña vacía. Limitación conocida: la exploración del backend y la vista nativa se autentican de forma independiente; la pestaña remota puede pedir su propio acceso. La clonación escribe un repositorio en el destino. **Eliminar primero la carpeta de destino si ya existe.** es destructivo: actívalo solo si se puede borrar todo lo que ya haya allí. Usa un destino nuevo si tienes dudas. Una clonación fallida no es motivo para eliminar un proyecto existente; inspecciona el destino y el error indicados antes de reintentar. -Las entradas recientes son accesos directos. **Renombrar workspace** cambia su nombre visible; **Eliminar de recientes** elimina el acceso directo, no sus archivos ni conversaciones. Hacer clic en un proyecto reciente que ya esté abierto abre una pestaña nueva; su botón **Abierta** (**Cambiar al proyecto abierto**) selecciona en cambio la pestaña existente. +Los recientes son accesos directos. Su menú de acciones en Inicio y pestañas vacías ofrece **Renombrar workspace** y **Eliminar de recientes** cuando corresponde; conserva archivos y conversaciones. En Inicio, pestañas vacías y lanzador rápido, pulsar un proyecto local, remoto o SideCar crea una nueva instancia aunque ya esté abierto. La acción separada **Abierta** (**Cambiar al proyecto abierto**) selecciona la existente. ## Usar el lanzador de nuevas instancias {#new-instance-launcher} 1. Mantén pulsado `+` o haz clic derecho; con el foco del teclado allí, usa **Alt+Down**, **Shift+F10** o la tecla Menú. -2. En **Abrir una pestaña**, busca en **Recientes** (proyectos, proyectos remotos y SideCars), abre **Explorar** o elige **Clonar repo Git** o **Nueva pestaña temporal**. +2. **Proyectos recientes** busca solo proyectos locales, remotos y SideCars recientes. Una fila crea una nueva instancia; su acción **Abierta** cambia a la existente. **Abrir otro proyecto…** abre una pestaña vacía para explorar, añadir servidores o crear proyectos. -Un clic normal abre una pestaña vacía. Inicio, desde el logotipo CodeNomad, ofrece las mismas opciones y cantidades en **Recientes** y **Explorar**. Cambia el nombre o quita pestañas recientes allí; gestiona los servidores en **Configuración → Servidores** y los SideCars en **Configuración → SideCars**. Escape cierra el lanzador y devuelve el foco a `+`. +Un clic normal abre una pestaña vacía. El lanzador rápido contiene recientes, su búsqueda y **Abrir otro proyecto…**. Gestiona los recientes en Inicio o una pestaña vacía, los servidores en **Configuración → Servidores** y los SideCars en **Configuración → SideCars**. Escape cierra el lanzador y devuelve el foco a `+`. ## Cerrar una pestaña de proyecto {#close-stop} @@ -40,7 +40,7 @@ Cerrar una ventana entera, salir o recargar no cierra sus conexiones de proyecto ## Espacios de trabajo temporales {#temporary-workspaces} -1. Elige **Nueva pestaña temporal** en la página de inicio o en el lanzador. +1. Elige **Nueva pestaña temporal** bajo la lista en Inicio o una pestaña vacía. 2. Trabaja en la carpeta vacía gestionada por CodeNomad; Git no se inicializa automáticamente. 3. Al cerrar la pestaña, elige **Conservar**, **Descartar** o **Cancelar**. El menú de la pestaña también ofrece **Conservar como proyecto**. diff --git a/docs/help/es/remote-access.md b/docs/help/es/remote-access.md index 7445cbf470..b5f4f921e1 100644 --- a/docs/help/es/remote-access.md +++ b/docs/help/es/remote-access.md @@ -83,9 +83,9 @@ Si un cliente muestra una advertencia de certificado, detente y comprueba el nom ## Guardar un servidor remoto {#saved-servers} -1. En Inicio, una pestaña vacía o el lanzador **Abrir una pestaña**, abre **Explorar** e introduce la dirección o enlace de emparejamiento en **Dirección o enlace del servidor**. Pegar lo añade al instante; Intro confirma el texto escrito. Se guarda el servidor con su nombre de host y se enfoca su fila; un enlace de emparejamiento también empareja el backend local para explorar. El lanzador permanece abierto. Haz clic en la fila para explorar sus proyectos en la misma lista. **Configuración → Servidores** ofrece el mismo campo. -2. Usa un origen HTTPS de confianza. Si su certificado no supera la verificación, aparece **Omitir la verificación TLS** bajo el campo: márcala solo para un servidor de confianza y pulsa Intro de nuevo para guardarlo. Elegir una carpeta o proyecto de ese perfil abre su propia ventana. -3. Elige su fila en **Explorar** para ver los proyectos en la misma lista. Si se solicita, introduce usuario y contraseña del servidor en el formulario integrado. Cambia su nombre o dirección con **Editar servidor** en **Configuración → Servidores**. +1. En Inicio o una pestaña vacía **Abrir un proyecto**, abre **Explorar** e introduce la dirección o enlace en **Dirección o enlace del servidor**. Desde el lanzador rápido, elige primero **Abrir otro proyecto…**. Pegar añade al instante; Intro confirma el texto escrito. Se guarda el servidor, se enfoca su fila y el selector permanece; un enlace también empareja el backend local para explorar. Pulsa la fila para explorar. **Configuración → Servidores** ofrece el mismo campo. +2. Usa un origen HTTPS de confianza. Los errores de certificado y servidor inaccesible están traducidos; el control de información muestra el diagnóstico técnico bajo demanda. **Omitir la verificación TLS** exige una elección explícita: úsalo solo con un servidor de confianza y confirma otra vez. La acción de apertura anuncia al elegir el proyecto que este perfil usa otra ventana. +3. El nombre del servidor permanece visible durante el acceso y la navegación, con campos etiquetados y secciones **Recientes** y **Carpetas**. Los errores de emparejamiento nombran al servidor. **Editar servidor** en **Configuración → Servidores** cambia URL y nombre; sus botones `i` muestran ayuda de URL/TLS bajo demanda. **Configuración → Servidores** gestiona los perfiles (**Editar servidor**, **Eliminar servidor guardado**). Al eliminar uno, primero se olvidan sus credenciales y sesión de exploración del backend, después se quita el marcador y se cierran sus pestañas. Los proyectos y conversaciones remotos permanecen en su servidor. El backend local guarda los secretos de exploración en `remote-server-credentials.json`, junto a su configuración; protege ese archivo como una contraseña. Las vistas integradas mantienen una autenticación separada. @@ -99,9 +99,9 @@ Pegar un enlace nuevo de Control remoto guarda el origen del túnel y empareja e En la aplicación de escritorio (Electron, o Tauri en Windows), un servidor guardado también puede abrir uno de sus proyectos en una pestaña de esta ventana, junto a tus proyectos locales: -1. En Inicio, una pestaña vacía o el lanzador **Abrir una pestaña**, abre **Explorar** y elige un servidor guardado. Para añadirlo primero, usa **Dirección o enlace del servidor** y haz clic en su nueva fila. -2. La lista pasa a mostrar los proyectos recientes y carpetas de ese servidor. Inicia sesión en el formulario integrado si hace falta. Elige un proyecto reciente o navega por las carpetas y pulsa **Seleccionar actual**. **Volver a Explorar** regresa a la lista de servidores. -3. Elegir la carpeta abre su pestaña remota y sustituye la pestaña vacía de origen. El lanzador `+` permanece abierto hasta esa elección. El proyecto se añade a **Recientes** para abrirlo directamente. +1. En Inicio o una pestaña vacía, abre **Explorar** y elige un servidor. Desde el lanzador rápido, usa primero **Abrir otro proyecto…**. Para añadir uno, usa **Dirección o enlace del servidor** y pulsa su fila. +2. El servidor identificado muestra **Recientes** y **Carpetas** en el mismo lugar. Accede en el formulario etiquetado si hace falta. Elige un reciente o navega y pulsa **Abrir esta carpeta**. **Volver a Explorar** regresa a los servidores. +3. Elegir carpeta crea una nueva instancia remota en lugar de la pestaña vacía y la añade a **Recientes**. La acción separada **Abierta** selecciona la existente. La acción de apertura anuncia otra ventana al elegir, incluidos los casos de TLS y Tauri macOS/Linux. Limitación conocida: la exploración del backend y la vista nativa se autentican de forma independiente. Las conversaciones, archivos, Git, ajustes y Missions de la pestaña se ejecutan en el servidor remoto. Su vista integrada comparte el almacenamiento de la ventana remota y puede pedir otro inicio de sesión independiente de Explorar. Las pestañas remotas participan en la restauración al iniciar. Los servidores sin modo integrado muestran su interfaz completa; los perfiles que omiten TLS y Tauri en macOS/Linux abren otra ventana. La página integrada permanece en su servidor y solo dispone de notificaciones en el anfitrión. Los clientes web y dispositivos de Control remoto carecen de pestañas remotas. diff --git a/docs/help/fr/browser-sidecars.md b/docs/help/fr/browser-sidecars.md index 69146e5b79..7fabf1aef1 100644 --- a/docs/help/fr/browser-sidecars.md +++ b/docs/help/fr/browser-sidecars.md @@ -47,7 +47,7 @@ Les modèles mobiles natifs définissent identité Android/Chromium, orientation 1. Démarrez l’outil web séparément sur l’hôte backend CodeNomad, en écoute sur `127.0.0.1:`. 2. Ouvrez **Paramètres → SideCars**. Saisissez **Nom** et **Port** ; vérifiez le **Chemin de base** dérivé (`/sidecars/`). 3. Réglez **Protocole** selon le service amont et choisissez **Mode de préfixe**. -4. Choisissez **Ajouter un SideCar**, puis ouvrez le SideCar depuis **Parcourir** sur l’accueil ou dans le lanceur ; il rejoint alors les **Récents**. **Nouveau SideCar** ouvre ce formulaire. +4. Choisissez **Ajouter un SideCar**, puis ouvrez-le depuis **Parcourir** sur l'accueil ou un onglet vide ; il rejoint **Récents** et la recherche du lanceur rapide. **Nouveau SideCar**, sous la liste du sélecteur, ouvre ce formulaire. Choisir un SideCar crée une nouvelle occurrence ; son action séparée **Ouvert** rejoint l'existante ([onglets de projet](projects.md#open-project)). | Choix | Effet exact | | --- | --- | diff --git a/docs/help/fr/projects.md b/docs/help/fr/projects.md index c080a2ad35..121bdd3020 100644 --- a/docs/help/fr/projects.md +++ b/docs/help/fr/projects.md @@ -4,24 +4,24 @@ Un onglet de projet relie CodeNomad à un dossier sur l’ordinateur du backend. ## Ouvrir un projet {#open-project} -1. Cliquez sur **Nouvelle instance** (`+`) pour ouvrir un **Nouvel onglet** vide, avec le focus dans la recherche. Il reprend le fond de l'accueil, le logo et le nom CodeNomad centrés, les grands boutons **Cloner un dépôt Git**, **Nouvel onglet temporaire** et **Nouveau SideCar**, et le sélecteur **Récents | Parcourir** avec compteurs. La recherche est sous le sélecteur dans **Récents**. Choisir un projet local ou distant ou un SideCar remplit cet onglet sur place. Un onglet vide dure jusqu'au rechargement de la fenêtre et se ferme sans laisser de projet. Le logo CodeNomad de la barre de titre ou d'onglets ouvre l'accueil, qui propose aussi les réglages, la langue et le bouton cœur **Sponsor** ([Soutenir CodeNomad](sponsor.md)). +1. Cliquez sur **Nouvelle instance** (`+`) ou utilisez `Ctrl/Cmd+N` pour ouvrir un onglet vide au titre compact **Ouvrir un projet**. L'accueil partage le même sélecteur **Récents | Parcourir**, les compteurs, la recherche et les actions. **Cloner un dépôt Git**, **Nouvel onglet temporaire** et **Nouveau SideCar** occupent une barre secondaire sous la liste ; clonage et dossiers temporaires ciblent le backend local. Choisir un projet local ou distant ou un SideCar remplit cet onglet sur place. Les onglets vides durent jusqu'au rechargement et se ferment sans laisser de projet. Le logo ouvre l'accueil avec l'identité CodeNomad, les réglages, la langue, les liens et **Sponsor** ([Soutenir CodeNomad](sponsor.md)). 2. Dans **Récents**, choisissez un projet ; ou ouvrez **Parcourir**, choisissez **Cet ordinateur**, puis sélectionnez le dossier du backend et ouvrez-le. **Parcourir** liste aussi les serveurs CodeNomad enregistrés ([onglets de projets distants](remote-access.md#remote-project-tabs)) et les SideCars ([SideCars](browser-sidecars.md#register-sidecar)). 3. Pour une copie de dépôt, choisissez **Cloner un depot Git**, saisissez **URL du depot** et **Dossier de destination**, puis **Cloner**. **Dossier de destination** est prérempli avec le nom du dépôt, dans le dossier qui contient votre dernier clone, sinon à côté de votre projet le plus récent. **Parcourir** choisit le dossier qui contiendra le clone ; vous pouvez aussi modifier le chemin, y compris le nom du dossier du clone. Parcourir un serveur distant signifie parcourir son système de fichiers, pas votre téléphone ou ordinateur portable. Ouvrir un projet ne crée pas un démon OpenCode distinct par onglet. Les conversations sont des sessions natives OpenCode ; leur durée de vie n’est pas celle de l’onglet. -Choisir un serveur dans **Parcourir** remplace la liste par ses projets récents et ses dossiers. Connectez-vous dans le formulaire intégré si demandé, puis choisissez un projet récent ou un dossier avec **Sélectionner le dossier actuel**. Le retour à Parcourir affiche les serveurs. Seul le choix d’un projet remplit l’onglet vide et ferme le lanceur `+`. L’onglet distant peut demander sa propre connexion, séparément du parcours. +Le nom du serveur choisi dans **Parcourir** reste visible pendant la connexion et la navigation. Les champs de connexion sont libellés ; **Récents** ouvre un projet, **Dossiers** parcourt les dossiers. **Ouvrir ce dossier** ouvre le dossier courant ; le retour à Parcourir affiche les serveurs. Seul le choix d'un projet remplit l'onglet vide. Limite connue : le backend de parcours et la vue native s'authentifient indépendamment ; l'onglet distant peut demander sa propre connexion. Le clonage écrit un dépôt dans la destination. **Supprimer d'abord le dossier de destination s'il existe deja.** est destructeur : n’activez cette option que si tout ce qui s’y trouve peut être supprimé. Dans le doute, utilisez une nouvelle destination. Un échec de clonage n’est pas une raison de supprimer un projet existant ; vérifiez la destination et l’erreur signalées avant de réessayer. -Les entrées récentes sont des raccourcis. **Renommer l'espace de travail** change son nom affiché ; **Retirer des récents** retire le raccourci, pas ses fichiers ni ses conversations. Cliquer sur un projet récent déjà ouvert ouvre un nouvel onglet ; son bouton **Ouvert** (**Basculer vers le projet ouvert**) sélectionne plutôt l’onglet existant. +Les récents sont des raccourcis. Leur menu d'actions sur l'accueil et les onglets vides propose **Renommer l'espace de travail** et **Retirer des récents** selon l'entrée ; retirer conserve fichiers et conversations. Partout, accueil, onglet vide et lanceur rapide, cliquer sur un projet local, distant ou un SideCar crée une nouvelle occurrence, même déjà ouvert. L'action séparée **Ouvert** (**Basculer vers le projet ouvert**) rejoint l'occurrence existante. ## Utiliser le lanceur de nouvelle instance {#new-instance-launcher} 1. Appuyez longuement ou faites un clic droit sur `+` ; lorsque ce bouton a le focus clavier, utilisez **Alt+Down**, **Shift+F10** ou la touche Menu. -2. Dans **Ouvrir un onglet**, recherchez parmi les **Récents** (projets, projets distants et SideCars), ouvrez **Parcourir**, ou choisissez **Cloner un dépôt Git** ou **Nouvel onglet temporaire**. +2. **Projets récents** recherche uniquement les projets locaux, distants et SideCars récents. Une ligne crée une nouvelle occurrence ; son action **Ouvert** rejoint l'existante. **Ouvrir un autre projet…** ouvre un onglet vide pour parcourir, ajouter un serveur ou créer un projet. -Un clic normal ouvre un onglet vide. L'accueil, ouvert depuis le logo CodeNomad, propose les mêmes choix et les compteurs dans **Récents** et **Parcourir**. Renommez ou retirez-y les onglets récents ; gérez les serveurs dans **Paramètres → Serveurs** et les SideCars dans **Paramètres → SideCars**. Échap ferme le lanceur et rend le focus à `+`. +Un clic normal ouvre un onglet vide. Le lanceur rapide contient les récents, leur recherche et **Ouvrir un autre projet…**. Gérez les récents sur l'accueil ou un onglet vide, les serveurs dans **Paramètres → Serveurs** et les SideCars dans **Paramètres → SideCars**. Échap ferme le lanceur et rend le focus à `+`. ## Fermer un onglet de projet {#close-stop} @@ -40,7 +40,7 @@ Fermer une fenêtre entière, quitter ou recharger ne ferme pas ses connexions d ## Espaces de travail temporaires {#temporary-workspaces} -1. Choisissez **Nouvel onglet temporaire** sur l’accueil ou dans le lanceur. +1. Choisissez **Nouvel onglet temporaire** sous la liste de l'accueil ou d'un onglet vide. 2. Travaillez dans le dossier vide géré par CodeNomad ; Git n’est pas initialisé automatiquement. 3. À la fermeture de l’onglet, choisissez **Garder**, **Jeter** ou **Annuler**. Le menu de l’onglet propose aussi **Garder comme projet**. diff --git a/docs/help/fr/remote-access.md b/docs/help/fr/remote-access.md index a701d86b15..7e7d4bb413 100644 --- a/docs/help/fr/remote-access.md +++ b/docs/help/fr/remote-access.md @@ -83,9 +83,9 @@ Si un client signale un avertissement de certificat, arrêtez-vous et vérifiez ## Enregistrer un serveur distant {#saved-servers} -1. Sur l’accueil, un onglet vide ou le lanceur **Ouvrir un onglet**, ouvrez **Parcourir** et saisissez l’adresse ou le lien d’appairage dans **Adresse ou lien du serveur**. Le collage l’ajoute immédiatement ; Entrée ajoute le texte saisi. L’ajout enregistre le serveur sous son nom d’hôte et place le focus sur sa ligne ; un lien d’appairage appaire aussi le backend local pour le parcours. Le lanceur reste ouvert. Cliquez sur cette ligne pour parcourir ses projets sur place. **Paramètres → Serveurs** propose le même champ. -2. Utilisez une origine HTTPS de confiance. Si son certificat échoue à la vérification, l’erreur s’affiche sous le champ avec **Ignorer la vérification TLS** : cochez-la seulement pour un serveur de confiance, puis appuyez de nouveau sur Entrée pour l’enregistrer. Choisir un dossier ou un projet de ce profil ouvre sa propre fenêtre. -3. Choisissez sa ligne dans **Parcourir** pour explorer ses projets sur place. Si demandé, saisissez le nom d’utilisateur et le mot de passe du serveur dans le formulaire intégré. Modifiez son nom ou son adresse avec **Modifier le serveur** dans **Paramètres → Serveurs**. +1. Sur l'accueil ou un onglet vide **Ouvrir un projet**, ouvrez **Parcourir** et saisissez l'adresse ou le lien d'appairage dans **Adresse ou lien du serveur**. Depuis le lanceur rapide, choisissez d'abord **Ouvrir un autre projet…**. Coller ajoute immédiatement ; Entrée ajoute le texte saisi. Le serveur est enregistré, sa ligne reçoit le focus et le sélecteur reste en place ; un lien appaire aussi le backend local pour le parcours. Cliquez sur la ligne pour parcourir. **Paramètres → Serveurs** propose le même champ. +2. Utilisez une origine HTTPS de confiance. Les erreurs de certificat et de serveur inaccessible sont localisées ; leur contrôle d'information révèle le diagnostic technique à la demande. **Ignorer la vérification TLS** exige votre choix explicite : réservez-le aux serveurs de confiance, puis validez de nouveau. L'action d'ouverture annonce au choix du projet la fenêtre séparée utilisée par ce profil. +3. Le nom du serveur reste visible à la connexion et pendant la navigation, avec des champs libellés et les sections **Récents** et **Dossiers**. Les erreurs d'appairage nomment le serveur concerné. **Modifier le serveur** dans **Paramètres → Serveurs** change URL et nom ; ses boutons `i` révèlent l'aide URL/TLS à la demande. **Paramètres → Serveurs** gère les profils (**Modifier le serveur**, **Supprimer le serveur enregistré**). La suppression oublie d’abord les identifiants et la session de parcours conservés par le backend, puis retire le favori et ferme ses onglets. Les projets et conversations distants restent sur leur serveur. Le backend local conserve les secrets de parcours dans `remote-server-credentials.json`, à côté de sa configuration ; protégez ce fichier comme un mot de passe. Les vues intégrées gardent leur authentification séparément. @@ -99,9 +99,9 @@ Coller un lien neuf du Contrôle à distance enregistre l’origine du tunnel et Dans l'application de bureau (Electron, ou Tauri sous Windows), un serveur enregistré peut aussi ouvrir l'un de ses projets dans un onglet de cette fenêtre, à côté de vos projets locaux : -1. Sur l’accueil, un onglet vide ou le lanceur **Ouvrir un onglet**, ouvrez **Parcourir** et choisissez un serveur enregistré. Pour en ajouter un, utilisez **Adresse ou lien du serveur**, puis cliquez sur sa nouvelle ligne. -2. La liste affiche sur place les projets récents et les dossiers de ce serveur. Connectez-vous avec le formulaire intégré si nécessaire. Choisissez un projet récent, ou parcourez les dossiers puis choisissez **Sélectionner le dossier actuel**. **Retour à Parcourir** revient à la liste des serveurs. -3. Le choix du dossier ouvre son onglet distant et remplace l’onglet vide d’origine. Le lanceur `+` reste ouvert jusqu’à ce choix. Le projet rejoint **Récents** pour être rouvert directement. +1. Sur l'accueil ou un onglet vide, ouvrez **Parcourir** et choisissez un serveur enregistré. Depuis le lanceur rapide, choisissez d'abord **Ouvrir un autre projet…**. Ajoutez un serveur avec **Adresse ou lien du serveur**, puis cliquez sur sa ligne. +2. Le serveur nommé présente **Récents** et **Dossiers** sur place. Connectez-vous dans le formulaire libellé si nécessaire. Choisissez un récent, ou parcourez les dossiers puis **Ouvrir ce dossier**. **Retour à Parcourir** revient aux serveurs. +3. Le dossier choisi crée une nouvelle occurrence distante à la place de l'onglet vide et rejoint **Récents**. L'action séparée **Ouvert** rejoint l'occurrence existante. Une ouverture en fenêtre séparée est annoncée par l'action au moment du choix, notamment pour le repli TLS et Tauri macOS/Linux. Limite connue : l'authentification du parcours backend et celle de la vue native sont indépendantes. Les conversations, fichiers, Git, paramètres et Missions de l’onglet s’exécutent sur le serveur distant. Sa vue intégrée partage le stockage de la fenêtre distante de ce serveur et peut demander une connexion distincte de Parcourir. Les onglets distants participent à la restauration au démarrage. Les serveurs sans mode intégré affichent leur interface complète ; les profils ignorant TLS et Tauri sous macOS/Linux ouvrent une fenêtre distincte. La page intégrée reste sur son serveur et dispose seulement des notifications sur l’hôte. Les clients web et appareils du Contrôle à distance n’ont pas d’onglets distants. diff --git a/docs/help/he/browser-sidecars.md b/docs/help/he/browser-sidecars.md index 9db16651b4..a9052918a1 100644 --- a/docs/help/he/browser-sidecars.md +++ b/docs/help/he/browser-sidecars.md @@ -47,7 +47,7 @@ 1. הפעילו את כלי הרשת בנפרד במארח שרת הקצה של CodeNomad, בהאזנה ב־`127.0.0.1:`. 2. פתחו **הגדרות → SideCars**. הזינו **שם** ו־**פורט**; בדקו את **נתיב בסיס** הנגזר (`/sidecars/`). 3. הגדירו **פרוטוקול** בהתאם לשירות שמאחוריו, ובחרו **מצב קידומת**. -4. בחרו **הוסף SideCar**, ואז פתחו את ה־SideCar מ־**עיון** בדף הבית או במפעיל; לאחר מכן הוא מופיע ב־**אחרונים**. **SideCar חדש** פותח טופס זה. +4. בחרו **הוסף SideCar** ופתחו אותו מ־**עיון** בדף הבית או בלשונית ריקה; הוא נוסף ל־**אחרונים** ולחיפוש במשגר המהיר. **SideCar חדש**, מתחת לרשימת הבורר, פותח טופס זה. בחירת SideCar יוצרת מופע חדש; הפעולה הנפרדת **פתוח** בוחרת מופע קיים ([לשוניות פרויקט](projects.md#open-project)). | בחירה | השפעה מדויקת | | --- | --- | diff --git a/docs/help/he/projects.md b/docs/help/he/projects.md index 9d38dd15ad..5ca374dabb 100644 --- a/docs/help/he/projects.md +++ b/docs/help/he/projects.md @@ -4,24 +4,24 @@ ## פתיחת פרויקט {#open-project} -1. **מופע חדש** (`+`) פותח **לשונית חדשה** ריקה עם מיקוד בחיפוש. היא משתמשת ברקע של דף הבית, בלוגו ובשם CodeNomad במרכז ובכפתורים הגדולים **שכפל מאגר Git**, **לשונית זמנית חדשה** ו־**SideCar חדש**. הבורר **אחרונים | עיון** מציג מספר פריטים; החיפוש נמצא מתחתיו בתוך **אחרונים**. בחירת פרויקט מקומי או מרוחק או SideCar ממלאת את הלשונית במקומה. לשונית ריקה קיימת עד לטעינה מחדש ונסגרת בלי להשאיר פרויקט. הלוגו של CodeNomad בשורת הכותרת או הלשוניות פותח את דף הבית עם הגדרות, שפה וכפתור הלב **חסות** ([תמיכה ב־CodeNomad](sponsor.md)). +1. **מופע חדש** (`+`) או `Ctrl/Cmd+N` פותח לשונית ריקה עם הכותרת הקומפקטית **פתיחת פרויקט**. דף הבית משתמש באותו בורר **אחרונים | עיון**, מונים, חיפוש ופעולות. **שכפל מאגר Git**, **לשונית זמנית חדשה** ו־**SideCar חדש** נמצאים בסרגל משני מתחת לרשימה; שכפול ותיקיות זמניות משתמשים בשרת הקצה המקומי. בחירת פרויקט מקומי, מרוחק או SideCar ממלאת את הלשונית במקומה. לשוניות ריקות קיימות עד לטעינה מחדש ונסגרות בלי פרויקט. הלוגו פותח את דף הבית עם זהות CodeNomad, הגדרות, שפה, קישורים ו־**חסות** ([תמיכה ב־CodeNomad](sponsor.md)). 2. ב־**אחרונים**, בחרו פרויקט; או פתחו את **עיון**, בחרו **המחשב הזה**, ואז בחרו את תיקיית ה־backend ופתחו אותה. **עיון** מציג גם שרתי CodeNomad שמורים ([לשוניות של פרויקטים מרוחקים](remote-access.md#remote-project-tabs)) ו־SideCars ([SideCars](browser-sidecars.md#register-sidecar)). 3. לעותק מאגר, בחרו **שכפל מאגר Git**, הזינו **כתובת המאגר** ו־**תיקיית יעד**, ואז **שכפל**. **תיקיית יעד** ממולא מראש בשם המאגר, בתיקייה שמכילה את השכפול האחרון שלך, או לצד הפרויקט האחרון שלך. **עיון** בוחר את התיקייה שתכיל את השכפול; אפשר גם לערוך את הנתיב, כולל שם התיקייה של השכפול. עיון בשרת מרוחק הוא עיון במערכת הקבצים שלו, לא בטלפון או במחשב הנייד שלכם. פתיחת פרויקט אינה יוצרת דמון OpenCode נפרד לכל לשונית. שיחות הן סשנים מקוריים של OpenCode; משך חייהן אינו משך חיי הלשונית. -בחירת שרת ב־**עיון** מחליפה את הרשימה בפרויקטים האחרונים ובתיקיות שלו. התחברו בטופס המשולב אם תתבקשו, ואז בחרו פרויקט או נווטו לתיקייה ובחרו **בחר נוכחית**. חזרה לעיון מציגה את השרתים. רק בחירת פרויקט ממלאת את הלשונית הריקה וסוגרת את משגר `+`. הלשונית המרוחקת עשויה לדרוש התחברות משלה, בנפרד מהעיון. +שם השרת שנבחר ב־**עיון** נשאר גלוי במהלך ההתחברות והניווט. לשדות ההתחברות יש תוויות; **אחרונים** פותח פרויקטים ו־**תיקיות** מאפשר ניווט. **פתיחת תיקייה זו** פותח את התיקייה הנוכחית; חזרה לעיון מציגה את השרתים. רק בחירת פרויקט ממלאת את הלשונית הריקה. מגבלה ידועה: העיון דרך שרת הקצה והתצוגה המקורית משתמשים באימות נפרד, ולכן הלשונית עשויה לדרוש התחברות נוספת. שכפול כותב מאגר ליעד. **מחק תחילה את תיקיית היעד אם היא כבר קיימת.** היא אפשרות הרסנית: הפעילו אותה רק כשמותר למחוק את כל מה שכבר נמצא שם. השתמשו ביעד חדש אם אינכם בטוחים. שכפול שנכשל אינו סיבה למחוק פרויקט קיים; בדקו את היעד והשגיאה שדווחו לפני ניסיון חוזר. -רשומות אחרונות הן קיצורי דרך. **שנה שם סביבת עבודה** משנה את שמה המוצג; **הסר מהרשימה האחרונה** מסיר את קיצור הדרך, לא את קבציו או שיחותיו. לחיצה על פרויקט אחרון שכבר פתוח פותחת לשונית חדשה; הכפתור **פתוח** שלו (**עבור לפרויקט הפתוח**) בוחר במקום זאת את הלשונית הקיימת. +רשומות אחרונות הן קיצורי דרך. תפריט הפעולות שלהן בדף הבית ובלשוניות ריקות מציע **שנה שם סביבת עבודה** ו־**הסר מהרשימה האחרונה** לפי הרשומה; הקבצים והשיחות נשמרים. בדף הבית, בלשונית ריקה ובמשגר המהיר, לחיצה על פרויקט מקומי, מרוחק או SideCar יוצרת מופע חדש גם כשהוא כבר פתוח. הפעולה הנפרדת **פתוח** (**עבור לפרויקט הפתוח**) בוחרת במופע הקיים. ## שימוש במשגר המופע החדש {#new-instance-launcher} 1. לחצו לחיצה ארוכה או לחיצה ימנית על `+`; כשהמקלדת ממוקדת בו, השתמשו ב־**Alt+Down**, ב־**Shift+F10** או במקש Menu. -2. ב־**פתיחת לשונית**, חפשו ב־**אחרונים** (פרויקטים, פרויקטים מרוחקים ו־SideCars), פתחו את **עיון**, או בחרו **שכפל מאגר Git** או **לשונית זמנית חדשה**. +2. **פרויקטים אחרונים** מחפש רק פרויקטים מקומיים, מרוחקים ו־SideCars אחרונים. שורה יוצרת מופע חדש; הפעולה **פתוח** עוברת למופע הקיים. **פתיחת פרויקט אחר…** פותח לשונית ריקה לעיון, הוספת שרתים ויצירת פרויקטים. -לחיצה רגילה פותחת לשונית ריקה. דף הבית דרך הלוגו של CodeNomad מציע אותן אפשרויות ואת מספר הפריטים ב־**אחרונים** וב־**עיון**. שנו שם של לשוניות אחרונות או הסירו אותן שם; נהלו שרתים ב־**הגדרות → שרתים** ו־SideCars ב־**הגדרות → SideCars**. Escape סוגר את המפעיל ומחזיר את המיקוד ל־`+`. +לחיצה רגילה פותחת לשונית ריקה. המשגר המהיר מכיל אחרונים, חיפוש ו־**פתיחת פרויקט אחר…**. נהלו אחרונים בדף הבית או בלשונית ריקה, שרתים ב־**הגדרות → שרתים** ו־SideCars ב־**הגדרות → SideCars**. Escape סוגר את המשגר ומחזיר את המיקוד ל־`+`. ## סגירת לשונית פרויקט {#close-stop} @@ -40,7 +40,7 @@ ## סביבות עבודה זמניות {#temporary-workspaces} -1. בחרו **לשונית זמנית חדשה** בדף הבית או במפעיל. +1. בחרו **לשונית זמנית חדשה** מתחת לרשימה בדף הבית או בלשונית ריקה. 2. עבדו בתיקייה הריקה שבניהול CodeNomad; Git אינו מאותחל אוטומטית. 3. בסגירת הלשונית, בחרו **שמור**, **מחק** או **ביטול**. תפריט הלשונית מציע גם **שמור כפרויקט**. diff --git a/docs/help/he/remote-access.md b/docs/help/he/remote-access.md index 32ac5c7e69..cd3a18f87a 100644 --- a/docs/help/he/remote-access.md +++ b/docs/help/he/remote-access.md @@ -83,9 +83,9 @@ codenomad --host 127.0.0.1 --https=false --http=true ## שמירת שרת מרוחק {#saved-servers} -1. בדף הבית, בלשונית ריקה או במשגר **פתיחת לשונית**, פתחו את **עיון** והזינו כתובת או קישור צימוד ב־**כתובת או קישור של השרת**. הדבקה מוסיפה מיד; Enter מוסיף טקסט שהוקלד. ההוספה שומרת את השרת בשם המארח וממקדת את השורה שלו; קישור צימוד גם מצמד את שרת הקצה המקומי לעיון. המשגר נשאר פתוח. לחצו על השורה כדי לעיין בפרויקטים באותה רשימה. **הגדרות → שרתים** מציע את אותו השדה. -2. השתמשו במקור HTTPS מהימן. אם התעודה נכשלת בבדיקה, **דילוג על אימות TLS** מופיע מתחת לשדה: סמנו רק לשרת מהימן והקישו Enter שוב כדי לשמור. בחירת תיקייה או פרויקט בפרופיל הזה פותחת חלון משלו. -3. בחרו בשורת השרת ב־**עיון** כדי לעיין בפרויקטים באותה רשימה. אם תתבקשו, הזינו שם משתמש וסיסמה בטופס המשולב. שנו את שמו או כתובתו באמצעות **עריכת שרת** ב־**הגדרות → שרתים**. +1. בדף הבית או בלשונית ריקה **פתיחת פרויקט**, פתחו **עיון** והזינו כתובת או קישור ב־**כתובת או קישור של השרת**. במשגר המהיר בחרו תחילה **פתיחת פרויקט אחר…**. הדבקה מוסיפה מיד; Enter מאשר טקסט שהוקלד. השרת נשמר, השורה מקבלת מיקוד והבורר נשאר; קישור גם מצמד את שרת הקצה המקומי לעיון. לחצו על השורה לעיון. **הגדרות → שרתים** מציע אותו שדה. +2. השתמשו במקור HTTPS מהימן. שגיאות תעודה ושרת לא נגיש מתורגמות; כפתור המידע מציג אבחון טכני לפי דרישה. **דילוג על אימות TLS** דורש בחירה מפורשת: הפעילו רק לשרת מהימן ואשרו שוב. פעולת הפתיחה מודיעה בעת בחירת הפרויקט שפרופיל זה משתמש בחלון נפרד. +3. שם השרת נשאר גלוי בהתחברות ובניווט, עם שדות מתויגים ואזורים נפרדים של **אחרונים** ו־**תיקיות**. שגיאות צימוד מציינות את השרת. **עריכת שרת** ב־**הגדרות → שרתים** משנה כתובת ושם; כפתורי `i` מציגים עזרת כתובת/TLS לפי דרישה. **הגדרות → שרתים** מנהל פרופילים (**עריכת שרת**, **הסר שרת שמור**). הסרה שוכחת תחילה את פרטי ההתחברות וסשן העיון שבשרת הקצה, ואז מסירה את הסימנייה וסוגרת את לשוניותיה. פרויקטים ושיחות מרוחקים נשארים בשרת שלהם. שרת הקצה המקומי שומר את סודות העיון ב־`remote-server-credentials.json` לצד התצורה שלו; הגנו על קובץ זה כמו על סיסמה. תצוגות מוטמעות שומרות אימות נפרד. @@ -99,9 +99,9 @@ codenomad --host 127.0.0.1 --https=false --http=true ביישום שולחן העבודה (Electron, או Tauri ב-Windows), שרת שמור יכול לפתוח גם אחד מהפרויקטים שלו בלשונית של החלון הזה, לצד הפרויקטים המקומיים שלך: -1. בדף הבית, בלשונית ריקה או במשגר **פתיחת לשונית**, פתחו את **עיון** ובחרו שרת שמור. להוספה תחילה השתמשו ב־**כתובת או קישור של השרת**, ואז לחצו על השורה החדשה. -2. הרשימה מתחלפת באותו מקום לפרויקטים אחרונים ולתיקיות של השרת. התחברו בטופס המשולב לפי הצורך. בחרו פרויקט אחרון, או נווטו לתיקייה ובחרו **בחר נוכחית**. **חזרה לעיון** מחזירה לרשימת השרתים. -3. בחירת תיקייה פותחת לשונית פרויקט מרוחק ומחליפה את הלשונית הריקה המקורית. משגר `+` נשאר פתוח עד הבחירה. הפרויקט נוסף ל־**אחרונים** לפתיחה ישירה. +1. בדף הבית או בלשונית ריקה פתחו **עיון** ובחרו שרת. במשגר המהיר בחרו קודם **פתיחת פרויקט אחר…**. הוסיפו שרת עם **כתובת או קישור של השרת**, ואז לחצו על השורה שלו. +2. השרת המזוהה מציג **אחרונים** ו־**תיקיות** באותו מקום. התחברו בטופס המתויג לפי הצורך. בחרו פרויקט או נווטו ובחרו **פתיחת תיקייה זו**. **חזרה לעיון** מציגה שרתים. +3. בחירת תיקייה יוצרת מופע מרוחק חדש במקום הלשונית הריקה ומוסיפה אותו ל־**אחרונים**. הפעולה הנפרדת **פתוח** בוחרת מופע קיים. פתיחה בחלון נפרד מוכרזת בזמן הבחירה, כולל מקרי TLS ו־Tauri ב־macOS/Linux. מגבלה ידועה: העיון דרך שרת הקצה והתצוגה המקורית משתמשים באימות עצמאי. השיחות, הקבצים, Git, ההגדרות ו־Missions בלשונית פועלים בשרת המרוחק. התצוגה המוטמעת חולקת את אחסון החלון המרוחק שלו ועשויה לדרוש התחברות נפרדת מעיון. לשוניות מרוחקות משתתפות בשחזור בהפעלה. שרתים ללא מצב מוטמע מציגים את הממשק המלא; פרופילים שמדלגים על TLS ו־Tauri ב־macOS/Linux פותחים חלון נפרד. הדף המוטמע נשאר בשרת שלו ויכול רק לשלוח התראות למארח. ללקוחות דפדפן ולמכשירי שליטה מרחוק אין לשוניות מרוחקות. diff --git a/docs/help/ja/browser-sidecars.md b/docs/help/ja/browser-sidecars.md index d620a745b0..dbeee16115 100644 --- a/docs/help/ja/browser-sidecars.md +++ b/docs/help/ja/browser-sidecars.md @@ -47,7 +47,7 @@ 1. CodeNomad バックエンドホストで、ウェブツールを別途起動し、`127.0.0.1:` で待ち受けます。 2. **設定 → SideCar** を開き、**名前** と **ポート** を入力し、算出された **ベースパス**(`/sidecars/`)を確認します。 3. 上流サービスに合わせて **プロトコル** を設定し、**プレフィックスモード** を選びます。 -4. **SideCar を追加** を選び、ホームページまたはランチャーの **参照** から SideCar を開きます。開いた SideCar は **最近** に加わります。**新しい SideCar** はこのフォームを開きます。 +4. **SideCar を追加** を選び、ホームか空タブの **参照** から開きます。**最近** とクイックランチャーの検索に加わります。一覧の下の **新しい SideCar** はこのフォームを開きます。SideCar の選択は新しいインスタンスを作り、独立した **開いています** 操作は既存のものを選びます([プロジェクトタブ](projects.md#open-project))。 | 選択 | 正確な効果 | | --- | --- | diff --git a/docs/help/ja/projects.md b/docs/help/ja/projects.md index 51072120a0..a1ae2246ef 100644 --- a/docs/help/ja/projects.md +++ b/docs/help/ja/projects.md @@ -4,24 +4,24 @@ ## プロジェクトを開く {#open-project} -1. **新しいインスタンス**(`+`)は検索欄にフォーカスした空の **新しいタブ** を開きます。ホームと同じ背景、中央の CodeNomad ロゴと名前、大きな **Git リポジトリをクローン**・**新しい一時タブ**・**新しい SideCar** ボタンを使います。**最近 | 参照** セレクターに件数が表示され、検索はその下の **最近** 内にあります。ローカルまたはリモートのプロジェクトや SideCar を選ぶと、その位置でタブが切り替わります。空のタブは再読み込みまで有効で、プロジェクトを残さず閉じます。タイトルバーまたはタブバーの CodeNomad ロゴは、設定・言語・ハートの **スポンサー** ボタンもあるホームを開きます([CodeNomad を支援](sponsor.md))。 +1. **新しいインスタンス**(`+`)または `Ctrl/Cmd+N` は、コンパクトな **プロジェクトを開く** セレクターを持つ空のタブを開きます。ホームも同じ **最近 | 参照**、件数、検索、操作を使います。**Git リポジトリをクローン**・**新しい一時タブ**・**新しい SideCar** は一覧の下の補助バーにあります。クローンと一時フォルダーはローカルバックエンドを対象とします。プロジェクトや SideCar を選ぶと空のタブがその位置で切り替わります。空のタブは再読み込みまで有効です。ロゴは CodeNomad の名称・設定・言語・リンク・**スポンサー** のあるホームを開きます([CodeNomad を支援](sponsor.md))。 2. **最近** でプロジェクトを選ぶか、**参照** を開いて **このコンピューター** を選び、バックエンドのフォルダーを選択して開きます。**参照** には保存した CodeNomad サーバー([リモートプロジェクトのタブ](remote-access.md#remote-project-tabs))と SideCar([SideCar](browser-sidecars.md#register-sidecar))も表示されます。 3. リポジトリをコピーするには、**Git リポジトリをクローン** を選び、**リポジトリ URL** と **保存先フォルダ** を入力して **クローン** を選びます。**保存先フォルダ** には、前回のクローンがあるフォルダー(なければ最近のプロジェクトと同じ場所)にリポジトリ名のフォルダーが入力されます。**参照** ではクローンを置くフォルダーを選びます。クローンのフォルダー名を含め、パスは直接編集することもできます。 リモートサーバーの参照とは、そのサーバーのファイルシステムの参照であり、スマートフォンやノートパソコンの参照ではありません。プロジェクトを開いても、タブごとに別の OpenCode デーモンは作成されません。会話は OpenCode ネイティブのセッションであり、その寿命はタブの寿命と同じではありません。 -**参照** でサーバーを選ぶと、一覧がその最近のプロジェクトとフォルダーに切り替わります。必要ならインラインフォームでサインインし、最近のプロジェクトを選ぶか、フォルダーを移動して **現在のフォルダを選択** を押します。参照に戻るとサーバー一覧が表示されます。プロジェクトの選択後に空タブが埋まり、`+` ランチャーが閉じます。リモートタブは参照とは別のサインインを求める場合があります。 +**参照** で選んだサーバー名は、サインイン中もフォルダー移動中も表示されます。入力欄にはラベルがあり、**最近のプロジェクト** はプロジェクトを開き、**フォルダー** は移動に使います。**このフォルダーを開く** で現在のフォルダーを開き、参照への戻る操作でサーバー一覧に戻ります。プロジェクトを選ぶと空タブが切り替わります。既知の制限として、バックエンドの参照とネイティブ表示の認証は独立しており、別途サインインを求める場合があります。 クローンは保存先にリポジトリを書き込みます。**保存先フォルダが既に存在する場合は先に削除します。** は破壊的な操作です。そこに既にあるすべての内容を削除してよい場合にのみ有効にしてください。不確かな場合は、新しい保存先を使用します。クローンの失敗を理由に既存のプロジェクトを削除しないでください。再試行する前に、表示された保存先とエラーを確認します。 -最近使った項目はショートカットです。**ワークスペース名を変更** は表示名を変更し、**履歴から削除** はショートカットを削除しますが、ファイルや会話は削除しません。既に開いている最近のプロジェクトをクリックすると新しいタブで開きます。その **開いています** ボタン(**開いているプロジェクトに切り替え**)は、代わりに既存のタブを選択します。 +最近の項目はショートカットです。ホームと空タブの操作メニューでは、項目に応じて **ワークスペース名を変更** と **履歴から削除** を使えます。ファイルと会話は保持されます。ホーム、空タブ、クイックランチャーのどこでも、ローカル・リモートプロジェクトや SideCar の行を選ぶと、既に開いていても新しいインスタンスを作ります。独立した **開いています** 操作(**開いているプロジェクトに切り替え**)は既存のものを選びます。 ## 新しいインスタンスのランチャーを使う {#new-instance-launcher} 1. `+` を長押しまたは右クリックします。キーボードフォーカスがある場合は、**Alt+Down**、**Shift+F10**、または Menu キーを使用します。 -2. **タブを開く** で **最近**(プロジェクト、リモートプロジェクト、SideCar)を検索するか、**参照** を開くか、**Git リポジトリをクローン** または **新しい一時タブ** を選びます。 +2. **最近のプロジェクト** は最近のローカル・リモートプロジェクトと SideCar だけを検索します。行は新しいインスタンスを作り、独立した **開いています** 操作は既存のものに移ります。**別のプロジェクトを開く…** は参照、サーバー追加、作成用の空タブを開きます。 -通常のクリックでは空のタブが開きます。CodeNomad ロゴから開くホームにも、同じ選択肢と **最近**・**参照** の件数があります。最近のタブの名前変更や削除はそこで行い、サーバーは **設定 → サーバー**、SideCar は **設定 → SideCar** で管理します。Escape でランチャーが閉じ、フォーカスが `+` に戻ります。 +通常のクリックでは空タブが開きます。クイックランチャーは最近の項目、検索、**別のプロジェクトを開く…** を提供します。最近の項目はホームか空タブ、サーバーは **設定 → サーバー**、SideCar は **設定 → SideCar** で管理します。Escape で閉じ、フォーカスが `+` に戻ります。 ## タブを閉じてプロジェクトを閉じる {#close-stop} @@ -40,7 +40,7 @@ ## 一時ワークスペース {#temporary-workspaces} -1. ホームページまたはランチャーで **新しい一時タブ** を選びます。 +1. ホームまたは空タブの一覧の下で **新しい一時タブ** を選びます。 2. CodeNomad が管理する空のフォルダーで作業します。Git は自動初期化されません。 3. タブを閉じるときに、**保持**、**破棄**、**キャンセル** を選びます。タブメニューには **プロジェクトとして保持** もあります。 diff --git a/docs/help/ja/remote-access.md b/docs/help/ja/remote-access.md index 9851a32cbc..3f94a24f6d 100644 --- a/docs/help/ja/remote-access.md +++ b/docs/help/ja/remote-access.md @@ -83,9 +83,9 @@ HTTPS が有効で鍵/証明書のペアを指定していない場合、CodeN ## リモートサーバーを保存する {#saved-servers} -1. ホーム、空のタブ、**タブを開く** ランチャーで **参照** を開き、アドレスまたはペアリングリンクを **サーバーのアドレスまたはリンク** に入力します。貼り付けは即座に追加し、手入力は Enter で追加します。サーバーはホスト名で保存され、その行にフォーカスが移ります。ペアリングリンクでは参照用のローカルバックエンドもペアリングします。ランチャーは開いたままです。行をクリックすると、その場でプロジェクトを参照できます。**設定 → サーバー** にも同じ入力欄があります。 -2. 信頼できる HTTPS オリジンを使ってください。証明書の検証に失敗した場合、入力欄の下に **TLS 検証をスキップ** が表示されます。信頼できるサーバーだけでオンにして Enter で保存します。このプロファイルのフォルダーやプロジェクトを選ぶと専用ウィンドウで開きます。 -3. **参照** の保存済みサーバー行を選ぶと、その場でプロジェクトを参照できます。求められたらインラインフォームにユーザー名とパスワードを入力します。名前やアドレスは **設定 → サーバー** の **サーバーを編集** で変更できます。 +1. ホームか空の **プロジェクトを開く** タブで **参照** を開き、アドレスやリンクを **サーバーのアドレスまたはリンク** に入力します。クイックランチャーでは先に **別のプロジェクトを開く…** を選びます。貼り付けは即座に追加し、手入力は Enter で確定します。サーバーを保存して行にフォーカスし、セレクターはそのまま残ります。リンクは参照用バックエンドもペアリングします。行を押すと参照できます。**設定 → サーバー** にも同じ欄があります。 +2. 信頼できる HTTPS オリジンを使います。証明書や接続不能のエラーは翻訳され、情報ボタンで技術的な詳細を確認できます。**TLS 検証をスキップ** は明示的な選択が必要です。信頼するサーバーだけで有効にし、再度確定します。このプロファイルが別ウィンドウを開くことは、プロジェクト選択時の操作に表示されます。 +3. サーバー名はサインインと移動中も表示され、入力欄にはラベルがあり、**最近のプロジェクト** と **フォルダー** が分かれています。ペアリングエラーには対象サーバー名が表示されます。**設定 → サーバー** の **サーバーを編集** で URL と名前を変更し、`i` ボタンで URL/TLS の説明を開けます。 **設定 → サーバー** でプロファイルを管理します(**サーバーを編集**、**保存したサーバーを削除**)。削除時は、まずバックエンドの参照用認証情報とセッションを消去し、ブックマークを削除して関連タブを閉じます。リモートのプロジェクトと会話はサーバーに残ります。ローカルバックエンドは参照用の秘密情報を設定の隣の `remote-server-credentials.json` に保存します。このファイルはパスワードと同様に保護してください。埋め込みビューの認証は独立しています。 @@ -99,9 +99,9 @@ HTTPS が有効で鍵/証明書のペアを指定していない場合、CodeN デスクトップアプリ(Electron、または Windows の Tauri)では、保存済みサーバーのプロジェクトを、ローカルプロジェクトと並べてこのウィンドウのタブで開くこともできます。 -1. ホーム、空のタブ、**タブを開く** ランチャーで **参照** を開き、保存済みサーバーを選びます。先に追加する場合は **サーバーのアドレスまたはリンク** を使い、新しい行をクリックします。 -2. 一覧がその場でサーバーの最近のプロジェクトとフォルダーに切り替わります。必要ならインラインフォームでサインインします。最近のプロジェクトを選ぶか、フォルダーを移動して **現在のフォルダを選択** を押します。**参照に戻る** でサーバー一覧に戻れます。 -3. フォルダーを選ぶとリモートプロジェクトのタブが開き、元の空タブを置き換えます。`+` ランチャーは選択まで開いたままです。プロジェクトは直接開き直せるよう **最近** に追加されます。 +1. ホームか空タブで **参照** を開き、サーバーを選びます。クイックランチャーでは先に **別のプロジェクトを開く…** を選びます。追加には **サーバーのアドレスまたはリンク** を使い、その行を押します。 +2. 名前の表示されたサーバーの **最近のプロジェクト** と **フォルダー** がその場に現れます。必要ならラベル付きフォームでサインインします。最近の項目を選ぶか、移動して **このフォルダーを開く** を押します。**参照に戻る** でサーバー一覧に戻ります。 +3. フォルダー選択は空タブを新しいリモートインスタンスに置き換え、**最近** に追加します。独立した **開いています** 操作は既存のものを選びます。TLS の代替動作や macOS/Linux の Tauri などで別ウィンドウを使う場合、選択時に明示されます。既知の制限として、バックエンドの参照とネイティブ表示の認証は独立しています。 タブの会話、ファイル、Git、設定、Missions はリモートサーバーで動作します。埋め込みビューはそのサーバーのリモートウィンドウのストレージを共有し、参照とは別にサインインを求める場合があります。リモートタブは起動時に復元されます。埋め込みモードのないサーバーは完全な UI を表示し、TLS 検証を省略するプロファイルと macOS/Linux の Tauri は別ウィンドウを開きます。埋め込みページはサーバー内に留まり、ホストへは通知のみ送れます。Web クライアントとリモートコントロール端末にはリモートタブはありません。 diff --git a/docs/help/ne/browser-sidecars.md b/docs/help/ne/browser-sidecars.md index f34f6d05a0..054f739256 100644 --- a/docs/help/ne/browser-sidecars.md +++ b/docs/help/ne/browser-sidecars.md @@ -47,7 +47,7 @@ 1. CodeNomad backend host मा `127.0.0.1:` मा सुन्ने गरी web tool छुट्टै सुरु गर्नुहोस्। 2. **सेटिङहरू → SideCars** खोल्नुहोस्। **नाम** र **पोर्ट** भर्नुहोस्; निकालिएको **आधार मार्ग (Base path)** (`/sidecars/`) जाँच्नुहोस्। 3. upstream सेवासँग मिल्ने **प्रोटोकल** सेट गरी **प्रिफिक्स मोड** रोज्नुहोस्। -4. **SideCar थप्नुहोस्** छान्नुहोस्, अनि गृह पृष्ठ वा लन्चरको **ब्राउज गर्नुहोस्** बाट SideCar खोल्नुहोस्; त्यसपछि यो **हालका** मा देखिन्छ। **नयाँ SideCar** ले यो फारम खोल्छ। +4. **SideCar थप्नुहोस्** छानी गृह पृष्ठ वा खाली ट्याबको **ब्राउज गर्नुहोस्** बाट खोल्नुहोस्; यो **हालका** र छिटो लन्चरको खोजमा आउँछ। सूचीमुनिको **नयाँ SideCar** ले यो फाराम खोल्छ। SideCar छान्दा नयाँ उदाहरण बन्छ; छुट्टै **खोल्नुहोस्** कार्यले विद्यमान उदाहरण रोज्छ ([परियोजना ट्याब](projects.md#open-project))। | चयन | ठ्याक्कै असर | | --- | --- | diff --git a/docs/help/ne/projects.md b/docs/help/ne/projects.md index 6d99852759..e9e12f03ed 100644 --- a/docs/help/ne/projects.md +++ b/docs/help/ne/projects.md @@ -4,24 +4,24 @@ ## परियोजना खोल्नुहोस् {#open-project} -1. **नयाँ उदाहरण** (`+`) ले खोजमा focus भएको खाली **नयाँ ट्याब** खोल्छ। यसमा गृह पृष्ठकै पृष्ठभूमि, बीचमा CodeNomad लोगो र नाम तथा ठूला **Git Repo क्लोन गर्नुहोस्**, **नयाँ अस्थायी ट्याब** र **नयाँ SideCar** बटन हुन्छन्। **हालका | ब्राउज गर्नुहोस्** चयनकर्ताले प्रविष्टि संख्या देखाउँछ; खोज त्यसको तल **हालका** भित्र हुन्छ। स्थानीय वा remote परियोजना वा SideCar छान्दा ट्याब उही स्थानमा भरिन्छ। खाली ट्याब पुनः लोड हुँदासम्म रहन्छ र बन्द गर्दा परियोजना बाँकी रहँदैन। शीर्षक वा ट्याब पट्टीको CodeNomad लोगोले सेटिङ, भाषा र मुटु भएको **प्रायोजन** बटनसहित गृह पृष्ठ खोल्छ ([CodeNomad लाई सहयोग](sponsor.md))। +1. **नयाँ उदाहरण** (`+`) वा `Ctrl/Cmd+N` ले छोटो **परियोजना खोल्नुहोस्** शीर्षक भएको खाली ट्याब खोल्छ। गृह पृष्ठमा पनि उही **हालका | ब्राउज गर्नुहोस्** चयनकर्ता, संख्या, खोज र कार्य हुन्छन्। **Git Repo क्लोन गर्नुहोस्**, **नयाँ अस्थायी ट्याब** र **नयाँ SideCar** सूचीमुनिको सहायक पट्टीमा छन्; क्लोन र अस्थायी फोल्डरले स्थानीय ब्याकएन्ड प्रयोग गर्छन्। परियोजना वा SideCar छान्दा खाली ट्याब उही स्थानमा भरिन्छ। खाली ट्याब पुनः लोडसम्म रहन्छ र बन्द गर्दा परियोजना बाँकी रहँदैन। लोगोले CodeNomad पहिचान, सेटिङ, भाषा, लिङ्क र **प्रायोजन** भएको गृह पृष्ठ खोल्छ ([CodeNomad लाई सहयोग](sponsor.md))। 2. **हालका** मा परियोजना छान्नुहोस्; वा **ब्राउज गर्नुहोस्** खोलेर **यो कम्प्युटर** छान्नुहोस्, अनि backend फोल्डर चयन गरी खोल्नुहोस्। **ब्राउज गर्नुहोस्** ले बचत गरिएका CodeNomad सर्भरहरू ([रिमोट परियोजना ट्याबहरू](remote-access.md#remote-project-tabs)) र SideCar हरू ([SideCars](browser-sidecars.md#register-sidecar)) पनि देखाउँछ। 3. रिपोजिटरी प्रतिलिपिका लागि **Git Repo क्लोन गर्नुहोस्** रोजी **रिपोजिटरी URL** र **गन्तव्य फोल्डर** भर्नुहोस्, अनि **क्लोन गर्नुहोस्**। **गन्तव्य फोल्डर** मा तपाईंको पछिल्लो क्लोन भएको फोल्डरभित्र (नभए सबैभन्दा हालको प्रोजेक्टको छेउमा) रिपोजिटरीको नाम पहिल्यै भरिन्छ। **ब्राउज गर्नुहोस्** ले क्लोन राख्ने फोल्डर छान्छ; क्लोनको फोल्डर नामसहित path आफैँ पनि बदल्न सकिन्छ। रिमोट सर्भर ब्राउज गर्नु त्यस सर्भरको फाइल प्रणाली ब्राउज गर्नु हो, आफ्नो फोन वा ल्यापटपको होइन। परियोजना खोल्दा प्रत्येक ट्याबको छुट्टै OpenCode daemon बन्दैन। कुराकानी नेटिभ OpenCode सत्र हुन्; तिनको आयु ट्याबको आयु होइन। -**ब्राउज गर्नुहोस्** मा सर्भर छान्दा सूची त्यसका हालका परियोजना र folder ले बदलिन्छ। मागिएमा inline form बाट sign in गरी परियोजना छान्नुहोस्, वा folder मा गई **हालको चयन गर्नुहोस्** थिच्नुहोस्। ब्राउजमा फर्कँदा सर्भर सूची देखिन्छ। परियोजना छानेपछि मात्र खाली ट्याब भरिन्छ र `+` लन्चर बन्द हुन्छ। Remote ट्याबले browsing भन्दा छुट्टै sign-in माग्न सक्छ। +**ब्राउज गर्नुहोस्** मा छानिएको सर्भरको नाम लगइन र नेभिगेसनभरि देखिन्छ। लगइन फिल्डमा लेबल छन्; **हालका** ले परियोजना खोल्छ र **फोल्डरहरू** ले भित्र जान दिन्छ। **यो फोल्डर खोल्नुहोस्** ले हालको फोल्डर खोल्छ; ब्राउजमा फर्कँदा सर्भर सूची आउँछ। परियोजना छानेपछि मात्र खाली ट्याब भरिन्छ। ज्ञात सीमा: ब्याकएन्ड ब्राउजिङ र नेटिभ दृश्यको प्रमाणीकरण स्वतन्त्र छ; रिमोट ट्याबले फेरि लगइन माग्न सक्छ। क्लोनले गन्तव्यमा रिपोजिटरी लेख्छ। **यदि पहिले नै अवस्थित छ भने पहिले गन्तव्य फोल्डर हटाउनुहोस्।** विनाशकारी छ: त्यहाँका सबै सामग्री मेट्न मिल्दा मात्र सक्षम गर्नुहोस्। अनिश्चित भए नयाँ गन्तव्य प्रयोग गर्नुहोस्। क्लोन असफल भयो भन्दै विद्यमान परियोजना नमेट्नुहोस्; फेरि प्रयासअघि देखाइएको गन्तव्य र त्रुटि जाँच्नुहोस्। -भर्खरका प्रविष्टि shortcut हुन्। **कार्यस्थान पुन: नामकरण गर्नुहोस्** ले देखिने नाम बदल्छ; **भर्खरको सूचीबाट हटाउनुहोस्** ले shortcut हटाउँछ, फाइल वा कुराकानी होइन। पहिले नै खुला recent परियोजना क्लिक गर्दा नयाँ ट्याब खुल्छ; त्यसको सट्टा विद्यमान ट्याब चयन गर्न त्यसको **खोल्नुहोस्** बटन (**खुला परियोजनामा जानुहोस्**) प्रयोग गर्नुहोस्। +हालका प्रविष्टि सर्टकट हुन्। गृह पृष्ठ र खाली ट्याबको कार्य मेनुमा उपलब्ध भएअनुसार **कार्यस्थान पुन: नामकरण गर्नुहोस्** र **भर्खरको सूचीबाट हटाउनुहोस्** छन्; फाइल र कुराकानी रहन्छन्। गृह पृष्ठ, खाली ट्याब र छिटो लन्चरमा स्थानीय वा रिमोट परियोजना वा SideCar क्लिक गर्दा पहिले खुला भए पनि नयाँ उदाहरण बन्छ। छुट्टै **खोल्नुहोस्** कार्य (**खुला परियोजनामा जानुहोस्**) ले विद्यमान उदाहरण रोज्छ। ## नयाँ-इन्स्ट्यान्स launcher प्रयोग गर्नुहोस् {#new-instance-launcher} 1. `+` लामो थिच्नुहोस् वा right-click गर्नुहोस्; त्यहाँ keyboard focus हुँदा **Alt+Down**, **Shift+F10** वा Menu key प्रयोग गर्नुहोस्। -2. **ट्याब खोल्नुहोस्** मा **हालका** (परियोजना, रिमोट परियोजना र SideCar) खोज्नुहोस्, **ब्राउज गर्नुहोस्** खोल्नुहोस्, वा **Git Repo क्लोन गर्नुहोस्** वा **नयाँ अस्थायी ट्याब** छान्नुहोस्। +2. **हालका परियोजनाहरू** ले हालका स्थानीय, रिमोट परियोजना र SideCar मात्र खोज्छ। पङ्क्तिले नयाँ उदाहरण खोल्छ; छुट्टै **खोल्नुहोस्** कार्यले विद्यमानमा लैजान्छ। **अर्को परियोजना खोल्नुहोस्…** ले ब्राउजिङ, सर्भर थप्न र परियोजना सिर्जना गर्न खाली ट्याब खोल्छ। -सामान्य क्लिकले खाली ट्याब खोल्छ। CodeNomad लोगोबाट खुल्ने गृह पृष्ठमा उही विकल्प र **हालका** तथा **ब्राउज गर्नुहोस्** का प्रविष्टि संख्या छन्। हालका ट्याबहरूको नाम बदल्ने वा हटाउने काम त्यहीँ गर्नुहोस्; सर्भरहरू **सेटिङहरू → सर्भरहरू** मा र SideCar हरू **सेटिङहरू → SideCars** मा व्यवस्थापन गर्नुहोस्। Escape ले लन्चर बन्द गरी focus `+` मा फर्काउँछ। +सामान्य क्लिकले खाली ट्याब खोल्छ। छिटो लन्चरमा हालका, खोज र **अर्को परियोजना खोल्नुहोस्…** छन्। हालका प्रविष्टि गृह पृष्ठ वा खाली ट्याबमा, सर्भर **सेटिङहरू → सर्भरहरू** मा र SideCar **सेटिङहरू → SideCars** मा व्यवस्थापन गर्नुहोस्। Escape ले लन्चर बन्द गरी फोकस `+` मा फर्काउँछ। ## ट्याब बन्द गरेर परियोजना बन्द गर्नुहोस् {#close-stop} @@ -40,7 +40,7 @@ ## अस्थायी कार्यस्थान {#temporary-workspaces} -1. गृह पृष्ठमा वा लन्चरमा **नयाँ अस्थायी ट्याब** छान्नुहोस्। +1. गृह पृष्ठ वा खाली ट्याबको सूचीमुनि **नयाँ अस्थायी ट्याब** छान्नुहोस्। 2. खाली CodeNomad-व्यवस्थित फोल्डरमा काम गर्नुहोस्; Git स्वतः सुरु हुँदैन। 3. ट्याब बन्द गर्दा **राख्नुहोस्**, **हटाउनुहोस्** वा **रद्द गर्नुहोस्** रोज्नुहोस्। ट्याब menu मा **परियोजनाको रूपमा राख्नुहोस्** पनि छ। diff --git a/docs/help/ne/remote-access.md b/docs/help/ne/remote-access.md index ef9aa1d9cf..58f2c8f4fc 100644 --- a/docs/help/ne/remote-access.md +++ b/docs/help/ne/remote-access.md @@ -83,9 +83,9 @@ certificate चेतावनी आए रोकिएर hostname, SAN, trust ## remote server बचत {#saved-servers} -1. गृह पृष्ठ, खाली ट्याब वा **ट्याब खोल्नुहोस्** लन्चरमा **ब्राउज गर्नुहोस्** खोली ठेगाना वा pairing link **सर्भरको ठेगाना वा लिङ्क** मा राख्नुहोस्। टाँस्दा तुरुन्त थपिन्छ; टाइप गरेको पाठ Enter ले थप्छ। सर्भर host name मा बचत हुन्छ र यसको पङ्क्तिमा focus जान्छ; pairing link ले browsing का लागि local backend पनि pair गर्छ। लन्चर खुलै रहन्छ। त्यही सूचीमा परियोजना हेर्न पङ्क्ति क्लिक गर्नुहोस्। **सेटिङहरू → सर्भरहरू** मा पनि यही फिल्ड छ। -2. विश्वसनीय HTTPS origin प्रयोग गर्नुहोस्। प्रमाणपत्र जाँच असफल भए फिल्डमुनि **TLS प्रमाणीकरण छोड्नुहोस्** देखिन्छ: विश्वसनीय सर्भरका लागि मात्र चिन्ह लगाई बचत गर्न फेरि Enter थिच्नुहोस्। यो profile को folder वा परियोजना छान्दा आफ्नै विन्डोमा खुल्छ। -3. **ब्राउज गर्नुहोस्** मा सर्भरको पङ्क्ति छानेर त्यही सूचीमा परियोजना हेर्नुहोस्। मागिएमा inline form मा username र password दिनुहोस्। नाम वा ठेगाना **सेटिङहरू → सर्भरहरू** को **सर्भर सम्पादन गर्नुहोस्** बाट बदल्नुहोस्। +1. गृह पृष्ठ वा खाली **परियोजना खोल्नुहोस्** ट्याबमा **ब्राउज गर्नुहोस्** खोली **सर्भरको ठेगाना वा लिङ्क** मा ठेगाना वा लिंक राख्नुहोस्। छिटो लन्चरमा पहिले **अर्को परियोजना खोल्नुहोस्…** रोज्नुहोस्। टाँस्दा तुरुन्त थपिन्छ; Enter ले टाइप गरेको पाठ थप्छ। सर्भर बचत भएर पङ्क्तिमा फोकस जान्छ र चयनकर्ता रहन्छ; लिंकले ब्राउजिङका लागि स्थानीय ब्याकएन्ड पनि पेयर गर्छ। ब्राउज गर्न पङ्क्ति थिच्नुहोस्। **सेटिङहरू → सर्भरहरू** मा पनि यही फिल्ड छ। +2. विश्वसनीय HTTPS स्रोत प्रयोग गर्नुहोस्। प्रमाणपत्र र सर्भर नपुग्ने त्रुटि अनुवादित छन्; सूचना बटनबाट प्राविधिक विवरण माग्न सकिन्छ। **TLS प्रमाणीकरण छोड्नुहोस्** स्पष्ट रोजाइ चाहिन्छ: विश्वसनीय सर्भरका लागि मात्र रोजी फेरि पुष्टि गर्नुहोस्। यो प्रोफाइलले छुट्टै विन्डो खोल्ने कुरा परियोजना छान्ने कार्यमा स्पष्ट हुन्छ। +3. सर्भरको नाम लगइन र नेभिगेसनभरि देखिन्छ; फिल्ड लेबलसहित छन् र **हालका** तथा **फोल्डरहरू** छुट्टाछुट्टै छन्। पेयरिङ त्रुटिले सम्बन्धित सर्भरको नाम दिन्छ। **सेटिङहरू → सर्भरहरू** को **सर्भर सम्पादन गर्नुहोस्** ले URL र नाम बदल्छ; `i` बटनले URL/TLS सहायता माग्दा देखाउँछ। **सेटिङहरू → सर्भरहरू** मा profile व्यवस्थापन हुन्छ (**सर्भर सम्पादन गर्नुहोस्**, **बचत गरिएको सर्भर हटाउनुहोस्**)। हटाउँदा पहिले backend मा भएका browsing credential र session बिर्सिन्छ, अनि bookmark हट्छ र सम्बन्धित ट्याब बन्द हुन्छन्। Remote परियोजना र कुराकानी सर्भरमै रहन्छन्। स्थानीय backend ले browsing secret आफ्नो configuration सँगै `remote-server-credentials.json` मा राख्छ; यो फाइललाई password जस्तै सुरक्षित राख्नुहोस्। Embedded view को authentication छुट्टै हुन्छ। @@ -99,9 +99,9 @@ certificate चेतावनी आए रोकिएर hostname, SAN, trust डेस्कटप एपमा (Electron, वा Windows मा Tauri), बचत गरिएको सर्भरले आफ्नो कुनै परियोजना यो सञ्झ्यालको ट्याबमा, तपाईंका स्थानीय परियोजनाहरूसँगै, खोल्न पनि सक्छ: -1. गृह पृष्ठ, खाली ट्याब वा **ट्याब खोल्नुहोस्** लन्चरमा **ब्राउज गर्नुहोस्** खोली बचत गरिएको सर्भर छान्नुहोस्। पहिले थप्न **सर्भरको ठेगाना वा लिङ्क** प्रयोग गरी नयाँ पङ्क्ति क्लिक गर्नुहोस्। -2. त्यही सूचीमा सर्भरका हालका परियोजना र folder देखिन्छन्। आवश्यक भए inline form बाट sign in गर्नुहोस्। हालको परियोजना छान्नुहोस् वा folder मा गई **हालको चयन गर्नुहोस्** थिच्नुहोस्। **ब्राउजमा फर्कनुहोस्** ले सर्भर सूची देखाउँछ। -3. Folder छान्दा remote project ट्याब खुल्छ र सुरुको खाली ट्याबलाई बदल्छ। `+` लन्चर यो छनोटसम्म खुलै रहन्छ। परियोजना सिधै फेरि खोल्न **हालका** मा थपिन्छ। +1. गृह पृष्ठ वा खाली ट्याबमा **ब्राउज गर्नुहोस्** खोली सर्भर छान्नुहोस्। छिटो लन्चरमा पहिले **अर्को परियोजना खोल्नुहोस्…** रोज्नुहोस्। थप्न **सर्भरको ठेगाना वा लिङ्क** प्रयोग गरी पङ्क्ति थिच्नुहोस्। +2. नाम देखिएको सर्भरका **हालका** र **फोल्डरहरू** त्यहीँ आउँछन्। आवश्यक भए लेबलयुक्त फाराममा लगइन गर्नुहोस्। हालको परियोजना छान्नुहोस् वा भित्र गई **यो फोल्डर खोल्नुहोस्** रोज्नुहोस्। **ब्राउजमा फर्कनुहोस्** ले सर्भर देखाउँछ। +3. फोल्डर छान्दा खाली ट्याबको ठाउँमा नयाँ रिमोट उदाहरण बन्छ र **हालका** मा थपिन्छ। छुट्टै **खोल्नुहोस्** कार्यले विद्यमान उदाहरण रोज्छ। TLS विकल्प र Tauri macOS/Linux लगायतमा छुट्टै विन्डो खुल्ने कुरा छान्ने बेलामै भनिन्छ। ज्ञात सीमा: ब्याकएन्ड ब्राउजिङ र नेटिभ दृश्य स्वतन्त्र प्रमाणीकरण प्रयोग गर्छन्। ट्याबका कुराकानी, फाइल, Git, सेटिङ र Missions remote server मा चल्छन्। Embedded view ले सर्भरको remote-window storage साझा गर्छ र Browse भन्दा छुट्टै sign-in माग्न सक्छ। Remote ट्याब startup restoration मा फर्कन्छन्। Embedded mode नभएका सर्भरले पूर्ण UI देखाउँछन्; TLS verification छोड्ने profile र macOS/Linux को Tauri ले छुट्टै window खोल्छन्। Embedded page सर्भरमै रहन्छ र host मा notification मात्र दिन सक्छ। Web client र Remote Control device मा remote ट्याब हुँदैनन्। diff --git a/docs/help/ru/browser-sidecars.md b/docs/help/ru/browser-sidecars.md index 7ea2092834..d9891d7215 100644 --- a/docs/help/ru/browser-sidecars.md +++ b/docs/help/ru/browser-sidecars.md @@ -47,7 +47,7 @@ 1. Отдельно запустите веб-инструмент на хосте серверной части CodeNomad с прослушиванием `127.0.0.1:`. 2. Откройте **Настройки → SideCars**. Введите **Имя** и **Порт**; проверьте вычисленный **Базовый путь** (`/sidecars/`). 3. Задайте **Протокол** по исходной службе и выберите **Режим префикса**. -4. Выберите **Добавить SideCar**, затем откройте SideCar из **Обзор** на главной странице или в панели запуска; после этого он появится в **Недавние**. **Новый SideCar** открывает эту форму. +4. Выберите **Добавить SideCar** и откройте его из **Обзор** на главной странице или пустой вкладке; он появится в **Недавние** и поиске быстрого меню. **Новый SideCar** под списком открывает эту форму. Выбор SideCar создаёт новый экземпляр; отдельное действие **Открыта** выбирает существующий ([вкладки проектов](projects.md#open-project)). | Выбор | Точный эффект | | --- | --- | diff --git a/docs/help/ru/projects.md b/docs/help/ru/projects.md index f5e51b306d..3bdafa930a 100644 --- a/docs/help/ru/projects.md +++ b/docs/help/ru/projects.md @@ -4,24 +4,24 @@ ## Открытие проекта {#open-project} -1. **Новый экземпляр** (`+`) открывает пустую **Новую вкладку** с фокусом в поиске. Она использует фон главной страницы, логотип и имя CodeNomad по центру и большие кнопки **Клонировать Git-репозиторий**, **Новая временная вкладка**, **Новый SideCar**. Переключатель **Недавние | Обзор** показывает число элементов; поиск расположен под ним в **Недавние**. Выбор локального или удалённого проекта либо SideCar заполняет вкладку на её месте. Пустая вкладка существует до перезагрузки и закрывается без оставшегося проекта. Логотип CodeNomad в заголовке или панели вкладок открывает главную страницу с настройками, языком и кнопкой с сердцем **Спонсировать** ([Поддержать CodeNomad](sponsor.md)). +1. **Новый экземпляр** (`+`) или `Ctrl/Cmd+N` открывает пустую вкладку с компактным заголовком **Открыть проект**. Главная страница использует тот же переключатель **Недавние | Обзор**, счётчики, поиск и действия. **Клонировать Git-репозиторий**, **Новая временная вкладка** и **Новый SideCar** расположены на вспомогательной панели под списком; клонирование и временные папки используют локальный бэкенд. Выбор проекта или SideCar заполняет пустую вкладку на её месте. Пустые вкладки существуют до перезагрузки и закрываются без проекта. Логотип открывает главную страницу с названием CodeNomad, настройками, языком, ссылками и **Спонсировать** ([Поддержать CodeNomad](sponsor.md)). 2. В **Недавние** выберите проект; или откройте **Обзор**, выберите **Этот компьютер**, затем укажите папку на бэкенде и откройте её. **Обзор** также показывает сохранённые серверы CodeNomad ([вкладки удалённых проектов](remote-access.md#remote-project-tabs)) и SideCar ([SideCar](browser-sidecars.md#register-sidecar)). 3. Для копирования репозитория выберите **Клонировать Git-репозиторий**, заполните **URL репозитория** и **Папка назначения**, затем нажмите **Клонировать**. **Папка назначения** заполняется заранее: папка с именем репозитория в папке, где лежит последний клон, а без него — рядом с последним проектом. **Обзор** выбирает папку, в которой будет клон; путь, включая имя папки клона, можно изменить и вручную. Просмотр удалённого сервера означает просмотр его файловой системы, а не телефона или ноутбука. Открытие проекта не создаёт отдельный демон OpenCode для каждой вкладки. Разговоры — нативные сессии OpenCode; их время жизни не совпадает со временем жизни вкладки. -Выбор сервера в **Обзор** заменяет список его недавними проектами и папками. При запросе войдите во встроенной форме, затем выберите проект или перейдите в папку и нажмите **Выбрать текущую**. Возврат к обзору показывает серверы. Только выбор проекта заполняет пустую вкладку и закрывает панель `+`. Удалённая вкладка может запросить отдельный вход независимо от просмотра. +Имя сервера из **Обзор** остаётся видимым при входе и навигации. Поля входа подписаны; **Недавние** открывает проекты, **Папки** позволяет переходить по папкам. **Открыть эту папку** открывает текущую папку; возврат к обзору показывает серверы. Только выбор проекта заполняет пустую вкладку. Известное ограничение: просмотр через бэкенд и нативная панель используют независимую аутентификацию; вкладка может запросить отдельный вход. Клонирование записывает репозиторий в папку назначения. Параметр **Сначала удалить папку назначения, если она уже существует.** разрушителен: включайте его, только если всё уже находящееся там можно удалить. Если не уверены, используйте новую папку. Неудачное клонирование не повод удалять существующий проект; перед повтором проверьте указанные папку назначения и ошибку. -Недавние записи — это ярлыки. **Переименовать рабочее пространство** меняет отображаемое имя; **Убрать из недавних** удаляет ярлык, но не файлы и разговоры. Щелчок по уже открытому недавнему проекту открывает новую вкладку; его кнопка **Открыта** (**Перейти к открытому проекту**) вместо этого выбирает существующую вкладку. +Недавние записи — ярлыки. Их меню действий на главной странице и пустых вкладках предлагает **Переименовать рабочее пространство** и **Убрать из недавних**, когда применимо; файлы и разговоры сохраняются. На главной странице, пустой вкладке и в быстром меню нажатие на локальный или удалённый проект либо SideCar создаёт новый экземпляр, даже если он уже открыт. Отдельное действие **Открыта** (**Перейти к открытому проекту**) выбирает существующий экземпляр. ## Меню нового экземпляра {#new-instance-launcher} 1. Удерживайте `+` или щёлкните правой кнопкой; когда на ней фокус, используйте **Alt+Down**, **Shift+F10** или клавишу Menu. -2. В **Открыть вкладку** найдите нужное в **Недавние** (проекты, удалённые проекты и SideCar), откройте **Обзор** или выберите **Клонировать Git-репозиторий** или **Новая временная вкладка**. +2. **Недавние проекты** ищет только недавние локальные и удалённые проекты и SideCar. Строка создаёт новый экземпляр; отдельное действие **Открыта** переходит к существующему. **Открыть другой проект…** открывает пустую вкладку для обзора, добавления серверов и создания проектов. -Обычный щелчок открывает пустую вкладку. Главная страница через логотип CodeNomad предлагает те же варианты и число элементов в **Недавние** и **Обзор**. Переименовывайте и удаляйте недавние вкладки там; серверами управляйте в **Настройки → Серверы**, а SideCar — в **Настройки → SideCars**. Escape закрывает панель запуска и возвращает фокус на `+`. +Обычный щелчок открывает пустую вкладку. Быстрое меню содержит недавние проекты, поиск и **Открыть другой проект…**. Управляйте недавними на главной странице или пустой вкладке, серверами в **Настройки → Серверы**, SideCar в **Настройки → SideCars**. Escape закрывает меню и возвращает фокус на `+`. ## Закрытие вкладки проекта {#close-stop} @@ -40,7 +40,7 @@ ## Временные рабочие пространства {#temporary-workspaces} -1. Выберите **Новая временная вкладка** на главной странице или в панели запуска. +1. Выберите **Новая временная вкладка** под списком на главной странице или пустой вкладке. 2. Работайте в пустой папке под управлением CodeNomad; Git автоматически не инициализируется. 3. При закрытии вкладки выберите **Сохранить**, **Удалить** или **Отмена**. В меню вкладки также есть **Сохранить как проект**. diff --git a/docs/help/ru/remote-access.md b/docs/help/ru/remote-access.md index fd47d8edea..4689a25d06 100644 --- a/docs/help/ru/remote-access.md +++ b/docs/help/ru/remote-access.md @@ -83,9 +83,9 @@ codenomad --host 127.0.0.1 --https=false --http=true ## Сохранение удалённого сервера {#saved-servers} -1. На главной странице, пустой вкладке или в панели **Открыть вкладку** откройте **Обзор** и введите адрес или ссылку сопряжения в **Адрес или ссылка сервера**. Вставка добавляет сразу, Enter подтверждает набранный текст. Сервер сохраняется под именем хоста, фокус переходит на его строку; ссылка сопряжения также сопрягает локальную серверную часть для просмотра. Панель остаётся открытой. Нажмите на строку для просмотра проектов на месте. В **Настройки → Серверы** есть то же поле. -2. Используйте доверенный HTTPS-источник. Если сертификат не прошёл проверку, под полем появится **Пропустить проверку TLS**: включайте это только для доверенного сервера и снова нажмите Enter для сохранения. Выбор папки или проекта этого профиля открывает отдельное окно. -3. Выберите строку сервера в **Обзор**, чтобы просматривать проекты на месте. При запросе введите имя пользователя и пароль во встроенной форме. Имя и адрес меняются через **Изменить сервер** в **Настройки → Серверы**. +1. На главной странице или пустой вкладке **Открыть проект** откройте **Обзор** и введите адрес или ссылку в **Адрес или ссылка сервера**. В быстром меню сначала выберите **Открыть другой проект…**. Вставка добавляет сразу, Enter подтверждает текст. Сервер сохраняется, строка получает фокус, выбор остаётся на месте; ссылка также сопрягает локальный бэкенд для просмотра. Нажмите строку для просмотра. **Настройки → Серверы** предлагает то же поле. +2. Используйте доверенный HTTPS-источник. Ошибки сертификата и недоступности сервера переведены; технические детали доступны через кнопку информации. **Пропустить проверку TLS** требует явного выбора: только для доверенного сервера, затем подтвердите снова. Действие открытия сообщает при выборе проекта, что профиль использует отдельное окно. +3. Имя сервера видно при входе и навигации, поля подписаны, разделы **Недавние** и **Папки** разделены. Ошибки сопряжения называют сервер. **Изменить сервер** в **Настройки → Серверы** меняет URL и имя; кнопки `i` открывают справку URL/TLS по запросу. **Настройки → Серверы** управляет профилями (**Изменить сервер**, **Удалить сохраненный сервер**). При удалении сначала забываются учётные данные и сеанс просмотра в серверной части, затем удаляется закладка и закрываются её вкладки. Удалённые проекты и разговоры остаются на своём сервере. Локальная серверная часть хранит секреты просмотра в `remote-server-credentials.json` рядом с конфигурацией; защищайте файл как пароль. Встроенные представления сохраняют отдельную аутентификацию. @@ -99,9 +99,9 @@ codenomad --host 127.0.0.1 --https=false --http=true В настольном приложении (Electron или Tauri в Windows) сохранённый сервер может также открыть один из своих проектов во вкладке этого окна, рядом с локальными проектами: -1. На главной странице, пустой вкладке или в панели **Открыть вкладку** откройте **Обзор** и выберите сохранённый сервер. Для добавления используйте **Адрес или ссылка сервера**, затем нажмите на новую строку. -2. Список на месте переключится на недавние проекты и папки сервера. При необходимости войдите во встроенной форме. Выберите недавний проект или перейдите в папку и нажмите **Выбрать текущую**. **Назад к обзору** открывает список серверов. -3. Выбор папки открывает вкладку удалённого проекта вместо исходной пустой вкладки. Панель `+` остаётся открытой до выбора. Проект добавляется в **Недавние** для прямого открытия. +1. На главной странице или пустой вкладке откройте **Обзор** и выберите сервер. В быстром меню сначала используйте **Открыть другой проект…**. Добавьте сервер через **Адрес или ссылка сервера**, затем нажмите его строку. +2. Сервер с видимым именем показывает **Недавние** и **Папки** на месте. При необходимости войдите в подписанной форме. Выберите проект или перейдите в папку и нажмите **Открыть эту папку**. **Назад к обзору** показывает серверы. +3. Выбор папки создаёт новый удалённый экземпляр вместо пустой вкладки и добавляет его в **Недавние**. Отдельное действие **Открыта** выбирает существующий экземпляр. Отдельное окно явно объявляется при выборе, в том числе для TLS и Tauri macOS/Linux. Известное ограничение: просмотр через бэкенд и нативная панель аутентифицируются независимо. Беседы, файлы, Git, настройки и Missions вкладки работают на удалённом сервере. Встроенное представление использует хранилище удалённого окна и может запросить отдельный вход независимо от Обзора. Удалённые вкладки восстанавливаются при запуске. Серверы без встроенного режима показывают полный интерфейс; профили без проверки TLS и Tauri в macOS/Linux открывают отдельное окно. Встроенная страница остаётся на своём сервере и имеет только доступ к уведомлениям хоста. У веб-клиентов и устройств удалённого управления нет удалённых вкладок. diff --git a/docs/help/tr/browser-sidecars.md b/docs/help/tr/browser-sidecars.md index 3fd6838caa..c0303dc544 100644 --- a/docs/help/tr/browser-sidecars.md +++ b/docs/help/tr/browser-sidecars.md @@ -47,7 +47,7 @@ Yerel mobil şablonlar Android/Chromium kimliğini, yönelimini, dokunuşunu ve 1. Web aracını CodeNomad arka ucunun ana bilgisayarında ayrı olarak başlatıp `127.0.0.1:` adresinde dinlemesini sağlayın. 2. **Ayarlar → SideCars** öğesini açın. **Ad** ve **Port** öğesini girin; türetilen **Temel yol** öğesini (`/sidecars/`) kontrol edin. 3. **Protokol** öğesini yukarı akış hizmetiyle eşleşecek şekilde ayarlayın ve **Ön ek modu** öğesini seçin. -4. **SideCar ekle** seçin, ardından SideCar'ı ana sayfadaki veya başlatıcıdaki **Gözat** bölümünden açın; sonra **Son kullanılanlar** arasında görünür. **Yeni SideCar** bu formu açar. +4. **SideCar ekle** seçip ana sayfa veya boş sekmenin **Gözat** bölümünden açın; **Son kullanılanlar** ve hızlı başlatıcı aramasına katılır. Listenin altındaki **Yeni SideCar** bu formu açar. SideCar seçmek yeni örnek oluşturur; ayrı **Aç** eylemi mevcut örneğe geçer ([proje sekmeleri](projects.md#open-project)). | Seçim | Kesin etki | | --- | --- | diff --git a/docs/help/tr/projects.md b/docs/help/tr/projects.md index 726d8cbcf5..4896fb8f0d 100644 --- a/docs/help/tr/projects.md +++ b/docs/help/tr/projects.md @@ -4,24 +4,24 @@ Bir proje sekmesi CodeNomad'i arka uç bilgisayarındaki bir klasöre bağlar. S ## Bir proje açın {#open-project} -1. **Yeni instance** (`+`), aramaya odaklanan boş bir **Yeni sekme** açar. Ana sayfanın arka planını, ortalanmış CodeNomad logosu ve adını, büyük **Git Deposunu Klonla**, **Yeni geçici sekme** ve **Yeni SideCar** düğmelerini kullanır. **Son kullanılanlar | Gözat** seçicisi öğe sayılarını gösterir; arama, seçicinin altında **Son kullanılanlar** içindedir. Yerel veya uzak proje ya da SideCar seçimi sekmeyi yerinde doldurur. Boş sekme yeniden yüklemeye kadar yaşar ve proje bırakmadan kapanır. Başlık veya sekme çubuğundaki CodeNomad logosu ayarlar, dil ve kalpli **Sponsor** düğmesini içeren ana sayfayı açar ([CodeNomad'i destekleyin](sponsor.md)). +1. **Yeni instance** (`+`) veya `Ctrl/Cmd+N`, kısa **Proje aç** başlıklı boş bir sekme açar. Ana sayfa aynı **Son kullanılanlar | Gözat** seçicisini, sayıları, aramayı ve eylemleri kullanır. **Git Deposunu Klonla**, **Yeni geçici sekme** ve **Yeni SideCar** listenin altındaki ikincil çubuktadır; klonlama ve geçici klasörler yerel arka ucu hedefler. Proje veya SideCar seçimi boş sekmeyi yerinde doldurur. Boş sekmeler yeniden yüklemeye kadar yaşar ve proje bırakmadan kapanır. Logo, CodeNomad kimliği, ayarlar, dil, bağlantılar ve **Sponsor** içeren ana sayfayı açar ([CodeNomad'i destekleyin](sponsor.md)). 2. **Son kullanılanlar** içinde bir proje seçin; ya da **Gözat** bölümünü açıp **Bu bilgisayar** seçin, ardından arka uç klasörünü seçip açın. **Gözat** kayıtlı CodeNomad sunucularını ([uzak proje sekmeleri](remote-access.md#remote-project-tabs)) ve SideCar'ları ([SideCar'lar](browser-sidecars.md#register-sidecar)) da listeler. 3. Depoyu kopyalamak için **Git Deposunu Klonla** eylemini seçin; **Depo URL'si** ve **Hedef klasör** alanlarını doldurup **Klonla** eylemini seçin. **Hedef klasör**, son klonunuzun bulunduğu klasörde (yoksa en son projenizin yanında) depo adıyla önceden doldurulur. **Göz At** klonu içerecek klasörü seçer; klon klasörünün adı dahil yolu elle de düzenleyebilirsiniz. Uzak bir sunucuya göz atmak, telefonunuzun veya dizüstü bilgisayarınızın değil, o sunucunun dosya sistemine göz atmak anlamına gelir. Bir projeyi açmak, her sekme için ayrı bir OpenCode arka plan programı oluşturmaz. Konuşmalar yerel OpenCode oturumlarıdır; bunların ömrü sekmenin ömrü değildir. -**Gözat** içinde sunucu seçmek listeyi onun son projeleri ve klasörleriyle değiştirir. İstenirse satır içi formdan oturum açın, sonra proje seçin veya klasöre gidip **Geçerli Olanı Seç** öğesini kullanın. Gözat'a dönüş sunucuları gösterir. Yalnızca proje seçimi boş sekmeyi doldurur ve `+` başlatıcısını kapatır. Uzak sekme taramadan bağımsız oturum açmanızı isteyebilir. +**Gözat** içindeki sunucunun adı oturum açarken ve gezinirken görünür kalır. Giriş alanları etiketlidir; **Son kullanılanlar** proje açar, **Klasörler** gezinir. **Bu klasörü aç** geçerli klasörü açar; Gözat'a dönüş sunucuları gösterir. Yalnızca proje seçimi boş sekmeyi doldurur. Bilinen sınır: arka uç taraması ve yerel görünüm bağımsız kimlik doğrular; uzak sekme ayrı oturum açmanızı isteyebilir. Klonlama hedefe bir depo yazar. **Hedef klasör zaten varsa önce onu kaldırın.** yıkıcıdır: yalnızca zaten orada olan her şeyin silinebildiği durumlarda etkinleştirin. Emin değilseniz yeni bir hedef kullanın. Başarısız bir klon, mevcut bir projeyi silmek için bir neden değildir; yeniden denemeden önce bildirilen hedefi ve hatayı inceleyin. -Son kullanılan kayıtlar birer kısayoldur. **Workspace'i yeniden adlandır** görünen adı değiştirir; **Son kullanılanlardan kaldır** dosyaları veya konuşmaları değil, kısayolu kaldırır. Zaten açık olan bir son kullanılan projeye tıklamak yeni bir sekme açar; mevcut sekmeyi seçmek için bunun yerine projenin **Aç** düğmesini (**Açık projeye geç**) kullanın. +Son kullanılanlar kısayoldur. Ana sayfa ve boş sekmelerdeki eylem menüsü uygun olduğunda **Workspace'i yeniden adlandır** ve **Son kullanılanlardan kaldır** sunar; dosyalar ve konuşmalar korunur. Ana sayfa, boş sekme ve hızlı başlatıcıda yerel/uzak proje veya SideCar satırına tıklamak, zaten açık olsa da yeni bir örnek oluşturur. Ayrı **Aç** eylemi (**Açık projeye geç**) mevcut örneği seçer. ## Yeni örnek başlatıcıyı kullanın {#new-instance-launcher} 1. `+`'ye uzun basın veya sağ tıklayın; Klavye odağı oradayken **Alt+Down**, **Shift+F10** veya Menü tuşunu kullanın. -2. **Sekme aç** içinde **Son kullanılanlar** arasında arayın (projeler, uzak projeler ve SideCar'lar), **Gözat** bölümünü açın ya da **Git Deposunu Klonla** veya **Yeni geçici sekme** seçin. +2. **Son projeler** yalnızca son yerel projeleri, uzak projeleri ve SideCar'ları arar. Satır yeni örnek oluşturur; ayrı **Aç** eylemi mevcut örneğe geçer. **Başka bir proje aç…** gezinmek, sunucu eklemek ve proje oluşturmak için boş sekme açar. -Normal tıklama boş bir sekme açar. CodeNomad logosundan açılan ana sayfa aynı seçenekleri ve **Son kullanılanlar** ile **Gözat** öğe sayılarını sunar. Son sekmeleri orada yeniden adlandırın veya kaldırın; sunucuları **Ayarlar → Sunucular**, SideCar'ları ise **Ayarlar → SideCars** bölümünde yönetin. Escape başlatıcıyı kapatır ve odağı `+` düğmesine döndürür. +Normal tıklama boş sekme açar. Hızlı başlatıcı son kullanılanları, aramayı ve **Başka bir proje aç…** eylemini içerir. Son kullanılanları ana sayfa veya boş sekmede, sunucuları **Ayarlar → Sunucular**, SideCar'ları **Ayarlar → SideCars** bölümünde yönetin. Escape başlatıcıyı kapatır ve odağı `+` düğmesine döndürür. ## Bir projeyi kapatın {#close-stop} @@ -40,7 +40,7 @@ Bir pencerenin tamamını kapatmak, uygulamadan çıkmak veya yeniden yüklemek ## Geçici çalışma alanları {#temporary-workspaces} -1. Ana sayfada veya başlatıcıda **Yeni geçici sekme** seçin. +1. Ana sayfa veya boş sekmede listenin altından **Yeni geçici sekme** seçin. 2. Boş CodeNomad tarafından yönetilen klasörde çalışın; Git otomatik olarak başlatılmıyor. 3. Sekmeyi kapatırken **Sakla**, **At** veya **İptal** öğesini seçin. Sekme menüsü ayrıca **Proje olarak sakla** öğesini de sunar. diff --git a/docs/help/tr/remote-access.md b/docs/help/tr/remote-access.md index 99191d6818..18cf33fcc3 100644 --- a/docs/help/tr/remote-access.md +++ b/docs/help/tr/remote-access.md @@ -83,9 +83,9 @@ Bir istemci bir sertifika uyarısı bildirirse, durdurun ve ana bilgisayar adın ## Uzak sunucuyu kaydedin {#saved-servers} -1. Ana sayfada, boş sekmede veya **Sekme aç** başlatıcısında **Gözat** bölümünü açıp adresi ya da eşleştirme bağlantısını **Sunucu adresi veya bağlantısı** alanına girin. Yapıştırma hemen ekler; Enter yazılan metni ekler. Sunucu ana bilgisayar adıyla kaydedilir ve satırına odaklanılır; eşleştirme bağlantısı tarama için yerel arka ucu da eşleştirir. Başlatıcı açık kalır. Projeleri aynı yerde taramak için bu satıra tıklayın. **Ayarlar → Sunucular** aynı alanı sunar. -2. Güvenilir bir HTTPS kaynağı kullanın. Sertifika doğrulanamazsa alanın altında **TLS doğrulamasını atla** görünür: yalnızca güvendiğiniz sunucu için işaretleyip kaydetmek üzere yeniden Enter'a basın. Bu profilde klasör veya proje seçmek kendi penceresini açar. -3. Projeleri aynı yerde taramak için **Gözat** içindeki kayıtlı satırını seçin. İstenirse satır içi forma sunucu kullanıcı adını ve parolasını girin. Adı veya adresi **Ayarlar → Sunucular** içindeki **Sunucuyu düzenle** ile değiştirin. +1. Ana sayfa veya boş **Proje aç** sekmesinde **Gözat** bölümünü açıp **Sunucu adresi veya bağlantısı** alanına adres veya bağlantı girin. Hızlı başlatıcıda önce **Başka bir proje aç…** seçin. Yapıştırmak hemen ekler; Enter yazılan metni onaylar. Sunucu kaydedilir, satırı odaklanır ve seçici yerinde kalır; bağlantı tarama için yerel arka ucu da eşleştirir. Taramak için satıra tıklayın. **Ayarlar → Sunucular** aynı alanı sunar. +2. Güvenilir HTTPS kaynağı kullanın. Sertifika ve erişilemeyen sunucu hataları çevrilmiştir; bilgi denetimi teknik ayrıntıları isteğe bağlı gösterir. **TLS doğrulamasını atla** açık seçim gerektirir: yalnızca güvenilir sunucuda kullanıp yeniden onaylayın. Açma eylemi, proje seçilirken profilin ayrı pencere kullanacağını belirtir. +3. Sunucu adı oturum açarken ve gezinirken görünür kalır; alanlar etiketlidir, **Son kullanılanlar** ve **Klasörler** ayrıdır. Eşleştirme hataları sunucuyu adlandırır. **Ayarlar → Sunucular** içindeki **Sunucuyu düzenle** URL ve adı değiştirir; `i` düğmeleri URL/TLS yardımını istek üzerine gösterir. **Ayarlar → Sunucular** profilleri yönetir (**Sunucuyu düzenle**, **Kayıtlı sunucuyu kaldır**). Kaldırma önce arka uçtaki tarama kimlik bilgilerini ve oturumunu unutur, ardından yer imini kaldırıp sekmelerini kapatır. Uzak projeler ve konuşmalar sunucuda kalır. Yerel arka uç tarama sırlarını yapılandırmasının yanında `remote-server-credentials.json` içinde saklar; bu dosyayı parola gibi koruyun. Gömülü görünümlerin kimlik doğrulaması ayrıdır. @@ -99,9 +99,9 @@ Yeni bir Uzaktan Kontrol bağlantısı yapıştırmak tünel kökenini kaydeder Masaüstü uygulamasında (Electron veya Windows'ta Tauri), kayıtlı bir sunucu projelerinden birini yerel projelerinizin yanında bu pencerenin bir sekmesinde de açabilir: -1. Ana sayfada, boş sekmede veya **Sekme aç** başlatıcısında **Gözat** bölümünü açıp kayıtlı bir sunucu seçin. Önce eklemek için **Sunucu adresi veya bağlantısı** alanını kullanıp yeni satıra tıklayın. -2. Liste aynı yerde sunucunun son projelerine ve klasörlerine geçer. Gerekirse satır içi formdan oturum açın. Son projelerden birini seçin veya klasörlere gidip **Geçerli Olanı Seç** öğesini kullanın. **Gözat'a dön** sunucu listesini açar. -3. Klasör seçimi uzak proje sekmesini açar ve başlangıçtaki boş sekmenin yerini alır. `+` başlatıcısı seçime kadar açık kalır. Proje doğrudan yeniden açılmak üzere **Son kullanılanlar** listesine eklenir. +1. Ana sayfa veya boş sekmede **Gözat** bölümünden sunucu seçin. Hızlı başlatıcıda önce **Başka bir proje aç…** kullanın. Sunucu eklemek için **Sunucu adresi veya bağlantısı** alanını kullanıp satırına tıklayın. +2. Adı görünen sunucu **Son kullanılanlar** ve **Klasörler** bölümlerini yerinde gösterir. Gerekirse etiketli formda oturum açın. Son proje seçin veya gezinip **Bu klasörü aç** kullanın. **Gözat'a dön** sunucuları gösterir. +3. Klasör seçimi boş sekmenin yerine yeni uzak örnek oluşturur ve **Son kullanılanlar** listesine ekler. Ayrı **Aç** eylemi mevcut örneğe geçer. TLS ve Tauri macOS/Linux dahil ayrı pencere kullanılacağı seçim anında belirtilir. Bilinen sınır: arka uç taraması ve yerel görünüm bağımsız kimlik doğrular. Sekmenin konuşmaları, dosyaları, Git'i, ayarları ve Missions uzak sunucuda çalışır. Gömülü görünüm sunucunun uzak pencere depolamasını paylaşır ve Gözat'tan bağımsız oturum açmanızı isteyebilir. Uzak sekmeler başlangıçta geri yüklenir. Gömülü modu olmayan sunucular tam arayüzü gösterir; TLS doğrulamasını atlayan profiller ve macOS/Linux'ta Tauri ayrı pencere açar. Gömülü sayfa kendi sunucusunda kalır ve ana bilgisayarda yalnızca bildirim erişimine sahiptir. Web istemcilerinde ve Uzaktan Kontrol cihazlarında uzak sekme yoktur. diff --git a/docs/help/zh-Hans/browser-sidecars.md b/docs/help/zh-Hans/browser-sidecars.md index 4ebaca8463..c24cd999a4 100644 --- a/docs/help/zh-Hans/browser-sidecars.md +++ b/docs/help/zh-Hans/browser-sidecars.md @@ -47,7 +47,7 @@ 1. 在 CodeNomad 后端主机上单独启动网页工具,监听 `127.0.0.1:`。 2. 打开**设置 → SideCars**。输入**名称**和**端口**;检查推导出的**基础路径**(`/sidecars/`)。 3. 将**协议**设为匹配上游服务,并选择**前缀模式**。 -4. 选择 **添加 SideCar**,然后在主页或启动器的 **浏览** 中打开该 SideCar;之后它会出现在 **最近** 中。**新建 SideCar** 会打开此表单。 +4. 选择 **添加 SideCar**,然后从主页或空白标签页的 **浏览** 中打开;它会加入 **最近** 和快速启动器的搜索。列表下方的**新建 SideCar**打开此表单。选择 SideCar 会创建新实例;独立的**已打开**操作选择现有实例([项目标签页](projects.md#open-project))。 | 选择 | 精确影响 | | --- | --- | diff --git a/docs/help/zh-Hans/projects.md b/docs/help/zh-Hans/projects.md index 4800f8f95d..499b35f54a 100644 --- a/docs/help/zh-Hans/projects.md +++ b/docs/help/zh-Hans/projects.md @@ -4,24 +4,24 @@ ## 打开项目 {#open-project} -1. 点击**新建实例**(`+`)打开空白的**新标签页**,焦点位于搜索框。它使用主页的背景、居中的 CodeNomad 标志和名称,以及大号的**克隆 Git 仓库**、**新建临时标签页**和**新建 SideCar**按钮。**最近 | 浏览**选择器附有条目数量,搜索框位于选择器下方的**最近**中。选择本地或远程项目或 SideCar 会在原位置填充此标签页。空白标签页仅保留到重新加载,关闭后不留下项目。标题栏或标签栏中的 CodeNomad 标志打开主页,其中还提供设置、语言和心形**赞助**按钮([支持 CodeNomad](sponsor.md))。 +1. 点击**新建实例**(`+`)或按 `Ctrl/Cmd+N`,打开标题为**打开项目**的紧凑空白标签页。主页使用相同的**最近 | 浏览**选择器、数量、搜索和操作。**克隆 Git 仓库**、**新建临时标签页**和**新建 SideCar**位于列表下方的次要操作栏;克隆和临时文件夹以本地后端为目标。选择项目或 SideCar 会在原位置填充空白标签页。空白标签页保留到重新加载,关闭后不留下项目。标志打开主页,保留 CodeNomad 品牌、设置、语言、链接和**赞助**([支持 CodeNomad](sponsor.md))。 2. 在 **最近** 中选择一个项目;或打开 **浏览**,选择 **此电脑**,然后选择后端文件夹并打开。**浏览** 也列出已保存的 CodeNomad 服务器([远程项目标签页](remote-access.md#remote-project-tabs))和 SideCar([SideCar](browser-sidecars.md#register-sidecar))。 3. 若需仓库副本,选择**克隆 Git 仓库**,输入**仓库 URL** 和**目标文件夹**,然后选择**克隆**。**目标文件夹** 会预填为上次克隆所在文件夹中以仓库名命名的文件夹(没有则为最近项目旁边)。**浏览** 用于选择存放克隆的文件夹;也可以手动编辑路径,包括克隆文件夹的名称。 浏览远程服务器意味着浏览该服务器的文件系统,而非你的手机或笔记本电脑。打开项目不会为每个标签页创建独立的 OpenCode 守护进程。对话是原生 OpenCode 会话;其生命周期不等于标签页的生命周期。 -在**浏览**中选择服务器后,列表会切换为该服务器的最近项目和文件夹。出现提示时通过内嵌表单登录,然后选择项目,或进入文件夹并点击**选择当前**。返回浏览会显示服务器列表。只有选择项目后才会填充空白标签页并关闭 `+` 启动器。远程标签页可能要求独立于浏览流程再次登录。 +在**浏览**中选择的服务器名称在登录和导航期间始终可见。登录字段带有标签;**最近项目**打开项目,**文件夹**用于导航。**打开此文件夹**打开当前文件夹,返回浏览则显示服务器列表。只有选择项目才会填充空白标签页。已知限制:后端浏览与原生视图独立认证,远程标签页可能要求再次登录。 克隆会将仓库写入目标位置。**如果目标文件夹已存在,先将其删除。**具有破坏性:仅在其中所有现有内容都可以删除时启用。不确定时请使用新目标位置。克隆失败不是删除现有项目的理由;重试之前先检查报告的目标位置和错误。 -最近条目只是快捷方式。**重命名工作区**更改显示名称;**从最近列表移除**仅移除快捷方式,不会删除文件或对话。点击已打开的最近项目会打开新标签页;其**已打开**按钮(**切换到已打开的项目**)则会选择现有标签页。 +最近条目是快捷方式。主页和空白标签页的操作菜单按条目提供**重命名工作区**和**从最近列表移除**;文件和对话会保留。在主页、空白标签页和快速启动器中,点击本地项目、远程项目或 SideCar 行都会创建新实例,即使已经打开。独立的**已打开**操作(**切换到已打开的项目**)则选择现有实例。 ## 使用新建实例启动器 {#new-instance-launcher} 1. 长按或右键点击 `+`;键盘焦点位于此处时,使用 **Alt+Down**、**Shift+F10** 或 Menu 键。 -2. 在 **打开标签页** 中搜索 **最近**(项目、远程项目和 SideCar),打开 **浏览**,或选择 **克隆 Git 仓库** 或 **新建临时标签页**。 +2. **最近的项目**仅搜索最近的本地项目、远程项目和 SideCar。点击行创建新实例;独立的**已打开**操作切换到现有实例。**打开其他项目…**打开空白标签页,用于浏览、添加服务器和创建项目。 -普通点击打开空白标签页。通过 CodeNomad 标志打开的主页提供相同的选项及**最近**和**浏览**的条目数量。在那里重命名或移除最近的标签页;在 **设置 → 服务器** 中管理服务器,在 **设置 → SideCars** 中管理 SideCar。Escape 会关闭启动器并将焦点返回 `+`。 +普通点击打开空白标签页。快速启动器包含最近条目、搜索和**打开其他项目…**。在主页或空白标签页管理最近条目,在 **设置 → 服务器** 管理服务器,在 **设置 → SideCars** 管理 SideCar。Escape 关闭启动器并将焦点返回 `+`。 ## 关闭标签页以关闭项目 {#close-stop} @@ -40,7 +40,7 @@ ## 临时工作区 {#temporary-workspaces} -1. 在主页或启动器中选择 **新建临时标签页**。 +1. 在主页或空白标签页的列表下方选择 **新建临时标签页**。 2. 在 CodeNomad 管理的空文件夹中工作;不会自动初始化 Git。 3. 关闭标签页时,选择**保留**、**丢弃**或**取消**。标签页菜单还提供**保留为项目**。 diff --git a/docs/help/zh-Hans/remote-access.md b/docs/help/zh-Hans/remote-access.md index 499c2423a6..d5d74a892d 100644 --- a/docs/help/zh-Hans/remote-access.md +++ b/docs/help/zh-Hans/remote-access.md @@ -83,9 +83,9 @@ codenomad --host 127.0.0.1 --https=false --http=true ## 保存远程服务器 {#saved-servers} -1. 在主页、空白标签页或**打开标签页**启动器中打开**浏览**,在**服务器地址或链接**中输入地址或配对链接。粘贴会立即添加,手动输入后按 Enter 添加。添加会以主机名保存服务器并将焦点移到其行;配对链接还会为本地后端配对以供浏览。启动器保持打开。点击该行可在原位浏览项目。**设置 → 服务器**也提供相同的输入框。 -2. 请使用受信任的 HTTPS 源。如果证书未通过检查,输入框下方会显示**跳过 TLS 验证**:仅对可信服务器勾选,再按 Enter 保存。选择此配置的文件夹或项目后,会在单独窗口打开。 -3. 选择**浏览**中的已保存服务器行,即可在原位浏览项目。出现提示时,在内嵌表单中输入服务器用户名和密码。可在 **设置 → 服务器** 中通过 **编辑服务器** 更改名称或地址。 +1. 在主页或空白的**打开项目**标签页中打开**浏览**,在**服务器地址或链接**输入地址或链接。从快速启动器进入时,先选择**打开其他项目…**。粘贴立即添加;Enter 确认手动输入。服务器保存后焦点移至其行,选择器保留;链接也会为本地后端配对以供浏览。点击该行浏览项目。**设置 → 服务器**提供同一输入框。 +2. 使用可信的 HTTPS 源。证书和服务器不可达错误已本地化;信息按钮按需显示技术诊断。**跳过 TLS 验证**需要明确选择:仅对可信服务器启用,然后再次提交。项目选择时,打开操作会明确说明此配置使用单独窗口。 +3. 服务器名称在登录和导航期间始终可见,字段带有标签,并区分**最近项目**与**文件夹**。配对错误会指明服务器。**设置 → 服务器**中的**编辑服务器**更改 URL 和名称;`i` 按钮按需显示 URL/TLS 帮助。 **设置 → 服务器**管理配置(**编辑服务器**、**删除已保存服务器**)。删除时先清除后端保存的浏览凭据和会话,再移除书签并关闭其标签页。远程项目和对话保留在服务器上。本地后端将浏览密钥保存在配置旁的 `remote-server-credentials.json` 中;请像保护密码一样保护此文件。嵌入视图的身份验证独立保存。 @@ -99,9 +99,9 @@ codenomad --host 127.0.0.1 --https=false --http=true 在桌面应用中(Electron,或 Windows 上的 Tauri),已保存的服务器也可以在此窗口的标签页中打开其某个项目,与本地项目并列: -1. 在主页、空白标签页或**打开标签页**启动器中打开**浏览**并选择已保存的服务器。若需先添加,使用**服务器地址或链接**,然后点击新增的行。 -2. 列表在原位切换为该服务器的最近项目和文件夹。必要时通过内嵌表单登录。选择最近项目,或进入文件夹后点击**选择当前**。**返回浏览**会回到服务器列表。 -3. 选择文件夹后打开远程项目标签页,并替换原来的空白标签页。`+` 启动器在选择之前保持打开。项目会加入**最近**,便于直接重新打开。 +1. 在主页或空白标签页中打开**浏览**并选择服务器。在快速启动器中先选择**打开其他项目…**。添加服务器可用**服务器地址或链接**,然后点击其行。 +2. 显示名称的服务器在原位提供**最近项目**和**文件夹**。必要时在带标签的表单中登录。选择最近项目,或进入文件夹后选择**打开此文件夹**。**返回浏览**回到服务器列表。 +3. 选择文件夹会创建新的远程实例,替换原空白标签页并加入**最近**。独立的**已打开**操作选择现有实例。对于 TLS 回退及 macOS/Linux 上的 Tauri 等单独窗口情况,打开操作会在选择时明确说明。已知限制:后端浏览与原生视图独立认证。 标签页的对话、文件、Git、设置和 Missions 在远程服务器上运行。嵌入视图共享该服务器远程窗口的存储,可能要求独立于浏览流程再次登录。远程标签页参与启动恢复。没有嵌入模式的服务器显示完整界面;跳过 TLS 验证的配置及 macOS/Linux 上的 Tauri 会打开单独窗口。嵌入页面始终停留在其服务器上,对本机仅有通知权限。Web 客户端和远程控制设备没有远程标签页。 diff --git a/packages/ui/src/App.tsx b/packages/ui/src/App.tsx index b59dc4755b..0f7b19590c 100644 --- a/packages/ui/src/App.tsx +++ b/packages/ui/src/App.tsx @@ -926,7 +926,7 @@ const App: Component = () => { onOpenChange={setLauncherOpen} onSelectFolder={(path) => void handleSelectFolder(path)} onSelectExistingInstance={handleSelectExistingInstance} - onNewTemporaryInstance={() => void handleNewTemporaryInstance()} + onOpenAnotherProject={() => { openBlankTab(); setShowFolderSelection(false) }} /> diff --git a/packages/ui/src/components/browse-menu.tsx b/packages/ui/src/components/browse-menu.tsx index dbb0c3f0a2..37634e7588 100644 --- a/packages/ui/src/components/browse-menu.tsx +++ b/packages/ui/src/components/browse-menu.tsx @@ -1,5 +1,5 @@ -import { For, Show, createEffect, createMemo, createSignal, createUniqueId, onMount } from "solid-js" -import { ChevronRight, Globe, Laptop, Server } from "lucide-solid" +import { For, Show, createEffect, createMemo, createSignal, onMount } from "solid-js" +import { Globe, Laptop, Server } from "lucide-solid" import type { RemoteServerProfile, SideCar } from "../../../server/src/api-types" import { useI18n } from "../lib/i18n" import { serverDisplayName } from "../lib/codenomad-link" @@ -13,28 +13,21 @@ import { openRemoteProject, opensRemoteProjectTab } from "../stores/remote-proje import { embeddedProjectUrl } from "../lib/embed-mode" import { remoteServers as savedServers } from "../stores/preferences" import { ensureSidecarsLoaded, sidecars } from "../stores/sidecars" +import { joinRecentOpenTarget, recentAccessibleName, recentOpenTarget } from "../lib/recent-open-target" +import type { LaunchableRecent } from "../lib/remote-project-recents" interface BrowseMenuProps { isLoading: boolean /** Browses this computer's folders (native dialog or folder browser). */ onBrowseLocal: () => void - /** Called before an entry runs, e.g. to dismiss the launcher. */ - onRun?: () => void - /** The home page's Browse tab: the list without its disclosure. */ - alwaysOpen?: boolean } -// One disclosure state per window for the launcher's section. -const [expanded, setExpanded] = createSignal(false) - /** Choices only: this computer, available saved servers and configured SideCars (the add field is an action). */ export const browseEntryCount = () => 1 + (canOpenRemoteWindows() ? savedServers().length : 0) + sidecars().size /** - * Browse, shared by the home page (a tab) and the new-instance launcher (a - * folded section): this computer's folders, each saved CodeNomad server, whose - * project tab picks the folder, each configured SideCar, then the field that - * adds a server to the list. + * Browse in the canonical project selector: this computer's folders, saved + * CodeNomad servers, configured SideCars, then the inline server-add field. * Only host windows (never a web client, a Remote Control device or a remote * page) list or add servers. */ @@ -42,33 +35,22 @@ export default function BrowseMenu(props: BrowseMenuProps) { const { t } = useI18n() const { remoteServers, openServer } = useRemoteServerProfiles() const [selectedServer, setSelectedServer] = createSignal() + const [pairingFailures, setPairingFailures] = createSignal([]) createEffect(() => { if (selectedServer() && !remoteServers().some(profile => profile.id === selectedServer()!.id)) setSelectedServer(undefined) }) - const bodyId = createUniqueId() - let toggleRef: HTMLButtonElement | undefined let bodyRef: HTMLDivElement | undefined onMount(() => void ensureSidecarsLoaded()) - const open = () => props.alwaysOpen || expanded() const navItems = () => [...(bodyRef?.querySelectorAll("[data-browse-nav]") ?? [])].filter((item) => !item.hasAttribute("disabled")) - const focusFirst = () => queueMicrotask(() => navItems()[0]?.focus()) const servers = () => (canOpenRemoteWindows() ? remoteServers() : []) const displayName = (profile: RemoteServerProfile) => serverDisplayName(profile, remoteServers()) const orderedSidecars = createMemo(() => [...sidecars().values()].sort((left, right) => left.name.localeCompare(right.name))) - // The launcher closes first, so the opened flow (dialog, tab, window) owns focus. function run(action: () => void) { if (props.isLoading) return - props.onRun?.() action() } - function handleToggleKeyDown(event: KeyboardEvent) { - if (event.key !== "ArrowDown" || !expanded()) return - event.preventDefault() - navItems()[0]?.focus() - } - function handleKeyDown(event: KeyboardEvent) { if (event.defaultPrevented || event.isComposing) return const items = navItems() @@ -83,10 +65,6 @@ export default function BrowseMenu(props: BrowseMenuProps) { else if (event.key === "Escape" && selectedServer()) { event.preventDefault() backToRoot() - } else if (event.key === "Escape" && !props.alwaysOpen) { - event.preventDefault() - setExpanded(false) - toggleRef?.focus() } } @@ -99,19 +77,11 @@ export default function BrowseMenu(props: BrowseMenuProps) { const sidecarRunning = (sidecar: SideCar) => sidecar.status === "running" return ( -
- - - - -
+
{(profile) => setPairingFailures(ids => ids.filter(id => id !== profile().id))} onSelect={(folder) => run(() => { if (opensRemoteProjectTab(profile())) openRemoteProject(profile().id, { folder }) else openServer(profile(), embeddedProjectUrl(profile().baseUrl, folder)) @@ -130,27 +100,42 @@ export default function BrowseMenu(props: BrowseMenuProps) { aria-label={t("folderSelection.remoteProject.openProject", { name: displayName(profile) })}>
-
) } diff --git a/packages/ui/src/components/folder-selection-view.tsx b/packages/ui/src/components/folder-selection-view.tsx index c5e4357a8e..d7fef87ecb 100644 --- a/packages/ui/src/components/folder-selection-view.tsx +++ b/packages/ui/src/components/folder-selection-view.tsx @@ -1,10 +1,11 @@ import { Component, createMemo, createSignal, createUniqueId, Show, For, onMount, onCleanup, createEffect, on } from "solid-js" -import { Clock, Trash2, FolderPlus, Settings, ChevronRight, MonitorUp, Star, X, Pencil, Search } from "lucide-solid" +import { Trash2, FolderPlus, Settings, ChevronRight, MonitorUp, Star, X, Pencil, Search } from "lucide-solid" import { removeRemoteProjectRecent, removeSideCarRecent, useConfig } from "../stores/preferences" import { launchableRecents, openRemoteProject } from "../stores/remote-project-open" import { recentKey, type LaunchableRecent } from "../lib/remote-project-recents" import BrowseMenu, { browseEntryCount } from "./browse-menu" -import EntryCount from "./entry-count" +import ActionOverflowMenu from "./action-overflow-menu" +import { joinRecentOpenTarget, recentAccessibleName, recentOpenTarget } from "../lib/recent-open-target" import { ensureSidecarsLoaded } from "../stores/sidecars" import { helpUrl } from "../lib/help-url" import { Heart } from "lucide-solid" @@ -23,7 +24,6 @@ import { useI18n } from "../lib/i18n" import { showAlertDialog } from "../stores/alerts" import { openSettings, settingsOpen } from "../stores/settings-screen" import { openExternalUrl } from "../lib/external-url" -import { getExistingInstanceForFolder } from "../stores/instances" import { renameProject } from "../stores/project-names" import { LocaleSelector } from "./locale-selector" import { createNewInstanceDialogs } from "./new-instance-dialogs" @@ -56,17 +56,18 @@ const FolderSelectionView: Component = (props) => { const [focusMode, setFocusMode] = createSignal<"recent" | "new" | null>("recent") const [renameProjectTarget, setRenameProjectTarget] = createSignal<{ path: string; name: string; label: string } | null>(null) const [isRenamingProject, setIsRenamingProject] = createSignal(false) - // The right card's tabs: the recent tabs, or Browse (this computer, servers, SideCars). + // The canonical selector shared by Home and blank tabs. const [homeTab, setHomeTab] = createSignal<"recent" | "browse">("recent") const [query, setQuery] = createSignal("") let homeRootRef: HTMLDivElement | undefined - let actionsColumnRef: HTMLDivElement | undefined let recentListRef: HTMLDivElement | undefined let searchRef: HTMLInputElement | undefined createEffect(on(() => props.blank && props.active !== false, (active) => { if (!active) return - setHomeTab("recent") - requestAnimationFrame(() => { if (props.active !== false) searchRef?.focus() }) + setHomeTab(allRecents().length ? "recent" : "browse") + requestAnimationFrame(() => { + if (props.active !== false) (searchRef ?? homeRootRef?.querySelector('[data-home-tab="browse"]'))?.focus() + }) })) // This computer's folders, the remote projects this window reopens and SideCars, newest first. @@ -84,14 +85,8 @@ const FolderSelectionView: Component = (props) => { const element = container.querySelector(`[data-list-index="${index}"]`) as HTMLElement | null if (!element) return - const containerRect = container.getBoundingClientRect() - const elementRect = element.getBoundingClientRect() - - if (elementRect.top < containerRect.top) { - container.scrollTop -= containerRect.top - elementRect.top - } else if (elementRect.bottom > containerRect.bottom) { - container.scrollTop += elementRect.bottom - containerRect.bottom - } + element.focus() + element.scrollIntoView({ block: "nearest" }) } @@ -101,6 +96,7 @@ const FolderSelectionView: Component = (props) => { if (typeof document !== "undefined") { activeElement = document.activeElement as HTMLElement | null } + if (activeElement && activeElement !== document.body && !homeRootRef?.contains(activeElement)) return const insideModal = activeElement?.closest(".modal-surface") || activeElement?.closest("[role='dialog']") const isEditingField = activeElement && @@ -134,13 +130,13 @@ const FolderSelectionView: Component = (props) => { if (e.key === "ArrowDown") { e.preventDefault() - const newIndex = Math.min(selectedIndex() + 1, listLength - 1) + const newIndex = (selectedIndex() + 1) % listLength setSelectedIndex(newIndex) setFocusMode("recent") scrollToIndex(newIndex) } else if (e.key === "ArrowUp") { e.preventDefault() - const newIndex = Math.max(selectedIndex() - 1, 0) + const newIndex = (selectedIndex() - 1 + listLength) % listLength setSelectedIndex(newIndex) setFocusMode("recent") scrollToIndex(newIndex) @@ -202,27 +198,7 @@ const FolderSelectionView: Component = (props) => { }) }) - onMount(() => { - const syncActionsHeight = () => { - if (!homeRootRef || !actionsColumnRef) return - const height = actionsColumnRef.getBoundingClientRect().height - homeRootRef.style.setProperty("--folder-home-actions-height", `${Math.ceil(height)}px`) - } - - syncActionsHeight() - window.addEventListener("resize", syncActionsHeight) - - let observer: ResizeObserver | undefined - if (typeof ResizeObserver !== "undefined" && actionsColumnRef) { - observer = new ResizeObserver(syncActionsHeight) - observer.observe(actionsColumnRef) - } - - onCleanup(() => { - window.removeEventListener("resize", syncActionsHeight) - observer?.disconnect() - }) - }) + onMount(() => { if (!allRecents().length) setHomeTab("browse") }) function dropTargetBlocked() { return props.active === false || isLoading() || dialogs.isFolderBrowserOpen() || settingsOpen() @@ -267,7 +243,7 @@ const FolderSelectionView: Component = (props) => { if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault() if (!count) return - const next = (selectedIndex() + (event.key === "ArrowDown" ? 1 : -1) + count) % count + const next = event.key === "ArrowDown" ? 0 : count - 1 setFocusMode("recent") setSelectedIndex(next) scrollToIndex(next) @@ -286,11 +262,6 @@ const FolderSelectionView: Component = (props) => { homeRootRef?.querySelector(`[data-home-tab="${target}"]`)?.focus() } - function handleExistingInstanceSelect(instanceId: string, recentPath: string) { - if (isLoading()) return - props.onSelectExistingInstance(instanceId, recentPath) - } - function setRecentActionHovered(path: string, active: boolean) { setHoveredRecentActionPath((current) => active ? path : current === path ? null : current) } @@ -299,11 +270,6 @@ const FolderSelectionView: Component = (props) => { setFocusedRecentActionPath((current) => active ? path : current === path ? null : current) } - function clearRecentActionState(path: string) { - setRecentActionHovered(path, false) - setRecentActionFocused(path, false) - } - const dialogs = createNewInstanceDialogs({ defaultPath: () => allRecents().find((folder) => !folder.remote && !folder.sidecar)?.path, isLoading, @@ -367,7 +333,7 @@ const FolderSelectionView: Component = (props) => { onDrop={folderDrop.bind.onDrop} >
@@ -407,10 +373,12 @@ const FolderSelectionView: Component = (props) => {
-
+ {t("folderSelection.openProject")}}> +
-

CodeNomad

+
= (props) => {
- {/* Right column: recent folders */}
-
+
-
+
{(tab) => ( )} @@ -504,58 +469,58 @@ const FolderSelectionView: Component = (props) => {
- void handleBrowse()} /> + void handleBrowse()} />
- 0}> - 0} fallback={ 0} fallback={ -
-
- -
-

{t("folderSelection.empty.title")}

-

{t("folderSelection.empty.description")}

-
+ }> -

{t("newInstanceLauncher.noMatch")}

+

{t("newInstanceLauncher.noMatch")}

} >
(recentListRef = el)} > {(folder, index) => { const key = recentKey(folder) - // A remote project reopens its tab from the row itself. - const existingInstance = () => folder.remote || folder.sidecar ? undefined : getExistingInstanceForFolder(folder.path) + const existingInstance = () => recentOpenTarget(folder) const projectName = () => getProjectDisplayName(folder.path, folder.projectName) const projectLabelId = () => `recent-folder-${viewId}-${index()}-name` - const openActionLabelId = () => `recent-folder-${viewId}-${index()}-open-action` + const actions = createMemo(() => [ + ...(!folder.remote && !folder.sidecar ? [{ key: "rename", label: t("folderSelection.recent.rename"), + icon: , disabled: isLoading(), onSelect: () => openProjectRename(folder.path, folder.projectName) }] : []), + { key: "remove", label: t("folderSelection.recent.remove"), icon: , + disabled: isLoading(), onSelect: () => handleRemove(folder) }, + ]) return
= (props) => { type="button" class="folder-home-recent-primary-action" disabled={isLoading()} - aria-labelledby={projectLabelId()} + aria-label={recentAccessibleName(folder)} + title={recentAccessibleName(folder)} onClick={() => openRecent(folder)} onFocus={() => { setFocusMode("recent") @@ -592,7 +558,7 @@ const FolderSelectionView: Component = (props) => { {projectName()} - {(instance) => { + {(_target) => { let ownsHoverState = false let ownsFocusState = false onCleanup(() => { @@ -602,11 +568,11 @@ const FolderSelectionView: Component = (props) => { return ( ) }} @@ -634,8 +600,9 @@ const FolderSelectionView: Component = (props) => { {(remote) => {remote().serverName}} + {t("folderSelection.browseMenu.thisComputer")} · {t("folderSelection.recent.sidecar")}}> - + {getDisplayPath(folder.path)} @@ -644,36 +611,8 @@ const FolderSelectionView: Component = (props) => {
- {/* A remote project is renamed on its server, a SideCar in Settings. */} - - - - + setRecentActionFocused(key, open)} />
}} @@ -682,46 +621,22 @@ const FolderSelectionView: Component = (props) => {
+
- {/* Left column: creation buttons, OpenCode settings, version */} -
(actionsColumnRef = el)} - > -
-
- -
- - {/* OpenCode settings section */} - -
- -
-
-
- - -
-
- -
-
-
-
-
- + +
+ + +
+
diff --git a/packages/ui/src/components/new-instance-launcher.tsx b/packages/ui/src/components/new-instance-launcher.tsx index 8e4a23b164..6ad0e58731 100644 --- a/packages/ui/src/components/new-instance-launcher.tsx +++ b/packages/ui/src/components/new-instance-launcher.tsx @@ -1,10 +1,7 @@ import { Popover } from "@kobalte/core/popover" import { useI18n } from "../lib/i18n" -import { launchableRecents } from "../stores/remote-project-open" -import { createNewInstanceDialogs } from "./new-instance-dialogs" -import BrowseMenu from "./browse-menu" +import { FolderOpen } from "lucide-solid" import RecentTabsMenu from "./recent-tabs-menu" -import NewTabActions from "./new-tab-actions" interface NewInstanceLauncherProps { open: boolean @@ -13,17 +10,12 @@ interface NewInstanceLauncherProps { onOpenChange: (open: boolean) => void onSelectFolder: (path: string) => void onSelectExistingInstance: (id: string, path: string) => void - onNewTemporaryInstance: () => void + onOpenAnotherProject: () => void } -/** The compact + launcher: search, Recent, Browse, Clone and New temporary tab. */ +/** Quick recents only; other choices belong in a blank tab. */ export default function NewInstanceLauncher(props: NewInstanceLauncherProps) { const { t } = useI18n() - const dialogs = createNewInstanceDialogs({ - defaultPath: () => launchableRecents().find((entry) => !entry.remote && !entry.sidecar)?.path, - isLoading: () => props.isLoading, - onSelectFolder: props.onSelectFolder, - }) const close = () => props.onOpenChange(false) let returnFocus = false let content: HTMLDivElement | undefined @@ -32,23 +24,29 @@ export default function NewInstanceLauncher(props: NewInstanceLauncherProps) { props.anchor} placement="bottom-start" gutter={6}> { + event.preventDefault() + content?.querySelector("input[type='search']")?.focus() + }} onEscapeKeyDown={() => { returnFocus = true }} onCloseAutoFocus={(event) => { event.preventDefault() const active = document.activeElement - if (returnFocus && (!active || active === document.body || content?.contains(active))) props.anchor?.focus() + if (returnFocus && !props.open && (!active || active === document.body || content?.contains(active))) props.anchor?.focus() returnFocus = false }}>
{t("newInstanceLauncher.title")}
{t("newInstanceLauncher.description")} - void dialogs.browse()} /> -
+
- ) } diff --git a/packages/ui/src/components/new-tab-actions.tsx b/packages/ui/src/components/new-tab-actions.tsx index 2acd73acf5..0247177e3b 100644 --- a/packages/ui/src/components/new-tab-actions.tsx +++ b/packages/ui/src/components/new-tab-actions.tsx @@ -5,52 +5,28 @@ import { openSettingsRow } from "../stores/settings-screen" interface NewTabActionsProps { isLoading: boolean - /** The home page's full-width buttons, or the launcher's compact ones. */ - variant: "home" | "launcher" onClone: () => void onNewTemporary?: () => void - /** Called before an action runs, e.g. to dismiss the launcher. */ - onRun?: () => void } -/** - * The creation buttons shared by the home page and the launcher: clone a - * repository and a temporary tab; the home page adds a SideCar (its form in - * Settings → SideCars). Servers are added in Browse. - */ +/** Secondary creation actions inside the canonical project selector. */ export default function NewTabActions(props: NewTabActionsProps) { const { t } = useI18n() - const buttonClass = () => props.variant === "home" - ? "button-primary w-full flex items-center justify-center gap-2 text-sm disabled:cursor-not-allowed" - : "window-action" - - function run(action: () => void) { - if (props.isLoading) return - props.onRun?.() - action() - } - - const Action = (action: { label: string; icon: typeof Globe; onClick: () => void; title?: string; disabled?: boolean }) => ( - ) - return ( <> - {(onNewTemporary) => ( - onNewTemporary()()} /> - )} - - {/* The launcher keeps only the project creations. */} - - void openSettingsRow("sidecars", "sidecar-add")} /> + {(onNewTemporary) => onNewTemporary()()} />} + void openSettingsRow("sidecars", "sidecar-add")} /> ) } diff --git a/packages/ui/src/components/recent-tabs-menu.tsx b/packages/ui/src/components/recent-tabs-menu.tsx index 0cdbdb74d1..21e95b7c4f 100644 --- a/packages/ui/src/components/recent-tabs-menu.tsx +++ b/packages/ui/src/components/recent-tabs-menu.tsx @@ -1,23 +1,18 @@ import { For, Show, createEffect, createMemo, createSignal, createUniqueId, on } from "solid-js" -import { ChevronRight, Search } from "lucide-solid" +import { Search } from "lucide-solid" import { useI18n } from "../lib/i18n" import { filterRecents, formatRelativeTime, getDisplayPath, getProjectDisplayName } from "../lib/recent-folder-display" +import { joinRecentOpenTarget, recentAccessibleName, recentOpenTarget } from "../lib/recent-open-target" import type { LaunchableRecent } from "../lib/remote-project-recents" -import { launchableRecents, openRemoteProject, openRemoteProjectTabFor } from "../stores/remote-project-open" +import { launchableRecents, openRemoteProject } from "../stores/remote-project-open" import { openSidecar } from "../stores/sidecar-open" import { ensureSidecarsLoaded } from "../stores/sidecars" -import { getExistingInstanceForFolder } from "../stores/instances" import RecentTabIcon from "./recent-tab-icon" -import EntryCount from "./entry-count" -const [expanded, setExpanded] = createSignal(true) - -/** Search and recent choices shared by the compact launcher and a blank tab. */ +/** The quick launcher's recent choices, with a separate action to join an open tab. */ export default function RecentTabsMenu(props: { isLoading: boolean active: boolean - alwaysOpen?: boolean - counts?: boolean onSelectFolder: (path: string) => void onSelectExistingInstance: (id: string, path: string) => void onRun?: () => void @@ -25,90 +20,77 @@ export default function RecentTabsMenu(props: { const { t } = useI18n() const [query, setQuery] = createSignal("") const listId = `recent-list-${createUniqueId()}` - const optionId = (position: number) => `${listId}-option-${position}` const [index, setIndex] = createSignal(0) const matches = createMemo(() => filterRecents(launchableRecents(), query())) - const shown = () => props.alwaysOpen || expanded() - let root: HTMLDivElement | undefined let list: HTMLDivElement | undefined createEffect(on(() => props.active, (active) => { if (!active) return setQuery("") setIndex(0) void ensureSidecarsLoaded() - if (props.alwaysOpen) requestAnimationFrame(() => root?.querySelector("input")?.focus()) })) createEffect(on(matches, () => setIndex(0), { defer: true })) - createEffect(on([index, matches], ([value]) => { - list?.querySelector(`[data-launcher-index="${value}"]`)?.scrollIntoView({ block: "nearest" }) - })) - const existing = (recent: LaunchableRecent) => recent.sidecar ? false - : recent.remote ? Boolean(openRemoteProjectTabFor(recent)) : Boolean(getExistingInstanceForFolder(recent.path)) function open(recent: LaunchableRecent) { if (props.isLoading) return props.onRun?.() if (recent.sidecar) return void openSidecar(recent.sidecar.sidecarId) if (recent.remote) return openRemoteProject(recent.remote.profileId, { folder: recent.path }) - const instance = getExistingInstanceForFolder(recent.path) - if (instance) props.onSelectExistingInstance(instance.id, recent.path) - else props.onSelectFolder(recent.path) + props.onSelectFolder(recent.path) } - function searchKey(event: KeyboardEvent) { - if (event.key === "ArrowDown" || event.key === "ArrowUp") { + function navigate(event: KeyboardEvent, fromSearch = false) { + if (props.isLoading || !matches().length) return + if (event.key === "ArrowDown" || event.key === "ArrowUp" || (!fromSearch && (event.key === "Home" || event.key === "End"))) { event.preventDefault() - if (!shown()) setExpanded(true) - else if (matches().length) setIndex((index() + (event.key === "ArrowDown" ? 1 : -1) + matches().length) % matches().length) - } else if (event.key === "Enter" && shown() && matches()[index()]) { + const count = matches().length + const next = event.key === "Home" ? 0 : event.key === "End" ? count - 1 + : fromSearch ? (event.key === "ArrowDown" ? 0 : count - 1) + : (index() + (event.key === "ArrowDown" ? 1 : -1) + count) % count + setIndex(next) + list?.querySelector(`[data-launcher-index="${next}"]`)?.focus() + } else if (fromSearch && event.key === "Enter" && matches()[index()]) { event.preventDefault() open(matches()[index()]) } } return ( -
+
-

{t("newInstanceLauncher.recentTitle")}

-
- }> - - - -
- {t(launchableRecents().length ? "newInstanceLauncher.noMatch" : "newInstanceLauncher.empty")}

}> - {(recent, position) => ( -
setIndex(position())} onClick={() => open(recent)}> +
navigate(event)}> + {t(launchableRecents().length ? "newInstanceLauncher.noMatch" : "newInstanceLauncher.empty")}

}> + {(recent, position) => ( +
+
- )} -
-
- + + {formatRelativeTime(t, recent.lastAccessed)}}> + + +
+ )} +
+
) } diff --git a/packages/ui/src/components/remote-server-browser.tsx b/packages/ui/src/components/remote-server-browser.tsx index 72ff3a9930..ec2e3ee57c 100644 --- a/packages/ui/src/components/remote-server-browser.tsx +++ b/packages/ui/src/components/remote-server-browser.tsx @@ -1,32 +1,52 @@ -import { For, Show, createSignal, onCleanup, onMount } from "solid-js" -import { ArrowLeft, ArrowUp, Folder, Loader2 } from "lucide-solid" +import { For, Show, createSignal, createUniqueId, onCleanup, onMount } from "solid-js" +import { ArrowLeft, ArrowUp, ChevronRight, Folder, FolderOpen, Loader2, Server } from "lucide-solid" import type { RemoteServerBrowseResponse, RemoteServerProfile } from "../../../server/src/api-types" import { serverApi } from "../lib/api-client" import { useI18n } from "../lib/i18n" import { getProjectDisplayName } from "../lib/recent-folder-display" +import { serverDisplayName } from "../lib/codenomad-link" +import { remoteServers } from "../stores/preferences" +import { opensRemoteProjectTab } from "../stores/remote-project-open" +import { SettingsInfoTip } from "./settings/settings-info-tip" +import ServerAddField from "./server-add-field" +import { captureRequestFocus } from "../lib/request-focus" +import { joinRecentOpenTarget, recentAccessibleName, recentOpenTarget } from "../lib/recent-open-target" +import type { LaunchableRecent } from "../lib/remote-project-recents" /** Remote metadata is read by the local backend; only this component's password input holds entered text. */ export default function RemoteServerBrowser(props: { profile: RemoteServerProfile onBack: () => void onSelect: (folder: string) => void + onConnected?: () => void }) { const { t } = useI18n() const [result, setResult] = createSignal() const [busy, setBusy] = createSignal(false) const [error, setError] = createSignal("") const [username, setUsername] = createSignal("codenomad") + const [diagnostic, setDiagnostic] = createSignal("") + const errorId = createUniqueId() + const name = () => serverDisplayName(props.profile, remoteServers()) + const needsPairing = () => needsCredentials() && new URL(props.profile.baseUrl).hostname.endsWith(".opentunnel.xyz") let password: HTMLInputElement | undefined let root: HTMLDivElement | undefined let controller: AbortController | undefined let generation = 0 const needsCredentials = () => error() === "needs_credentials" || error() === "auth" || error() === "pairing_unavailable" - function failure(value: unknown) { + function failure(value: unknown, mayFocus: () => boolean) { const code = value instanceof Error ? value.message : "unreachable" + setDiagnostic(code) setError(["needs_credentials", "auth", "pairing_unavailable", "tls_error"].includes(code) ? code : "unreachable") - if (needsCredentials()) queueMicrotask(() => password?.focus()) + if (needsCredentials()) queueMicrotask(() => { + if (!mayFocus()) return + if (needsPairing()) root?.querySelector("[data-server-add-field]")?.focus() + else password?.focus() + }) } - async function browse(path?: string) { + async function browse(path?: string, mayFocus?: () => boolean) { + const focus = captureRequestFocus() + const retained = () => focus.retained() && (mayFocus?.() ?? true) controller?.abort() controller = new AbortController() const current = ++generation @@ -36,43 +56,60 @@ export default function RemoteServerBrowser(props: { const value = await serverApi.browseRemoteServer(props.profile.id, path, controller.signal) if (current !== generation) return setResult(value) - queueMicrotask(() => root?.querySelector("[data-remote-folder]")?.focus()) - } catch (error) { if (current === generation) failure(error) } - finally { if (current === generation) setBusy(false) } + props.onConnected?.() + queueMicrotask(() => { if (retained()) root?.querySelector("[data-remote-folder]")?.focus() }) + } catch (error) { if (current === generation) failure(error, retained) } + finally { focus.dispose(); if (current === generation) setBusy(false) } } async function connect(event: SubmitEvent) { event.preventDefault() if (busy() || !password?.value) return + const focus = captureRequestFocus() setBusy(true) const current = generation const entered = password.value password.value = "" try { await serverApi.connectRemoteServer(props.profile.id, { username: username(), password: entered }) - if (current === generation) await browse(result()?.listing.metadata.currentPath) - } catch (error) { if (current === generation) failure(error) } - finally { if (current === generation) setBusy(false) } + if (current === generation) await browse(result()?.listing.metadata.currentPath, focus.retained) + } catch (error) { if (current === generation) failure(error, focus.retained) } + finally { focus.dispose(); if (current === generation) setBusy(false) } } onMount(() => void browse()) onCleanup(() => { ++generation; controller?.abort(); if (password) password.value = "" }) return (
- - +
+ +
+ + + void browse(undefined, mayFocus)} /> + + - - + : error() === "tls_error" ? "remoteBrowse.tlsError" : "remoteBrowse.unreachable")} +

@@ -82,10 +119,10 @@ export default function RemoteServerBrowser(props: { {(value) => { const listing = () => value().listing return <> -
{listing().metadata.displayPath}
+
{listing().metadata.displayPath}
@@ -93,15 +130,29 @@ export default function RemoteServerBrowser(props: { - {(recent) => - - } + + + +
+ }} +

{t("remoteBrowse.folders")}

{(entry) => - } diff --git a/packages/ui/src/components/remote-server-dialog.tsx b/packages/ui/src/components/remote-server-dialog.tsx index 83050ffc8b..db9f1f31ec 100644 --- a/packages/ui/src/components/remote-server-dialog.tsx +++ b/packages/ui/src/components/remote-server-dialog.tsx @@ -1,7 +1,8 @@ import { Dialog } from "@kobalte/core/dialog" -import { createEffect, createSignal, createUniqueId, Show, type Component } from "solid-js" +import { createEffect, createSignal, Show, type Component } from "solid-js" import { useI18n } from "../lib/i18n" -import type { RemoteServerInput } from "../lib/hooks/use-remote-server-profiles" +import { RemoteServerProbeError, type RemoteServerInput } from "../lib/hooks/use-remote-server-profiles" +import { SettingsInfoTip } from "./settings/settings-info-tip" interface RemoteServerDialogProps { open: boolean @@ -19,7 +20,7 @@ export const RemoteServerDialog: Component = (props) => const [skipTlsVerify, setSkipTlsVerify] = createSignal(false) const [error, setError] = createSignal(null) const [busy, setBusy] = createSignal(false) - const urlHintId = createUniqueId() + const [diagnostic, setDiagnostic] = createSignal("") createEffect(() => { if (!props.open) return @@ -27,17 +28,29 @@ export const RemoteServerDialog: Component = (props) => setBaseUrl(props.initial?.baseUrl ?? "") setSkipTlsVerify(props.initial?.skipTlsVerify ?? false) setError(null) + setDiagnostic("") }) const submit = async () => { if (busy()) return + setDiagnostic("") + if (!baseUrl().trim()) { + setError("folderSelection.servers.dialog.errorRequired") + return + } + if (/^[a-z][a-z\d+.-]*:\/\/[^/?#]*@/i.test(baseUrl().trim())) { + setError("folderSelection.browseMenu.errorCredentials") + return + } setBusy(true) setError(null) try { await props.onSubmit({ id: props.initial?.id, name: name(), baseUrl: baseUrl(), skipTlsVerify: skipTlsVerify() }, false) props.onOpenChange(false) } catch (submitError) { - setError(submitError instanceof Error ? submitError.message : String(submitError)) + setError(submitError instanceof RemoteServerProbeError && submitError.code === "tls_error" ? "remoteBrowse.tlsError" + : submitError instanceof RemoteServerProbeError && submitError.code === "auth" ? "authRecovery.credentials" : "remoteBrowse.unreachable") + setDiagnostic(submitError instanceof Error ? submitError.message : "") } finally { setBusy(false) } @@ -48,14 +61,14 @@ export const RemoteServerDialog: Component = (props) =>
- - {t("folderSelection.remoteProject.edit")} + +
{t("folderSelection.remoteProject.edit")}
+
- {t("folderSelection.servers.dialog.urlHint")}
{/* Optional: a server without a name reads as its host name. */} - {(message) =>

{message()}

}
-
+ {(message) => } +
+ diff --git a/packages/ui/src/components/server-add-field.tsx b/packages/ui/src/components/server-add-field.tsx index c8ff7add1a..2610acd1a6 100644 --- a/packages/ui/src/components/server-add-field.tsx +++ b/packages/ui/src/components/server-add-field.tsx @@ -1,15 +1,20 @@ import { Show, createSignal, createUniqueId } from "solid-js" import { Loader2, Plus } from "lucide-solid" import { useI18n } from "../lib/i18n" -import { classifyCodeNomadLink } from "../lib/codenomad-link" +import { classifyCodeNomadLink, codeNomadLinkName, serverDisplayName } from "../lib/codenomad-link" import { RemoteServerProbeError, useRemoteServerProfiles } from "../lib/hooks/use-remote-server-profiles" +import type { RemoteServerProfile } from "../../../server/src/api-types" +import { SettingsInfoTip } from "./settings/settings-info-tip" +import { captureRequestFocus } from "../lib/request-focus" interface ServerAddFieldProps { disabled?: boolean /** Called with the saved row's ID, e.g. to focus it in Browse. */ - onAdded?: (id: string) => void + onAdded?: (id: string, mayFocus?: () => boolean) => void + onPairingFailure?: (id: string) => void /** Marks the field as a Browse row for its arrow-key navigation. */ navAttribute?: string + pairingProfile?: RemoteServerProfile } const carriesCredentials = (value: string) => /^[a-z][a-z\d+.-]*:\/\/[^/?#]*@/i.test(value.trim()) @@ -26,6 +31,8 @@ export default function ServerAddField(props: ServerAddFieldProps) { const [address, setAddress] = createSignal("") const [busy, setBusy] = createSignal(false) const [error, setError] = createSignal() + const [diagnostic, setDiagnostic] = createSignal() + const [errorServer, setErrorServer] = createSignal("") // The certificate check failed for this address: the field offers skipping it. const [tlsFailedFor, setTlsFailedFor] = createSignal() const [skipTls, setSkipTls] = createSignal(false) @@ -34,6 +41,8 @@ export default function ServerAddField(props: ServerAddFieldProps) { function reset() { setAddress("") setError(undefined) + setDiagnostic(undefined) + setErrorServer("") setTlsFailedFor(undefined) setSkipTls(false) } @@ -42,9 +51,17 @@ export default function ServerAddField(props: ServerAddFieldProps) { const value = text.trim() if (!value || busy() || props.disabled) return setError(undefined) + setDiagnostic(undefined) + setErrorServer("") const link = classifyCodeNomadLink(value) if (!link) { - setError(t(carriesCredentials(value) ? "folderSelection.browseMenu.errorCredentials" : "folderSelection.browseMenu.errorInvalid")) + setError(carriesCredentials(value) ? "folderSelection.browseMenu.errorCredentials" : "folderSelection.browseMenu.errorInvalid") + return + } + if (props.pairingProfile && (link.kind !== "pairing" || link.baseUrl !== props.pairingProfile.baseUrl)) { + setAddress("") + setErrorServer(serverDisplayName(props.pairingProfile, remoteServers())) + setError("remoteBrowse.pairAgain") return } const existing = remoteServers().find((server) => server.baseUrl === link.baseUrl) @@ -53,27 +70,37 @@ export default function ServerAddField(props: ServerAddFieldProps) { id: existing?.id, name: existing?.name ?? "", baseUrl: value, skipTlsVerify: skipping || (existing?.skipTlsVerify ?? false), } + const focus = captureRequestFocus() setBusy(true) try { const profile = await submitServer(input, false) reset() - props.onAdded?.(profile.id) + props.onAdded?.(profile.id, focus.retained) } catch (failure) { if (link.kind === "pairing") { - const code = failure instanceof Error ? failure.message : "unreachable" + const code = failure instanceof RemoteServerProbeError ? failure.code : failure instanceof Error ? failure.message : "unreachable" reset() - setError(t(code === "pairing_unavailable" ? "remoteBrowse.pairingUnavailable" - : code === "pairing_expired" ? "remoteBrowse.pairingExpired" - : code === "pairing_rate_limited" ? "remoteBrowse.pairingRateLimited" : "folderSelection.servers.dialog.errorConnect")) const saved = remoteServers().find(server => server.baseUrl === link.baseUrl) - if (saved) props.onAdded?.(saved.id) + const name = saved ? serverDisplayName(saved, remoteServers()) : codeNomadLinkName(link.baseUrl) + const reason = code === "pairing_unavailable" ? "remoteBrowse.pairingUnavailable" + : code === "pairing_expired" ? "remoteBrowse.pairingExpired" + : code === "pairing_rate_limited" ? "remoteBrowse.pairingRateLimited" + : code === "tls_error" ? "remoteBrowse.tlsError" : "remoteBrowse.unreachable" + setErrorServer(name) + setError(reason) + if (saved && !props.pairingProfile) { + props.onAdded?.(saved.id, focus.retained) + props.onPairingFailure?.(saved.id) + } return } - setError(failure instanceof Error && failure.message ? failure.message : t("folderSelection.servers.dialog.errorConnect")) const tls = failure instanceof RemoteServerProbeError && failure.code === "tls_error" && link.kind === "address" + setError(tls ? "remoteBrowse.tlsError" : "remoteBrowse.unreachable") + setDiagnostic(failure instanceof Error ? failure.message : undefined) setTlsFailedFor(tls ? link.baseUrl : undefined) if (!tls) setSkipTls(false) } finally { + focus.dispose() setBusy(false) } } @@ -85,14 +112,16 @@ export default function ServerAddField(props: ServerAddFieldProps) {
{ event.preventDefault(); void add(address()) }}> { setAddress(event.currentTarget.value) setError(undefined) + setDiagnostic(undefined) + setErrorServer("") }} onPaste={(event) => { // A pasted link or address is added at once. @@ -110,7 +139,7 @@ export default function ServerAddField(props: ServerAddFieldProps) {
- {(message) => } + {(message) => }
-
+
+
{(profile) => setPairingFailures(ids => ids.filter(id => id !== profile().id))} onSelect={(folder) => run(() => { @@ -126,16 +134,12 @@ export default function BrowseMenu(props: BrowseMenuProps) {
}} - - setPairingFailures(ids => ids.includes(id) ? ids : [...ids, id])} - onAdded={(id, mayFocus) => { - setPairingFailures(ids => ids.filter(value => value !== id)) - queueMicrotask(() => { if (mayFocus?.() ?? true) bodyRef?.querySelector(`[data-remote-server="${CSS.escape(id)}"]`)?.focus() }) - }} /> - +
+ + +
) } diff --git a/packages/ui/src/components/folder-selection-view.tsx b/packages/ui/src/components/folder-selection-view.tsx index d7fef87ecb..af1ad15658 100644 --- a/packages/ui/src/components/folder-selection-view.tsx +++ b/packages/ui/src/components/folder-selection-view.tsx @@ -4,6 +4,7 @@ import { removeRemoteProjectRecent, removeSideCarRecent, useConfig } from "../st import { launchableRecents, openRemoteProject } from "../stores/remote-project-open" import { recentKey, type LaunchableRecent } from "../lib/remote-project-recents" import BrowseMenu, { browseEntryCount } from "./browse-menu" +import EntryCount from "./entry-count" import ActionOverflowMenu from "./action-overflow-menu" import { joinRecentOpenTarget, recentAccessibleName, recentOpenTarget } from "../lib/recent-open-target" import { ensureSidecarsLoaded } from "../stores/sidecars" @@ -53,7 +54,7 @@ const FolderSelectionView: Component = (props) => { const [selectedIndex, setSelectedIndex] = createSignal(0) const [hoveredRecentActionPath, setHoveredRecentActionPath] = createSignal(null) const [focusedRecentActionPath, setFocusedRecentActionPath] = createSignal(null) - const [focusMode, setFocusMode] = createSignal<"recent" | "new" | null>("recent") + const [focusMode, setFocusMode] = createSignal<"recent" | "new" | null>(null) const [renameProjectTarget, setRenameProjectTarget] = createSignal<{ path: string; name: string; label: string } | null>(null) const [isRenamingProject, setIsRenamingProject] = createSignal(false) // The canonical selector shared by Home and blank tabs. @@ -66,7 +67,7 @@ const FolderSelectionView: Component = (props) => { if (!active) return setHomeTab(allRecents().length ? "recent" : "browse") requestAnimationFrame(() => { - if (props.active !== false) (searchRef ?? homeRootRef?.querySelector('[data-home-tab="browse"]'))?.focus() + if (props.active !== false) searchRef?.focus() }) })) @@ -76,7 +77,7 @@ const FolderSelectionView: Component = (props) => { const isLoading = () => Boolean(props.isLoading) function getActiveListLength() { - return homeTab() === "recent" ? folders().length : 0 + return props.blank || homeTab() === "recent" ? folders().length : 0 } function scrollToIndex(index: number) { @@ -331,6 +332,8 @@ const FolderSelectionView: Component = (props) => { onDragOver={folderDrop.bind.onDragOver} onDragLeave={folderDrop.bind.onDragLeave} onDrop={folderDrop.bind.onDrop} + onPointerMove={() => setFocusMode(null)} + onKeyDown={(event) => { if (event.key === "Tab") setFocusMode("recent") }} >
= (props) => {
- {t("folderSelection.openProject")}}>
-
-
= (props) => {
-
-
+ +
+
+
+ +
+
+ +
+
+
+
+
+
+
-
+

{t("newInstanceLauncher.recentTitle")}

+ +
{(tab) => ( )}
+
- +
void handleBrowse()} />
- -
+ +
- setRecentActionFocused(key, open)} /> + + + + + + + }> + setRecentActionFocused(key, open)} /> +
}} @@ -621,22 +662,21 @@ const FolderSelectionView: Component = (props) => {
-
+ +
+

{t("folderSelection.browseMenu.title")}

+ void handleBrowse()} footer={ + + } /> +
+
- -
- - -
-
diff --git a/packages/ui/src/components/new-instance-launcher.tsx b/packages/ui/src/components/new-instance-launcher.tsx index 6ad0e58731..25c96c82a8 100644 --- a/packages/ui/src/components/new-instance-launcher.tsx +++ b/packages/ui/src/components/new-instance-launcher.tsx @@ -1,6 +1,6 @@ import { Popover } from "@kobalte/core/popover" import { useI18n } from "../lib/i18n" -import { FolderOpen } from "lucide-solid" +import { Hourglass } from "lucide-solid" import RecentTabsMenu from "./recent-tabs-menu" interface NewInstanceLauncherProps { @@ -10,7 +10,7 @@ interface NewInstanceLauncherProps { onOpenChange: (open: boolean) => void onSelectFolder: (path: string) => void onSelectExistingInstance: (id: string, path: string) => void - onOpenAnotherProject: () => void + onNewTemporary: () => void } /** Quick recents only; other choices belong in a blank tab. */ @@ -34,16 +34,17 @@ export default function NewInstanceLauncher(props: NewInstanceLauncherProps) { if (returnFocus && !props.open && (!active || active === document.body || content?.contains(active))) props.anchor?.focus() returnFocus = false }}> -
{t("newInstanceLauncher.title")}
+
+ {t("newInstanceLauncher.title")} + +
{t("newInstanceLauncher.description")} - diff --git a/packages/ui/src/components/new-tab-actions.tsx b/packages/ui/src/components/new-tab-actions.tsx index 0247177e3b..33de09048f 100644 --- a/packages/ui/src/components/new-tab-actions.tsx +++ b/packages/ui/src/components/new-tab-actions.tsx @@ -7,13 +7,15 @@ interface NewTabActionsProps { isLoading: boolean onClone: () => void onNewTemporary?: () => void + hideSidecar?: boolean + home?: boolean } /** Secondary creation actions inside the canonical project selector. */ export default function NewTabActions(props: NewTabActionsProps) { const { t } = useI18n() const Action = (action: { label: string; icon: typeof Globe; onClick: () => void; title?: string }) => ( - {formatRelativeTime(t, recent.lastAccessed)}}> -
}} - +
- - + +
) diff --git a/packages/ui/src/components/folder-selection-view.tsx b/packages/ui/src/components/folder-selection-view.tsx index af1ad15658..6b5144b9da 100644 --- a/packages/ui/src/components/folder-selection-view.tsx +++ b/packages/ui/src/components/folder-selection-view.tsx @@ -1,10 +1,16 @@ import { Component, createMemo, createSignal, createUniqueId, Show, For, onMount, onCleanup, createEffect, on } from "solid-js" -import { Trash2, FolderPlus, Settings, ChevronRight, MonitorUp, Star, X, Pencil, Search } from "lucide-solid" +import { Trash2, FolderPlus, Settings, ChevronRight, MonitorUp, Star, X, Pencil } from "lucide-solid" import { removeRemoteProjectRecent, removeSideCarRecent, useConfig } from "../stores/preferences" -import { launchableRecents, openRemoteProject } from "../stores/remote-project-open" +import { launchableRecents, openRemoteProject, opensRemoteProjectTab } from "../stores/remote-project-open" +import type { RemoteServerProfile } from "../../../server/src/api-types" +import { useRemoteServerProfiles } from "../lib/hooks/use-remote-server-profiles" +import { embeddedProjectUrl } from "../lib/embed-mode" +import { serverDisplayName } from "../lib/codenomad-link" +import { captureRequestFocus } from "../lib/request-focus" import { recentKey, type LaunchableRecent } from "../lib/remote-project-recents" import BrowseMenu, { browseEntryCount } from "./browse-menu" import EntryCount from "./entry-count" +import RemoteRecentSession from "./remote-recent-session" import ActionOverflowMenu from "./action-overflow-menu" import { joinRecentOpenTarget, recentAccessibleName, recentOpenTarget } from "../lib/recent-open-target" import { ensureSidecarsLoaded } from "../stores/sidecars" @@ -28,7 +34,7 @@ import { openExternalUrl } from "../lib/external-url" import { renameProject } from "../stores/project-names" import { LocaleSelector } from "./locale-selector" import { createNewInstanceDialogs } from "./new-instance-dialogs" -import { filterRecents, formatRelativeTime, getDisplayPath, getProjectDisplayName } from "../lib/recent-folder-display" +import { formatRelativeTime, getDisplayPath, getProjectDisplayName } from "../lib/recent-folder-display" const GITHUB_URL = "https://github.com/NeuralNomadsAI/CodeNomad" const DISCORD_URL = "https://discord.com/channels/1391832426048651334/1458412028325793887/1464701235683917945" @@ -47,11 +53,15 @@ interface FolderSelectionViewProps { const FolderSelectionView: Component = (props) => { const { removeRecentFolder } = useConfig() const { t, locale } = useI18n() + const { openServer, remoteServers } = useRemoteServerProfiles() + const [remoteSource, setRemoteSource] = createSignal<{ profile: RemoteServerProfile; recents: LaunchableRecent[]; available: boolean }>() const viewId = createUniqueId() const tabId = (tab: string) => `folder-home-tab-${viewId}-${tab}` const panelId = (tab: string) => `folder-home-panel-${viewId}-${tab}` onMount(() => void ensureSidecarsLoaded()) const [selectedIndex, setSelectedIndex] = createSignal(0) + const [connectingRecent, setConnectingRecent] = createSignal() + createEffect(on([() => props.active, remoteSource], () => setConnectingRecent(undefined), { defer: true })) const [hoveredRecentActionPath, setHoveredRecentActionPath] = createSignal(null) const [focusedRecentActionPath, setFocusedRecentActionPath] = createSignal(null) const [focusMode, setFocusMode] = createSignal<"recent" | "new" | null>(null) @@ -59,21 +69,25 @@ const FolderSelectionView: Component = (props) => { const [isRenamingProject, setIsRenamingProject] = createSignal(false) // The canonical selector shared by Home and blank tabs. const [homeTab, setHomeTab] = createSignal<"recent" | "browse">("recent") - const [query, setQuery] = createSignal("") let homeRootRef: HTMLDivElement | undefined let recentListRef: HTMLDivElement | undefined - let searchRef: HTMLInputElement | undefined createEffect(on(() => props.blank && props.active !== false, (active) => { if (!active) return setHomeTab(allRecents().length ? "recent" : "browse") - requestAnimationFrame(() => { - if (props.active !== false) searchRef?.focus() - }) + const focus = captureRequestFocus() + let cancelled = false + onCleanup(() => { cancelled = true; focus.dispose() }) + // The initial SideCar read can replace recent rows; focus their settled DOM. + void ensureSidecarsLoaded().then(() => requestAnimationFrame(() => { + if (!cancelled && props.active !== false && focus.retained()) homeRootRef?.querySelector('[data-list-index="0"], [data-browse-nav]')?.focus() + focus.dispose() + })) })) // This computer's folders, the remote projects this window reopens and SideCars, newest first. - const allRecents = () => launchableRecents() - const folders = createMemo(() => filterRecents(allRecents(), query())) + const allRecents = () => remoteSource()?.recents ?? launchableRecents() + const recentsAvailable = () => !remoteSource() || remoteSource()!.available + const folders = allRecents const isLoading = () => Boolean(props.isLoading) function getActiveListLength() { @@ -234,24 +248,12 @@ const FolderSelectionView: Component = (props) => { function openRecent(folder: LaunchableRecent) { if (isLoading()) return if (folder.sidecar) void openSidecar(folder.sidecar.sidecarId) - else if (folder.remote) openRemoteProject(folder.remote.profileId, { folder: folder.path }) - else handleFolderSelect(folder.path) - } - - // The search field keeps the keyboard on the list, as in the launcher. - function handleSearchKeyDown(event: KeyboardEvent) { - const count = folders().length - if (event.key === "ArrowDown" || event.key === "ArrowUp") { - event.preventDefault() - if (!count) return - const next = event.key === "ArrowDown" ? 0 : count - 1 - setFocusMode("recent") - setSelectedIndex(next) - scrollToIndex(next) - } else if (event.key === "Enter") { - const folder = folders()[selectedIndex()] - if (folder) { event.preventDefault(); openRecent(folder) } + else if (folder.remote) { + const profile = remoteSource()?.profile + if (profile && !opensRemoteProjectTab(profile)) openServer(profile, embeddedProjectUrl(profile.baseUrl, folder.path)) + else setConnectingRecent(recentKey(folder)) } + else handleFolderSelect(folder.path) } function handleTabKeyDown(event: KeyboardEvent) { @@ -272,7 +274,7 @@ const FolderSelectionView: Component = (props) => { } const dialogs = createNewInstanceDialogs({ - defaultPath: () => allRecents().find((folder) => !folder.remote && !folder.sidecar)?.path, + defaultPath: () => launchableRecents().find((folder) => !folder.remote && !folder.sidecar)?.path, isLoading, onSelectFolder: handleFolderSelect, }) @@ -286,7 +288,7 @@ const FolderSelectionView: Component = (props) => { } function handleRemove(folder: LaunchableRecent, e?: Event) { - if (isLoading()) return + if (isLoading() || remoteSource()) return e?.stopPropagation() if (folder.sidecar) removeSideCarRecent(folder.sidecar.sidecarId) else if (folder.remote) removeRemoteProjectRecent(folder.remote.profileId, folder.path) @@ -377,8 +379,8 @@ const FolderSelectionView: Component = (props) => {
-
-

CodeNomad

+
+

CodeNomad

@@ -438,6 +440,11 @@ const FolderSelectionView: Component = (props) => {
+ +
+ +
+
@@ -457,7 +464,7 @@ const FolderSelectionView: Component = (props) => {
-

{t("newInstanceLauncher.recentTitle")}

+

{t("newInstanceLauncher.recentTitle")}

@@ -466,7 +473,7 @@ const FolderSelectionView: Component = (props) => { type="button" role="tab" aria-label={t(tab === "recent" ? "newInstanceLauncher.recentTitle" : "folderSelection.browseMenu.title")} - aria-description={t((tab === "recent" ? allRecents().length : browseEntryCount()) === 1 ? "newTab.items.one" : "newTab.items.other", { count: tab === "recent" ? allRecents().length : browseEntryCount() })} + aria-description={tab === "recent" && !recentsAvailable() ? undefined : t((tab === "recent" ? allRecents().length : browseEntryCount()) === 1 ? "newTab.items.one" : "newTab.items.other", { count: tab === "recent" ? allRecents().length : browseEntryCount() })} id={tabId(tab)} data-home-tab={tab} aria-selected={homeTab() === tab} @@ -474,13 +481,13 @@ const FolderSelectionView: Component = (props) => { tabIndex={homeTab() === tab ? 0 : -1} class="folder-home-header-tab px-4 py-3 text-left transition-colors" classList={{ "border-r border-base": tab === "recent" }} - style={{ "background-color": homeTab() === tab ? "var(--surface-control)" : "var(--surface-secondary)" }} + style={{ "background-color": homeTab() === tab ? "var(--surface-secondary)" : "var(--surface-control)" }} onClick={() => setHomeTab(tab)} > {t(tab === "recent" ? "newInstanceLauncher.recentTitle" : "folderSelection.browseMenu.title")} - + )} @@ -488,36 +495,25 @@ const FolderSelectionView: Component = (props) => {
- -
- void handleBrowse()} /> + +
- + {(source) => {serverDisplayName(source().profile, remoteServers())}} 0} fallback={ +

{t("newInstanceLauncher.empty")}

}> 0} fallback={ }>

{t("newInstanceLauncher.noMatch")}

+
} >
= (props) => { setSelectedIndex(index()) }} > +
-
+
+
}> + { setConnectingRecent(undefined); queueMicrotask(() => scrollToIndex(index())) }} + onReady={() => { setConnectingRecent(undefined); openRemoteProject(folder.remote!.profileId, { folder: folder.path }) }} /> +
}} @@ -669,11 +672,7 @@ const FolderSelectionView: Component = (props) => {

{t("folderSelection.browseMenu.title")}

- void handleBrowse()} footer={ - - } /> + void handleBrowse()} pinAddField />
diff --git a/packages/ui/src/components/new-instance-launcher.tsx b/packages/ui/src/components/new-instance-launcher.tsx index 25c96c82a8..e6d53e93af 100644 --- a/packages/ui/src/components/new-instance-launcher.tsx +++ b/packages/ui/src/components/new-instance-launcher.tsx @@ -26,9 +26,12 @@ export default function NewInstanceLauncher(props: NewInstanceLauncherProps) { { event.preventDefault() - content?.querySelector("input[type='search']")?.focus() + if (!content?.contains(document.activeElement) || document.activeElement === content) content?.querySelector(".recent-tabs-menu")?.focus() }} - onEscapeKeyDown={() => { returnFocus = true }} onCloseAutoFocus={(event) => { + onEscapeKeyDown={(event) => { + if ((event.target as HTMLElement)?.closest("[data-remote-view-session]")) event.preventDefault() + else returnFocus = true + }} onCloseAutoFocus={(event) => { event.preventDefault() const active = document.activeElement if (returnFocus && !props.open && (!active || active === document.body || content?.contains(active))) props.anchor?.focus() diff --git a/packages/ui/src/components/new-tab-actions.tsx b/packages/ui/src/components/new-tab-actions.tsx index 33de09048f..44b835ce36 100644 --- a/packages/ui/src/components/new-tab-actions.tsx +++ b/packages/ui/src/components/new-tab-actions.tsx @@ -9,6 +9,7 @@ interface NewTabActionsProps { onNewTemporary?: () => void hideSidecar?: boolean home?: boolean + blank?: boolean } /** Secondary creation actions inside the canonical project selector. */ @@ -21,13 +22,15 @@ export default function NewTabActions(props: NewTabActionsProps) { {action.label} ) + const Temporary = () => + {(onNewTemporary) => onNewTemporary()()} />} + return ( <> - - - {(onNewTemporary) => onNewTemporary()()} />} - + + + void openSettingsRow("sidecars", "sidecar-add")} /> diff --git a/packages/ui/src/components/recent-tabs-menu.tsx b/packages/ui/src/components/recent-tabs-menu.tsx index 79e9a0a30e..c70ec66fa1 100644 --- a/packages/ui/src/components/recent-tabs-menu.tsx +++ b/packages/ui/src/components/recent-tabs-menu.tsx @@ -4,6 +4,8 @@ import { useI18n } from "../lib/i18n" import { filterRecents, formatRelativeTime, getDisplayPath, getProjectDisplayName } from "../lib/recent-folder-display" import { joinRecentOpenTarget, recentAccessibleName, recentOpenTarget } from "../lib/recent-open-target" import type { LaunchableRecent } from "../lib/remote-project-recents" +import { recentKey } from "../lib/remote-project-recents" +import RemoteRecentSession from "./remote-recent-session" import { launchableRecents, openRemoteProject } from "../stores/remote-project-open" import { openSidecar } from "../stores/sidecar-open" import { ensureSidecarsLoaded } from "../stores/sidecars" @@ -19,12 +21,14 @@ export default function RecentTabsMenu(props: { }) { const { t } = useI18n() const [query, setQuery] = createSignal("") + const [connectingRecent, setConnectingRecent] = createSignal() const listId = `recent-list-${createUniqueId()}` const [index, setIndex] = createSignal(0) const [keyboardNavigation, setKeyboardNavigation] = createSignal(false) const matches = createMemo(() => filterRecents(launchableRecents(), query())) let list: HTMLDivElement | undefined createEffect(on(() => props.active, (active) => { + setConnectingRecent(undefined) if (!active) return setQuery("") setIndex(0) @@ -34,12 +38,13 @@ export default function RecentTabsMenu(props: { createEffect(on(matches, () => setIndex(0), { defer: true })) function open(recent: LaunchableRecent) { if (props.isLoading) return + if (recent.remote) { setConnectingRecent(recentKey(recent)); return } props.onRun?.() if (recent.sidecar) return void openSidecar(recent.sidecar.sidecarId) - if (recent.remote) return openRemoteProject(recent.remote.profileId, { folder: recent.path }) props.onSelectFolder(recent.path) } function navigate(event: KeyboardEvent, fromSearch = false) { + if ((event.target as HTMLElement).closest("[data-remote-view-session]")) return if (props.isLoading || !matches().length) return if (event.key === "ArrowDown" || event.key === "ArrowUp" || (!fromSearch && (event.key === "Home" || event.key === "End"))) { event.preventDefault() @@ -56,9 +61,12 @@ export default function RecentTabsMenu(props: { } } return ( -
setKeyboardNavigation(false)} - onKeyDown={(event) => { if (event.key === "Tab") setKeyboardNavigation(true) }}> + onKeyDown={(event) => { + if (event.key === "Tab") setKeyboardNavigation(true) + if (event.target === event.currentTarget) navigate(event, true) + }}>